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_ACCOUNT_ID(optional): Account ID for signing transactions.NEAR_PRIVATE_KEY(optional): Private key for signing (e.g.,"ed25519:...").
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=testnet
export NEAR_ACCOUNT_ID=alice.testnet
export NEAR_PRIVATE_KEY=ed25519:...// 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 format
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) -> Option<&AccountId>
pub fn account_id(&self) -> Option<&AccountId>
Get the signer’s account ID, if a signer is configured.
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::near(1)).await?;
// bob.transfer("carol.testnet", NearToken::near(2)).await?;Sourcepub fn balance(&self, account_id: impl AsRef<str>) -> BalanceQuery
pub fn balance(&self, account_id: impl AsRef<str>) -> 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 AsRef<str>) -> AccountQuery
pub fn account(&self, account_id: impl AsRef<str>) -> 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 AsRef<str>) -> AccountExistsQuery
pub fn account_exists(&self, account_id: impl AsRef<str>) -> 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 AsRef<str>, method: &str) -> ViewCall<T>
pub fn view<T>(&self, contract_id: impl AsRef<str>, 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 AsRef<str>) -> AccessKeysQuery
pub fn access_keys(&self, account_id: impl AsRef<str>) -> 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 AsRef<str>,
amount: impl IntoNearToken,
) -> TransactionBuilder
pub fn transfer( &self, receiver: impl AsRef<str>, 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::near(1)).await?;
// Transfer with wait for finality
near.transfer("bob.testnet", NearToken::near(1000))
.wait_until(TxExecutionStatus::Final)
.await?;Sourcepub fn call(&self, contract_id: impl AsRef<str>, method: &str) -> CallBuilder
pub fn call(&self, contract_id: impl AsRef<str>, 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(
&self,
account_id: impl AsRef<str>,
code: impl Into<Vec<u8>>,
) -> TransactionBuilder
pub fn deploy( &self, account_id: impl AsRef<str>, code: impl Into<Vec<u8>>, ) -> TransactionBuilder
Deploy a contract.
§Example
let near = Near::testnet()
.credentials("ed25519:...", "alice.testnet")?
.build();
let wasm_code = std::fs::read("contract.wasm").unwrap();
near.deploy("alice.testnet", wasm_code).await?;Sourcepub fn add_full_access_key(
&self,
account_id: impl AsRef<str>,
public_key: PublicKey,
) -> TransactionBuilder
pub fn add_full_access_key( &self, account_id: impl AsRef<str>, public_key: PublicKey, ) -> TransactionBuilder
Add a full access key to an account.
Sourcepub fn delete_key(
&self,
account_id: impl AsRef<str>,
public_key: PublicKey,
) -> TransactionBuilder
pub fn delete_key( &self, account_id: impl AsRef<str>, public_key: PublicKey, ) -> TransactionBuilder
Delete an access key from an account.
Sourcepub fn transaction(&self, receiver_id: impl AsRef<str>) -> TransactionBuilder
pub fn transaction(&self, receiver_id: impl AsRef<str>) -> 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 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::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<FinalExecutionOutcome, Error>
pub async fn send_with_options( &self, signed_tx: &SignedTransaction, wait_until: TxExecutionStatus, ) -> Result<FinalExecutionOutcome, Error>
Send a pre-signed transaction with custom wait options.
Sourcepub async fn view_with_args<T: DeserializeOwned + Send + 'static, A: Serialize>(
&self,
contract_id: impl AsRef<str>,
method: &str,
args: &A,
) -> Result<T, Error>
pub async fn view_with_args<T: DeserializeOwned + Send + 'static, A: Serialize>( &self, contract_id: impl AsRef<str>, 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 AsRef<str>,
method: &str,
args: &A,
) -> Result<FinalExecutionOutcome, Error>
pub async fn call_with_args<A: Serialize>( &self, contract_id: impl AsRef<str>, 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 AsRef<str>,
method: &str,
args: &A,
gas: Gas,
deposit: NearToken,
) -> Result<FinalExecutionOutcome, Error>
pub async fn call_with_options<A: Serialize>( &self, contract_id: impl AsRef<str>, method: &str, args: &A, gas: Gas, deposit: NearToken, ) -> Result<FinalExecutionOutcome, Error>
Call a function with full options (convenience method).
Sourcepub fn contract<T: Contract + ?Sized>(
&self,
contract_id: impl AsRef<str>,
) -> T::Client<'_>
pub fn contract<T: Contract + ?Sized>( &self, contract_id: impl AsRef<str>, ) -> 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?;