Skip to main content

TransactionBuilder

Struct TransactionBuilder 

Source
pub struct TransactionBuilder { /* private fields */ }
Expand description

Builder for constructing multi-action transactions.

Created via crate::Near::transaction. Supports chaining multiple actions into a single atomic transaction.

§Example

let near = Near::testnet()
    .credentials("ed25519:...", "alice.testnet")?
    .build();

// Single action
near.transaction("bob.testnet")
    .transfer(NearToken::near(1))
    .send()
    .await?;

// Multiple actions (atomic)
let key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse()?;
near.transaction("new.alice.testnet")
    .create_account()
    .transfer(NearToken::near(5))
    .add_full_access_key(key)
    .send()
    .await?;

Implementations§

Source§

impl TransactionBuilder

Source

pub fn create_account(self) -> Self

Add a create account action.

Creates a new sub-account. Must be followed by transfer and add_key to properly initialize the account.

Source

pub fn transfer(self, amount: impl IntoNearToken) -> Self

Add a transfer action.

Transfers NEAR tokens to the receiver account.

§Example
near.transaction("bob.testnet")
    .transfer(NearToken::near(1))
    .send()
    .await?;
§Panics

Panics if the amount string cannot be parsed.

Source

pub fn deploy(self, code: impl Into<Vec<u8>>) -> Self

Add a deploy contract action.

Deploys WASM code to the receiver account.

Source

pub fn call(self, method: &str) -> CallBuilder

Add a function call action.

Returns a CallBuilder for configuring the call with args, gas, and deposit.

§Example
near.transaction("contract.testnet")
    .call("set_greeting")
        .args(serde_json::json!({ "greeting": "Hello" }))
        .gas(Gas::tgas(10))
        .deposit(NearToken::ZERO)
    .call("another_method")
        .args(serde_json::json!({ "value": 42 }))
    .send()
    .await?;
Source

pub fn add_full_access_key(self, public_key: PublicKey) -> Self

Add a full access key to the account.

Source

pub fn add_function_call_key( self, public_key: PublicKey, receiver_id: impl AsRef<str>, method_names: Vec<String>, allowance: Option<NearToken>, ) -> Self

Add a function call access key to the account.

§Arguments
  • public_key - The public key to add
  • receiver_id - The contract this key can call
  • method_names - Methods this key can call (empty = all methods)
  • allowance - Maximum amount this key can spend (None = unlimited)
Source

pub fn delete_key(self, public_key: PublicKey) -> Self

Delete an access key from the account.

Source

pub fn delete_account(self, beneficiary_id: impl AsRef<str>) -> Self

Delete the account and transfer remaining balance to beneficiary.

Source

pub fn stake(self, amount: impl IntoNearToken, public_key: PublicKey) -> Self

Add a stake action.

§Panics

Panics if the amount string cannot be parsed.

Source

pub fn signed_delegate_action( self, signed_delegate: SignedDelegateAction, ) -> Self

Add a signed delegate action to this transaction (for relayers).

This is used by relayers to wrap a user’s signed delegate action and submit it to the blockchain, paying for the gas on behalf of the user.

§Example
// Relayer receives base64 payload from user
let signed_delegate = SignedDelegateAction::from_base64(payload)?;

// Relayer submits it, paying the gas
let result = relayer
    .transaction(signed_delegate.sender_id().as_str())
    .signed_delegate_action(signed_delegate)
    .send()
    .await?;
Source

pub async fn delegate( self, options: DelegateOptions, ) -> Result<DelegateResult, Error>

Build and sign a delegate action for meta-transactions (NEP-366).

This allows the user to sign a set of actions off-chain, which can then be submitted by a relayer who pays the gas fees. The user’s signature authorizes the actions, but they don’t need to hold NEAR for gas.

§Example
// User builds and signs a delegate action
let result = near
    .transaction("contract.testnet")
    .call("add_message")
        .args(serde_json::json!({ "text": "Hello!" }))
        .gas(Gas::tgas(30))
    .delegate(Default::default())
    .await?;

// Send payload to relayer via HTTP
println!("Payload to send: {}", result.payload);
Source

pub fn publish_contract(self, code: impl Into<Vec<u8>>, by_hash: bool) -> Self

Publish a contract to the global registry.

Global contracts are deployed once and can be referenced by multiple accounts, saving storage costs. Two modes are available:

  • by_hash = false (default): Contract is identified by the signer’s account ID. The signer can update the contract later, and all users will automatically use the updated version.

  • by_hash = true: Contract is identified by its code hash. This creates an immutable contract that cannot be updated.

