### Quick Start: Interact with NEAR Blockchain Source: https://github.com/near/near-api-js/blob/master/README.md Demonstrates creating a provider, making read-only calls to a contract, and signing transactions to modify state. ```typescript import { Account, JsonRpcProvider, teraToGas, KeyPairString, nearToYocto } from "near-api-js"; // Create a testnet provider const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); // For read only calls, you can use the provider directly const messages = await provider.callFunction({ contractId: 'guestbook.near-examples.testnet', method: "get_messages", args: {}, }); console.log(messages); // To modify state, you need an account to sign the transaction const accountId: string = 'example.testnet'; const privateKey = 'ed25519:5nM...' as KeyPairString; const account = new Account(accountId, provider, privateKey); // Call the contract await account.callFunction({ contractId: 'guestbook.near-examples.testnet', methodName: "add_message", args: { text: "Hello!" }, gas: teraToGas('30'), deposit: nearToYocto('0.1'), }); ``` -------------------------------- ### Install near-api-js Source: https://github.com/near/near-api-js/blob/master/README.md Add near-api-js to your project using npm, yarn, or pnpm. ```bash npm install near-api-js # or yarn add near-api-js # or pnpm add near-api-js ``` -------------------------------- ### Manage Accounts with Account Class Source: https://context7.com/near/near-api-js/llms.txt The Account class is used for state-changing operations. It can be constructed with a provider URL string, a Provider instance, or an encoded private key string. This example shows how to get account state. ```typescript import { Account, JsonRpcProvider } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }); const privateKey = 'ed25519:5nMSA...' as KeyPairString; // Shorthand: pass URL string + private key string directly const account = new Account('alice.testnet', 'https://test.rpc.fastnear.com', privateKey); // Or use explicit provider + key const account2 = new Account('alice.testnet', provider, privateKey); // Get account state (balance, storage, contract hash) const state = await account.getState(); console.log(state.balance.available); // bigint in yoctoNEAR console.log(state.balance.total); // includes staked + unstaked console.log(state.storageUsage); // bytes used for storage ``` -------------------------------- ### Failover RPC Provider Setup in near-api-js Source: https://github.com/near/near-api-js/blob/master/README.md Illustrates setting up a FailoverRpcProvider with multiple NEAR network RPC endpoints. If the primary endpoint fails, the provider automatically attempts to use the next available endpoint. ```typescript import { JsonRpcProvider, FailoverRpcProvider } from 'near-api-js'; const provider = new FailoverRpcProvider([ new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }), new JsonRpcProvider({ url: 'https://rpc.mainnet.pagoda.co' }), ]); ``` -------------------------------- ### Connect to NEAR RPC with JsonRpcProvider Source: https://context7.com/near/near-api-js/llms.txt Use JsonRpcProvider to connect to NEAR RPC nodes. It handles retries and error parsing. This example shows connecting to testnet and mainnet, and performing a read-only contract call. ```typescript import { JsonRpcProvider } from 'near-api-js'; // Connect to testnet const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com', }); // Connect to mainnet with custom retry settings const mainnetProvider = new JsonRpcProvider( { url: 'https://rpc.mainnet.near.org' }, { retries: 5, wait: 200, backoff: 2.0 } ); // Check network status const status = await provider.viewNodeStatus(); console.log(status.chain_id); // "testnet" // Read-only contract call (no signing needed) const messages = await provider.callFunction<{ text: string; sender: string }>({ contractId: 'guestbook.near-examples.testnet', method: 'get_messages', args: { from_index: 0, limit: 10 }, }); console.log(messages); // [{ text: "Hello!", sender: "alice.testnet" }, ...] ``` -------------------------------- ### Query Token Balance with Account.getBalance Source: https://context7.com/near/near-api-js/llms.txt Retrieve the available balance for the native NEAR token or any FungibleToken instance. This example shows fetching both native NEAR and USDC balances. ```typescript import { Account, JsonRpcProvider } from 'near-api-js'; import { USDC } from 'near-api-js/tokens/mainnet'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'alice.near', new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }), 'ed25519:5nM...' as KeyPairString ); // Native NEAR balance (yoctoNEAR) const nearBalance = await account.getBalance(); console.log(nearBalance); // 5000000000000000000000000n (= 5 NEAR) // Fungible token balance (USDC, 6 decimals) const usdcBalance = await account.getBalance(USDC); console.log(USDC.toDecimal(usdcBalance, 2)); // "12.34" ``` -------------------------------- ### Create New Accounts with Account.createAccount and createSubAccount Source: https://context7.com/near/near-api-js/llms.txt Use `createAccount` to create a new top-level account (e.g., `bob.near`) via the registrar contract, or `createSubAccount` to create a sub-account directly (e.g., `sub.alice.testnet`). Both require a public key for the new account and a NEAR amount to fund it. ```typescript import { Account, JsonRpcProvider, KeyPair, nearToYocto } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const alice = new Account( 'alice.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); // Generate a key pair for the new account const newKey = KeyPair.fromRandom('ed25519'); console.log(newKey.getPublicKey().toString()); // ed25519:... // Create a sub-account of alice.testnet await alice.createSubAccount({ accountOrPrefix: 'sub', // creates sub.alice.testnet publicKey: newKey.getPublicKey(), nearToTransfer: nearToYocto('1'), // fund with 1 NEAR }); // Create an independent account (requires TLA registration) await alice.createAccount({ newAccountId: 'newbob.testnet', publicKey: newKey.getPublicKey(), nearToTransfer: nearToYocto('2'), }); ``` -------------------------------- ### Provider — View Methods Source: https://context7.com/near/near-api-js/llms.txt `JsonRpcProvider` and `FailoverRpcProvider` expose methods for inspecting chain state. ```APIDOC ## Provider View Methods ### Description `JsonRpcProvider` and `FailoverRpcProvider` expose a rich set of read-only query methods for inspecting chain state. ### Methods #### `viewAccount(accountId: string)` - **Description**: View account state. - **Response**: `accountView` object containing `amount` (bigint yoctoNEAR). #### `viewAccessKey(accountId: string, publicKey: string)` - **Description**: View a specific access key. - **Response**: `key` object containing `nonce` and `permission`. #### `viewBlock(finality: 'final' | 'optimistic' | 'near-final')` - **Description**: View block information. - **Response**: `block` object containing `header` with `height` and `hash`. #### `viewGasPrice()` - **Description**: View the current gas price. - **Response**: `gasPrice` object containing `gas_price`. #### `viewTransactionStatus(txHash: string, accountId: string, waitUntil?: 'PENDING' | 'EXECUTED' | 'ABORTED')` - **Description**: View the status of a transaction. - **Response**: `txStatus` object containing `status`. #### `viewContractState(contractId: string, prefix?: string)` - **Description**: View contract state (key-value storage). - **Response**: `contractState` object containing `values` (array of `{ key: string, value: string }`). #### `viewValidators()` - **Description**: Get validator information. - **Response**: `validators` object containing `current_validators`. #### `getCurrentEpochSeatPrice()` - **Description**: Get the current epoch seat prices. - **Response**: `seatPrice` (bigint) - minimum stake to become a validator. ### Request Example ```typescript import { JsonRpcProvider } from 'near-api-js'; const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }); // View account state const accountView = await provider.viewAccount({ accountId: 'alice.testnet' }); console.log(accountView.amount); // bigint yoctoNEAR // View a specific access key const key = await provider.viewAccessKey({ accountId: 'alice.testnet', publicKey: 'ed25519:abc...', }); console.log(key.nonce, key.permission); // View block const block = await provider.viewBlock({ finality: 'final' }); console.log(block.header.height, block.header.hash); // View gas price const gasPrice = await provider.viewGasPrice(); console.log(gasPrice.gas_price); // View transaction status const txStatus = await provider.viewTransactionStatus({ txHash: 'ABC123...', accountId: 'alice.testnet', waitUntil: 'EXECUTED', }); console.log(txStatus.status); // View contract state (key-value storage) const contractState = await provider.viewContractState({ contractId: 'my-contract.testnet', prefix: 'account:', }); console.log(contractState.values); // [{ key: '...', value: '...' }, ...] // Validator information const validators = await provider.viewValidators(); console.log(validators.current_validators.length); // Epoch seat prices const seatPrice = await provider.getCurrentEpochSeatPrice(); console.log(seatPrice); // bigint: minimum stake to become validator ``` ``` -------------------------------- ### Account.createAccount / createSubAccount Source: https://context7.com/near/near-api-js/llms.txt Creates a new top-level account (e.g., `bob.near`) via the registrar contract, or a sub-account directly (e.g., `sub.alice.testnet`). ```APIDOC ## Account.createAccount / createSubAccount — Create New Accounts Creates a new top-level account (e.g., `bob.near`) via the registrar contract, or a sub-account directly (e.g., `sub.alice.testnet`). ```typescript import { Account, JsonRpcProvider, KeyPair, nearToYocto } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const alice = new Account( 'alice.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); // Generate a key pair for the new account const newKey = KeyPair.fromRandom('ed25519'); console.log(newKey.getPublicKey().toString()); // ed25519:... // Create a sub-account of alice.testnet await alice.createSubAccount({ accountOrPrefix: 'sub', // creates sub.alice.testnet publicKey: newKey.getPublicKey(), nearToTransfer: nearToYocto('1'), // fund with 1 NEAR }); // Create an independent account (requires TLA registration) await alice.createAccount({ newAccountId: 'newbob.testnet', publicKey: newKey.getPublicKey(), nearToTransfer: nearToYocto('2'), }); ``` ``` -------------------------------- ### Decoupled Transaction Signing and Broadcasting in near-api-js Source: https://github.com/near/near-api-js/blob/master/README.md Shows how to create, sign, and broadcast NEAR transactions independently. This is useful for offline signing or scenarios where signing and sending are separate operations. Ensure you have the necessary imports and initialize the provider and account correctly. ```typescript import { JsonRpcProvider, Account, KeyPairSigner, actions, nearToYocto, KeyPairString } from "near-api-js"; const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); // You can create a transaction only knowing the accountId and public key const publicKey = ''; const accountId = ''; const account = new Account(accountId, provider); const transaction = await account.createTransaction({ receiverId: "receiver-account.testnet", actions: [actions.transfer(nearToYocto("0.1"))], publicKey: publicKey }); // Whoever holds the private key can sign the transaction const signer = KeyPairSigner.fromSecretKey(privateKey as KeyPairString); const signResult = await signer.signTransaction(transaction); console.log(signResult.signedTransaction); // Anybody can send the signed transaction to the network const sendTransactionResult = await provider.sendTransaction(signResult.signedTransaction); console.log(sendTransactionResult); ``` -------------------------------- ### Create Typed Contract Wrappers with ABI Source: https://context7.com/near/near-api-js/llms.txt Use the `Contract` class to create type-safe proxies for NEAR contracts based on their ABI. This enables strongly-typed view and call methods, improving developer experience and reducing errors. Ensure the ABI definition accurately reflects the contract's functions. ```typescript import { Contract, JsonRpcProvider, Account } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; // NEAR ABI definition (generated by near-sdk or cargo-near) const abi = { schema_version: '0.4.0', body: { functions: [ { name: 'get_greeting', kind: 'view', result: { serialization_type: 'json', type_schema: { type: 'string' } }, }, { name: 'set_greeting', kind: 'call', params: { serialization_type: 'json', args: [{ name: 'greeting', type_schema: { type: 'string' } }], }, }, ], root_schema: { $schema: 'http://json-schema.org/draft-07/schema#', definitions: {} }, }, } as const; const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }); const contract = new Contract({ abi, provider, contractId: 'hello.near-examples.testnet' }); // Typed view call — TypeScript knows this returns string const greeting = await contract.view.get_greeting(); console.log(greeting); // "Hello, NEAR!" // Typed call — TypeScript enforces { greeting: string } args const account = new Account( 'alice.testnet', provider, 'ed25519:5nM...' as KeyPairString ); await contract.call.set_greeting({ args: { greeting: 'Hello from ABI!' }, account }); ``` -------------------------------- ### Typed Contract Function Calls in near-api-js Source: https://github.com/near/near-api-js/blob/master/README.md Demonstrates how to make typed contract function calls, specifying the expected return type T for enhanced type safety. Requires initializing a JsonRpcProvider and an Account. ```typescript const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); const account = new Account("accountId", provider, "privateKey"); await provider.callFunction() await account.callFunction() ``` -------------------------------- ### Create and Relay Meta-Transactions (Gasless) Source: https://context7.com/near/near-api-js/llms.txt Enables gasless transactions using NEP-366 delegate actions. The user account signs the meta-transaction, and a relayer pays the gas to broadcast it. `blockHeightTtl` specifies the validity period. ```typescript import { Account, JsonRpcProvider, actions, nearToYocto } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; // User's account (signs the meta-tx, pays no gas) const userAccount = new Account( 'user.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:userKey...' as KeyPairString ); // Build and sign the meta-transaction const { signedDelegate } = await userAccount.createSignedMetaTransaction({ receiverId: 'contract.testnet', actions: [ actions.functionCall('free_mint', { recipient: 'user.testnet' }, 30_000_000_000_000n, 0n), ], blockHeightTtl: 200, // valid for 200 blocks (~4 minutes) }); // Relayer account pays gas to broadcast it const relayer = new Account( 'relayer.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:relayerKey...' as KeyPairString ); const result = await relayer.relayMetaTransaction(signedDelegate); console.log(result.transaction.hash); ``` -------------------------------- ### Account.addFullAccessKey / addFunctionCallAccessKey / deleteKey Source: https://context7.com/near/near-api-js/llms.txt Manages access keys for a NEAR account. Full access keys grant broad permissions, while function call keys offer restricted access with gas allowances. Keys can also be deleted. ```APIDOC ## Account.addFullAccessKey / addFunctionCallAccessKey / deleteKey ### Description Adds or removes access keys from an account. Full access keys can do anything; function call keys are restricted to specific methods and have a gas allowance. ### Methods - `addFullAccessKey(publicKey: PublicKey)` - `addFunctionCallAccessKey(options: { publicKey: PublicKey, contractId: string, methodNames: string[], allowance: bigint })` - `deleteKey(publicKey: PublicKey)` - `getAccessKeyList(): Promise<{ keys: Array<{ public_key: PublicKey, access_key: { nonce: number, permission: object } }> }>` ### Parameters #### `addFullAccessKey` - **publicKey** (PublicKey) - Required - The public key of the new access key. #### `addFunctionCallAccessKey` - **publicKey** (PublicKey) - Required - The public key of the new access key. - **contractId** (string) - Required - The ID of the contract the key can access. - **methodNames** (string[]) - Required - An array of method names the key can call. - **allowance** (bigint) - Required - The gas allowance for the function call key. #### `deleteKey` - **publicKey** (PublicKey) - Required - The public key of the access key to delete. ### Request Example ```typescript // Add a full access key await account.addFullAccessKey(newKey.getPublicKey()); // Add a function call key await account.addFunctionCallAccessKey({ publicKey: newKey.getPublicKey(), contractId: 'app.testnet', methodNames: ['vote', 'register'], allowance: 250_000_000_000_000_000_000_000n, }); // Remove a key await account.deleteKey(newKey.getPublicKey()); // Retrieve all keys const keyList = await account.getAccessKeyList(); ``` ### Response #### Success Response (200) - **keys** (Array) - A list of access keys associated with the account. ``` -------------------------------- ### Account.deployContract Source: https://context7.com/near/near-api-js/llms.txt Deploys a compiled WASM smart contract to a NEAR account, replacing any existing contract. This method is crucial for deploying new or updated smart contracts. ```APIDOC ## Account.deployContract ### Description Deploys a compiled WASM contract to the account, replacing any existing contract. ### Method `deployContract(contractBytes: Uint8Array)` ### Parameters #### Request Body - **contractBytes** (Uint8Array) - Required - The compiled WASM bytecode of the smart contract. ### Request Example ```typescript import { Account, JsonRpcProvider } from 'near-api-js'; import { readFileSync } from 'fs'; const wasmCode = readFileSync('./contract.wasm'); const result = await account.deployContract(new Uint8Array(wasmCode)); ``` ### Response #### Success Response (200) - **transaction_outcome** (object) - Details of the transaction outcome, including the block hash. ### Response Example ```json { "transaction_outcome": { "block_hash": "..." } } ``` ``` -------------------------------- ### Decoupled Transaction Signing Workflow Source: https://context7.com/near/near-api-js/llms.txt Build, sign, and broadcast transactions in separate steps. This is useful for signing transactions on offline devices. Ensure you have a JsonRpcProvider, public and private keys, and the recipient's account ID. ```typescript import { Account, JsonRpcProvider, KeyPairSigner, actions, nearToYocto } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }); const publicKey = 'ed25519:abc...' as KeyPairString; // Step 1: Build an unsigned transaction (only public key needed) const unsignedAccount = new Account('alice.testnet', provider); const tx = await unsignedAccount.createTransaction({ receiverId: 'bob.testnet', actions: [actions.transfer(nearToYocto('0.5'))], publicKey, }); // Step 2: Sign offline (private key holder) const privateKey = 'ed25519:5nM...' as KeyPairString; const signer = KeyPairSigner.fromSecretKey(privateKey); const { signedTransaction } = await signer.signTransaction(tx); // Step 3: Broadcast the signed transaction from any machine const result = await provider.sendTransaction(signedTransaction); console.log(result.transaction.hash); ``` -------------------------------- ### Submit Raw Transactions with Account.signAndSendTransaction Source: https://context7.com/near/near-api-js/llms.txt This low-level method builds, signs, and broadcasts a transaction containing one or more raw `Action` objects. It automatically handles nonce collisions with retries. You can specify `waitUntil` to control when the method returns and `throwOnFailure` to determine behavior on transaction failure. ```typescript import { Account, JsonRpcProvider, actions, nearToYocto, teraToGas } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'alice.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); // Batch multiple actions in a single transaction const result = await account.signAndSendTransaction({ receiverId: 'my-contract.testnet', actions: [ actions.transfer(nearToYocto('0.5')), actions.functionCall( 'some_method', { key: 'value' }, teraToGas(30), 0n ), ], waitUntil: 'EXECUTED', // wait for full execution throwOnFailure: true, // throw if tx fails }); console.log(result.status); ``` -------------------------------- ### Deploy WASM Contract to NEAR Account Source: https://context7.com/near/near-api-js/llms.txt Deploys a compiled WASM contract to a NEAR account. Use this to replace an existing contract. Ensure the WASM file is correctly read into a Uint8Array. ```typescript import { Account, JsonRpcProvider } from 'near-api-js'; import { readFileSync } from 'fs'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'my-contract.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); const wasmCode = readFileSync('./contract.wasm'); const result = await account.deployContract(new Uint8Array(wasmCode)); console.log('Deployed at block:', result.transaction_outcome.block_hash); // Deploy as a global contract (reusable by multiple accounts) await account.deployGlobalContract(new Uint8Array(wasmCode), 'codeHash'); // Other accounts can then use it: // await otherAccount.useGlobalContract({ codeHash: '...' }); ``` -------------------------------- ### Generate and Manage Ed25519 Key Pairs Source: https://context7.com/near/near-api-js/llms.txt Demonstrates generating random Ed25519 key pairs, deriving implicit addresses, loading keys from strings, and recovering keys from seed phrases. Ensure you handle private keys securely. ```typescript import { KeyPair, keyToImplicitAddress } from 'near-api-js'; import { generateSeedPhrase, parseSeedPhrase } from 'near-api-js/seed-phrase'; // Generate a random Ed25519 key pair const keyPair = KeyPair.fromRandom('ed25519'); console.log(keyPair.toString()); // "ed25519:" console.log(keyPair.getPublicKey().toString()); // "ed25519:" // Derive implicit account address from public key (64-char hex) const implicitAddress = keyToImplicitAddress(keyPair.getPublicKey()); console.log(implicitAddress); // "8f3e5b..." // Load from an encoded string const loaded = KeyPair.fromString('ed25519:5nMSA...' as any); // Generate from a BIP-39 seed phrase const { seedPhrase, keyPair: derivedKey } = generateSeedPhrase(); console.log(seedPhrase); // "word1 word2 ... word12" // Recover key from seed phrase const recoveredKey = parseSeedPhrase(seedPhrase); console.log(recoveredKey.getPublicKey().toString() === derivedKey.getPublicKey().toString()); // true ``` -------------------------------- ### Update Near/Yocto Conversion Utilities Source: https://github.com/near/near-api-js/blob/master/MIGRATION.md The `parseNear` and `formatNear` utility functions have been renamed to `yoctoToNear` and `nearToYocto` respectively and are now imported directly from `near-api-js`. ```typescript import { utils: {parseNear, formatNear} } from 'near-api-js'; ``` ```typescript import { yoctoToNear, nearToYocto } from 'near-api-js'; ``` -------------------------------- ### Manage NEAR Account Access Keys Source: https://context7.com/near/near-api-js/llms.txt Manages access keys for a NEAR account. Use `addFullAccessKey` for unrestricted access, `addFunctionCallAccessKey` for restricted permissions, and `deleteKey` to remove keys. `getAccessKeyList` retrieves all keys. ```typescript import { Account, JsonRpcProvider, KeyPair } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'alice.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); const newKey = KeyPair.fromRandom('ed25519'); // Add a full access key await account.addFullAccessKey(newKey.getPublicKey()); // Add a function call key restricted to specific methods await account.addFunctionCallAccessKey({ publicKey: newKey.getPublicKey(), contractId: 'app.testnet', methodNames: ['vote', 'register'], allowance: 250_000_000_000_000_000_000_000n, // 0.25 NEAR }); // Remove a key await account.deleteKey(newKey.getPublicKey()); // Retrieve all keys for the account const keyList = await account.getAccessKeyList(); console.log(keyList.keys); // [{ public_key, access_key: { nonce, permission } }, ...] ``` -------------------------------- ### Querying NEAR Blockchain State with JsonRpcProvider Source: https://context7.com/near/near-api-js/llms.txt Utilize JsonRpcProvider to view various aspects of the NEAR blockchain state, including account details, access keys, blocks, gas prices, transaction statuses, contract storage, validator information, and epoch seat prices. Requires a JsonRpcProvider instance configured with an RPC URL. ```typescript import { JsonRpcProvider } from 'near-api-js'; const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }); // View account state const accountView = await provider.viewAccount({ accountId: 'alice.testnet' }); console.log(accountView.amount); // bigint yoctoNEAR // View a specific access key const key = await provider.viewAccessKey({ accountId: 'alice.testnet', publicKey: 'ed25519:abc...', }); console.log(key.nonce, key.permission); // View block const block = await provider.viewBlock({ finality: 'final' }); console.log(block.header.height, block.header.hash); // View gas price const gasPrice = await provider.viewGasPrice(); console.log(gasPrice.gas_price); // View transaction status const txStatus = await provider.viewTransactionStatus({ txHash: 'ABC123...', accountId: 'alice.testnet', waitUntil: 'EXECUTED', }); console.log(txStatus.status); // View contract state (key-value storage) const contractState = await provider.viewContractState({ contractId: 'my-contract.testnet', prefix: 'account:', }); console.log(contractState.values); // [{ key: '...', value: '...' }, ...] // Validator information const validators = await provider.viewValidators(); console.log(validators.current_validators.length); // Epoch seat prices const seatPrice = await provider.getCurrentEpochSeatPrice(); console.log(seatPrice); // bigint: minimum stake to become validator ``` -------------------------------- ### Update Gas and Near Conversion in Account Call Source: https://github.com/near/near-api-js/blob/master/MIGRATION.md Demonstrates the use of new gas conversion utilities (`teraToGas`) and updated Near/Yocto conversion utilities (`nearToYocto`) when calling account methods. ```typescript import { utils: {parseNear} } from 'near-api-js'; account.callFunction({ contractId: 'example.testnet', methodName: 'some_method', args: {}, gas: '30000000000000', // 30 TeraGas, maybe? deposit: parseNear('0.1'), // or was formatNear? }); ``` ```typescript import { teraToGas, nearToYocto } from 'near-api-js'; account.callFunction({ contractId: 'example.testnet', methodName: 'some_method', args: {}, gas: teraToGas('30'), // 30 TeraGas deposit: nearToYocto('0.1'), // 0.1 NEAR }); ``` -------------------------------- ### Interact with NEP-141 Fungible Tokens Source: https://context7.com/near/near-api-js/llms.txt The `FungibleToken` class provides a convenient way to interact with NEP-141 compliant tokens on NEAR. It supports common operations like checking balances, transferring tokens, and registering accounts. Pre-built instances for popular tokens like wNEAR, USDC, and USDT are available. ```typescript import { FungibleToken, Account, JsonRpcProvider } from 'near-api-js'; import { USDC, USDT, wNEAR } from 'near-api-js/tokens/mainnet'; import type { KeyPairString } from 'near-api-js'; const provider = new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }); const account = new Account('alice.near', provider, 'ed25519:5nM...' as KeyPairString); // Use a pre-built token const balance = await account.getBalance(USDC); console.log(USDC.toDecimal(balance, 2)); // "42.00" // Define a custom NEP-141 token const myToken = new FungibleToken('token.myapp.near', { name: 'My Token', symbol: 'MYT', decimals: 18, }); // Transfer with ft_transfer_call (triggers ft_on_transfer on receiver contract) await myToken.transferCall({ from: account, receiverId: 'defi-app.near', amount: myToken.toUnits('100'), msg: JSON.stringify({ action: 'deposit' }), }); // Register an account manually await myToken.registerAccount({ accountIdToRegister: 'new-user.near', fundingAccount: account, }); // Check if registered const isReg = await myToken.isAccountRegistered({ accountId: 'new-user.near', provider, }); console.log(isReg); // true ``` -------------------------------- ### Simple Units Conversions Source: https://github.com/near/near-api-js/blob/master/README.md Easily convert between NEAR and yoctoNEAR, and between gas units like TeraGas. ```typescript import { nearToYocto, yoctoToNear, teraToGas, gigaToGas } from 'near-api-js'; await account.callFunction({ contractId: 'example.testnet', methodName: 'some_method', args: {}, gas: teraToGas('30'), // 30 TeraGas deposit: nearToYocto('0.1'), // 0.1 NEAR }); // balance in NEAR with 2 decimals const balance = yoctoToNear(await account.getBalance(), 2); ``` -------------------------------- ### Account.getBalance - Query Token Balance Source: https://context7.com/near/near-api-js/llms.txt Retrieves the available balance of an account for the native NEAR token or any FungibleToken instance. ```APIDOC ## Account.getBalance — Query Token Balance ### Description Returns the available balance of the account for the native NEAR token or any `FungibleToken` instance. ### Usage ```typescript import { Account, JsonRpcProvider } from 'near-api-js'; import { USDC } from 'near-api-js/tokens/mainnet'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'alice.near', new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }), 'ed25519:5nM...' as KeyPairString ); // Native NEAR balance (yoctoNEAR) const nearBalance = await account.getBalance(); console.log(nearBalance); // 5000000000000000000000000n (= 5 NEAR) // Fungible token balance (USDC, 6 decimals) const usdcBalance = await account.getBalance(USDC); console.log(USDC.toDecimal(usdcBalance, 2)); // "12.34" ``` ``` -------------------------------- ### High-Availability RPC with FailoverRpcProvider Source: https://context7.com/near/near-api-js/llms.txt FailoverRpcProvider wraps multiple JsonRpcProvider instances, automatically falling back to the next provider if one fails. All Provider methods are available. ```typescript import { JsonRpcProvider, FailoverRpcProvider } from 'near-api-js'; const provider = new FailoverRpcProvider([ new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }), new JsonRpcProvider({ url: 'https://rpc.mainnet.pagoda.co' }), new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), ]); // All Provider methods are available — failover is transparent const block = await provider.viewBlock({ finality: 'final' }); console.log(block.header.height); // 12345678 const account = await provider.viewAccount({ accountId: 'alice.near' }); console.log(account.amount); // bigint: available balance in yoctoNEAR ``` -------------------------------- ### Account.signAndSendTransaction Source: https://context7.com/near/near-api-js/llms.txt Low-level transaction submission. Builds, signs, and broadcasts a transaction composed of one or more raw `Action` objects. Automatically retries on nonce collisions. ```APIDOC ## Account.signAndSendTransaction — Low-Level Transaction Submission Builds, signs, and broadcasts a transaction composed of one or more raw `Action` objects. Automatically retries on nonce collisions. ```typescript import { Account, JsonRpcProvider, actions, nearToYocto, teraToGas } from 'near-api-js'; import type { KeyPairString } from 'near-api-js'; const account = new Account( 'alice.testnet', new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), 'ed25519:5nM...' as KeyPairString ); // Batch multiple actions in a single transaction const result = await account.signAndSendTransaction({ receiverId: 'my-contract.testnet', actions: [ actions.transfer(nearToYocto('0.5')), actions.functionCall( 'some_method', { key: 'value' }, teraToGas(30), 0n ), ], waitUntil: 'EXECUTED', // wait for full execution throwOnFailure: true, // throw if tx fails }); console.log(result.status); ``` ``` -------------------------------- ### KeyPair — Cryptographic Key Management Source: https://context7.com/near/near-api-js/llms.txt KeyPair allows for the generation, loading, and management of cryptographic keys for Ed25519 and Secp256k1 curves. It supports random generation, loading from strings, and derivation from seed phrases. ```APIDOC ## KeyPair — Cryptographic Key Management `KeyPair` supports Ed25519 and Secp256k1 curves. Keys can be generated randomly, loaded from a string, or derived from a seed phrase. ```typescript import { KeyPair, keyToImplicitAddress } from 'near-api-js'; import { generateSeedPhrase, parseSeedPhrase } from 'near-api-js/seed-phrase'; // Generate a random Ed25519 key pair const keyPair = KeyPair.fromRandom('ed25519'); console.log(keyPair.toString()); // "ed25519:" console.log(keyPair.getPublicKey().toString()); // "ed25519:" // Derive implicit account address from public key (64-char hex) const implicitAddress = keyToImplicitAddress(keyPair.getPublicKey()); console.log(implicitAddress); // "8f3e5b..." // Load from an encoded string const loaded = KeyPair.fromString('ed25519:5nMSA...' as any); // Generate from a BIP-39 seed phrase const { seedPhrase, keyPair: derivedKey } = generateSeedPhrase(); console.log(seedPhrase); // "word1 word2 ... word12" // Recover key from seed phrase const recoveredKey = parseSeedPhrase(seedPhrase); console.log(recoveredKey.getPublicKey().toString() === derivedKey.getPublicKey().toString()); // true ``` ``` -------------------------------- ### Parallel Transactions with Key Rotation Source: https://github.com/near/near-api-js/blob/master/README.md Send transactions in parallel by rotating multiple keys for an account. Nonce collisions are automatically handled by retrying with an incremented nonce. ```typescript import { Account, actions, JsonRpcProvider, KeyPair, MultiKeySigner } from "near-api-js" import { NEAR } from "near-api-js/tokens" const privateKey = ... // const accountId = ... // // 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, privateKey) // create 10 keys and add them to the account const keys = [] const txActions = [] for (let j = 0; j < 10; j++) { const newKeyPair = KeyPair.fromRandom('ed25519') keys.push(newKeyPair) txActions.push( actions.addFullAccessKey(newKeyPair.getPublicKey()) ) } await account.signAndSendTransaction({ receiverId: accountId, actions: txActions }) console.log(`Added ${keys.length} keys to account ${accountId}`) // ------- Send NEAR tokens using multiple keys ------- const multiKeySigner = new MultiKeySigner(keys) const multiAccount = new Account(accountId, provider, multiKeySigner) const transfers = [] for (let i = 0; i < 100; i++) { transfers.push( multiAccount.transfer( { token: NEAR, amount: NEAR.toUnits("0.001"), receiverId: "influencer.testnet" } )) } const sendNearTokensResults = await Promise.all(transfers) sendNearTokensResults.forEach(result => console.log(result)) ``` -------------------------------- ### Unit Conversion Source: https://context7.com/near/near-api-js/llms.txt Provides helper functions for converting between NEAR and yoctoNEAR, as well as between TGas and GGas units. ```APIDOC ## Unit Conversion — nearToYocto, yoctoToNear, teraToGas, gigaToGas Helper functions for converting between human-readable and on-chain units. ```typescript import { nearToYocto, yoctoToNear, teraToGas, gigaToGas } from 'near-api-js'; // NEAR ↔ yoctoNEAR (1 NEAR = 10^24 yoctoNEAR) console.log(nearToYocto('1')); // 1000000000000000000000000n console.log(nearToYocto('0.1')); // 100000000000000000000000n console.log(yoctoToNear(1_000_000_000_000_000_000_000_000n, 2)); // "1.00" console.log(yoctoToNear('500000000000000000000000n', 4)); // "0.5000" // Gas conversions (TGas and GGas) console.log(teraToGas(30)); // 30000000000000n (30 TGas) console.log(teraToGas('10')); // 10000000000000n console.log(gigaToGas(300)); // 300000000000n ``` ``` -------------------------------- ### Account.createSignedMetaTransaction Source: https://context7.com/near/near-api-js/llms.txt Creates a signed meta-transaction (NEP-366 delegate action) that can be submitted to a relayer, enabling gasless transactions where a third party pays the gas. ```APIDOC ## Account.createSignedMetaTransaction ### Description Creates a signed meta-transaction (NEP-366 delegate action) that can be submitted to a relayer, enabling gasless transactions where a third party pays the gas. ### Method `createSignedMetaTransaction(metaTx: { receiverId: string, actions: Action[], blockHeightTtl: number })` ### Parameters #### Request Body - **receiverId** (string) - Required - The ID of the account receiving the transaction. - **actions** (Action[]) - Required - An array of actions to be included in the meta-transaction. - **blockHeightTtl** (number) - Required - The maximum block height for which the transaction is valid. ### Request Example ```typescript const { signedDelegate } = await userAccount.createSignedMetaTransaction({ receiverId: 'contract.testnet', actions: [ actions.functionCall('free_mint', { recipient: 'user.testnet' }, 30_000_000_000_000n, 0n), ], blockHeightTtl: 200, }); ``` ### Related Method - `relayer.relayMetaTransaction(signedDelegate)` - Used by a relayer to submit the meta-transaction. ``` -------------------------------- ### FailoverRpcProvider - High-Availability RPC Source: https://context7.com/near/near-api-js/llms.txt The FailoverRpcProvider wraps multiple JsonRpcProvider instances, automatically falling back to the next provider if one fails. ```APIDOC ## FailoverRpcProvider — High-Availability RPC ### Description `FailoverRpcProvider` wraps multiple `JsonRpcProvider` instances and automatically falls back to the next provider if one fails, cycling through the list until a successful response is returned. ### Usage ```typescript import { JsonRpcProvider, FailoverRpcProvider } from 'near-api-js'; const provider = new FailoverRpcProvider([ new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }), new JsonRpcProvider({ url: 'https://rpc.mainnet.pagoda.co' }), new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com' }), ]); // All Provider methods are available — failover is transparent const block = await provider.viewBlock({ finality: 'final' }); console.log(block.header.height); // 12345678 const account = await provider.viewAccount({ accountId: 'alice.near' }); console.log(account.amount); // bigint: available balance in yoctoNEAR ``` ``` -------------------------------- ### TypeScript Type Definitions Source: https://github.com/near/near-api-js/blob/master/README.md Importing type definitions for advanced TypeScript usage within near-api-js. ```typescript import type { AccountView, BlockReference, Action, SignedTransaction } from 'near-api-js'; ``` -------------------------------- ### Convert NEAR Units and Gas Source: https://context7.com/near/near-api-js/llms.txt Utilize helper functions for converting between NEAR and yoctoNEAR, and between TGas and GGas. These functions simplify handling different units of currency and gas in your NEAR applications. Note the large integer values involved in yoctoNEAR conversions. ```typescript import { nearToYocto, yoctoToNear, teraToGas, gigaToGas } from 'near-api-js'; // NEAR ↔ yoctoNEAR (1 NEAR = 10^24 yoctoNEAR) console.log(nearToYocto('1')); // 1000000000000000000000000n console.log(nearToYocto('0.1')); // 100000000000000000000000n console.log(yoctoToNear(1_000_000_000_000_000_000_000_000n, 2)); // "1.00" console.log(yoctoToNear('500000000000000000000000n', 4)); // "0.5000" // Gas conversions (TGas and GGas) console.log(teraToGas(30)); // 30000000000000n (30 TGas) console.log(teraToGas('10')); // 10000000000000n console.log(gigaToGas(300)); // 300000000000n ``` -------------------------------- ### JsonRpcProvider - Connect to NEAR RPC Source: https://context7.com/near/near-api-js/llms.txt The JsonRpcProvider is the main client for communicating with a NEAR RPC node. It automatically handles retries, exponential backoff, JSON-RPC encoding, and error parsing. ```APIDOC ## JsonRpcProvider - Connect to NEAR RPC ### Description The `JsonRpcProvider` is the main client for talking to a NEAR RPC node. It handles retries, exponential backoff, JSON-RPC encoding, and error parsing automatically. ### Usage ```typescript import { JsonRpcProvider } from 'near-api-js'; // Connect to testnet const provider = new JsonRpcProvider({ url: 'https://test.rpc.fastnear.com', }); // Connect to mainnet with custom retry settings const mainnetProvider = new JsonRpcProvider( { url: 'https://rpc.mainnet.near.org' }, { retries: 5, wait: 200, backoff: 2.0 } ); // Check network status const status = await provider.viewNodeStatus(); console.log(status.chain_id); // "testnet" // Read-only contract call (no signing needed) const messages = await provider.callFunction<{ text: string; sender: string }[]>({ contractId: 'guestbook.near-examples.testnet', method: 'get_messages', args: { from_index: 0, limit: 10 }, }); console.log(messages); // [{ text: "Hello!", sender: "alice.testnet" }, ...] ``` ```