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 calls = self
366 .calls
367 .iter()
368 .map(|c| Call { target: c.target, callData: c.callData.clone() })
369 .collect::<Vec<_>>();
370 let call = aggregateCall { calls: calls.to_vec() };
371 let output = self.build_and_call(call, None).await?;
372 T::decode_returns(&output.returnData)
373 }
374
375 /// Call the `tryAggregate` function
376 ///
377 /// Allows for calls to fail by setting `require_success` to false.
378 ///
379 /// ## Solidity Function Signature
380 ///
381 /// ```ignore
382 /// sol! {
383 /// function tryAggregate(bool requireSuccess, Call[] calldata calls) external payable returns (Result[] memory returnData);
384 /// }
385 /// ```
386 ///
387 /// ## Returns
388 ///
389 /// - A tuple of the decoded return values for the calls.
390 /// - Each return value is wrapped in a [`Result`] struct.
391 /// - The [`Result::Ok`] variant contains the decoded return value.
392 /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
393 /// index(-position) of the call and the returned data as [`Bytes`].
394 ///
395 /// # Examples
396 ///
397 /// ```ignore
398 /// use alloy_primitives::address;
399 /// use alloy_provider::{MulticallBuilder, Provider, ProviderBuilder};
400 /// use alloy_sol_types::sol;
401 ///
402 /// sol! {
403 /// #[sol(rpc)]
404 /// #[derive(Debug, PartialEq)]
405 /// interface ERC20 {
406 /// function totalSupply() external view returns (uint256 totalSupply);
407 /// function balanceOf(address owner) external view returns (uint256 balance);
408 /// }
409 /// }
410 ///
411 /// #[tokio::main]
412 /// async fn main() {
413 /// let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
414 /// let provider = ProviderBuilder::new().connect_http("https://eth.merkle.io".parse().unwrap());
415 /// let erc20 = ERC20::new(weth, &provider);
416 ///
417 /// let ts_call = erc20.totalSupply();
418 /// let balance_call = erc20.balanceOf(address!("d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"));
419 ///
420 /// let multicall = provider.multicall().add(ts_call).add(balance_call);
421 ///
422 /// let (total_supply, balance) = multicall.try_aggregate(true).await.unwrap();
423 ///
424 /// assert!(total_supply.is_ok());
425 /// assert!(balance.is_ok());
426 /// }
427 /// ```
428 pub async fn try_aggregate(&self, require_success: bool) -> Result<T::Returns> {
429 let calls = &self
430 .calls
431 .iter()
432 .map(|c| Call { target: c.target, callData: c.callData.clone() })
433 .collect::<Vec<_>>();
434 let call = tryAggregateCall { requireSuccess: require_success, calls: calls.to_vec() };
435 let output = self.build_and_call(call, None).await?;
436 T::decode_return_results(&output)
437 }
438
439 /// Call the `aggregate3` function
440 ///
441 /// Doesn't require that all calls succeed, reverts only if a call with `allowFailure` set to
442 /// false, fails.
443 ///
444 /// By default, adding a call via [`MulticallBuilder::add`] sets `allow_failure` to false.
445 ///
446 /// You can add a call that allows failure by using [`MulticallBuilder::add_call`], and setting
447 /// `allow_failure` to true in [`CallItem`].
448 ///
449 /// ## Solidity Function Signature
450 ///
451 /// ```ignore
452 /// sol! {
453 /// function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);
454 /// }
455 /// ```
456 ///
457 /// ## Returns
458 ///
459 /// - A tuple of the decoded return values for the calls.
460 /// - Each return value is wrapped in a [`Result`] struct.
461 /// - The [`Result::Ok`] variant contains the decoded return value.
462 /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
463 /// index(-position) of the call and the returned data as [`Bytes`].
464 pub async fn aggregate3(&self) -> Result<T::Returns> {
465 let calls = self
466 .calls
467 .iter()
468 .map(|c| Call3 {
469 target: c.target,
470 callData: c.callData.clone(),
471 allowFailure: c.allowFailure,
472 })
473 .collect::<Vec<_>>();
474 let call = aggregate3Call { calls: calls.to_vec() };
475 let output = self.build_and_call(call, None).await?;
476 T::decode_return_results(&output)
477 }
478
479 /// Call the `aggregate3Value` function
480 ///
481 /// Similar to `aggregate3` allows for calls to fail. Moreover, it allows for calling into
482 /// `payable` functions with the `value` parameter.
483 ///
484 /// One can set the `value` field in the [`CallItem`] struct and use
485 /// [`MulticallBuilder::add_call`] to add it to the stack.
486 ///
487 /// It is important to note the `aggregate3Value` only succeeds when `msg.value` is _strictly_
488 /// equal to the sum of the values of all calls. Summing up the values of all calls and setting
489 /// it in the transaction request is handled internally by the builder.
490 ///
491 /// ## Solidity Function Signature
492 ///
493 /// ```ignore
494 /// sol! {
495 /// function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData);
496 /// }
497 /// ```
498 ///
499 /// ## Returns
500 ///
501 /// - A tuple of the decoded return values for the calls.
502 /// - Each return value is wrapped in a [`Result`] struct.
503 /// - The [`Result::Ok`] variant contains the decoded return value.
504 /// - The [`Result::Err`] variant contains the [`Failure`] struct which holds the
505 /// index(-position) of the call and the returned data as [`Bytes`].
506 pub async fn aggregate3_value(&self) -> Result<T::Returns> {
507 let total_value = self.calls.iter().map(|c| c.value).fold(U256::ZERO, |acc, x| acc + x);
508 let call = aggregate3ValueCall { calls: self.calls.to_vec() };
509 let output = self.build_and_call(call, Some(total_value)).await?;
510 T::decode_return_results(&output)
511 }
512
513 /// Call the `blockAndAggregate` function
514 pub async fn block_and_aggregate(&self) -> Result<(u64, B256, T::SuccessReturns)> {
515 let calls = self
516 .calls
517 .iter()
518 .map(|c| Call { target: c.target, callData: c.callData.clone() })
519 .collect::<Vec<_>>();
520 let call = blockAndAggregateCall { calls: calls.to_vec() };
521 let output = self.build_and_call(call, None).await?;
522 let blockAndAggregateReturn { blockNumber, blockHash, returnData } = output;
523 let result = T::decode_return_results(&returnData)?;
524 Ok((blockNumber.to::<u64>(), blockHash, T::try_into_success(result)?))
525 }
526
527 /// Call the `tryBlockAndAggregate` function
528 pub async fn try_block_and_aggregate(
529 &self,
530 require_success: bool,
531 ) -> Result<(u64, B256, T::Returns)> {
532 let calls = self
533 .calls
534 .iter()
535 .map(|c| Call { target: c.target, callData: c.callData.clone() })
536 .collect::<Vec<_>>();
537 let call =
538 tryBlockAndAggregateCall { requireSuccess: require_success, calls: calls.to_vec() };
539 let output = self.build_and_call(call, None).await?;
540 let tryBlockAndAggregateReturn { blockNumber, blockHash, returnData } = output;
541 Ok((blockNumber.to::<u64>(), blockHash, T::decode_return_results(&returnData)?))
542 }
543
544 /// Helper fn to build a tx and call the multicall contract
545 ///
546 /// ## Params
547 ///
548 /// - `call_type`: The [`SolCall`] being made.
549 /// - `value`: Total value to send with the call in case of `aggregate3Value` request.
550 async fn build_and_call<M: SolCall>(
551 &self,
552 call_type: M,
553 value: Option<U256>,
554 ) -> Result<M::Return> {
555 let call = call_type.abi_encode();
556 let mut tx = N::TransactionRequest::default()
557 .with_to(self.address)
558 .with_input_kind(Bytes::from_iter(call), self.input_kind);
559
560 if let Some(value) = value {
561 tx.set_value(value);
562 }
563
564 let mut eth_call = self.provider.root().call(tx);
565
566 if let Some(block) = self.block {
567 eth_call = eth_call.block(block);
568 }
569
570 if let Some(overrides) = self.state_override.clone() {
571 eth_call = eth_call.overrides(overrides);
572 }
573
574 let res = eth_call.await.map_err(MulticallError::TransportError)?;
575 M::abi_decode_returns(&res).map_err(MulticallError::DecodeError)
576 }
577
578 /// Add a call to get the block hash from a block number
579 pub fn get_block_hash(self, number: BlockNumber) -> MulticallBuilder<T::Pushed, P, N>
580 where
581 T: TuplePush<getBlockHashCall>,
582 T::Pushed: CallTuple,
583 {
584 let call = CallItem::<getBlockHashCall>::new(
585 self.address,
586 getBlockHashCall { blockNumber: U256::from(number) }.abi_encode().into(),
587 );
588 self.add_call(call)
589 }
590
591 /// Add a call to get the coinbase of the current block
592 pub fn get_current_block_coinbase(self) -> MulticallBuilder<T::Pushed, P, N>
593 where
594 T: TuplePush<getCurrentBlockCoinbaseCall>,
595 T::Pushed: CallTuple,
596 {
597 let call = CallItem::<getCurrentBlockCoinbaseCall>::new(
598 self.address,
599 getCurrentBlockCoinbaseCall {}.abi_encode().into(),
600 );
601 self.add_call(call)
602 }
603
604 /// Add a call to get the current block number
605 pub fn get_block_number(self) -> MulticallBuilder<T::Pushed, P, N>
606 where
607 T: TuplePush<getBlockNumberCall>,
608 T::Pushed: CallTuple,
609 {
610 let call = CallItem::<getBlockNumberCall>::new(
611 self.address,
612 getBlockNumberCall {}.abi_encode().into(),
613 );
614 self.add_call(call)
615 }
616
617 /// Add a call to get the current block difficulty
618 pub fn get_current_block_difficulty(self) -> MulticallBuilder<T::Pushed, P, N>
619 where
620 T: TuplePush<getCurrentBlockDifficultyCall>,
621 T::Pushed: CallTuple,
622 {
623 let call = CallItem::<getCurrentBlockDifficultyCall>::new(
624 self.address,
625 getCurrentBlockDifficultyCall {}.abi_encode().into(),
626 );
627 self.add_call(call)
628 }
629
630 /// Add a call to get the current block gas limit
631 pub fn get_current_block_gas_limit(self) -> MulticallBuilder<T::Pushed, P, N>
632 where
633 T: TuplePush<getCurrentBlockGasLimitCall>,
634 T::Pushed: CallTuple,
635 {
636 let call = CallItem::<getCurrentBlockGasLimitCall>::new(
637 self.address,
638 getCurrentBlockGasLimitCall {}.abi_encode().into(),
639 );
640 self.add_call(call)
641 }
642
643 /// Add a call to get the current block timestamp
644 pub fn get_current_block_timestamp(self) -> MulticallBuilder<T::Pushed, P, N>
645 where
646 T: TuplePush<getCurrentBlockTimestampCall>,
647 T::Pushed: CallTuple,
648 {
649 let call = CallItem::<getCurrentBlockTimestampCall>::new(
650 self.address,
651 getCurrentBlockTimestampCall {}.abi_encode().into(),
652 );
653 self.add_call(call)
654 }
655
656 /// Add a call to get the chain id
657 pub fn get_chain_id(self) -> MulticallBuilder<T::Pushed, P, N>
658 where
659 T: TuplePush<getChainIdCall>,
660 T::Pushed: CallTuple,
661 {
662 let call =
663 CallItem::<getChainIdCall>::new(self.address, getChainIdCall {}.abi_encode().into());
664 self.add_call(call)
665 }
666
667 /// Add a call to get the base fee
668 pub fn get_base_fee(self) -> MulticallBuilder<T::Pushed, P, N>
669 where
670 T: TuplePush<getBasefeeCall>,
671 T::Pushed: CallTuple,
672 {
673 let call =
674 CallItem::<getBasefeeCall>::new(self.address, getBasefeeCall {}.abi_encode().into());
675 self.add_call(call)
676 }
677
678 /// Add a call to get the eth balance of an address
679 pub fn get_eth_balance(self, address: Address) -> MulticallBuilder<T::Pushed, P, N>
680 where
681 T: TuplePush<getEthBalanceCall>,
682 T::Pushed: CallTuple,
683 {
684 let call = CallItem::<getEthBalanceCall>::new(
685 self.address,
686 getEthBalanceCall { addr: address }.abi_encode().into(),
687 );
688 self.add_call(call)
689 }
690
691 /// Add a call to get the last block hash
692 pub fn get_last_block_hash(self) -> MulticallBuilder<T::Pushed, P, N>
693 where
694 T: TuplePush<getLastBlockHashCall>,
695 T::Pushed: CallTuple,
696 {
697 let call = CallItem::<getLastBlockHashCall>::new(
698 self.address,
699 getLastBlockHashCall {}.abi_encode().into(),
700 );
701 self.add_call(call)
702 }
703
704 /// Returns an [`Empty`] builder
705 ///
706 /// Retains previously set provider, address, block and state_override settings.
707 pub fn clear(self) -> MulticallBuilder<Empty, P, N> {
708 MulticallBuilder {
709 calls: Vec::new(),
710 provider: self.provider,
711 block: self.block,
712 state_override: self.state_override,
713 address: self.address,
714 input_kind: self.input_kind,
715 _pd: Default::default(),
716 }
717 }
718
719 /// Get the number of calls in the builder
720 pub fn len(&self) -> usize {
721 self.calls.len()
722 }
723
724 /// Check if the builder is empty
725 pub fn is_empty(&self) -> bool {
726 self.calls.is_empty()
727 }
728
729 /// Set the input kind for this builder
730 pub const fn with_input_kind(mut self, input_kind: TransactionInputKind) -> Self {
731 self.input_kind = input_kind;
732 self
733 }
734
735 /// Get the input kind for this builder
736 pub const fn input_kind(&self) -> TransactionInputKind {
737 self.input_kind
738 }
739}