Using JavaScript API to interact with NEAR
Quick Reference
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 utility functions.
To quickly get started with integrating NEAR in a web browser, read our Web Frontend integration article.
Note the difference between near-api-js
and near-sdk-js
:
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.
- Browser
- Node
import * as nearAPI from "near-api-js";
const nearAPI = require("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.
- Using Browser
- Using Credentials Directory
- Using a File
- Using a private key string
// creates keyStore using private key in local storage
const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
// creates a keyStore that searches for keys in .near-credentials
// requires credentials stored locally by using a NEAR-CLI command: `near login`
// https://docs.near.org/tools/cli#near-login
const { keyStores } = nearAPI;
const homedir = require("os").homedir();
const CREDENTIALS_DIR = ".near-credentials";
const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);