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";

Key Store

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

Check if Signed In

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

Method WalletConnection.isSignedId

Get Authorized Account Id

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

Method WalletConnection.getAccountId

Get Authorized Account Object

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

Create 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

Delete 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

Get Account Balance

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

Method Account.getAccountBalance

Get Account details

// 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 a 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

Access Keys

Add 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

Add 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

Get All Access Keys

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

Method Account.getAccessKeys

Delete 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"],
sender: account
});
// `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
sender: account, // account object to initialize and sign transactions.
}
);

Class Contract

Call Contract

await contract.method_name(
{
arg_name: "value", // argument name and value - pass empty object if no args required
},
"300000000000000", // attached GAS (optional)
"1000000000000000000000000" // attached deposit in yoctoNEAR (optional)
);

Class Contract

Utils

NEAR => yoctoNEAR

// converts NEAR amount into yoctoNEAR (10^-24)

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

Function parseNearAmount

YoctoNEAR => NEAR

// converts yoctoNEAR (10^-24) amount into NEAR

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

Function formatNearAmount