Skip to main content

Near

Struct Near 

Source
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 accounts

Implementations§

Source§

impl Near

Source

pub fn mainnet() -> NearBuilder

Create a builder for mainnet.

Source

pub fn testnet() -> NearBuilder

Create a builder for testnet.

Source

pub fn custom(rpc_url: impl Into<String>) -> NearBuilder

Create a builder with a custom RPC URL.

Source

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_ID is set without NEAR_PRIVATE_KEY (or vice versa)
  • NEAR_PRIVATE_KEY contains an invalid key format
Source

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?;
Source

pub fn rpc(&self) -> &RpcClient

Get the underlying RPC client.

Source

pub fn rpc_url(&self) -> &str

Get the RPC URL.

Source

pub fn account_id(&self) -> Option<&AccountId>

Get the signer’s account ID, if a signer is configured.

Source

pub fn network(&self) -> Network

Get the network this client is connected to.

Source

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?;
Source

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?;
Source

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);
Source

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!");
}
Source

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?;
Source

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);
}
Source

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

Source

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?;
Source

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?;
Source

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?;
Source

pub fn add_full_access_key( &self, account_id: impl AsRef<str>, public_key: PublicKey, ) -> TransactionBuilder

Add a full access key to an account.

Source

pub fn delete_key( &self, account_id: impl AsRef<str>, public_key: PublicKey, ) -> TransactionBuilder

Delete an access key from an account.

Source

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?;
Source

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?;
Source

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.

Source

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).

Source

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).

Source

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).

Source

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(())
}
Source

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"
Source

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?;

Trait Implementations§

Source§

impl Clone for Near

Source§

fn clone(&self) -> Near

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Near

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<NearBuilder> for Near

Source§

fn from(builder: NearBuilder) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Near

§

impl !RefUnwindSafe for Near

§

impl Send for Near

§

impl Sync for Near

§

impl Unpin for Near

§

impl UnsafeUnpin for Near

§

impl !UnwindSafe for Near

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more