Struct alloy_contract::CallBuilder

source ·
pub struct CallBuilder<T, P, D, N: Network = Ethereum> {
    pub provider: P,
    /* private fields */
}
Expand description

A builder for sending a transaction via eth_sendTransaction, or calling a contract via eth_call.

The builder can be .awaited directly, which is equivalent to invoking call. Prefer using call when possible, as awaiting the builder directly will consume it, and currently also boxes the future due to type system limitations.

A call builder can currently be instantiated in the following ways:

Each method represents a different way to decode the output of the contract call.

§Note

This will set state overrides for eth_call, but this is not supported by all clients.

§Examples

Using sol!:

use alloy_contract::SolCallBuilder;
use alloy_primitives::{Address, U256};
use alloy_sol_types::sol;

sol! {
    #[sol(rpc)] // <-- Important!
    contract MyContract {
        function doStuff(uint a, bool b) public returns(address c, bytes32 d);
    }
}

let provider = ...;
let address = Address::ZERO;
let contract = MyContract::new(address, &provider);

// Through `contract.<function_name>(args...)`
let a = U256::ZERO;
let b = true;
let builder: SolCallBuilder<_, _, MyContract::doStuffCall, _> = contract.doStuff(a, b);
let MyContract::doStuffReturn { c: _, d: _ } = builder.call().await?;

// Through `contract.call_builder(&<FunctionCall { args... }>)`:
// (note that this is discouraged because it's inherently less type-safe)
let call = MyContract::doStuffCall { a, b };
let builder: SolCallBuilder<_, _, MyContract::doStuffCall, _> = contract.call_builder(&call);
let MyContract::doStuffReturn { c: _, d: _ } = builder.call().await?;

Using ContractInstance:

use alloy_primitives::{Address, Bytes, U256};
use alloy_dyn_abi::DynSolValue;
use alloy_contract::{CallBuilder, ContractInstance, DynCallBuilder, Interface, RawCallBuilder};

let dynamic_abi: JsonAbi = ...;
let interface = Interface::new(dynamic_abi);

let provider = ...;
let address = Address::ZERO;
let contract: ContractInstance<_, _, _> = interface.connect(address, &provider);

// Build and call the function:
let call_builder: DynCallBuilder<_, _, _> = contract.function("doStuff", &[U256::ZERO.into(), true.into()])?;
let result: Vec<DynSolValue> = call_builder.call().await?;

// You can also decode the output manually. Get the raw bytes:
let raw_result: Bytes = call_builder.call_raw().await?;
// Or, equivalently:
let raw_builder: RawCallBuilder<_, _, _> = call_builder.clone().clear_decoder();
let raw_result: Bytes = raw_builder.call().await?;
// Decode the raw bytes:
let decoded_result: Vec<DynSolValue> = call_builder.decode_output(raw_result, false)?;

Fields§

§provider: P

The provider.

Implementations§

source§

impl<T, P, D, N: Network> CallBuilder<T, P, D, N>

source

pub fn into_transaction_request(self) -> N::TransactionRequest

Converts the call builder to the inner transaction request

source§

impl<T: Transport + Clone, P: Provider<T, N>, N: Network> CallBuilder<T, P, Function, N>

source

pub fn clear_decoder(self) -> RawCallBuilder<T, P, N>

Clears the decoder, returning a raw call builder.

source§

impl<T: Transport + Clone, P: Provider<T, N>, C: SolCall, N: Network> CallBuilder<T, P, PhantomData<C>, N>

source

pub fn clear_decoder(self) -> RawCallBuilder<T, P, N>

Clears the decoder, returning a raw call builder.

source§

impl<T: Transport + Clone, P: Provider<T, N>, N: Network> CallBuilder<T, P, (), N>

source

pub fn with_sol_decoder<C: SolCall>(self) -> SolCallBuilder<T, P, C, N>

Sets the decoder to the provided SolCall.

Converts the raw call builder into a sol call builder.

Note that generally you would want to instantiate a sol call builder directly using the sol! macro, but this method is provided for flexibility, for example to convert a raw deploy call builder into a sol call builder.

§Examples

Decode a return value from a constructor:

