alloy_provider/provider/multicall/
mod.rs

1//! A Multicall Builder
2
3use crate::Provider;
4use alloy_network::{Network, TransactionBuilder};
5use alloy_primitives::{address, Address, BlockNumber, Bytes, B256, U256};
6use alloy_rpc_types_eth::{state::StateOverride, BlockId, TransactionInputKind};
7use alloy_sol_types::SolCall;
8use bindings::IMulticall3::{
9    blockAndAggregateCall, blockAndAggregateReturn, tryBlockAndAggregateCall,
10    tryBlockAndAggregateReturn, Call, Call3, Call3Value,
11};
12
13/// Multicall bindings
14pub mod bindings;
15use crate::provider::multicall::bindings::IMulticall3::{
16    aggregate3Call, aggregate3ValueCall, aggregateCall, getBasefeeCall, getBlockHashCall,
17    getBlockNumberCall, getChainIdCall, getCurrentBlockCoinbaseCall, getCurrentBlockDifficultyCall,
18    getCurrentBlockGasLimitCall, getCurrentBlockTimestampCall, getEthBalanceCall,
19    getLastBlockHashCall, tryAggregateCall,
20};
21
22mod inner_types;
23pub use inner_types::{
24    CallInfoTrait, CallItem, CallItemBuilder, Dynamic, Failure, MulticallError, MulticallItem,
25    Result,
26};
27
28mod tuple;
29use tuple::TuplePush;
30pub use tuple::{CallTuple, Empty};
31
32/// Default address for the Multicall3 contract on most chains. See: <https://github.com/mds1/multicall>
33pub const MULTICALL3_ADDRESS: Address = address!("0xcA11bde05977b3631167028862bE2a173976CA11");
34
35/// A Multicall3 builder
36///
37/// This builder implements a simple API interface to build and execute multicalls using the
38/// [`IMultiCall3`](crate::bindings::IMulticall3) contract which is available on 270+
39/// chains.
40///
41/// # Examples
42///
43/// ```ignore (missing alloy-contract)
44/// use alloy_primitives::address;
45/// use alloy_provider::{MulticallBuilder, Provider, ProviderBuilder};
46/// use alloy_sol_types::sol;
47///
48/// sol! {
49///     #[sol(rpc)]
50///     #[derive(Debug, PartialEq)]
51///     interface ERC20 {
52///         function totalSupply() external view returns (uint256 totalSupply);
53///         function balanceOf(address owner) external view returns (uint256 balance);
54///     }
55/// }
56///
57/// #[tokio::main]
58/// async fn main() {
59///     let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
60///     let provider =
61///         ProviderBuilder::new().connect_http("https://eth.merkle.io".parse().unwrap());
62///     let erc20 = ERC20::new(weth, &provider);
63///
64///     let ts_call = erc20.totalSupply();
65///     let balance_call = erc20.balanceOf(address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"));
66///
67///     let multicall = provider.multicall().add(ts_call).add(balance_call);
68///
69///     let (total_supply, balance) = multicall.aggregate().await.unwrap();
70///     println!("Total Supply: {total_supply}, Balance: {balance}");
71///
72///     // Or dynamically:
73///     let mut dynamic_multicall = provider.multicall().dynamic();
74///     let addresses = vec![
75///         address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"),
76///         address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96046"),
77///     ];
78///     for &address in &addresses {
79///         dynamic_multicall = dynamic_multicall.add_dynamic(erc20.balanceOf(address));
80///     }
81///     let balances: Vec<_> = dynamic_multicall.aggregate().await.unwrap();
82///     println!("Balances: {:#?}", balances);
83/// }
84/// ```
85#[derive(Debug)]
86pub struct MulticallBuilder<T: CallTuple, P: Provider<N>, N: Network> {
87    /// Batched calls
88    calls: Vec<Call3Value>,
89    /// The provider to use
90    provider: P,
91    /// The [`BlockId`] to use for the call
92    block: Option<BlockId>,
93    /// The [`StateOverride`] for the call
94    state_override: Option<StateOverride>,
95    /// This is the address of the [`IMulticall3`](crate::bindings::IMulticall3)
96    /// contract.
97    ///
98    /// By default it is set to [`MULTICALL3_ADDRESS`].
99    address: Address,
100    /// The input kind supported by this builder
101    input_kind: TransactionInputKind,
102    _pd: std::marker::PhantomData<(T, N)>,
103}
104
105impl<P, N> MulticallBuilder<Empty, P, N>
106where
107    P: Provider<N>,
108    N: Network,
109{
110    /// Instantiate a new [`MulticallBuilder`]
111    pub fn new(provider: P) -> Self {
112        Self {
113            calls: Vec::new(),
114            provider,
115            _pd: Default::default(),
116            block: None,
117            state_override: None,
118            address: MULTICALL3_ADDRESS,
119            input_kind: TransactionInputKind::default(),
120        }
121    }
122
123    /// Converts an empty [`MulticallBuilder`] into a dynamic one
124    pub fn dynamic<D: SolCall + 'static>(self) -> MulticallBuilder<Dynamic<D>, P, N> {
125        MulticallBuilder {
126            calls: self.calls,
127            provider: self.provider,
128            block: self.block,
129            state_override: self.state_override,
130            address: self.address,
131            input_kind: self.input_kind,
132            _pd: Default::default(),
133        }
134    }
135}
136
137impl<D: SolCall + 'static, P, N> MulticallBuilder<Dynamic<D>, P, N>
138where
139    P: Provider<N>,
140    N: Network,
141{
142    /// Instantiate a new [`MulticallBuilder`] that restricts the calls to a specific call type.
143    ///
144    /// Multicalls made using this builder return a vector of the decoded return values.
145    ///
146    /// An example would be trying to fetch multiple ERC20 balances of an address.
147    ///
148    /// This is equivalent to `provider.multicall().dynamic()`.
149    ///
150    /// # Examples
151    ///
152    /// ```ignore (missing alloy-contract)
153    /// use alloy_primitives::address;
154    /// use alloy_provider::{MulticallBuilder, Provider, ProviderBuilder};
155    /// use alloy_sol_types::sol;
156    ///
157    /// sol! {
158    ///     #[sol(rpc)]
159    ///     #[derive(Debug, PartialEq)]
160    ///     interface ERC20 {
161    ///         function balanceOf(address owner) external view returns (uint256 balance);
162    ///     }
163    /// }
164    ///
165    /// #[tokio::main]
166    /// async fn main() {
167    ///    let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
168    ///    let usdc = address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
169    ///     
170    ///    let provider = ProviderBuilder::new().connect_http("https://eth.merkle.io".parse().unwrap());
171    ///    let weth = ERC20::new(weth, &provider);
172    ///    let usdc = ERC20::new(usdc, &provider);
173    ///
174    ///    let owner = address!("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
175    ///
176    ///    let mut erc20_balances = MulticallBuilder::new_dynamic(provider);
177    ///    // Or:
178    ///    let mut erc20_balances = provider.multicall().dynamic();
179    ///
180    ///    for token in &[weth, usdc] {
181    ///        erc20_balances = erc20_balances.add_dynamic(token.balanceOf(owner));
182    ///    }
183    ///
184    ///    let balances: Vec<ERC20::balanceOfReturn> = erc20_balances.aggregate().await.unwrap();
185    ///
186    ///    let weth_bal = &balances[0];
187    ///    let usdc_bal = &balances[1];
188    ///    println!("WETH Balance: {:?}, USDC Balance: {:?}", weth_bal, usdc_bal);
189    /// }
190    pub fn new_dynamic(provider: P) -> Self {
191        MulticallBuilder::new(provider).dynamic()
192    }
193
194    /// Add a dynamic call to the builder
195    ///
196    /// The call will have `allowFailure` set to `false`. To allow failure, use
197    /// [`Self::add_call_dynamic`], potentially converting a [`MulticallItem`] to a fallible
198    /// [`CallItem`] with [`MulticallItem::into_call`].
199    pub fn add_dynamic(mut self, item: impl MulticallItem<Decoder = D>) -> Self {
200        let call: CallItem<D> = item.into();
201
202        self.calls.push(call.to_call3_value());
203        self
204    }
205
206    /// Add a dynamic [`CallItem`] to the builder
207    pub fn add_call_dynamic(mut self, call: CallItem<D>) -> Self {
208        self.calls.push(call.to_call3_value());
209        self
210    }
211
212    /// Extend the builder with a sequence of calls
213    pub fn extend(
214        mut self,
215        items: impl IntoIterator<Item = impl MulticallItem<Decoder = D>>,
216    ) -> Self {
217        for item in items {
218            self = self.add_dynamic(item);
219        }
220        self
221    }
222
223    /// Extend the builder with a sequence of [`CallItem`]s
224    pub fn extend_calls(mut self, calls: impl IntoIterator<Item = CallItem<D>>) -> Self {
225        for call in calls {
226            self = self.add_call_dynamic(call);
227        }
228        self
229    }
230}
231
232impl<T, P, N> MulticallBuilder<T, &P, N>
233where
234    T: CallTuple,
235    P: Provider<N> + Clone,
236    N: Network,
237{
238    /// Clones the underlying provider and returns a new [`MulticallBuilder`].
239    pub fn with_cloned_provider(&self) -> MulticallBuilder<Empty, P, N> {
240        MulticallBuilder {
241            calls: Vec::new(),
242            provider: self.provider.clone(),
243            block: None,
244            state_override: None,
245            address: MULTICALL3_ADDRESS,
246            input_kind: TransactionInputKind::default(),
247            _pd: Default::default(),
248        }
249    }
250}
251
252impl<T, P, N> MulticallBuilder<T, P, N>
253where
254    T: CallTuple,
255    P: Provider<N>,
256    N: Network,
257{
258    /// Set the address of the multicall3 contract
259    ///
260    /// Default is [`MULTICALL3_ADDRESS`].
261    pub const fn address(mut self, address: Address) -> Self {
262        self.address = address;
263        self
264    }
265
266    /// Sets the block to be used for the call.
267    pub const fn block(mut self, block: BlockId) -> Self {
268        self.block = Some(block);
269        self
270    }
271
272    /// Set the state overrides for the call.
273    pub fn overrides(mut self, state_override: impl Into<StateOverride>) -> Self {
274        self.state_override = Some(state_override.into());
275        self
276    }
277
278    /// Appends a [`SolCall`] to the stack.
279    ///
280    /// The call will have `allowFailure` set to `false`. To allow failure, use [`Self::add_call`],
281    /// potentially converting a [`MulticallItem`] to a fallible [`CallItem`] with
282    /// [`MulticallItem::into_call`].
283    #[expect(clippy::should_implement_trait)]
284    pub fn add<Item: MulticallItem>(self, item: Item) -> MulticallBuilder<T::Pushed, P, N>
285    where
286        Item::Decoder: 'static,
287        T: TuplePush<Item::Decoder>,
288        <T as TuplePush<Item::Decoder>>::Pushed: CallTuple,
289    {
290        let call: CallItem<Item::Decoder> = item.into();
291        self.add_call(call)
292    }
293
294    /// Appends a [`CallItem`] to the stack.
295    pub fn add_call<D>(mut self, call: CallItem<D>) -> MulticallBuilder<T::Pushed, P, N>
296    where
297        D: SolCall + 'static,
298        T: TuplePush<D>,
299        <T as TuplePush<D>>::Pushed: CallTuple,
300    {
301        self.calls.push(call.to_call3_value());
302        MulticallBuilder {
303            calls: self.calls,
304            provider: self.provider,
305            block: self.block,
306            state_override: self.state_override,
307            address: self.address,
308            input_kind: self.input_kind,
309            _pd: Default::default(),
310        }
311    }
312
313    /// Calls the `aggregate` function
314    ///
315    /// Requires that all calls succeed, else reverts.
316    ///
317    /// ## Solidity Function Signature
318    ///
319    /// ```ignore
320    /// sol! {
321    ///     function aggregate(Call[] memory calls) external returns (uint256 blockNumber, bytes[] memory returnData);
322    /// }
323    /// ```
324    ///
325    /// ## Returns
326    ///
327    /// - `returnData`: A tuple of the decoded return values for the calls
328    ///
329    /// One can obtain the block context such as block number and block hash by using the
330    /// [MulticallBuilder::block_and_aggregate] function.
331    ///
332    /// # Examples
333    ///
334    /// ```ignore (missing alloy-contract)
335    /// use alloy_primitives::address;
336    /// use alloy_provider::{MulticallBuilder, Provider, ProviderBuilder};
337    /// use alloy_sol_types::sol;
338    ///
339    /// sol! {
340    ///     #[sol(rpc)]
341    ///     #[derive(Debug, PartialEq)]
342    ///     interface ERC20 {
343    ///         function totalSupply() external view returns (uint256 totalSupply);
344    ///         function balanceOf(address owner) external view returns (uint256 balance);
345    ///     }
346    /// }
347    ///
348    /// #[tokio::main]
349    /// async fn main() {
350    ///     let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
351    ///     let provider = ProviderBuilder::new().connect_http("https://eth.merkle.io".parse().unwrap());
352    ///     let erc20 = ERC20::new(weth, &provider);
353    ///
354    ///     let ts_call = erc20.totalSupply();
355    ///     let balance_call = erc20.balanceOf(address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"));
356    ///
357    ///     let multicall = provider.multicall().add(ts_call).add(balance_call);
358    ///
359    ///     let (total_supply, balance) = multicall.aggregate().await.unwrap();
360    ///
361    ///     println!("Total Supply: {:?}, Balance: {:?}", total_supply, balance);
362    /// }
363    /// ```
364    pub async fn aggregate(&self) -> Result<T::SuccessReturns> {
365        let output = self.build_and_call(self.to_aggregate_call(), None).await?;
366        T::decode_returns(&output.returnData)
367    }
368
369    /// Encodes the calls for the `aggregate` function and returns the populated transaction
370    /// request.
371    pub fn to_aggregate_request(&self) -> N::TransactionRequest {
372        self.build_request(self.to_aggregate_call(), None)
373    }
374
375    /// Creates the [`aggregate3Call`].
376    fn to_aggregate_call(&self) -> aggregateCall {
377        let calls = self
378            .calls
379            .iter()
380            .map(|c| Call { target: c.target, callData: c.callData.clone() })
381            .collect::<Vec<_>>();
382        aggregateCall { calls: calls.to_vec() }
383    }
384
385    /// Call the `tryAggregate` function
386    ///
387    /// Allows for calls to fail by setting `require_success` to false.
388    ///
389    /// ## Solidity Function Signature
390    ///
391    /// ```ignore
392    /// sol! {
393    ///     function tryAggregate(bool requireSuccess, Call[] calldata calls) external payable returns (Result[] memory returnData);
394    /// }
395    /// ```
396    ///
397    /// ## Returns
398    ///
399    /// - A tuple of the decoded return values for the calls.
400    /// - Each return value is wrapped in a [`Result`] struct.
401    /// - The [`Result::Ok`] variant contains the decoded return value.
402    /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
403    ///   index(-position) of the call and the returned data as [`Bytes`].
404    ///
405    /// # Examples
406    ///
407    /// ```ignore
408    /// use alloy_primitives::address;
409    /// use alloy_provider::{MulticallBuilder, Provider, ProviderBuilder};
410    /// use alloy_sol_types::sol;
411    ///
412    /// sol! {
413    ///    #[sol(rpc)]
414    ///    #[derive(Debug, PartialEq)]
415    ///    interface ERC20 {
416    ///        function totalSupply() external view returns (uint256 totalSupply);
417    ///        function balanceOf(address owner) external view returns (uint256 balance);
418    ///    }
419    /// }
420    ///
421    /// #[tokio::main]
422    /// async fn main() {
423    ///     let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
424    ///     let provider = ProviderBuilder::new().connect_http("https://eth.merkle.io".parse().unwrap());
425    ///     let erc20 = ERC20::new(weth, &provider);
426    ///
427    ///     let ts_call = erc20.totalSupply();
428    ///     let balance_call = erc20.balanceOf(address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"));
429    ///
430    ///     let multicall = provider.multicall().add(ts_call).add(balance_call);
431    ///
432    ///     let (total_supply, balance) = multicall.try_aggregate(true).await.unwrap();
433    ///
434    ///     assert!(total_supply.is_ok());
435    ///     assert!(balance.is_ok());
436    /// }
437    /// ```
438    pub async fn try_aggregate(&self, require_success: bool) -> Result<T::Returns> {
439        let output = self.build_and_call(self.to_try_aggregate_call(require_success), None).await?;
440        T::decode_return_results(&output)
441    }
442
443    /// Encodes the calls for the `tryAggregateCall` function and returns the populated transaction
444    /// request.
445    pub fn to_try_aggregate_request(&self, require_success: bool) -> N::TransactionRequest {
446        self.build_request(self.to_try_aggregate_call(require_success), None)
447    }
448
449    /// Creates the [`tryAggregateCall`].
450    fn to_try_aggregate_call(&self, require_success: bool) -> tryAggregateCall {
451        let calls = &self
452            .calls
453            .iter()
454            .map(|c| Call { target: c.target, callData: c.callData.clone() })
455            .collect::<Vec<_>>();
456        tryAggregateCall { requireSuccess: require_success, calls: calls.to_vec() }
457    }
458
459    /// Call the `aggregate3` function
460    ///
461    /// Doesn't require that all calls succeed, reverts only if a call with `allowFailure` set to
462    /// false, fails.
463    ///
464    /// By default, adding a call via [`MulticallBuilder::add`] sets `allow_failure` to false.
465    ///
466    /// You can add a call that allows failure by using [`MulticallBuilder::add_call`], and setting
467    /// `allow_failure` to true in [`CallItem`].
468    ///
469    /// ## Solidity Function Signature
470    ///
471    /// ```ignore
472    /// sol! {
473    ///     function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);
474    /// }
475    /// ```
476    ///
477    /// ## Returns
478    ///
479    /// - A tuple of the decoded return values for the calls.
480    /// - Each return value is wrapped in a [`Result`] struct.
481    /// - The [`Result::Ok`] variant contains the decoded return value.
482    /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
483    ///   index(-position) of the call and the returned data as [`Bytes`].
484    pub async fn aggregate3(&self) -> Result<T::Returns> {
485        let call = self.to_aggregate3_call();
486        let output = self.build_and_call(call, None).await?;
487        T::decode_return_results(&output)
488    }
489
490    /// Encodes the calls for the `aggregate3` function and returns the populated transaction
491    /// request.
492    pub fn to_aggregate3_request(&self) -> N::TransactionRequest {
493        self.build_request(self.to_aggregate3_call(), None)
494    }
495
496    /// Creates the [`aggregate3Call`]
497    fn to_aggregate3_call(&self) -> aggregate3Call {
498        let calls = self
499            .calls
500            .iter()
501            .map(|c| Call3 {
502                target: c.target,
503                callData: c.callData.clone(),
504                allowFailure: c.allowFailure,
505            })
506            .collect::<Vec<_>>();
507        aggregate3Call { calls: calls.to_vec() }
508    }
509
510    /// Call the `aggregate3Value` function
511    ///
512    /// Similar to `aggregate3` allows for calls to fail. Moreover, it allows for calling into
513    /// `payable` functions with the `value` parameter.
514    ///
515    /// One can set the `value` field in the [`CallItem`] struct and use
516    /// [`MulticallBuilder::add_call`] to add it to the stack.
517    ///
518    /// It is important to note the `aggregate3Value` only succeeds when `msg.value` is _strictly_
519    /// equal to the sum of the values of all calls. Summing up the values of all calls and setting
520    /// it in the transaction request is handled internally by the builder.
521    ///
522    /// ## Solidity Function Signature
523    ///
524    /// ```ignore
525    /// sol! {
526    ///     function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData);
527    /// }
528    /// ```
529    ///
530    /// ## Returns
531    ///
532    /// - A tuple of the decoded return values for the calls.
533    /// - Each return value is wrapped in a [`Result`] struct.
534    /// - The [`Result::Ok`] variant contains the decoded return value.
535    /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
536    ///   index(-position) of the call and the returned data as [`Bytes`].
537    pub async fn aggregate3_value(&self) -> Result<T::Returns> {
538        let total_value = self.calls.iter().map(|c| c.value).fold(U256::ZERO, |acc, x| acc + x);
539        let call = aggregate3ValueCall { calls: self.calls.to_vec() };
540        let output = self.build_and_call(call, Some(total_value)).await?;
541        T::decode_return_results(&output)
542    }
543
544    /// Call the `blockAndAggregate` function
545    pub async fn block_and_aggregate(&self) -> Result<(u64, B256, T::SuccessReturns)> {
546        let calls = self
547            .calls
548            .iter()
549            .map(|c| Call { target: c.target, callData: c.callData.clone() })
550            .collect::<Vec<_>>();
551        let call = blockAndAggregateCall { calls: calls.to_vec() };
552        let output = self.build_and_call(call, None).await?;
553        let blockAndAggregateReturn { blockNumber, blockHash, returnData } = output;
554        let result = T::decode_return_results(&returnData)?;
555        Ok((blockNumber.to::<u64>(), blockHash, T::try_into_success(result)?))
556    }
557
558    /// Call the `tryBlockAndAggregate` function
559    pub async fn try_block_and_aggregate(
560        &self,
561        require_success: bool,
562    ) -> Result<(u64, B256, T::Returns)> {
563        let calls = self
564            .calls
565            .iter()
566            .map(|c| Call { target: c.target, callData: c.callData.clone() })
567            .collect::<Vec<_>>();
568        let call =
569            tryBlockAndAggregateCall { requireSuccess: require_success, calls: calls.to_vec() };
570        let output = self.build_and_call(call, None).await?;
571        let tryBlockAndAggregateReturn { blockNumber, blockHash, returnData } = output;
572        Ok((blockNumber.to::<u64>(), blockHash, T::decode_return_results(&returnData)?))
573    }
574
575    /// Helper for building the transaction request for the given call type input.
576    fn build_request<M: SolCall>(
577        &self,
578        call_type: M,
579        value: Option<U256>,
580    ) -> N::TransactionRequest {
581        let call = call_type.abi_encode();
582        let mut tx = N::TransactionRequest::default()
583            .with_to(self.address)
584            .with_input_kind(Bytes::from_iter(call), self.input_kind);
585
586        if let Some(value) = value {
587            tx.set_value(value);
588        }
589        tx
590    }
591
592    /// Helper fn to build a tx and call the multicall contract
593    ///
594    /// ## Params
595    ///
596    /// - `call_type`: The [`SolCall`] being made.
597    /// - `value`: Total value to send with the call in case of `aggregate3Value` request.
598    async fn build_and_call<M: SolCall>(
599        &self,
600        call_type: M,
601        value: Option<U256>,
602    ) -> Result<M::Return> {
603        let tx = self.build_request(call_type, value);
604
605        let mut eth_call = self.provider.root().call(tx);
606
607        if let Some(block) = self.block {
608            eth_call = eth_call.block(block);
609        }
610
611        if let Some(overrides) = self.state_override.clone() {
612            eth_call = eth_call.overrides(overrides);
613        }
614
615        let res = eth_call.await.map_err(MulticallError::TransportError)?;
616        M::abi_decode_returns(&res).map_err(MulticallError::DecodeError)
617    }
618
619    /// Add a call to get the block hash from a block number
620    pub fn get_block_hash(self, number: BlockNumber) -> MulticallBuilder<T::Pushed, P, N>
621    where
622        T: TuplePush<getBlockHashCall>,
623        T::Pushed: CallTuple,
624    {
625        let call = CallItem::<getBlockHashCall>::new(
626            self.address,
627            getBlockHashCall { blockNumber: U256::from(number) }.abi_encode().into(),
628        );
629        self.add_call(call)
630    }
631
632    /// Add a call to get the coinbase of the current block
633    pub fn get_current_block_coinbase(self) -> MulticallBuilder<T::Pushed, P, N>
634    where
635        T: TuplePush<getCurrentBlockCoinbaseCall>,
636        T::Pushed: CallTuple,
637    {
638        let call = CallItem::<getCurrentBlockCoinbaseCall>::new(
639            self.address,
640            getCurrentBlockCoinbaseCall {}.abi_encode().into(),
641        );
642        self.add_call(call)
643    }
644
645    /// Add a call to get the current block number
646    pub fn get_block_number(self) -> MulticallBuilder<T::Pushed, P, N>
647    where
648        T: TuplePush<getBlockNumberCall>,
649        T::Pushed: CallTuple,
650    {
651        let call = CallItem::<getBlockNumberCall>::new(
652            self.address,
653            getBlockNumberCall {}.abi_encode().into(),
654        );
655        self.add_call(call)
656    }
657
658    /// Add a call to get the current block difficulty
659    pub fn get_current_block_difficulty(self) -> MulticallBuilder<T::Pushed, P, N>
660    where
661        T: TuplePush<getCurrentBlockDifficultyCall>,
662        T::Pushed: CallTuple,
663    {
664        let call = CallItem::<getCurrentBlockDifficultyCall>::new(
665            self.address,
666            getCurrentBlockDifficultyCall {}.abi_encode().into(),
667        );
668        self.add_call(call)
669    }
670
671    /// Add a call to get the current block gas limit
672    pub fn get_current_block_gas_limit(self) -> MulticallBuilder<T::Pushed, P, N>
673    where
674        T: TuplePush<getCurrentBlockGasLimitCall>,
675        T::Pushed: CallTuple,
676    {
677        let call = CallItem::<getCurrentBlockGasLimitCall>::new(
678            self.address,
679            getCurrentBlockGasLimitCall {}.abi_encode().into(),
680        );
681        self.add_call(call)
682    }
683
684    /// Add a call to get the current block timestamp
685    pub fn get_current_block_timestamp(self) -> MulticallBuilder<T::Pushed, P, N>
686    where
687        T: TuplePush<getCurrentBlockTimestampCall>,
688        T::Pushed: CallTuple,
689    {
690        let call = CallItem::<getCurrentBlockTimestampCall>::new(
691            self.address,
692            getCurrentBlockTimestampCall {}.abi_encode().into(),
693        );
694        self.add_call(call)
695    }
696
697    /// Add a call to get the chain id
698    pub fn get_chain_id(self) -> MulticallBuilder<T::Pushed, P, N>
699    where
700        T: TuplePush<getChainIdCall>,
701        T::Pushed: CallTuple,
702    {
703        let call =
704            CallItem::<getChainIdCall>::new(self.address, getChainIdCall {}.abi_encode().into());
705        self.add_call(call)
706    }
707
708    /// Add a call to get the base fee
709    pub fn get_base_fee(self) -> MulticallBuilder<T::Pushed, P, N>
710    where
711        T: TuplePush<getBasefeeCall>,
712        T::Pushed: CallTuple,
713    {
714        let call =
715            CallItem::<getBasefeeCall>::new(self.address, getBasefeeCall {}.abi_encode().into());
716        self.add_call(call)
717    }
718
719    /// Add a call to get the eth balance of an address
720    pub fn get_eth_balance(self, address: Address) -> MulticallBuilder<T::Pushed, P, N>
721    where
722        T: TuplePush<getEthBalanceCall>,
723        T::Pushed: CallTuple,
724    {
725        let call = CallItem::<getEthBalanceCall>::new(
726            self.address,
727            getEthBalanceCall { addr: address }.abi_encode().into(),
728        );
729        self.add_call(call)
730    }
731
732    /// Add a call to get the last block hash
733    pub fn get_last_block_hash(self) -> MulticallBuilder<T::Pushed, P, N>
734    where
735        T: TuplePush<getLastBlockHashCall>,
736        T::Pushed: CallTuple,
737    {
738        let call = CallItem::<getLastBlockHashCall>::new(
739            self.address,
740            getLastBlockHashCall {}.abi_encode().into(),
741        );
742        self.add_call(call)
743    }
744
745    /// Returns an [`Empty`] builder
746    ///
747    /// Retains previously set provider, address, block and state_override settings.
748    pub fn clear(self) -> MulticallBuilder<Empty, P, N> {
749        MulticallBuilder {
750            calls: Vec::new(),
751            provider: self.provider,
752            block: self.block,
753            state_override: self.state_override,
754            address: self.address,
755            input_kind: self.input_kind,
756            _pd: Default::default(),
757        }
758    }
759
760    /// Get the number of calls in the builder
761    pub fn len(&self) -> usize {
762        self.calls.len()
763    }
764
765    /// Check if the builder is empty
766    pub fn is_empty(&self) -> bool {
767        self.calls.is_empty()
768    }
769
770    /// Set the input kind for this builder
771    pub const fn with_input_kind(mut self, input_kind: TransactionInputKind) -> Self {
772        self.input_kind = input_kind;
773        self
774    }
775
776    /// Get the input kind for this builder
777    pub const fn input_kind(&self) -> TransactionInputKind {
778        self.input_kind
779    }
780}