From 6fcbe03d032a43a98b76ed4b6b2b426b0513ccd8 Mon Sep 17 00:00:00 2001 From: denbite Date: Fri, 11 Apr 2025 22:09:08 +0200 Subject: [PATCH 01/12] feat: update examples to the recent `near-api-js` version --- javascript/examples/account-details.js | 18 +- javascript/examples/batch-actions.js | 28 +- javascript/examples/contract-interaction.js | 80 ++-- .../examples/create-account-from-seed.js | 34 +- javascript/examples/create-account.js | 42 +- javascript/examples/delete-account.js | 49 +- javascript/examples/keys.js | 38 +- .../keystore-options/credentials-directory.js | 31 +- .../keystore-options/credentials-file.js | 27 +- .../keystore-options/private-key-string.js | 25 +- .../examples/keystore-options/seed-phrase.js | 22 +- javascript/examples/manual-sign.js | 45 +- javascript/examples/rpc-failover.js | 28 +- javascript/examples/send-tokens.js | 26 +- .../examples/simultaneous-transactions.js | 57 +-- .../verify-signature/authentication.js | 4 +- javascript/package.json | 5 + javascript/pnpm-lock.yaml | 419 +----------------- 18 files changed, 240 insertions(+), 738 deletions(-) diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index 1448d94..31077ef 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -1,21 +1,17 @@ -import { connect } from "near-api-js"; +import { PublicAccount, providers } from "near-api-js"; -const connection = await connect({ - networkId: "testnet", - nodeUrl: "https://test.rpc.fastnear.com", +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", }); // Create an account object -const account = await connection.account("example-account.testnet"); +const account = new PublicAccount("example-account.testnet", provider); // Gets the total, staked and available balance in yoctoNEAR -const accountBalance = await account.getAccountBalance(); +const accountBalance = await account.getBalance(); console.log(accountBalance); // Account's state, including its code hash and storage usage -const accountState = await account.state(); +const accountState = await account.getInformation(); console.log(accountState); - -// Gets a list of authorized apps for an account -const accountDetails = await account.getAccountDetails(); -console.log(accountDetails); diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index e4e735d..a6e0088 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -1,32 +1,30 @@ -import { connect, keyStores, KeyPair, transactions, utils } from "near-api-js"; +import { Account, providers, KeyPairSigner, transactions, utils } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Send a batch of actions to a single receiver // Prepare the actions const callAction = transactions.functionCall( "increment", // Method name - [], // Arguments - "30000000000000", // Gas - 0, // Deposit + {}, // Arguments + BigInt(30_000_000_000_000), // Gas + BigInt(0) // Deposit ); -const transferAction = transactions.transfer(utils.format.parseNearAmount("1")); +const transferAction = transactions.transfer(BigInt(utils.format.parseNearAmount("1"))); // Send the batch of actions const batchActionsResult = await account.signAndSendTransaction({ diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index e3db355..d007613 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -1,4 +1,4 @@ -import { connect, keyStores, KeyPair, providers } from "near-api-js"; +import { Account, providers, KeyPairSigner } from "near-api-js"; import dotenv from "dotenv"; import fs from "fs"; @@ -6,53 +6,17 @@ dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); - -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); - -const account = await nearConnection.account(accountId); - -// Make a view call to a contract -async function viewContract({ - contractId, - methodName, - args = {}, - finality = "optimistic", -}) { - // Set up a new provider - const url = `https://test.rpc.fastnear.com`; - const provider = new providers.JsonRpcProvider({ url }); - - // Convert the arguments to base64 - const argsBase64 = args - ? Buffer.from(JSON.stringify(args)).toString("base64") - : ""; - - // Make the view call - const viewCallResult = await provider.query({ - request_type: "call_function", - account_id: contractId, - method_name: methodName, - args_base64: argsBase64, - finality: finality, - }); - - // Parse the result - return JSON.parse(Buffer.from(viewCallResult.result).toString()); -} +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); // Use the view call function -const viewCallData = await viewContract({ - contractId: "guestbook.near-examples.testnet", - methodName: "total_messages", -}); +const viewCallData = await provider.callContractViewFunction( + "guestbook.near-examples.testnet", + "total_messages", + {} +); console.log(viewCallData); // If args are required, they can be passed in like this: @@ -61,20 +25,26 @@ console.log(viewCallData); // limit: "10" // } +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet + // Make a function call to a contract -const contractCallResult = await account.functionCall({ - contractId: "guestbook.near-examples.testnet", // Contract account ID - methodName: "add_message", // Method to call - args: { +const contractCallResult = await account.callFunction( + "guestbook.near-examples.testnet", + "add_message", + { text: "Hello, world!", - }, // Arguments for the method - gas: 100000000000000, // Optional: gas limit - attachedDeposit: 0, // Optional: deposit in yoctoNEAR -}); + }, + BigInt(0), + BigInt(100_000_000_000_000) +); console.log(contractCallResult); // Deploy a contract to the account const deployResult = await account.deployContract( - fs.readFileSync("../contracts/contract.wasm"), // Path of contract WASM relative to the working directory + fs.readFileSync("../contracts/contract.wasm") // Path of contract WASM relative to the working directory ); console.log(deployResult); diff --git a/javascript/examples/create-account-from-seed.js b/javascript/examples/create-account-from-seed.js index a2d2f0d..c970d28 100644 --- a/javascript/examples/create-account-from-seed.js +++ b/javascript/examples/create-account-from-seed.js @@ -1,4 +1,4 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { Account, providers, KeyPairSigner, utils } from "near-api-js"; import { generateSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; @@ -6,18 +6,16 @@ dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Create a .testnet account // Generate a new account ID based on the current timestamp @@ -28,13 +26,9 @@ console.log("Seed phrase", seedPhrase); console.log("Private key", secretKey); console.log("Public key", publicKey); -const createAccountResult = await account.functionCall({ - contractId: "testnet", - methodName: "create_account", - args: { - new_account_id: newAccountId, // example-account.testnet - new_public_key: publicKey, // ed25519:2ASWc... - }, - attachedDeposit: utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR -}); +const createAccountResult = await account.createTopLevelAccount( + newAccountId, + publicKey, + BigInt(utils.format.parseNearAmount("0.1")) +); console.log(createAccountResult); diff --git a/javascript/examples/create-account.js b/javascript/examples/create-account.js index c24b4fb..8f78833 100644 --- a/javascript/examples/create-account.js +++ b/javascript/examples/create-account.js @@ -1,22 +1,20 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Create a .testnet account // Generate a new account ID based on the current timestamp @@ -28,20 +26,16 @@ const newPrivateKey = newKeyPair.toString(); console.log("Private key", newPrivateKey); console.log("Public key", newPublicKey); -const createAccountResult = await account.functionCall({ - contractId: "testnet", - methodName: "create_account", - args: { - new_account_id: newAccountId, // example-account.testnet - new_public_key: newPublicKey, // ed25519:2ASWc... - }, - attachedDeposit: utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR -}); +const createAccountResult = await account.createTopLevelAccount( + newAccountId, + newPublicKey, // ed25519:2ASWc... + BigInt(utils.format.parseNearAmount("0.1")) // Initial balance for new account in yoctoNEAR +); console.log(createAccountResult); // Create a sub account // Generate a new sub account ID based on the current timestamp -const newSubAccountId = Date.now() + "." + accountId; +const newSubAccountIdPrefix = Date.now().toString(); // Generate a new key pair const newSubKeyPair = KeyPair.fromRandom("ed25519"); const newSubPublicKey = newSubKeyPair.getPublicKey().toString(); @@ -49,9 +43,9 @@ const newSubPrivateKey = newSubKeyPair.toString(); console.log("Private key", newSubPrivateKey); console.log("Public key", newSubPublicKey); -const createSubAccountResult = await account.createAccount( - newSubAccountId, // sub.example-account.testnet +const createSubAccountResult = await account.createSubAccount( + newSubAccountIdPrefix, newSubPublicKey, // ed25519:2ASWc... - utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR + BigInt(utils.format.parseNearAmount("0.1")) // Initial balance for new account in yoctoNEAR ); console.log(createSubAccountResult); diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index 6d35437..af0d4d3 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -1,22 +1,20 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const beneficiaryAccountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", beneficiaryAccountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const accountCreator = await nearConnection.account(beneficiaryAccountId); +// Create an account object +const account = new Account(beneficiaryAccountId, provider, signer); // example-account.testnet // First create a new account to be deleted // Generate a new account ID based on the current timestamp @@ -24,24 +22,21 @@ const accountToDeleteId = Date.now() + ".testnet"; const newKeyPair = KeyPair.fromRandom("ed25519"); const newPublicKey = newKeyPair.getPublicKey().toString(); -await accountCreator.functionCall({ - contractId: "testnet", - methodName: "create_account", - args: { - new_account_id: accountToDeleteId, - new_public_key: newPublicKey, - }, - gas: "300000000000000", - attachedDeposit: utils.format.parseNearAmount("0.1"), -}); +await account.createTopLevelAccount( + accountToDeleteId, + newPublicKey, + BigInt(utils.format.parseNearAmount("0.1")) +); + +// Create a signer from a key pair that was added to new account +const signerToDelete = new KeyPairSigner(newKeyPair); -// Create an account object for the new account -// and add the new key pair to the keystore -const accountToDelete = await nearConnection.account(accountToDeleteId); -await myKeyStore.setKey("testnet", accountToDeleteId, newKeyPair); +// Create an account object for the new account with corresponding signer +const accountToDelete = new Account(accountToDeleteId, provider, signerToDelete); // Delete the account with account ID of the account object // specifying the beneficiary account ID -const deleteAccountResult = - await accountToDelete.deleteAccount(beneficiaryAccountId); // example-beneficiary.testnet +const deleteAccountResult = await accountToDelete.deleteAccount( + beneficiaryAccountId +); // example-beneficiary.testnet console.log(deleteAccountResult); diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index e727e01..3f14653 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -1,49 +1,47 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Get all access keys for the account -const accessKeys = await account.getAccessKeys(); +const accessKeys = await account.getAccessKeyList(); console.log(accessKeys); // Add full access key // Generate a new key pair const newFullKeyPair = KeyPair.fromRandom("ed25519"); -const newFullPublicKey = newFullKeyPair.getPublicKey().toString(); -console.log(newFullPublicKey); +const newFullPublicKey = newFullKeyPair.getPublicKey(); +console.log(newFullPublicKey.toString()); -const addFullKeyResult = await account.addKey( - newFullPublicKey, // The new public key ed25519:2ASWc... +const addFullKeyResult = await account.addFullAccessKey( + newFullPublicKey // The new public key ed25519:2ASWc... ); console.log(addFullKeyResult); // Add function call access key // Generate a new key pair const newFunctionKeyPair = KeyPair.fromRandom("ed25519"); -const newFunctionPublicKey = newFunctionKeyPair.getPublicKey().toString(); -console.log(newFunctionPublicKey); +const newFunctionPublicKey = newFunctionKeyPair.getPublicKey(); +console.log(newFunctionPublicKey.toString()); -const addFunctionKeyResult = await account.addKey( +const addFunctionKeyResult = await account.addFunctionAccessKey( newFunctionPublicKey, // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) - utils.format.parseNearAmount("0.25"), // Gas allowance key can use to call methods (optional) + BigInt(utils.format.parseNearAmount("0.25")) // Gas allowance key can use to call methods (optional) ); console.log(addFunctionKeyResult); diff --git a/javascript/examples/keystore-options/credentials-directory.js b/javascript/examples/keystore-options/credentials-directory.js index 029864f..9297063 100644 --- a/javascript/examples/keystore-options/credentials-directory.js +++ b/javascript/examples/keystore-options/credentials-directory.js @@ -1,4 +1,11 @@ -import { connect, keyStores, utils } from "near-api-js"; +import { + providers, + keyStores, + Account, + KeyPairSigner, + utils, +} from "near-api-js"; + import dotenv from "dotenv"; import { homedir } from "os"; import path from "path"; @@ -12,20 +19,20 @@ const credentialsDirectory = ".near-credentials"; const credentialsPath = path.join(homedir(), credentialsDirectory); const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); -// Create a connection to the NEAR testnet -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); + +const keyPair = await myKeyStore.getKey("testnet", accountId); + +const signer = new KeyPairSigner(keyPair); -// Create an account object -const account = await nearConnection.account(accountId); // example-account.testnet +const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + BigInt(utils.format.parseNearAmount("1")) ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index 42f965c..a4a0e2d 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -1,4 +1,4 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { providers, KeyPairSigner, utils, Account } from "near-api-js"; import dotenv from "dotenv"; import fs from "fs"; @@ -9,26 +9,19 @@ const accountId = process.env.ACCOUNT_ID; // Fetch the private key from a credentials file const credentialsPath = "../credentials-file.json"; // Path relative to the working directory const credentials = JSON.parse(fs.readFileSync(credentialsPath)); -// Create a key pair from the private key -const keyPair = KeyPair.fromString(credentials.private_key); -// Create a keystore and add the key pair -const myKeyStore = new keyStores.InMemoryKeyStore(); -myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from the private key +const signer = KeyPairSigner.fromSecretKey(credentials.private_key); -// Create a connection to the NEAR testnet -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -// Create an account object -const account = await nearConnection.account(accountId); // example-account.testnet +const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + BigInt(utils.format.parseNearAmount("1")), ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/private-key-string.js b/javascript/examples/keystore-options/private-key-string.js index ecfa921..e86205e 100644 --- a/javascript/examples/keystore-options/private-key-string.js +++ b/javascript/examples/keystore-options/private-key-string.js @@ -1,4 +1,4 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { utils, KeyPairSigner, Account, providers } from "near-api-js"; import dotenv from "dotenv"; // Load environment variables @@ -6,25 +6,20 @@ dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -// Create a keystore and add the key pair via a private key string -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); // ed25519:5Fg2... -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -// Create a connection to NEAR testnet -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); // Create an account object -const account = await nearConnection.account(accountId); // example-account.testnet +const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer by transferring NEAR -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + BigInt(utils.format.parseNearAmount("1")), ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/seed-phrase.js b/javascript/examples/keystore-options/seed-phrase.js index cdd78ec..a68736d 100644 --- a/javascript/examples/keystore-options/seed-phrase.js +++ b/javascript/examples/keystore-options/seed-phrase.js @@ -1,4 +1,4 @@ -import { connect, keyStores, KeyPair, utils } from "near-api-js"; +import { utils, providers, Account, KeyPairSigner } from "near-api-js"; import { parseSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; @@ -9,24 +9,20 @@ const accountId = process.env.ACCOUNT_ID; // Create a keystore and add the key pair via a seed phrase const { secretKey } = parseSeedPhrase(seedPhrase); // "royal success river ..." -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(secretKey); // ed25519::5Fg2... -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(secretKey); // ed25519:5Fg2... -// Create a connection to NEAR testnet -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); // Create an account object -const account = await nearConnection.account(accountId); // example-account.testnet +const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer by transferring NEAR const sendTokensResult = await account.sendMoney( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + utils.format.parseNearAmount("1") ); console.log(sendTokensResult); diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 5d7874e..0200993 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -1,60 +1,45 @@ -import { KeyPair, transactions, providers, utils } from "near-api-js"; -import sha256 from "js-sha256"; +import { KeyPairSigner, transactions, providers, utils } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const keyPair = KeyPair.fromString(privateKey); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +// Create a connection to testnet RPC const provider = new providers.JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); +const signerPublicKey = await signer.getPublicKey(); + // Get the nonce of the key -const accessKey = await provider.query( - `access_key/${accountId}/${keyPair.getPublicKey().toString()}`, - "", -); +const accessKey = await provider.viewAccessKey(accountId, signerPublicKey); + const nonce = ++accessKey.nonce; // Get a recent block hash const recentBlockHash = utils.serialize.base_decode(accessKey.block_hash); // Construct actions -const actions = [transactions.transfer(utils.format.parseNearAmount("1"))]; +const actions = [ + transactions.transfer(BigInt(utils.format.parseNearAmount("1"))), +]; // Construct transaction const transaction = transactions.createTransaction( accountId, - keyPair.getPublicKey(), + signerPublicKey, "receiver-account.testnet", nonce, actions, - recentBlockHash, -); - -// Serialize transaction -const serializedTx = utils.serialize.serialize( - transactions.SCHEMA.Transaction, - transaction, + recentBlockHash ); -// Get serialized transaction hash -const serializedTxHash = new Uint8Array(sha256.sha256.array(serializedTx)); - -// Get signature -const signature = keyPair.sign(serializedTxHash); - -// Construct signed transaction -const signedTransaction = new transactions.SignedTransaction({ - transaction, - signature: new transactions.Signature({ - keyType: transaction.publicKey.keyType, - data: signature.signature, - }), -}); +const [txHash, signedTransaction] = await signer.signTransaction(transaction); +console.log(Buffer.from(txHash).toString("hex")); // Send transaction const sendTransactionResult = await provider.sendTransaction(signedTransaction); diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index af2189e..5ed91f5 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -1,43 +1,33 @@ -import { connect, keyStores, KeyPair, utils, providers } from "near-api-js"; +import { Account, KeyPairSigner, utils, providers } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Set up a new FailoverRpcProvider with two JSON RPC providers const jsonProviders = [ + new providers.JsonRpcProvider({ url: "https://incorrect-rpc-url.com" }), // Incorrect RPC URL new providers.JsonRpcProvider( { url: "https://test.rpc.fastnear.com" }, // RPC URL { retries: 3, // Number of retries before giving up on a request backoff: 2, // Backoff factor for the retry delay wait: 500, // Wait time between retries in milliseconds - }, // Retry options + } // Retry options ), - new providers.JsonRpcProvider({ - url: "https://test.rpc.fastnear.com", - }), // Second RPC URL ]; const provider = new providers.FailoverRpcProvider(jsonProviders); // Create a FailoverRpcProvider -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://incorrect-rpc-url.com", // Incorrect RPC URL - provider: provider, -}; -const nearConnection = await connect(connectionConfig); - -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer with transferring 1 NEAR -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + BigInt(utils.format.parseNearAmount("1")) ); console.log(sendTokensResult); diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index bf7bc64..c148ac8 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -1,31 +1,27 @@ import * as nearAPI from "near-api-js"; import dotenv from "dotenv"; -const { connect, keyStores, KeyPair, utils } = nearAPI; +const { Account, providers, KeyPairSigner, utils } = nearAPI; // Load environment variables dotenv.config({ path: "../.env" }); // Path relative to the working directory const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -// Create a keystore and add the key pair via the private key string -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -// Create a connection to the NEAR testnet -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Send NEAR tokens to another account -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", // Receiver account - utils.format.parseNearAmount("1"), // Amount being sent in yoctoNEAR + BigInt(utils.format.parseNearAmount("1")) // Amount being sent in yoctoNEAR ); console.log(sendTokensResult); diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index 160ff57..acaf0e8 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -1,49 +1,38 @@ -import { connect, keyStores, KeyPair, transactions } from "near-api-js"; +import { Account, providers, KeyPairSigner, transactions } from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; -const myKeyStore = new keyStores.InMemoryKeyStore(); -const keyPair = KeyPair.fromString(privateKey); -await myKeyStore.setKey("testnet", accountId, keyPair); +// Create a signer from a private key string +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... -const connectionConfig = { - networkId: "testnet", - keyStore: myKeyStore, - nodeUrl: "https://test.rpc.fastnear.com", -}; -const nearConnection = await connect(connectionConfig); +// Create a connection to testnet RPC +const provider = new providers.JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); -const account = await nearConnection.account(accountId); +// Create an account object +const account = new Account(accountId, provider, signer); // example-account.testnet // Send independent transactions simultaneously to different receivers // Prepare the transactions -const args = Buffer.from(JSON.stringify({ text: "Hello, world!" })); -const tx1 = account.signAndSendTransaction({ - receiverId: "guestbook.near-examples.testnet", - actions: [ - transactions.functionCall( - "add_message", // Method name - args, // Arguments - 100000000000000, // Gas - 0, // Deposit - ), - ], -}); +const tx1 = account.callFunction( + "guestbook.near-examples.testnet", + "add_message", + { text: "Hello, world!" }, + BigInt(0), + BigInt(100_000_000_000_000) +); -const tx2 = account.signAndSendTransaction({ - receiverId: "counter.near-examples.testnet", - actions: [ - transactions.functionCall( - "increment", // Method name - [], // Arguments - 100000000000000, // Gas - 0, // Deposit - ), - ], -}); +const tx2 = account.callFunction( + "counter.near-examples.testnet", + "increment", + {}, + BigInt(0), + BigInt(100_000_000_000_000) +); // Send the transactions simultaneously const transactionsResults = await Promise.all([tx1, tx2]); diff --git a/javascript/examples/verify-signature/authentication.js b/javascript/examples/verify-signature/authentication.js index b45ce5a..59bd57b 100644 --- a/javascript/examples/verify-signature/authentication.js +++ b/javascript/examples/verify-signature/authentication.js @@ -1,5 +1,5 @@ import * as borsh from 'borsh'; -import * as naj from 'near-api-js'; +import { utils } from 'near-api-js'; import js_sha256 from 'js-sha256'; class Payload { @@ -33,7 +33,7 @@ function verifySignature({ publicKey, signature, message, recipient, nonce }) { let real_signature = Buffer.from(signature, 'base64') // Use the public Key to verify that the private-counterpart signed the message - const myPK = naj.utils.PublicKey.from(publicKey) + const myPK = utils.PublicKey.from(publicKey) return myPK.verify(to_sign, real_signature) } diff --git a/javascript/package.json b/javascript/package.json index 535b14e..d449cb2 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -25,5 +25,10 @@ "simultaneous-transactions": "node examples/simultaneous-transactions.js", "utils": "node examples/utils.js", "verify-signature": "node examples/verify-signature/verify-signature.js" + }, + "pnpm": { + "overrides": { + "near-api-js": "link:../../near-api-js/packages/near-api-js" + } } } diff --git a/javascript/pnpm-lock.yaml b/javascript/pnpm-lock.yaml index 5d53a49..ab36e06 100644 --- a/javascript/pnpm-lock.yaml +++ b/javascript/pnpm-lock.yaml @@ -4,13 +4,16 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + near-api-js: link:../../near-api-js/packages/near-api-js + importers: .: dependencies: borsh: - specifier: 1.0.0 - version: 1.0.0 + specifier: 2.0.0 + version: 2.0.0 dotenv: specifier: ^16.4.7 version: 16.4.7 @@ -18,69 +21,17 @@ importers: specifier: ^0.11.0 version: 0.11.0 near-api-js: - specifier: ^4.0.4 - version: 4.0.4 + specifier: link:../../near-api-js/packages/near-api-js + version: link:../../near-api-js/packages/near-api-js near-seed-phrase: specifier: ^0.2.1 version: 0.2.1 packages: - '@near-js/accounts@1.2.2': - resolution: {integrity: sha512-8XInUVl8WwQyitRkG1HffZKhDmAXUwOaxurgkTYocDUUUp+ZB8NPxidg2uvj6f2wqnC8KAkjpm73wPoyRm6+yQ==} - - '@near-js/crypto@1.3.0': - resolution: {integrity: sha512-BIKO6v+rbYCzzrjsSV4KgClVgRiPluIXQ89B4ozIG8RjjBe/7IPFYF9tIxsXUyLzPFhISzeNQkL09ksHHmnymg==} - - '@near-js/keystores-browser@0.1.0': - resolution: {integrity: sha512-v/4uFHKnbEXY4UcOAVCUSb3GKsVdrwv4uXBSPluvE16H9oxjB1+gfcz5qejwKp2cifYNCO0KfAWLnZas66Ohcg==} - - '@near-js/keystores-node@0.0.13': - resolution: {integrity: sha512-cnk2mwIRr7bCPgqz7KHU1Bqxm0u9J+FIubZ0AllFpMVMv8TJVVbs7FcsVIk282oeM7xxikjVJjs35DG6//Fehw==} - - '@near-js/keystores@0.1.0': - resolution: {integrity: sha512-89EwYFDvPg7GnJAKmBDASKUSTXny0ZqgqDnSdhp7oJ78bXNlCs9xx0WnkK34TxFBnrL4c9szLjTkfGRcFT07NQ==} - - '@near-js/providers@0.2.3': - resolution: {integrity: sha512-JBSze9fdoRXkOsFeLiooPWGm3vemY2dgHT0u0HoJCjpQtt41v7tr+6sWpxGWCaDwrzIwhm7og4qkGv4K9IxFVw==} - - '@near-js/signers@0.1.5': - resolution: {integrity: sha512-UldCktmR6HF6N2gPbgiUS8QPYCcDwjyzpdi3ukKezfY2NGA++F068ZwP50S+aQrtcwEBpECTo/Ps6pZq7cSVeQ==} - - '@near-js/transactions@1.2.3': - resolution: {integrity: sha512-wwkUupWrmKfdZmv6TmnTrskysX37F2SVHcns6BVwPjp6nFD29NAhul71I6u++8496Lq2FrgM1Kb8pEIpG9TV9w==} - - '@near-js/types@0.2.1': - resolution: {integrity: sha512-YygQEGMdFe6d2e/6dtNZer9paH396XeAdIKEhY/RPXDUnjDdfiDQ5DK4mM130sEeID2bAH9X1LQ+7vXGRjvyWw==} - - '@near-js/utils@0.3.0': - resolution: {integrity: sha512-ExeWqP0b4subLcQuLDIixAZs6tiCWifDBz2OwU9ycntyjZslUUh4EKBaSS3mAEqhJ/t1B9WX80BntE/5PQ+JTg==} - - '@near-js/wallet-account@1.2.3': - resolution: {integrity: sha512-yuYKKA8D06ztmbTvbajD8HBjP50x2NbMRPInsSSgNjBnvFA9f2J82SarzDLg+nTsayhMJdFGfArnKgIlO+bUaw==} - - '@noble/curves@1.2.0': - resolution: {integrity: sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==} - - '@noble/hashes@1.3.2': - resolution: {integrity: sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==} - engines: {node: '>= 16'} - - '@noble/hashes@1.3.3': - resolution: {integrity: sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA==} - engines: {node: '>= 16'} - - '@types/json-schema@7.0.15': - resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - '@types/node@11.11.6': resolution: {integrity: sha512-Exw4yUWMBXM3X+8oqzJNRqZSwUAaS4+7NdvHqQuFi/d+synz++xmX3QIf+BFqneW8N31R8Ky+sikfZUXq07ggQ==} - base-x@2.0.6: - resolution: {integrity: sha512-UAmjxz9KbK+YIi66xej+pZVo/vxUOh49ubEvZW5egCbxhur05pBb+hwuireQwKO4nDpsNm64/jEei17LEpsr5g==} - engines: {node: '>=4.5.0'} - deprecated: use 3.0.0 instead, safe-buffer has been merged and release for compatability - base-x@3.0.10: resolution: {integrity: sha512-7d0s06rR9rYaIWHkpfLIFICM/tkSVdoPC9qYAQRpxn9DdKNWNsKC0uk++akckyLq16Tx2WIinnZ6WRriAt6njQ==} @@ -90,17 +41,8 @@ packages: bip39@3.0.2: resolution: {integrity: sha512-J4E1r2N0tUylTKt07ibXvhpT2c5pyAFgvuA5q1H9uDy6dEGpjV8jmymh3MTYJDLCNbIVClSB9FbND49I6N24MQ==} - bn.js@4.12.1: - resolution: {integrity: sha512-k8TVBiPkPJT9uHLdOKfFpqcfprwBFOAAXXozRubr7R7PfIuKvQlzcI4M0pALeqXN09vdaMbUdUj+pass+uULAg==} - - borsh@1.0.0: - resolution: {integrity: sha512-fSVWzzemnyfF89EPwlUNsrS5swF5CrtiN4e+h0/lLf4dz2he4L3ndM20PS9wj7ICSkXJe/TQUHdaPTq15b1mNQ==} - - brorand@1.1.0: - resolution: {integrity: sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==} - - bs58@4.0.0: - resolution: {integrity: sha512-/jcGuUuSebyxwLLfKrbKnCJttxRf9PM51EnHTwmFKBxl4z1SGkoAhrfd6uZKE0dcjQTfm6XzTP8DPr1tzE4KIw==} + borsh@2.0.0: + resolution: {integrity: sha512-kc9+BgR3zz9+cjbwM8ODoUB4fs3X3I5A/HtX7LZKxCLaMrEeDFoBpnhZY//DTS1VZBSs6S5v46RZRbZjRFspEg==} bs58@4.0.1: resolution: {integrity: sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==} @@ -115,108 +57,29 @@ packages: create-hmac@1.1.7: resolution: {integrity: sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==} - depd@1.1.2: - resolution: {integrity: sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==} - engines: {node: '>= 0.6'} - - depd@2.0.0: - resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} - engines: {node: '>= 0.8'} - dotenv@16.4.7: resolution: {integrity: sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==} engines: {node: '>=12'} - elliptic@6.6.1: - resolution: {integrity: sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==} - - generate-function@2.3.1: - resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} - - generate-object-property@1.2.0: - resolution: {integrity: sha512-TuOwZWgJ2VAMEGJvAyPWvpqxSANF0LDpmyHauMjFYzaACvn+QTT/AZomvPCzVBV7yDN3OmwHQ5OvHaeLKre3JQ==} - hash-base@3.1.0: resolution: {integrity: sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==} engines: {node: '>=4'} - hash.js@1.1.7: - resolution: {integrity: sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==} - - hmac-drbg@1.0.1: - resolution: {integrity: sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==} - - http-errors@1.7.2: - resolution: {integrity: sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==} - engines: {node: '>= 0.6'} - - inherits@2.0.3: - resolution: {integrity: sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==} - inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - is-my-ip-valid@1.0.1: - resolution: {integrity: sha512-jxc8cBcOWbNK2i2aTkCZP6i7wkHF1bqKFrwEHuN5Jtg5BSaZHUZQ/JTOJwoV41YvHnOaRyWWh72T/KvfNz9DJg==} - - is-my-json-valid@2.20.6: - resolution: {integrity: sha512-1JQwulVNjx8UqkPE/bqDaxtH4PXCe/2VRh/y3p99heOV87HG4Id5/VfDswd+YiAfHcRTfDlWgISycnHuhZq1aw==} - - is-property@1.0.2: - resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} - js-sha256@0.11.0: resolution: {integrity: sha512-6xNlKayMZvds9h1Y1VWc0fQHQ82BxTXizWPEtEeGvmOUYpBRy4gbWroHLpzowe6xiQhHpelCQiE7HEdznyBL9Q==} - jsonpointer@5.0.1: - resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} - engines: {node: '>=0.10.0'} - - lru_map@0.4.1: - resolution: {integrity: sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg==} - md5.js@1.3.5: resolution: {integrity: sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==} - minimalistic-assert@1.0.1: - resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==} - - minimalistic-crypto-utils@1.0.1: - resolution: {integrity: sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg==} - - mustache@4.0.0: - resolution: {integrity: sha512-FJgjyX/IVkbXBXYUwH+OYwQKqWpFPLaLVESd70yHjSDunwzV2hZOoTBvPf4KLoxesUzzyfTH6F784Uqd7Wm5yA==} - engines: {npm: '>=1.4.0'} - hasBin: true - - near-abi@0.1.1: - resolution: {integrity: sha512-RVDI8O+KVxRpC3KycJ1bpfVj9Zv+xvq9PlW1yIFl46GhrnLw83/72HqHGjGDjQ8DtltkcpSjY9X3YIGZ+1QyzQ==} - - near-api-js@4.0.4: - resolution: {integrity: sha512-IG+6NAMtn854palu/cIbVgey0OsIzllcajc3fbEbh7cb2pyPNMsfsBIO5WqsV+rY+7Tqr6lqYQ8f+4BHGUttyg==} - near-hd-key@1.2.1: resolution: {integrity: sha512-SIrthcL5Wc0sps+2e1xGj3zceEa68TgNZDLuCx0daxmfTP7sFTB3/mtE2pYhlFsCxWoMn+JfID5E1NlzvvbRJg==} near-seed-phrase@0.2.1: resolution: {integrity: sha512-feMuums+kVL3LSuPcP4ld07xHCb2mu6z48SGfP3W+8tl1Qm5xIcjiQzY2IDPBvFgajRDxWSb8GzsRHoInazByw==} - node-addon-api@5.1.0: - resolution: {integrity: sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==} - - node-fetch@2.6.7: - resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==} - engines: {node: 4.x || >=6.0.0} - peerDependencies: - encoding: ^0.1.0 - peerDependenciesMeta: - encoding: - optional: true - - node-gyp-build@4.8.4: - resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} - hasBin: true - pbkdf2@3.1.2: resolution: {integrity: sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==} engines: {node: '>=0.12'} @@ -234,155 +97,23 @@ packages: safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - secp256k1@5.0.0: - resolution: {integrity: sha512-TKWX8xvoGHrxVdqbYeZM9w+izTF4b9z3NhSaDkdn81btvuh+ivbIMGT/zQvDtTFWhRlThpoz6LEYTr7n8A5GcA==} - engines: {node: '>=14.0.0'} - - setprototypeof@1.1.1: - resolution: {integrity: sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==} - sha.js@2.4.11: resolution: {integrity: sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==} hasBin: true - statuses@1.5.0: - resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} - engines: {node: '>= 0.6'} - string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} - toidentifier@1.0.0: - resolution: {integrity: sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==} - engines: {node: '>=0.6'} - - tr46@0.0.3: - resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} - tweetnacl@1.0.3: resolution: {integrity: sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==} util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - webidl-conversions@3.0.1: - resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} - - whatwg-url@5.0.0: - resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - - xtend@4.0.2: - resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} - engines: {node: '>=0.4'} - snapshots: - '@near-js/accounts@1.2.2': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/providers': 0.2.3 - '@near-js/signers': 0.1.5 - '@near-js/transactions': 1.2.3 - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - 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 - transitivePeerDependencies: - - encoding - - '@near-js/crypto@1.3.0': - dependencies: - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - '@noble/curves': 1.2.0 - borsh: 1.0.0 - randombytes: 2.1.0 - secp256k1: 5.0.0 - - '@near-js/keystores-browser@0.1.0': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/keystores': 0.1.0 - - '@near-js/keystores-node@0.0.13': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/keystores': 0.1.0 - - '@near-js/keystores@0.1.0': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/types': 0.2.1 - - '@near-js/providers@0.2.3': - dependencies: - '@near-js/transactions': 1.2.3 - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - borsh: 1.0.0 - http-errors: 1.7.2 - optionalDependencies: - node-fetch: 2.6.7 - transitivePeerDependencies: - - encoding - - '@near-js/signers@0.1.5': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/keystores': 0.1.0 - '@noble/hashes': 1.3.3 - - '@near-js/transactions@1.2.3': - dependencies: - '@near-js/crypto': 1.3.0 - '@near-js/signers': 0.1.5 - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - '@noble/hashes': 1.3.3 - borsh: 1.0.0 - - '@near-js/types@0.2.1': {} - - '@near-js/utils@0.3.0': - dependencies: - '@near-js/types': 0.2.1 - bs58: 4.0.0 - depd: 2.0.0 - mustache: 4.0.0 - - '@near-js/wallet-account@1.2.3': - dependencies: - '@near-js/accounts': 1.2.2 - '@near-js/crypto': 1.3.0 - '@near-js/keystores': 0.1.0 - '@near-js/providers': 0.2.3 - '@near-js/signers': 0.1.5 - '@near-js/transactions': 1.2.3 - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - borsh: 1.0.0 - transitivePeerDependencies: - - encoding - - '@noble/curves@1.2.0': - dependencies: - '@noble/hashes': 1.3.2 - - '@noble/hashes@1.3.2': {} - - '@noble/hashes@1.3.3': {} - - '@types/json-schema@7.0.15': {} - '@types/node@11.11.6': {} - base-x@2.0.6: - dependencies: - safe-buffer: 5.2.1 - base-x@3.0.10: dependencies: safe-buffer: 5.2.1 @@ -399,15 +130,7 @@ snapshots: pbkdf2: 3.1.2 randombytes: 2.1.0 - bn.js@4.12.1: {} - - borsh@1.0.0: {} - - brorand@1.1.0: {} - - bs58@4.0.0: - dependencies: - base-x: 2.0.6 + borsh@2.0.0: {} bs58@4.0.1: dependencies: @@ -435,115 +158,24 @@ snapshots: safe-buffer: 5.2.1 sha.js: 2.4.11 - depd@1.1.2: {} - - depd@2.0.0: {} - dotenv@16.4.7: {} - elliptic@6.6.1: - dependencies: - bn.js: 4.12.1 - brorand: 1.1.0 - hash.js: 1.1.7 - hmac-drbg: 1.0.1 - inherits: 2.0.4 - minimalistic-assert: 1.0.1 - minimalistic-crypto-utils: 1.0.1 - - generate-function@2.3.1: - dependencies: - is-property: 1.0.2 - - generate-object-property@1.2.0: - dependencies: - is-property: 1.0.2 - hash-base@3.1.0: dependencies: inherits: 2.0.4 readable-stream: 3.6.2 safe-buffer: 5.2.1 - hash.js@1.1.7: - dependencies: - inherits: 2.0.4 - minimalistic-assert: 1.0.1 - - hmac-drbg@1.0.1: - dependencies: - hash.js: 1.1.7 - minimalistic-assert: 1.0.1 - minimalistic-crypto-utils: 1.0.1 - - http-errors@1.7.2: - dependencies: - depd: 1.1.2 - inherits: 2.0.3 - setprototypeof: 1.1.1 - statuses: 1.5.0 - toidentifier: 1.0.0 - - inherits@2.0.3: {} - inherits@2.0.4: {} - is-my-ip-valid@1.0.1: {} - - is-my-json-valid@2.20.6: - dependencies: - generate-function: 2.3.1 - generate-object-property: 1.2.0 - is-my-ip-valid: 1.0.1 - jsonpointer: 5.0.1 - xtend: 4.0.2 - - is-property@1.0.2: {} - js-sha256@0.11.0: {} - jsonpointer@5.0.1: {} - - lru_map@0.4.1: {} - md5.js@1.3.5: dependencies: hash-base: 3.1.0 inherits: 2.0.4 safe-buffer: 5.2.1 - minimalistic-assert@1.0.1: {} - - minimalistic-crypto-utils@1.0.1: {} - - mustache@4.0.0: {} - - near-abi@0.1.1: - dependencies: - '@types/json-schema': 7.0.15 - - near-api-js@4.0.4: - dependencies: - '@near-js/accounts': 1.2.2 - '@near-js/crypto': 1.3.0 - '@near-js/keystores': 0.1.0 - '@near-js/keystores-browser': 0.1.0 - '@near-js/keystores-node': 0.0.13 - '@near-js/providers': 0.2.3 - '@near-js/signers': 0.1.5 - '@near-js/transactions': 1.2.3 - '@near-js/types': 0.2.1 - '@near-js/utils': 0.3.0 - '@near-js/wallet-account': 1.2.3 - '@noble/curves': 1.2.0 - borsh: 1.0.0 - depd: 2.0.0 - http-errors: 1.7.2 - near-abi: 0.1.1 - node-fetch: 2.6.7 - transitivePeerDependencies: - - encoding - near-hd-key@1.2.1: dependencies: bip39: 3.0.2 @@ -557,14 +189,6 @@ snapshots: near-hd-key: 1.2.1 tweetnacl: 1.0.3 - node-addon-api@5.1.0: {} - - node-fetch@2.6.7: - dependencies: - whatwg-url: 5.0.0 - - node-gyp-build@4.8.4: {} - pbkdf2@3.1.2: dependencies: create-hash: 1.2.0 @@ -590,38 +214,15 @@ snapshots: safe-buffer@5.2.1: {} - secp256k1@5.0.0: - dependencies: - elliptic: 6.6.1 - node-addon-api: 5.1.0 - node-gyp-build: 4.8.4 - - setprototypeof@1.1.1: {} - sha.js@2.4.11: dependencies: inherits: 2.0.4 safe-buffer: 5.2.1 - statuses@1.5.0: {} - string_decoder@1.3.0: dependencies: safe-buffer: 5.2.1 - toidentifier@1.0.0: {} - - tr46@0.0.3: {} - tweetnacl@1.0.3: {} util-deprecate@1.0.2: {} - - webidl-conversions@3.0.1: {} - - whatwg-url@5.0.0: - dependencies: - tr46: 0.0.3 - webidl-conversions: 3.0.1 - - xtend@4.0.2: {} From 56b195e62694df713bd8b18566bb79d6b876b794 Mon Sep 17 00:00:00 2001 From: denbite Date: Sun, 13 Apr 2025 20:38:14 +0200 Subject: [PATCH 02/12] fix: use new `transfer` instead of deprecated `sendMoney` --- javascript/examples/keystore-options/seed-phrase.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/examples/keystore-options/seed-phrase.js b/javascript/examples/keystore-options/seed-phrase.js index a68736d..0dc9053 100644 --- a/javascript/examples/keystore-options/seed-phrase.js +++ b/javascript/examples/keystore-options/seed-phrase.js @@ -21,7 +21,7 @@ const provider = new providers.JsonRpcProvider({ const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer by transferring NEAR -const sendTokensResult = await account.sendMoney( +const sendTokensResult = await account.transfer( "receiver-account.testnet", utils.format.parseNearAmount("1") ); From ba6ce7b46c07789dde47eea0935d03d68ca768a8 Mon Sep 17 00:00:00 2001 From: denbite Date: Sun, 13 Apr 2025 20:48:55 +0200 Subject: [PATCH 03/12] fix: use string representation of numbers wherever is possible --- javascript/examples/batch-actions.js | 6 +++--- javascript/examples/contract-interaction.js | 4 ++-- javascript/examples/create-account-from-seed.js | 2 +- javascript/examples/create-account.js | 4 ++-- javascript/examples/delete-account.js | 2 +- javascript/examples/keys.js | 2 +- .../examples/keystore-options/credentials-directory.js | 2 +- javascript/examples/keystore-options/credentials-file.js | 2 +- .../examples/keystore-options/private-key-string.js | 2 +- javascript/examples/manual-sign.js | 4 +--- javascript/examples/rpc-failover.js | 2 +- javascript/examples/send-tokens.js | 2 +- javascript/examples/simultaneous-transactions.js | 8 ++++---- 13 files changed, 20 insertions(+), 22 deletions(-) diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index a6e0088..48c609e 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -21,10 +21,10 @@ const account = new Account(accountId, provider, signer); // example-account.tes const callAction = transactions.functionCall( "increment", // Method name {}, // Arguments - BigInt(30_000_000_000_000), // Gas - BigInt(0) // Deposit + "30000000000000", // Gas + 0 // Deposit ); -const transferAction = transactions.transfer(BigInt(utils.format.parseNearAmount("1"))); +const transferAction = transactions.transfer(utils.format.parseNearAmount("1")); // Send the batch of actions const batchActionsResult = await account.signAndSendTransaction({ diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index d007613..3dc773d 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -38,8 +38,8 @@ const contractCallResult = await account.callFunction( { text: "Hello, world!", }, - BigInt(0), - BigInt(100_000_000_000_000) + 0, + "100000000000000" ); console.log(contractCallResult); diff --git a/javascript/examples/create-account-from-seed.js b/javascript/examples/create-account-from-seed.js index c970d28..9957097 100644 --- a/javascript/examples/create-account-from-seed.js +++ b/javascript/examples/create-account-from-seed.js @@ -29,6 +29,6 @@ console.log("Public key", publicKey); const createAccountResult = await account.createTopLevelAccount( newAccountId, publicKey, - BigInt(utils.format.parseNearAmount("0.1")) + utils.format.parseNearAmount("0.1") ); console.log(createAccountResult); diff --git a/javascript/examples/create-account.js b/javascript/examples/create-account.js index 8f78833..cd0092a 100644 --- a/javascript/examples/create-account.js +++ b/javascript/examples/create-account.js @@ -29,7 +29,7 @@ console.log("Public key", newPublicKey); const createAccountResult = await account.createTopLevelAccount( newAccountId, newPublicKey, // ed25519:2ASWc... - BigInt(utils.format.parseNearAmount("0.1")) // Initial balance for new account in yoctoNEAR + utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR ); console.log(createAccountResult); @@ -46,6 +46,6 @@ console.log("Public key", newSubPublicKey); const createSubAccountResult = await account.createSubAccount( newSubAccountIdPrefix, newSubPublicKey, // ed25519:2ASWc... - BigInt(utils.format.parseNearAmount("0.1")) // Initial balance for new account in yoctoNEAR + utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR ); console.log(createSubAccountResult); diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index af0d4d3..280e60c 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -25,7 +25,7 @@ const newPublicKey = newKeyPair.getPublicKey().toString(); await account.createTopLevelAccount( accountToDeleteId, newPublicKey, - BigInt(utils.format.parseNearAmount("0.1")) + utils.format.parseNearAmount("0.1") ); // Create a signer from a key pair that was added to new account diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index 3f14653..99706d8 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -41,7 +41,7 @@ const addFunctionKeyResult = await account.addFunctionAccessKey( newFunctionPublicKey, // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) - BigInt(utils.format.parseNearAmount("0.25")) // Gas allowance key can use to call methods (optional) + utils.format.parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) ); console.log(addFunctionKeyResult); diff --git a/javascript/examples/keystore-options/credentials-directory.js b/javascript/examples/keystore-options/credentials-directory.js index 9297063..9be395a 100644 --- a/javascript/examples/keystore-options/credentials-directory.js +++ b/javascript/examples/keystore-options/credentials-directory.js @@ -33,6 +33,6 @@ const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - BigInt(utils.format.parseNearAmount("1")) + utils.format.parseNearAmount("1") ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index a4a0e2d..d772116 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -22,6 +22,6 @@ const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - BigInt(utils.format.parseNearAmount("1")), + utils.format.parseNearAmount("1"), ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/private-key-string.js b/javascript/examples/keystore-options/private-key-string.js index e86205e..2aafada 100644 --- a/javascript/examples/keystore-options/private-key-string.js +++ b/javascript/examples/keystore-options/private-key-string.js @@ -20,6 +20,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - BigInt(utils.format.parseNearAmount("1")), + utils.format.parseNearAmount("1") ); console.log(sendTokensResult); diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 0200993..9f2057b 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -24,9 +24,7 @@ const nonce = ++accessKey.nonce; const recentBlockHash = utils.serialize.base_decode(accessKey.block_hash); // Construct actions -const actions = [ - transactions.transfer(BigInt(utils.format.parseNearAmount("1"))), -]; +const actions = [transactions.transfer(utils.format.parseNearAmount("1"))]; // Construct transaction const transaction = transactions.createTransaction( diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index 5ed91f5..20b313e 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -28,6 +28,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Test the signer with transferring 1 NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - BigInt(utils.format.parseNearAmount("1")) + utils.format.parseNearAmount("1") ); console.log(sendTokensResult); diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index c148ac8..f2e384c 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -22,6 +22,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Send NEAR tokens to another account const sendTokensResult = await account.transfer( "receiver-account.testnet", // Receiver account - BigInt(utils.format.parseNearAmount("1")) // Amount being sent in yoctoNEAR + utils.format.parseNearAmount("1") // Amount being sent in yoctoNEAR ); console.log(sendTokensResult); diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index acaf0e8..ace01f2 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -22,16 +22,16 @@ const tx1 = account.callFunction( "guestbook.near-examples.testnet", "add_message", { text: "Hello, world!" }, - BigInt(0), - BigInt(100_000_000_000_000) + 0, + "100000000000000" ); const tx2 = account.callFunction( "counter.near-examples.testnet", "increment", {}, - BigInt(0), - BigInt(100_000_000_000_000) + 0, + "100000000000000" ); // Send the transactions simultaneously From d872b6d34c8056c9c9994cce0dc68052398306ed Mon Sep 17 00:00:00 2001 From: denbite Date: Sun, 13 Apr 2025 20:50:29 +0200 Subject: [PATCH 04/12] style: fix formatting --- javascript/examples/batch-actions.js | 8 +++++++- javascript/examples/delete-account.js | 6 +++++- javascript/examples/keystore-options/credentials-file.js | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index 48c609e..a5e0579 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -1,4 +1,10 @@ -import { Account, providers, KeyPairSigner, transactions, utils } from "near-api-js"; +import { + Account, + providers, + KeyPairSigner, + transactions, + utils, +} from "near-api-js"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index 280e60c..d1bcb84 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -32,7 +32,11 @@ await account.createTopLevelAccount( const signerToDelete = new KeyPairSigner(newKeyPair); // Create an account object for the new account with corresponding signer -const accountToDelete = new Account(accountToDeleteId, provider, signerToDelete); +const accountToDelete = new Account( + accountToDeleteId, + provider, + signerToDelete +); // Delete the account with account ID of the account object // specifying the beneficiary account ID diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index d772116..64437c7 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -22,6 +22,6 @@ const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1"), + utils.format.parseNearAmount("1") ); console.log(sendTokensResult); From d26dda718f49baffa7fe76a8b03042e1be918760 Mon Sep 17 00:00:00 2001 From: denbite Date: Tue, 15 Apr 2025 21:01:37 +0200 Subject: [PATCH 05/12] fix: make an example of read-only requests with just a `Provider` wherever it's possible --- javascript/examples/account-details.js | 5 +++++ javascript/examples/contract-interaction.js | 11 ++++++++++- javascript/examples/keys.js | 5 +++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index 31077ef..a8c2734 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -13,5 +13,10 @@ const accountBalance = await account.getBalance(); console.log(accountBalance); // Account's state, including its code hash and storage usage +// Option 1 - via PublicAccount const accountState = await account.getInformation(); console.log(accountState); + +// Option 2 - via Provider +const accountState2 = await provider.viewAccount("example-account.testnet"); +console.log(accountState2); diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index 3dc773d..973d0f2 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -12,13 +12,22 @@ const provider = new providers.JsonRpcProvider({ }); // Use the view call function -const viewCallData = await provider.callContractViewFunction( +// Option 1 - via PublicAccount +const viewCallData = await account.callReadFunction( "guestbook.near-examples.testnet", "total_messages", {} ); console.log(viewCallData); +// Option 2 - via Provider +const viewCallData2 = await provider.callContractViewFunction( + "guestbook.near-examples.testnet", + "total_messages", + {} +); +console.log(viewCallData2); + // If args are required, they can be passed in like this: // args: { // from_index: "0", diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index 99706d8..4fbbd7f 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -17,9 +17,14 @@ const provider = new providers.JsonRpcProvider({ const account = new Account(accountId, provider, signer); // example-account.testnet // Get all access keys for the account +// Option 1 - via Account, or PublicAccount const accessKeys = await account.getAccessKeyList(); console.log(accessKeys); +// Option 2 - via Provider +const accessKeys2 = await provider.viewAccessKeyList(accountId); +console.log(accessKeys2); + // Add full access key // Generate a new key pair const newFullKeyPair = KeyPair.fromRandom("ed25519"); From 9ba2575f6c001924be0afeed548d3c094f8e2a2a Mon Sep 17 00:00:00 2001 From: denbite Date: Thu, 17 Apr 2025 21:50:37 +0200 Subject: [PATCH 06/12] fix: update examples to use individual `@near-js/*` packages --- javascript/examples/account-details.js | 5 +-- javascript/examples/batch-actions.js | 18 +++++------ javascript/examples/contract-interaction.js | 23 ++++++------- .../examples/create-account-from-seed.js | 10 ++++-- javascript/examples/create-account.js | 13 +++++--- javascript/examples/delete-account.js | 11 +++++-- javascript/examples/keys.js | 11 +++++-- .../keystore-options/credentials-directory.js | 18 +++++------ .../keystore-options/credentials-file.js | 10 ++++-- .../keystore-options/private-key-string.js | 10 ++++-- .../examples/keystore-options/seed-phrase.js | 9 ++++-- javascript/examples/manual-sign.js | 14 +++++--- javascript/examples/rpc-failover.js | 14 +++++--- javascript/examples/send-tokens.js | 12 ++++--- .../examples/simultaneous-transactions.js | 7 ++-- javascript/examples/utils.js | 6 ++-- .../verify-signature/authentication.js | 4 +-- javascript/package.json | 16 ++++++++-- javascript/pnpm-lock.yaml | 32 ++++++++++++++++--- 19 files changed, 157 insertions(+), 86 deletions(-) diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index a8c2734..bf56f46 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -1,7 +1,8 @@ -import { PublicAccount, providers } from "near-api-js"; +import { PublicAccount } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index a5e0579..d1926d9 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -1,10 +1,8 @@ -import { - Account, - providers, - KeyPairSigner, - transactions, - utils, -} from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; +import { actionCreators } from "@near-js/transactions"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -15,7 +13,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -24,13 +22,13 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Send a batch of actions to a single receiver // Prepare the actions -const callAction = transactions.functionCall( +const callAction = actionCreators.functionCall( "increment", // Method name {}, // Arguments "30000000000000", // Gas 0 // Deposit ); -const transferAction = transactions.transfer(utils.format.parseNearAmount("1")); +const transferAction = actionCreators.transfer(parseNearAmount("0.1")); // Send the batch of actions const batchActionsResult = await account.signAndSendTransaction({ diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index 973d0f2..512e75e 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -1,33 +1,28 @@ -import { Account, providers, KeyPairSigner } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; + import dotenv from "dotenv"; import fs from "fs"; dotenv.config({ path: "../.env" }); const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; +const contractId = "guestbook.near-examples.testnet"; // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); // Use the view call function -// Option 1 - via PublicAccount -const viewCallData = await account.callReadFunction( - "guestbook.near-examples.testnet", +const viewCallData = await provider.callContractViewFunction( + contractId, "total_messages", {} ); console.log(viewCallData); -// Option 2 - via Provider -const viewCallData2 = await provider.callContractViewFunction( - "guestbook.near-examples.testnet", - "total_messages", - {} -); -console.log(viewCallData2); - // If args are required, they can be passed in like this: // args: { // from_index: "0", @@ -42,7 +37,7 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Make a function call to a contract const contractCallResult = await account.callFunction( - "guestbook.near-examples.testnet", + contractId, "add_message", { text: "Hello, world!", diff --git a/javascript/examples/create-account-from-seed.js b/javascript/examples/create-account-from-seed.js index 9957097..4921497 100644 --- a/javascript/examples/create-account-from-seed.js +++ b/javascript/examples/create-account-from-seed.js @@ -1,4 +1,8 @@ -import { Account, providers, KeyPairSigner, utils } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; + import { generateSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; @@ -10,7 +14,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -29,6 +33,6 @@ console.log("Public key", publicKey); const createAccountResult = await account.createTopLevelAccount( newAccountId, publicKey, - utils.format.parseNearAmount("0.1") + parseNearAmount("0.1") ); console.log(createAccountResult); diff --git a/javascript/examples/create-account.js b/javascript/examples/create-account.js index cd0092a..ed91704 100644 --- a/javascript/examples/create-account.js +++ b/javascript/examples/create-account.js @@ -1,4 +1,9 @@ -import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { KeyPair } from "@near-js/crypto"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -9,7 +14,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -29,7 +34,7 @@ console.log("Public key", newPublicKey); const createAccountResult = await account.createTopLevelAccount( newAccountId, newPublicKey, // ed25519:2ASWc... - utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR + parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR ); console.log(createAccountResult); @@ -46,6 +51,6 @@ console.log("Public key", newSubPublicKey); const createSubAccountResult = await account.createSubAccount( newSubAccountIdPrefix, newSubPublicKey, // ed25519:2ASWc... - utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR + parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR ); console.log(createSubAccountResult); diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index d1bcb84..adac73e 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -1,4 +1,9 @@ -import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { KeyPair } from "@near-js/crypto"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -9,7 +14,7 @@ const beneficiaryAccountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -25,7 +30,7 @@ const newPublicKey = newKeyPair.getPublicKey().toString(); await account.createTopLevelAccount( accountToDeleteId, newPublicKey, - utils.format.parseNearAmount("0.1") + parseNearAmount("0.1") ); // Create a signer from a key pair that was added to new account diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index 4fbbd7f..f35541b 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -1,4 +1,9 @@ -import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { KeyPair } from "@near-js/crypto"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -9,7 +14,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -46,7 +51,7 @@ const addFunctionKeyResult = await account.addFunctionAccessKey( newFunctionPublicKey, // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) - utils.format.parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) + parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) ); console.log(addFunctionKeyResult); diff --git a/javascript/examples/keystore-options/credentials-directory.js b/javascript/examples/keystore-options/credentials-directory.js index 9be395a..820f4a3 100644 --- a/javascript/examples/keystore-options/credentials-directory.js +++ b/javascript/examples/keystore-options/credentials-directory.js @@ -1,10 +1,8 @@ -import { - providers, - keyStores, - Account, - KeyPairSigner, - utils, -} from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; +import { UnencryptedFileSystemKeyStore } from "@near-js/keystores-node"; import dotenv from "dotenv"; import { homedir } from "os"; @@ -17,10 +15,10 @@ const accountId = process.env.ACCOUNT_ID; // Create a keystore and add the key pair via credentials directory const credentialsDirectory = ".near-credentials"; const credentialsPath = path.join(homedir(), credentialsDirectory); -const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); +const myKeyStore = new UnencryptedFileSystemKeyStore(credentialsPath); // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -33,6 +31,6 @@ const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1") + parseNearAmount("0.1") ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index 64437c7..67d6894 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -1,4 +1,8 @@ -import { providers, KeyPairSigner, utils, Account } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; import fs from "fs"; @@ -13,7 +17,7 @@ const credentials = JSON.parse(fs.readFileSync(credentialsPath)); const signer = KeyPairSigner.fromSecretKey(credentials.private_key); // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -22,6 +26,6 @@ const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1") + parseNearAmount("0.1") ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/private-key-string.js b/javascript/examples/keystore-options/private-key-string.js index 2aafada..4452e33 100644 --- a/javascript/examples/keystore-options/private-key-string.js +++ b/javascript/examples/keystore-options/private-key-string.js @@ -1,4 +1,8 @@ -import { utils, KeyPairSigner, Account, providers } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; // Load environment variables @@ -10,7 +14,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -20,6 +24,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1") + parseNearAmount("0.1") ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/seed-phrase.js b/javascript/examples/keystore-options/seed-phrase.js index 0dc9053..131668c 100644 --- a/javascript/examples/keystore-options/seed-phrase.js +++ b/javascript/examples/keystore-options/seed-phrase.js @@ -1,4 +1,7 @@ -import { utils, providers, Account, KeyPairSigner } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; import { parseSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; @@ -13,7 +16,7 @@ const { secretKey } = parseSeedPhrase(seedPhrase); // "royal success river ..." const signer = KeyPairSigner.fromSecretKey(secretKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -23,6 +26,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1") + parseNearAmount("0.1") ); console.log(sendTokensResult); diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 9f2057b..564eee3 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -1,4 +1,8 @@ -import { KeyPairSigner, transactions, providers, utils } from "near-api-js"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { actionCreators, createTransaction } from "@near-js/transactions"; +import { parseNearAmount, baseDecode } from "@near-js/utils"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -9,7 +13,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -21,13 +25,13 @@ const accessKey = await provider.viewAccessKey(accountId, signerPublicKey); const nonce = ++accessKey.nonce; // Get a recent block hash -const recentBlockHash = utils.serialize.base_decode(accessKey.block_hash); +const recentBlockHash = baseDecode(accessKey.block_hash); // Construct actions -const actions = [transactions.transfer(utils.format.parseNearAmount("1"))]; +const actions = [actionCreators.transfer(parseNearAmount("0.1"))]; // Construct transaction -const transaction = transactions.createTransaction( +const transaction = createTransaction( accountId, signerPublicKey, "receiver-account.testnet", diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index 20b313e..7779458 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -1,4 +1,8 @@ -import { Account, KeyPairSigner, utils, providers } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider, FailoverRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -10,8 +14,8 @@ const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Set up a new FailoverRpcProvider with two JSON RPC providers const jsonProviders = [ - new providers.JsonRpcProvider({ url: "https://incorrect-rpc-url.com" }), // Incorrect RPC URL - new providers.JsonRpcProvider( + new JsonRpcProvider({ url: "https://incorrect-rpc-url.com" }), // Incorrect RPC URL + new JsonRpcProvider( { url: "https://test.rpc.fastnear.com" }, // RPC URL { retries: 3, // Number of retries before giving up on a request @@ -20,7 +24,7 @@ const jsonProviders = [ } // Retry options ), ]; -const provider = new providers.FailoverRpcProvider(jsonProviders); // Create a FailoverRpcProvider +const provider = new FailoverRpcProvider(jsonProviders); // Create a FailoverRpcProvider // Create an account object const account = new Account(accountId, provider, signer); // example-account.testnet @@ -28,6 +32,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Test the signer with transferring 1 NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", - utils.format.parseNearAmount("1") + parseNearAmount("0.1") ); console.log(sendTokensResult); diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index f2e384c..6bf2936 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -1,7 +1,9 @@ -import * as nearAPI from "near-api-js"; -import dotenv from "dotenv"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount } from "@near-js/utils"; -const { Account, providers, KeyPairSigner, utils } = nearAPI; +import dotenv from "dotenv"; // Load environment variables dotenv.config({ path: "../.env" }); // Path relative to the working directory @@ -12,7 +14,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); @@ -22,6 +24,6 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Send NEAR tokens to another account const sendTokensResult = await account.transfer( "receiver-account.testnet", // Receiver account - utils.format.parseNearAmount("1") // Amount being sent in yoctoNEAR + parseNearAmount("0.1") // Amount being sent in yoctoNEAR ); console.log(sendTokensResult); diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index ace01f2..914d351 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -1,4 +1,7 @@ -import { Account, providers, KeyPairSigner, transactions } from "near-api-js"; +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; + import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -9,7 +12,7 @@ const accountId = process.env.ACCOUNT_ID; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC -const provider = new providers.JsonRpcProvider({ +const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); diff --git a/javascript/examples/utils.js b/javascript/examples/utils.js index 81c5704..cc20a48 100644 --- a/javascript/examples/utils.js +++ b/javascript/examples/utils.js @@ -1,9 +1,9 @@ -import { utils } from "near-api-js"; +import { parseNearAmount, formatNearAmount } from "@near-js/utils"; // Convert NEAR amount into yoctoNEAR -const amountInYoctoNear = utils.format.parseNearAmount("1"); +const amountInYoctoNear = parseNearAmount("0.1"); console.log(amountInYoctoNear); // Convert yoctoNEAR amount into NEAR -const amountInNear = utils.format.formatNearAmount("1000000000000000000000000"); +const amountInNear = formatNearAmount("1000000000000000000000000"); console.log(amountInNear); diff --git a/javascript/examples/verify-signature/authentication.js b/javascript/examples/verify-signature/authentication.js index 59bd57b..dc15f1a 100644 --- a/javascript/examples/verify-signature/authentication.js +++ b/javascript/examples/verify-signature/authentication.js @@ -1,5 +1,5 @@ import * as borsh from 'borsh'; -import { utils } from 'near-api-js'; +import { PublicKey } from '@near-js/crypto'; import js_sha256 from 'js-sha256'; class Payload { @@ -33,7 +33,7 @@ function verifySignature({ publicKey, signature, message, recipient, nonce }) { let real_signature = Buffer.from(signature, 'base64') // Use the public Key to verify that the private-counterpart signed the message - const myPK = utils.PublicKey.from(publicKey) + const myPK = PublicKey.from(publicKey) return myPK.verify(to_sign, real_signature) } diff --git a/javascript/package.json b/javascript/package.json index d449cb2..98e9220 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -1,10 +1,16 @@ { "type": "module", "dependencies": { + "@near-js/accounts": "link:../../near-api-js/packages/accounts", + "@near-js/crypto": "link:../../near-api-js/packages/crypto", + "@near-js/keystores-node": "link:../../near-api-js/packages/keystores-node", + "@near-js/providers": "link:../../near-api-js/packages/providers", + "@near-js/signers": "link:../../near-api-js/packages/signers", + "@near-js/transactions": "link:../../near-api-js/packages/transactions", + "@near-js/utils": "link:../../near-api-js/packages/utils", "borsh": "2.0.0", "dotenv": "^16.4.7", "js-sha256": "^0.11.0", - "near-api-js": "^4.0.4", "near-seed-phrase": "^0.2.1" }, "scripts": { @@ -28,7 +34,13 @@ }, "pnpm": { "overrides": { - "near-api-js": "link:../../near-api-js/packages/near-api-js" + "@near-js/accounts": "link:../../near-api-js/packages/accounts", + "@near-js/signers": "link:../../near-api-js/packages/signers", + "@near-js/providers": "link:../../near-api-js/packages/providers", + "@near-js/utils": "link:../../near-api-js/packages/utils", + "@near-js/transactions": "link:../../near-api-js/packages/transactions", + "@near-js/keystores-node": "link:../../near-api-js/packages/keystores-node", + "@near-js/crypto": "link:../../near-api-js/packages/crypto" } } } diff --git a/javascript/pnpm-lock.yaml b/javascript/pnpm-lock.yaml index ab36e06..0f69365 100644 --- a/javascript/pnpm-lock.yaml +++ b/javascript/pnpm-lock.yaml @@ -5,12 +5,39 @@ settings: excludeLinksFromLockfile: false overrides: - near-api-js: link:../../near-api-js/packages/near-api-js + '@near-js/accounts': link:../../near-api-js/packages/accounts + '@near-js/signers': link:../../near-api-js/packages/signers + '@near-js/providers': link:../../near-api-js/packages/providers + '@near-js/utils': link:../../near-api-js/packages/utils + '@near-js/transactions': link:../../near-api-js/packages/transactions + '@near-js/keystores-node': link:../../near-api-js/packages/keystores-node + '@near-js/crypto': link:../../near-api-js/packages/crypto importers: .: dependencies: + '@near-js/accounts': + specifier: link:../../near-api-js/packages/accounts + version: link:../../near-api-js/packages/accounts + '@near-js/crypto': + specifier: link:../../near-api-js/packages/crypto + version: link:../../near-api-js/packages/crypto + '@near-js/keystores-node': + specifier: link:../../near-api-js/packages/keystores-node + version: link:../../near-api-js/packages/keystores-node + '@near-js/providers': + specifier: link:../../near-api-js/packages/providers + version: link:../../near-api-js/packages/providers + '@near-js/signers': + specifier: link:../../near-api-js/packages/signers + version: link:../../near-api-js/packages/signers + '@near-js/transactions': + specifier: link:../../near-api-js/packages/transactions + version: link:../../near-api-js/packages/transactions + '@near-js/utils': + specifier: link:../../near-api-js/packages/utils + version: link:../../near-api-js/packages/utils borsh: specifier: 2.0.0 version: 2.0.0 @@ -20,9 +47,6 @@ importers: js-sha256: specifier: ^0.11.0 version: 0.11.0 - near-api-js: - specifier: link:../../near-api-js/packages/near-api-js - version: link:../../near-api-js/packages/near-api-js near-seed-phrase: specifier: ^0.2.1 version: 0.2.1 From c351d807fe920e29d4f5df1ea3356e60856a89f0 Mon Sep 17 00:00:00 2001 From: denbite Date: Tue, 22 Apr 2025 22:34:36 +0200 Subject: [PATCH 07/12] fix: use Account instead of PublicAccount --- javascript/examples/account-details.js | 6 +++--- javascript/examples/keys.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index bf56f46..53175c4 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -1,4 +1,4 @@ -import { PublicAccount } from "@near-js/accounts"; +import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; // Create a connection to testnet RPC @@ -7,14 +7,14 @@ const provider = new JsonRpcProvider({ }); // Create an account object -const account = new PublicAccount("example-account.testnet", provider); +const account = new Account("example-account.testnet", provider); // Gets the total, staked and available balance in yoctoNEAR const accountBalance = await account.getBalance(); console.log(accountBalance); // Account's state, including its code hash and storage usage -// Option 1 - via PublicAccount +// Option 1 - via Account const accountState = await account.getInformation(); console.log(accountState); diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index f35541b..e0b2898 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -22,7 +22,7 @@ const provider = new JsonRpcProvider({ const account = new Account(accountId, provider, signer); // example-account.testnet // Get all access keys for the account -// Option 1 - via Account, or PublicAccount +// Option 1 - via Account const accessKeys = await account.getAccessKeyList(); console.log(accessKeys); From ae8a8fb7aa9feb669dc744cc375c8b66e1a8a59d Mon Sep 17 00:00:00 2001 From: denbite Date: Mon, 28 Apr 2025 23:52:53 +0200 Subject: [PATCH 08/12] fix: update an example to use new package `@near-js/tokens` for sending a token --- javascript/examples/send-tokens.js | 46 ++++++++++++++++++++++++++---- javascript/package.json | 4 ++- javascript/pnpm-lock.yaml | 4 +++ 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index 6bf2936..598d1ae 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -1,10 +1,18 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; +import { FungibleToken, NearToken } from "@near-js/tokens"; +import { USDT as USDTFungibleToken } from "@near-js/tokens/usdt/testnet"; import dotenv from "dotenv"; +const NEAR = new NearToken(); +const USDT = new USDTFungibleToken(); +const RefToken = new FungibleToken("ref.fakes.testnet", { + decimals: 8, + symbol: "REF", +}); + // Load environment variables dotenv.config({ path: "../.env" }); // Path relative to the working directory const privateKey = process.env.PRIVATE_KEY; @@ -22,8 +30,36 @@ const provider = new JsonRpcProvider({ const account = new Account(accountId, provider, signer); // example-account.testnet // Send NEAR tokens to another account -const sendTokensResult = await account.transfer( - "receiver-account.testnet", // Receiver account - parseNearAmount("0.1") // Amount being sent in yoctoNEAR +const sendNearTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), // Amount being sent in yoctoNEAR + "receiver-account.testnet" // Receiver account +); + +console.log(sendNearTokensResult); + +const usdtBalance = await account.getFormattedTokenBalance(USDT); + +console.log("USDT balance", usdtBalance); + +// Send USDT tokens to another account +const sendUsdtTokensResult = await account.transferToken( + USDT, + USDT.toUnits("1"), // Amount of USDT being sent + "receiver-account.testnet" // Receiver account ); -console.log(sendTokensResult); + +console.log(sendUsdtTokensResult); + +const refBalance = await account.getFormattedTokenBalance(RefToken); + +console.log("Ref balance", refBalance); + +// Send USDT tokens to another account +const sendRefTokensResult = await account.transferToken( + RefToken, + RefToken.toUnits("1"), // Amount of Ref tokens being sent + "receiver-account.testnet" // Receiver account +); + +console.log(sendRefTokensResult); diff --git a/javascript/package.json b/javascript/package.json index 98e9220..4fffb0a 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -6,6 +6,7 @@ "@near-js/keystores-node": "link:../../near-api-js/packages/keystores-node", "@near-js/providers": "link:../../near-api-js/packages/providers", "@near-js/signers": "link:../../near-api-js/packages/signers", + "@near-js/tokens": "link:../../near-api-js/packages/tokens", "@near-js/transactions": "link:../../near-api-js/packages/transactions", "@near-js/utils": "link:../../near-api-js/packages/utils", "borsh": "2.0.0", @@ -40,7 +41,8 @@ "@near-js/utils": "link:../../near-api-js/packages/utils", "@near-js/transactions": "link:../../near-api-js/packages/transactions", "@near-js/keystores-node": "link:../../near-api-js/packages/keystores-node", - "@near-js/crypto": "link:../../near-api-js/packages/crypto" + "@near-js/crypto": "link:../../near-api-js/packages/crypto", + "@near-js/tokens": "link:../../near-api-js/packages/tokens" } } } diff --git a/javascript/pnpm-lock.yaml b/javascript/pnpm-lock.yaml index 0f69365..dc8f914 100644 --- a/javascript/pnpm-lock.yaml +++ b/javascript/pnpm-lock.yaml @@ -12,6 +12,7 @@ overrides: '@near-js/transactions': link:../../near-api-js/packages/transactions '@near-js/keystores-node': link:../../near-api-js/packages/keystores-node '@near-js/crypto': link:../../near-api-js/packages/crypto + '@near-js/tokens': link:../../near-api-js/packages/tokens importers: @@ -32,6 +33,9 @@ importers: '@near-js/signers': specifier: link:../../near-api-js/packages/signers version: link:../../near-api-js/packages/signers + '@near-js/tokens': + specifier: link:../../near-api-js/packages/tokens + version: link:../../near-api-js/packages/tokens '@near-js/transactions': specifier: link:../../near-api-js/packages/transactions version: link:../../near-api-js/packages/transactions From 5415bc3466c15f840233fbf7994d86ab7030b80e Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Tue, 29 Apr 2025 06:22:26 -0400 Subject: [PATCH 09/12] wip: changes to the new interface --- javascript/examples/account-details.js | 21 +++---- javascript/examples/batch-actions.js | 21 +++---- javascript/examples/contract-interaction.js | 36 ++++-------- .../examples/create-account-from-seed.js | 24 +++----- javascript/examples/create-account.js | 56 ------------------- javascript/examples/create-subaccount.js | 37 ++++++++++++ javascript/examples/create-tla.js | 53 ++++++++++++++++++ javascript/examples/delete-account.js | 39 +++++-------- javascript/examples/deploy-contract.js | 28 ++++++++++ javascript/examples/keys.js | 55 +++++++++--------- .../keystore-options/credentials-directory.js | 8 ++- .../keystore-options/credentials-file.js | 5 +- .../keystore-options/private-key-string.js | 11 ++-- .../examples/keystore-options/seed-phrase.js | 12 ++-- javascript/examples/manual-sign.js | 9 +-- javascript/examples/rpc-failover.js | 5 +- 16 files changed, 220 insertions(+), 200 deletions(-) delete mode 100644 javascript/examples/create-account.js create mode 100644 javascript/examples/create-subaccount.js create mode 100644 javascript/examples/create-tla.js create mode 100644 javascript/examples/deploy-contract.js diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index 53175c4..2b9c75a 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -1,23 +1,18 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; -// Create a connection to testnet RPC +// Gather details through the RPC Provider const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account("example-account.testnet", provider); +const rpcBalance = await provider.getBalance("example-account.testnet") +const rpcState = await provider.viewAccount("example-account.testnet"); +console.log({ rpcBalance, rpcState }); -// Gets the total, staked and available balance in yoctoNEAR +// Option 2: Use an Account object +const account = new Account("example-account.testnet", provider); const accountBalance = await account.getBalance(); -console.log(accountBalance); - -// Account's state, including its code hash and storage usage -// Option 1 - via Account -const accountState = await account.getInformation(); -console.log(accountState); +const accountState = await account.getState(); -// Option 2 - via Provider -const accountState2 = await provider.viewAccount("example-account.testnet"); -console.log(accountState2); +console.log({ accountState, accountBalance }); \ No newline at end of file diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index d1926d9..67f8c63 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -6,10 +6,9 @@ import { actionCreators } from "@near-js/transactions"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; // Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC @@ -18,21 +17,15 @@ const provider = new JsonRpcProvider({ }); // Create an account object +const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet -// Send a batch of actions to a single receiver -// Prepare the actions -const callAction = actionCreators.functionCall( - "increment", // Method name - {}, // Arguments - "30000000000000", // Gas - 0 // Deposit -); -const transferAction = actionCreators.transfer(parseNearAmount("0.1")); - // Send the batch of actions -const batchActionsResult = await account.signAndSendTransaction({ +const batchActionsResult = await account.createSignAndSendTx({ receiverId: "counter.near-examples.testnet", - actions: [callAction, transferAction], + actions: [ + actionCreators.functionCall("increment", {}, "30000000000000", 0), + actionCreators.transfer(parseNearAmount("0.1")) + ], }); console.log(batchActionsResult); diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index 512e75e..f907810 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -3,52 +3,38 @@ import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; import dotenv from "dotenv"; -import fs from "fs"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; -const contractId = "guestbook.near-examples.testnet"; // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Use the view call function -const viewCallData = await provider.callContractViewFunction( +const contractId = "guestbook.near-examples.testnet"; + +// Make a read-only function call +const totalMessages = await provider.callFunction( contractId, "total_messages", {} ); -console.log(viewCallData); -// If args are required, they can be passed in like this: -// args: { -// from_index: "0", -// limit: "10" -// } +console.log(totalMessages); // Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create an account object +const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet -// Make a function call to a contract -const contractCallResult = await account.callFunction( +// Make a function call that modifies state +const result = await account.callFunction( contractId, "add_message", - { - text: "Hello, world!", - }, - 0, - "100000000000000" + { text: "Hello, world!" } ); -console.log(contractCallResult); -// Deploy a contract to the account -const deployResult = await account.deployContract( - fs.readFileSync("../contracts/contract.wasm") // Path of contract WASM relative to the working directory -); -console.log(deployResult); +console.log(result); \ No newline at end of file diff --git a/javascript/examples/create-account-from-seed.js b/javascript/examples/create-account-from-seed.js index 4921497..0f86172 100644 --- a/javascript/examples/create-account-from-seed.js +++ b/javascript/examples/create-account-from-seed.js @@ -7,32 +7,22 @@ import { generateSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; - -// Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet +// Instantiate the account that will create the new account +const signer = KeyPairSigner.fromSecretKey(process.env.PRIVATE_KEY); +const account = new Account(process.env.ACCOUNT_ID, provider, signer); -// Create a .testnet account -// Generate a new account ID based on the current timestamp -const newAccountId = Date.now() + ".testnet"; -// Generate a new seed phrase +// Generate a new key const { seedPhrase, publicKey, secretKey } = generateSeedPhrase(); -console.log("Seed phrase", seedPhrase); -console.log("Private key", secretKey); -console.log("Public key", publicKey); +console.log(`Created key ${secretKey} with seed phrase ${seedPhrase}`); -const createAccountResult = await account.createTopLevelAccount( - newAccountId, +await account.createTopLevelAccount( + `acc-${Date.now()}.testnet`, publicKey, parseNearAmount("0.1") ); -console.log(createAccountResult); diff --git a/javascript/examples/create-account.js b/javascript/examples/create-account.js deleted file mode 100644 index ed91704..0000000 --- a/javascript/examples/create-account.js +++ /dev/null @@ -1,56 +0,0 @@ -import { Account } from "@near-js/accounts"; -import { JsonRpcProvider } from "@near-js/providers"; -import { KeyPairSigner } from "@near-js/signers"; -import { KeyPair } from "@near-js/crypto"; -import { parseNearAmount } from "@near-js/utils"; - -import dotenv from "dotenv"; - -dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; - -// Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... - -// Create a connection to testnet RPC -const provider = new JsonRpcProvider({ - url: "https://test.rpc.fastnear.com", -}); - -// Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet - -// Create a .testnet account -// Generate a new account ID based on the current timestamp -const newAccountId = Date.now() + ".testnet"; -// Generate a new key pair -const newKeyPair = KeyPair.fromRandom("ed25519"); -const newPublicKey = newKeyPair.getPublicKey().toString(); -const newPrivateKey = newKeyPair.toString(); -console.log("Private key", newPrivateKey); -console.log("Public key", newPublicKey); - -const createAccountResult = await account.createTopLevelAccount( - newAccountId, - newPublicKey, // ed25519:2ASWc... - parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR -); -console.log(createAccountResult); - -// Create a sub account -// Generate a new sub account ID based on the current timestamp -const newSubAccountIdPrefix = Date.now().toString(); -// Generate a new key pair -const newSubKeyPair = KeyPair.fromRandom("ed25519"); -const newSubPublicKey = newSubKeyPair.getPublicKey().toString(); -const newSubPrivateKey = newSubKeyPair.toString(); -console.log("Private key", newSubPrivateKey); -console.log("Public key", newSubPublicKey); - -const createSubAccountResult = await account.createSubAccount( - newSubAccountIdPrefix, - newSubPublicKey, // ed25519:2ASWc... - parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR -); -console.log(createSubAccountResult); diff --git a/javascript/examples/create-subaccount.js b/javascript/examples/create-subaccount.js new file mode 100644 index 0000000..30c0ab2 --- /dev/null +++ b/javascript/examples/create-subaccount.js @@ -0,0 +1,37 @@ +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; +import { KeyPair } from "@near-js/crypto"; +import { parseNearAmount } from "@near-js/utils"; + +import dotenv from "dotenv"; + +dotenv.config({ path: "../.env" }); + +// Create a connection to testnet RPC +const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); + +// Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + +// Create an account object +const accountId = process.env.ACCOUNT_ID; +const account = new Account(accountId, provider, signer); // example-account.testnet + +// Generate a new key pair +const keyPair = KeyPair.fromRandom("ed25519"); +const publicKey = keyPair.getPublicKey().toString(); + +const prefix = Date.now().toString(); + +await account.createSubAccount( + prefix, // prefix for the sub account (e.g. sub.near.testnet) + publicKey, // ed25519:2ASWc... + parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR +); + +console.log(`Created ${newAccountId} with private key ${keyPair.toString()}`) +console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) diff --git a/javascript/examples/create-tla.js b/javascript/examples/create-tla.js new file mode 100644 index 0000000..56fd22e --- /dev/null +++ b/javascript/examples/create-tla.js @@ -0,0 +1,53 @@ +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPair } from "@near-js/crypto"; +import { KeyPairSigner } from "@near-js/signers"; +import { parseNearAmount, keyToSeedPhrase } from "@near-js/utils"; + +import dotenv from "dotenv"; + +dotenv.config({ path: "../.env" }); + +// Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + +// Create a connection to testnet RPC +const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); + +// Create an account object +const accountId = process.env.ACCOUNT_ID; +const account = new Account(accountId, provider, signer); // example-account.testnet + +// New .testnet account +const newAccountId = Date.now() + ".testnet"; + +// Generate a new key +const keyPair = KeyPair.fromRandom("ed25519"); +const publicKey = keyPair.getPublicKey().toString(); + +await account.createTopLevelAccount( + newAccountId, + publicKey, + parseNearAmount("0.1") +); + +console.log(`Created ${newAccountId} with private key ${keyPair.toString()}`) +console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) + +// Option 2: Call `testnet` directly +const newAccountId2 = Date.now() + ".testnet"; + +await account.functionCall({ + contractId: "testnet", + methodName: "create_account", + args: { + "new_account_id": newAccountId2, + "new_public_key": publicKey + } +}) + +console.log(`Created account ${newAccountId2} with privateKey: ${secretKey}`) +console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index adac73e..45667b2 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -7,10 +7,10 @@ import { parseNearAmount } from "@near-js/utils"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const beneficiaryAccountId = process.env.ACCOUNT_ID; // Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; +const keyPair = KeyPair.fromString(privateKey); const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Create a connection to testnet RPC @@ -18,34 +18,21 @@ const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account(beneficiaryAccountId, provider, signer); // example-account.testnet +// Create a new account to be deleted +const accountId = process.env.ACCOUNT_ID; +const master = new Account(accountId, provider, signer) -// First create a new account to be deleted -// Generate a new account ID based on the current timestamp -const accountToDeleteId = Date.now() + ".testnet"; -const newKeyPair = KeyPair.fromRandom("ed25519"); -const newPublicKey = newKeyPair.getPublicKey().toString(); +const deleteMe = Date.now().toString(); -await account.createTopLevelAccount( - accountToDeleteId, - newPublicKey, +await master.createTopLevelAccount( + deleteMe, + keyPair.getPublicKey().toString(), parseNearAmount("0.1") ); -// Create a signer from a key pair that was added to new account -const signerToDelete = new KeyPairSigner(newKeyPair); - // Create an account object for the new account with corresponding signer -const accountToDelete = new Account( - accountToDeleteId, - provider, - signerToDelete -); +const accountToDelete = new Account(deleteMe, provider, signer); -// Delete the account with account ID of the account object -// specifying the beneficiary account ID -const deleteAccountResult = await accountToDelete.deleteAccount( - beneficiaryAccountId -); // example-beneficiary.testnet -console.log(deleteAccountResult); +// Delete the account +await accountToDelete.deleteAccount(accountId); // example-beneficiary.testnet +console.log(`Account ${deleteMe} was deleted`); diff --git a/javascript/examples/deploy-contract.js b/javascript/examples/deploy-contract.js new file mode 100644 index 0000000..543db1d --- /dev/null +++ b/javascript/examples/deploy-contract.js @@ -0,0 +1,28 @@ +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { KeyPairSigner } from "@near-js/signers"; + +import dotenv from "dotenv"; +import fs from "fs"; + +dotenv.config({ path: "../.env" }); + +// Create a connection to testnet RPC +const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); + +// Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + +// Create an account object +const accountId = process.env.ACCOUNT_ID; +const account = new Account(accountId, provider, signer); // example-account.testnet + +// Deploy a contract to the account +const result = await account.deployContract( + fs.readFileSync("../contracts/contract.wasm") // Path of contract WASM relative to the working directory +); + +console.log(result); diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index e0b2898..c213399 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -7,55 +7,52 @@ import { parseNearAmount } from "@near-js/utils"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; -// Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +const accountId = process.env.ACCOUNT_ID; // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet +// Query keys with the provider +const keysProvider = await provider.viewAccessKeyList(accountId); +console.log(keysProvider); + +// Create an Account object without a signer +const account = new Account(accountId, provider); -// Get all access keys for the account -// Option 1 - via Account +// Query keys const accessKeys = await account.getAccessKeyList(); console.log(accessKeys); -// Option 2 - via Provider -const accessKeys2 = await provider.viewAccessKeyList(accountId); -console.log(accessKeys2); + +// Create a signer and add it to the Account +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + +account.setSigner(signer); // Add full access key -// Generate a new key pair -const newFullKeyPair = KeyPair.fromRandom("ed25519"); -const newFullPublicKey = newFullKeyPair.getPublicKey(); -console.log(newFullPublicKey.toString()); +const fullKeyPair = KeyPair.fromRandom("ed25519"); -const addFullKeyResult = await account.addFullAccessKey( - newFullPublicKey // The new public key ed25519:2ASWc... +await account.addFullAccessKey( + fullKeyPair.getPublicKey().toString() // ed25519:2ASWc... ); -console.log(addFullKeyResult); +console.log(`Added FAK ${fullKeyPair.toString()}`); // Add function call access key -// Generate a new key pair -const newFunctionKeyPair = KeyPair.fromRandom("ed25519"); -const newFunctionPublicKey = newFunctionKeyPair.getPublicKey(); -console.log(newFunctionPublicKey.toString()); +const fnKeyPair = KeyPair.fromRandom("ed25519"); -const addFunctionKeyResult = await account.addFunctionAccessKey( - newFunctionPublicKey, // The new public key ed25519:2ASWc... +await account.addFunctionAccessKey( + fnKeyPair.getPublicKey().toString(), // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) ); -console.log(addFunctionKeyResult); +console.log(`Added FCK ${fnKeyPair.toString()}`); -// Delete full access key -const publicKeyToDelete = newFullPublicKey; -const deleteFullKeyResult = await account.deleteKey(publicKeyToDelete); // The public key being deleted ed25519:2ASWc... -console.log(deleteFullKeyResult); +// Use the new FullAccess Key to delete the Function Call Key +const newSigner = KeyPairSigner.fromSecretKey(fullKeyPair.toString()); +account.setSigner(newSigner) +await account.deleteKey(fnKeyPair.getPublicKey().toString()); diff --git a/javascript/examples/keystore-options/credentials-directory.js b/javascript/examples/keystore-options/credentials-directory.js index 820f4a3..407c080 100644 --- a/javascript/examples/keystore-options/credentials-directory.js +++ b/javascript/examples/keystore-options/credentials-directory.js @@ -10,9 +10,8 @@ import path from "path"; // Load environment variables dotenv.config({ path: "../.env" }); -const accountId = process.env.ACCOUNT_ID; -// Create a keystore and add the key pair via credentials directory +// Create a keystore that stores keys in the `~/.near-credentials` const credentialsDirectory = ".near-credentials"; const credentialsPath = path.join(homedir(), credentialsDirectory); const myKeyStore = new UnencryptedFileSystemKeyStore(credentialsPath); @@ -22,10 +21,12 @@ const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); +// Get the key from the keystore const keyPair = await myKeyStore.getKey("testnet", accountId); - const signer = new KeyPairSigner(keyPair); +// Instantiate the account +const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR @@ -33,4 +34,5 @@ const sendTokensResult = await account.transfer( "receiver-account.testnet", parseNearAmount("0.1") ); + console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index 67d6894..b7d328d 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -8,11 +8,11 @@ import fs from "fs"; // Load environment variables dotenv.config({ path: "../.env" }); -const accountId = process.env.ACCOUNT_ID; // Fetch the private key from a credentials file const credentialsPath = "../credentials-file.json"; // Path relative to the working directory const credentials = JSON.parse(fs.readFileSync(credentialsPath)); + // Create a signer from the private key const signer = KeyPairSigner.fromSecretKey(credentials.private_key); @@ -21,6 +21,8 @@ const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); +// Instantiate the account +const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR @@ -28,4 +30,5 @@ const sendTokensResult = await account.transfer( "receiver-account.testnet", parseNearAmount("0.1") ); + console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/private-key-string.js b/javascript/examples/keystore-options/private-key-string.js index 4452e33..01b74f9 100644 --- a/javascript/examples/keystore-options/private-key-string.js +++ b/javascript/examples/keystore-options/private-key-string.js @@ -7,23 +7,24 @@ import dotenv from "dotenv"; // Load environment variables dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; // Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet +// Instantiate an account +const accountId = process.env.ACCOUNT_ID; +const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", parseNearAmount("0.1") ); + console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/seed-phrase.js b/javascript/examples/keystore-options/seed-phrase.js index 131668c..608b0a6 100644 --- a/javascript/examples/keystore-options/seed-phrase.js +++ b/javascript/examples/keystore-options/seed-phrase.js @@ -7,13 +7,13 @@ import dotenv from "dotenv"; // Load environment variables dotenv.config({ path: "../.env" }); -const seedPhrase = process.env.SEED_PHRASE; -const accountId = process.env.ACCOUNT_ID; // Create a keystore and add the key pair via a seed phrase -const { secretKey } = parseSeedPhrase(seedPhrase); // "royal success river ..." +const seedPhrase = process.env.SEED_PHRASE; // "royal success river ..." +const { secretKey } = parseSeedPhrase(seedPhrase); + // Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(secretKey); // ed25519:5Fg2... +const signer = KeyPairSigner.fromSecretKey(secretKey); // Create a connection to testnet RPC const provider = new JsonRpcProvider({ @@ -21,11 +21,13 @@ const provider = new JsonRpcProvider({ }); // Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet +const accountId = process.env.ACCOUNT_ID; +const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR const sendTokensResult = await account.transfer( "receiver-account.testnet", parseNearAmount("0.1") ); + console.log(sendTokensResult); diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 564eee3..10757d8 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -6,17 +6,18 @@ import { parseNearAmount, baseDecode } from "@near-js/utils"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; -// Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +const accountId = process.env.ACCOUNT_ID; // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); +// Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; +const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... + const signerPublicKey = await signer.getPublicKey(); // Get the nonce of the key diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index 7779458..5f8e026 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -6,10 +6,9 @@ import { parseNearAmount } from "@near-js/utils"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); -const privateKey = process.env.PRIVATE_KEY; -const accountId = process.env.ACCOUNT_ID; // Create a signer from a private key string +const privateKey = process.env.PRIVATE_KEY; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... // Set up a new FailoverRpcProvider with two JSON RPC providers @@ -24,9 +23,11 @@ const jsonProviders = [ } // Retry options ), ]; + const provider = new FailoverRpcProvider(jsonProviders); // Create a FailoverRpcProvider // Create an account object +const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer with transferring 1 NEAR From 00f14688d6fd51d392b31fa8d689343f02b257d8 Mon Sep 17 00:00:00 2001 From: denbite Date: Thu, 1 May 2025 23:07:21 +0200 Subject: [PATCH 10/12] fix: update examples according to the new interface of some functions --- javascript/examples/account-details.js | 2 +- javascript/examples/batch-actions.js | 2 +- javascript/examples/contract-interaction.js | 10 ++-- javascript/examples/create-subaccount.js | 3 +- javascript/examples/create-tla.js | 8 ++- javascript/examples/delete-account.js | 2 +- javascript/examples/keys.js | 4 +- .../keystore-options/credentials-directory.js | 14 ++++-- .../keystore-options/credentials-file.js | 11 +++-- .../keystore-options/private-key-string.js | 11 +++-- .../examples/keystore-options/seed-phrase.js | 10 ++-- javascript/examples/rpc-failover.js | 11 +++-- javascript/examples/send-tokens.js | 31 ++++++------ .../examples/simultaneous-transactions.js | 28 +++++------ javascript/examples/tokens-balance.js | 49 +++++++++++++++++++ javascript/examples/utils.js | 10 ++++ javascript/package.json | 5 +- 17 files changed, 141 insertions(+), 70 deletions(-) create mode 100644 javascript/examples/tokens-balance.js diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index 2b9c75a..85941ef 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -6,7 +6,7 @@ const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -const rpcBalance = await provider.getBalance("example-account.testnet") +const rpcBalance = await provider.viewAccountBalance("example-account.testnet") const rpcState = await provider.viewAccount("example-account.testnet"); console.log({ rpcBalance, rpcState }); diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index 67f8c63..3aa23d1 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -21,7 +21,7 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet // Send the batch of actions -const batchActionsResult = await account.createSignAndSendTx({ +const batchActionsResult = await account.signAndSendTransaction({ receiverId: "counter.near-examples.testnet", actions: [ actionCreators.functionCall("increment", {}, "30000000000000", 0), diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index f907810..67fdad4 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -31,10 +31,10 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet // Make a function call that modifies state -const result = await account.callFunction( - contractId, - "add_message", - { text: "Hello, world!" } -); +const result = await account.callFunction({ + contractId: contractId, + methodName: "add_message", + args: { text: "Hello, world!" }, +}); console.log(result); \ No newline at end of file diff --git a/javascript/examples/create-subaccount.js b/javascript/examples/create-subaccount.js index 30c0ab2..964596b 100644 --- a/javascript/examples/create-subaccount.js +++ b/javascript/examples/create-subaccount.js @@ -33,5 +33,4 @@ await account.createSubAccount( parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR ); -console.log(`Created ${newAccountId} with private key ${keyPair.toString()}`) -console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) +console.log(`Created ${prefix}.${accountId} with private key ${keyPair.toString()}`) diff --git a/javascript/examples/create-tla.js b/javascript/examples/create-tla.js index 56fd22e..9088916 100644 --- a/javascript/examples/create-tla.js +++ b/javascript/examples/create-tla.js @@ -2,7 +2,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPair } from "@near-js/crypto"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount, keyToSeedPhrase } from "@near-js/utils"; +import { parseNearAmount } from "@near-js/utils"; import dotenv from "dotenv"; @@ -35,12 +35,11 @@ await account.createTopLevelAccount( ); console.log(`Created ${newAccountId} with private key ${keyPair.toString()}`) -console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) // Option 2: Call `testnet` directly const newAccountId2 = Date.now() + ".testnet"; -await account.functionCall({ +await account.callFunction({ contractId: "testnet", methodName: "create_account", args: { @@ -49,5 +48,4 @@ await account.functionCall({ } }) -console.log(`Created account ${newAccountId2} with privateKey: ${secretKey}`) -console.log(`Seed phrase: ${keyToSeedPhrase(keyPair)}`) +console.log(`Created account ${newAccountId2} with privateKey: ${keyPair.toString()}`) diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index 45667b2..ab9a720 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -22,7 +22,7 @@ const provider = new JsonRpcProvider({ const accountId = process.env.ACCOUNT_ID; const master = new Account(accountId, provider, signer) -const deleteMe = Date.now().toString(); +const deleteMe = `${Date.now()}.testnet`; await master.createTopLevelAccount( deleteMe, diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index c213399..8ce6b90 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -44,8 +44,8 @@ console.log(`Added FAK ${fullKeyPair.toString()}`); // Add function call access key const fnKeyPair = KeyPair.fromRandom("ed25519"); -await account.addFunctionAccessKey( - fnKeyPair.getPublicKey().toString(), // The new public key ed25519:2ASWc... +await account.addFunctionCallAccessKey( + fnKeyPair.getPublicKey(), // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) diff --git a/javascript/examples/keystore-options/credentials-directory.js b/javascript/examples/keystore-options/credentials-directory.js index 407c080..dd48e5e 100644 --- a/javascript/examples/keystore-options/credentials-directory.js +++ b/javascript/examples/keystore-options/credentials-directory.js @@ -1,8 +1,10 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; import { UnencryptedFileSystemKeyStore } from "@near-js/keystores-node"; +import { NearToken } from "@near-js/tokens"; + +const NEAR = new NearToken(); import dotenv from "dotenv"; import { homedir } from "os"; @@ -16,6 +18,8 @@ const credentialsDirectory = ".near-credentials"; const credentialsPath = path.join(homedir(), credentialsDirectory); const myKeyStore = new UnencryptedFileSystemKeyStore(credentialsPath); +const accountId = process.env.ACCOUNT_ID; + // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", @@ -26,13 +30,13 @@ const keyPair = await myKeyStore.getKey("testnet", accountId); const signer = new KeyPairSigner(keyPair); // Instantiate the account -const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.transfer( - "receiver-account.testnet", - parseNearAmount("0.1") +const sendTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), + "receiver-account.testnet" ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/credentials-file.js b/javascript/examples/keystore-options/credentials-file.js index b7d328d..2ac9abf 100644 --- a/javascript/examples/keystore-options/credentials-file.js +++ b/javascript/examples/keystore-options/credentials-file.js @@ -1,7 +1,9 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; +import { NearToken } from "@near-js/tokens"; + +const NEAR = new NearToken(); import dotenv from "dotenv"; import fs from "fs"; @@ -26,9 +28,10 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.transfer( - "receiver-account.testnet", - parseNearAmount("0.1") +const sendTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), + "receiver-account.testnet" ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/private-key-string.js b/javascript/examples/keystore-options/private-key-string.js index 01b74f9..dca05b3 100644 --- a/javascript/examples/keystore-options/private-key-string.js +++ b/javascript/examples/keystore-options/private-key-string.js @@ -1,7 +1,9 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; +import { NearToken } from "@near-js/tokens"; + +const NEAR = new NearToken(); import dotenv from "dotenv"; @@ -22,9 +24,10 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.transfer( - "receiver-account.testnet", - parseNearAmount("0.1") +const sendTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), + "receiver-account.testnet" ); console.log(sendTokensResult); diff --git a/javascript/examples/keystore-options/seed-phrase.js b/javascript/examples/keystore-options/seed-phrase.js index 608b0a6..0145318 100644 --- a/javascript/examples/keystore-options/seed-phrase.js +++ b/javascript/examples/keystore-options/seed-phrase.js @@ -4,6 +4,9 @@ import { KeyPairSigner } from "@near-js/signers"; import { parseNearAmount } from "@near-js/utils"; import { parseSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; +import { NearToken } from "@near-js/tokens"; + +const NEAR = new NearToken(); // Load environment variables dotenv.config({ path: "../.env" }); @@ -25,9 +28,10 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // Test the signer by transferring NEAR -const sendTokensResult = await account.transfer( - "receiver-account.testnet", - parseNearAmount("0.1") +const sendTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), + "receiver-account.testnet" ); console.log(sendTokensResult); diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index 5f8e026..862c0a3 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -1,7 +1,9 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider, FailoverRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; +import { NearToken } from "@near-js/tokens"; + +const NEAR = new NearToken(); import dotenv from "dotenv"; @@ -31,8 +33,9 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer with transferring 1 NEAR -const sendTokensResult = await account.transfer( - "receiver-account.testnet", - parseNearAmount("0.1") +const sendTokensResult = await account.transferToken( + NEAR, + NEAR.toUnits("0.1"), + "receiver-account.testnet" ); console.log(sendTokensResult); diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index 598d1ae..e786854 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -8,7 +8,7 @@ import dotenv from "dotenv"; const NEAR = new NearToken(); const USDT = new USDTFungibleToken(); -const RefToken = new FungibleToken("ref.fakes.testnet", { +const REF = new FungibleToken("ref.fakes.testnet", { decimals: 8, symbol: "REF", }); @@ -29,37 +29,34 @@ const provider = new JsonRpcProvider({ // Create an account object const account = new Account(accountId, provider, signer); // example-account.testnet -// Send NEAR tokens to another account +// ------- Send NEAR tokens to another account ------- const sendNearTokensResult = await account.transferToken( NEAR, NEAR.toUnits("0.1"), // Amount being sent in yoctoNEAR "receiver-account.testnet" // Receiver account ); - console.log(sendNearTokensResult); -const usdtBalance = await account.getFormattedTokenBalance(USDT); - -console.log("USDT balance", usdtBalance); +// ------- Send USDT tokens to another account ------- +// if a user isn't registered, the transfer will fail +// it a user is already registered, we'll just get funds back +await account.registerTokenAccount(USDT, "receiver-account.testnet"); -// Send USDT tokens to another account +// Use https://testnet.rhea.finance/#near|usdtt.fakes.testnet to get USDT token const sendUsdtTokensResult = await account.transferToken( USDT, USDT.toUnits("1"), // Amount of USDT being sent "receiver-account.testnet" // Receiver account ); - console.log(sendUsdtTokensResult); -const refBalance = await account.getFormattedTokenBalance(RefToken); - -console.log("Ref balance", refBalance); - -// Send USDT tokens to another account -const sendRefTokensResult = await account.transferToken( - RefToken, - RefToken.toUnits("1"), // Amount of Ref tokens being sent +// ------- Send REF tokens to another account ------- +// Use https://testnet.rhea.finance/#near|ref.fakes.testnet to get REF tokens +const sendREFsResult = await account.transferToken( + REF, + REF.toUnits("1"), // Amount of Ref tokens being sent "receiver-account.testnet" // Receiver account ); -console.log(sendRefTokensResult); +// we haven't registered a receiver before sending, so it may fail +console.log(sendREFsResult); diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index 914d351..55c53c3 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -21,21 +21,19 @@ const account = new Account(accountId, provider, signer); // example-account.tes // Send independent transactions simultaneously to different receivers // Prepare the transactions -const tx1 = account.callFunction( - "guestbook.near-examples.testnet", - "add_message", - { text: "Hello, world!" }, - 0, - "100000000000000" -); - -const tx2 = account.callFunction( - "counter.near-examples.testnet", - "increment", - {}, - 0, - "100000000000000" -); +const tx1 = account.callFunction({ + contractId: "guestbook.near-examples.testnet", + methodName: "add_message", + args: { text: "Hello, world!" }, + gas: "100000000000000", +}); + +const tx2 = account.callFunction({ + contractId: "counter.near-examples.testnet", + methodName: "increment", + args: {}, + gas: "100000000000000", +}); // Send the transactions simultaneously const transactionsResults = await Promise.all([tx1, tx2]); diff --git a/javascript/examples/tokens-balance.js b/javascript/examples/tokens-balance.js new file mode 100644 index 0000000..2e5e086 --- /dev/null +++ b/javascript/examples/tokens-balance.js @@ -0,0 +1,49 @@ +import { Account } from "@near-js/accounts"; +import { JsonRpcProvider } from "@near-js/providers"; +import { FungibleToken, NearToken } from "@near-js/tokens"; +import { USDT as USDTFungibleToken } from "@near-js/tokens/usdt/testnet"; + +import dotenv from "dotenv"; + +const NEAR = new NearToken(); +const USDT = new USDTFungibleToken(); +const REF = new FungibleToken("ref.fakes.testnet", { + decimals: 8, + symbol: "REF", +}); + +// Load environment variables +dotenv.config({ path: "../.env" }); // Path relative to the working directory +const accountId = process.env.ACCOUNT_ID; + +// Create a connection to testnet RPC +const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", +}); + +// Create an account object +const account = new Account(accountId, provider); // example-account.testnet + +// ------- Fetch NEAR tokens formatted balance ------- +const nearTokensBalance = await account.getFormattedTokenBalance(NEAR); +console.log("NEAR: ", nearTokensBalance); + +// ------- Fetch USDT tokens formatted balance ------- +const usdtTokensBalance = await account.getFormattedTokenBalance(USDT); +console.log("USDT: ", usdtTokensBalance); + +// ------- Fetch REF tokens formatted balance ------- +const refTokensBalance = await account.getFormattedTokenBalance(REF); +console.log("REF: ", refTokensBalance); + +// ------- Fetch NEAR tokens balance in the smallest units as BigInt ------- +const nearTokensBalanceInt = await account.getTokenBalance(NEAR); +console.log("NEAR as units: ", nearTokensBalanceInt); + +// ------- Fetch USDT tokens balance in the smallest units as BigInt ------- +const usdtTokensBalanceInt = await account.getTokenBalance(USDT); +console.log("USDT as units: ", usdtTokensBalanceInt); + +// ------- Fetch REF tokens balance in the smallest units as BigInt ------- +const refTokensBalanceInt = await account.getTokenBalance(REF); +console.log("REF as units: ", refTokensBalanceInt); diff --git a/javascript/examples/utils.js b/javascript/examples/utils.js index cc20a48..0c69168 100644 --- a/javascript/examples/utils.js +++ b/javascript/examples/utils.js @@ -1,4 +1,5 @@ import { parseNearAmount, formatNearAmount } from "@near-js/utils"; +import { USDT } from "@near-js/tokens/usdt/testnet"; // Convert NEAR amount into yoctoNEAR const amountInYoctoNear = parseNearAmount("0.1"); @@ -7,3 +8,12 @@ console.log(amountInYoctoNear); // Convert yoctoNEAR amount into NEAR const amountInNear = formatNearAmount("1000000000000000000000000"); console.log(amountInNear); + +const usdt = new USDT(); +// convert USDT amount into base units +const amountInUsdtUnits = usdt.toUnits("0.1").toString(); +console.log(amountInUsdtUnits); + +// convert base units into USDT +const amountInUsdt = usdt.toAmount("12300000"); +console.log(amountInUsdt); diff --git a/javascript/package.json b/javascript/package.json index 4fffb0a..49e812c 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -21,10 +21,13 @@ "seed-phrase": "node examples/keystore-options/seed-phrase.js", "account-details": "node examples/account-details.js", "batch-actions": "node examples/batch-actions.js", + "tokens-balance": "node examples/tokens-balance.js", "contract-interaction": "node examples/contract-interaction.js", "create-account-from-seed": "node examples/create-account-from-seed.js", - "create-account": "node examples/create-account.js", + "create-subaccount": "node examples/create-subaccount.js", + "create-tla": "node examples/create-tla.js", "delete-account": "node examples/delete-account.js", + "deploy-contract": "node examples/deploy-contract.js", "keys": "node examples/keys.js", "manual-sign": "node examples/manual-sign.js", "rpc-failover": "node examples/rpc-failover.js", From 51dd2b52f7f0362e19775615b53cb4824245fc42 Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Fri, 9 May 2025 19:19:13 +0200 Subject: [PATCH 11/12] fix: examples --- javascript/examples/account-details.js | 3 +- javascript/examples/batch-actions.js | 1 + javascript/examples/contract-interaction.js | 4 +- javascript/examples/manual-sign.js | 41 ++++++++++-- javascript/examples/rpc-failover.js | 14 ++-- javascript/examples/send-tokens.js | 43 +++++++------ .../examples/simultaneous-transactions.js | 64 +++++++++++++------ javascript/examples/tokens-balance.js | 31 +++------ javascript/examples/utils.js | 7 +- javascript/package.json | 10 +-- 10 files changed, 134 insertions(+), 84 deletions(-) diff --git a/javascript/examples/account-details.js b/javascript/examples/account-details.js index 85941ef..81af1a7 100644 --- a/javascript/examples/account-details.js +++ b/javascript/examples/account-details.js @@ -6,9 +6,8 @@ const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -const rpcBalance = await provider.viewAccountBalance("example-account.testnet") const rpcState = await provider.viewAccount("example-account.testnet"); -console.log({ rpcBalance, rpcState }); +console.log({ rpcState }); // Option 2: Use an Account object const account = new Account("example-account.testnet", provider); diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index 3aa23d1..9abffde 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -28,4 +28,5 @@ const batchActionsResult = await account.signAndSendTransaction({ actionCreators.transfer(parseNearAmount("0.1")) ], }); + console.log(batchActionsResult); diff --git a/javascript/examples/contract-interaction.js b/javascript/examples/contract-interaction.js index 67fdad4..dc52284 100644 --- a/javascript/examples/contract-interaction.js +++ b/javascript/examples/contract-interaction.js @@ -20,7 +20,7 @@ const totalMessages = await provider.callFunction( {} ); -console.log(totalMessages); +console.log({ totalMessages }); // Create a signer from a private key string const privateKey = process.env.PRIVATE_KEY; @@ -37,4 +37,4 @@ const result = await account.callFunction({ args: { text: "Hello, world!" }, }); -console.log(result); \ No newline at end of file +console.log({ result }); \ No newline at end of file diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 10757d8..9a2a351 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -1,4 +1,5 @@ import { JsonRpcProvider } from "@near-js/providers"; +import { Account } from "@near-js/accounts"; import { KeyPairSigner } from "@near-js/signers"; import { actionCreators, createTransaction } from "@near-js/transactions"; import { parseNearAmount, baseDecode } from "@near-js/utils"; @@ -9,29 +10,30 @@ dotenv.config({ path: "../.env" }); const accountId = process.env.ACCOUNT_ID; -// Create a connection to testnet RPC +// Create a provider for testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create a signer from a private key string +// Assume there is a signer that will sign the transaction const privateKey = process.env.PRIVATE_KEY; const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +// We only need to know the public key of the signer const signerPublicKey = await signer.getPublicKey(); -// Get the nonce of the key -const accessKey = await provider.viewAccessKey(accountId, signerPublicKey); +// We create a transaction manually +// 1. Get the nonce of the key +const accessKey = await provider.viewAccessKey(accountId, signerPublicKey); const nonce = ++accessKey.nonce; -// Get a recent block hash +// 2. Get a recent block hash const recentBlockHash = baseDecode(accessKey.block_hash); -// Construct actions +// 3. Construct the transaction const actions = [actionCreators.transfer(parseNearAmount("0.1"))]; -// Construct transaction const transaction = createTransaction( accountId, signerPublicKey, @@ -41,9 +43,34 @@ const transaction = createTransaction( recentBlockHash ); +// Sign and send const [txHash, signedTransaction] = await signer.signTransaction(transaction); console.log(Buffer.from(txHash).toString("hex")); // Send transaction const sendTransactionResult = await provider.sendTransaction(signedTransaction); console.log(sendTransactionResult); + + +/** + * We can also simply instantiate an account object (that does not require a signer) + * and use let it construct the transaction for us. + */ + +// 1. Instantiate account +const account = new Account(accountId, provider); + +// 2. Create transaction +const transaction2 = await account.createTransaction( + "receiver-account.testnet", + actions, + signerPublicKey +) + +// 3. Sign transaction +const [txHash2, signedTransaction2] = await signer.signTransaction(transaction2); +console.log(Buffer.from(txHash2).toString("hex")); + +// 4. Send transaction +const sendTransactionResult2 = await provider.sendTransaction(signedTransaction2); +console.log(sendTransactionResult2); diff --git a/javascript/examples/rpc-failover.js b/javascript/examples/rpc-failover.js index 862c0a3..21eb60b 100644 --- a/javascript/examples/rpc-failover.js +++ b/javascript/examples/rpc-failover.js @@ -1,9 +1,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider, FailoverRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { NearToken } from "@near-js/tokens"; - -const NEAR = new NearToken(); +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -33,9 +31,11 @@ const accountId = process.env.ACCOUNT_ID; const account = new Account(accountId, provider, signer); // example-account.testnet // Test the signer with transferring 1 NEAR -const sendTokensResult = await account.transferToken( - NEAR, - NEAR.toUnits("0.1"), - "receiver-account.testnet" +const sendTokensResult = await account.transfer( + { + token: NEAR, + amount: NEAR.toUnits("0.1"), // Amount of NEAR being sent + receiverId: "receiver-account.testnet", // Receiver account ID + } ); console.log(sendTokensResult); diff --git a/javascript/examples/send-tokens.js b/javascript/examples/send-tokens.js index e786854..4ad6e0a 100644 --- a/javascript/examples/send-tokens.js +++ b/javascript/examples/send-tokens.js @@ -1,15 +1,13 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { FungibleToken, NearToken } from "@near-js/tokens"; -import { USDT as USDTFungibleToken } from "@near-js/tokens/usdt/testnet"; +import { FungibleToken, NEAR } from "@near-js/tokens"; +import { USDT } from "@near-js/tokens/testnet"; import dotenv from "dotenv"; -const NEAR = new NearToken(); -const USDT = new USDTFungibleToken(); const REF = new FungibleToken("ref.fakes.testnet", { - decimals: 8, + decimals: 18, symbol: "REF", }); @@ -30,32 +28,41 @@ const provider = new JsonRpcProvider({ const account = new Account(accountId, provider, signer); // example-account.testnet // ------- Send NEAR tokens to another account ------- -const sendNearTokensResult = await account.transferToken( - NEAR, - NEAR.toUnits("0.1"), // Amount being sent in yoctoNEAR - "receiver-account.testnet" // Receiver account +const sendNearTokensResult = await account.transfer( + { + token: NEAR, + amount: NEAR.toUnits("0.1"), + receiverId: "receiver-account.testnet" + } ); console.log(sendNearTokensResult); // ------- Send USDT tokens to another account ------- // if a user isn't registered, the transfer will fail // it a user is already registered, we'll just get funds back -await account.registerTokenAccount(USDT, "receiver-account.testnet"); +await USDT.registerAccount({ + accountIdToRegister: "receiver-account.testnet", + fundingAccount: account, +}) // Use https://testnet.rhea.finance/#near|usdtt.fakes.testnet to get USDT token -const sendUsdtTokensResult = await account.transferToken( - USDT, - USDT.toUnits("1"), // Amount of USDT being sent - "receiver-account.testnet" // Receiver account +const sendUsdtTokensResult = await account.transfer( + { + token: USDT, + amount: USDT.toUnits("1"), // Amount of USDT being sent + receiverId: "receiver-account.testnet" + } ); console.log(sendUsdtTokensResult); // ------- Send REF tokens to another account ------- // Use https://testnet.rhea.finance/#near|ref.fakes.testnet to get REF tokens -const sendREFsResult = await account.transferToken( - REF, - REF.toUnits("1"), // Amount of Ref tokens being sent - "receiver-account.testnet" // Receiver account +const sendREFsResult = await account.transfer( + { + token: REF, + amount: REF.toUnits("1"), // Amount of REF tokens being sent + receiverId: "receiver-account.testnet" + } ); // we haven't registered a receiver before sending, so it may fail diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index 55c53c3..d255a74 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -1,6 +1,8 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; +import { actionCreators, createTransaction } from "@near-js/transactions"; +import { baseDecode } from "@near-js/utils"; import dotenv from "dotenv"; @@ -9,32 +11,58 @@ const privateKey = process.env.PRIVATE_KEY; const accountId = process.env.ACCOUNT_ID; // Create a signer from a private key string -const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2... +const signer = KeyPairSigner.fromSecretKey(privateKey); +const signerPublicKey = await signer.getPublicKey(); // Create a connection to testnet RPC const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); -// Create an account object -const account = new Account(accountId, provider, signer); // example-account.testnet +// 1. Get information about the access key +const accessKey = await provider.viewAccessKey(accountId, signerPublicKey); -// Send independent transactions simultaneously to different receivers -// Prepare the transactions -const tx1 = account.callFunction({ - contractId: "guestbook.near-examples.testnet", - methodName: "add_message", - args: { text: "Hello, world!" }, - gas: "100000000000000", -}); +// 2. Get a recent block hash +const recentBlockHash = baseDecode(accessKey.block_hash); -const tx2 = account.callFunction({ - contractId: "counter.near-examples.testnet", - methodName: "increment", - args: {}, - gas: "100000000000000", -}); +// 3. Construct the transactions +let actions = [actionCreators.functionCall("add_message", { text: "Hello, world!" }, "30000000000000", 0)]; + +let nonce = ++accessKey.nonce; + +const addMessage = createTransaction( + accountId, + signerPublicKey, + "guestbook.near-examples.testnet", + nonce, + actions, + recentBlockHash +); + +// increment nonce so there are no collisions +nonce = nonce + 1n; + +actions = [actionCreators.functionCall("increment", {}, "30000000000000", 0)] +const increment = createTransaction( + accountId, + signerPublicKey, + "counter.near-examples.testnet", + nonce, + actions, + recentBlockHash +); + +// 4. Sign the transactions +const [txHash1, signedTransaction1] = await signer.signTransaction(addMessage); +const [txHash2, signedTransaction2] = await signer.signTransaction(increment); + +console.log(Buffer.from(txHash1).toString("hex")); +console.log(Buffer.from(txHash2).toString("hex")); + +// 5. Send the transactions +const tx1 = provider.sendTransaction(signedTransaction1); +const tx2 = provider.sendTransaction(signedTransaction2); -// Send the transactions simultaneously +// Wait for them to finish const transactionsResults = await Promise.all([tx1, tx2]); console.log(transactionsResults); diff --git a/javascript/examples/tokens-balance.js b/javascript/examples/tokens-balance.js index 2e5e086..2ffe6ef 100644 --- a/javascript/examples/tokens-balance.js +++ b/javascript/examples/tokens-balance.js @@ -1,14 +1,12 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; -import { FungibleToken, NearToken } from "@near-js/tokens"; -import { USDT as USDTFungibleToken } from "@near-js/tokens/usdt/testnet"; +import { FungibleToken, NEAR } from "@near-js/tokens"; +import { USDT } from "@near-js/tokens/testnet"; import dotenv from "dotenv"; -const NEAR = new NearToken(); -const USDT = new USDTFungibleToken(); const REF = new FungibleToken("ref.fakes.testnet", { - decimals: 8, + decimals: 18, symbol: "REF", }); @@ -22,28 +20,19 @@ const provider = new JsonRpcProvider({ }); // Create an account object -const account = new Account(accountId, provider); // example-account.testnet - -// ------- Fetch NEAR tokens formatted balance ------- -const nearTokensBalance = await account.getFormattedTokenBalance(NEAR); -console.log("NEAR: ", nearTokensBalance); - -// ------- Fetch USDT tokens formatted balance ------- -const usdtTokensBalance = await account.getFormattedTokenBalance(USDT); -console.log("USDT: ", usdtTokensBalance); - -// ------- Fetch REF tokens formatted balance ------- -const refTokensBalance = await account.getFormattedTokenBalance(REF); -console.log("REF: ", refTokensBalance); +const account = new Account(accountId, provider); // ------- Fetch NEAR tokens balance in the smallest units as BigInt ------- -const nearTokensBalanceInt = await account.getTokenBalance(NEAR); +const nearTokensBalanceInt = await account.getBalance(NEAR); console.log("NEAR as units: ", nearTokensBalanceInt); +console.log("NEAR: ", NEAR.toDecimal(nearTokensBalanceInt)); // ------- Fetch USDT tokens balance in the smallest units as BigInt ------- -const usdtTokensBalanceInt = await account.getTokenBalance(USDT); +const usdtTokensBalanceInt = await account.getBalance(USDT); console.log("USDT as units: ", usdtTokensBalanceInt); +console.log("USDT: ", USDT.toDecimal(usdtTokensBalanceInt)); // ------- Fetch REF tokens balance in the smallest units as BigInt ------- -const refTokensBalanceInt = await account.getTokenBalance(REF); +const refTokensBalanceInt = await account.getBalance(REF); console.log("REF as units: ", refTokensBalanceInt); +console.log("REF: ", REF.toDecimal(refTokensBalanceInt)); diff --git a/javascript/examples/utils.js b/javascript/examples/utils.js index 0c69168..f7ee0cb 100644 --- a/javascript/examples/utils.js +++ b/javascript/examples/utils.js @@ -1,5 +1,5 @@ import { parseNearAmount, formatNearAmount } from "@near-js/utils"; -import { USDT } from "@near-js/tokens/usdt/testnet"; +import { USDT } from "@near-js/tokens/testnet"; // Convert NEAR amount into yoctoNEAR const amountInYoctoNear = parseNearAmount("0.1"); @@ -9,11 +9,10 @@ console.log(amountInYoctoNear); const amountInNear = formatNearAmount("1000000000000000000000000"); console.log(amountInNear); -const usdt = new USDT(); // convert USDT amount into base units -const amountInUsdtUnits = usdt.toUnits("0.1").toString(); +const amountInUsdtUnits = USDT.toUnits("0.1").toString(); console.log(amountInUsdtUnits); // convert base units into USDT -const amountInUsdt = usdt.toAmount("12300000"); +const amountInUsdt = USDT.toDecimal("12300000"); console.log(amountInUsdt); diff --git a/javascript/package.json b/javascript/package.json index 49e812c..06e31ef 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -15,24 +15,24 @@ "near-seed-phrase": "^0.2.1" }, "scripts": { - "credentials-directory": "node examples/keystore-options/credentials-directory.js", - "credentials-file": "node examples/keystore-options/credentials-file.js", - "private-key-string": "node examples/keystore-options/private-key-string.js", - "seed-phrase": "node examples/keystore-options/seed-phrase.js", "account-details": "node examples/account-details.js", "batch-actions": "node examples/batch-actions.js", - "tokens-balance": "node examples/tokens-balance.js", "contract-interaction": "node examples/contract-interaction.js", "create-account-from-seed": "node examples/create-account-from-seed.js", "create-subaccount": "node examples/create-subaccount.js", "create-tla": "node examples/create-tla.js", + "credentials-directory": "node examples/keystore-options/credentials-directory.js", + "credentials-file": "node examples/keystore-options/credentials-file.js", "delete-account": "node examples/delete-account.js", "deploy-contract": "node examples/deploy-contract.js", "keys": "node examples/keys.js", "manual-sign": "node examples/manual-sign.js", + "private-key-string": "node examples/keystore-options/private-key-string.js", "rpc-failover": "node examples/rpc-failover.js", + "seed-phrase": "node examples/keystore-options/seed-phrase.js", "send-tokens": "node examples/send-tokens.js", "simultaneous-transactions": "node examples/simultaneous-transactions.js", + "tokens-balance": "node examples/tokens-balance.js", "utils": "node examples/utils.js", "verify-signature": "node examples/verify-signature/verify-signature.js" }, From 5c65c07f4c3fde5f6b0a23badb33c59818d28f18 Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Fri, 9 May 2025 19:26:52 +0200 Subject: [PATCH 12/12] fix: simplified --- javascript/examples/batch-actions.js | 4 ++-- javascript/examples/create-account-from-seed.js | 5 ++--- javascript/examples/create-subaccount.js | 4 ++-- javascript/examples/create-tla.js | 4 ++-- javascript/examples/delete-account.js | 4 ++-- javascript/examples/keys.js | 4 ++-- javascript/examples/manual-sign.js | 5 +++-- javascript/examples/simultaneous-transactions.js | 1 - javascript/examples/utils.js | 6 +++--- 9 files changed, 18 insertions(+), 19 deletions(-) diff --git a/javascript/examples/batch-actions.js b/javascript/examples/batch-actions.js index 9abffde..5d28809 100644 --- a/javascript/examples/batch-actions.js +++ b/javascript/examples/batch-actions.js @@ -1,8 +1,8 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; import { actionCreators } from "@near-js/transactions"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; dotenv.config({ path: "../.env" }); @@ -25,7 +25,7 @@ const batchActionsResult = await account.signAndSendTransaction({ receiverId: "counter.near-examples.testnet", actions: [ actionCreators.functionCall("increment", {}, "30000000000000", 0), - actionCreators.transfer(parseNearAmount("0.1")) + actionCreators.transfer(NEAR.toUnits("0.1")) ], }); diff --git a/javascript/examples/create-account-from-seed.js b/javascript/examples/create-account-from-seed.js index 0f86172..2ed1215 100644 --- a/javascript/examples/create-account-from-seed.js +++ b/javascript/examples/create-account-from-seed.js @@ -1,8 +1,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; - +import { NEAR } from "@near-js/tokens"; import { generateSeedPhrase } from "near-seed-phrase"; import dotenv from "dotenv"; @@ -24,5 +23,5 @@ console.log(`Created key ${secretKey} with seed phrase ${seedPhrase}`); await account.createTopLevelAccount( `acc-${Date.now()}.testnet`, publicKey, - parseNearAmount("0.1") + NEAR.toUnits("0.1") ); diff --git a/javascript/examples/create-subaccount.js b/javascript/examples/create-subaccount.js index 964596b..db82598 100644 --- a/javascript/examples/create-subaccount.js +++ b/javascript/examples/create-subaccount.js @@ -2,7 +2,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; import { KeyPair } from "@near-js/crypto"; -import { parseNearAmount } from "@near-js/utils"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -30,7 +30,7 @@ const prefix = Date.now().toString(); await account.createSubAccount( prefix, // prefix for the sub account (e.g. sub.near.testnet) publicKey, // ed25519:2ASWc... - parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR + NEAR.toUnits("0.1") // Initial balance for new account in yoctoNEAR ); console.log(`Created ${prefix}.${accountId} with private key ${keyPair.toString()}`) diff --git a/javascript/examples/create-tla.js b/javascript/examples/create-tla.js index 9088916..90e8824 100644 --- a/javascript/examples/create-tla.js +++ b/javascript/examples/create-tla.js @@ -2,7 +2,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPair } from "@near-js/crypto"; import { KeyPairSigner } from "@near-js/signers"; -import { parseNearAmount } from "@near-js/utils"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -31,7 +31,7 @@ const publicKey = keyPair.getPublicKey().toString(); await account.createTopLevelAccount( newAccountId, publicKey, - parseNearAmount("0.1") + NEAR.toUnits("0.1") ); console.log(`Created ${newAccountId} with private key ${keyPair.toString()}`) diff --git a/javascript/examples/delete-account.js b/javascript/examples/delete-account.js index ab9a720..88dbca8 100644 --- a/javascript/examples/delete-account.js +++ b/javascript/examples/delete-account.js @@ -2,7 +2,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; import { KeyPair } from "@near-js/crypto"; -import { parseNearAmount } from "@near-js/utils"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -27,7 +27,7 @@ const deleteMe = `${Date.now()}.testnet`; await master.createTopLevelAccount( deleteMe, keyPair.getPublicKey().toString(), - parseNearAmount("0.1") + NEAR.toUnits("0.1") ); // Create an account object for the new account with corresponding signer diff --git a/javascript/examples/keys.js b/javascript/examples/keys.js index 8ce6b90..8b7393f 100644 --- a/javascript/examples/keys.js +++ b/javascript/examples/keys.js @@ -2,7 +2,7 @@ import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; import { KeyPair } from "@near-js/crypto"; -import { parseNearAmount } from "@near-js/utils"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -48,7 +48,7 @@ await account.addFunctionCallAccessKey( fnKeyPair.getPublicKey(), // The new public key ed25519:2ASWc... "example-contract.testnet", // Contract this key is allowed to call (optional) ["example_method"], // Methods this key is allowed to call (optional) - parseNearAmount("0.25") // Gas allowance key can use to call methods (optional) + NEAR.toUnits("0.25") // Gas allowance key can use to call methods (optional) ); console.log(`Added FCK ${fnKeyPair.toString()}`); diff --git a/javascript/examples/manual-sign.js b/javascript/examples/manual-sign.js index 9a2a351..ffa41f0 100644 --- a/javascript/examples/manual-sign.js +++ b/javascript/examples/manual-sign.js @@ -2,7 +2,8 @@ import { JsonRpcProvider } from "@near-js/providers"; import { Account } from "@near-js/accounts"; import { KeyPairSigner } from "@near-js/signers"; import { actionCreators, createTransaction } from "@near-js/transactions"; -import { parseNearAmount, baseDecode } from "@near-js/utils"; +import { baseDecode } from "@near-js/utils"; +import { NEAR } from "@near-js/tokens"; import dotenv from "dotenv"; @@ -32,7 +33,7 @@ const nonce = ++accessKey.nonce; const recentBlockHash = baseDecode(accessKey.block_hash); // 3. Construct the transaction -const actions = [actionCreators.transfer(parseNearAmount("0.1"))]; +const actions = [actionCreators.transfer(NEAR.toUnits("0.1"))]; const transaction = createTransaction( accountId, diff --git a/javascript/examples/simultaneous-transactions.js b/javascript/examples/simultaneous-transactions.js index d255a74..e371439 100644 --- a/javascript/examples/simultaneous-transactions.js +++ b/javascript/examples/simultaneous-transactions.js @@ -1,4 +1,3 @@ -import { Account } from "@near-js/accounts"; import { JsonRpcProvider } from "@near-js/providers"; import { KeyPairSigner } from "@near-js/signers"; import { actionCreators, createTransaction } from "@near-js/transactions"; diff --git a/javascript/examples/utils.js b/javascript/examples/utils.js index f7ee0cb..015d6a6 100644 --- a/javascript/examples/utils.js +++ b/javascript/examples/utils.js @@ -1,12 +1,12 @@ -import { parseNearAmount, formatNearAmount } from "@near-js/utils"; import { USDT } from "@near-js/tokens/testnet"; +import { NEAR } from "@near-js/tokens"; // Convert NEAR amount into yoctoNEAR -const amountInYoctoNear = parseNearAmount("0.1"); +const amountInYoctoNear = NEAR.toUnits("0.1"); console.log(amountInYoctoNear); // Convert yoctoNEAR amount into NEAR -const amountInNear = formatNearAmount("1000000000000000000000000"); +const amountInNear = NEAR.toDecimal("1000000000000000000000000"); console.log(amountInNear); // convert USDT amount into base units