pub struct CallBuilder<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:
- by
sol!-generated contract structs’ methods (through the#[sol(rpc)]attribute) (SolCallBuilder); - by
ContractInstance’s methods (DynCallBuilder); - using
CallBuilder::new_raw(RawCallBuilder).
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)?;Fields§
§provider: PThe provider.
Implementations§
Source§impl<P, D, N: Network> CallBuilder<P, D, N>
impl<P, D, N: Network> CallBuilder<P, D, N>
Sourcepub fn into_transaction_request(self) -> N::TransactionRequest
pub fn into_transaction_request(self) -> N::TransactionRequest
Converts the call builder to the inner transaction request
Sourcepub fn build_unsigned_raw_transaction(
self,
) -> Result<Vec<u8>, TransactionBuilderError<N>>
pub fn build_unsigned_raw_transaction( self, ) -> Result<Vec<u8>, TransactionBuilderError<N>>
Builds and returns a RLP-encoded unsigned transaction from the call that can be signed.
§Examples
sol! {
#[sol(rpc, bytecode = "0x")]
contract Counter {
uint128 public counter;
function increment() external {
counter += 1;
}
}
}
#[tokio::main]
async fn main() {
let provider = ProviderBuilder::new().connect_anvil_with_wallet();
let my_contract = Counter::deploy(provider).await.unwrap();
let call = my_contract.increment();
let unsigned_raw_tx: Vec<u8> = call.build_unsigned_raw_transaction().unwrap();
assert!(!unsigned_raw_tx.is_empty())
}Sourcepub async fn build_raw_transaction<S>(
self,
signer: S,
) -> Result<Vec<u8>, TransactionBuilderError<N>>
pub async fn build_raw_transaction<S>( self, signer: S, ) -> Result<Vec<u8>, TransactionBuilderError<N>>
Build a RLP-encoded signed raw transaction for the call that can be sent to the network
using Provider::send_raw_transaction.
§Examples
sol! {
#[sol(rpc, bytecode = "0x")]
contract Counter {
uint128 public counter;
function increment() external {
counter += 1;
}
}
}
#[tokio::main]
async fn main() {
let provider = ProviderBuilder::new().connect_anvil_with_wallet();
let my_contract = Counter::deploy(&provider).await.unwrap();
let call = my_contract.increment();
let pk_signer: PrivateKeySigner = "0x..".parse().unwrap();
let signed_raw_tx: Vec<u8> = call.build_raw_transaction(pk_signer).await.unwrap();
let tx = provider.send_raw_transaction(&signed_raw_tx).await.unwrap();
}Source§impl<P: Provider<N>, N: Network> CallBuilder<P, Function, N>
impl<P: Provider<N>, N: Network> CallBuilder<P, Function, N>
Sourcepub fn clear_decoder(self) -> RawCallBuilder<P, N>
pub fn clear_decoder(self) -> RawCallBuilder<P, N>
Clears the decoder, returning a raw call builder.
Source§impl<P: Provider<N>, C: SolCall, N: Network> CallBuilder<P, PhantomData<C>, N>
impl<P: Provider<N>, C: SolCall, N: Network> CallBuilder<P, PhantomData<C>, N>
Sourcepub fn clear_decoder(self) -> RawCallBuilder<P, N>
pub fn clear_decoder(self) -> RawCallBuilder<P, N>
Clears the decoder, returning a raw call builder.
Source§impl<P: Provider<N>, N: Network> CallBuilder<P, (), N>
impl<P: Provider<N>, N: Network> CallBuilder<P, (), N>
Sourcepub fn with_sol_decoder<C: SolCall>(self) -> SolCallBuilder<P, C, N>
pub fn with_sol_decoder<C: SolCall>(self) -> SolCallBuilder<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, MyContract::MyStruct { a: 42, b: true });Source§impl<P: Provider<N>, N: Network> CallBuilder<P, (), N>
impl<P: Provider<N>, N: Network> CallBuilder<P, (), N>
Source§impl<P: Provider<N>, D: CallDecoder, N: Network> CallBuilder<P, D, N>
impl<P: Provider<N>, D: CallDecoder, N: Network> CallBuilder<P, D, N>
Sourcepub fn chain_id(self, chain_id: ChainId) -> Self
pub fn chain_id(self, chain_id: ChainId) -> Self
Sets the chain_id field in the transaction to the provided value
Sourcepub fn from(self, from: Address) -> Self
pub fn from(self, from: Address) -> Self
Sets the from field in the transaction to the provided value.
Sourcepub fn to(self, to: Address) -> Self
pub fn to(self, to: Address) -> Self
Sets the to field in the transaction to the provided address.
Sourcepub fn sidecar(self, blob_sidecar: BlobTransactionSidecar) -> Selfwhere
N::TransactionRequest: TransactionBuilder4844,
pub fn sidecar(self, blob_sidecar: BlobTransactionSidecar) -> Selfwhere
N::TransactionRequest: TransactionBuilder4844,
Sets the sidecar field in the transaction to the provided value.
Sourcepub fn legacy(self) -> Self
pub fn legacy(self) -> Self
Uses a Legacy transaction instead of an EIP-1559 one to execute the call
Sourcepub fn gas_price(self, gas_price: u128) -> Self
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
Sourcepub fn max_fee_per_gas(self, max_fee_per_gas: u128) -> Self
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
Sourcepub fn max_priority_fee_per_gas(self, max_priority_fee_per_gas: u128) -> Self
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
Sourcepub fn max_fee_per_blob_gas(self, max_fee_per_blob_gas: u128) -> Selfwhere
N::TransactionRequest: TransactionBuilder4844,
pub fn max_fee_per_blob_gas(self, max_fee_per_blob_gas: u128) -> Selfwhere
N::TransactionRequest: TransactionBuilder4844,
Sets the max_fee_per_blob_gas in the transaction to the provided value
Sourcepub fn access_list(self, access_list: AccessList) -> Self
pub fn access_list(self, access_list: AccessList) -> Self
Sets the access_list in the transaction to the provided value
Sourcepub fn value(self, value: U256) -> Self
pub fn value(self, value: U256) -> Self
Sets the value field in the transaction to the provided value
Sourcepub fn nonce(self, nonce: u64) -> Self
pub fn nonce(self, nonce: u64) -> Self
Sets the nonce field in the transaction to the provided value
Sourcepub const fn block(self, block: BlockId) -> Self
pub const fn block(self, block: BlockId) -> Self
Sets the block field for sending the tx to the chain
Sourcepub fn state(self, state: impl Into<StateOverride>) -> Self
pub fn state(self, state: impl Into<StateOverride>) -> Self
Sets the state override set.
§Note
Not all client implementations will support this as a parameter to eth_call.
Sourcepub async fn estimate_gas(&self) -> Result<u64>
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.
Sourcepub fn call(&self) -> EthCall<'_, D, N>
pub fn call(&self) -> EthCall<'_, D, 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.
Sourcepub fn call_raw(&self) -> EthCall<'_, (), N>
pub fn call_raw(&self) -> EthCall<'_, (), 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.
Sourcepub fn decode_output(&self, data: Bytes) -> Result<D::CallOutput>
pub fn decode_output(&self, data: Bytes) -> Result<D::CallOutput>
Decodes the output of a contract function using the provided decoder.
Sourcepub async fn deploy(&self) -> Result<Address>
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.
Sourcepub async fn send(&self) -> Result<PendingTransactionBuilder<N>>
pub async fn send(&self) -> Result<PendingTransactionBuilder<N>>
Broadcasts the underlying transaction to the network.
Returns a builder for configuring the pending transaction watcher.
See Provider::send_transaction for more information.
Sourcepub fn calculate_create_address(&self) -> Option<Address>
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<P: Clone, D, N: Network> CallBuilder<&P, D, N>
impl<P: Clone, D, N: Network> CallBuilder<&P, D, N>
Sourcepub fn with_cloned_provider(self) -> CallBuilder<P, D, N>
pub fn with_cloned_provider(self) -> CallBuilder<P, D, N>
Clones the provider and returns a new builder with the cloned provider.
Trait Implementations§
Source§impl<P, D, N: Network> AsRef<<N as Network>::TransactionRequest> for CallBuilder<P, D, N>
impl<P, D, N: Network> AsRef<<N as Network>::TransactionRequest> for CallBuilder<P, D, N>
Source§fn as_ref(&self) -> &N::TransactionRequest
fn as_ref(&self) -> &N::TransactionRequest
Source§impl<P: Clone, D: Clone, N: Clone + Network> Clone for CallBuilder<P, D, N>where
N::TransactionRequest: Clone,
impl<P: Clone, D: Clone, N: Clone + Network> Clone for CallBuilder<P, D, N>where
N::TransactionRequest: Clone,
Source§fn clone(&self) -> CallBuilder<P, D, N>
fn clone(&self) -> CallBuilder<P, D, N>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreAuto Trait Implementations§
impl<P, D, N> Freeze for CallBuilder<P, D, N>
impl<P, D, N> RefUnwindSafe for CallBuilder<P, D, N>
impl<P, D, N> Send for CallBuilder<P, D, N>
impl<P, D, N> Sync for CallBuilder<P, D, N>
impl<P, D, N> Unpin for CallBuilder<P, D, N>
impl<P, D, N> UnwindSafe for CallBuilder<P, D, N>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moreSource§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> ToHex for T
impl<T> ToHex for T
Source§fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
ToHexExt insteadself into the result.
Lower case letters are used (e.g. f9b4ca).Source§fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
ToHexExt insteadself into the result.
Upper case letters are used (e.g. F9B4CA).Source§impl<T> ToHexExt for T
impl<T> ToHexExt for T
Source§fn encode_hex(&self) -> String
fn encode_hex(&self) -> String
self into the result.
Lower case letters are used (e.g. f9b4ca).Source§fn encode_hex_upper(&self) -> String
fn encode_hex_upper(&self) -> String
self into the result.
Upper case letters are used (e.g. F9B4CA).Source§fn encode_hex_with_prefix(&self) -> String
fn encode_hex_with_prefix(&self) -> String
self into the result with prefix 0x.
Lower case letters are used (e.g. 0xf9b4ca).Source§fn encode_hex_upper_with_prefix(&self) -> String
fn encode_hex_upper_with_prefix(&self) -> String
self into the result with prefix 0X.
Upper case letters are used (e.g. 0xF9B4CA).