Struct TransactionBuilder

Source
pub struct TransactionBuilder<'a, P: JsonRpcProvider + 'static> { /* private fields */ }

Implementations§

Source§

impl<'a, P: JsonRpcProvider + 'static> TransactionBuilder<'a, P>

Source

pub fn signers(&self) -> &Vec<Signer>

Source

pub fn additional_network_fee(&self) -> &u64

Source

pub fn additional_system_fee(&self) -> &u64

Source

pub fn attributes(&self) -> &Vec<TransactionAttribute>

Source

pub fn script(&self) -> &Option<Bytes>

Source§

impl<'a, P: JsonRpcProvider + 'static> TransactionBuilder<'a, P>

Source

pub fn set_additional_network_fee(&mut self, val: u64) -> &mut Self

Source

pub fn set_additional_system_fee(&mut self, val: u64) -> &mut Self

Source

pub fn set_script(&mut self, val: Option<Bytes>) -> &mut Self

Source§

impl<'a, P: JsonRpcProvider + 'static> TransactionBuilder<'a, P>

Source

pub const BALANCE_OF_FUNCTION: &'static str = "balanceOf"

Source

pub const DUMMY_PUB_KEY: &'static str = "02ec143f00b88524caf36a0121c2de09eef0519ddbe1c710a00f0e2663201ee4c0"

Source

pub fn new() -> Self

Creates a new TransactionBuilder instance with default values.

§Returns

A new TransactionBuilder instance with default values.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::HttpProvider;

let tx_builder: TransactionBuilder<'_, HttpProvider> = TransactionBuilder::default();
Source

pub fn with_client(client: &'a RpcClient<P>) -> Self

Creates a new TransactionBuilder instance with a client reference.

§Arguments
  • client - A reference to an RPC client for network operations.
§Returns

A new TransactionBuilder instance with the specified client.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};

let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
let client = RpcClient::new(provider);
let tx_builder = TransactionBuilder::with_client(&client);
Source

pub fn version(&mut self, version: u8) -> &mut Self

Sets the version of the transaction.

§Arguments
  • version - The transaction version (typically 0 for Neo N3).
§Returns

A mutable reference to the TransactionBuilder for method chaining.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};

let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
let client = RpcClient::new(provider);
let mut tx_builder = TransactionBuilder::with_client(&client);
tx_builder.version(0);
Source

pub fn nonce(&mut self, nonce: u32) -> Result<&mut Self, TransactionError>

Sets the nonce of the transaction.

The nonce is a random number used to prevent transaction duplication.

§Arguments
  • nonce - A random number to prevent transaction duplication.
§Returns

A Result containing a mutable reference to the TransactionBuilder for method chaining, or a TransactionError if the nonce is invalid.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};

let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
let client = RpcClient::new(provider);
let mut tx_builder = TransactionBuilder::with_client(&client);
tx_builder.nonce(1234567890).unwrap();
Source

pub fn valid_until_block( &mut self, block: u32, ) -> Result<&mut Self, TransactionError>

Sets the block height until which the transaction is valid.

In Neo N3, transactions have a limited validity period defined by block height. This helps prevent transaction replay attacks and cleans up the memory pool.

§Arguments
  • block - The block height until which the transaction is valid.
§Returns

A Result containing a mutable reference to the TransactionBuilder for method chaining, or a TransactionError if the block height is invalid.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};
use neo3::neo_clients::APITrait;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
    let client = RpcClient::new(provider);
     
    let current_height = client.get_block_count().await?;
     
    let mut tx_builder = TransactionBuilder::with_client(&client);
    tx_builder.valid_until_block(current_height + 5760)?; // Valid for ~1 day
     
    Ok(())
}
Source

pub fn first_signer( &mut self, sender: &Account, ) -> Result<&mut Self, TransactionError>

Source

pub fn first_signer_by_hash( &mut self, sender: &H160, ) -> Result<&mut Self, TransactionError>

Source

pub fn extend_script(&mut self, script: Vec<u8>) -> &mut Self

Source

pub async fn call_invoke_script( &self, ) -> Result<InvocationResult, TransactionError>

Source

pub async fn build(&mut self) -> Result<Transaction<'_, P>, TransactionError>

Builds a transaction from the current builder configuration

§Returns

