Nhảy đến nội dung chính

Using JavaScript API to interact with NEAR

What is near-api-js

near-api-js is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime.

You'll typically first create a connection to NEAR with connect using a KeyStore. With the connection object you now can:

  • Interact with the Wallet in a browser.
  • Instantiate an Account object to:
    • Send tokens
    • Deploy contracts
    • Inspect, create or delete accounts
    • Manage keys for accounts.
  • Instantiate a Contract object to call smart contract methods.

The library also contains some utils functions.

To quickly get started with integrating NEAR in a web browser, read our Web Frontend integration article. :::

The JavaScript SDK is a library for developing smart contracts. It contains classes and functions you use to write your smart contract code.

The JavaScript API is a complete library for all possible commands to interact with NEAR. It’s a wrapper for the RPC endpoints, a library to interact with NEAR Wallet in the browser, and a tool for keys management. :::


Install

Include near-api-js as a dependency in your package.

npm i --save near-api-js

Import

You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the WalletConnection is only for the browser, and there are different KeyStore providers for each environment.

import * as nearAPI from "near-api-js";

Lưu trữ key

If you sign transactions, you need to create a Key Store. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.

// creates keyStore using private key in local storage

const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();

Class BrowserLocalStorageKeyStore

Connecting to NEAR

The object returned from connect is your entry-point for all commands in the API. To sign a transaction you'll need a KeyStore to create a connection.

const { connect } = nearAPI;

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore, // first create a key store
nodeUrl: "https://rpc.testnet.near.org",
walletUrl: "https://wallet.testnet.near.org",
helperUrl: "https://helper.testnet.near.org",
explorerUrl: "https://explorer.testnet.near.org",
};
const nearConnection = await connect(connectionConfig);

Module connect

Interacting with the Wallet

Wallet interaction is possible only in the browser, because NEAR's Wallet is web-based.

Creating Wallet Connection

In Wallet connection you use a LocalStorage KeyStore.

const { connect, keyStores, WalletConnection } = nearAPI;

const connectionConfig = {
networkId: "testnet",
keyStore: new keyStores.BrowserLocalStorageKeyStore(),
nodeUrl: "https://rpc.testnet.near.org",
walletUrl: "https://wallet.testnet.near.org",
helperUrl: "https://helper.testnet.near.org",
explorerUrl: "https://explorer.testnet.near.org",
};

// connect to NEAR
const nearConnection = await connect(connectionConfig);

// create wallet connection
const walletConnection = new WalletConnection(nearConnection);

Module browserConnect     Class WalletConnection

Ask your user to Sign In

You first create a WalletConnection, and then call requestSignIn. This will redirect the current page to the Wallet authentication page. You can configure success and failure redirect URLs.

This action creates an access key that will be stored in the browser's local storage. The access key can then be used to connect to NEAR and sign transactions via the KeyStore.

// const walletConnection = new WalletConnection(nearConnection);
walletConnection.requestSignIn(
"example-contract.testnet", // contract requesting access
"Example App", // optional title
"http://YOUR-URL.com/success", // optional redirect URL on success
"http://YOUR-URL.com/failure" // optional redirect URL on failure
);

Method WalletConnection.requestSignIn

Sign In is not required if you are using an alternative key store to local storage, or you are not signing transactions (meaning - you are only calling read-only view methods on a contract) :::

Sign Out on behalf of your user

// const walletConnection = new WalletConnection(nearConnection);
walletConnection.signOut();

Method WalletConnection.signOut

Kiểm tra xem đã đăng nhập hay chưa

// const walletConnection = new WalletConnection(nearConnection);
if (walletConnection.isSignedIn()) {
// user is signed in
}

Method WalletConnection.isSignedId

Lấy id của account được ủy quyền

// const walletConnection = new WalletConnection(nearConnection);
const walletAccountId = walletConnection.getAccountId();

Method WalletConnection.getAccountId

Lấy Object của account được ủy quyền

This will return an instance of Account that this wallet is authorized for.

// const walletConnection = new WalletConnection(nearConnection);
const walletAccountObj = walletConnection.account();

