pub struct Near { /* private fields */ }Expand description
The main client for interacting with NEAR Protocol.
The Near client is the single entry point for all NEAR operations.
It can be configured with a signer for write operations, or used
without a signer for read-only operations.
Transport (RPC connection) and signing are separate concerns — the client
holds a shared Arc<RpcClient> and an optional signer. Use with_signer
to derive new clients that share the same connection but sign as different accounts.
§Example
use near_kit::*;
#[tokio::main]
async fn main() -> Result<(), near_kit::Error> {
// Read-only client (no signer)
let near = Near::testnet().build();
let balance = near.balance("alice.testnet").await?;
println!("Balance: {}", balance);
// Client with signer for transactions
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
near.transfer("bob.testnet", "1 NEAR").await?;
Ok(())
}§Multiple Accounts
For production apps that manage multiple accounts, set up the connection once
and derive signing contexts with with_signer:
let near = Near::testnet().build();
let alice = near.with_signer(InMemorySigner::new("alice.testnet", "ed25519:...")?);
let bob = near.with_signer(InMemorySigner::new("bob.testnet", "ed25519:...")?);
// Both share the same RPC connection, sign as different accountsImplementations§
Source§impl Near
impl Near
Sourcepub fn mainnet() -> NearBuilder
pub fn mainnet() -> NearBuilder
Create a builder for mainnet.
Sourcepub fn testnet() -> NearBuilder
pub fn testnet() -> NearBuilder
Create a builder for testnet.
Sourcepub fn custom(rpc_url: impl Into<String>) -> NearBuilder
pub fn custom(rpc_url: impl Into<String>) -> NearBuilder
Create a builder with a custom RPC URL.
Sourcepub fn from_env() -> Result<Near, Error>
pub fn from_env() -> Result<Near, Error>
Create a configured client from environment variables.
Reads the following environment variables:
NEAR_NETWORK(optional):"mainnet","testnet", or a custom RPC URL. Defaults to"testnet"if not set.NEAR_CHAIN_ID(optional): Overrides the chain identifier (e.g.,"pinet"). If set, always overrides the chain ID inferred fromNEAR_NETWORK, including the built-in"mainnet"and"testnet"presets. Typically only needed for custom networks.NEAR_ACCOUNT_ID(optional): Account ID for signing transactions.NEAR_PRIVATE_KEY(optional): Private key for signing (e.g.,"ed25519:...").NEAR_MAX_NONCE_RETRIES(optional): Number of nonce retries onInvalidNonceerrors.0means no retries. Defaults to3.
If NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY are both set, the client will
be configured with signing capability. Otherwise, it will be read-only.
§Example
# Environment variables
export NEAR_NETWORK=https://rpc.pinet.near.org
export NEAR_CHAIN_ID=pinet
export NEAR_ACCOUNT_ID=alice.testnet
export NEAR_PRIVATE_KEY=ed25519:...
export NEAR_MAX_NONCE_RETRIES=10// Auto-configures from environment
let near = Near::from_env()?;
// If credentials are set, transactions work
near.transfer("bob.testnet", "1 NEAR").await?;§Errors
Returns an error if:
NEAR_ACCOUNT_IDis set withoutNEAR_PRIVATE_KEY(or vice versa)NEAR_PRIVATE_KEYcontains an invalid key formatNEAR_MAX_NONCE_RETRIESis set but not a valid integer
Sourcepub fn sandbox(network: &impl SandboxNetwork) -> Near
pub fn sandbox(network: &impl SandboxNetwork) -> Near
Create a builder configured for a sandbox network.
This automatically configures the client with the sandbox’s RPC URL and root account credentials, making it ready for transactions.
§Example
use near_sandbox::Sandbox;
use near_kit::*;
let sandbox = Sandbox::start_sandbox().await?;
let near = Near::sandbox(&sandbox);
// Root account credentials are auto-configured - ready for transactions!
near.transfer("alice.sandbox", "10 NEAR").await?;Sourcepub fn account_id(&self) -> &AccountId
pub fn account_id(&self) -> &AccountId
Get the signer’s account ID.
§Panics
Panics if no signer is configured. Use try_account_id
if you need to handle the no-signer case.
Sourcepub fn try_account_id(&self) -> Option<&AccountId>
pub fn try_account_id(&self) -> Option<&AccountId>
Get the signer’s account ID, if a signer is configured.
Sourcepub fn public_key(&self) -> Option<PublicKey>
pub fn public_key(&self) -> Option<PublicKey>
Get the signer’s public key, if a signer is configured.
This does not advance the rotation counter on RotatingSigner.
Sourcepub fn signer(&self) -> Option<Arc<dyn Signer>>
pub fn signer(&self) -> Option<Arc<dyn Signer>>
Get the signer, if one is configured.
This is useful when you need to pass the signer to another system or construct clients manually.
Sourcepub fn max_nonce_retries(self, retries: u32) -> Near
pub fn max_nonce_retries(self, retries: u32) -> Near
Set the number of nonce retries on InvalidNonce errors.
0 means no retries (send once), 1 means one retry, etc. Defaults to 3.
Useful when you need to adjust retries after construction, for example when using a client obtained from a sandbox.
§Example
let relayer = sandbox.max_nonce_retries(u32::MAX);Sourcepub fn with_signer(&self, signer: impl Signer + 'static) -> Near
pub fn with_signer(&self, signer: impl Signer + 'static) -> Near
Create a new client that shares this client’s transport but uses a different signer.
This is the recommended way to manage multiple accounts. The RPC connection
is shared (via Arc), so there’s no overhead from creating multiple clients.
§Example
// Set up a shared connection
let near = Near::testnet().build();
// Derive signing contexts for different accounts
let alice = near.with_signer(InMemorySigner::new("alice.testnet", "ed25519:...")?);
let bob = near.with_signer(InMemorySigner::new("bob.testnet", "ed25519:...")?);
// Both share the same RPC connection
// alice.transfer("carol.testnet", NearToken::from_near(1)).await?;
// bob.transfer("carol.testnet", NearToken::from_near(2)).await?;Sourcepub fn balance(&self, account_id: impl TryIntoAccountId) -> BalanceQuery
pub fn balance(&self, account_id: impl TryIntoAccountId) -> BalanceQuery
Get account balance.
Returns a query builder that can be customized with block reference options before awaiting.
§Example
let near = Near::testnet().build();
// Simple query
let balance = near.balance("alice.testnet").await?;
println!("Available: {}", balance.available);
// Query at specific block height
let balance = near.balance("alice.testnet")
.at_block(100_000_000)
.await?;
// Query with specific finality
let balance = near.balance("alice.testnet")
.finality(Finality::Optimistic)
.await?;Sourcepub fn account(&self, account_id: impl TryIntoAccountId) -> AccountQuery
pub fn account(&self, account_id: impl TryIntoAccountId) -> AccountQuery
Get full account information.
§Example
let near = Near::testnet().build();
let account = near.account("alice.testnet").await?;
println!("Storage used: {} bytes", account.storage_usage);Sourcepub fn account_exists(
&self,
account_id: impl TryIntoAccountId,
) -> AccountExistsQuery
pub fn account_exists( &self, account_id: impl TryIntoAccountId, ) -> AccountExistsQuery
Check if an account exists.
§Example
let near = Near::testnet().build();
if near.account_exists("alice.testnet").await? {
println!("Account exists!");
}Sourcepub fn view<T>(
&self,
contract_id: impl TryIntoAccountId,
method: &str,
) -> ViewCall<T>
pub fn view<T>( &self, contract_id: impl TryIntoAccountId, method: &str, ) -> ViewCall<T>
Call a view function on a contract.
Returns a query builder that can be customized with arguments and block reference options before awaiting.
§Example
let near = Near::testnet().build();
// Simple view call
let count: u64 = near.view("counter.testnet", "get_count").await?;
// View call with arguments
let messages: Vec<String> = near.view("guestbook.testnet", "get_messages")
.args(serde_json::json!({ "limit": 10 }))
.await?;Sourcepub fn access_keys(&self, account_id: impl TryIntoAccountId) -> AccessKeysQuery
pub fn access_keys(&self, account_id: impl TryIntoAccountId) -> AccessKeysQuery
Get all access keys for an account.
§Example
let near = Near::testnet().build();
let keys = near.access_keys("alice.testnet").await?;
for key_info in keys.keys {
println!("Key: {}", key_info.public_key);
}Sourcepub async fn sign_message(
&self,
params: SignMessageParams,
) -> Result<SignedMessage, Error>
pub async fn sign_message( &self, params: SignMessageParams, ) -> Result<SignedMessage, Error>
Sign a message for off-chain authentication (NEP-413).
This enables users to prove account ownership without gas fees or blockchain transactions. Commonly used for:
- Web3 authentication/login
- Off-chain message signing
- Proof of account ownership
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
let signed = near.sign_message(nep413::SignMessageParams {
message: "Login to MyApp".to_string(),
recipient: "myapp.com".to_string(),
nonce: nep413::generate_nonce(),
callback_url: None,
state: None,
}).await?;
println!("Signed by: {}", signed.account_id);@see https://github.com/near/NEPs/blob/master/neps/nep-0413.md
Sourcepub fn transfer(
&self,
receiver: impl TryIntoAccountId,
amount: impl IntoNearToken,
) -> TransactionBuilder
pub fn transfer( &self, receiver: impl TryIntoAccountId, amount: impl IntoNearToken, ) -> TransactionBuilder
Transfer NEAR tokens.
Returns a transaction builder that can be customized with wait options before awaiting.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
// Preferred: typed constructor
near.transfer("bob.testnet", NearToken::from_near(1)).await?;
// Transfer with wait for finality
near.transfer("bob.testnet", NearToken::from_near(1000))
.wait_until(TxExecutionStatus::Final)
.await?;Sourcepub fn call(
&self,
contract_id: impl TryIntoAccountId,
method: &str,
) -> CallBuilder
pub fn call( &self, contract_id: impl TryIntoAccountId, method: &str, ) -> CallBuilder
Call a function on a contract.
Returns a transaction builder that can be customized with arguments, gas, deposit, and other options before awaiting.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
// Simple call
near.call("counter.testnet", "increment").await?;
// Call with args, gas, and deposit
near.call("nft.testnet", "nft_mint")
.args(serde_json::json!({ "token_id": "1" }))
.gas("100 Tgas")
.deposit("0.1 NEAR")
.await?;Sourcepub fn deploy_from(
&self,
contract_ref: impl GlobalContractRef,
) -> TransactionBuilder
pub fn deploy_from( &self, contract_ref: impl GlobalContractRef, ) -> TransactionBuilder
Deploy a contract from the global registry.
Accepts either a CryptoHash (for immutable contracts identified by hash)
or an account ID string/AccountId (for publisher-updatable contracts).
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
// Deploy by publisher (updatable)
near.deploy_from("publisher.near").await?;
// Deploy by hash (immutable)
near.deploy_from(code_hash).await?;§Panics
Panics if no signer is configured.
Sourcepub fn publish(
&self,
code: impl Into<Vec<u8>>,
mode: PublishMode,
) -> TransactionBuilder
pub fn publish( &self, code: impl Into<Vec<u8>>, mode: PublishMode, ) -> TransactionBuilder
Publish a contract to the global registry.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
let wasm_code = std::fs::read("contract.wasm").unwrap();
// Publish updatable contract (identified by your account)
near.publish(wasm_code.clone(), PublishMode::Updatable).await?;
// Publish immutable contract (identified by its hash)
near.publish(wasm_code, PublishMode::Immutable).await?;§Panics
Panics if no signer is configured.
Sourcepub fn add_full_access_key(&self, public_key: PublicKey) -> TransactionBuilder
pub fn add_full_access_key(&self, public_key: PublicKey) -> TransactionBuilder
Sourcepub fn delete_key(&self, public_key: PublicKey) -> TransactionBuilder
pub fn delete_key(&self, public_key: PublicKey) -> TransactionBuilder
Sourcepub fn transaction(
&self,
receiver_id: impl TryIntoAccountId,
) -> TransactionBuilder
pub fn transaction( &self, receiver_id: impl TryIntoAccountId, ) -> TransactionBuilder
Create a transaction builder for multi-action transactions.
This allows chaining multiple actions (transfers, function calls, account creation, etc.) into a single atomic transaction. All actions either succeed together or fail together.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
// Create a new sub-account with funding and a key
let new_public_key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse()?;
near.transaction("new.alice.testnet")
.create_account()
.transfer("5 NEAR")
.add_full_access_key(new_public_key)
.send()
.await?;
// Multiple function calls in one transaction
near.transaction("contract.testnet")
.call("method1")
.args(serde_json::json!({ "value": 1 }))
.call("method2")
.args(serde_json::json!({ "value": 2 }))
.send()
.await?;Sourcepub fn state_init(
&self,
state_init: DeterministicAccountStateInit,
deposit: impl IntoNearToken,
) -> TransactionBuilder
pub fn state_init( &self, state_init: DeterministicAccountStateInit, deposit: impl IntoNearToken, ) -> TransactionBuilder
Create a NEP-616 deterministic state init transaction.
The receiver_id is automatically derived from the state init parameters,
so unlike transaction(), no receiver needs to be specified.
§Example
let si = DeterministicAccountStateInit::by_hash(code_hash, Default::default());
let outcome = near.state_init(si, NearToken::from_near(5))
.send()
.await?;§Panics
Panics if the deposit amount string cannot be parsed.
Sourcepub async fn send(
&self,
signed_tx: &SignedTransaction,
) -> Result<FinalExecutionOutcome, Error>
pub async fn send( &self, signed_tx: &SignedTransaction, ) -> Result<FinalExecutionOutcome, Error>
Send a pre-signed transaction.
Use this with transactions signed via .sign() for offline signing
or inspection before sending.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
// Sign offline
let signed = near.transfer("bob.testnet", NearToken::from_near(1))
.sign()
.await?;
// Send later
let outcome = near.send(&signed).await?;Sourcepub async fn send_with_options(
&self,
signed_tx: &SignedTransaction,
wait_until: TxExecutionStatus,
) -> Result<SendTxResponse, Error>
pub async fn send_with_options( &self, signed_tx: &SignedTransaction, wait_until: TxExecutionStatus, ) -> Result<SendTxResponse, Error>
Send a pre-signed transaction with custom wait options.
Returns the raw SendTxResponse, which
always contains the transaction_hash and final_execution_status. The
outcome field is Some when the transaction has been executed, and
None for non-executed wait levels (None, Included, IncludedFinal).
Note: Unlike send, this method does not convert
InvalidTxError failures into Error::InvalidTx. Callers that need
structured error handling for invalid transactions should inspect
outcome.status themselves or use send instead.
Sourcepub async fn view_with_args<T: DeserializeOwned + Send + 'static, A: Serialize>(
&self,
contract_id: impl TryIntoAccountId,
method: &str,
args: &A,
) -> Result<T, Error>
pub async fn view_with_args<T: DeserializeOwned + Send + 'static, A: Serialize>( &self, contract_id: impl TryIntoAccountId, method: &str, args: &A, ) -> Result<T, Error>
Call a view function with arguments (convenience method).
Sourcepub async fn call_with_args<A: Serialize>(
&self,
contract_id: impl TryIntoAccountId,
method: &str,
args: &A,
) -> Result<FinalExecutionOutcome, Error>
pub async fn call_with_args<A: Serialize>( &self, contract_id: impl TryIntoAccountId, method: &str, args: &A, ) -> Result<FinalExecutionOutcome, Error>
Call a function with arguments (convenience method).
Sourcepub async fn call_with_options<A: Serialize>(
&self,
contract_id: impl TryIntoAccountId,
method: &str,
args: &A,
gas: Gas,
deposit: NearToken,
) -> Result<FinalExecutionOutcome, Error>
pub async fn call_with_options<A: Serialize>( &self, contract_id: impl TryIntoAccountId, method: &str, args: &A, gas: Gas, deposit: NearToken, ) -> Result<FinalExecutionOutcome, Error>
Call a function with full options (convenience method).
Sourcepub fn contract<T: Contract>(
&self,
contract_id: impl TryIntoAccountId,
) -> T::Client
pub fn contract<T: Contract>( &self, contract_id: impl TryIntoAccountId, ) -> T::Client
Create a typed contract client.
This method creates a type-safe client for interacting with a contract,
using the interface defined via the #[near_kit::contract] macro.
§Example
use near_kit::*;
use serde::Serialize;
#[near_kit::contract]
pub trait Counter {
fn get_count(&self) -> u64;
#[call]
fn increment(&mut self);
#[call]
fn add(&mut self, args: AddArgs);
}
#[derive(Serialize)]
pub struct AddArgs {
pub value: u64,
}
async fn example(near: &Near) -> Result<(), near_kit::Error> {
let counter = near.contract::<Counter>("counter.testnet");
// View call - type-safe!
let count = counter.get_count().await?;
// Change call - type-safe!
counter.increment().await?;
counter.add(AddArgs { value: 5 }).await?;
Ok(())
}Sourcepub fn ft(&self, contract: impl IntoContractId) -> Result<FungibleToken, Error>
pub fn ft(&self, contract: impl IntoContractId) -> Result<FungibleToken, Error>
Get a fungible token client for a NEP-141 contract.
Accepts either a string/AccountId for raw addresses, or a KnownToken
constant (like tokens::USDC) which auto-resolves based on the network.
§Example
let near = Near::mainnet().build();
// Use a known token - auto-resolves based on network
let usdc = near.ft(tokens::USDC)?;
// Or use a raw address
let custom = near.ft("custom-token.near")?;
// Get metadata
let meta = usdc.metadata().await?;
println!("{} ({})", meta.name, meta.symbol);
// Get balance - returns FtAmount for nice formatting
let balance = usdc.balance_of("alice.near").await?;
println!("Balance: {}", balance); // e.g., "1.5 USDC"Sourcepub fn nft(
&self,
contract: impl IntoContractId,
) -> Result<NonFungibleToken, Error>
pub fn nft( &self, contract: impl IntoContractId, ) -> Result<NonFungibleToken, Error>
Get a non-fungible token client for a NEP-171 contract.
Accepts either a string/AccountId for raw addresses, or a contract
identifier that implements IntoContractId.
§Example
let near = Near::testnet().build();
let nft = near.nft("nft-contract.near")?;
// Get a specific token
if let Some(token) = nft.token("token-123").await? {
println!("Owner: {}", token.owner_id);
}
// List tokens for an owner
let tokens = nft.tokens_for_owner("alice.near", None, Some(10)).await?;