sol! {
    // NOTE: This contract is not meant to be deployed on-chain, but rather
    // used in a static call with its creation code as the call data.
    #[sol(rpc, bytecode = "34601457602a60e052600161010052604060e0f35b5f80fdfe")]
    contract MyContract {
        // The type returned by the constructor.
        #[derive(Debug, PartialEq)]
        struct MyStruct {
            uint64 a;
            bool b;
        }

        constructor() {
            MyStruct memory s = MyStruct(42, true);
            bytes memory returnData = abi.encode(s);
            assembly {
                return(add(returnData, 0x20), mload(returnData))
            }
        }

        // A shim that represents the return value of the constructor.
        function constructorReturn() external view returns (MyStruct memory s);
    }
}

let provider = ...;
let call_builder = MyContract::deploy_builder(&provider)
    .with_sol_decoder::<MyContract::constructorReturnCall>();
let result = call_builder.call().await?;
assert_eq!(result.s, MyContract::MyStruct { a: 42, b: true });
source§

impl<T: Transport + Clone, P: Provider<T, N>, N: Network> CallBuilder<T, P, (), N>

source

pub fn new_raw(provider: P, input: Bytes) -> Self

Creates a new call builder with the provided provider and ABI encoded input.

Will not decode the output of the call, meaning that call will behave the same as call_raw.

source

pub fn new_raw_deploy(provider: P, input: Bytes) -> Self

Creates a new call builder with the provided provider and contract deploy code.

Will not decode the output of the call, meaning that call will behave the same as call_raw.

source§

impl<T: Transport + Clone, P: Provider<T, N>, D: CallDecoder, N: Network> CallBuilder<T, P, D, N>

source

pub fn chain_id(self, chain_id: ChainId) -> Self

Sets the chain_id field in the transaction to the provided value

source

pub fn from(self, from: Address) -> Self

Sets the from field in the transaction to the provided value.

source

pub fn kind(self, to: TxKind) -> Self

Sets the transaction request to the provided tx kind.

source

pub fn to(self, to: Address) -> Self

Sets the to field in the transaction to the provided address.

source

pub fn sidecar(self, blob_sidecar: BlobTransactionSidecar) -> Self

Sets the sidecar field in the transaction to the provided value.

source

pub fn legacy(self) -> Self

Uses a Legacy transaction instead of an EIP-1559 one to execute the call

source

pub fn gas(self, gas: u64) -> Self

Sets the gas field in the transaction to the provided value

source

pub fn gas_price(self, gas_price: u128) -> Self

Sets the gas_price field in the transaction to the provided value If the internal transaction is an EIP-1559 one, then it sets both max_fee_per_gas and max_priority_fee_per_gas to the same value

source

pub fn max_fee_per_gas(self, max_fee_per_gas: u128) -> Self

Sets the max_fee_per_gas in the transaction to the provide value

source

pub fn max_priority_fee_per_gas(self, max_priority_fee_per_gas: u128) -> Self

Sets the max_priority_fee_per_gas in the transaction to the provide value

source

pub fn max_fee_per_blob_gas(self, max_fee_per_blob_gas: u128) -> Self

Sets the max_fee_per_blob_gas in the transaction to the provided value

source

pub fn access_list(self, access_list: AccessList) -> Self

Sets the access_list in the transaction to the provided value

source

pub fn value(self, value: U256) -> Self

Sets the value field in the transaction to the provided value

source

pub fn nonce(self, nonce: u64) -> Self

Sets the nonce field in the transaction to the provided value

source

pub fn map<F>(self, f: F) -> Self

Applies a function to the internal transaction request.

source

pub const fn block(self, block: BlockId) -> Self

Sets the block field for sending the tx to the chain

source

pub fn state(self, state: StateOverride) -> Self

Sets the state override set.

§Note

Not all client implementations will support this as a parameter to eth_call.

source

pub fn calldata(&self) -> &Bytes

Returns the underlying transaction’s ABI-encoded data.

source

pub async fn estimate_gas(&self) -> Result<u64>

Returns the estimated gas cost for the underlying transaction to be executed If state overrides are set, they will be applied to the gas estimation.

source

pub fn call(&self) -> EthCall<'_, '_, D, T, N>

Queries the blockchain via an eth_call without submitting a transaction to the network. If state overrides are set, they will be applied to the call.

Returns the decoded the output by using the provided decoder. If this is not desired, use call_raw to get the raw output data.

source

pub fn call_raw(&self) -> EthCall<'_, '_, (), T, N>

Queries the blockchain via an eth_call without submitting a transaction to the network. If state overrides are set, they will be applied to the call.

Does not decode the output of the call, returning the raw output data instead.

See call for more information.

source

pub fn decode_output( &self, data: Bytes, validate: bool, ) -> Result<D::CallOutput>

Decodes the output of a contract function using the provided decoder.

source

