Skip to main content

cast/cmd/
batch_send.rs

1//! `cast batch-send` command implementation.
2//!
3//! Sends a batch of calls as a single Tempo transaction using native call batching.
4//! Uses a single type 0x76 transaction with multiple calls executed atomically.
5
6use crate::{
7    call_spec::CallSpec,
8    cmd::{
9        auth::{confirm_and_build, confirm_and_build_with_tempo_wallet},
10        send::{
11            SendOptions, cast_send, cast_send_with_configurable_account,
12            cast_send_with_tempo_wallet,
13        },
14    },
15    tempo,
16    tx::{self, CastTxBuilder, InitState, InputState, SendTxOpts, apply_poll_interval},
17};
18use alloy_network::EthereumWallet;
19use alloy_provider::{Provider, ProviderBuilder as AlloyProviderBuilder};
20use clap::Parser;
21use eyre::Result;
22use foundry_cli::{
23    opts::TransactionOpts,
24    utils::{self, resolve_lane},
25};
26use tempo_alloy::TempoNetwork;
27
28/// CLI arguments for `cast batch-send`.
29///
30/// Sends multiple calls as a single atomic Tempo transaction.
31#[derive(Debug, Parser)]
32pub struct BatchSendArgs {
33    /// Call specifications in format: `to[:<value>][:<sig>[:<args>]]` or `to[:<value>][:<0xdata>]`
34    ///
35    /// Examples:
36    ///   --call "0x1234567890123456789012345678901234567890:0.1ether" (ETH transfer)
37    ///   --call "0x1234567890123456789012345678901234567890::transfer(address,uint256):
38    /// 0x0987654321098765432109876543210987654321,1000" (ERC20 transfer)
39    ///   --call "0x1234567890123456789012345678901234567890::0x123def" (raw calldata)
40    ///   --call "0x1234567890123456789012345678901234567890:1ether:deposit()" (value + function
41    /// call)
42    #[arg(long = "call", value_name = "SPEC", required = true)]
43    pub calls: Vec<String>,
44
45    #[command(flatten)]
46    pub send_tx: SendTxOpts,
47
48    #[command(flatten)]
49    pub tx: TransactionOpts,
50
51    /// Skip the EIP-7702 authorization disclosure confirmation.
52    #[arg(long)]
53    pub force: bool,
54
55    /// Send via `eth_sendTransaction` using the `--from` argument or $ETH_FROM as sender
56    #[arg(long, requires = "from")]
57    pub unlocked: bool,
58}
59
60impl BatchSendArgs {
61    pub async fn run(self) -> Result<()> {
62        let Self { calls, send_tx, mut tx, force, unlocked } = self;
63        // Tempo sessions must sign with the session key; these modes route signing through a
64        // node-managed account or browser wallet instead.
65        if tx.tempo.session_id()?.is_some() && unlocked {
66            eyre::bail!("--tempo.session/TEMPO_SESSION_ID cannot be combined with --unlocked");
67        }
68        tempo::ensure_session_not_browser(&tx.tempo, send_tx.browser.browser)?;
69
70        let expires_at = tx.tempo.resolve_expires();
71
72        let (config, provider) = tempo::tempo_provider(&send_tx.eth)?;
73        let resolved_lane = resolve_lane(&mut tx.tempo, &config.root)?;
74        let lane = resolved_lane.as_ref();
75
76        apply_poll_interval(&provider, send_tx.poll_interval);
77
78        let chain = utils::get_chain(config.chain, &provider).await?;
79        let (mut signer, tempo_access_key) =
80            tempo::resolve_session_or_wallet_signer(&tx.tempo, &send_tx.eth.wallet, chain.id())
81                .await?;
82        let configurable_account = if unlocked || tempo_access_key.is_some() {
83            eyre::ensure!(
84                tx.tempo.configurable_access_key.is_none(),
85                "--tempo.configurable-access-key cannot be combined with --unlocked or a Tempo \
86                 access key"
87            );
88            None
89        } else {
90            tempo::resolve_configurable_account::<TempoNetwork>(
91                &tx.tempo,
92                &config,
93                &send_tx.eth.wallet,
94                &mut signer,
95            )
96            .await?
97        };
98
99        // Preserve key_id for modes that do not call build_with_tempo_wallet, such as unlocked.
100        if let Some(access_key) = &tempo_access_key {
101            tx.tempo.key_id = Some(access_key.key_id()?);
102        }
103
104        let builder = CastTxBuilder::<TempoNetwork, _, _>::new(&provider, tx, &config).await?;
105        let mut builder = with_batch_calls(&calls, builder, &provider).await?;
106        if let Some(account) = &configurable_account {
107            account.prepare_request::<TempoNetwork>(builder.tx_mut());
108        }
109        tempo::print_expires(expires_at)?;
110
111        let send_opts = SendOptions::new(&send_tx, &config).resolving_fee_token(true, &config);
112
113        if unlocked {
114            let Some(tx) = confirm_and_build(builder, config.sender, force, lane, false).await?
115            else {
116                return Ok(());
117            };
118            cast_send(provider, tx, &send_opts).await?;
119        } else if let Some(access_key) = &tempo_access_key {
120            let Some((tx_request, prepared)) =
121                confirm_and_build_with_tempo_wallet(builder, access_key, force, lane).await?
122            else {
123                return Ok(());
124            };
125            cast_send_with_tempo_wallet(&provider, tx_request, &prepared, &send_opts).await?;
126        } else if let Some(account) = &configurable_account {
127            let Some(tx_request) =
128                confirm_and_build(builder, account.sender(), force, lane, false).await?
129            else {
130                return Ok(());
131            };
132            cast_send_with_configurable_account(&provider, tx_request, account, &send_opts).await?;
133        } else {
134            let (signer, _) = tx::resolve_send_signer(signer, &send_tx.eth).await?;
135            let Some(tx_request) = confirm_and_build(builder, &signer, force, lane, false).await?
136            else {
137                return Ok(());
138            };
139            let provider = AlloyProviderBuilder::<_, _, TempoNetwork>::default()
140                .wallet(EthereumWallet::from(signer))
141                .connect_provider(&provider);
142            cast_send(provider, tx_request, &send_opts).await?;
143        }
144
145        Ok(())
146    }
147}
148
149/// Parses the `--call` specs, resolves them against the builder's chain and sets them as the
150/// batch calls of the transaction.
151pub(super) async fn with_batch_calls<P: Provider<TempoNetwork>>(
152    calls: &[String],
153    mut builder: CastTxBuilder<TempoNetwork, P, InitState>,
154    provider: &impl Provider<TempoNetwork>,
155) -> Result<CastTxBuilder<TempoNetwork, P, InputState>> {
156    let specs = calls.iter().map(|s| CallSpec::parse(s)).collect::<Result<Vec<_>>>()?;
157    let (etherscan_api_key, etherscan_api_url) = builder.etherscan_api();
158    let mut tempo_calls = Vec::with_capacity(specs.len());
159    for (i, spec) in specs.iter().enumerate() {
160        tempo_calls.push(
161            spec.resolve(i, builder.chain(), provider, etherscan_api_key, etherscan_api_url)
162                .await?,
163        );
164    }
165    sh_status!("Building batch transaction with {} call(s)...", tempo_calls.len())?;
166    builder.tx_mut().calls = tempo_calls;
167
168    // The builder requires a `to`; `build_aa` uses the calls instead, so point it at the first
169    // call's target.
170    builder
171        .with_to(specs.first().map(|spec| spec.to.into()))
172        .await?
173        .with_code_sig_and_args(None, None, vec![])
174        .await
175}