A Result containing the built transaction or a TransactionError

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
    let client = RpcClient::new(provider);
     
    let mut tx_builder = TransactionBuilder::with_client(&client);
    tx_builder.version(0)
              .nonce(1234567890)?
              .valid_until_block(100)?;
     
    let tx = tx_builder.build().await?;
     
    Ok(())
}
Source

pub async fn get_unsigned_tx( &mut self, ) -> Result<Transaction<'_, P>, TransactionError>

Source

pub async fn sign(&mut self) -> Result<Transaction<'_, P>, BuilderError>

Signs the transaction with the provided signers.

This method creates an unsigned transaction, signs it with the appropriate signers, and returns the signed transaction. For account signers, it uses the account’s private key to create a signature. For contract signers, it creates a contract witness.

§Returns

A Result containing the signed Transaction if successful, or a BuilderError if an error occurs during signing.

§Errors

Returns an error if:

  • The transaction cannot be built (see get_unsigned_tx)
  • A multi-signature account is used (these require manual signing)
  • An account does not have a private key
  • Witness creation fails
§Examples
use neo3::neo_builder::{TransactionBuilder, ScriptBuilder, AccountSigner};
use neo3::neo_clients::{HttpProvider, RpcClient};
use neo3::neo_protocol::{Account, AccountTrait};
use neo3::neo_types::ContractParameter;
use std::str::FromStr;
use neo3::neo_clients::APITrait;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
    let client = RpcClient::new(provider);
     
    // Create an account for signing
    let account = Account::from_wif("YOUR_WIF_HERE")?;
     
    // Create a proper contract invocation script
    let contract_hash = neo3::neo_types::ScriptHash::from_str("0xd2a4cff31913016155e38e474a2c06d08be276cf")?; // GAS
    let from_address = account.get_script_hash();
    let to_address = neo3::neo_types::ScriptHash::from_str("0x0000000000000000000000000000000000000000")?;
    let amount = 1_000_000i64;
    let mut script_builder = ScriptBuilder::new();
    script_builder.contract_call(
        &contract_hash,
        "transfer",
        &[
            ContractParameter::from(from_address),
            ContractParameter::from(to_address),
            ContractParameter::integer(amount),
            ContractParameter::any()
        ],
        None
    )?;
    let script = script_builder.to_bytes();
     
    // Create and configure the transaction
    let mut tx_builder = TransactionBuilder::with_client(&client);
    tx_builder.extend_script(script);
    let account_signer = AccountSigner::called_by_entry(&account)?;
    tx_builder.set_signers(vec![account_signer.into()])?;
    tx_builder.valid_until_block(client.get_block_count().await? + 5760)?; // Valid for ~1 day

    // Sign the transaction
    let signed_tx = tx_builder.sign().await?;
     
    // Send the transaction to the network
    let tx_response = signed_tx.send_tx().await?;
    println!("Transaction sent: {:?}", tx_response);
     
    Ok(())
}
Source

pub fn set_signers( &mut self, signers: Vec<Signer>, ) -> Result<&mut Self, TransactionError>

Sets the signers for the transaction.

Signers are entities that authorize the transaction. They can be accounts, contracts, or other entities that can provide a signature or verification method.

§Arguments
  • signers - A vector of Signer objects representing the transaction signers.
§Returns

A Result containing a mutable reference to the TransactionBuilder for method chaining, or a TransactionError if there are duplicate signers or if adding the signers would exceed the maximum allowed number of attributes.

§Examples
use neo3::neo_builder::{TransactionBuilder, Signer, AccountSigner};
use neo3::neo_protocol::{Account, AccountTrait};

let account = Account::create().unwrap();
let account_signer = AccountSigner::called_by_entry(&account).unwrap();
let signer: Signer = account_signer.into();

let mut tx_builder: TransactionBuilder<'_, HttpProvider> = TransactionBuilder::default();
tx_builder.set_signers(vec![signer]).unwrap();
Source

pub fn add_attributes( &mut self, attributes: Vec<TransactionAttribute>, ) -> Result<&mut Self, TransactionError>

Adds transaction attributes to the transaction.

Transaction attributes provide additional metadata or functionality to the transaction. This method checks for duplicate attribute types and ensures the total number of attributes does not exceed the maximum allowed.

§Arguments
  • attributes - A vector of TransactionAttribute objects to add to the transaction.
§Returns

A Result containing a mutable reference to the TransactionBuilder for method chaining, or a TransactionError if adding the attributes would exceed the maximum allowed number of attributes or if an attribute of the same type already exists.

