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
These examples are references to code snippets, feel free to explore the full code examples in context by clicking See full example on GitHub
below each example.
Install
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Include near-api-js
as a dependency in your package.
npm i 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
pip install py-near
Import
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
You can use the API library in the browser, or in Node.js runtime.
Loading...
Using the API in Node.js
All these examples are written for the browser, to use these examples in Node.js you should convert the project to an ES module. To do this, add the following to your package.json
:
Loading...
The methods to interact with the NEAR API are available through the prelude
module.
Loading...
You can use the NEAR API by importing the py_near
package, either entirely
import py_near
or only the parts you need, for example:
from py_near.account import Account
from py_near.providers import JsonProvider
Connecting to NEAR
- 🌐 JavaScript
- 🦀 Rust
The object returned from connect
is your entry-point for all commands in the API.
To transactions you'll need a KeyStore
.
Loading...
Mainnet/Localnet connection
// Mainnet config example
const connectionConfig = {
networkId: "mainnet",
keyStore: myKeyStore,
nodeUrl: "https://rpc.mainnet.near.org",
};
// Localnet config example
const connectionConfig = {
networkId: "local",
nodeUrl: "http://localhost:3030",
};
To interact with the blockchain you'll need to create a NetworkConfig
object.
Preset connections mainnet
and testnet
are available that come with standard configurations for each network.
Loading...
You can also create your own custom connection.
Loading...
Key Handlers: Stores & Signers
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
To sign transactions you'll need to a KeyStore
with valid keypairs.
- Browser
- Credentials Path
- File
- Private Key
- Seed Phrase
BrowserLocalStorageKeyStore
can only be used in the browser, it uses the browser's local storage to store the keys.
// Creates keyStore using private key in local storage
const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
UnencryptedFileSystemKeyStore
can be used is used to load keys from the legacy credentials directory used by the NEAR CLI.
Loading...
Keystores can be created by loading a private key from a json file.
Loading...
Keystores can be created by using a private key string.
Private keys have the format "ed25519:5Fg2...".
Loading...
Keystores can be created by using a seed phrase. To parse the seed phrase into a private key, the near-seed-phrase
library is needed.
npm i near-seed-phrase
Seed phrases have the format "shoe three gate ..." and are usually 12 words long.
Loading...
To sign transactions you'll need to create a Signer
that holds a valid keypair.
- Keystore
- Credentials Path
- File
- Private Key
- Seed Phrase
Signers can be created using the Keystore that is also used as the standard for saving keys with the NEAR CLI.
Loading...
Signers can be created using the credentials directory which is the legacy option for saving keys with the NEAR CLI.
Loading...
Signers can be created by loading a public and private key from a file.
Loading...
Signers can be created by using a private key string.
Private keys have the format "ed25519:5Fg2...".
Loading...
Signers can be created by using a seed phrase.
Seed phrases have the format "shoe three gate ..." and are usually 12 words long.
Loading...
TODO: not exactly the same in Python, it's more and account + RPC URL, or a JSON RPC provider
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
- 🐍 Python
Loading...
You can pass multiple RPC providers to JsonRpcProvider
from py_near.providers import JsonProvider
provider = JsonProvider(["https://test.rpc.fastnear.com", "https://rpc.testnet.pagoda.co"])
Account
Instantiate Account
This will return an Account object for you to interact with.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
You can instantiate any account with the following code:
from py_near.account import Account
account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
If you want to use it to submit transactions later, you need to also pass the private_key
param:
account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
Get Balance
Gets the available and staked balance of an account in yoctoNEAR.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
from py_near.account import Account
account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
account_balance = account.get_balance()
Get State
Get basic account information, such as its code hash and storage usage.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
from py_near.account import Account
account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
account_state = account.fetch_state()
Get Details
Returns the authorized apps of an account. This is a list of contracts that the account has function call access keys for.
- 🌐 JavaScript
Loading...
Create an Account
In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain account (i.e. near
or testnet
), calling create_account
. In this example we generate a new public key for the account by generating a random private key.
The deposit determines the initial balance of the account.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Creating an account from a seed phrase
You can also create an account with a public key that is derived from a randomly generated seed phrase.
Loading...
Loading...
Creating an account from a seed phrase
You can also create an account via a randomly generated seed phrase.
Loading...
await account.function_call("testnet", "create_account", {"new_account_id": "example-account.testnet", "new_public_key": "ed25519:..."}, "30000000000000", 1 * NEAR)
Create a Sub-Account
Accounts can create sub-accounts of themselves, which are useful for creating separate accounts for different purposes. It is important to remark that the parent account has no control over any of its sub-accounts.
The deposit determines the initial balance of the account.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
Create a sub-account and fund it with your main account:
from py_near.account import Account
from py_near.dapps.core import NEAR
account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
res = account.create_account(account_id="sub.example-account.testnet", public_key="...", initial_balance=1 * NEAR))
Delete Account
When deleting an account, you need to specify a beneficiary account id. This is the account that will receive the remaining NEAR balance of the account being deleted.
- 🌐 JavaScript
- 🦀 Rust
Loading...
Loading...
Only NEAR tokens will be transferred to the beneficiary, so you should transfer all your FTs, NFTs, etc. to another account before deleting.
If the beneficiary account does not exist, the NEAR tokens will be burned
Transactions
Send Tokens
Transfer NEAR tokens between accounts.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
from py_near.account import Account
from py_near.dapps.core import NEAR
account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
await account.send_money("receiver-account.testnet", 1 * NEAR))
Call Function
A call function changes the contract's state and requires a signer/keypair.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
Loading...
await account.function_call("usn.near", "ft_transfer", {"receiver_id": "bob.near", "amount": "1000000000000000000000000"})
Batch Actions
You can send multiple actions in a batch to a single receiver. If one action fails then the entire batch of actions will be reverted.
- 🌐 JavaScript
- 🦀 Rust
Loading...
Loading...
Simultaneous Transactions
Transactions can be sent in parallel to the network, so you don't have to wait for one transaction to complete before sending the next one. Note that these one transaction could be successful and the other one could fail.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
import asyncio
from py_near.account import Account
account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
# Prepare the transactions
tx1 = account.function_call("guestbook.near-examples.testnet", "add_message", { "text": "Hello, world!" })
tx2 = account.function_call("counter.near-examples.testnet", "increment", {})
# Send the transactions simultaneously
const transactionsResults = await asyncio.gather(tx1, tx2)
Deploy a Contract
You can deploy a contract from a compiled WASM file.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Note that the signer
here needs to be a signer for the same account_id
as the one used to construct the Contract
object.
Loading...
import asyncio
from py_near.account import Account
account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
await account.startup()
with open("contract.wasm", "rb") as f:
contract_code = f.read()
await account.deploy_contract(contract_code)
View Function
View functions are read-only functions that don't change the state of the contract. We can call these functions without a signer / keypair or any gas.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
view_call_result = await account.view_function("guestbook.near-examples.testnet", "total_messages", {})
# If args are required, they can be passed in like this in the 3rd argument:
# {
# "from_index": "0",
# "limit": "10"
# }
print(view_call_result)
Keys
Get All Access Keys
List all the access keys for an account.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
keys = await account.get_access_key_list()
Add Full Access Key
Add a new full access key to an account. Here we generate a random keypair, alternatively you can use a keypair from a seed phrase.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
keys = await account.add_full_access_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj")
Add Function Call Key
Add a new function call key to an account. When adding the key you should specify the contract id the key can call, an array of methods the key is allowed to call, and the allowance in gas for the key.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
await account.add_public_key(
"5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj",
"example-contract.testnet", # Contract this key is allowed to call
["example_method"], # Methods this key is allowed to call (optional)
0.25 * NEAR # Gas allowance key can use to call methods (optional)
)
Delete Access Key
When deleting an access key, you need to specify the public key of the key you want to delete.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
await account.delete_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj")
Utilities
NEAR to yoctoNEAR
Convert an amount in NEAR to an amount in yoctoNEAR.
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
Loading...
Loading...
from py_near.dapps.core import NEAR
amount_in_yocto = 1 * NEAR
Format Amount
- 🌐 JavaScript
- 🦀 Rust
Format an amount in yoctoNEAR to an amount in NEAR.
Loading...
Format an amount of NEAR into a string of NEAR or yoctoNEAR depending on the amount.
Loading...
Additional resources
- 🌐 JavaScript
- 🦀 Rust
- 🐍 Python
- Documentation
- Github
- Full Examples
- Cookbook which contains examples using the near-js/client package, a wrapper tree shakable package for near-api-js.