| name | near-api-js |
| description | Guide for developing with near-api-js v7 - the JavaScript/TypeScript library for NEAR blockchain interaction. Use when: (1) building apps that interact with NEAR blockchain, (2) creating/signing transactions, (3) calling smart contracts, (4) managing accounts and keys, (5) working with NEAR RPC API, (6) handling FT/NFT tokens on NEAR, (7) using NEAR cryptographic operations (KeyPair, signing), (8) converting between NEAR units (yocto, gas), (9) gasless/meta transactions with relayers, (10) NEP-413 message signing for authentication, (11) storage deposit management for FT contracts. Triggers on any NEAR blockchain development tasks. |
near-api-js Skill
JavaScript/TypeScript library for NEAR blockchain interaction. Works in browser and Node.js.
Quick Start
import { Account, JsonRpcProvider, KeyPairString } from "near-api-js";
import { NEAR } from "near-api-js/tokens";
const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
const account = new Account(
"my-account.testnet",
provider,
"ed25519:..." as KeyPairString,
);
const data = await provider.callFunction({
contractId: "guestbook.near-examples.testnet",
method: "get_messages",
args: {},
});
await account.callFunction({
contractId: "guestbook.near-examples.testnet",
methodName: "add_message",
args: { text: "Hello!" },
gas: teraToGas("30"),
deposit: nearToYocto("0.1"),
});
Import Cheatsheet
import { Account, JsonRpcProvider, FailoverRpcProvider } from "near-api-js";
import { KeyPair, PublicKey, KeyType, KeyPairString } from "near-api-js";
import { KeyPairSigner, MultiKeySigner, Signer } from "near-api-js";
import { nearToYocto, yoctoToNear, teraToGas, gigaToGas } from "near-api-js";
import { NEAR, FungibleToken } from "near-api-js/tokens";
import { USDC, wNEAR } from "near-api-js/tokens/mainnet";
import { USDT } from "near-api-js/tokens/testnet";
import { generateSeedPhrase, parseSeedPhrase } from "near-api-js/seed-phrase";
import { createTransaction, signTransaction, actions } from "near-api-js";
import { Contract } from "near-api-js";
import { keyToImplicitAddress } from "near-api-js";
import { verifyMessage, signMessage } from "near-api-js/nep413";
import {
RpcError,
RpcMethodNotFoundError,
RpcRequestParseError,
ContractMethodNotFoundError,
AccountDoesNotExistError,
} from "near-api-js/rpc-errors";
Core Modules
Account
Main class for account operations.
const account = new Account(accountId, provider, privateKey);
const account = new Account(accountId, provider);
const signer = KeyPairSigner.fromSecretKey(privateKey);
account.setSigner(signer);
const state = await account.getState();
const balance = await account.getBalance();
const balance = await account.getBalance(USDC);
await account.transfer({
receiverId: "bob.testnet",
amount: NEAR.toUnits("0.1"),
token: NEAR,
});
await account.transfer({
receiverId: "bob.testnet",
amount: USDC.toUnits("0.1"),
token: USDC,
});
await account.callFunction({
contractId: "contract.testnet",
methodName: "set_greeting",
args: { message: "Hello" },
deposit: nearToYocto("0"),
gas: teraToGas("30"),
});
await account.signAndSendTransaction({
receiverId: "contract.testnet",
actions: [
actions.functionCall(
"method",
{ arg: "value" },
teraToGas("30"),
nearToYocto("0"),
),
actions.transfer(nearToYocto("1")),
],
});
Account Management
await account.addFullAccessKey(
keyPair.getPublicKey(),
);
await account.addFunctionCallAccessKey({
publicKey: keyPair.getPublicKey(),
contractId: "contract.testnet",
methodNames: ["example_method"],
allowance: nearToYocto("0.25"),
});
await account.deleteKey(keyPair.getPublicKey());
await account.deleteAccount("beneficiary.testnet");
Provider
RPC client for querying blockchain.
const provider = new JsonRpcProvider({ url: "https://rpc.mainnet.near.org" });
const failover = new FailoverRpcProvider([
new JsonRpcProvider({ url: "https://rpc.mainnet.near.org" }),
new JsonRpcProvider({ url: "https://free.rpc.fastnear.com" }),
new JsonRpcProvider({ url: "https://rpc.mainnet.near.org" }),
]);
await provider.viewAccount({ accountId: "alice.near" });
await provider.viewAccessKey({
accountId: "alice.near",
publicKey: keyPair.getPublicKey(),
});
await provider.viewAccessKeyList({ accountId: "alice.near" });
await provider.callFunction({
contractId: "contract.testnet",
method: "get_greeting",
args: {},
});
await provider.viewBlock({ finality: "final" });
await provider.sendTransaction(signedTx);
Signers
import { KeyPairSigner, MultiKeySigner } from "near-api-js";
const signer = KeyPairSigner.fromSecretKey(privateKey);
const account = new Account(accountId, provider, signer);
Contract (with ABI)
import { Contract, AbiRoot } from "near-api-js";
const abi = {
schema_version: "0.4.0",
metadata: {},
body: {
functions: [
{
name: "add_message",
kind: "call",
modifiers: ["payable"],
params: {
serialization_type: "json",
args: [
{
name: "text",
type_schema: {
type: "string",
},
},
],
},
},
{
name: "total_messages",
kind: "view",
result: {
serialization_type: "json",
type_schema: {
type: "integer",
format: "uint32",
minimum: 0.0,
},
},
},
],
root_schema: {},
},
} as const satisfies AbiRoot;
const contract = new Contract({
contractId: "guestbook.near-examples.testnet",
provider: provider,
abi: abi,
});
const total = await contract.view.total_messages();
await contract.call.add_message({
account: account,
args: { text: "Hello, NEAR!" },
deposit: nearToYocto("0.1"),
});
Contract (without ABI)
import { Contract, AbiRoot } from "near-api-js";
const contract = new Contract({
contractId: "guestbook.near-examples.testnet",
provider: provider,
});
const total = await contract.view.total_messages<number>({ args: {} });
await contract.call.add_message<void>({
account: account,
args: { text: "Hello, NEAR!" },
deposit: nearToYocto("0.1"),
});
Seed Phrases
import { generateSeedPhrase, parseSeedPhrase } from "near-api-js/seed-phrase";
const { seedPhrase, keyPair } = generateSeedPhrase();
const keyPair = parseSeedPhrase("word1 word2 ... word12");
const account = new Account(accountId, provider, new KeyPairSigner(keyPair));
Tokens
import { NEAR, FungibleToken } from "near-api-js/tokens";
import { USDT } from "near-api-js/tokens/testnet";
NEAR.toUnits("1.5");
NEAR.toDecimal("1500000000000000000000000");
await account.transfer({
token: NEAR,
amount: NEAR.toUnits("0.1"),
receiverId: "bob.testnet",
});
await account.transfer({
token: USDT,
amount: USDT.toUnits("1"),
receiverId: "bob.testnet",
});
const REF = new FungibleToken("ref.fakes.testnet", {
decimals: 18,
symbol: "REF",
name: "REF Token",
});
await account.transfer({
token: REF,
amount: REF.toUnits("1"),
receiverId: "bob.testnet",
});
await USDT.registerAccount({
accountIdToRegister: "bob.testnet",
fundingAccount: account,
});
Actions
All transaction actions.
import { actions } from "near-api-js";
actions.transfer(amount);
actions.functionCall(methodName, args, gas, deposit);
actions.createAccount();
actions.deployContract(wasmBytes);
actions.addFullAccessKey(publicKey);
actions.addFunctionAccessKey(publicKey, contractId, methodNames, allowance);
actions.deleteKey(publicKey);
actions.deleteAccount(beneficiaryId);
actions.stake(amount, publicKey);
actions.signedDelegate(signedDelegateAction);
RPC Endpoints
| Network | URL |
|---|
| Mainnet | https://rpc.mainnet.near.org |
| Mainnet (FastNEAR) | https://free.rpc.fastnear.com |
| Testnet | https://rpc.testnet.near.org |
| Testnet (FastNEAR) | https://test.rpc.fastnear.com |
Common Patterns
Batch Actions
await account.signAndSendTransaction({
receiverId: account.accountId,
actions: [
actions.addFullAccessKey(key1.getPublicKey()),
actions.addFullAccessKey(key2.getPublicKey()),
],
});
Meta Transactions
const metaTx = await userAccount.createSignedMetaTransaction({
receiverId: "contract.near",
actions: [
actions.functionCall("method", {}, teraToGas(10), nearToYocto("0")),
],
});
const result = await relayerAccount.relayMetaTransaction(metaTx.signedDelegate);
Implicit Accounts
const account = new Account(
keyToImplicitAddress(keyPair.getPublicKey()),
provider,
new KeyPairSigner(keyPair),
);
NEP-413
import { signMessage, verifyMessage } from "near-api-js/nep413";
const account = new Account("bob.near", provider, new KeyPairSigner(keyPair));
const signedMessage = await signMessage({
signerAccount: account,
payload: {
message: "Hello, world!",
recipient: "alice.near",
nonce: new Uint8Array(new Array(32)),
},
});
await verifyMessage({
signerAccountId: account.accountId,
signerPublicKey: keyPair.getPublicKey(),
signature: signedMessage.signature,
payload: {
message: "Hello, world!",
recipient: "alice.near",
nonce: new Uint8Array(new Array(32)),
},
provider: provider,
});
Manual Transaction Signing
const signer = KeyPairSigner.fromSecretKey(privateKey);
const account = new Account(accountId, provider);
const transaction = await account.createTransaction({
receiverId: "receiver.testnet",
actions: [actions.transfer(nearToYocto("0.1"))],
publicKey: await signer.getPublicKey(),
});
const signResult = await signer.signTransaction(transaction);
const result = await provider.sendTransaction(signResult.signedTransaction);
Concurrent Transactions
await Promise.all([
account.transfer({
amount: nearToYocto(1),
receiverId: "user1.testnet",
}),
account.transfer({
amount: nearToYocto(2),
receiverId: "user2.testnet",
}),
account.transfer({
amount: nearToYocto(3),
receiverId: "user3.testnet",
}),
]);
Error Handling
import {
AccountDoesNotExistActionError,
RpcRequestParseError,
UnknownBlockError,
RpcError,
} from "near-api-js/rpc-errors";
try {
await account.transfer({
amount: nearToYocto(0.01),
receiverId: "unexisted_account.testnet",
});
} catch (error) {
if (error instanceof AccountDoesNotExistActionError) {
console.error(
`Transaction ${error.txHash} failed because recipient ${error.accountId} does not exist!`,
);
}
}
try {
await account.transfer({
amount: nearToYocto(0.001),
receiverId: "account_name_that_fail_validation%.testnet",
});
} catch (error) {
if (error instanceof RpcRequestParseError) {
console.error(error.message);
}
}
const unexistedBlockHeight = 1_000_000_000_000_000;
try {
await provider.viewBlock({ blockId: unexistedBlockHeight });
} catch (error) {
if (error instanceof UnknownBlockError) {
console.error(
`Block at height ${unexistedBlockHeight} could not be found on the node!`,
);
}
}
try {
await provider.viewAccessKey({
accountId: "user.testnet",
publicKey: "ed25519:EaQnZxCMwh9yhkqW2XE2umd21iNmXep1BkM6Wtw2Qr1b",
});
} catch (error) {
if (error instanceof RpcError) {
console.error(error.message);
}
}
try {
await provider.viewAccessKey({
accountId: "user.testnet",
publicKey: "ed25519:EaQnZxCMwh9yhkqW2XE2umd21iNmXep1BkM6Wtw2Qr1bxxxx",
});
} catch (error) {
if (error instanceof RpcError) {
console.error(error.message);
}
}
Reference Documentation
For detailed patterns and advanced usage, see:
- API Patterns Reference - Complete Account/Provider method reference, manual signing, parallel transactions
- Tokens Guide - FT/NFT operations, storage deposits, pre-defined tokens
- Key Management - KeyPair types, seed phrases, signers, access keys
- Meta Transactions - Gasless transactions, relayer integration
- NEP-413 - NEP-413 message signing & verification
- Contracts - Typed Contract with ABI, Contract without ABI