pub async fn deploy(&self) -> Result<Address>

Broadcasts the underlying transaction to the network as a deployment transaction, returning the address of the deployed contract after the transaction has been confirmed.

Returns an error if the transaction is not a deployment transaction, or if the contract address is not found in the deployment transaction’s receipt.

For more fine-grained control over the deployment process, use send instead.

Note that the deployment address can be pre-calculated if the from address and nonce are known using calculate_create_address.

source

pub async fn send(&self) -> Result<PendingTransactionBuilder<T, N>>

Broadcasts the underlying transaction to the network.

Returns a builder for configuring the pending transaction watcher. See Provider::send_transaction for more information.

source

pub fn calculate_create_address(&self) -> Option<Address>

Calculates the address that will be created by the transaction, if any.

Returns None if the transaction is not a contract creation (the to field is set), or if the from or nonce fields are not set.

source§

impl<T: Transport, P: Clone, D, N: Network> CallBuilder<T, &P, D, N>

source

pub fn with_cloned_provider(self) -> CallBuilder<T, P, D, N>

Clones the provider and returns a new builder with the cloned provider.

Trait Implementations§

source§

impl<T, P, D, N: Network> AsRef<<N as Network>::TransactionRequest> for CallBuilder<T, P, D, N>

source§

fn as_ref(&self) -> &N::TransactionRequest

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T: Clone, P: Clone, D: Clone, N: Clone + Network> Clone for CallBuilder<T, P, D, N>

source§

fn clone(&self) -> CallBuilder<T, P, D, N>

Returns a copy 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<T, P, D: CallDecoder, N: Network> Debug for CallBuilder<T, P, D, N>

source§

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

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

impl<T, P, D, N> IntoFuture for CallBuilder<T, P, D, N>
where T: Transport + Clone, P: Provider<T, N>, D: CallDecoder + Send + Sync + Unpin, N: Network, Self: 'static,

CallBuilder can be turned into a Future automatically with .await.

Defaults to calling CallBuilder::call.

§Note

This requires Self: 'static due to a current limitation in the Rust type system, namely that the associated future type, the returned future, must be a concrete type (Box<dyn Future ...>) and cannot be an opaque type (impl Future ...) because impl Trait in this position is not stable yet. See rust-lang/rust#63063.

§

type Output = Result<<D as CallDecoder>::CallOutput, Error>

The output that the future will produce on completion.
§

type IntoFuture = Pin<Box<dyn Future<Output = <CallBuilder<T, P, D, N> 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§

§

impl<T, P, D, N> Freeze for CallBuilder<T, P, D, N>

§

impl<T, P, D, N> RefUnwindSafe for CallBuilder<T, P, D, N>

§

impl<T, P, D, N> Send for CallBuilder<T, P, D, N>
where P: Send, D: Send, T: Send,

§

impl<T, P, D, N> Sync for CallBuilder<T, P, D, N>
where P: Sync, D: Sync, T: Sync,

§

impl<T, P, D, N> Unpin for CallBuilder<T, P, D, N>
where P: Unpin, D: Unpin, T: Unpin,

§

impl<T, P, D, N> UnwindSafe for CallBuilder<T, P, D, N>

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§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> 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
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToHex for T
where T: AsRef<[u8]>,

source§

fn encode_hex<U>(&self) -> U
where U: FromIterator<char>,

👎Deprecated: use ToHexExt instead
Encode the hex strict representing self into the result. Lower case letters are used (e.g. f9b4ca).
source§

fn encode_hex_upper<U>(&self) -> U
where U: FromIterator<char>,

👎Deprecated: use ToHexExt instead
Encode the hex strict representing self into the result. Upper case letters are used (e.g. F9B4CA).
source§

impl<T> ToHexExt for T
where T: AsRef<[u8]>,

source§

fn encode_hex(&self) -> String

Encode the hex strict representing self into the result. Lower case letters are used (e.g. f9b4ca).
source§

fn encode_hex_upper(&self) -> String

Encode the hex strict representing self into the result. Upper case letters are used (e.g. F9B4CA).
source§

fn encode_hex_with_prefix(&self) -> String

Encode the hex strict representing self into the result with prefix 0x. Lower case letters are used (e.g. 0xf9b4ca).
source§

fn encode_hex_upper_with_prefix(&self) -> String

Encode the hex strict representing self into the result with prefix 0X. Upper case letters are used (e.g. 0xF9B4CA).
source§

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

§

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

§

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

§

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

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

source§

impl<T> MaybeSendSync for T