import Tabs from ‘@theme/Tabs’;
import TabItem from ‘@theme/TabItem’;
Here is a collection of the most commonly used methods within
near-api-js
. For more in-depth look into this library, please reference the TypeDocs.
Setup
Install
npm i near-api-js
Import
“`js
import * as nearAPI from “near-api-js”;
“`
“`js
const nearAPI = require(“near-api-js”);
“`
Key Store
“`js
// creates keyStore using private key in local storage
// *** REQUIRES SignIn using walletConnection.requestSignIn() ***
const { keyStores } = nearAPI;
const keyStore = new keyStores.BrowserLocalStorageKeyStore();
“`
“`js
// 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/docs/tools/near-cli#near-login
const { keyStores } = nearAPI;
const homedir = require(“os”).homedir();
const CREDENTIALS_DIR = “.near-credentials”;
const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
“`
“`js
// 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 keyStore = new keyStores.InMemoryKeyStore();
keyStore.setKey(NETWORK_ID, ACCOUNT_ID, KeyPair.fromString(credentials.private_key));
“`
“`js
// creates keyStore from a private key string
// you can define your key here or use an environment variable
const { keyStores, KeyPair } = nearAPI;
const keyStore = 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 keyStore.setKey(“testnet”, “example-account.testnet”, keyPair);
“`
Note: Key store is not required if you are not signing transactions (using view call methods on a contract)
Connect
“`js
const { connect } = nearAPI;
const config = {
networkId: “testnet”,
keyStore, // optional if not signing transactions
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 near = await connect(config);
“`
“`js
const { connect } = nearAPI;
const config = {
networkId: “mainnet”,
keyStore, // optional if not signing transactions
nodeUrl: “https://rpc.mainnet.near.org”,
walletUrl: “https://wallet.mainnet.near.org”,
helperUrl: “https://helper.mainnet.near.org”,
explorerUrl: “https://explorer.mainnet.near.org”,
};
const near = await connect(config);
“`
“`js
const { connect } = nearAPI;
const config = {
networkId: “betanet”,
keyStore, // optional if not signing transactions
nodeUrl: “https://rpc.betanet.near.org”,
walletUrl: “https://wallet.betanet.near.org”,
helperUrl: “https://helper.betanet.near.org”,
explorerUrl: “https://explorer.betanet.near.org”,
};
const near = await connect(config);
“`
“`js
const { connect } = nearAPI;
const config = {
networkId: “local”,
nodeUrl: “http://localhost:3030”,
walletUrl: “http://localhost:4000/wallet”,
};
const near = await connect(config);
“`
Wallet
Connection
“`js
const { connect, keyStores, WalletConnection } = nearAPI;
const config = {
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 near = await connect(config);
// create wallet connection
const wallet = new WalletConnection(near);
“`
“`js
const { connect, keyStores, WalletConnection } = nearAPI;
const config = {
networkId: “mainnet”,
keyStore: new keyStores.BrowserLocalStorageKeyStore(),
nodeUrl: “https://rpc.mainnet.near.org”,
walletUrl: “https://wallet.mainnet.near.org”,
helperUrl: “https://helper.mainnet.near.org”,
explorerUrl: “https://explorer.mainnet.near.org”,
};
// connect to NEAR
const near = await connect(config);
// create wallet connection
const wallet = new WalletConnection(near);
“`
“`js
const { connect, keyStores, WalletConnection } = nearAPI;
const config = {
networkId: “betanet”,
keyStore: new keyStores.BrowserLocalStorageKeyStore(),
nodeUrl: “https://rpc.betanet.near.org”,
walletUrl: “https://wallet.betanet.near.org”,
helperUrl: “https://helper.betanet.near.org”,
explorerUrl: “https://explorer.betanet.near.org”,
};
// connect to NEAR
const near = await connect(config);
// create wallet connection
const wallet = new WalletConnection(near);
“`
Sign In
// redirects user to wallet to authorize your dApp
// this creates an access key that will be stored in the browser's local storage
// access key can then be used to connect to NEAR and sign transactions via keyStore
const signIn = () => {
wallet.requestSignIn(
"example-contract.testnet", // contract requesting access
"Example App", // optional
"http://YOUR-URL.com/success", // optional
"http://YOUR-URL.com/failure" // optional
);
};
Note: Sign In is not required if you are using an alternative key store to local storage or you are not signing transactions (using view call methods on a contract)
Sign Out
const signOut = () => {
wallet.signOut();
};
Check if Signed In
if(wallet.isSignedIn()) {
doSomething();
}
Get Authorized Account Id
// returns account Id as string
const walletAccountId = wallet.getAccountId();
Get Authorized Account Object
// returns account object for transaction signing
const walletAccountObj = wallet.account();
Account
Load Account
const near = await connect(config);
const account = await near.account("example-account.testnet");
Create Account
// creates a new account using funds from the account used to create it
const near = await connect(config);
const account = await near.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
);
Delete Account
// deletes account found in the `account` object
// transfers remaining account balance to the accountId passed as an argument
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.deleteAccount("beneficiary-account.testnet");
Get Account Balance
// gets account balance
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.getAccountBalance();
Get Account details
// gets account details in terms of authorized apps and transactions
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.getAccountDetails();
Deploy a Contract
const near = await connect(config);
const account = await near.account("example-account.testnet");
const response = await account.deployContract(fs.readFileSync('./wasm_files/status_message.wasm'));
console.log(response);
Send Tokens
// sends NEAR tokens
const near = await connect(config);
const account = await near.account("sender-account.testnet");
await account.sendMoney(
"receiver-account.testnet", // receiver account
"1000000000000000000000000" // amount in yoctoNEAR
);
State
// gets the state of the account
const near = await connect(config);
const account = await near.account("example-account.testnet");
const response = await account.state();
console.log(response);
Contract
Load Contract
“`js
const contract = new nearAPI.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.
}
);
“`
[`config setup`](/docs/api/naj-quick-reference#connect)
“`js
const contract = new nearAPI.Contract(
wallet.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: wallet.Account(), // account object to initialize and sign transactions.
}
);
“`
[`config setup`](/docs/api/naj-quick-reference#connect)
Call Contract
“`js
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)
);
“`
“`js
const response = await contract.view_method_name();
console.log(response);
“`
“`js
const response = await contract.view_method_name({ arg_name: “arg_value” });
console.log(response);
“`
Access Keys
Add Full Access Key
// takes public key as string for argument
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
Add Function Access Key
// adds function access key
const near = await connect(config);
const account = await near.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)
);
Get All Access Keys
// returns all access keys associated with an account
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.getAccessKeys();
Delete Access Key
// takes public key as string for argument
const near = await connect(config);
const account = await near.account("example-account.testnet");
await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
Utils
NEAR => yoctoNEAR
// converts NEAR amount into yoctoNEAR (10^-24)
const { utils } = nearAPI;
const amountInYocto = utils.format.parseNearAmount("1");
YoctoNEAR => NEAR
// converts yoctoNEAR (10^-24) amount into NEAR
const { utils } = nearAPI;
const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");