diff --git a/.changeset/eight-owls-grow.md b/.changeset/eight-owls-grow.md new file mode 100644 index 0000000000..47b4e4712b --- /dev/null +++ b/.changeset/eight-owls-grow.md @@ -0,0 +1,14 @@ +--- +"near-api-js": major +"@near-js/accounts": minor +"@near-js/transactions": minor +"@near-js/types": minor +"@near-js/utils": minor +"@near-js/biometric-ed25519": patch +"@near-js/cookbook": patch +"@near-js/crypto": patch +"@near-js/providers": patch +"@near-js/wallet-account": patch +--- + +Replace bn.js by BigInt. diff --git a/.eslintrc.js.yml b/.eslintrc.js.yml index 54abdec6e0..1a932a041c 100644 --- a/.eslintrc.js.yml +++ b/.eslintrc.js.yml @@ -5,3 +5,4 @@ globals: jasmine: true window: false fail: true + BigInt: true diff --git a/packages/accounts/package.json b/packages/accounts/package.json index 8ccc4be177..894ff6b965 100644 --- a/packages/accounts/package.json +++ b/packages/accounts/package.json @@ -1,45 +1,44 @@ { - "name": "@near-js/accounts", - "version": "1.0.4", - "description": "Classes encapsulating account-specific functionality", - "main": "lib/index.js", - "scripts": { - "build": "pnpm compile", - "compile": "tsc -p tsconfig.json", - "lint:js": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc", - "lint:js:fix": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc --fix", - "lint:ts": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc", - "lint:ts:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc --fix", - "test": "jest test" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@near-js/crypto": "workspace:*", - "@near-js/providers": "workspace:*", - "@near-js/signers": "workspace:*", - "@near-js/transactions": "workspace:*", - "@near-js/types": "workspace:*", - "@near-js/utils": "workspace:*", - "bn.js": "5.2.1", - "borsh": "1.0.0", - "depd": "2.0.0", - "is-my-json-valid": "^2.20.6", - "lru_map": "0.4.1", - "near-abi": "0.1.1" - }, - "devDependencies": { - "@near-js/keystores": "workspace:*", - "@types/node": "18.11.18", - "bs58": "4.0.0", - "jest": "26.0.1", - "near-hello": "0.5.1", - "near-workspaces": "3.4.0", - "ts-jest": "26.5.6", - "typescript": "4.9.4" - }, - "files": [ - "lib" - ] + "name": "@near-js/accounts", + "version": "1.0.4", + "description": "Classes encapsulating account-specific functionality", + "main": "lib/index.js", + "scripts": { + "build": "pnpm compile", + "compile": "tsc -p tsconfig.json", + "lint:js": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc", + "lint:js:fix": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc --fix", + "lint:ts": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc", + "lint:ts:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc --fix", + "test": "jest test" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "@near-js/crypto": "workspace:*", + "@near-js/providers": "workspace:*", + "@near-js/signers": "workspace:*", + "@near-js/transactions": "workspace:*", + "@near-js/types": "workspace:*", + "@near-js/utils": "workspace:*", + "borsh": "1.0.0", + "depd": "2.0.0", + "is-my-json-valid": "^2.20.6", + "lru_map": "0.4.1", + "near-abi": "0.1.1" + }, + "devDependencies": { + "@near-js/keystores": "workspace:*", + "@types/node": "18.11.18", + "bs58": "4.0.0", + "jest": "26.0.1", + "near-hello": "0.5.1", + "near-workspaces": "3.4.0", + "ts-jest": "26.5.6", + "typescript": "4.9.4" + }, + "files": [ + "lib" + ] } diff --git a/packages/accounts/src/account.ts b/packages/accounts/src/account.ts index 989ae1daf3..0eb29095de 100644 --- a/packages/accounts/src/account.ts +++ b/packages/accounts/src/account.ts @@ -34,7 +34,6 @@ import { printTxOutcomeLogs, printTxOutcomeLogsAndFailures, } from '@near-js/utils'; -import BN from 'bn.js'; import { Connection } from './connection'; @@ -106,9 +105,9 @@ export interface FunctionCallOptions { */ args?: object; /** max amount of gas that method call can use */ - gas?: BN; + gas?: bigint; /** amount of NEAR (in yoctoNEAR) to send together with the call */ - attachedDeposit?: BN; + attachedDeposit?: bigint; /** * Convert input arguments into bytes array. */ @@ -145,7 +144,7 @@ interface StakedBalance { interface ActiveDelegatedStakeBalance { stakedValidators: StakedBalance[]; failedValidators: StakedBalance[]; - total: BN | string; + total: bigint | string; } interface SignedDelegateOptions { @@ -202,7 +201,7 @@ export class Account { const block = await this.connection.provider.block({ finality: 'final' }); const blockHash = block.header.hash; - const nonce = accessKey.nonce.add(new BN(1)); + const nonce = accessKey.nonce + BigInt(1); return await signTransaction( receiverId, nonce, actions, baseDecode(blockHash), this.connection.signer, this.accountId, this.connection.networkId ); @@ -297,10 +296,10 @@ export class Account { finality: 'optimistic' }); - // store nonce as BN to preserve precision on big number + // store nonce as BigInt to preserve precision on big number const accessKey = { ...rawAccessKey, - nonce: new BN(rawAccessKey.nonce), + nonce: BigInt(rawAccessKey.nonce || 0) }; // this function can be called multiple times and retrieve the same access key // this checks to see if the access key was already retrieved and cached while @@ -329,7 +328,7 @@ export class Account { * @param data The compiled contract code * @param amount of NEAR to transfer to the created contract account. Transfer enough to pay for storage https://docs.near.org/docs/concepts/storage-staking */ - async createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: BN): Promise { + async createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: bigint): Promise { const accessKey = fullAccessKey(); await this.signAndSendTransaction({ receiverId: contractId, @@ -343,7 +342,7 @@ export class Account { * @param receiverId NEAR account receiving Ⓝ * @param amount Amount to send in yoctoⓃ */ - async sendMoney(receiverId: string, amount: BN): Promise { + async sendMoney(receiverId: string, amount: bigint): Promise { return this.signAndSendTransaction({ receiverId, actions: [transfer(amount)] @@ -354,7 +353,7 @@ export class Account { * @param newAccountId NEAR account name to be created * @param publicKey A public key created from the masterAccount */ - async createAccount(newAccountId: string, publicKey: string | PublicKey, amount: BN): Promise { + async createAccount(newAccountId: string, publicKey: string | PublicKey, amount: bigint): Promise { const accessKey = fullAccessKey(); return this.signAndSendTransaction({ receiverId: newAccountId, @@ -431,7 +430,7 @@ export class Account { * @param methodNames The method names on the contract that should be allowed to be called. Pass null for no method names and '' or [] for any method names. * @param amount Payment in yoctoⓃ that is sent to the contract during this function call */ - async addKey(publicKey: string | PublicKey, contractId?: string, methodNames?: string | string[], amount?: BN): Promise { + async addKey(publicKey: string | PublicKey, contractId?: string, methodNames?: string | string[], amount?: bigint): Promise { if (!methodNames) { methodNames = []; } @@ -467,7 +466,7 @@ export class Account { * @param publicKey The public key for the account that's staking * @param amount The account to stake in yoctoⓃ */ - async stake(publicKey: string | PublicKey, amount: BN): Promise { + async stake(publicKey: string | PublicKey, amount: bigint): Promise { return this.signAndSendTransaction({ receiverId: this.accountId, actions: [stake(amount, PublicKey.from(publicKey))] @@ -493,8 +492,8 @@ export class Account { const delegateAction = buildDelegateAction({ actions, - maxBlockHeight: new BN(header.height).add(new BN(blockHeightTtl)), - nonce: new BN(accessKey.nonce).add(new BN(1)), + maxBlockHeight: BigInt(header.height) + BigInt(blockHeightTtl), + nonce: BigInt(accessKey.nonce) + BigInt(1), publicKey, receiverId, senderId: this.accountId, @@ -611,8 +610,8 @@ export class Account { account_id: this.accountId, finality: 'optimistic' }); - // Replace raw nonce into a new BN - return response?.keys?.map((key) => ({ ...key, access_key: { ...key.access_key, nonce: new BN(key.access_key.nonce) } })); + // Replace raw nonce into a new BigInt + return response?.keys?.map((key) => ({ ...key, access_key: { ...key.access_key, nonce: BigInt(key.access_key.nonce) } })); } /** @@ -643,11 +642,11 @@ export class Account { const protocolConfig = await this.connection.provider.experimental_protocolConfig({ finality: 'final' }); const state = await this.state(); - const costPerByte = new BN(protocolConfig.runtime_config.storage_amount_per_byte); - const stateStaked = new BN(state.storage_usage).mul(costPerByte); - const staked = new BN(state.locked); - const totalBalance = new BN(state.amount).add(staked); - const availableBalance = totalBalance.sub(BN.max(staked, stateStaked)); + const costPerByte = BigInt(protocolConfig.runtime_config.storage_amount_per_byte); + const stateStaked = BigInt(state.storage_usage) * costPerByte; + const staked = BigInt(state.locked); + const totalBalance = BigInt(state.amount) + staked; + const availableBalance = totalBalance - (staked > stateStaked ? staked : stateStaked); return { total: totalBalance.toString(), @@ -699,12 +698,12 @@ export class Account { const summary = results.reduce((result, state, index) => { const validatorId = uniquePools[index]; if (state.status === 'fulfilled') { - const currentBN = new BN(state.value); - if (!currentBN.isZero()) { + const currentBN = BigInt(state.value); + if (currentBN !== BigInt(0)) { return { ...result, stakedValidators: [...result.stakedValidators, { validatorId, amount: currentBN.toString() }], - total: result.total.add(currentBN), + total: result.total + currentBN, }; } } @@ -716,7 +715,7 @@ export class Account { } return result; }, - { stakedValidators: [], failedValidators: [], total: new BN(0) }); + { stakedValidators: [], failedValidators: [], total: BigInt(0) }); return { ...summary, diff --git a/packages/accounts/src/account_2fa.ts b/packages/accounts/src/account_2fa.ts index c22e664a0d..78533fbee9 100644 --- a/packages/accounts/src/account_2fa.ts +++ b/packages/accounts/src/account_2fa.ts @@ -3,7 +3,6 @@ import { FinalExecutionOutcome, TypedError, FunctionCallPermissionView } from '@ import { fetchJson } from '@near-js/providers'; import { actionCreators } from '@near-js/transactions'; import { Logger } from '@near-js/utils' -import BN from 'bn.js'; import { SignAndSendTransactionOptions } from './account'; import { AccountMultisig } from './account_multisig'; @@ -159,7 +158,7 @@ export class Account2FA extends AccountMultisig { const currentAccountStateKeys = currentAccountState.map(({ key }) => key.toString('base64')); return currentAccountState.length ? [ deployContract(cleanupContractBytes), - functionCall('clean', { keys: currentAccountStateKeys }, MULTISIG_GAS, new BN('0')) + functionCall('clean', { keys: currentAccountStateKeys }, MULTISIG_GAS, BigInt('0')) ] : []; } diff --git a/packages/accounts/src/account_creator.ts b/packages/accounts/src/account_creator.ts index 29d306f803..62fac47fdb 100644 --- a/packages/accounts/src/account_creator.ts +++ b/packages/accounts/src/account_creator.ts @@ -1,6 +1,5 @@ import { PublicKey } from '@near-js/crypto'; import { fetchJson } from '@near-js/providers'; -import BN from 'bn.js'; import { Connection } from './connection'; import { Account } from './account'; @@ -14,9 +13,9 @@ export abstract class AccountCreator { export class LocalAccountCreator extends AccountCreator { readonly masterAccount: Account; - readonly initialBalance: BN; + readonly initialBalance: bigint; - constructor(masterAccount: Account, initialBalance: BN) { + constructor(masterAccount: Account, initialBalance: bigint) { super(); this.masterAccount = masterAccount; this.initialBalance = initialBalance; diff --git a/packages/accounts/src/constants.ts b/packages/accounts/src/constants.ts index 464afa7da0..ad8bec4dac 100644 --- a/packages/accounts/src/constants.ts +++ b/packages/accounts/src/constants.ts @@ -1,10 +1,9 @@ import { parseNearAmount } from '@near-js/utils'; -import BN from 'bn.js'; export const MULTISIG_STORAGE_KEY = '__multisigRequest'; -export const MULTISIG_ALLOWANCE = new BN(parseNearAmount('1')); +export const MULTISIG_ALLOWANCE = BigInt(parseNearAmount('1')); // TODO: Different gas value for different requests (can reduce gas usage dramatically) -export const MULTISIG_GAS = new BN('100000000000000'); -export const MULTISIG_DEPOSIT = new BN('0'); +export const MULTISIG_GAS = BigInt('100000000000000'); +export const MULTISIG_DEPOSIT = BigInt('0'); export const MULTISIG_CHANGE_METHODS = ['add_request', 'add_request_and_confirm', 'delete_request', 'confirm']; export const MULTISIG_CONFIRM_METHODS = ['confirm']; diff --git a/packages/accounts/src/contract.ts b/packages/accounts/src/contract.ts index c2b005429a..f3afe2da83 100644 --- a/packages/accounts/src/contract.ts +++ b/packages/accounts/src/contract.ts @@ -1,32 +1,57 @@ -import { getTransactionLastResult, Logger } from '@near-js/utils'; -import { ArgumentTypeError, PositionalArgsError } from '@near-js/types'; -import { LocalViewExecution } from './local-view-execution'; -import validator from 'is-my-json-valid' -import BN from 'bn.js'; -import depd from 'depd'; -import { AbiFunction, AbiFunctionKind, AbiRoot, AbiSerializationType } from 'near-abi'; +import { getTransactionLastResult, Logger } from "@near-js/utils"; +import { ArgumentTypeError, PositionalArgsError } from "@near-js/types"; +import { LocalViewExecution } from "./local-view-execution"; +import validator from "is-my-json-valid"; +import depd from "depd"; +import { + AbiFunction, + AbiFunctionKind, + AbiRoot, + AbiSerializationType, +} from "near-abi"; -import { Account } from './account'; -import { UnsupportedSerializationError, UnknownArgumentError, ArgumentSchemaError, ConflictingOptions } from './errors'; +import { Account } from "./account"; +import { + UnsupportedSerializationError, + UnknownArgumentError, + ArgumentSchemaError, + ConflictingOptions, +} from "./errors"; // Makes `function.name` return given name function nameFunction(name: string, body: (args?: any[]) => any) { return { [name](...args: any[]) { return body(...args); - } + }, }[name]; } -function validateArguments(args: object, abiFunction: AbiFunction, abiRoot: AbiRoot) { +function validateArguments( + args: object, + abiFunction: AbiFunction, + abiRoot: AbiRoot +) { if (!isObject(args)) return; - if (abiFunction.params && abiFunction.params.serialization_type !== AbiSerializationType.Json) { - throw new UnsupportedSerializationError(abiFunction.name, abiFunction.params.serialization_type); + if ( + abiFunction.params && + abiFunction.params.serialization_type !== AbiSerializationType.Json + ) { + throw new UnsupportedSerializationError( + abiFunction.name, + abiFunction.params.serialization_type + ); } - if (abiFunction.result && abiFunction.result.serialization_type !== AbiSerializationType.Json) { - throw new UnsupportedSerializationError(abiFunction.name, abiFunction.result.serialization_type); + if ( + abiFunction.result && + abiFunction.result.serialization_type !== AbiSerializationType.Json + ) { + throw new UnsupportedSerializationError( + abiFunction.name, + abiFunction.result.serialization_type + ); } const params = abiFunction.params?.args || []; @@ -34,8 +59,8 @@ function validateArguments(args: object, abiFunction: AbiFunction, abiRoot: AbiR const arg = args[p.name]; const typeSchema = p.type_schema; typeSchema.definitions = abiRoot.body.root_schema.definitions; - const validate = validator(typeSchema) - const valid = validate(arg) + const validate = validator(typeSchema); + const valid = validate(arg); if (!valid) { throw new ArgumentSchemaError(p.name, validate.errors); } @@ -44,7 +69,10 @@ function validateArguments(args: object, abiFunction: AbiFunction, abiRoot: AbiR for (const argName of Object.keys(args)) { const param = params.find((p) => p.name === argName); if (!param) { - throw new UnknownArgumentError(argName, params.map((p) => p.name)); + throw new UnknownArgumentError( + argName, + params.map((p) => p.name) + ); } } } @@ -53,13 +81,13 @@ const isUint8Array = (x: any) => x && x.byteLength !== undefined && x.byteLength === x.length; const isObject = (x: any) => - Object.prototype.toString.call(x) === '[object Object]'; + Object.prototype.toString.call(x) === "[object Object]"; interface ChangeMethodOptions { args: object; methodName: string; - gas?: BN; - amount?: BN; + gas?: bigint; + amount?: bigint; meta?: string; callbackUrl?: string; } @@ -134,16 +162,34 @@ export class Contract { * @param contractId NEAR account id where the contract is deployed * @param options NEAR smart contract methods that your application will use. These will be available as `contract.methodName` */ - constructor(account: Account, contractId: string, options: ContractMethods) { + constructor( + account: Account, + contractId: string, + options: ContractMethods + ) { this.account = account; this.contractId = contractId; this.lve = new LocalViewExecution(account); - const { viewMethods = [], changeMethods = [], abi: abiRoot, useLocalViewExecution } = options; + const { + viewMethods = [], + changeMethods = [], + abi: abiRoot, + useLocalViewExecution, + } = options; - let viewMethodsWithAbi = viewMethods.map((name) => ({ name, abi: null as AbiFunction })); - let changeMethodsWithAbi = changeMethods.map((name) => ({ name, abi: null as AbiFunction })); + let viewMethodsWithAbi = viewMethods.map((name) => ({ + name, + abi: null as AbiFunction, + })); + let changeMethodsWithAbi = changeMethods.map((name) => ({ + name, + abi: null as AbiFunction, + })); if (abiRoot) { - if (viewMethodsWithAbi.length > 0 || changeMethodsWithAbi.length > 0) { + if ( + viewMethodsWithAbi.length > 0 || + changeMethodsWithAbi.length > 0 + ) { throw new ConflictingOptions(); } viewMethodsWithAbi = abiRoot.body.functions @@ -158,36 +204,45 @@ export class Contract { Object.defineProperty(this, name, { writable: false, enumerable: true, - value: nameFunction(name, async (args: object = {}, options = {}, ...ignored) => { - if (ignored.length || !(isObject(args) || isUint8Array(args)) || !isObject(options)) { - throw new PositionalArgsError(); - } + value: nameFunction( + name, + async (args: object = {}, options = {}, ...ignored) => { + if ( + ignored.length || + !(isObject(args) || isUint8Array(args)) || + !isObject(options) + ) { + throw new PositionalArgsError(); + } - if (abi) { - validateArguments(args, abi, abiRoot); - } + if (abi) { + validateArguments(args, abi, abiRoot); + } - if (useLocalViewExecution) { - try { - return await this.lve.viewFunction({ - contractId: this.contractId, - methodName: name, - args, - ...options, - }); - } catch (error) { - Logger.warn(`Local view execution failed with: "${error.message}"`); - Logger.warn(`Fallback to normal RPC call`); + if (useLocalViewExecution) { + try { + return await this.lve.viewFunction({ + contractId: this.contractId, + methodName: name, + args, + ...options, + }); + } catch (error) { + Logger.warn( + `Local view execution failed with: "${error.message}"` + ); + Logger.warn(`Fallback to normal RPC call`); + } } - } - return this.account.viewFunction({ - contractId: this.contractId, - methodName: name, - args, - ...options, - }); - }) + return this.account.viewFunction({ + contractId: this.contractId, + methodName: name, + args, + ...options, + }); + } + ), }); }); changeMethodsWithAbi.forEach(({ name, abi }) => { @@ -195,17 +250,25 @@ export class Contract { writable: false, enumerable: true, value: nameFunction(name, async (...args: any[]) => { - if (args.length && (args.length > 3 || !(isObject(args[0]) || isUint8Array(args[0])))) { + if ( + args.length && + (args.length > 3 || + !(isObject(args[0]) || isUint8Array(args[0]))) + ) { throw new PositionalArgsError(); } if (args.length > 1 || !(args[0] && args[0].args)) { - const deprecate = depd('contract.methodName(args, gas, amount)'); - deprecate('use `contract.methodName({ args, gas?, amount?, callbackUrl?, meta? })` instead'); + const deprecate = depd( + "contract.methodName(args, gas, amount)" + ); + deprecate( + "use `contract.methodName({ args, gas?, amount?, callbackUrl?, meta? })` instead" + ); args[0] = { args: args[0], gas: args[1], - amount: args[2] + amount: args[2], }; } @@ -214,12 +277,19 @@ export class Contract { } return this._changeMethod({ methodName: name, ...args[0] }); - }) + }), }); }); } - private async _changeMethod({ args, methodName, gas, amount, meta, callbackUrl }: ChangeMethodOptions) { + private async _changeMethod({ + args, + methodName, + gas, + amount, + meta, + callbackUrl, + }: ChangeMethodOptions) { validateBNLike({ gas, amount }); const rawResult = await this.account.functionCall({ @@ -229,7 +299,7 @@ export class Contract { gas, attachedDeposit: amount, walletMeta: meta, - walletCallbackUrl: callbackUrl + walletCallbackUrl: callbackUrl, }); return getTransactionLastResult(rawResult); @@ -237,15 +307,14 @@ export class Contract { } /** - * Validation on arguments being a big number from bn.js - * Throws if an argument is not in BN format or otherwise invalid + * Throws if an argument is not in BigInt format or otherwise invalid * @param argMap */ function validateBNLike(argMap: { [name: string]: any }) { - const bnLike = 'number, decimal string or BN'; + const bnLike = "number, decimal string or BigInt"; for (const argName of Object.keys(argMap)) { const argValue = argMap[argName]; - if (argValue && !BN.isBN(argValue) && isNaN(argValue)) { + if (argValue && typeof argValue !== "bigint" && isNaN(argValue)) { throw new ArgumentTypeError(argName, bnLike, argValue); } } diff --git a/packages/accounts/test/account.test.js b/packages/accounts/test/account.test.js index 9b32d4b4d3..b51ba05a63 100644 --- a/packages/accounts/test/account.test.js +++ b/packages/accounts/test/account.test.js @@ -1,7 +1,6 @@ const { getTransactionLastResult, Logger } = require('@near-js/utils'); const { actionCreators } = require('@near-js/transactions'); const { TypedError } = require('@near-js/types'); -const BN = require('bn.js'); const fs = require('fs'); const { Account, Contract } = require('../lib'); @@ -32,7 +31,7 @@ test('create account and then view account returns the created account', async ( const newAccountName = testUtils.generateUniqueString('test'); const newAccountPublicKey = '9AhWenZ3JddamBoyMqnTbp7yVbRuvqAv3zwfrWgfVRJE'; const { amount } = await workingAccount.state(); - const newAmount = new BN(amount).div(new BN(10)); + const newAmount = BigInt(amount) / BigInt(10); await workingAccount.createAccount(newAccountName, newAccountPublicKey, newAmount); const newAccount = new Account(nearjs.connection, newAccountName); const state = await newAccount.state(); @@ -43,9 +42,9 @@ test('send money', async() => { const sender = await testUtils.createAccount(nearjs); const receiver = await testUtils.createAccount(nearjs); const { amount: receiverAmount } = await receiver.state(); - await sender.sendMoney(receiver.accountId, new BN(10000)); + await sender.sendMoney(receiver.accountId, BigInt(10000)); const state = await receiver.state(); - expect(state.amount).toEqual(new BN(receiverAmount).add(new BN(10000)).toString()); + expect(state.amount).toEqual((BigInt(receiverAmount) + BigInt(10000)).toString()); }); test('send money through signAndSendTransaction', async() => { @@ -54,10 +53,10 @@ test('send money through signAndSendTransaction', async() => { const { amount: receiverAmount } = await receiver.state(); await sender.signAndSendTransaction({ receiverId: receiver.accountId, - actions: [actionCreators.transfer(new BN(10000))], + actions: [actionCreators.transfer(BigInt(10000))], }); const state = await receiver.state(); - expect(state.amount).toEqual(new BN(receiverAmount).add(new BN(10000)).toString()); + expect(state.amount).toEqual((BigInt(receiverAmount) + BigInt(10000)).toString()); }); test('delete account', async() => { @@ -74,7 +73,7 @@ test('multiple parallel transactions', async () => { const account = new Account(workingAccount.connection, workingAccount.accountId); // NOTE: Need to have different transactions outside of nonce, or they all succeed by being identical // TODO: Check if randomization of exponential back off helps to do more transactions without exceeding retries - await account.sendMoney(account.accountId, new BN(i)); + await account.sendMoney(account.accountId, BigInt(i)); })); }); diff --git a/packages/accounts/test/account_multisig.test.js b/packages/accounts/test/account_multisig.test.js index 51907fc45e..63898d2396 100644 --- a/packages/accounts/test/account_multisig.test.js +++ b/packages/accounts/test/account_multisig.test.js @@ -1,9 +1,7 @@ -/* global BigInt */ const { parseNearAmount } = require('@near-js/utils'); const { KeyPair } = require('@near-js/crypto'); const { InMemorySigner } = require('@near-js/signers'); const { actionCreators } = require('@near-js/transactions'); -const BN = require('bn.js'); const fs = require('fs'); const semver = require('semver'); @@ -86,7 +84,7 @@ describe('account2fa transactions', () => { const appPublicKey = KeyPair.fromRandom('ed25519').getPublicKey(); const appAccountId = 'foobar'; const appMethodNames = ['some_app_stuff','some_more_app_stuff']; - await account.addKey(appPublicKey.toString(), appAccountId, appMethodNames, new BN(parseNearAmount('0.25'))); + await account.addKey(appPublicKey.toString(), appAccountId, appMethodNames, BigInt(parseNearAmount('0.25'))); account = await getAccount2FA(account); const keys = await account.getAccessKeys(); expect(keys.find(({ public_key }) => appPublicKey.toString() === public_key) @@ -101,7 +99,7 @@ describe('account2fa transactions', () => { const appPublicKey = KeyPair.fromRandom('ed25519').getPublicKey(); const appAccountId = 'foobar'; const appMethodNames = ['some_app_stuff', 'some_more_app_stuff']; - await account.addKey(appPublicKey.toString(), appAccountId, appMethodNames, new BN(parseNearAmount('0.25'))); + await account.addKey(appPublicKey.toString(), appAccountId, appMethodNames, BigInt(parseNearAmount('0.25'))); const keys = await account.getAccessKeys(); expect(keys.find(({ public_key }) => appPublicKey.toString() === public_key) .access_key.permission.FunctionCall.method_names).toEqual(appMethodNames); @@ -115,9 +113,9 @@ describe('account2fa transactions', () => { sender = await getAccount2FA(sender); receiver = await getAccount2FA(receiver); const { amount: receiverAmount } = await receiver.state(); - await sender.sendMoney(receiver.accountId, new BN(parseNearAmount('1'))); + await sender.sendMoney(receiver.accountId, BigInt(parseNearAmount('1'))); const state = await receiver.state(); - expect(BigInt(state.amount)).toBeGreaterThanOrEqual(BigInt(new BN(receiverAmount).add(new BN(parseNearAmount('0.9'))).toString())); + expect(BigInt(state.amount)).toBeGreaterThanOrEqual(BigInt(receiverAmount)+ BigInt(parseNearAmount('0.9').toString())); }); test('send money through signAndSendTransaction', async() => { @@ -126,9 +124,9 @@ describe('account2fa transactions', () => { sender = await getAccount2FA(sender); receiver = await getAccount2FA(receiver); const { amount: receiverAmount } = await receiver.state(); - await sender.signAndSendTransaction({ receiverId: receiver.accountId, actions: [transfer(new BN(parseNearAmount('1')))] }); + await sender.signAndSendTransaction({ receiverId: receiver.accountId, actions: [transfer(BigInt(parseNearAmount('1')))] }); const state = await receiver.state(); - expect(BigInt(state.amount)).toBeGreaterThanOrEqual(BigInt(new BN(receiverAmount).add(new BN(parseNearAmount('0.9'))).toString())); + expect(BigInt(state.amount)).toBeGreaterThanOrEqual(BigInt(receiverAmount) + BigInt(parseNearAmount('0.9').toString())); }); }); diff --git a/packages/accounts/test/contract.test.js b/packages/accounts/test/contract.test.js index 43b49121c3..452c0a5aad 100644 --- a/packages/accounts/test/contract.test.js +++ b/packages/accounts/test/contract.test.js @@ -77,11 +77,11 @@ describe('viewMethod', () => { describe('changeMethod', () => { test('throws error message for invalid gas argument', () => { - return expect(contract.changeMethod({ a: 1 }, 'whatever')).rejects.toThrow(/Expected number, decimal string or BN for 'gas' argument, but got.+/); + return expect(contract.changeMethod({ a: 1 }, 'whatever')).rejects.toThrow(/Expected number, decimal string or BigInt for 'gas' argument, but got.+/); }); test('gives error message for invalid amount argument', () => { - return expect(contract.changeMethod({ a: 1 }, 1000, 'whatever')).rejects.toThrow(/Expected number, decimal string or BN for 'amount' argument, but got.+/); + return expect(contract.changeMethod({ a: 1 }, 1000, 'whatever')).rejects.toThrow(/Expected number, decimal string or BigInt for 'amount' argument, but got.+/); }); test('makes a functionCall and passes along walletCallbackUrl and walletMeta', async() => { diff --git a/packages/accounts/test/promise.test.js b/packages/accounts/test/promise.test.js index f0cc67cc3c..af755eb052 100644 --- a/packages/accounts/test/promise.test.js +++ b/packages/accounts/test/promise.test.js @@ -1,5 +1,3 @@ -const BN = require('bn.js'); - const testUtils = require('./test-utils'); let nearjs; @@ -7,7 +5,7 @@ let workingAccount; jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000; -const CONTRACT_CALL_GAS = new BN(300000000000000); +const CONTRACT_CALL_GAS = BigInt(300000000000000); beforeAll(async () => { nearjs = await testUtils.setUpTestConnection(); diff --git a/packages/accounts/test/providers.test.js b/packages/accounts/test/providers.test.js index 6355090cea..4705777a4c 100644 --- a/packages/accounts/test/providers.test.js +++ b/packages/accounts/test/providers.test.js @@ -1,4 +1,3 @@ -const BN = require('bn.js'); const base58 = require('bs58'); const testUtils = require('./test-utils'); @@ -19,7 +18,7 @@ describe('providers', () => { test('txStatus with string hash and buffer hash', async () => { const sender = await testUtils.createAccount(near); const receiver = await testUtils.createAccount(near); - const outcome = await sender.sendMoney(receiver.accountId, new BN('1')); + const outcome = await sender.sendMoney(receiver.accountId, BigInt('1')); const responseWithString = await provider.txStatus(outcome.transaction.hash, sender.accountId); const responseWithUint8Array = await provider.txStatus(base58.decode(outcome.transaction.hash), sender.accountId); expect(responseWithString).toMatchObject(outcome); @@ -29,7 +28,7 @@ describe('providers', () => { test('txStatusReciept with string hash and buffer hash', async () => { const sender = await testUtils.createAccount(near); const receiver = await testUtils.createAccount(near); - const outcome = await sender.sendMoney(receiver.accountId, new BN('1')); + const outcome = await sender.sendMoney(receiver.accountId, BigInt('1')); const reciepts = await provider.sendJsonRpc('EXPERIMENTAL_tx_status', [outcome.transaction.hash, sender.accountId]); const responseWithString = await provider.txStatusReceipts(outcome.transaction.hash, sender.accountId); @@ -131,7 +130,7 @@ describe('providers', () => { test('json rpc light client proof', async () => { const workingAccount = await testUtils.createAccount(near); - const executionOutcome = await workingAccount.sendMoney(workingAccount.accountId, new BN(10000)); + const executionOutcome = await workingAccount.sendMoney(workingAccount.accountId, BigInt(10000)); const provider = near.connection.provider; async function waitForStatusMatching(isMatching) { diff --git a/packages/accounts/test/test-utils.js b/packages/accounts/test/test-utils.js index 086d7706a1..090b8f9b08 100644 --- a/packages/accounts/test/test-utils.js +++ b/packages/accounts/test/test-utils.js @@ -1,6 +1,5 @@ const { KeyPair } = require('@near-js/crypto'); const { InMemoryKeyStore } = require('@near-js/keystores'); -const BN = require('bn.js'); const fs = require('fs').promises; const path = require('path'); @@ -9,7 +8,7 @@ const { Account, AccountMultisig, Contract, Connection, LocalAccountCreator } = const networkId = 'unittest'; const HELLO_WASM_PATH = process.env.HELLO_WASM_PATH || 'node_modules/near-hello/dist/main.wasm'; -const HELLO_WASM_BALANCE = new BN('10000000000000000000000000'); +const HELLO_WASM_BALANCE = BigInt('10000000000000000000000000'); const HELLO_WASM_METHODS = { viewMethods: ['getValue', 'getLastResult'], changeMethods: ['setValue', 'callPromise'] @@ -69,7 +68,7 @@ async function setUpTestConnection() { }); return { - accountCreator: new LocalAccountCreator(new Account(connection, config.masterAccount), new BN('500000000000000000000000000')), + accountCreator: new LocalAccountCreator(new Account(connection, config.masterAccount), BigInt('500000000000000000000000000')), connection, }; } diff --git a/packages/biometric-ed25519/package.json b/packages/biometric-ed25519/package.json index 8f99cb9847..8c2217af90 100644 --- a/packages/biometric-ed25519/package.json +++ b/packages/biometric-ed25519/package.json @@ -19,7 +19,6 @@ "@noble/curves": "1.2.0", "@noble/hashes": "1.3.3", "asn1-parser": "1.1.8", - "bn.js": "5.2.1", "borsh": "1.0.0", "buffer": "6.0.3", "fido2-lib": "3.4.1" diff --git a/packages/cookbook/package.json b/packages/cookbook/package.json index e2842c76ef..4720f1d4ba 100644 --- a/packages/cookbook/package.json +++ b/packages/cookbook/package.json @@ -12,7 +12,6 @@ "@near-js/providers": "workspace:*", "@near-js/signers": "workspace:*", "@near-js/transactions": "workspace:*", - "bn.js": "5.2.1", "chalk": "4.1.1", "homedir": "0.6.0", "near-api-js": "workspace:*" diff --git a/packages/cookbook/transactions/meta-transaction-relayer.js b/packages/cookbook/transactions/meta-transaction-relayer.js index 11bd71d12d..a0f5054fb1 100644 --- a/packages/cookbook/transactions/meta-transaction-relayer.js +++ b/packages/cookbook/transactions/meta-transaction-relayer.js @@ -3,7 +3,6 @@ const { UnencryptedFileSystemKeyStore } = require('@near-js/keystores-node'); const { JsonRpcProvider, fetchJson } = require('@near-js/providers'); const { InMemorySigner } = require('@near-js/signers'); const { actionCreators, encodeSignedDelegate } = require('@near-js/transactions'); -const BN = require('bn.js'); const os = require('os'); const path = require('path'); @@ -44,7 +43,7 @@ if (require.main === module) { }, SENDER_ACCOUNT_ID); console.log(await sendNearThroughRelayer({ - amount: new BN('1000000000'), + amount: BigInt('1000000000'), receiverId: RECEIVER_ACCOUNT_ID, senderAccount, })); diff --git a/packages/cookbook/transactions/meta-transaction.js b/packages/cookbook/transactions/meta-transaction.js index 0d8772ac98..a37a8c3562 100644 --- a/packages/cookbook/transactions/meta-transaction.js +++ b/packages/cookbook/transactions/meta-transaction.js @@ -3,7 +3,6 @@ const { UnencryptedFileSystemKeyStore } = require('@near-js/keystores-node'); const { JsonRpcProvider } = require('@near-js/providers'); const { InMemorySigner } = require('@near-js/signers'); const { actionCreators } = require('@near-js/transactions'); -const BN = require('bn.js'); const os = require('os'); const path = require('path'); @@ -52,7 +51,7 @@ if (require.main === module) { }, SIGNER_ACCOUNT_ID); console.log(await sendNearViaMetaTransaction({ - amount: new BN('1000000000'), + amount: BigInt('1000000000'), receiverId: RECEIVER_ACCOUNT_ID, senderAccount, signingAccount, diff --git a/packages/crypto/package.json b/packages/crypto/package.json index b23c994325..6a380b4245 100644 --- a/packages/crypto/package.json +++ b/packages/crypto/package.json @@ -18,7 +18,6 @@ "dependencies": { "@near-js/types": "workspace:*", "@near-js/utils": "workspace:*", - "bn.js": "5.2.1", "borsh": "1.0.0", "@noble/curves": "1.2.0", "randombytes": "2.1.0" diff --git a/packages/near-api-js/package.json b/packages/near-api-js/package.json index 616d5e7f6b..bf315900b9 100644 --- a/packages/near-api-js/package.json +++ b/packages/near-api-js/package.json @@ -22,7 +22,6 @@ "@near-js/types": "workspace:*", "@near-js/utils": "workspace:*", "@near-js/wallet-account": "workspace:*", - "bn.js": "5.2.1", "borsh": "1.0.0", "depd": "2.0.0", "http-errors": "1.7.2", @@ -31,7 +30,6 @@ "@noble/curves": "1.2.0" }, "devDependencies": { - "@types/bn.js": "5.1.0", "@types/http-errors": "1.6.1", "@types/node": "18.11.18", "browserify": "16.2.3", diff --git a/packages/near-api-js/src/transaction.ts b/packages/near-api-js/src/transaction.ts index 456c290fc7..6e0065b598 100644 --- a/packages/near-api-js/src/transaction.ts +++ b/packages/near-api-js/src/transaction.ts @@ -25,7 +25,6 @@ export { import { PublicKey } from '@near-js/crypto'; import { AccessKey, actionCreators, stringifyJsonOrBytes } from '@near-js/transactions'; -import BN from 'bn.js'; export const addKey = (publicKey: PublicKey, accessKey: AccessKey) => actionCreators.addKey(publicKey, accessKey); export const createAccount = () => actionCreators.createAccount(); @@ -33,7 +32,7 @@ export const deleteAccount = (beneficiaryId: string) => actionCreators.deleteAcc export const deleteKey = (publicKey: PublicKey) => actionCreators.deleteKey(publicKey); export const deployContract = (code: Uint8Array) => actionCreators.deployContract(code); export const fullAccessKey = () => actionCreators.fullAccessKey(); -export const functionCall = (methodName: string, args: object | Uint8Array, gas: BN, deposit: BN, stringify?: typeof stringifyJsonOrBytes, jsContract?: boolean) => actionCreators.functionCall(methodName, args, gas, deposit, stringify, jsContract); -export const functionCallAccessKey = (receiverId: string, methodNames: string[], allowance?: BN) => actionCreators.functionCallAccessKey(receiverId, methodNames, allowance); -export const stake = (stake: BN, publicKey: PublicKey) => actionCreators.stake(stake, publicKey); -export const transfer = (deposit: BN) => actionCreators.transfer(deposit); +export const functionCall = (methodName: string, args: object | Uint8Array, gas: bigint, deposit: bigint, stringify?: typeof stringifyJsonOrBytes, jsContract?: boolean) => actionCreators.functionCall(methodName, args, gas, deposit, stringify, jsContract); +export const functionCallAccessKey = (receiverId: string, methodNames: string[], allowance?: bigint) => actionCreators.functionCallAccessKey(receiverId, methodNames, allowance); +export const stake = (stake: bigint, publicKey: PublicKey) => actionCreators.stake(stake, publicKey); +export const transfer = (deposit: bigint) => actionCreators.transfer(deposit); diff --git a/packages/near-api-js/test/test-utils.js b/packages/near-api-js/test/test-utils.js index e70ec851ff..275cf0b7e8 100644 --- a/packages/near-api-js/test/test-utils.js +++ b/packages/near-api-js/test/test-utils.js @@ -1,12 +1,11 @@ const fs = require('fs').promises; -const BN = require('bn.js'); const nearApi = require('../src/index'); const networkId = 'unittest'; const HELLO_WASM_PATH = process.env.HELLO_WASM_PATH || 'node_modules/near-hello/dist/main.wasm'; -const HELLO_WASM_BALANCE = new BN('10000000000000000000000000'); +const HELLO_WASM_BALANCE = BigInt('10000000000000000000000000'); const HELLO_WASM_METHODS = { viewMethods: ['getValue', 'getLastResult'], changeMethods: ['setValue', 'callPromise'] diff --git a/packages/near-api-js/tsconfig.json b/packages/near-api-js/tsconfig.json index 8f9d63fd8d..4345274879 100644 --- a/packages/near-api-js/tsconfig.json +++ b/packages/near-api-js/tsconfig.json @@ -2,12 +2,12 @@ "compilerOptions": { "esModuleInterop": true, "lib": [ - "es2015", + "es2016", "esnext", "dom" ], "module": "commonjs", - "target": "es2015", + "target": "es2016", "moduleResolution": "node", "alwaysStrict": true, "outDir": "./lib", diff --git a/packages/providers/package.json b/packages/providers/package.json index f65b4e69ed..9a773fbeeb 100644 --- a/packages/providers/package.json +++ b/packages/providers/package.json @@ -19,7 +19,6 @@ "@near-js/transactions": "workspace:*", "@near-js/types": "workspace:*", "@near-js/utils": "workspace:*", - "bn.js": "5.2.1", "borsh": "1.0.0", "http-errors": "1.7.2" }, diff --git a/packages/transactions/package.json b/packages/transactions/package.json index 5009bd3f23..af311e3ba3 100644 --- a/packages/transactions/package.json +++ b/packages/transactions/package.json @@ -20,7 +20,6 @@ "@near-js/signers": "workspace:*", "@near-js/types": "workspace:*", "@near-js/utils": "workspace:*", - "bn.js": "5.2.1", "borsh": "1.0.0", "@noble/hashes": "1.3.3" }, diff --git a/packages/transactions/src/action_creators.ts b/packages/transactions/src/action_creators.ts index 021106b97b..2fcf064126 100644 --- a/packages/transactions/src/action_creators.ts +++ b/packages/transactions/src/action_creators.ts @@ -1,5 +1,4 @@ import { PublicKey } from '@near-js/crypto'; -import BN from 'bn.js'; import { AccessKey, @@ -29,9 +28,10 @@ function fullAccessKey(): AccessKey { nonce: 0, permission: new AccessKeyPermission({ fullAccess: new FullAccessPermission({}), - }) + }), }); } + /** * Creates an access key with function call permission for a specific receiver and method names. * @param receiverId The NEAR account ID of the function call receiver. @@ -39,12 +39,20 @@ function fullAccessKey(): AccessKey { * @param allowance An optional allowance (maximum amount) for the function call. Default: Unlimited. * @returns A new access key with function call permission. */ -function functionCallAccessKey(receiverId: string, methodNames: string[], allowance?: BN): AccessKey { +function functionCallAccessKey( + receiverId: string, + methodNames: string[], + allowance?: bigint +): AccessKey { return new AccessKey({ nonce: 0, permission: new AccessKeyPermission({ - functionCall: new FunctionCallPermission({ receiverId, allowance, methodNames }), - }) + functionCall: new FunctionCallPermission({ + receiverId, + allowance, + methodNames, + }), + }), }); } @@ -71,7 +79,8 @@ function deployContract(code: Uint8Array): Action { * @returns A Buffer representation of the input argument. */ export function stringifyJsonOrBytes(args: any): Buffer { - const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length; + const isUint8Array = + args.byteLength !== undefined && args.byteLength === args.length; return isUint8Array ? args : Buffer.from(JSON.stringify(args)); } @@ -86,9 +95,18 @@ export function stringifyJsonOrBytes(args: any): Buffer { * @param stringify Convert input arguments into bytes array. * @param jsContract Is contract from JS SDK, skips stringification of arguments. */ -function functionCall(methodName: string, args: Uint8Array | object, gas: BN = new BN(0), deposit: BN = new BN(0), stringify = stringifyJsonOrBytes, jsContract = false): Action { - if(jsContract){ - return new Action({ functionCall: new FunctionCall({ methodName, args, gas, deposit }) }); +function functionCall( + methodName: string, + args: Uint8Array | object, + gas = BigInt(0), + deposit = BigInt(0), + stringify = stringifyJsonOrBytes, + jsContract = false +): Action { + if (jsContract) { + return new Action({ + functionCall: new FunctionCall({ methodName, args, gas, deposit }), + }); } return new Action({ @@ -106,7 +124,7 @@ function functionCall(methodName: string, args: Uint8Array | object, gas: BN = n * @param deposit The amount to be deposited along with the transfer. Default: 0. * @returns A new action for transferring funds. */ -function transfer(deposit: BN = new BN(0)): Action { +function transfer(deposit = BigInt(0)): Action { return new Action({ transfer: new Transfer({ deposit }) }); } @@ -116,7 +134,7 @@ function transfer(deposit: BN = new BN(0)): Action { * @param publicKey The public key associated with the staking action. * @returns A new action for staking tokens. */ -function stake(stake: BN = new BN(0), publicKey: PublicKey): Action { +function stake(stake = BigInt(0), publicKey: PublicKey): Action { return new Action({ stake: new Stake({ stake, publicKey }) }); } @@ -154,8 +172,16 @@ function deleteAccount(beneficiaryId: string): Action { * @param signature The signature associated with the delegate action. * @returns A new action for a signed delegation. */ -function signedDelegate({ delegateAction, signature }: { delegateAction: DelegateAction, signature: Signature }): Action { - return new Action({ signedDelegate: new SignedDelegate({ delegateAction, signature }) }); +function signedDelegate({ + delegateAction, + signature, +}: { + delegateAction: DelegateAction; + signature: Signature; +}): Action { + return new Action({ + signedDelegate: new SignedDelegate({ delegateAction, signature }), + }); } export const actionCreators = { diff --git a/packages/transactions/src/actions.ts b/packages/transactions/src/actions.ts index 3a161be5fc..ab0e6cd609 100644 --- a/packages/transactions/src/actions.ts +++ b/packages/transactions/src/actions.ts @@ -1,6 +1,5 @@ import { PublicKey } from '@near-js/crypto'; import { Assignable } from '@near-js/types'; -import BN from 'bn.js'; import { DelegateAction } from './delegate'; import { Signature } from './signature'; @@ -20,7 +19,7 @@ abstract class Enum { } export class FunctionCallPermission extends Assignable { - allowance?: BN; + allowance?: bigint; receiverId: string; methodNames: string[]; } @@ -33,7 +32,7 @@ export class AccessKeyPermission extends Enum { } export class AccessKey extends Assignable { - nonce: BN; + nonce: bigint; permission: AccessKeyPermission; } @@ -41,9 +40,9 @@ export class IAction extends Assignable {} export class CreateAccount extends IAction {} export class DeployContract extends IAction { code: Uint8Array; } -export class FunctionCall extends IAction { methodName: string; args: Uint8Array; gas: BN; deposit: BN; } -export class Transfer extends IAction { deposit: BN; } -export class Stake extends IAction { stake: BN; publicKey: PublicKey; } +export class FunctionCall extends IAction { methodName: string; args: Uint8Array; gas: bigint; deposit: bigint; } +export class Transfer extends IAction { deposit: bigint; } +export class Stake extends IAction { stake: bigint; publicKey: PublicKey; } export class AddKey extends IAction { publicKey: PublicKey; accessKey: AccessKey; } export class DeleteKey extends IAction { publicKey: PublicKey; } export class DeleteAccount extends IAction { beneficiaryId: string; } diff --git a/packages/transactions/src/create_transaction.ts b/packages/transactions/src/create_transaction.ts index 5da87aa248..d8e8fc6027 100644 --- a/packages/transactions/src/create_transaction.ts +++ b/packages/transactions/src/create_transaction.ts @@ -1,5 +1,4 @@ import { PublicKey } from '@near-js/crypto'; -import BN from 'bn.js'; import { Action } from './actions'; import { Transaction } from './schema'; @@ -14,6 +13,21 @@ import { Transaction } from './schema'; * @param blockHash The hash of the block where the transaction will be included. * @returns A new transaction object initialized with the provided parameters. */ -export function createTransaction(signerId: string, publicKey: PublicKey, receiverId: string, nonce: BN | string | number, actions: Action[], blockHash: Uint8Array): Transaction { - return new Transaction({ signerId, publicKey, nonce: new BN(nonce), receiverId, actions, blockHash }); +export function createTransaction( + signerId: string, + publicKey: PublicKey, + receiverId: string, + nonce: bigint | string | number, + actions: Action[], + blockHash: Uint8Array +): Transaction { + const txNonce = typeof nonce === 'bigint' ? nonce : BigInt(nonce); + return new Transaction({ + signerId, + publicKey, + nonce: txNonce, + receiverId, + actions, + blockHash, + }); } diff --git a/packages/transactions/src/delegate.ts b/packages/transactions/src/delegate.ts index c25db66427..b78de85fff 100644 --- a/packages/transactions/src/delegate.ts +++ b/packages/transactions/src/delegate.ts @@ -1,6 +1,5 @@ import { PublicKey } from '@near-js/crypto'; import { Assignable } from '@near-js/types'; -import BN from 'bn.js'; import { actionCreators } from './action_creators'; import { Action } from './actions'; @@ -20,8 +19,8 @@ export class DelegateAction extends Assignable { senderId: string; receiverId: string; actions: Array; - nonce: BN; - maxBlockHeight: BN; + nonce: bigint; + maxBlockHeight: bigint; publicKey: PublicKey; } diff --git a/packages/transactions/src/schema.ts b/packages/transactions/src/schema.ts index cb1ddf8806..dd004f5ab4 100644 --- a/packages/transactions/src/schema.ts +++ b/packages/transactions/src/schema.ts @@ -1,7 +1,6 @@ import { PublicKey } from '@near-js/crypto'; import { Assignable } from '@near-js/types'; import { deserialize, serialize, Schema } from 'borsh'; -import BN from 'bn.js'; import { Action, @@ -61,7 +60,7 @@ export function decodeSignedTransaction(bytes: Uint8Array) { export class Transaction extends Assignable { signerId: string; publicKey: PublicKey; - nonce: BN; + nonce: bigint; receiverId: string; actions: Action[]; blockHash: Uint8Array; diff --git a/packages/transactions/src/sign.ts b/packages/transactions/src/sign.ts index f84fc5a844..0151b4587d 100644 --- a/packages/transactions/src/sign.ts +++ b/packages/transactions/src/sign.ts @@ -1,5 +1,4 @@ import { Signer } from '@near-js/signers'; -import BN from 'bn.js'; import { sha256 } from '@noble/hashes/sha256'; import { Action, SignedDelegate } from './actions'; @@ -41,7 +40,7 @@ async function signTransactionObject(transaction: Transaction, signer: Signer, a } export async function signTransaction(transaction: Transaction, signer: Signer, accountId?: string, networkId?: string): Promise<[Uint8Array, SignedTransaction]>; -export async function signTransaction(receiverId: string, nonce: BN, actions: Action[], blockHash: Uint8Array, signer: Signer, accountId?: string, networkId?: string): Promise<[Uint8Array, SignedTransaction]>; +export async function signTransaction(receiverId: string, nonce: bigint, actions: Action[], blockHash: Uint8Array, signer: Signer, accountId?: string, networkId?: string): Promise<[Uint8Array, SignedTransaction]>; export async function signTransaction(...args): Promise<[Uint8Array, SignedTransaction]> { if (args[0].constructor === Transaction) { const [ transaction, signer, accountId, networkId ] = args; diff --git a/packages/transactions/test/serialize.test.js b/packages/transactions/test/serialize.test.js index d6977e1664..54cbc034e1 100644 --- a/packages/transactions/test/serialize.test.js +++ b/packages/transactions/test/serialize.test.js @@ -4,7 +4,6 @@ const { InMemorySigner } = require('@near-js/signers'); const { Assignable } = require('@near-js/types'); const { baseDecode, baseEncode } = require('@near-js/utils'); const fs = require('fs'); -const BN = require('bn.js'); const { deserialize, serialize } = require('borsh'); const { @@ -153,7 +152,7 @@ describe('serialize and deserialize on different types of nonce', () => { transfer(1), ]; const blockHash = baseDecode('244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM'); - const targetNonce = new BN(1); + const targetNonce = BigInt(1); test('number typed nonce', async () => { const transaction = createTransaction( 'test.near', @@ -184,12 +183,12 @@ describe('serialize and deserialize on different types of nonce', () => { expect(deserialized.nonce.toString()).toEqual(targetNonce.toString()); }); - test('BN typed nonce', async () => { + test('BigInt typed nonce', async () => { const transaction = createTransaction( 'test.near', PublicKey.fromString('Anu7LYDfpLtkP7E16LT9imXF694BdQaa9ufVkQiwTQxC'), 'whatever.near', - new BN(1), + BigInt(1), actions, blockHash); const serialized = encodeTransaction(transaction); diff --git a/packages/transactions/test/transaction.test.js b/packages/transactions/test/transaction.test.js index 29bda2319d..c48040a46c 100644 --- a/packages/transactions/test/transaction.test.js +++ b/packages/transactions/test/transaction.test.js @@ -1,31 +1,29 @@ -const BN = require('bn.js'); - const { actionCreators } = require('../lib'); const { functionCall } = actionCreators; test('functionCall with already serialized args', () => { const serializedArgs = Buffer.from('{}'); - const action = functionCall('methodName', serializedArgs, new BN(1), new BN(2)); + const action = functionCall('methodName', serializedArgs, BigInt(1), BigInt(2)); expect(action).toMatchObject({ functionCall: { methodName: 'methodName', args: serializedArgs, - gas: new BN(1), - deposit: new BN(2) + gas: BigInt(1), + deposit: BigInt(2) } }); }); test('functionCall with non-serialized args', () => { const serializedArgs = Buffer.from('{}'); - const action = functionCall('methodName', {}, new BN(1), new BN(2)); + const action = functionCall('methodName', {}, BigInt(1), BigInt(2)); expect(action).toMatchObject({ functionCall: { methodName: 'methodName', args: serializedArgs, - gas: new BN(1), - deposit: new BN(2) + gas: BigInt(1), + deposit: BigInt(2) } }); }); diff --git a/packages/types/package.json b/packages/types/package.json index e72b5d6942..1f74423b27 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -12,9 +12,6 @@ "keywords": [], "author": "", "license": "ISC", - "dependencies": { - "bn.js": "5.2.1" - }, "devDependencies": { "@types/node": "18.11.18", "jest": "26.0.1", diff --git a/packages/types/src/provider/protocol.ts b/packages/types/src/provider/protocol.ts index f8da829f41..d03a1e5c32 100644 --- a/packages/types/src/provider/protocol.ts +++ b/packages/types/src/provider/protocol.ts @@ -3,8 +3,6 @@ * @module */ -import BN from 'bn.js'; - export interface SyncInfo { latest_block_hash: string; latest_block_height: number; @@ -127,7 +125,7 @@ export interface Chunk { export interface Transaction { actions: Array; hash: string; - nonce: BN; + nonce: BigInt; public_key: string; receiver_id: string; signature: string; diff --git a/packages/types/src/provider/response.ts b/packages/types/src/provider/response.ts index f195139266..e5a427da3c 100644 --- a/packages/types/src/provider/response.ts +++ b/packages/types/src/provider/response.ts @@ -3,8 +3,6 @@ * @module */ -import BN from 'bn.js'; - import { BlockHash, BlockHeight, MerklePath } from './protocol'; export enum ExecutionStatusBasic { @@ -110,7 +108,7 @@ export interface AccessKeyViewRaw extends QueryResponseKind { permission: 'FullAccess' | FunctionCallPermissionView; } export interface AccessKeyView extends QueryResponseKind { - nonce: BN; + nonce: bigint; permission: 'FullAccess' | FunctionCallPermissionView; } diff --git a/packages/utils/package.json b/packages/utils/package.json index 296749dc35..da7004aaea 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -15,7 +15,6 @@ "license": "ISC", "dependencies": { "@near-js/types": "workspace:*", - "bn.js": "5.2.1", "bs58": "4.0.0", "depd": "2.0.0", "mustache": "4.0.0" diff --git a/packages/utils/src/constants.ts b/packages/utils/src/constants.ts index 63a7c421ce..01b413f985 100644 --- a/packages/utils/src/constants.ts +++ b/packages/utils/src/constants.ts @@ -1,9 +1,7 @@ -import BN from 'bn.js'; - // Default amount of gas to be sent with the function calls. Used to pay for the fees // incurred while running the contract execution. The unused amount will be refunded back to // the originator. // Due to protocol changes that charge upfront for the maximum possible gas price inflation due to // full blocks, the price of max_prepaid_gas is decreased to `300 * 10**12`. // For discussion see https://github.com/nearprotocol/NEPs/issues/67 -export const DEFAULT_FUNCTION_CALL_GAS = new BN('30000000000000'); \ No newline at end of file +export const DEFAULT_FUNCTION_CALL_GAS = BigInt('30000000000000'); \ No newline at end of file diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts index 1f718d6819..8e4830d545 100644 --- a/packages/utils/src/format.ts +++ b/packages/utils/src/format.ts @@ -1,5 +1,4 @@ -import BN from 'bn.js'; -import bs58 from 'bs58'; +import bs58 from "bs58"; /** * Exponent for calculating how many indivisible units are there in one NEAR. See {@link NEAR_NOMINATION}. @@ -9,12 +8,16 @@ export const NEAR_NOMINATION_EXP = 24; /** * Number of indivisible units in one NEAR. Derived from {@link NEAR_NOMINATION_EXP}. */ -export const NEAR_NOMINATION = new BN('10', 10).pow(new BN(NEAR_NOMINATION_EXP, 10)); +export const NEAR_NOMINATION = BigInt(10) ** BigInt(NEAR_NOMINATION_EXP); // Pre-calculate offsets used for rounding to different number of digits -const ROUNDING_OFFSETS: BN[] = []; -const BN10 = new BN(10); -for (let i = 0, offset = new BN(5); i < NEAR_NOMINATION_EXP; i++, offset = offset.mul(BN10)) { +const ROUNDING_OFFSETS: bigint[] = []; +const BN10 = BigInt(10); +for ( + let i = 0, offset = BigInt(5); + i < NEAR_NOMINATION_EXP; + i++, offset = offset * BN10 +) { ROUNDING_OFFSETS[i] = offset; } @@ -26,20 +29,26 @@ for (let i = 0, offset = new BN(5); i < NEAR_NOMINATION_EXP; i++, offset = offse * @param fracDigits number of fractional digits to preserve in formatted string. Balance is rounded to match given number of digits. * @returns Value in Ⓝ */ -export function formatNearAmount(balance: string, fracDigits: number = NEAR_NOMINATION_EXP): string { - const balanceBN = new BN(balance, 10); +export function formatNearAmount( + balance: string, + fracDigits: number = NEAR_NOMINATION_EXP +): string { + let balanceBN = BigInt(balance); if (fracDigits !== NEAR_NOMINATION_EXP) { // Adjust balance for rounding at given number of digits const roundingExp = NEAR_NOMINATION_EXP - fracDigits - 1; if (roundingExp > 0) { - balanceBN.iadd(ROUNDING_OFFSETS[roundingExp]); + balanceBN += ROUNDING_OFFSETS[roundingExp]; } } balance = balanceBN.toString(); - const wholeStr = balance.substring(0, balance.length - NEAR_NOMINATION_EXP) || '0'; - const fractionStr = balance.substring(balance.length - NEAR_NOMINATION_EXP) - .padStart(NEAR_NOMINATION_EXP, '0').substring(0, fracDigits); + const wholeStr = + balance.substring(0, balance.length - NEAR_NOMINATION_EXP) || "0"; + const fractionStr = balance + .substring(balance.length - NEAR_NOMINATION_EXP) + .padStart(NEAR_NOMINATION_EXP, "0") + .substring(0, fracDigits); return trimTrailingZeroes(`${formatWithCommas(wholeStr)}.${fractionStr}`); } @@ -52,15 +61,19 @@ export function formatNearAmount(balance: string, fracDigits: number = NEAR_NOMI * @returns The parsed yoctoⓃ amount or null if no amount was passed in */ export function parseNearAmount(amt?: string): string | null { - if (!amt) { return null; } + if (!amt) { + return null; + } amt = cleanupAmount(amt); - const split = amt.split('.'); + const split = amt.split("."); const wholePart = split[0]; - const fracPart = split[1] || ''; + const fracPart = split[1] || ""; if (split.length > 2 || fracPart.length > NEAR_NOMINATION_EXP) { throw new Error(`Cannot parse '${amt}' as NEAR amount`); } - return trimLeadingZeroes(wholePart + fracPart.padEnd(NEAR_NOMINATION_EXP, '0')); + return trimLeadingZeroes( + wholePart + fracPart.padEnd(NEAR_NOMINATION_EXP, "0") + ); } /** @@ -69,7 +82,7 @@ export function parseNearAmount(amt?: string): string | null { * @returns string The cleaned value */ function cleanupAmount(amount: string): string { - return amount.replace(/,/g, '').trim(); + return amount.replace(/,/g, "").trim(); } /** @@ -78,7 +91,7 @@ function cleanupAmount(amount: string): string { * @returns string The value without the trailing zeros */ function trimTrailingZeroes(value: string): string { - return value.replace(/\.?0*$/, ''); + return value.replace(/\.?0*$/, ""); } /** @@ -87,9 +100,9 @@ function trimTrailingZeroes(value: string): string { * @returns string The value without the leading zeroes */ function trimLeadingZeroes(value: string): string { - value = value.replace(/^0+/, ''); - if (value === '') { - return '0'; + value = value.replace(/^0+/, ""); + if (value === "") { + return "0"; } return value; } @@ -102,7 +115,7 @@ function trimLeadingZeroes(value: string): string { function formatWithCommas(value: string): string { const pattern = /(-?\d+)(\d{3})/; while (pattern.test(value)) { - value = value.replace(pattern, '$1,$2'); + value = value.replace(pattern, "$1,$2"); } return value; } @@ -113,9 +126,9 @@ function formatWithCommas(value: string): string { * @returns string base58 encoding of the value */ export function baseEncode(value: Uint8Array | string): string { - if (typeof value === 'string') { + if (typeof value === "string") { const bytes = []; - for(let c = 0; c < value.length; c++){ + for (let c = 0; c < value.length; c++) { bytes.push(value.charCodeAt(c)); } value = new Uint8Array(bytes); @@ -130,4 +143,4 @@ export function baseEncode(value: Uint8Array | string): string { */ export function baseDecode(value: string): Uint8Array { return new Uint8Array(bs58.decode(value)); -} \ No newline at end of file +} diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 6fb6401bf4..95eb389afe 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -5,3 +5,4 @@ export * from './logging'; export * from './provider'; export * from './validators'; export * from './logger'; +export * from './utils'; \ No newline at end of file diff --git a/packages/utils/src/utils.ts b/packages/utils/src/utils.ts new file mode 100644 index 0000000000..2e02ba2254 --- /dev/null +++ b/packages/utils/src/utils.ts @@ -0,0 +1,3 @@ +export function sortBigIntAsc(a: bigint, b: bigint) { + return (a < b ? -1 : a > b ? 1 : 0) +} \ No newline at end of file diff --git a/packages/utils/src/validators.ts b/packages/utils/src/validators.ts index 7dac43ffce..ff167ddd61 100644 --- a/packages/utils/src/validators.ts +++ b/packages/utils/src/validators.ts @@ -1,6 +1,6 @@ import { CurrentEpochValidatorInfo, NextEpochValidatorInfo } from '@near-js/types'; -import BN from 'bn.js'; import depd from 'depd'; +import { sortBigIntAsc } from './utils'; /** Finds seat price given validators stakes and number of seats. * Calculation follow the spec: https://nomicon.io/Economics/README.html#validator-selection @@ -9,7 +9,7 @@ import depd from 'depd'; * @param minimumStakeRatio: minimum stake ratio * @param protocolVersion: version of the protocol from genesis config */ -export function findSeatPrice(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], maxNumberOfSeats: number, minimumStakeRatio: number[], protocolVersion?: number): BN { +export function findSeatPrice(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], maxNumberOfSeats: number, minimumStakeRatio: number[], protocolVersion?: number): bigint { if (protocolVersion && protocolVersion < 49) { return findSeatPriceForProtocolBefore49(validators, maxNumberOfSeats); } @@ -21,22 +21,22 @@ export function findSeatPrice(validators: (CurrentEpochValidatorInfo | NextEpoch return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio); } -function findSeatPriceForProtocolBefore49(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], numSeats: number): BN { - const stakes = validators.map(v => new BN(v.stake, 10)).sort((a, b) => a.cmp(b)); - const num = new BN(numSeats); - const stakesSum = stakes.reduce((a, b) => a.add(b)); - if (stakesSum.lt(num)) { +function findSeatPriceForProtocolBefore49(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], numSeats: number): bigint { + const stakes = validators.map(v => BigInt(v.stake)).sort(sortBigIntAsc); + const num = BigInt(numSeats); + const stakesSum = stakes.reduce((a, b) => a + b); + if (stakesSum < num) { throw new Error('Stakes are below seats'); } // assert stakesSum >= numSeats - let left = new BN(1), right = stakesSum.add(new BN(1)); - while (!left.eq(right.sub(new BN(1)))) { - const mid = left.add(right).div(new BN(2)); + let left = BigInt(1), right = stakesSum + BigInt(1); + while (left !== right - BigInt(1)) { + const mid = (left + right) / BigInt(2); let found = false; - let currentSum = new BN(0); + let currentSum = BigInt(0); for (let i = 0; i < stakes.length; ++i) { - currentSum = currentSum.add(stakes[i].div(mid)); - if (currentSum.gte(num)) { + currentSum = currentSum + (stakes[i] / mid); + if (currentSum >= num) { left = mid; found = true; break; @@ -50,16 +50,16 @@ function findSeatPriceForProtocolBefore49(validators: (CurrentEpochValidatorInfo } // nearcore reference: https://github.com/near/nearcore/blob/5a8ae263ec07930cd34d0dcf5bcee250c67c02aa/chain/epoch_manager/src/validator_selection.rs#L308;L315 -function findSeatPriceForProtocolAfter49(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], maxNumberOfSeats: number, minimumStakeRatio: number[]): BN { +function findSeatPriceForProtocolAfter49(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], maxNumberOfSeats: number, minimumStakeRatio: number[]): bigint { if (minimumStakeRatio.length != 2) { throw Error('minimumStakeRatio should have 2 elements'); } - const stakes = validators.map(v => new BN(v.stake, 10)).sort((a, b) => a.cmp(b)); - const stakesSum = stakes.reduce((a, b) => a.add(b)); + const stakes = validators.map(v => BigInt(v.stake)).sort(sortBigIntAsc); + const stakesSum = stakes.reduce((a, b) => a + b); if (validators.length < maxNumberOfSeats) { - return stakesSum.mul(new BN(minimumStakeRatio[0])).div(new BN(minimumStakeRatio[1])); + return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]); } else { - return stakes[0].add(new BN(1)); + return stakes[0] + BigInt(1); } } diff --git a/packages/utils/test/format.test.js b/packages/utils/test/format.test.js index fcd642d5b5..686f8b3241 100644 --- a/packages/utils/test/format.test.js +++ b/packages/utils/test/format.test.js @@ -1,4 +1,4 @@ -const { formatNearAmount, parseNearAmount } = require('../lib'); +const { formatNearAmount, parseNearAmount, NEAR_NOMINATION } = require('../lib'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; @@ -57,3 +57,7 @@ test('parseNearAmount fails when parsing values with ≥25 decimal places', () = 'Cannot parse \'0.0000080990999998370878871\' as NEAR amount' ); }); + +test('NEAR_NOMINATION value', () => { + expect(NEAR_NOMINATION).toEqual(1000000000000000000000000n) +}) diff --git a/packages/utils/test/validator.test.js b/packages/utils/test/validator.test.js index 6bb95cec4c..a90c0e09cd 100644 --- a/packages/utils/test/validator.test.js +++ b/packages/utils/test/validator.test.js @@ -1,20 +1,21 @@ -const BN = require('bn.js'); - const { diffEpochValidators, findSeatPrice } = require('../lib'); test('find seat price', async () => { expect(findSeatPrice( [{stake: '1000000'}, {stake: '1000000'}, {stake: '100'}], 2, [1, 6250], 49 - )).toEqual(new BN('101')); + )).toEqual(BigInt('101')); expect(findSeatPrice( [{stake: '1000000'}, {stake: '1000000'}, {stake: '100'}], 3, [1, 6250] - )).toEqual(new BN('101')); + )).toEqual(BigInt('101')); expect(findSeatPrice( [{stake: '1000000'}, {stake: '1000000'}, {stake: '100'}], 4, [1, 6250], 49 - )).toEqual(new BN('320')); + )).toEqual(BigInt('320')); + expect(findSeatPrice( + [{stake: '1000000'}, {stake: '1000000'}, {stake: '100'}], 4, [1, 6250], 48 + )).toEqual(BigInt('500000')); expect(findSeatPrice( [{stake: '1000'}, {stake: '1000'}, {stake: '200'}], 100, [1, 25] - )).toEqual(new BN('88')); + )).toEqual(BigInt('88')); }); test('diff validators', async () => { diff --git a/packages/wallet-account/package.json b/packages/wallet-account/package.json index 711f9828eb..6130024cd9 100644 --- a/packages/wallet-account/package.json +++ b/packages/wallet-account/package.json @@ -19,7 +19,6 @@ "@near-js/transactions": "workspace:*", "@near-js/types": "workspace:*", "@near-js/utils": "workspace:*", - "bn.js": "5.2.1", "borsh": "1.0.0" }, "devDependencies": { diff --git a/packages/wallet-account/src/near.ts b/packages/wallet-account/src/near.ts index 9762fa9be1..a5837d0f96 100644 --- a/packages/wallet-account/src/near.ts +++ b/packages/wallet-account/src/near.ts @@ -18,7 +18,6 @@ import { PublicKey } from '@near-js/crypto'; import { KeyStore } from '@near-js/keystores'; import { Signer } from '@near-js/signers'; import { LoggerService } from '@near-js/utils'; -import BN from 'bn.js'; export interface NearConfig { /** Holds {@link "@near-js/crypto".key_pair.KeyPair | KeyPair} for signing transactions */ @@ -107,7 +106,7 @@ export class Near { if (config.masterAccount) { // TODO: figure out better way of specifiying initial balance. // Hardcoded number below must be enough to pay the gas cost to dev-deploy with near-shell for multiple times - const initialBalance = config.initialBalance ? new BN(config.initialBalance) : new BN('500000000000000000000000000'); + const initialBalance = config.initialBalance ? BigInt(config.initialBalance) : BigInt('500000000000000000000000000'); this.accountCreator = new LocalAccountCreator(new Account(this.connection, config.masterAccount), initialBalance); } else if (config.helperUrl) { this.accountCreator = new UrlAccountCreator(this.connection, config.helperUrl); diff --git a/packages/wallet-account/src/wallet_account.ts b/packages/wallet-account/src/wallet_account.ts index 18d9115b72..daa40b8984 100644 --- a/packages/wallet-account/src/wallet_account.ts +++ b/packages/wallet-account/src/wallet_account.ts @@ -16,7 +16,6 @@ import { InMemorySigner } from '@near-js/signers'; import { FinalExecutionOutcome } from '@near-js/types'; import { baseDecode } from '@near-js/utils'; import { Transaction, Action, SCHEMA, createTransaction } from '@near-js/transactions'; -import BN from 'bn.js'; import { serialize } from 'borsh'; import { Near } from './near'; @@ -371,7 +370,7 @@ export class ConnectedWalletAccount extends Account { const publicKey = PublicKey.from(accessKey.public_key); // TODO: Cache & listen for nonce updates for given access key - const nonce = accessKey.access_key.nonce.add(new BN(1)); + const nonce = accessKey.access_key.nonce + BigInt(1); const transaction = createTransaction(this.accountId, publicKey, receiverId, nonce, actions, blockHash); await this.walletConnection.requestSignTransactions({ transactions: [transaction], diff --git a/packages/wallet-account/test/wallet_account.test.js b/packages/wallet-account/test/wallet_account.test.js index edce403c5c..c64c16d494 100644 --- a/packages/wallet-account/test/wallet_account.test.js +++ b/packages/wallet-account/test/wallet_account.test.js @@ -3,7 +3,6 @@ const { InMemoryKeyStore } = require('@near-js/keystores'); const { InMemorySigner } = require('@near-js/signers'); const { baseDecode } = require('@near-js/utils'); const { actionCreators, createTransaction, SCHEMA } = require('@near-js/transactions'); -const BN = require('bn.js'); const { deserialize } = require('borsh'); const localStorage = require('localstorage-memory'); const url = require('url'); @@ -342,11 +341,11 @@ describe('requests transaction signing automatically when there is no local key' expect(transactions).toHaveLength(1); expect(transactions[0]).toMatchObject({ signerId: 'signer.near', - // nonce: new BN(2) + // nonce: BigInt(2) receiverId: 'receiver.near', actions: [{ transfer: { - // deposit: new BN(1) + // deposit: BigInt(1) } }] }); @@ -389,7 +388,7 @@ describe('requests transaction signing automatically when function call has atta try { await walletConnection.account().signAndSendTransaction({ receiverId: 'receiver.near', - actions: [functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('1'))], + actions: [functionCall('someMethod', new Uint8Array(), BigInt('1'), BigInt('1'))], walletCallbackUrl: 'http://example.com/after', walletMeta: 'someStuff' }); @@ -430,7 +429,7 @@ describe('requests transaction signing with 2fa access key', () => { try { const res = await walletConnection.account().signAndSendTransaction({ receiverId: 'receiver.near', - actions: [functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('1'))] + actions: [functionCall('someMethod', new Uint8Array(), BigInt('1'), BigInt('1'))] }); // multisig access key is accepted res is object representing transaction, populated upon wallet redirect to app @@ -469,7 +468,7 @@ describe('fails requests transaction signing without 2fa access key', () => { return expect( walletConnection.account().signAndSendTransaction({ receiverId: 'receiver.near', - actions: [functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('1'))] + actions: [functionCall('someMethod', new Uint8Array(), BigInt('1'), BigInt('1'))] }) ).rejects.toThrow('Cannot find matching key for transaction sent to receiver.near'); }); @@ -498,8 +497,8 @@ describe('can sign transaction locally when function call has no attached deposi }); it.each([ - functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('0')), - functionCall('someMethod', new Uint8Array(), new BN('1')), + functionCall('someMethod', new Uint8Array(), BigInt('1'), BigInt('0')), + functionCall('someMethod', new Uint8Array(), BigInt('1')), functionCall('someMethod', new Uint8Array()) ])('V2', async (functionCall) => { await walletConnection.account().signAndSendTransaction({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5c2c78a51c..8ce6e85b14 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -68,9 +68,6 @@ importers: '@near-js/utils': specifier: workspace:* version: link:../utils - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -132,9 +129,6 @@ importers: asn1-parser: specifier: 1.1.8 version: 1.1.8 - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -166,9 +160,6 @@ importers: '@near-js/transactions': specifier: workspace:* version: link:../transactions - bn.js: - specifier: 5.2.1 - version: 5.2.1 chalk: specifier: 4.1.1 version: 4.1.1 @@ -190,9 +181,6 @@ importers: '@noble/curves': specifier: 1.2.0 version: 1.2.0 - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -324,9 +312,6 @@ importers: '@noble/curves': specifier: 1.2.0 version: 1.2.0 - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -343,9 +328,6 @@ importers: specifier: 2.6.7 version: 2.6.7 devDependencies: - '@types/bn.js': - specifier: 5.1.0 - version: 5.1.0 '@types/http-errors': specifier: 1.6.1 version: 1.6.1 @@ -409,9 +391,6 @@ importers: '@near-js/utils': specifier: workspace:* version: link:../utils - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -481,9 +460,6 @@ importers: '@noble/hashes': specifier: 1.3.3 version: 1.3.3 - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -505,10 +481,6 @@ importers: version: 4.9.4 packages/types: - dependencies: - bn.js: - specifier: 5.2.1 - version: 5.2.1 devDependencies: '@types/node': specifier: 18.11.18 @@ -528,9 +500,6 @@ importers: '@near-js/types': specifier: workspace:* version: link:../types - bn.js: - specifier: 5.2.1 - version: 5.2.1 bs58: specifier: 4.0.0 version: 4.0.0 @@ -577,9 +546,6 @@ importers: '@near-js/utils': specifier: workspace:* version: link:../utils - bn.js: - specifier: 5.2.1 - version: 5.2.1 borsh: specifier: 1.0.0 version: 1.0.0 @@ -2043,12 +2009,6 @@ packages: '@babel/types': 7.22.5 dev: true - /@types/bn.js@5.1.0: - resolution: {integrity: sha512-QSSVYj7pYFN49kW77o2s9xTCwZ8F2xLbjLLSEVh8D2F4JUhZtPAGOFLTD+ffqksBx/u4cE/KImFjyhqCjn/LIA==} - dependencies: - '@types/node': 18.11.18 - dev: true - /@types/cacheable-request@6.0.3: resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==} dependencies: @@ -2701,6 +2661,7 @@ packages: /bn.js@5.2.1: resolution: {integrity: sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==} + dev: true /borsh@0.5.0: resolution: {integrity: sha512-p9w/qGBeeFdUf2GPBPHdX5JQyez8K5VtoFN7PqSfmR+cVUMSmcwAKhP9n2aXoDSKbtS7xZlZt3MVnrJL7GdYhg==} diff --git a/tsconfig.base.json b/tsconfig.base.json index 8194814911..bdf0a92ecc 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -2,7 +2,7 @@ "compilerOptions": { "esModuleInterop": true, "module": "commonjs", - "target": "es2015", + "target": "es2016", "moduleResolution": "node", "alwaysStrict": true, "declaration": true, diff --git a/tsconfig.browser.json b/tsconfig.browser.json index 41a429f162..473e66c139 100644 --- a/tsconfig.browser.json +++ b/tsconfig.browser.json @@ -2,7 +2,7 @@ "extends": "./tsconfig.base.json", "compilerOptions": { "lib": [ - "es2015", + "es2016", "esnext", "dom" ], diff --git a/tsconfig.node.json b/tsconfig.node.json index 976778f200..e55fcd0b07 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -2,7 +2,7 @@ "extends": "./tsconfig.base.json", "compilerOptions": { "lib": [ - "es2015", + "es2016", "esnext" ], },