NEAR API
The NEAR API is a set of libraries that allow you to interact with the NEAR blockchain. You can use it to create accounts, send tokens, deploy contracts, and more.
The API is available in multiple languages, including:
- JavaScript:
near-api-js
- Rust:
near-api-rs
- Python:
py-near
For example, you could use near-api-js
to create web applications or backend services written in node.js servers.
To allow users to login into your web application using a wallet you will need the wallet-selector
. Read more in our Web Frontend integration article
Install
- 🌐 JavaScript
- 🦀 Rust
Include near-api-js
as a dependency in your package.
npm i --save near-api-js
If you are building a site without using npm
, you can include the library directly in your HTML file through a CDN.
<script src="https://cdn.jsdelivr.net/npm/near-api-js/dist/near-api-js.min.js"></script>
cargo add near-api
Import
- 🌐 JavaScript
- 🦀 Rust
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";
The methods to interact with the NEAR API are available through the prelude
module.
use near_api::prelude::*;
Connecting to NEAR
- 🌐 JavaScript
- 🦀 Rust
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://testnet.mynearwallet.com/",
helperUrl: "https://helper.testnet.near.org",
explorerUrl: "https://testnet.nearblocks.io",
};
const nearConnection = await connect(connectionConfig);
Mainnet/Localnet connection
// Mainnet config example
const connectionConfig = {
networkId: "mainnet",
keyStore: myKeyStore, // first create a key store
nodeUrl: "https://rpc.mainnet.near.org",
walletUrl: "https://wallet.mainnet.near.org",
helperUrl: "https://helper.mainnet.near.org",
explorerUrl: "https://nearblocks.io",
};
// Localnet config example
const connectionConfig = {
networkId: "local",
nodeUrl: "http://localhost:3030",
walletUrl: "http://localhost:4000/wallet",
};
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);
// creates keyStore from a provided file
// you will need to pass the location of the .json key pair
const { KeyPair, keyStores } = require("near-api-js");
const fs = require("fs");
const homedir = require("os").homedir();
const ACCOUNT_ID = "near-example.testnet"; // NEAR account tied to the keyPair
const NETWORK_ID = "testnet";
// path to your custom keyPair location (ex. function access key for example account)
const KEY_PATH = "/.near-credentials/near-example-testnet/get_token_price.json";
const credentials = JSON.parse(fs.readFileSync(homedir + KEY_PATH));
const myKeyStore = new keyStores.InMemoryKeyStore();
myKeyStore.setKey(
NETWORK_ID,
ACCOUNT_ID,
KeyPair.fromString(credentials.private_key)
);
// creates keyStore from a private key string
// you can define your key here or use an environment variable
const { keyStores, KeyPair } = nearAPI;
const myKeyStore = new keyStores.InMemoryKeyStore();
const PRIVATE_KEY =
"by8kdJoJHu7uUkKfoaLd2J2Dp1q1TigeWMG123pHdu9UREqPcshCM223kWadm";
// creates a public / private key pair using the provided private key
const keyPair = KeyPair.fromString(PRIVATE_KEY);
// adds the keyPair you created to keyStore
await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
Window error using Node.js
You're maybe using a KeyStore that's for the browser. Instead, use a filesystem key or private key string.
Browser KeyStore:
const { keyStores } = require("near-api-js");
const keyStore = new keyStores.BrowserLocalStorageKeyStore();
FileSystem KeyStore:
const { keyStores } = require("near-api-js");
const KEY_PATH = "~./near-credentials/testnet/example-account.json";
const keyStore = new keyStores.UnencryptedFileSystemKeyStore(KEY_PATH);
Standard connections mainnet
and testnet
are available that come with standard configurations for each network.
let network = NetworkConfig::testnet();
You can make the connection mutable to change some details of the connection.
let mut network = NetworkConfig::testnet();
network.rpc_url = "https://rpc.testnet.near.org".parse().unwrap();
You can also create your own custom connection.
let network = NetworkConfig {
network_name: "testnet".to_string(),
rpc_url: "https://rpc.testnet.near.org".parse().unwrap(),
rpc_api_key: None,
linkdrop_account_id: Some("testnet".parse().unwrap()),
near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
meta_transaction_relayer_url: Some("http://localhost:3030/relay".parse().unwrap()),
fastnear_url: None,
staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
};
Signer
If you're going to sign transactions, you need to create a signer
object.
- Using Keystore
- Using a File
- Using Seed Phrase
- Using a Private Key String
This example uses the Keystore that is also used as the standard for saving keys with the NEAR CLI.
use near_api::signer::keystore::KeystoreSigner;
let search_keystore_signer = KeystoreSigner::search_for_keys(my_account_id.clone(), &network)
.await
.unwrap();
let keystore_signer_search = Signer::new(search_keystore_signer).unwrap();
Keys can be loaded from a file that contains a public and private key. This is an example of loading a key from a file that was saved using the legacy option using the NEAR CLI.
use std::env;
use std::path::Path;
let my_account_id = "example-account.testnet";
let home_dir = env::var("HOME").unwrap();
let credentials_dir = Path::new(&home_dir).join(".near-credentials");
let file_path = credentials_dir.join(format!("testnet/{}.json", my_account_id));
let file_signer = Signer::new(Signer::access_keyfile(file_path).unwrap()).unwrap();
let seed_phrase =
"shoe three gate jelly whole tissue parrot robust census lens staff ship".to_string();
let seed_phrase_signer = Signer::new(Signer::seed_phrase(seed_phrase, None).unwrap()).unwrap();
use near_crypto::SecretKey;
use std::str::FromStr;
let private_key = SecretKey::from_str("ed25519:3bUTUXCPHPbAD5JDukzsWT6AaJ9iZA3FF9wLgYgRvzC7CDYMgmEExtxyGjnGATvmM3oggqUErvRkN9sjzNTD8yd7").unwrap();
let priv_key_signer = Signer::new(Signer::secret_key(private_key)).unwrap();
RPC Failover
RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the FailoverRpcProvider
that supports multiple RPC providers.
- 🌐 JavaScript
const jsonProviders = [
new JsonRpcProvider({
url: 'https://rpc.mainnet.near.org',
}),
new JsonRpcProvider(
{
url: 'https://another-rpc.cloud.com',
headers: { 'X-Api-Key': 'some string' },
},
{ retries: 3, backoff: 2, wait: 500 }
),
];
const provider = new FailoverRpcProvider(jsonProviders);
await connect({
networkId: 'mainnet',
provider: provider,
// this isn't used if `provider` is specified, but is still required for backward compatibility
nodeUrl: 'https://rpc.mainnet.near.org',
});
Account
Instantiate Account
This will return an Account object for you to interact with.
- 🌐 JavaScript
- 🦀 Rust
const account = await nearConnection.account("example-account.testnet");
In order to be able to use the account, its credentials must be stored in the key store
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let account = Account::new(account_id.clone(), network);
Get Balance
- 🌐 JavaScript
- 🦀 Rust
// gets account balance
const account = await nearConnection.account("example-account.testnet");
const accountBalance = await account.getAccountBalance();
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let account_balance = Tokens::of(account_id.clone())
.near_balance()
.fetch_from(&network)
.await
.unwrap();
Get Details
Returns information about an account, such as authorized apps.
- 🌐 JavaScript
// gets account details in terms of authorized apps and transactions
const account = await nearConnection.account("example-account.testnet");
const accountDetails = await account.getAccountDetails();
Get State
Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
- 🌐 JavaScript
- 🦀 Rust
const account = await nearConnection.account("example-account.testnet");
const accountState = await account.state();
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let account = Account::new(my_account_id.clone(), network);
let account_state = account.view().fetch_from(&network).await.unwrap();
Create Sub-Account
Create a sub-account.
- 🌐 JavaScript
- 🦀 Rust
// creates a sub-account using funds from the account used to create it.
const account = await nearConnection.account("example-account.testnet");
await account.createAccount(
"sub.example-account.testnet", // sub-account name
"8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for sub account
"10000000000000000000" // initial balance for new account in yoctoNEAR
);
Creating .near or .testnet accounts
In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. near
or testnet
), calling create_account
:
return await creatorAccount.functionCall({
contractId: "testnet",
methodName: "create_account",
args: {
new_account_id: "new-account.testnet",
new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
},
gas: "300000000000000",
attachedDeposit: utils.format.parseNearAmount(amount),
});
You will need to create a signer object first.
This example creates the sub-account and saves the seed phrase of a generated key pair to a file.
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let new_account_id: AccountId = "sub.example-account.testnet".parse().unwrap();
let res = Account::create_account()
.fund_myself(
new_account_id.clone(), // new account id
account_id.clone(), // account id funding the new account
NearToken::from_near(1), // Initial balance for the new account
)
.new_keypair() // Generates a new random key pair
.save_generated_seed_to_file("./new_account_seed".into())
.unwrap()
.with_signer(signer.clone())
.send_to(&network)
.await
.unwrap();
Creating a .near
or .testnet
account is the exact same process as creating a sub-account.
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let new_account_id: AccountId = "new_example-account.testnet".parse().unwrap();
let res = Account::create_account()
.fund_myself(
new_account_id.clone(), // new account id
account_id.clone(), // account id funding the new account
NearToken::from_near(1), // Initial balance for the new account
)
.new_keypair() // Generates a new random key pair
.save_generated_seed_to_file("./new_account_seed".into())
.unwrap()
.with_signer(signer.clone())
.send_to(&network)
.await
.unwrap();
Delete Account
- 🌐 JavaScript