NEAR API
The NEAR API is a collection of language-specific SDKs that allow developers to interact with the NEAR blockchain from both frontend and backend applications.
These libraries enable you to:
- Invoke view and call functions on deployed smart contracts
- Query on-chain data such as account state, keys, balance
- Create and manage NEAR accounts
- Transfer tokens, including native NEAR, Fungible Tokens, Non-Fungible Tokens
- Sign transactions/meta-transactions/messages and broadcasting them to the network
- Deploy smart contracts
Our API is available in multiple languages, including:
- JavaScript/TypeScript:
@near-js/accounts
- A collection of classes, functions, and types for interacting with accounts and contracts.@near-js/signers
- A collection of classes and types to facilitate cryptographic signing.@near-js/transactions
- A collection of classes, functions, and types for composing, serializing, and signing NEAR transactions.@near-js/tokens
- A collection of standard tokens.@near-js/providers
- A collection of classes, functions, and types for communicating with the NEAR RPC.@near-js/utils
- A collection of commonly-used functions and constants.@near-js/crypto
- A collection of classes and types for working with cryptographic key pairs.@near-js/types
- A collection of commonly-used classes and types..@near-js/keystores
,@near-js/keystores-node
and@near-js/keystores-browser
- A collection of classes for storing and managing NEAR-compatible cryptographic keys.
infoThe legacy
near-api-js
package has been replaced with a set of modular packages under the@near-js/*
namespace. These new libraries offer improved developer experience, better performance, and more flexibility by allowing you to import only the functionality you need. - Rust:
near-api-rs
- Python:
py-near
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
- π Python
Include the following core libraries as most applications will need them:
npm i @near-js/accounts@2 @near-js/providers@2 @near-js/signers@2
If you are building a site without using npm
, you can include libraries directly in your HTML file through a CDN.
<script src="https://cdn.jsdelivr.net/npm/@near-js/accounts/lib/esm/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@near-js/providers/lib/esm/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@near-js/signers/lib/esm/index.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.
import { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";
import { KeyPairSigner } from "@near-js/signers";
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 near_api
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β
- π¦ Rust
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
In previous versions of the NEAR SDK, signing transactions required setting up a KeyStore
to manage and retrieve keys. With the new @near-js/signers
package, this process has been simplified.
You can now use the Signer
abstraction, which provides a clean and extensible interface for signing. For most use cases, the KeyPairSigner
implementation is the simplest option β it allows you to sign transactions directly using a single in-memory key pair, without needing a persistent keystore.
- Browser
- Credentials Path
- File
- Private Key
- Seed Phrase
In browser, you typically donβt need to manage private keys manually. Instead, use Wallet Selector, the official wallet connection framework for NEAR dApps. It handles account access, key management, and user authentication across multiple wallet providers with a unified interface.
You can find a full example of browser-based signing with Wallet Selector
in the official example here.
Manually managing keys in the browser (not recommended)
If your use case requires direct control over keys in the browser (e.g. building a custom signing flow), you can use the KeyPairSigner
together with in-browser storage.
// Creates Signer using private key from local storage
import { KeyPairSigner } from "@near-js/signers";
import { BrowserLocalStorageKeyStore } from "@near-js/keystores-browser";
const keyStore = new BrowserLocalStorageKeyStore();
const key = await keyStore.getKey('testnet', 'user.testnet');
const signer = new KeyPairSigner(key);
For Node.js environments (CLI tools, backend services, etc) you can load signing keys from files using the UnencryptedFileSystemKeyStore
that reads unencrypted .json
key files stored in a directory on your local machine.
import { UnencryptedFileSystemKeyStore } from "@near-js/keystores-node";
import { homedir } from "os";
import path from "path";
// Create Signer using private key from a folder on the local machine
const credentialsDirectory = ".near-credentials";
const credentialsPath = path.join(homedir(), credentialsDirectory);
const keyStore = new UnencryptedFileSystemKeyStore(credentialsPath);
const key = await keyStore.getKey('testnet', 'user.testnet');
const signer = new KeyPairSigner(key);
See full example on GitHub
If you have a raw JSON file that includes a NEAR accountβs private key β it can directly parsed to then construct a KeyPairSigner.
import { KeyPairSigner } from "@near-js/signers";
import fs from "fs";
// Create Signer using private key from a JSON file on the local machine
const credentialsPath = "../credentials-file.json"; // Path relative to the working directory
const credentials = JSON.parse(fs.readFileSync(credentialsPath));
const signer = KeyPairSigner.fromSecretKey(credentials.private_key);
See full example on GitHub
It's common to load the NEAR private key from an environment variable or secret manager. With the new version of KeyPairSigner
, you can create ir directly from a raw private key string.
The private key must be in the format "ed25519:xxxxx..."
import { KeyPairSigner } from "@near-js/signers";
// Create Signer using private key from a raw private key string
const privateKey = "ed25519:1111222222....."; // put real key here
const signer = KeyPairSigner.fromSecretKey(privateKey);
See full example on GitHub
If you're working wallet recovery flows, developer tooling, or onboarding flows where users input their phrasesm you can derive the corresponding secret key and use it for signing.
To parse and derive a NEAR-compatible key pair from a seed phrase, youβll need to install the near-seed-phrase package:
npm i near-seed-phrase
Seed phrases are typically 12 words long, and are in the format "show three gate bird ..."
import { KeyPairSigner } from "@near-js/signers";
import { parseSeedPhrase } from "near-seed-phrase";
// Create Signer using seed phrase
const seedPhrase = "show three gate bird ..."; // 12 words long
const { secretKey } = parseSeedPhrase(seedPhrase);
const signer = KeyPairSigner.fromSecretKey(secretKey);
See full example on GitHub
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 endpoints can occasionally become unreliable due to network issues, server downtime, or rate limiting - leading to failed requests or dropped transactions. To make your application more resilient, you can define multiple RPC endpoints and automatically fall back to the next available one when an issue occurs.
- π JavaScript
- π Python
You can pass multiple individual Provider
instances into the FailoverRpcProvider
to improve the reliability of your application's connection.
Itβs also important to note that each Provider
can internally use different transport protocols (such as HTTPS or WebSocket), making the failover strategy flexible across various infrastructure setups.
import { JsonRpcProvider, FailoverRpcProvider } from "@near-js/providers";
const jsonProviders = [
new JsonRpcProvider({ url: "https://incorrect-rpc-url.com" }), // Incorrect RPC URL
new JsonRpcProvider(
{ url: "https://test.rpc.fastnear.com" }, // Valid RPC URL
{
retries: 3, // Number of retries before giving up on a request
backoff: 2, // Backoff factor for the retry delay
wait: 500, // Wait time between retries in milliseconds
} // Retry options
),
];
const provider = new FailoverRpcProvider(jsonProviders);
See full example on GitHub
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
You can create an Account
instance using the code below. At a minimum, it requires a Provider
to fetch data from the blockchain. If you also want to perform actions on behalf of the account (such as sending tokens, signing transactions, or managing keys) - youβll need to pass a Signer
as well. See the section above on how to create one using a private key, seed phrase, or JSON file.
import { JsonRpcProvider } from "@near-js/providers";
import { Account } from "@near-js/accounts";
const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
const account = new Account("user.testnet", provider, undefined // here could've been a Signer);
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
Once you've created an Account
instance, you can use it to query the balance of a token in its smallest unit β whether it's the native NEAR token or any other fungible token (FT). Let's start by checking the balance of NEAR.
If you need to display the balance in a human-readable format, each Token
instance provides a toDecimal
method that you can use to convert raw values to their standard decimal representation.
import { NEAR } from "@near-js/tokens";
const account = new Account("user.testnet", provider);
// returns yoctoNear amount as bigint
const amount = await account.getBalance(NEAR);
// converts to human-readable string like "1.234"
NEAR.toDecimal(amount);
For commonly used tokens like USDT or USDC, you can access pre-configured token definitions from the either @near-js/tokens/testnet
, or @near-js/tokens/mainnet
package, depending on the network. These built-in tokens make it easy to fetch balances without additional setup.
import { USDT } from "@near-js/tokens/testnet";
// import { USDT } from "@near-js/tokens/mainnet";
const account = new Account("user.testnet", provider);
// returns units as bigint
const amount = await account.getBalance(USDT);
// converts to human-readable string like "1.234"
USDT.toDecimal(amount);
If your token isnβt included in the provided collections, no problemβyou can manually create a Token
instance for any fungible token contract by following the example below.
import { FungibleToken } from "@near-js/tokens";
const account = new Account("user.testnet", provider);
const REF = new FungibleToken("ref.fakes.testnet", {
decimals: 18,
symbol: "REF",
});
// returns units as bigint
const amount = await account.getBalance(REF);
// converts to human-readable string like "1.234"
REF.toDecimal(amount);
See full example on GitHub
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
Once you've created an Account
instance, you can use it to query basic on-chain information about the account, such as its code hash and current storage usage.
const account = new Account("user.testnet", provider);
await account.getState();
While the Account
class represents a wallet on-chain, some use cases, like simply reading account state or contract data β do not require full account access. In those cases, you can skip creating an Account
and use the Provider
directly, as shown below.
await provider.viewAccount("user.testnet");
See full example on GitHub
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()
Create Named Accountβ
To create a named account like user.testnet
, you need to call the create_account
function on a top-level accountβs contract β thatβs testnet
on testnet or near
on mainnet. Yes, on NEAR, every account can have a contract deployed to it, even top-level ones.
Keep in mind that creating a named account requires a small amount of NEAR to cover Gas fees.
When creating a new account, youβll need to provide:
- A public key, which will be added to the account as FullAccess key
- An optional initial balance in NEAR (this can be zero if you donβt want to fund it right away)
- π JavaScript
- π¦ Rust
- π Python
Once you've created an Account
instance, you can create any available named account (as long as it's not already taken). To do this, the creator account must include a Signer
, since signing a transaction is required. If you're not sure how to set that up, check the section above on how to connect a signer.
const account = new Account("user.testnet", provider, signer);
// generate a keypair randomly
const keyPair = KeyPair.fromRandom("ed25519");
await account.createAccount(
"another_user.testnet",
keyPair.getPublicKey(),
// attaches 1.234 NEAR tokens that will become
// an initial balance of "another_user.testnet"
NEAR.toUnits("1.234")
);
See full example on GitHub
In some cases, you might need to create an account using a seed phrase. Hereβs how you can do that:
import { generateSeedPhrase } from "near-seed-phrase";
const account = new Account("user.testnet", provider, signer);
// get public key from a randomly generated seed phrase
const { seedPhrase, publicKey, secretKey } = generateSeedPhrase();
await account.createAccount(
"another_user.testnet",
publicKey,
// attaches 1.234 NEAR tokens that will become
// an initial balance of "another_user.testnet"
NEAR.toUnits("1.234")
);
See full example on GitHub
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 Sub-Accountβ
Accounts on NEAR can create sub-accounts under their own namespace, which is useful for organizing accounts by purpose β for example, project.user.testnet
.
The parent account DOES NOT have any control over its sub-accounts once they are created.
Keep in mind that creating a sub-account requires a small amount of NEAR to cover Gas fees.
To create a sub-account, the parent must send a transaction to itself with the CreateAccount
action. Just like when creating named accounts, you'll need to provide a public key that will be assigned to the new sub-account, along with an optional initial deposit to fund it (can be zero).
- π JavaScript
- π¦ Rust
- π Python
Once you've created an Account
instance, you can create any sub-account (as long as it hasn't been created previously). To do this, the creator account must include a Signer
, since signing a transaction is required. If you're not sure how to set that up, check the section above on how to connect a signer.
const account = new Account("user.testnet", provider, signer);
// generate a keypair randomly
const keyPair = KeyPair.fromRandom("ed25519");
await account.createAccount(
"project.user.testnet",
keyPair.getPublicKey(),
// attaches 1.234 NEAR tokens that will become
// an initial balance of "project.user.testnet"
NEAR.toUnits("1.234")
);
See full example on GitHub
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β
An account on NEAR can only delete itself β it CANNOT delete other accounts or its sub-accounts.
To delete an account, it must send a transaction to itself with the DeleteAccount
action, including a required parameter called beneficiary_id
. This is the account that will receive any remaining NEAR tokens.
Deleting an account DOES NOT affect its sub-accounts - they will remain active.
- π JavaScript
- π¦ Rust
const account = new Account("user.testnet", provider, signer);
// account "user.testnet" gets deleted
// and remaining funds will go to account "beneficiary.testnet" (if it exists)
await account.deleteAccount("beneficiary.testnet");
See full example on GitHub
Loading...
- Only NEAR tokens are transferred to the beneficiary.
- Fungible (FTs) or Non-Fungible tokens (NFTs) held by the account ARE NOT automatically transferred. These tokens are still associated with the account, even after the account is deleted. Make sure to transfer those assets manually before deletion, or you're risking losing them permanently! Once the account is gone, those assets are effectively stuck unless the same account is recreated by anyone (not necessarily you).
- If the beneficiary account doesn't exist, all NEAR tokens sent to it will be burned. Double-check the account ID before proceeding.
Transactionsβ
Send Tokensβ
Accounts can transfer different types of tokens to other accounts, including the native NEAR token and NEP-141 fungible tokens.
- π JavaScript
- π¦ Rust
- π Python
To begin with, youβll need the @near-js/tokens
package, which provides the necessary utilities.
Once you've created an Account
instance, you can transfer tokens to others. Letβs start by looking at how to transfer native NEAR
tokens.
import { NEAR } from "@near-js/tokens";
const account = new Account("user.testnet", provider, signer);
// transfer 0.1 NEAR tokens to receiver.testnet
await account.transfer({
token: NEAR,
amount: NEAR.toUnits("0.1"),
receiverId: "receiver.testnet"
});
You can also use the same package to send fungible tokens (NEP-141) like USDT β many of the most common tokens are included out of the box and can be imported from @near-js/tokens/testnet
or @near-js/tokens/mainnet
, depending on the network you're using.
Before receiving fungible tokens (NEP-141), the recipient must be registered on the tokenβs contract. If they arenβt, the transfer will fail.
If your use case involves sending tokens to users, you have two options:
- Cover the storage cost and register them yourself
- Ask the user to register in advance
Good news - if the account is already registered, any repeated registration attempt will automatically refund the storage deposit β so youβll never pay it twice.
import { USDT } from "@near-js/tokens/testnet";
const account = new Account("user.testnet", provider, signer);
// double-check that a recipient is registered
await USDT.registerAccount({
accountIdToRegister: "receiver.testnet",
fundingAccount: account,
})
// transfer 1.23 USDT to receiver.testnet
await account.transfer({
token: USDT,
amount: USDT.toUnits("1.23"),
receiverId: "receiver.testnet"
});
For more advanced use cases, such as working with custom or less common tokens, you can create your own instance of the FungibleToken
class by passing the appropriate parameters. The example below demonstrates this using the REF
token.
import { FungibleToken } from "@near-js/tokens/testnet";
const account = new Account("user.testnet", provider, signer);
const REF = new FungibleToken("ref.fakes.testnet", {
decimals: 18,
symbol: "REF",
});
// double-check that a recipient is registered
await REF.registerAccount({
accountIdToRegister: "receiver.testnet",
fundingAccount: account,
})
// transfer 2.34 REF to receiver.testnet
await account.transfer({
token: REF,
amount: REF.toUnits("2.34"),
receiverId: "receiver.testnet"
});
See full example on GitHub
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 smart contract exposes its methods, and making a function call that modifies state requires a Signer
/KeyPair
. You can optionally attach a NEAR
deposit to the call.
- π JavaScript
- π¦ Rust
- π Python
Once you've created an Account
instance, you can start interacting with smart contracts.
The most convenient way to interact with contracts is the TypedContract
class. It provides full type safety for method names, arguments, and return values, especially when used together with an ABI.
For example, lets say there is a Guestbook contract deployed at guestbook.near-examples.testnet
, and you want to add a message to it. To do that, youβd call its add_message
method.
import { NEAR } from "@near-js/tokens";
import { TypedContract, AbiRoot } from "@near-js/accounts";
// "as const satisfies AbiRoot" is necessary for TypeScript to infer ABI types
const guestbookAbi = {...} as const satisfies AbiRoot;
const account = new Account("user.testnet", provider, signer);
const contract = new TypedContract({
contractId: "guestbook.near-examples.testnet",
provider,
abi: guestbookAbi,
});
await contract.call.add_message({
account: account, // Account must have Signer to sign tx
args: {
text: "Hello, world!"
},
deposit: NEAR.toUnits("0.0001"), // optional
gas: BigInt("30000000000000") // 30 TGas, optional
});
See full example on GitHub
In this function call, weβve attached a small deposit of 0.001 NEAR to cover the storage cost of adding the message.
Weβve also attached 30 TGas to limit the amount of computational resources the method can consume.
What if I don't have ABI?
If no ABI was provided, TypedContract
would still work, though return types by default would be unknown
, which you could override with generics as in the example below:
type Message = { sender: string; text: string; premium: boolean };
const messages = await contract.view.get_messages<Message[]>();
// ^? { sender: string; text: string; premium: boolean }[]
You can also call contract methods directly using the Account
class. This approach is supported, but not recommended anymore, because it doesnβt provide compile-time safety for method names or arguments. The main benefit of this style is that it is quick to set up.
import { NEAR } from "@near-js/tokens";
const account = new Account("user.testnet", provider, signer);
await account.callFunction({
contractId: "guestbook.near-examples.testnet",
methodName: "add_message",
args: { text: "Hello, world!" },
deposit: NEAR.toUnits('0.001'), // 0.001 NEAR
gas: "30000000000000" // 30 TGas
});
See full example on GitHub
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
Once you've created an Account
instance, you can start sending transactions.
Letβs take a look at an example of a batched transaction that performs multiple actions in a single call - it increments a counter on a smart contract counter.near-examples.testnet
twice, then transfers 0.1 NEAR tokens to this address.
Each function call to increment the counter has 10 TGas attached, which is enough for a lightweight state update. No deposit is included with these calls, since they donβt store new data β just update existing values.
import { NEAR } from "@near-js/tokens";
const account = new Account("user.testnet", provider, signer);
await account.signAndSendTransaction({
receiverId: "counter.near-examples.testnet",
actions: [
actionCreators.functionCall(
"increment",
{},
"10000000000000", // 10 TGas
0 // 0 NEAR
),
actionCreators.functionCall(
"increment",
{},
"10000000000000", // 10 TGas
0 // 0 NEAR
),
actionCreators.transfer(NEAR.toUnits("0.1"))
],
});
See full example on GitHub
Loading...
Simultaneous Transactionsβ
While many other blockchains donβt support truly parallel transactions due to nonce collisions, NEAR takes a different approach. It supports access keys, and each key maintains its own independent nonce.
This means you can add multiple keys to an account and use them to sign and send transactions concurrently, without running into nonce conflicts. Itβs a powerful feature for parallel execution and high-throughput use cases.
Simultaneous execution means thereβs no guarantee of order or success. Any transaction may fail independently.
If your use case requires strict ordering or depends on all actions succeeding together, consider using cross-contract calls instead. They allow you to chain calls with guarantees around execution flow and error handling.
- π JavaScript
- π¦ Rust
- π Python
Once you've created an Account
instance, you can start by generating two new key pairs and adding them to the account. In our example, weβre using Full Access keys, but thatβs not a requirement β Function Call access keys can work just as well, depending on your use case.
If you already have the keys prepared, feel free to skip this step. We're including it here to show the full setup for learning purposes.
Notice that weβre adding both keys in a batched transaction. Learn more about it here.
const account = new Account("user.testnet", provider, signer);
const keyPairOne = KeyPair.fromRandom("ed25519");
const keyPairTwo = KeyPair.fromRandom("ed25519");
// add two keys in a single transaction
await account.signAndSendTransaction({
receiverId: account.accountId,
actions: [
actionCreators.addKey(
keyPairOne.getPublicKey(),
actionCreators.fullAccessKey()
),
actionCreators.addKey(
keyPairTwo.getPublicKey(),
actionCreators.fullAccessKey()
),
],
waitUntil: "FINAL",
});
Now that weβve created two separate keys, we need to create corresponding Account
instances for each one. These will be used to build and send different transactions independently.
One of the transactions adds a message to the Guestbook contract, while the other increments a counter on a different contract.
const accountOne = new Account(
accountId,
provider,
new KeyPairSigner(keyPairOne)
);
const accountTwo = new Account(
accountId,
provider,
new KeyPairSigner(keyPairTwo)
);
const signedTxOne = await accountOne.createSignedTransaction(
"guestbook.near-examples.testnet",
[
actionCreators.functionCall(
"add_message",
{ text: "Hello, world!" },
"30000000000000", // 30 TGas
NEAR.toUnits("0.001") // 0.001 NEAR
),
]
);
const signedTxTwo = await accountTwo.createSignedTransaction(
"counter.near-examples.testnet",
[
actionCreators.functionCall(
"increment",
{},
"10000000000000", // 10 TGas
0 // 0 NEAR
),
]
);
The last step is to broadcast both transactions concurrently to the network using the Provider
.
const sendTxOne = provider.sendTransaction(signedTxOne);
const sendTxTwo = provider.sendTransaction(signedTxTwo);
const transactionsResults = await Promise.all([sendTxOne, sendTxTwo]);
See full example on GitHub
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β
On NEAR, a smart contract is deployed as a WASM file. Every account has the potential to become a contract β you simply need to deploy code to it.
Unlike many other blockchains, contracts on NEAR are mutable, meaning you have the ability to redeploy updated versions to the same account. However, if you remove all access keys from the account, it becomes impossible to sign new deploy transactions, effectively locking the contract code permanently.
- π JavaScript