关于 near-api-js
near-api-js 是供 JavaScript/TypeScript 项目使用的 NEAR 区块链交互库,可在浏览器和 Node.js 中运行。它涵盖账户、RPC、签名、合约和代币操作。
主要功能
- 01账户与密钥管理
- 02JSON-RPC 查询及故障转移
- 03交易构建、签名与发送
- 04ABI 合约交互
- 05NEAR 及代币单位转换
- 06助记词生成与解析
适用场景
- 01读取 NEAR 账户和链上数据
- 02提交转账或合约调用交易
- 03管理签名者与账户访问密钥
- 04在应用中处理 NEAR 代币数值
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ near/ agent-skills --skill near-api-js安装后在 Claude Code 中输入/near-api-js确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/api_patterns.mdcontracts.mdkey_management.mdmeta_transactions.mdnep413.mdtokens_guide.md详细介绍
near-api-js 技能
用于与 NEAR 区块链交互的 JavaScript/TypeScript 库。支持在浏览器和 Node.js 中运行。
快速开始
import { Account, JsonRpcProvider, KeyPairString } from "near-api-js";
import { NEAR } from "near-api-js/tokens";
// Connect to testnet
const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
// Create account with signer
const account = new Account(
"my-account.testnet",
provider,
"ed25519:..." as KeyPairString,
);
// View call (read-only, via provider)
const data = await provider.callFunction({
contractId: "guestbook.near-examples.testnet",
method: "get_messages",
args: {},
});
// Change call (requires account)
await account.callFunction({
contractId: "guestbook.near-examples.testnet",
methodName: "add_message",
args: { text: "Hello!" },
gas: teraToGas("30"),
deposit: nearToYocto("0.1"),
});
导入速查表
// Core
import { Account, JsonRpcProvider, FailoverRpcProvider } from "near-api-js";
import { KeyPair, PublicKey, KeyType, KeyPairString } from "near-api-js";
// Signers
import { KeyPairSigner, MultiKeySigner, Signer } from "near-api-js";
// Units
import { nearToYocto, yoctoToNear, teraToGas, gigaToGas } from "near-api-js";
// Tokens
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";
// Seed phrases
import { generateSeedPhrase, parseSeedPhrase } from "near-api-js/seed-phrase";
// Transactions
import { createTransaction, signTransaction, actions } from "near-api-js";
// Contract with ABI
import { Contract } from "near-api-js";
// Transform key into implicit account ID
import { keyToImplicitAddress } from "near-api-js";
// NEP-413 signing & verification
import { verifyMessage, signMessage } from "near-api-js/nep413";
import {
RpcError,
RpcMethodNotFoundError,
RpcRequestParseError,
ContractMethodNotFoundError,
AccountDoesNotExistError,
// and many more
} from "near-api-js/rpc-errors";
核心模块
账户
用于账户操作的主类。
// With signer (can sign transactions)
const account = new Account(accountId, provider, privateKey);
// Without signer (read-only, can add signer later)
const account = new Account(accountId, provider);
// Add signer later
const signer = KeyPairSigner.fromSecretKey(privateKey);
account.setSigner(signer);
// Get state
const state = await account.getState(); // { balance: { total, available, locked }, storageUsage }
// Get balance (with optional token parameter)
const balance = await account.getBalance(); // NEAR balance
const balance = await account.getBalance(USDC); // FT balance
// Transfer NEAR
await account.transfer({
receiverId: "bob.testnet",
amount: NEAR.toUnits("0.1"),
token: NEAR,
});
// Transfer USDC
await account.transfer({
receiverId: "bob.testnet",
amount: USDC.toUnits("0.1"),
token: USDC,
});
// Call contract
await account.callFunction({
contractId: "contract.testnet",
methodName: "set_greeting",
args: { message: "Hello" },
deposit: nearToYocto("0"),
gas: teraToGas("30"),
});
// Sign and send transaction with multiple actions
await account.signAndSendTransaction({
receiverId: "contract.testnet",
actions: [
actions.functionCall(
"method",
{ arg: "value" },
teraToGas("30"),
nearToYocto("0"),
),
actions.transfer(nearToYocto("1")),
],
});
账户管理
// Add full access key
await account.addFullAccessKey(
keyPair.getPublicKey(), // or string "ed25519:2ASWc..."
);
// Add function call access key
await account.addFunctionCallAccessKey({
publicKey: keyPair.getPublicKey(), // or string "ed25519:2ASWc..."
contractId: "contract.testnet",
methodNames: ["example_method"],
allowance: nearToYocto("0.25"), // use "0" for unlimited
});
// Delete key
await account.deleteKey(keyPair.getPublicKey()); // or string "ed25519:2ASWc..."
// Delete account and transfer remaining NEAR tokens to beneficiary (FTs and NFTs must be transferred manually before deleting account)
await account.deleteAccount("beneficiary.testnet");
Provider
用于查询区块链的 RPC 客户端。
const provider = new JsonRpcProvider({ url: "https://rpc.mainnet.near.org" });
// Failover provider
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" }),
]);
// Query methods
await provider.viewAccount({ accountId: "alice.near" });
await provider.viewAccessKey({
accountId: "alice.near",
publicKey: keyPair.getPublicKey(), // or string "ed25519:2ASWc..."
});
await provider.viewAccessKeyList({ accountId: "alice.near" });
// read-only call to contract method
await provider.callFunction({
contractId: "contract.testnet",
method: "get_greeting",
args: {},
});
await provider.viewBlock({ finality: "final" });
await provider.sendTransaction(signedTx);
签名者
import { KeyPairSigner, MultiKeySigner } from "near-api-js";
// signer shouldn't be used directly for most use cases, instead it's used internally by Account class
const signer = KeyPairSigner.fromSecretKey(privateKey); // or "new KeyPairSigner(keyPair)"
const account = new Account(accountId, provider, signer);
Contract(带 ABI)
import { Contract, AbiRoot } from "near-api-js";
// ABI definition requires "as const" (const assertions), otherwise types won't be inferred correctly
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,
});
// the interface of view and call methods are fully inferred from the ABI, including argument and return types
const total = await contract.view.total_messages();
await contract.call.add_message({
account: account,
args: { text: "Hello, NEAR!" },
deposit: nearToYocto("0.1"),
});
Contract(不带 ABI)
import { Contract, AbiRoot } from "near-api-js";
const contract = new Contract({
contractId: "guestbook.near-examples.testnet",
provider: provider,
});
// the interface of view and call methods are generic and not inferred without ABI, so you need to specify argument and return types manually using generics
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"),
});
助记词
import { generateSeedPhrase, parseSeedPhrase } from "near-api-js/seed-phrase";
const { seedPhrase, keyPair } = generateSeedPhrase();
const keyPair = parseSeedPhrase("word1 word2 ... word12");
// Use with Account
const account = new Account(accountId, provider, new KeyPairSigner(keyPair));
代币
import { NEAR, FungibleToken } from "near-api-js/tokens";
import { USDT } from "near-api-js/tokens/testnet";
// Unit conversion
NEAR.toUnits("1.5"); // 1500000000000000000000000n (yoctoNEAR)
NEAR.toDecimal("1500000000000000000000000"); // "1.5" (NEAR)
// Transfer NEAR
await account.transfer({
token: NEAR,
amount: NEAR.toUnits("0.1"),
receiverId: "bob.testnet",
});
// Transfer USDT
await account.transfer({
token: USDT,
amount: USDT.toUnits("1"),
receiverId: "bob.testnet",
});
// Transfer custom Fungible Token
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",
});
// NEP-141 requires the receiver to be registered before receiving tokens, usually it's the receiver's responsibility to register their account, but in some cases the sender might want to cover the registration cost for the receiver
await USDT.registerAccount({
accountIdToRegister: "bob.testnet",
fundingAccount: account,
});
操作
所有交易操作。
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 端点
| 网络 | URL |
|---|---|
| 主网 | https://rpc.mainnet.near.org |
| 主网(FastNEAR) | https://free.rpc.fastnear.com |
| 测试网 | https://rpc.testnet.near.org |
| 测试网(FastNEAR) | https://test.rpc.fastnear.com |
常见模式
批量操作
await account.signAndSendTransaction({
receiverId: account.accountId,
actions: [
actions.addFullAccessKey(key1.getPublicKey()),
actions.addFullAccessKey(key2.getPublicKey()),
],
});
元交易
// Create and sign meta tx (user side)
const metaTx = await userAccount.createSignedMetaTransaction({
receiverId: "contract.near",
actions: [
actions.functionCall("method", {}, teraToGas(10), nearToYocto("0")),
],
});
// Relay via funded account
const result = await relayerAccount.relayMetaTransaction(metaTx.signedDelegate);
隐式账户
// keep in mind that implicit accounts don't actually exist on-chain until they receive at least 1 yoctoNEAR
const account = new Account(
keyToImplicitAddress(keyPair.getPublicKey()), // implicit account ID derived from public key
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, // requires signer to be set on account
payload: {
message: "Hello, world!",
recipient: "alice.near",
nonce: new Uint8Array(new Array(32)), // random 32 bytes
},
});
// throws an Error if verification fails
await verifyMessage({
signerAccountId: account.accountId,
signerPublicKey: keyPair.getPublicKey(),
signature: signedMessage.signature,
payload: {
message: "Hello, world!",
recipient: "alice.near",
nonce: new Uint8Array(new Array(32)),
}, // exact payload that was used above for signing
provider: provider,
});
手动签署交易
const signer = KeyPairSigner.fromSecretKey(privateKey);
const account = new Account(accountId, provider); // no signer needed
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);
并发交易
// Account is optimized for handling concurrent transactions efficiently, put as many transactions as you want in the array and they will be executed in parallel (usually within 1-2 blocks, depending on the amount)
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",
}),
]);
错误处理
import {
AccountDoesNotExistActionError,
RpcRequestParseError,
UnknownBlockError,
RpcError,
// and many more
} from "near-api-js/rpc-errors";
// End users can catch action-level errors (e.g. when a transaction fails because the recipient account does not exist):
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!`,
);
}
}
// Or, RPC request validation and parsing errors can also be handled explicitly (e.g. when an invalid account ID format is included in a transaction):
try {
await account.transfer({
amount: nearToYocto(0.001),
receiverId: "account_name_that_fail_validation%.testnet",
});
} catch (error) {
if (error instanceof RpcRequestParseError) {
// Failed parsing args: the value could not be decoded from borsh due to:
// invalid value: "account_name_that_fail_validation%.testnet",
// the Account ID contains an invalid character '%' at index 33
console.error(error.message);
}
}
// Or, some requests may reference data that is no longer available or cannot be resolved by the node (e.g. querying a block that cannot be found):
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!`,
);
}
}
// All exported errors ultimately extend the RpcError base class, so applications can also catch and handle any RPC-related error in a single place when fine-grained handling is not required:
try {
await provider.viewAccessKey({
accountId: "user.testnet",
publicKey: "ed25519:EaQnZxCMwh9yhkqW2XE2umd21iNmXep1BkM6Wtw2Qr1b",
});
} catch (error) {
if (error instanceof RpcError) {
// Access key ed25519:EaQnZx... does not exist at block height ...
console.error(error.message);
}
}
try {
await provider.viewAccessKey({
accountId: "user.testnet",
publicKey: "ed25519:EaQnZxCMwh9yhkqW2XE2umd21iNmXep1BkM6Wtw2Qr1bxxxx", // invalid key here
});
} catch (error) {
if (error instanceof RpcError) {
// Failed parsing args: invalid key length: expected the input of 32 bytes, but 33 was given
console.error(error.message);
}
}
参考文档
如需了解详细模式和高级用法,请参阅:
- API 模式参考 - 完整的 Account/Provider 方法参考、手动签名和并行交易
- 代币指南 - FT/NFT 操作、存储存款和预定义代币
- 密钥管理 - KeyPair 类型、助记词、签名者和访问密钥
- 元交易 - 无 Gas 交易和中继器集成
- NEP-413 - NEP-413 消息签名与验证
- 合约 - 带 ABI 的类型化 Contract、不带 ABI 的 Contract
上游文档
- API 库(docs.near.org) — 官方 near-api-js 指南
- npm 上的 near-api-js — 当前版本(v7.x)
- RPC 提供方列表 — 公共端点可能会变更;硬编码 RPC URL 前请先在此查看(以上示例使用
rpc.mainnet.near.org和 FastNEAR 镜像) - JSON-RPC 参考 — 此库封装的底层 RPC 方法
评论
支持 Markdown