Method WalletConnection.account     Class ConnectedWalletAccount

Account

You can create, delete and interact with accounts with the Account module.

Load Account

This will return an Account object for you to interact with.

const account = await nearConnection.account("example-account.testnet");

Class Account

Tạo account

// create a new account using funds from the account used to create it.
const account = await nearConnection.account("example-account.testnet");
await account.createAccount(
"example-account2.testnet", // new account name
"8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for new account
"10000000000000000000" // initial balance for new account in yoctoNEAR
);

Method Account.createAccount

Xóa account

// deletes account found in the `account` object
// transfers remaining account balance to the accountId passed as an argument
const account = await nearConnection.account("example-account.testnet");
await account.deleteAccount("beneficiary-account.testnet");

Method Account.deleteAccount

Kiểm tra số dư tài khoản

// gets account balance
const account = await nearConnection.account("example-account.testnet");
await account.getAccountBalance();

Method Account.getAccountBalance

Xem thông tin chi tiết của account

// gets account details in terms of authorized apps and transactions
const account = await nearConnection.account("example-account.testnet");
await account.getAccountDetails();

Method Account.getAccountDetails

Deploy contract

const account = await nearConnection.account("example-account.testnet");
const response = await account.deployContract(fs.readFileSync('./wasm_files/status_message.wasm'));
console.log(response);

Method Account.deployContract

Send Tokens

// sends NEAR tokens
const account = await nearConnection.account("sender-account.testnet");
await account.sendMoney(
"receiver-account.testnet", // receiver account
"1000000000000000000000000" // amount in yoctoNEAR
);

Method Account.sendMoney

State

// gets the state of the account
const account = await nearConnection.account("example-account.testnet");
const response = await account.state();
console.log(response);

Method Account.state

Các RPC Endpoint

Thêm một Full Access Key

// takes public key as string for argument
const account = await nearConnection.account("example-account.testnet");
await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");

Method Account.addKey

Thêm một Function Access Key

// adds function access key
const account = await nearConnection.account("example-account.testnet");
await account.addKey(
"8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for new account
"example-account.testnet", // contract this key is allowed to call (optional)
"example_method", // methods this key is allowed to call (optional)
"2500000000000" // allowance key can use to call methods (optional)
);

Method Account.addKey

Lấy tất cả các Access Key

// returns all access keys associated with an account
const account = await nearConnection.account("example-account.testnet");
await account.getAccessKeys();

Method Account.getAccessKeys

Xóa Access Key

// takes public key as string for argument
const account = await nearConnection.account("example-account.testnet");
await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");

Method Account.deleteKey

Contract

When you instantiate an instance of Contract, it includes the smart-contract functions as methods of the instance. For example if you deployed a contract with my_method function on it, then this will work:

const contract = new Contract(account, {
changeMethods: ["my_method"],
});
// `contract` object has `my_method` on it:
contract.my_method()

Load Contract

const { Contract } = nearAPI;

const contract = new Contract(
account, // the account object that is connecting
"example-contract.testnet",
{
// name of contract you're connecting to
viewMethods: ["getMessages"], // view methods do not change state but usually return a value
changeMethods: ["addMessage"], // change methods modify state
}
);

Class Contract

Call Contract

await contract.method_name(
{
arg_name: "value", // đối số name và value - truyền vào empty object nếu không có tham số nào được yêu cầu
},
"300000000000000", // lượng GAS đính kèm (tùy chọn)
"1000000000000000000000000" // tiền gửi đính kèm tính bằng yoctoNEAR (tùy chọn)
);

Class Contract

Các tiện ích

NEAR => yoctoNEAR

// chuyển đổi số lượng NEAR thành yoctoNEAR (10^-24)

const { utils } = nearAPI;
const amountInYocto = utils.format.parseNearAmount("1");

Function parseNearAmount

YoctoNEAR => NEAR

// chuyển đổi số lượng yoctoNEAR (10^-24) thành NEAR

const { utils } = nearAPI;
const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");

Function formatNearAmount