Skip to main content

forge_script/
broadcast.rs

1use std::{cmp::Ordering, num::NonZeroU64, sync::Arc, time::Duration};
2
3use crate::{
4    ScriptArgs, ScriptConfig,
5    build::LinkedBuildData,
6    progress::ScriptProgress,
7    sequence::ScriptSequenceKind,
8    session::{
9        RemainingScriptTransaction, SignerScope,
10        insert_session_access_key_for_remaining_transactions,
11        script_session_expected_sender_if_configured,
12    },
13    verify::BroadcastedState,
14};
15use alloy_chains::{Chain, NamedChain};
16use alloy_consensus::{SignableTransaction, Signed};
17use alloy_eips::eip2718::Encodable2718;
18use alloy_network::{
19    EthereumWallet, Network, NetworkTransactionBuilder, ReceiptResponse, TransactionBuilder,
20};
21use alloy_primitives::{
22    Address, TxHash, TxKind, U256, keccak256,
23    map::{AddressHashMap, AddressHashSet, HashMap},
24    utils::format_units,
25};
26use alloy_provider::{Provider, RootProvider, utils::Eip1559Estimation};
27use alloy_rpc_types::TransactionRequest;
28use alloy_signer::Signature;
29use eyre::{Context, Result, bail};
30use forge_script_sequence::ScriptSequence;
31use foundry_cheatcodes::Wallets;
32use foundry_cli::utils::{has_batch_support, has_different_gas_calc};
33use foundry_common::{
34    FoundryTransactionBuilder, TransactionMaybeSigned,
35    provider::{
36        ProviderBuilder,
37        fee::{estimate_eip1559_fees, resolve_broadcast_eip1559_fees},
38    },
39    shell,
40    tempo::{TempoSponsor, maybe_print_fee_token, resolve_and_set_fee_token},
41};
42use foundry_config::Config;
43use foundry_evm::core::{
44    constants::DEFAULT_CREATE2_DEPLOYER_CODEHASH,
45    evm::{FoundryEvmNetwork, TempoEvmNetwork},
46    fork::ResolvedFork,
47    opts::EvmOpts,
48};
49use foundry_wallets::{TempoAccountsWallet, wallet_browser::signer::BrowserSigner};
50use futures::{FutureExt, StreamExt, future::join_all, stream::FuturesUnordered};
51use itertools::Itertools;
52use revm_inspectors::tracing::types::CallKind;
53use tempo_alloy::{TempoNetwork, rpc::TempoTransactionRequest};
54use tempo_primitives::transaction::Call;
55
56/// Represents how to send a single transaction.
57#[derive(Clone)]
58pub enum SendTransactionKind<'a, N: Network> {
59    Unlocked(N::TransactionRequest),
60    Raw(N::TransactionRequest, &'a EthereumWallet),
61    Browser(N::TransactionRequest, &'a BrowserSigner<N>),
62    Signed(N::TxEnvelope),
63    AccessKey(N::TransactionRequest, Box<TempoAccountsWallet>),
64}
65
66impl<'a, N: Network> SendTransactionKind<'a, N>
67where
68    N::TxEnvelope: From<Signed<N::UnsignedTx>>,
69    N::UnsignedTx: SignableTransaction<Signature>,
70    N::TransactionRequest: FoundryTransactionBuilder<N>,
71{
72    /// Prepares the transaction for broadcasting by synchronizing nonce and estimating gas.
73    ///
74    /// This method performs two key operations:
75    /// 1. Nonce synchronization: Waits for the provider's nonce to catch up to the expected
76    ///    transaction nonce when doing sequential broadcast
77    /// 2. Gas estimation: Re-estimates gas right before broadcasting for chains that require it
78    #[allow(clippy::too_many_arguments)]
79    pub async fn prepare(
80        &mut self,
81        provider: &RootProvider<N>,
82        sequential_broadcast: bool,
83        is_fixed_gas_limit: bool,
84        estimate_via_rpc: bool,
85        estimate_multiplier: u64,
86        tempo_sponsor: Option<&TempoSponsor>,
87        chain: Option<Chain>,
88    ) -> Result<()> {
89        let tempo_browser = matches!(self, Self::Browser(..)) && chain.is_some_and(Chain::is_tempo);
90        let (tx, tempo_wallet) = match self {
91            Self::Raw(tx, _) | Self::Unlocked(tx) | Self::Browser(tx, _) => (tx, None),
92            Self::AccessKey(tx, wallet) => (tx, Some(wallet)),
93            Self::Signed(_) => return Ok(()),
94        };
95
96        reject_access_key_create::<N>(tx, tempo_wallet.is_some())?;
97
98        if sequential_broadcast {
99            let from = tx.from().expect("no sender");
100
101            let tx_nonce = tx.nonce().expect("no nonce");
102            for attempt in 0..5 {
103                let nonce = provider.get_transaction_count(from).await?;
104                match nonce.cmp(&tx_nonce) {
105                    Ordering::Greater => {
106                        bail!(
107                            "EOA nonce changed unexpectedly while sending transactions. Expected {tx_nonce} got {nonce} from provider."
108                        );
109                    }
110                    Ordering::Less => {
111                        if attempt == 4 {
112                            bail!(
113                                "After 5 attempts, provider nonce ({nonce}) is still behind expected nonce ({tx_nonce})."
114                            );
115                        }
116                        warn!(
117                            "Expected nonce ({tx_nonce}) is ahead of provider nonce ({nonce}). Retrying in 1 second..."
118                        );
119                        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
120                    }
121                    Ordering::Equal => {
122                        // Nonces are equal, we can proceed.
123                        break;
124                    }
125                }
126            }
127        }
128
129        if let Some(wallet) = tempo_wallet {
130            **wallet = tx.prepare_with_tempo_wallet(provider, wallet).await?;
131        }
132
133        let fee_token = if let Some(sponsor) = tempo_sponsor {
134            sponsor.resolve_and_set_fee_token(Some(provider), chain, tx).await?;
135            None
136        } else {
137            resolve_and_set_fee_token(Some(provider), chain, tx, tx.from()).await?
138        };
139
140        // A fee token, sponsor, validity window, or other Tempo field selects
141        // the AA transaction type. AA requests carry CREATE as their first
142        // call rather than as the Ethereum transaction `to` field.
143        convert_tempo_aa_create::<N>(tx);
144
145        // Chains which use `eth_estimateGas` are being sent sequentially and require their
146        // gas to be re-estimated right before broadcasting.
147        if !is_fixed_gas_limit && estimate_via_rpc {
148            estimate_gas(tx, provider, estimate_multiplier, tempo_browser).await?;
149        }
150
151        if let Some(sponsor) = tempo_sponsor {
152            let from = tx.from().expect("no sender");
153            sponsor.attach_and_print::<N>(tx, from).await?;
154        } else {
155            maybe_print_fee_token(Some(provider), fee_token).await?;
156        }
157
158        Ok(())
159    }
160
161    /// Sends the transaction to the network.
162    ///
163    /// Depending on the transaction kind, this will either:
164    /// - Submit via `eth_sendTransaction` for unlocked accounts
165    /// - Sign and submit via `eth_sendRawTransaction` for raw transactions
166    /// - Submit pre-signed transaction via `eth_sendRawTransaction`
167    pub async fn send(self, provider: Arc<RootProvider<N>>) -> Result<TxHash> {
168        match self {
169            Self::Unlocked(tx) => {
170                debug!("sending transaction from unlocked account {:?}", tx);
171
172                // Submit the transaction
173                let pending = provider.send_transaction(tx).await?;
174                Ok(*pending.tx_hash())
175            }
176            Self::Raw(tx, signer) => {
177                debug!("sending transaction: {:?}", tx);
178                let signed = tx.build(signer).await?;
179
180                // Submit the raw transaction
181                let pending = provider.send_raw_transaction(signed.encoded_2718().as_ref()).await?;
182                Ok(*pending.tx_hash())
183            }
184            Self::Signed(tx) => {
185                debug!("sending transaction: {:?}", tx);
186                let pending = provider.send_raw_transaction(tx.encoded_2718().as_ref()).await?;
187                Ok(*pending.tx_hash())
188            }
189            Self::Browser(tx, signer) => {
190                debug!("sending transaction: {:?}", tx);
191
192                // Sign and send the transaction via the browser wallet
193                Ok(signer.send_transaction_via_browser(tx).await?)
194            }
195            Self::AccessKey(tx, wallet) => {
196                debug!("sending transaction via tempo access key: {:?}", tx);
197
198                let raw_tx = tx.sign_with_tempo_wallet(&wallet).await?;
199
200                let pending = provider.send_raw_transaction(&raw_tx).await?;
201                Ok(*pending.tx_hash())
202            }
203        }
204    }
205
206    /// Prepares and sends the transaction in one operation.
207    ///
208    /// This is a convenience method that combines [`prepare`](Self::prepare) and
209    /// [`send`](Self::send) into a single call.
210    #[allow(clippy::too_many_arguments)]
211    pub async fn prepare_and_send(
212        mut self,
213        provider: Arc<RootProvider<N>>,
214        sequential_broadcast: bool,
215        is_fixed_gas_limit: bool,
216        estimate_via_rpc: bool,
217        estimate_multiplier: u64,
218        tempo_sponsor: Option<&TempoSponsor>,
219        chain: Option<Chain>,
220    ) -> Result<TxHash> {
221        self.prepare(
222            &provider,
223            sequential_broadcast,
224            is_fixed_gas_limit,
225            estimate_via_rpc,
226            estimate_multiplier,
227            tempo_sponsor,
228            chain,
229        )
230        .await?;
231
232        self.send(provider).await
233    }
234}
235
236pub(crate) fn remaining_unsigned_transactions<N: Network>(
237    sequences: &[ScriptSequence<N>],
238) -> impl Iterator<Item = RemainingScriptTransaction> + '_ {
239    sequences.iter().flat_map(|sequence| {
240        remaining_transactions(sequence).filter(|tx| tx.is_unsigned()).map(|tx| {
241            RemainingScriptTransaction {
242                chain: sequence.chain,
243                from: tx.from().expect("missing from"),
244            }
245        })
246    })
247}
248
249fn remaining_transaction_start<N: Network>(sequence: &ScriptSequence<N>) -> usize {
250    sequence.receipts.len().min(sequence.transactions.len())
251}
252
253fn remaining_transactions<N: Network>(
254    sequence: &ScriptSequence<N>,
255) -> impl Iterator<Item = &TransactionMaybeSigned<N>> + '_ {
256    sequence.transactions().skip(remaining_transaction_start(sequence))
257}
258
259/// Represents how to send _all_ transactions
260pub enum SendTransactionsKind<N: Network> {
261    /// Send via `eth_sendTransaction` and rely on the  `from` address being unlocked.
262    Unlocked(AddressHashSet),
263    /// Send a signed transaction via `eth_sendRawTransaction`, or via browser
264    Raw {
265        eth_wallets: AddressHashMap<EthereumWallet>,
266        browser: Option<BrowserSigner<N>>,
267        access_keys: HashMap<SignerScope, TempoAccountsWallet>,
268    },
269}
270
271impl<N: Network> SendTransactionsKind<N> {
272    /// Returns the [`SendTransactionKind`] for the given address
273    ///
274    /// Returns an error if no matching signer is found or the address is not unlocked
275    pub fn for_sender(
276        &self,
277        chain: u64,
278        addr: &Address,
279        tx: N::TransactionRequest,
280    ) -> Result<SendTransactionKind<'_, N>> {
281        match self {
282            Self::Unlocked(unlocked) => {
283                if !unlocked.contains(addr) {
284                    bail!("Sender address {:?} is not unlocked", addr);
285                }
286                Ok(SendTransactionKind::Unlocked(tx))
287            }
288            Self::Raw { eth_wallets, browser, access_keys } => {
289                if let Some(wallet) = access_keys.get(&SignerScope::new(chain, *addr)) {
290                    Ok(SendTransactionKind::AccessKey(tx, Box::new(wallet.clone())))
291                } else if let Some(wallet) = eth_wallets.get(addr) {
292                    Ok(SendTransactionKind::Raw(tx, wallet))
293                } else if let Some(b) = browser
294                    && b.address() == *addr
295                {
296                    Ok(SendTransactionKind::Browser(tx, b))
297                } else {
298                    bail!("No matching signer for {:?} found", addr);
299                }
300            }
301        }
302    }
303}
304
305/// State after we have bundled all
306/// [`TransactionWithMetadata`](forge_script_sequence::TransactionWithMetadata) objects into a
307/// single [`ScriptSequenceKind`] object containing one or more script sequences.
308pub struct BundledState<FEN: FoundryEvmNetwork> {
309    pub args: ScriptArgs,
310    pub script_config: ScriptConfig<FEN>,
311    pub script_wallets: Wallets,
312    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
313    pub build_data: LinkedBuildData,
314    pub sequence: ScriptSequenceKind<FEN::Network>,
315}
316
317impl<FEN: FoundryEvmNetwork> BundledState<FEN> {
318    pub async fn wait_for_pending(mut self) -> Result<Self> {
319        let progress = ScriptProgress::default();
320        let progress_ref = &progress;
321        let futs = self
322            .sequence
323            .sequences_mut()
324            .iter_mut()
325            .enumerate()
326            .map(|(sequence_idx, sequence)| async move {
327                let rpc_url = sequence.rpc_url();
328                let provider = Arc::new(ProviderBuilder::new(rpc_url).build()?);
329                progress_ref
330                    .wait_for_pending(
331                        sequence_idx,
332                        sequence,
333                        &provider,
334                        self.script_config.config.transaction_timeout,
335                        self.args.confirmations,
336                    )
337                    .await
338            })
339            .collect::<Vec<_>>();
340
341        let errors = join_all(futs).await.into_iter().filter_map(Result::err).collect::<Vec<_>>();
342
343        self.sequence.save(true, false)?;
344
345        if !errors.is_empty() {
346            return Err(eyre::eyre!("{}", errors.iter().format("\n")));
347        }
348
349        Ok(self)
350    }
351
352    /// Broadcasts transactions from all sequences.
353    pub async fn broadcast(mut self) -> Result<BroadcastedState<FEN>> {
354        let remaining_transactions =
355            remaining_unsigned_transactions(self.sequence.sequences()).collect::<Vec<_>>();
356        let required_addresses =
357            remaining_transactions.iter().map(|tx| tx.from).collect::<AddressHashSet>();
358
359        if required_addresses.contains(&Config::DEFAULT_SENDER) {
360            eyre::bail!(
361                "You seem to be using Foundry's default sender. Be sure to set your own --sender."
362            );
363        }
364
365        let send_kind = if self.args.unlocked {
366            SendTransactionsKind::Unlocked(required_addresses.clone())
367        } else {
368            let expected_session_sender = script_session_expected_sender_if_configured(
369                &self.script_config.tempo,
370                &required_addresses,
371            )?;
372
373            // For addresses without an explicit signer, try the Tempo Accounts store.
374            let mut access_keys: HashMap<SignerScope, TempoAccountsWallet> = HashMap::default();
375            if let Some(expected_session_sender) = expected_session_sender
376                && let Some(session) =
377                    self.script_config.tempo.session_signer_for_multi_wallet_any_chain(
378                        &self.args.wallets,
379                        Some(expected_session_sender),
380                    )?
381            {
382                insert_session_access_key_for_remaining_transactions(
383                    &mut access_keys,
384                    session,
385                    &remaining_transactions,
386                )?;
387            }
388
389            let signers: Vec<Address> = self
390                .script_wallets
391                .signers()
392                .map_err(|e| eyre::eyre!("{e}"))?
393                .into_iter()
394                .chain(self.browser_wallet.as_ref().map(|b| b.address()))
395                .collect();
396
397            let mut missing_addresses = Vec::new();
398            let accounts_wallet = self
399                .script_config
400                .evm_opts
401                .networks
402                .is_tempo()
403                .then(TempoAccountsWallet::try_from_default_store)
404                .transpose()?
405                .flatten();
406
407            for tx in &remaining_transactions {
408                let scope = tx.scope();
409                if !signers.contains(&tx.from) && !access_keys.contains_key(&scope) {
410                    if let Some(wallet) = accounts_wallet.as_ref()
411                        && wallet.has_account(tx.from)?
412                    {
413                        access_keys.insert(scope, wallet.clone().with_chain_id(tx.chain));
414                    } else {
415                        missing_addresses.push(tx.from);
416                    }
417                }
418            }
419
420            missing_addresses.sort_unstable();
421            missing_addresses.dedup();
422
423            if !missing_addresses.is_empty() {
424                eyre::bail!(
425                    "No associated wallet for addresses: {:?}. Unlocked wallets: {:?}",
426                    missing_addresses,
427                    signers
428                );
429            }
430
431            let signers = self.script_wallets.into_multi_wallet().into_signers()?;
432            let eth_wallets: AddressHashMap<EthereumWallet> =
433                signers.into_iter().map(|(addr, signer)| (addr, signer.into())).collect();
434
435            SendTransactionsKind::Raw { eth_wallets, browser: self.browser_wallet, access_keys }
436        };
437
438        let tempo_sponsor = self.script_config.tempo.sponsor_config().await?.map(Arc::new);
439        if tempo_sponsor.is_some()
440            && self.script_config.tempo.sponsor_sig.is_some()
441            && remaining_transactions.len() > 1
442        {
443            eyre::bail!(
444                "--tempo.sponsor-sig can only sponsor one remaining script transaction; use --tempo.sponsor-signer for multi-transaction scripts"
445            );
446        }
447
448        let progress = ScriptProgress::default();
449
450        for i in 0..self.sequence.sequences().len() {
451            let mut sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
452
453            let provider = Arc::new(ProviderBuilder::new(sequence.rpc_url()).build()?);
454            let already_broadcasted = sequence.receipts.len();
455
456            let seq_progress = progress.get_sequence_progress(i, sequence);
457
458            if already_broadcasted < sequence.transactions.len() {
459                let is_legacy = Chain::from(sequence.chain).is_legacy() || self.args.legacy;
460                // Make a one-time gas price estimation
461                let (gas_price, eip1559_fees) = match (
462                    is_legacy,
463                    self.args.with_gas_price,
464                    self.args.priority_gas_price,
465                ) {
466                    (true, Some(gas_price), _) => (Some(gas_price.to()), None),
467                    (true, None, _) => (Some(provider.get_gas_price().await?), None),
468                    (false, Some(max_fee_per_gas), Some(max_priority_fee_per_gas)) => {
469                        let max_fee: u128 = max_fee_per_gas.to();
470                        let max_priority: u128 = max_priority_fee_per_gas.to();
471                        if max_priority > max_fee {
472                            eyre::bail!(
473                                "--priority-gas-price ({max_priority}) cannot be higher than --with-gas-price ({max_fee})"
474                            );
475                        }
476                        (
477                            None,
478                            Some(Eip1559Estimation {
479                                max_fee_per_gas: max_fee,
480                                max_priority_fee_per_gas: max_priority,
481                            }),
482                        )
483                    }
484                    (false, _, _) => {
485                        let fees = estimate_eip1559_fees(
486                            &provider,
487                            self.script_config.config.eip1559_fee_estimate,
488                        )
489                        .await
490                        .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
491
492                        // Browser wallets may suggest their own tip; query it best-effort.
493                        let browser_suggested_tip = if matches!(
494                            &send_kind,
495                            SendTransactionsKind::Raw { browser: Some(_), .. }
496                        ) {
497                            provider.get_max_priority_fee_per_gas().await.ok()
498                        } else {
499                            None
500                        };
501
502                        let fees = resolve_broadcast_eip1559_fees(
503                            fees,
504                            self.args.with_gas_price.map(|p| p.to()),
505                            self.args.priority_gas_price.map(|p| p.to()),
506                            browser_suggested_tip,
507                        )?;
508
509                        (None, Some(fees.estimation()))
510                    }
511                };
512
513                // Iterate through transactions, matching the `from` field with the associated
514                // wallet. Then send the transaction. Panics if we find a unknown `from`
515                let sequence_chain = sequence.chain;
516                let mut transactions = Vec::with_capacity(
517                    sequence.transactions.len().saturating_sub(already_broadcasted),
518                );
519                for tx_with_metadata in sequence.transactions.iter().skip(already_broadcasted) {
520                    let is_fixed_gas_limit = tx_with_metadata.is_fixed_gas_limit;
521
522                    let kind = match tx_with_metadata.tx().clone() {
523                        TransactionMaybeSigned::Signed { tx, .. } => {
524                            if tempo_sponsor.is_some() {
525                                eyre::bail!(
526                                    "cannot attach Tempo sponsor signature to an already signed script transaction"
527                                );
528                            }
529                            SendTransactionKind::Signed(tx)
530                        }
531                        TransactionMaybeSigned::Unsigned(mut tx) => {
532                            let from = tx.from().expect("No sender for onchain transaction!");
533
534                            tx.set_chain_id(sequence_chain);
535
536                            // Set TxKind::Create explicitly to satisfy `check_reqd_fields` in
537                            // alloy
538                            if tx.kind().is_none() {
539                                tx.set_create();
540                            }
541
542                            if let Some(gas_price) = gas_price {
543                                tx.set_gas_price(gas_price);
544                            } else {
545                                let eip1559_fees = eip1559_fees.expect("was set above");
546                                tx.set_max_priority_fee_per_gas(
547                                    eip1559_fees.max_priority_fee_per_gas,
548                                );
549                                tx.set_max_fee_per_gas(eip1559_fees.max_fee_per_gas);
550                            }
551
552                            self.script_config.tempo.apply::<FEN::Network>(&mut tx, None);
553
554                            send_kind.for_sender(sequence_chain, &from, tx)?
555                        }
556                    };
557
558                    transactions.push((kind, is_fixed_gas_limit));
559                }
560
561                let estimate_via_rpc = has_different_gas_calc(sequence.chain)
562                    || self.script_config.evm_opts.networks.is_tempo()
563                    || self.args.skip_simulation;
564
565                // We only wait for a transaction receipt before sending the next transaction, if
566                // there is more than one signer. There would be no way of assuring
567                // their order otherwise.
568                // Or if the chain does not support batched transactions (eg. Arbitrum).
569                // Or if we need to invoke eth_estimateGas before sending transactions.
570                let sequential_broadcast = estimate_via_rpc
571                    || self.args.slow
572                    || required_addresses.len() != 1
573                    || !has_batch_support(sequence.chain);
574
575                // We send transactions and wait for receipts in batches of 100, since some networks
576                // cannot handle more than that.
577                let batch_size = if sequential_broadcast { 1 } else { 100 };
578                let mut index = already_broadcasted;
579                let sequence_chain = sequence.chain;
580
581                for (batch_number, batch) in transactions.chunks(batch_size).enumerate() {
582                    seq_progress.inner.write().set_status(&format!(
583                        "Sending transactions [{} - {}]",
584                        batch_number * batch_size,
585                        batch_number * batch_size + std::cmp::min(batch_size, batch.len()) - 1
586                    ));
587
588                    if !batch.is_empty() {
589                        let pending_transactions =
590                            batch.iter().map(|(kind, is_fixed_gas_limit)| {
591                                let provider = provider.clone();
592                                let tempo_sponsor = tempo_sponsor.clone();
593                                async move {
594                                    let res = kind
595                                        .clone()
596                                        .prepare_and_send(
597                                            provider,
598                                            sequential_broadcast,
599                                            *is_fixed_gas_limit,
600                                            estimate_via_rpc,
601                                            self.args.gas_estimate_multiplier,
602                                            tempo_sponsor.as_deref(),
603                                            Some(sequence_chain.into()),
604                                        )
605                                        .await;
606                                    (res, kind, *is_fixed_gas_limit, 0, None)
607                                }
608                                .boxed()
609                            });
610
611                        let mut buffer = pending_transactions.collect::<FuturesUnordered<_>>();
612
613                        'send: while let Some((
614                            res,
615                            kind,
616                            is_fixed_gas_limit,
617                            attempt,
618                            original_res,
619                        )) = buffer.next().await
620                        {
621                            if res.is_err()
622                                && self.script_config.tempo.sponsor_sig.is_some()
623                                && attempt == 0
624                            {
625                                debug!(
626                                    "not retrying transaction because --tempo.sponsor-sig is a static signature"
627                                );
628                            } else if res.is_err() && attempt <= 3 {
629                                // Try to resubmit the transaction
630                                let provider = provider.clone();
631                                let progress = seq_progress.inner.clone();
632                                let tempo_sponsor = tempo_sponsor.clone();
633                                buffer.push(Box::pin(async move {
634                                    debug!(err=?res, ?attempt, "retrying transaction ");
635                                    let attempt = attempt + 1;
636                                    progress.write().set_status(&format!(
637                                        "retrying transaction {res:?} (attempt {attempt})"
638                                    ));
639                                    tokio::time::sleep(Duration::from_millis(1000 * attempt)).await;
640                                    let r = kind
641                                        .clone()
642                                        .prepare_and_send(
643                                            provider,
644                                            sequential_broadcast,
645                                            is_fixed_gas_limit,
646                                            estimate_via_rpc,
647                                            self.args.gas_estimate_multiplier,
648                                            tempo_sponsor.as_deref(),
649                                            Some(sequence_chain.into()),
650                                        )
651                                        .await;
652                                    (
653                                        r,
654                                        kind,
655                                        is_fixed_gas_limit,
656                                        attempt,
657                                        original_res.or(Some(res)),
658                                    )
659                                }));
660
661                                continue 'send;
662                            }
663
664                            // Preserve the original error if any
665                            let tx_hash = res.wrap_err_with(|| {
666                                if let Some(original_res) = original_res {
667                                    format!(
668                                        "Failed to send transaction after {attempt} attempts {original_res:?}"
669                                    )
670                                } else {
671                                    "Failed to send transaction".to_string()
672                                }
673                            })?;
674                            sequence.add_pending(index, tx_hash);
675
676                            // Checkpoint save
677                            self.sequence.save(true, false)?;
678                            sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
679
680                            seq_progress.inner.write().tx_sent(tx_hash);
681                            index += 1;
682                        }
683
684                        // Checkpoint save
685                        self.sequence.save(true, false)?;
686                        sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
687
688                        progress
689                            .wait_for_pending(
690                                i,
691                                sequence,
692                                &provider,
693                                self.script_config.config.transaction_timeout,
694                                self.args.confirmations,
695                            )
696                            .await?
697                    }
698                    // Checkpoint save
699                    self.sequence.save(true, false)?;
700                    sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
701                }
702            }
703
704            let (total_gas, total_gas_price, total_paid) =
705                sequence.receipts.iter().fold((0, 0, 0), |acc, receipt| {
706                    let gas_used = receipt.gas_used();
707                    let gas_price = receipt.effective_gas_price() as u64;
708                    (acc.0 + gas_used, acc.1 + gas_price, acc.2 + gas_used * gas_price)
709                });
710            let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
711            let avg_gas_price = total_gas_price
712                .checked_div(sequence.receipts.len() as u64)
713                .and_then(|avg| format_units(avg, 9).ok())
714                .unwrap_or_else(|| "N/A".to_string());
715
716            let token_symbol = NamedChain::try_from(sequence.chain)
717                .unwrap_or_default()
718                .native_currency_symbol()
719                .unwrap_or("ETH");
720            seq_progress.inner.write().set_status(&format!(
721                "Total Paid: {} {} ({} gas * avg {} gwei)\n",
722                paid.trim_end_matches('0'),
723                token_symbol,
724                total_gas,
725                avg_gas_price.trim_end_matches('0').trim_end_matches('.')
726            ));
727            seq_progress.inner.write().finish();
728        }
729
730        if !shell::is_json() {
731            sh_println!("\n\n==========================")?;
732            sh_println!("\nONCHAIN EXECUTION COMPLETE & SUCCESSFUL.")?;
733        }
734
735        Ok(BroadcastedState {
736            args: self.args,
737            script_config: self.script_config,
738            build_data: self.build_data,
739            sequence: self.sequence,
740        })
741    }
742
743    pub async fn verify_preflight_check(&self) -> Result<()> {
744        if self.args.verify_external && self.script_config.config.offline {
745            bail!("External contract verification is unavailable in offline mode");
746        }
747
748        for sequence in self.sequence.sequences() {
749            let chain: Chain = sequence.chain.into();
750            // Resolve the API key: CLI arg first, then per-chain config, then global fallback.
751            let etherscan_key = self
752                .script_config
753                .config
754                .get_etherscan_api_key(Some(chain))
755                .or_else(|| self.script_config.config.etherscan_api_key.clone());
756            let api_key =
757                self.args.verifier.resolve_api_key(etherscan_key.as_deref()).map(str::to_owned);
758            let has_url = self.args.verifier.verifier_url.is_some();
759            let is_explicit = self.args.verifier.is_explicitly_set();
760            // Presence check: use the fully-resolved provider type so that implicit Etherscan
761            // selection (key from env/config, no explicit --verifier flag) is validated too.
762            self.args
763                .verifier
764                .resolve(api_key.as_deref(), Some(chain))
765                .client(api_key.as_deref(), Some(chain), has_url, is_explicit)
766                .wrap_err_with(|| {
767                    format!("Verification preflight check failed for chain {}", sequence.chain)
768                })?;
769            // Connectivity check: validates credentials are actually accepted by the verifier.
770            self.args
771                .verifier
772                .check_credentials(api_key.as_deref(), chain, &self.script_config.config)
773                .await
774                .wrap_err_with(|| {
775                    format!("Verification preflight check failed for chain {}", sequence.chain)
776                })?;
777        }
778
779        Ok(())
780    }
781}
782
783impl BundledState<TempoEvmNetwork> {
784    /// Broadcasts all transactions as a single Tempo batch transaction (type 0x76).
785    ///
786    /// This method collects all individual transactions from the script and combines them
787    /// into a single batch transaction for atomic execution on Tempo.
788    pub async fn broadcast_batch(mut self) -> Result<BroadcastedState<TempoEvmNetwork>> {
789        // Batch mode only supports single chain for now
790        if self.sequence.sequences().len() != 1 {
791            bail!(
792                "--batch mode only supports single-chain scripts. \
793                 Use --multi without --batch for multi-chain."
794            );
795        }
796
797        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
798        let total_transactions = sequence.transactions.len();
799        let remaining_start = remaining_transaction_start(sequence);
800
801        if remaining_start == total_transactions {
802            sh_println!("No transactions to broadcast in batch mode.")?;
803            return Ok(BroadcastedState {
804                args: self.args,
805                script_config: self.script_config,
806                build_data: self.build_data,
807                sequence: self.sequence,
808            });
809        }
810
811        // Reject pre-signed transactions: a batch is a single atomic tx from one sender,
812        // so any tx already signed by another key would silently be re-attributed.
813        if let Some((idx, _)) =
814            sequence.transactions().enumerate().find(|(_, tx)| !tx.is_unsigned())
815        {
816            bail!(
817                "--batch cannot include pre-signed transactions (found at position {}); \
818                 batch mode signs a single atomic transaction from one sender.",
819                idx + 1
820            );
821        }
822
823        // Collect sender addresses - batch mode requires single sender
824        let senders: AddressHashSet = remaining_transactions(sequence)
825            .filter(|tx| tx.is_unsigned())
826            .filter_map(|tx| tx.from())
827            .collect();
828
829        if senders.len() != 1 {
830            bail!(
831                "--batch mode requires all transactions to have the same sender. \
832                 Found {} unique senders: {:?}",
833                senders.len(),
834                senders
835            );
836        }
837
838        let sender = *senders.iter().next().unwrap();
839        let chain_id = sequence.chain;
840
841        if sender == Config::DEFAULT_SENDER {
842            bail!(
843                "You seem to be using Foundry's default sender. Be sure to set your own --sender."
844            );
845        }
846
847        let provider = Arc::new(ProviderBuilder::<TempoNetwork>::new(sequence.rpc_url()).build()?);
848
849        // Resume detection happens before signer resolution, gas estimation, and sponsor attachment
850        // so that recovering an already-submitted batch tx never requires the original
851        // signer/sponsor or a fresh estimate.
852        //
853        // If the hash is found in the stamped transactions but a receipt cannot be obtained within
854        // the timeout, the tx is assumed dropped. We clear the stamped hashes so that a subsequent
855        // --resume will re-send a replacement instead of waiting on a dead hash.
856        let pending_batch_hash: Option<TxHash> =
857            sequence.transactions.iter().skip(remaining_start).find_map(|tx| tx.hash);
858
859        if let Some(tx_hash) = pending_batch_hash {
860            sh_println!(
861                "Resuming batch: tx {tx_hash:#x} already submitted, waiting for receipt..."
862            )?;
863
864            let timeout = self.script_config.config.transaction_timeout;
865            let receipt_result = tokio::time::timeout(
866                Duration::from_secs(timeout),
867                wait_for_batch_receipt(provider.as_ref(), tx_hash, self.args.confirmations),
868            )
869            .await;
870
871            match receipt_result {
872                Ok(Ok(Some(receipt))) => {
873                    // Tx confirmed, process receipt and return without touching signer/sponsor.
874                    let success = receipt.status();
875                    if success {
876                        sh_println!(
877                            "Batch transaction confirmed in block {}",
878                            receipt.block_number.unwrap_or(0)
879                        )?;
880                    } else {
881                        bail!("Batch transaction failed (reverted)");
882                    }
883
884                    let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
885                    let remaining_len = sequence.transactions.len() - remaining_start;
886                    let per_tx_addresses: Vec<Option<Address>> = sequence
887                        .transactions
888                        .iter()
889                        .skip(remaining_start)
890                        .map(|tx| match tx.call_kind {
891                            CallKind::Create | CallKind::Create2 => tx.contract_address,
892                            _ => None,
893                        })
894                        .collect();
895
896                    for (idx, addr) in per_tx_addresses.iter().enumerate() {
897                        if let Some(addr) = addr {
898                            sh_println!("  call[{idx}] deployed at: {addr:#x}")?;
899                        }
900                    }
901
902                    for addr in &per_tx_addresses {
903                        let mut tx_receipt = receipt.clone();
904                        tx_receipt.contract_address = *addr;
905                        sequence.receipts.push(tx_receipt);
906                    }
907                    // Clear the pending entry now that we have a receipt.
908                    sequence.remove_pending(tx_hash);
909
910                    let chain = sequence.chain;
911                    let _ = sequence;
912                    self.sequence.save(true, false)?;
913
914                    let total_gas = receipt.gas_used();
915                    let gas_price = receipt.effective_gas_price() as u64;
916                    let total_paid = total_gas * gas_price;
917                    let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
918                    let gas_price_gwei =
919                        format_units(gas_price, 9).unwrap_or_else(|_| "N/A".to_string());
920                    let token_symbol = NamedChain::try_from(chain)
921                        .unwrap_or_default()
922                        .native_currency_symbol()
923                        .unwrap_or("ETH");
924                    sh_println!(
925                        "\nTotal Paid: {} {} ({} gas * {} gwei)\n(resumed from previous run, {} tx(s))",
926                        paid.trim_end_matches('0'),
927                        token_symbol,
928                        total_gas,
929                        gas_price_gwei.trim_end_matches('0').trim_end_matches('.'),
930                        remaining_len,
931                    )?;
932
933                    if !shell::is_json() {
934                        sh_println!("\n\n==========================")?;
935                        sh_println!("\nBATCH EXECUTION COMPLETE & SUCCESSFUL.")?;
936                        sh_println!(
937                            "All {} calls executed atomically in a single transaction.",
938                            remaining_len
939                        )?;
940                    }
941
942                    return Ok(BroadcastedState {
943                        args: self.args,
944                        script_config: self.script_config,
945                        build_data: self.build_data,
946                        sequence: self.sequence,
947                    });
948                }
949                Ok(Ok(None)) => {
950                    // Dropped from mempool, clear stamped hashes so the next --resume re-sends.
951                    sh_println!(
952                        "Batch tx {tx_hash:#x} was dropped from the mempool; will re-send..."
953                    )?;
954                    let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
955                    sequence.remove_pending(tx_hash);
956                    for tx in sequence.transactions.iter_mut().skip(remaining_start) {
957                        tx.hash = None;
958                    }
959                    self.sequence.save(true, false)?;
960                    // Fall through to full send path below.
961                }
962                Ok(Err(e)) => return Err(e),
963                Err(_) => {
964                    // Timeout, clear stamped hashes so the next --resume can re-send rather than
965                    // waiting indefinitely on a potentially dead hash.
966                    sh_println!(
967                        "Timeout waiting for batch tx {tx_hash:#x}; clearing checkpoint so \
968                         --resume can re-send a replacement."
969                    )?;
970                    let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
971                    sequence.remove_pending(tx_hash);
972                    for tx in sequence.transactions.iter_mut().skip(remaining_start) {
973                        tx.hash = None;
974                    }
975                    self.sequence.save(true, false)?;
976                    return Err(eyre::eyre!(
977                        "Timeout waiting for batch transaction receipt (tx: {tx_hash:#x}). \
978                         The transaction hash has been cleared; run with --resume to retry."
979                    ));
980                }
981            }
982        }
983
984        // Reborrow after the potential save above.
985        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
986
987        let tempo_sponsor = self.script_config.tempo.sponsor_config().await?;
988
989        // Get wallet for signing
990        enum BatchSigner {
991            Unlocked,
992            Wallet(EthereumWallet),
993            TempoKeychain(Box<TempoAccountsWallet>),
994        }
995
996        let mut batch_signer = if self.args.unlocked {
997            BatchSigner::Unlocked
998        } else if let Some(session) = self.script_config.tempo.session_signer_for_multi_wallet(
999            &self.args.wallets,
1000            Some(sender),
1001            chain_id,
1002        )? {
1003            BatchSigner::TempoKeychain(Box::new(session.access_key))
1004        } else {
1005            let mut signers = self.script_wallets.into_multi_wallet().into_signers()?;
1006            if let Some(signer) = signers.remove(&sender) {
1007                BatchSigner::Wallet(EthereumWallet::new(signer))
1008            } else {
1009                // Try the Tempo Accounts store only for Tempo broadcasts.
1010                if self.script_config.evm_opts.networks.is_tempo()
1011                    && let Some(wallet) = TempoAccountsWallet::try_from_default_store()?
1012                    && wallet.has_account(sender)?
1013                {
1014                    BatchSigner::TempoKeychain(Box::new(wallet.with_chain_id(chain_id)))
1015                } else {
1016                    bail!("No wallet found for sender {}", sender);
1017                }
1018            }
1019        };
1020
1021        let create2_deployer = self.script_config.evm_opts.create2_deployer;
1022        let mut calls: Vec<Call> = Vec::new();
1023        for (call_index, tx) in remaining_transactions(sequence).enumerate() {
1024            // --batch cannot carry EIP-7702 authorization lists: they require per-tx signing
1025            // and cannot be atomically bundled into a Tempo batch.
1026            if tx.authorization_list().is_some_and(|l| !l.is_empty()) {
1027                bail!(
1028                    "--batch does not support EIP-7702 authorization lists \
1029                     (found at transaction {}); use regular broadcast instead.",
1030                    call_index + 1
1031                );
1032            }
1033            // --batch cannot carry blob sidecars: Tempo batch txs are not blob-carrying txs.
1034            if let TransactionMaybeSigned::Unsigned(inner) = tx
1035                && inner.blob_sidecar().is_some()
1036            {
1037                bail!(
1038                    "--batch does not support blob (EIP-4844) transactions \
1039                     (found at transaction {}); use regular broadcast instead.",
1040                    call_index + 1
1041                );
1042            }
1043
1044            // CREATEs are rewritten to CREATE2 via the Arachnid factory by the batch
1045            // inspector before broadcast, so tx.to() should always be Some here.
1046            let to = match tx.to() {
1047                Some(addr) => TxKind::Call(addr),
1048                None => {
1049                    bail!(
1050                        "Unexpected raw CREATE in --batch mode at position {} — \
1051                     this is a bug; CREATEs should have been rewritten by the inspector.",
1052                        call_index + 1
1053                    );
1054                }
1055            };
1056            let value = tx.value().unwrap_or(U256::ZERO);
1057            let input = tx.input().cloned().unwrap_or_default();
1058
1059            calls.push(Call { to, value, input });
1060        }
1061
1062        if calls.is_empty() {
1063            sh_println!("No transactions to broadcast in batch mode.")?;
1064            return Ok(BroadcastedState {
1065                args: self.args,
1066                script_config: self.script_config,
1067                build_data: self.build_data,
1068                sequence: self.sequence,
1069            });
1070        }
1071
1072        // CREATE2 deployer must exist on-chain for any rewritten CREATEs.
1073        let needs_factory = sequence
1074            .transactions
1075            .iter()
1076            .skip(remaining_start)
1077            .any(|tx| matches!(tx.call_kind, CallKind::Create | CallKind::Create2));
1078        if needs_factory {
1079            let code = provider.get_code_at(create2_deployer).await?;
1080            if keccak256(&code) != DEFAULT_CREATE2_DEPLOYER_CODEHASH {
1081                bail!(
1082                    "CREATE2 deployer {create2_deployer:#x} is not deployed on this Tempo network; \
1083                     --batch requires it. Deploy it first and retry."
1084                );
1085            }
1086        }
1087
1088        sh_println!(
1089            "\n## Broadcasting batch transaction with {} call(s) to chain {}...",
1090            calls.len(),
1091            sequence.chain
1092        )?;
1093
1094        // Build the batch transaction request
1095        let nonce = provider.get_transaction_count(sender).await?;
1096
1097        // Batch transactions are Tempo-only and always use EIP-1559 style fees.
1098        let fees = estimate_eip1559_fees(&provider, self.script_config.config.eip1559_fee_estimate)
1099            .await?;
1100        let fees = resolve_broadcast_eip1559_fees(
1101            fees,
1102            self.args.with_gas_price.map(|p| p.to()),
1103            self.args.priority_gas_price.map(|p| p.to()),
1104            None,
1105        )?;
1106        let max_fee_per_gas = fees.max_fee_per_gas;
1107        let max_priority_fee_per_gas = fees.max_priority_fee_per_gas;
1108
1109        let mut batch_tx = TempoTransactionRequest {
1110            inner: TransactionRequest {
1111                from: Some(sender),
1112                to: None,
1113                value: None,
1114                input: Default::default(),
1115                nonce: Some(nonce),
1116                chain_id: Some(chain_id),
1117                max_fee_per_gas: Some(max_fee_per_gas),
1118                max_priority_fee_per_gas: Some(max_priority_fee_per_gas),
1119                ..Default::default()
1120            },
1121            fee_token: self.script_config.tempo.fee_token,
1122            calls: calls.clone(),
1123            nonce_key: self.script_config.tempo.expiring_nonce.then_some(U256::MAX),
1124            valid_before: self.script_config.tempo.valid_before.and_then(NonZeroU64::new),
1125            ..Default::default()
1126        };
1127        self.script_config.tempo.apply::<TempoNetwork>(&mut batch_tx, None);
1128        let fee_token = if let Some(sponsor) = &tempo_sponsor {
1129            sponsor
1130                .resolve_and_set_fee_token(
1131                    Some(provider.as_ref()),
1132                    Some(Chain::from_named(NamedChain::Tempo)),
1133                    &mut batch_tx,
1134                )
1135                .await?;
1136            None
1137        } else {
1138            resolve_and_set_fee_token(
1139                Some(provider.as_ref()),
1140                Some(Chain::from_named(NamedChain::Tempo)),
1141                &mut batch_tx,
1142                Some(sender),
1143            )
1144            .await?
1145        };
1146
1147        if let BatchSigner::TempoKeychain(wallet) = &mut batch_signer {
1148            **wallet = batch_tx.prepare_with_tempo_wallet(provider.as_ref(), wallet).await?;
1149        }
1150
1151        // Estimate gas for the batch transaction
1152        estimate_gas(&mut batch_tx, provider.as_ref(), self.args.gas_estimate_multiplier, false)
1153            .await?;
1154
1155        sh_println!("Estimated gas: {}", batch_tx.inner.gas.unwrap_or(0))?;
1156
1157        if let Some(sponsor) = &tempo_sponsor {
1158            sponsor.attach_and_print::<TempoNetwork>(&mut batch_tx, sender).await?;
1159        } else {
1160            maybe_print_fee_token(Some(provider.as_ref()), fee_token).await?;
1161        }
1162
1163        // Sign and send.
1164        let tx_hash = match batch_signer {
1165            BatchSigner::Wallet(wallet) => {
1166                let provider_with_wallet =
1167                    alloy_provider::ProviderBuilder::<_, _, TempoNetwork>::default()
1168                        .wallet(wallet)
1169                        .connect_provider(provider.as_ref());
1170
1171                let pending = provider_with_wallet.send_transaction(batch_tx).await?;
1172                *pending.tx_hash()
1173            }
1174            BatchSigner::TempoKeychain(wallet) => {
1175                let raw_tx = batch_tx.sign_with_tempo_wallet(&wallet).await?;
1176
1177                let pending = provider.send_raw_transaction(&raw_tx).await?;
1178                *pending.tx_hash()
1179            }
1180            BatchSigner::Unlocked => {
1181                let pending = provider.send_transaction(batch_tx).await?;
1182                *pending.tx_hash()
1183            }
1184        };
1185
1186        sh_println!("Batch transaction sent: {:#x}", tx_hash)?;
1187
1188        // Checkpoint: stamp the batch hash on all remaining transactions (so that resume
1189        // detection finds it regardless of which tx it inspects first), register one entry
1190        // in sequence.pending for drop/timeout tracking, then save.
1191        for tx in sequence.transactions.iter_mut().skip(remaining_start) {
1192            tx.hash = Some(tx_hash);
1193        }
1194        if !sequence.pending.contains(&tx_hash) {
1195            sequence.pending.push(tx_hash);
1196        }
1197        self.sequence.save(true, false)?;
1198
1199        // Wait for receipt
1200        let timeout = self.script_config.config.transaction_timeout;
1201        let receipt = tokio::time::timeout(
1202            Duration::from_secs(timeout),
1203            wait_for_batch_receipt(provider.as_ref(), tx_hash, self.args.confirmations),
1204        )
1205        .await
1206        .map_err(|_| eyre::eyre!("Timeout waiting for batch transaction receipt (tx: {tx_hash:#x}). Run with --resume to retry."))??
1207        .ok_or_else(|| eyre::eyre!("Batch transaction {tx_hash:#x} was dropped from the mempool. Run with --resume to retry."))?;
1208
1209        let success = receipt.status();
1210        if success {
1211            sh_println!(
1212                "Batch transaction confirmed in block {}",
1213                receipt.block_number.unwrap_or(0)
1214            )?;
1215        } else {
1216            bail!("Batch transaction failed (reverted)");
1217        }
1218
1219        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
1220        sequence.remove_pending(tx_hash);
1221
1222        // Receipts are pushed 1:1 with the remaining (not-yet-receipted) transactions.
1223        let remaining_len = sequence.transactions.len() - remaining_start;
1224        if calls.len() != remaining_len {
1225            bail!(
1226                "batch call count ({}) does not match remaining transactions ({}); \
1227                 refusing to push misaligned receipts",
1228                calls.len(),
1229                remaining_len
1230            );
1231        }
1232        // Only carry through contract_address for actual deployments; plain calls also
1233        // store the callee in `contract_address`, which would otherwise be copied into
1234        // the receipt and treated as a fresh deployment by downstream consumers
1235        // (broadcast JSON, verifier).
1236        let per_tx_addresses: Vec<Option<Address>> = sequence
1237            .transactions
1238            .iter()
1239            .skip(remaining_start)
1240            .map(|tx| match tx.call_kind {
1241                CallKind::Create | CallKind::Create2 => tx.contract_address,
1242                _ => None,
1243            })
1244            .collect();
1245
1246        for (idx, addr) in per_tx_addresses.iter().enumerate() {
1247            if let Some(addr) = addr {
1248                sh_println!("  call[{idx}] deployed at: {addr:#x}")?;
1249            }
1250        }
1251
1252        // gasUsed reflects the whole batch; per-call attribution is unavailable from the receipt.
1253        for addr in &per_tx_addresses {
1254            let mut tx_receipt = receipt.clone();
1255            tx_receipt.contract_address = *addr;
1256            sequence.receipts.push(tx_receipt);
1257        }
1258
1259        let chain = sequence.chain;
1260        let _ = sequence;
1261
1262        self.sequence.save(true, false)?;
1263
1264        let total_gas = receipt.gas_used();
1265        let gas_price = receipt.effective_gas_price() as u64;
1266        let total_paid = total_gas * gas_price;
1267        let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
1268        let gas_price_gwei = format_units(gas_price, 9).unwrap_or_else(|_| "N/A".to_string());
1269
1270        let token_symbol = NamedChain::try_from(chain)
1271            .unwrap_or_default()
1272            .native_currency_symbol()
1273            .unwrap_or("ETH");
1274        sh_println!(
1275            "\nTotal Paid: {} {} ({} gas * {} gwei)",
1276            paid.trim_end_matches('0'),
1277            token_symbol,
1278            total_gas,
1279            gas_price_gwei.trim_end_matches('0').trim_end_matches('.')
1280        )?;
1281
1282        if !shell::is_json() {
1283            sh_println!("\n\n==========================")?;
1284            sh_println!("\nBATCH EXECUTION COMPLETE & SUCCESSFUL.")?;
1285            sh_println!("All {} calls executed atomically in a single transaction.", calls.len())?;
1286        }
1287
1288        Ok(BroadcastedState {
1289            args: self.args,
1290            script_config: self.script_config,
1291            build_data: self.build_data,
1292            sequence: self.sequence,
1293        })
1294    }
1295}
1296
1297async fn wait_for_batch_receipt<N: Network>(
1298    provider: &RootProvider<N>,
1299    tx_hash: TxHash,
1300    confirmations: u64,
1301) -> Result<Option<N::ReceiptResponse>> {
1302    loop {
1303        if let Some(receipt) = provider.get_transaction_receipt(tx_hash).await?
1304            && let Some(receipt_block) = receipt.block_number()
1305        {
1306            let latest_block = provider.get_block_number().await?;
1307            if latest_block >= receipt_block.saturating_add(confirmations.saturating_sub(1)) {
1308                return Ok(Some(receipt));
1309            }
1310        }
1311
1312        if provider.get_transaction_by_hash(tx_hash).await?.is_none() {
1313            return Ok(None);
1314        }
1315
1316        tokio::time::sleep(Duration::from_millis(500)).await;
1317    }
1318}
1319
1320pub async fn estimate_gas<N: Network, P: Provider<N>>(
1321    tx: &mut N::TransactionRequest,
1322    provider: &P,
1323    estimate_multiplier: u64,
1324    tempo_browser: bool,
1325) -> Result<()>
1326where
1327    N::TransactionRequest: FoundryTransactionBuilder<N>,
1328{
1329    // if already set, some RPC endpoints might simply return the gas value that is already
1330    // set in the request and omit the estimate altogether, so we remove it here
1331    tx.reset_gas_limit();
1332
1333    let request =
1334        if tempo_browser { tx.browser_wallet_gas_estimation_request() } else { tx.clone() };
1335    tx.set_gas_limit(
1336        provider.estimate_gas(request).await.wrap_err("Failed to estimate gas for tx")?
1337            * estimate_multiplier
1338            / 100,
1339    );
1340    Ok(())
1341}
1342
1343/// Returns `caller`'s nonce at an already resolved fork block.
1344pub(super) async fn next_nonce_resolved(
1345    caller: Address,
1346    evm_opts: &EvmOpts,
1347    fork: &ResolvedFork,
1348) -> eyre::Result<u64> {
1349    evm_opts.transaction_count_at_resolved_fork(caller, fork).await
1350}
1351
1352fn reject_access_key_create<N: Network>(
1353    tx: &N::TransactionRequest,
1354    uses_access_key: bool,
1355) -> Result<()>
1356where
1357    N::TransactionRequest: FoundryTransactionBuilder<N>,
1358{
1359    if uses_access_key && tx.tempo_calls().iter().any(|(to, _)| to.is_create()) {
1360        bail!("Tempo access-key transactions cannot use CREATE");
1361    }
1362    Ok(())
1363}
1364
1365fn convert_tempo_aa_create<N: Network>(tx: &mut N::TransactionRequest)
1366where
1367    N::TransactionRequest: FoundryTransactionBuilder<N>,
1368{
1369    if tx.is_tempo_aa() {
1370        tx.convert_create_to_call();
1371    }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376    use super::*;
1377    use alloy_consensus::{Eip658Value, Receipt, ReceiptEnvelope, ReceiptWithBloom};
1378    use alloy_eips::BlockId;
1379    use alloy_network::Ethereum;
1380    use alloy_primitives::{Bloom, address};
1381    use alloy_rpc_types::TransactionReceipt;
1382    use alloy_signer::Signer;
1383    use forge_script_sequence::TransactionWithMetadata;
1384
1385    const ROOT_PRIVATE_KEY: &str =
1386        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1387    const ACCESS_KEY_PRIVATE_KEY: &str =
1388        "0x59c6995e998f97a5a004497e5da3b5d2b2b66a87f064d39c44da0b6d6e4f8ff0";
1389
1390    #[tokio::test(flavor = "multi_thread")]
1391    async fn next_nonce_uses_exact_fork_hash() {
1392        let (_api, handle) = anvil::spawn(anvil::NodeConfig::test()).await;
1393        let provider = handle.http_provider();
1394        let sender = handle.dev_accounts().next().unwrap();
1395        let recipient = Address::with_last_byte(1);
1396
1397        let receipt = provider
1398            .send_transaction(
1399                TransactionRequest::default()
1400                    .from(sender)
1401                    .to(recipient)
1402                    .value(U256::from(1))
1403                    .into(),
1404            )
1405            .await
1406            .unwrap()
1407            .get_receipt()
1408            .await
1409            .unwrap();
1410        let block_number = receipt.block_number.unwrap();
1411        let evm_opts = EvmOpts {
1412            fork_url: Some(handle.http_endpoint()),
1413            fork_block_number: Some(block_number),
1414            ..Default::default()
1415        };
1416        let fork = evm_opts.resolve_fork().await.unwrap().unwrap();
1417        assert_eq!(next_nonce_resolved(sender, &evm_opts, &fork).await.unwrap(), 1);
1418
1419        provider
1420            .raw_request::<_, ()>("anvil_reorg".into(), (1_u64, Vec::<serde_json::Value>::new()))
1421            .await
1422            .unwrap();
1423        assert_eq!(
1424            provider
1425                .get_transaction_count(sender)
1426                .block_id(BlockId::number(block_number))
1427                .await
1428                .unwrap(),
1429            0
1430        );
1431
1432        match next_nonce_resolved(sender, &evm_opts, &fork).await {
1433            Ok(0) => panic!("the exact lookup fell back to the replacement block"),
1434            Ok(1) | Err(_) => {}
1435            Ok(nonce) => panic!("unexpected nonce: {nonce}"),
1436        }
1437    }
1438
1439    #[test]
1440    fn access_key_signer_takes_precedence_over_same_sender_wallet() {
1441        let root = foundry_wallets::utils::create_private_key_signer(ROOT_PRIVATE_KEY).unwrap();
1442        let root_address = root.address();
1443        let access_key =
1444            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
1445        let access_key_address = access_key.address();
1446        let mut eth_wallets = AddressHashMap::default();
1447        eth_wallets.insert(root_address, EthereumWallet::new(root));
1448        let mut access_keys = HashMap::default();
1449        access_keys.insert(
1450            SignerScope::new(4217, root_address),
1451            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217),
1452        );
1453        let send_kind =
1454            SendTransactionsKind::<Ethereum>::Raw { eth_wallets, browser: None, access_keys };
1455
1456        let tx = TransactionRequest { from: Some(root_address), ..Default::default() };
1457        let sender = send_kind.for_sender(4217, &root_address, tx).unwrap();
1458
1459        match sender {
1460            SendTransactionKind::AccessKey(_, wallet) => {
1461                assert_eq!(wallet.key_id().unwrap(), access_key_address);
1462                assert_eq!(wallet.account(), root_address);
1463            }
1464            _ => panic!("expected access key signer"),
1465        }
1466    }
1467
1468    #[test]
1469    fn access_key_signer_is_scoped_to_chain() {
1470        let root = foundry_wallets::utils::create_private_key_signer(ROOT_PRIVATE_KEY).unwrap();
1471        let root_address = root.address();
1472        let access_key =
1473            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
1474        let mut eth_wallets = AddressHashMap::default();
1475        eth_wallets.insert(root_address, EthereumWallet::new(root));
1476        let mut access_keys = HashMap::default();
1477        access_keys.insert(
1478            SignerScope::new(4217, root_address),
1479            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217),
1480        );
1481        let send_kind =
1482            SendTransactionsKind::<Ethereum>::Raw { eth_wallets, browser: None, access_keys };
1483
1484        let tx = TransactionRequest { from: Some(root_address), ..Default::default() };
1485        let sender = send_kind.for_sender(1, &root_address, tx).unwrap();
1486
1487        match sender {
1488            SendTransactionKind::Raw(_, wallet) => {
1489                assert_eq!(wallet.default_signer().address(), root_address);
1490            }
1491            _ => panic!("expected root wallet signer for non-session chain"),
1492        }
1493    }
1494
1495    #[test]
1496    fn remaining_unsigned_transactions_skip_completed_transactions() {
1497        let completed = address!("0x1111111111111111111111111111111111111111");
1498        let remaining_sender = address!("0x2222222222222222222222222222222222222222");
1499        let mut sequence = ScriptSequence::<Ethereum> {
1500            chain: 4217,
1501            transactions: [script_tx(completed), script_tx(remaining_sender)].into(),
1502            receipts: vec![receipt()],
1503            ..Default::default()
1504        };
1505
1506        let remaining =
1507            remaining_unsigned_transactions(std::slice::from_ref(&sequence)).collect::<Vec<_>>();
1508        assert_eq!(remaining.len(), 1);
1509        assert_eq!(remaining[0].from, remaining_sender);
1510        assert_eq!(remaining[0].chain, 4217);
1511
1512        sequence.receipts.push(receipt());
1513        let remaining =
1514            remaining_unsigned_transactions(std::slice::from_ref(&sequence)).collect::<Vec<_>>();
1515        assert!(remaining.is_empty());
1516
1517        let completed_sequence = ScriptSequence::<Ethereum> {
1518            chain: 1,
1519            transactions: [script_tx(completed)].into(),
1520            receipts: vec![receipt()],
1521            ..Default::default()
1522        };
1523        let remaining_sequence = ScriptSequence::<Ethereum> {
1524            chain: 4217,
1525            transactions: [script_tx(remaining_sender)].into(),
1526            ..Default::default()
1527        };
1528
1529        let remaining = remaining_unsigned_transactions(&[completed_sequence, remaining_sequence])
1530            .collect::<Vec<_>>();
1531        assert_eq!(remaining.len(), 1);
1532        assert_eq!(remaining[0].chain, 4217);
1533    }
1534
1535    #[test]
1536    fn remaining_transactions_skip_receipt_prefix() {
1537        let completed = address!("0x1111111111111111111111111111111111111111");
1538        let second = address!("0x2222222222222222222222222222222222222222");
1539        let third = address!("0x3333333333333333333333333333333333333333");
1540        let mut sequence = ScriptSequence::<Ethereum> {
1541            chain: 4217,
1542            transactions: [script_tx(completed), script_tx(second), script_tx(third)].into(),
1543            receipts: vec![receipt()],
1544            ..Default::default()
1545        };
1546
1547        let remaining =
1548            remaining_transactions(&sequence).map(|tx| tx.from().unwrap()).collect::<Vec<_>>();
1549
1550        assert_eq!(remaining, vec![second, third]);
1551
1552        sequence.receipts = (0..4).map(|_| receipt()).collect();
1553        assert!(remaining_transactions(&sequence).next().is_none());
1554    }
1555
1556    #[tokio::test]
1557    async fn access_key_sets_key_id_before_estimation() {
1558        let root_address = address!("0x1111111111111111111111111111111111111111");
1559        let access_key =
1560            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
1561        let access_key_address = access_key.address();
1562        let access_key_wallet =
1563            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217);
1564        let mut sender = SendTransactionKind::<TempoNetwork>::AccessKey(
1565            TempoTransactionRequest {
1566                inner: TransactionRequest { from: Some(root_address), ..Default::default() },
1567                ..Default::default()
1568            },
1569            Box::new(access_key_wallet),
1570        );
1571        let provider =
1572            RootProvider::<TempoNetwork>::new_http("http://localhost:8545".parse().unwrap());
1573
1574        sender
1575            .prepare(
1576                &provider,
1577                false,
1578                true,
1579                false,
1580                100,
1581                None,
1582                Some(Chain::from_named(NamedChain::Mainnet)),
1583            )
1584            .await
1585            .unwrap();
1586
1587        match sender {
1588            SendTransactionKind::AccessKey(tx, _) => {
1589                assert_eq!(tx.key_id, Some(access_key_address));
1590            }
1591            _ => panic!("expected access key transaction"),
1592        }
1593    }
1594
1595    #[test]
1596    fn tempo_aa_create_moves_deployment_into_calls() {
1597        let mut tx = TempoTransactionRequest {
1598            inner: TransactionRequest { to: Some(TxKind::Create), ..Default::default() },
1599            fee_token: Some(address!("0x20c0000000000000000000000000000000000000")),
1600            ..Default::default()
1601        };
1602
1603        convert_tempo_aa_create::<TempoNetwork>(&mut tx);
1604
1605        assert!(tx.inner.to.is_none());
1606        assert_eq!(tx.calls.len(), 1);
1607        assert!(tx.calls[0].to.is_create());
1608    }
1609
1610    #[test]
1611    fn tempo_access_key_create_is_rejected_before_preparation() {
1612        let tx = TempoTransactionRequest {
1613            inner: TransactionRequest { to: Some(TxKind::Create), ..Default::default() },
1614            ..Default::default()
1615        };
1616
1617        let error = reject_access_key_create::<TempoNetwork>(&tx, true).unwrap_err();
1618
1619        assert!(error.to_string().contains("Tempo access-key transactions cannot use CREATE"));
1620    }
1621
1622    fn script_tx(from: Address) -> TransactionWithMetadata<Ethereum> {
1623        TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(TransactionRequest {
1624            from: Some(from),
1625            ..Default::default()
1626        }))
1627    }
1628
1629    fn receipt() -> TransactionReceipt {
1630        TransactionReceipt {
1631            inner: ReceiptEnvelope::Legacy(ReceiptWithBloom {
1632                receipt: Receipt {
1633                    status: Eip658Value::success(),
1634                    cumulative_gas_used: 0,
1635                    logs: vec![],
1636                },
1637                logs_bloom: Bloom::ZERO,
1638            }),
1639            transaction_hash: Default::default(),
1640            transaction_index: None,
1641            block_hash: None,
1642            block_number: None,
1643            gas_used: 0,
1644            effective_gas_price: 0,
1645            blob_gas_used: None,
1646            blob_gas_price: None,
1647            from: Address::ZERO,
1648            to: None,
1649            contract_address: None,
1650        }
1651    }
1652}