near/near-api-js
حول
مكتبة JavaScript للتفاعل مع NEAR Protocol عبر واجهة RPC API.
الأعمال والماليةالنمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- ٠
- خلال 15 يومًا
- ٠
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلNEAR JavaScript API
NEAR JavaScript API is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime.
[!IMPORTANT]
near-api-jsis ideal to build backend services, CLIs, and scripts that interact with NEAR. For frontend development please check the official web login docs
Why near-api-js?
near-api-js v7 is a single package that helps you to easily integrate NEAR blockchain into your JavaScript/TypeScript applications.
It includes all the functionality you need, including account management, transaction building, key management, interacting with smart contracts, making RPC calls, and more.
- ✅ Simple - just one package
- ✅ Batteries included - everything you need to build scripts and backend services
- ✅ Friendly - multiple helpers to make your life easier
- ✅ Full TypeScript support
- ✅ Works in browser and Node.js
Quick Start
Use Node.js 22.22.2 or later. The examples below use ES modules; set "type": "module" in your application's package.json. TypeScript examples require a TypeScript runner or compilation before execution.
Add near-api-js to your project using your favorite package manager:
npm install near-api-js
# or
yarn add near-api-js
# or
pnpm add near-api-js
Start using it!
import { Account, JsonRpcProvider, teraToGas, type 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 = process.env.NEAR_ACCOUNT_ID;
const privateKey = process.env.NEAR_PRIVATE_KEY as KeyPairString | undefined;
if (!accountId || !privateKey) throw new Error('Set NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY');
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'),
});
Use an existing testnet account and its prefixed private key (for example, ed25519:...). The key must have permission to call the contract, and the account must have enough balance for gas and the attached deposit. Setting these environment variables is an application convention; the library does not load credentials automatically.
For JavaScript, omit TypeScript-only syntax such as type KeyPairString and the as assertion. The feature snippets below reuse account and provider from this setup unless they define their own.
Documentation
- Learn how to use the library in your project
- See it in action in our API Examples
- Read the TypeDoc API documentation
Migration from @near-js/* packages
Check out the migration guide for v6 / @near-js/* imports, account methods, signers, units, and error handling.
New in 7.5
- Deterministic (
0s…) accounts:DeterministicStateInitbuilds initial code/storage, derives the account ID, and works withAccount.createDeterministicAccount(). - Universal (
0u…) accounts:UniversalStateInitsupports code, storage, and access keys;Account.createUniversalAccount()supports initialization, including prefunded self-bootstrap. - Access-key pagination:
provider.viewAccessKeyList({ accountId, limit, afterKey })returnslast_keyfor the next page. - Global contracts:
(await account.getState()).globalContractidentifies the global code used by an account. Global contract helpers accept the base58 hashes returned by RPC. - Meta transactions:
SignedDelegate.decode(bytes)anddecodeSignedDelegate(bytes)complement signed-delegate encoding.
Gas-key creation, funding, withdrawals, and automatic nonce-lane rotation were added in 7.4. See the release notes and API reference for details. State-init deposits cover storage staking and refund excess; transfer spending balance separately.
Features
near-api-js includes some advanced features to help you build robust applications.
Access-key pagination
Call account.getAccessKeyList({ limit: 100 }) to retrieve one page. If the response includes last_key, pass it unchanged as afterKey in the next call. The return shape is the same as provider.viewAccessKeyList(). No-argument calls remain supported, but nodes may reject them for accounts exceeding their unpaginated key limit.
Simple Units Conversions
You can easily convert between NEAR and yoctoNEAR, and between gas units:
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);
Parallel Transactions
near-api-js can send transactions in parallel by rotating multiple keys for an account.
The SDK reserves nonces locally and retries invalid-nonce failures. Multiple keys can improve concurrency; this example submits ten transfers and spends real testnet balance.
import { Account, actions, KeyPair, MultiKeySigner, type Action } from "near-api-js"
import { NEAR } from "near-api-js/tokens"
const accountId = account.accountId
// create 10 keys and add them to the account
const keys: KeyPair[] = []
const txActions: Action[] = []
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 < 10; 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))
Typescript Support
near-api-js is written in TypeScript and includes full type definitions:
import type {
AccountView,
BlockReference,
Action,
SignedTransaction
} from 'near-api-js';
Typed Function Calls
You can even type the expected results from contract function calls:
type Message = { text: string; sender: string };
const messages = await provider.callFunction<Message[]>({
contractId: 'guestbook.near-examples.testnet',
method: 'get_messages',
args: {},
blockQuery: { finality: 'final' },
});
console.log(messages);
Provider.callFunction() uses method and returns the decoded view result (or undefined for an empty result). Account.callFunction() uses methodName and returns the decoded transaction result; use Account.callFunctionRaw() for the transaction outcome. Generic types describe the expected JSON shape; they do not validate the contract's response at runtime.
Reading after a transaction
Transactions default to waitUntil: 'EXECUTED_OPTIMISTIC', and view calls default to blockQuery: { finality: 'optimistic' }. A single RPC URL can route requests to different backend nodes at different heights, so an immediate view may return older state even after the transaction's non-refund receipts have executed. These defaults do not guarantee read-after-write consistency across backend nodes.
If your application needs to observe the write, retry the view with bounded backoff and a deadline. Alternatively, query a specific snapshot using blockQuery: { blockId: receipt.block_hash }, where receipt is the entry in the transaction result's receipts_outcome that performed the relevant write. A lagging backend may not have that block available yet, so pinned queries can also require retries.
Use the execution receipt's block, rather than transaction_outcome.block_hash, which can precede the write. Cross-contract transactions can contain several receipts that change state; choose the receipt relevant to the state you are reading.
Handling transaction failures
Account throws on transaction failure by default. Catch exported error classes instead of extracting information from error-message strings. Contract panics expose panicMessage; execution errors derived from a submitted transaction also expose its full RPC response as transactionResult:
import {
ContractExecutionError,
HostGuestPanicError,
TransactionExecutionError,
} from 'near-api-js/rpc-errors';
try {
await account.callFunction({
contractId: 'contract.testnet',
methodName: 'some_method',
args: {},
});
} catch (error) {
if (error instanceof HostGuestPanicError) {
console.error(error.panicMessage);
}
if (error instanceof ContractExecutionError || error instanceof TransactionExecutionError) {
for (const receipt of error.transactionResult?.receipts_outcome ?? []) {
const status = receipt.outcome.status;
if (typeof status === 'object' && 'Failure' in status) {
console.error({
receiptId: receipt.id,
receiverId: receipt.outcome.executor_id,
failure: status.Failure,
logs: receipt.outcome.logs,
});
}
}
}
throw error;
}
This inspection needs no additional RPC call. There may be multiple failed receipts, including failures handled by callbacks, so the first failed receipt is not necessarily the cause of the transaction's final failure. Read-only calls produce no transaction receipts; submission or RPC errors may also lack transactionResult.
With account.signAndSendTransaction({ receiverId, actions, throwOnFailure: false }), inspect the returned outcome's status and receipts_outcome instead. If you only retained the transaction hash, fetch the outcome with provider.viewTransactionStatus({ txHash, accountId: senderAccountId, waitUntil: 'FINAL' }). viewTransactionStatusWithReceipts() additionally retrieves receipt details. These low-level status methods return the RPC result; inspect its failure status explicitly.
Failover RPC Provider
You can easily define multiple RPC endpoints to connect to NEAR network, if one fails the next one will be used automatically.
import { JsonRpcProvider, FailoverRpcProvider } from 'near-api-js';
const provider = new FailoverRpcProvider([
new JsonRpcProvider({ url: 'https://rpc.mainnet.near.org' }),
new JsonRpcProvider({ url: 'https://free.rpc.fastnear.com' }),
]);
Decoupled Transaction Signing
You can separately build transactions, sign them, and broadcast them to the network.
Transaction creation reads the nonce and a recent block hash from RPC. Signing itself can happen separately; broadcast before the transaction's block reference expires.
import { JsonRpcProvider, Account, KeyPairSigner, actions, nearToYocto, type KeyPairString } from "near-api-js";
const provider = new JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});
const accountId = process.env.NEAR_ACCOUNT_ID;
const privateKey = process.env.NEAR_PRIVATE_KEY as KeyPairString | undefined;
if (!accountId || !privateKey) throw new Error('Set NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY');
const signer = KeyPairSigner.fromSecretKey(privateKey);
const publicKey = await signer.getPublicKey();
// The account used to construct the transaction needs no signer.
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 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);
Browser and Node.js Support
- ✅ Node.js - Requires Node.js 22.22.2 or later
- ✅ Browsers - Uses modern Web APIs, including Web Crypto,
TextEncoder, andUint8Array; use a bundler and a browser supporting those APIs - ✅ ESM - Native ES modules support
- ✅ CommonJS - For legacy Node.js projects
- ✅ TypeScript - Full type definitions included
Contributing
Contributions are welcome! Please check out the contributing guidelines.
Install dependencies
pnpm installRun continuous build with:
pnpm dev
Integration Test
Build first, then run the unit and sandbox integration suites:
pnpm build
pnpm test
The integration tests start local NEAR sandbox nodes; they do not require a public-network faucet. Run package import tests separately with pnpm --dir e2e test. Other checks are pnpm lint, pnpm typecheck, and pnpm check-exports.
License
This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE and LICENSE-APACHE for details.
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…