§Example
let wasm_code = std::fs::read("contract.wasm")?;

// Publish updatable contract (identified by your account)
near.transaction("alice.testnet")
    .publish_contract(wasm_code.clone(), false)
    .send()
    .await?;

// Publish immutable contract (identified by its hash)
near.transaction("alice.testnet")
    .publish_contract(wasm_code, true)
    .send()
    .await?;
Source

pub fn deploy_from_hash(self, code_hash: CryptoHash) -> Self

Deploy a contract from the global registry by code hash.

References a previously published immutable contract.

§Example
near.transaction("alice.testnet")
    .deploy_from_hash(code_hash)
    .send()
    .await?;
Source

pub fn deploy_from_publisher(self, publisher_id: impl AsRef<str>) -> Self

Deploy a contract from the global registry by publisher account.

References a contract published by the given account. The contract can be updated by the publisher.

§Example
near.transaction("alice.testnet")
    .deploy_from_publisher("contract-publisher.near")
    .send()
    .await?;
Source

pub fn state_init_by_hash( self, code_hash: CryptoHash, data: BTreeMap<Vec<u8>, Vec<u8>>, deposit: impl IntoNearToken, ) -> Self

Create a NEP-616 deterministic state init action with code hash reference.

The receiver_id is automatically set to the deterministically derived account ID: "0s" + hex(keccak256(borsh(state_init))[12..32])

§Example
// Note: the receiver_id passed to transaction() is ignored for state_init -
// it will be replaced with the derived deterministic account ID
let outcome = near.transaction("alice.testnet")
    .state_init_by_hash(code_hash, Default::default(), NearToken::near(1))
    .send()
    .await?;
§Panics

Panics if the deposit amount string cannot be parsed.

Source

pub fn state_init_by_publisher( self, publisher_id: impl AsRef<str>, data: BTreeMap<Vec<u8>, Vec<u8>>, deposit: impl IntoNearToken, ) -> Self

Create a NEP-616 deterministic state init action with publisher account reference.

The receiver_id is automatically set to the deterministically derived account ID.

§Example
// Note: the receiver_id passed to transaction() is ignored for state_init -
// it will be replaced with the derived deterministic account ID
let outcome = near.transaction("alice.testnet")
    .state_init_by_publisher("contract-publisher.near", Default::default(), NearToken::near(1))
    .send()
    .await?;
§Panics

Panics if the deposit amount string cannot be parsed.

Source

pub fn sign_with(self, signer: impl Signer + 'static) -> Self

Override the signer for this transaction.

Source

pub fn wait_until(self, status: TxExecutionStatus) -> Self

Set the execution wait level.

Source

pub async fn sign(self) -> Result<SignedTransaction, Error>

Sign the transaction without sending it.

Returns a SignedTransaction that can be inspected or sent later.

§Example
let signed = near.transaction("bob.testnet")
    .transfer(NearToken::near(1))
    .sign()
    .await?;

// Inspect the transaction
println!("Hash: {}", signed.transaction.get_hash());
println!("Actions: {:?}", signed.transaction.actions);

// Send it later
let outcome = near.send(&signed).await?;
Source

pub async fn sign_offline( self, block_hash: CryptoHash, nonce: u64, ) -> Result<SignedTransaction, Error>

Sign the transaction offline without network access.

This is useful for air-gapped signing workflows where you need to provide the block hash and nonce manually (obtained from a separate online machine).

§Arguments
  • block_hash - A recent block hash (transaction expires ~24h after this block)
  • nonce - The next nonce for the signing key (current nonce + 1)
§Example
// On online machine: get block hash and nonce
// let block = near.rpc().block(BlockReference::latest()).await?;
// let access_key = near.rpc().view_access_key(...).await?;

// On offline machine: sign with pre-fetched values
let block_hash: CryptoHash = "11111111111111111111111111111111".parse().unwrap();
let nonce = 12345u64;

let signed = near.transaction("bob.testnet")
    .transfer(NearToken::near(1))
    .sign_offline(block_hash, nonce)
    .await?;

// Transport signed_tx.to_base64() back to online machine
Source

pub fn send(self) -> TransactionSend

Send the transaction.

This is equivalent to awaiting the builder directly.

Trait Implementations§

Source§

impl IntoFuture for TransactionBuilder

Source§

type Output = Result<FinalExecutionOutcome, Error>

The output that the future will produce on completion.
Source§

type IntoFuture = Pin<Box<dyn Future<Output = <TransactionBuilder as IntoFuture>::Output> + Send>>

Which kind of future are we turning this into?
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

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> 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, 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