§Examples
use neo3::neo_builder::{TransactionBuilder, TransactionAttribute};
use neo3::neo_clients::{HttpProvider, RpcClient};

let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
let client = RpcClient::new(provider);
let mut tx_builder = TransactionBuilder::with_client(&client);

// Add a high-priority attribute
let high_priority_attr = TransactionAttribute::HighPriority;

// Add a not-valid-before attribute
let not_valid_before_attr = TransactionAttribute::NotValidBefore { height: 1000 };

tx_builder.add_attributes(vec![high_priority_attr, not_valid_before_attr]).unwrap();
Source

pub fn do_if_sender_cannot_cover_fees<F>( &mut self, consumer: F, ) -> Result<&mut Self, TransactionError>
where F: FnMut(i64, i64) + Send + Sync + 'static,

Checks if the sender account of this transaction can cover the network and system fees. If not, executes the given consumer supplying it with the required fee and the sender’s GAS balance.

The check and potential execution of the consumer is only performed when the transaction is built, i.e., when calling TransactionBuilder::sign or TransactionBuilder::get_unsigned_transaction.

  • Parameter consumer: The consumer
  • Returns: This transaction builder (self) Checks if the sender account can cover the transaction fees and executes a callback if not.

This method allows you to provide a callback function that will be executed if the sender account does not have enough GAS to cover the network and system fees. The callback receives the required fee amount and the sender’s current balance.

§Arguments
  • consumer - A callback function that takes two i64 parameters: the required fee and the sender’s current balance.
§Returns

A Result containing a mutable reference to the TransactionBuilder for method chaining, or a TransactionError if a fee error handler is already set.

§Examples
use neo3::neo_builder::TransactionBuilder;
use neo3::neo_clients::{HttpProvider, RpcClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider = HttpProvider::new("https://testnet1.neo.org:443").unwrap();
    let client = RpcClient::new(provider);
     
    let mut tx_builder = TransactionBuilder::with_client(&client);
     
    // Add a callback for insufficient funds
    tx_builder.do_if_sender_cannot_cover_fees(|required_fee, balance| {
        println!("Insufficient funds: Required {} GAS, but only have {} GAS",
            required_fee as f64 / 100_000_000.0,
            balance as f64 / 100_000_000.0);
    })?;
     
    Ok(())
}
Source

pub fn throw_if_sender_cannot_cover_fees( &mut self, error: TransactionError, ) -> Result<&mut Self, TransactionError>

Checks if the sender account of this transaction can cover the network and system fees. If not, otherwise throw an error created by the provided supplier.

The check and potential throwing of the exception is only performed when the transaction is built, i.e., when calling TransactionBuilder::sign or TransactionBuilder::get_unsigned_transaction.

  • Parameter error: The error to throw
  • Returns: This transaction builder (self)

Trait Implementations§

Source§

impl<'a, P: JsonRpcProvider + 'static> Clone for TransactionBuilder<'a, P>

Source§

fn clone(&self) -> Self

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

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

Performs copy-assignment from source. Read more
Source§

impl<'a, P: JsonRpcProvider + 'static> Debug for TransactionBuilder<'a, P>

Source§

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

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

impl<'a, P: Default + JsonRpcProvider + 'static> Default for TransactionBuilder<'a, P>

Source§

fn default() -> TransactionBuilder<'a, P>

Returns the “default value” for a type. Read more
Source§

impl<'a, P: JsonRpcProvider + 'static> Hash for TransactionBuilder<'a, P>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a, P: JsonRpcProvider + 'static> PartialEq for TransactionBuilder<'a, P>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

const fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, P: JsonRpcProvider + 'static> Eq for TransactionBuilder<'a, P>

Auto Trait Implementations§

§

impl<'a, P> Freeze for TransactionBuilder<'a, P>

§

impl<'a, P> !RefUnwindSafe for TransactionBuilder<'a, P>

§

impl<'a, P> !Send for TransactionBuilder<'a, P>

§

impl<'a, P> !Sync for TransactionBuilder<'a, P>

§

impl<'a, P> Unpin for TransactionBuilder<'a, P>

§

impl<'a, P> !UnwindSafe for TransactionBuilder<'a, P>

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
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

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

§

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
§

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

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
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
§

impl<T> ErasedDestructor for T
where T: 'static,