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    owner_approvals::{self, OfflineOwners},
7    progress::ScriptProgress,
8    receipts::is_mined_receipt_for,
9    recovery::{AttemptKind, DelegatedStatus},
10    sequence::{
11        DelegatedResolution, ScriptSequenceKind, blocked_pending, completed_transaction_prefix,
12        operation_ordinal,
13    },
14    session::{
15        SignerScope, insert_session_access_key_for_remaining_transactions,
16        script_session_expected_sender_if_configured,
17    },
18    verify::BroadcastedState,
19};
20use alloy_chains::{Chain, NamedChain};
21use alloy_consensus::{SignableTransaction, Signed, transaction::SignerRecoverable};
22use alloy_eips::eip2718::{Decodable2718, Encodable2718};
23use alloy_network::{
24    EthereumWallet, Network, NetworkTransactionBuilder, ReceiptResponse, TransactionBuilder,
25    TransactionResponse,
26};
27use alloy_primitives::{
28    Address, Bytes, TxHash, TxKind, U256, keccak256,
29    map::{AddressHashMap, AddressHashSet, HashMap, HashSet},
30    utils::format_units,
31};
32use alloy_provider::{
33    Provider, RootProvider,
34    transport::{RpcError, TransportError},
35    utils::Eip1559Estimation,
36};
37use alloy_rpc_types::{BlockId, TransactionRequest};
38use alloy_signer::{Signature, Signer};
39use eyre::{Context, ContextCompat, Result, bail};
40use forge_script_sequence::{ScriptSequence, TransactionWithMetadata};
41use foundry_cheatcodes::Wallets;
42use foundry_cli::{
43    opts::TempoOpts,
44    utils::{apply_gas_estimate_multiplier, has_batch_support, has_different_gas_calc},
45};
46use foundry_common::{
47    FoundryTransactionBuilder, TransactionMaybeSigned,
48    provider::{
49        ProviderBuilder,
50        fee::{estimate_eip1559_fees, resolve_broadcast_eip1559_fees},
51    },
52    shell,
53    tempo::{
54        TempoSponsor, active_tempo_hardfork,
55        configurable_account::{
56            ConfigurableAccountSigner, detect_configurable_account, reaches_threshold,
57        },
58        mark_sponsored_gas_estimation, maybe_print_fee_token, resolve_and_set_fee_token,
59    },
60};
61use foundry_config::Config;
62use foundry_evm::{
63    core::{
64        constants::DEFAULT_CREATE2_DEPLOYER_CODEHASH,
65        evm::{FoundryEvmNetwork, TempoEvmNetwork},
66    },
67    traces::CallKind,
68};
69use foundry_wallets::wallet_browser::{error::BrowserWalletError, signer::BrowserSigner};
70use futures::{FutureExt, StreamExt, future::join_all, stream::FuturesUnordered};
71use itertools::Itertools;
72use tempo_alloy::{
73    TempoNetwork,
74    accounts::TempoAccountsWallet,
75    chainspec::hardfork::TempoHardfork,
76    rpc::{TempoTransactionReceipt, TempoTransactionRequest},
77};
78use tempo_primitives::transaction::{Call, TEMPO_EXPIRING_NONCE_KEY, TempoTxEnvelope};
79
80/// Represents how to send a single transaction.
81#[derive(Clone)]
82pub enum SendTransactionKind<'a, N: Network> {
83    Unlocked(N::TransactionRequest),
84    Raw(N::TransactionRequest, &'a EthereumWallet),
85    Browser(N::TransactionRequest, &'a BrowserSigner<N>),
86    Signed(N::TxEnvelope),
87    AccessKey(N::TransactionRequest, Box<TempoAccountsWallet>),
88    ConfigurableAccount(N::TransactionRequest, &'a ConfigurableAccountSigner),
89    /// A configurable account transaction that is saved for its owners to approve, not sent.
90    OfflineOwners(N::TransactionRequest, &'a OfflineOwners),
91    PreparedRaw(Bytes, TxHash),
92}
93
94impl<'a, N: Network> SendTransactionKind<'a, N>
95where
96    N::TxEnvelope: From<Signed<N::UnsignedTx>>,
97    N::UnsignedTx: SignableTransaction<Signature>,
98    N::TransactionRequest: FoundryTransactionBuilder<N>,
99{
100    /// Prepares the transaction for broadcasting by synchronizing nonce and estimating gas.
101    ///
102    /// This method performs two key operations:
103    /// 1. Nonce synchronization: Waits for the provider's nonce to catch up to the expected
104    ///    transaction nonce when doing sequential broadcast
105    /// 2. Gas estimation: Re-estimates gas right before broadcasting for chains that require it
106    #[allow(clippy::too_many_arguments)]
107    pub async fn prepare(
108        &mut self,
109        provider: &RootProvider<N>,
110        sequential_broadcast: bool,
111        is_fixed_gas_limit: bool,
112        estimate_via_rpc: bool,
113        estimate_multiplier: u64,
114        tempo_sponsor: Option<&TempoSponsor>,
115    ) -> Result<()> {
116        let browser = matches!(self, Self::Browser(..));
117        let (tx, tempo_wallet) = match self {
118            Self::Raw(tx, _) | Self::Unlocked(tx) | Self::Browser(tx, _) => (tx, None),
119            Self::AccessKey(tx, wallet) => (tx, Some(wallet)),
120            Self::ConfigurableAccount(tx, account) => {
121                // The estimate models the owners' approvals.
122                account.prepare_request::<N>(tx);
123                (tx, None)
124            }
125            Self::Signed(_) | Self::PreparedRaw(..) => return Ok(()),
126            Self::OfflineOwners(..) => bail!("a transaction awaiting owner approvals is not sent"),
127        };
128
129        reject_access_key_create::<N>(tx, tempo_wallet.is_some())?;
130
131        // An expiring nonce is a TIP-1106 discriminator rather than a position in the sender's
132        // nonce sequence, so there is no provider nonce to wait for.
133        if sequential_broadcast && tx.nonce_key() != Some(TEMPO_EXPIRING_NONCE_KEY) {
134            let from = tx.from().expect("no sender");
135
136            let tx_nonce = tx.nonce().expect("no nonce");
137            for attempt in 0..5 {
138                let nonce = provider.get_transaction_count(from).await?;
139                match nonce.cmp(&tx_nonce) {
140                    Ordering::Greater => {
141                        bail!(
142                            "EOA nonce changed unexpectedly while sending transactions. Expected {tx_nonce} got {nonce} from provider."
143                        );
144                    }
145                    Ordering::Less => {
146                        if attempt == 4 {
147                            bail!(
148                                "After 5 attempts, provider nonce ({nonce}) is still behind expected nonce ({tx_nonce})."
149                            );
150                        }
151                        warn!(
152                            "Expected nonce ({tx_nonce}) is ahead of provider nonce ({nonce}). Retrying in 1 second..."
153                        );
154                        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
155                    }
156                    Ordering::Equal => {
157                        // Nonces are equal, we can proceed.
158                        break;
159                    }
160                }
161            }
162        }
163
164        if let Some(wallet) = tempo_wallet {
165            **wallet = tx.prepare_with_tempo_wallet(provider, wallet).await?;
166        }
167
168        let fee_token = if let Some(sponsor) = tempo_sponsor {
169            sponsor.resolve_and_set_fee_token(Some(provider), tx).await?;
170            None
171        } else {
172            resolve_and_set_fee_token(Some(provider), tx, tx.from()).await?
173        };
174
175        // A fee token, sponsor, validity window, or other Tempo field selects
176        // the AA transaction type. AA requests carry CREATE as their first
177        // call rather than as the Ethereum transaction `to` field.
178        convert_tempo_aa_create::<N>(tx);
179
180        // Chains which use `eth_estimateGas` are being sent sequentially and require their
181        // gas to be re-estimated right before broadcasting.
182        if !is_fixed_gas_limit && estimate_via_rpc {
183            estimate_gas(tx, provider, estimate_multiplier, browser, tempo_sponsor.is_some())
184                .await?;
185        }
186
187        if let Some(sponsor) = tempo_sponsor {
188            let from = tx.from().expect("no sender");
189            sponsor.attach_and_print::<N>(tx, from).await?;
190        } else {
191            maybe_print_fee_token(Some(provider), fee_token).await?;
192        }
193
194        Ok(())
195    }
196
197    #[allow(clippy::too_many_arguments)]
198    async fn prepare_for_durable_send(
199        mut self,
200        provider: &RootProvider<N>,
201        sequential_broadcast: bool,
202        is_fixed_gas_limit: bool,
203        estimate_via_rpc: bool,
204        estimate_multiplier: u64,
205        tempo_sponsor: Option<&TempoSponsor>,
206    ) -> Result<PreparedTransaction<'a, N>> {
207        self.prepare(
208            provider,
209            sequential_broadcast,
210            is_fixed_gas_limit,
211            estimate_via_rpc,
212            estimate_multiplier,
213            tempo_sponsor,
214        )
215        .await?;
216        if let Self::Unlocked(tx) = &mut self {
217            tx.prep_for_submission();
218        }
219        Ok(match self {
220            Self::Raw(tx, signer) => {
221                let signed = tx.build(signer).await?;
222                PreparedTransaction::Raw(Bytes::from(signed.encoded_2718()), signed.trie_hash())
223            }
224            Self::Signed(tx) => {
225                let hash = tx.trie_hash();
226                PreparedTransaction::Raw(Bytes::from(tx.encoded_2718()), hash)
227            }
228            Self::AccessKey(tx, wallet) => {
229                let payload = Bytes::from(tx.sign_with_tempo_wallet(&wallet).await?);
230                let envelope = N::TxEnvelope::decode_2718_exact(&payload)?;
231                PreparedTransaction::Raw(payload, envelope.trie_hash())
232            }
233            Self::ConfigurableAccount(tx, account) => {
234                let payload = Bytes::from(tx.sign_with_configurable_account(account).await?);
235                let envelope = N::TxEnvelope::decode_2718_exact(&payload)?;
236                PreparedTransaction::Raw(payload, envelope.trie_hash())
237            }
238            Self::PreparedRaw(payload, hash) => PreparedTransaction::Raw(payload, hash),
239            Self::Unlocked(request) => PreparedTransaction::Unlocked(request),
240            Self::Browser(request, signer) => PreparedTransaction::Browser(request, signer),
241            Self::OfflineOwners(..) => unreachable!("rejected by `prepare`"),
242        })
243    }
244
245    /// CREATE uses the protocol account nonce even when the signed nonce is a discriminator.
246    async fn validate_expiring_create_nonce(
247        &self,
248        provider: &RootProvider<N>,
249        planned: &TransactionWithMetadata<N>,
250    ) -> Result<()> {
251        if planned.tx().to().is_some() {
252            return Ok(());
253        }
254        let nonce_key = match self {
255            Self::Raw(tx, _)
256            | Self::Unlocked(tx)
257            | Self::Browser(tx, _)
258            | Self::AccessKey(tx, _)
259            | Self::ConfigurableAccount(tx, _)
260            | Self::OfflineOwners(tx, _) => tx.nonce_key(),
261            Self::Signed(tx) => {
262                <N::TransactionRequest as From<N::TxEnvelope>>::from(tx.clone()).nonce_key()
263            }
264            Self::PreparedRaw(payload, _) => <N::TransactionRequest as From<N::TxEnvelope>>::from(
265                N::TxEnvelope::decode_2718_exact(payload)?,
266            )
267            .nonce_key(),
268        };
269        if nonce_key == Some(TEMPO_EXPIRING_NONCE_KEY) {
270            let sender = planned.tx().from().context("CREATE is missing its planned sender")?;
271            let expected = match planned.tx() {
272                TransactionMaybeSigned::Signed { .. } => {
273                    planned.contract_address.context("CREATE is missing its planned address")?
274                }
275                TransactionMaybeSigned::Unsigned(tx) => sender
276                    .create(tx.nonce().context("CREATE is missing its planned account nonce")?),
277            };
278            let actual = sender.create(provider.get_transaction_count(sender).await?);
279            if actual != expected {
280                bail!(
281                    "CREATE address changed unexpectedly while sending transactions. Expected {expected} got {actual} from provider nonce."
282                );
283            }
284        }
285        Ok(())
286    }
287}
288
289/// A prepared submission, with local signatures fixed before checkpointing and sending.
290#[derive(Clone)]
291enum PreparedTransaction<'a, N: Network> {
292    Raw(Bytes, TxHash),
293    Unlocked(N::TransactionRequest),
294    Browser(N::TransactionRequest, &'a BrowserSigner<N>),
295}
296
297impl<N: Network> PreparedTransaction<'_, N>
298where
299    N::TransactionRequest: FoundryTransactionBuilder<N>,
300{
301    const fn delegated_request(&self) -> Option<&N::TransactionRequest> {
302        match self {
303            Self::Unlocked(request) | Self::Browser(request, _) => Some(request),
304            _ => None,
305        }
306    }
307
308    fn validate_delegated_submission(&self) -> Result<()> {
309        let Self::Browser(request, signer) = self else { return Ok(()) };
310        if request.from().is_some_and(|from| from != signer.address()) {
311            bail!("Transaction `from` address does not match connected wallet address");
312        }
313        if request.chain_id().is_some_and(|chain_id| chain_id != signer.chain_id()) {
314            bail!("Transaction `chainId` does not match connected wallet chain ID");
315        }
316        Ok(())
317    }
318
319    fn is_definite_non_submission(&self, error: &eyre::Report) -> bool {
320        match self {
321            Self::Browser(..) => is_definite_browser_non_submission(error),
322            Self::Unlocked(_) => is_definite_unlocked_non_submission(error),
323            _ => false,
324        }
325    }
326
327    async fn send(self, provider: Arc<RootProvider<N>>) -> Result<TxHash> {
328        match self {
329            Self::Raw(payload, _) => {
330                let pending = provider.send_raw_transaction(&payload).await?;
331                Ok(*pending.tx_hash())
332            }
333            Self::Unlocked(tx) => {
334                debug!("sending transaction from unlocked account {:?}", tx);
335                let pending = provider.send_transaction(tx).await?;
336                Ok(*pending.tx_hash())
337            }
338            Self::Browser(tx, signer) => {
339                debug!("sending transaction: {:?}", tx);
340                Ok(signer.send_transaction_via_browser(tx).await?)
341            }
342        }
343    }
344}
345
346fn is_definite_browser_non_submission(error: &eyre::Report) -> bool {
347    let Some(alloy_signer::Error::Other(error)) = error.downcast_ref::<alloy_signer::Error>()
348    else {
349        return false;
350    };
351    matches!(
352        error.downcast_ref::<BrowserWalletError>(),
353        Some(BrowserWalletError::Rejected { .. } | BrowserWalletError::NotConnected)
354    )
355}
356
357fn is_definite_unlocked_non_submission(error: &eyre::Report) -> bool {
358    matches!(
359        error.downcast_ref::<TransportError>(),
360        Some(RpcError::ErrorResp(error))
361            if is_unlocked_non_submission(error.code, &error.message)
362    )
363}
364
365fn is_unlocked_non_submission(code: i64, message: &str) -> bool {
366    code == -32602 && message == "No Signer available"
367}
368
369fn tempo_batch_calls(
370    sequence: &ScriptSequence<TempoNetwork>,
371    first_operation: usize,
372) -> Result<Vec<Call>> {
373    sequence
374        .transactions()
375        .skip(first_operation)
376        .enumerate()
377        .map(|(call_index, tx)| {
378            if tx.authorization_list().is_some_and(|list| !list.is_empty()) {
379                bail!(
380                    "--batch does not support EIP-7702 authorization lists \
381                     (found at transaction {}); use regular broadcast instead.",
382                    call_index + first_operation + 1
383                );
384            }
385            if let TransactionMaybeSigned::Unsigned(inner) = tx
386                && inner.blob_sidecar().is_some()
387            {
388                bail!(
389                    "--batch does not support blob (EIP-4844) transactions \
390                     (found at transaction {}); use regular broadcast instead.",
391                    call_index + first_operation + 1
392                );
393            }
394            let to = tx.to().map(TxKind::Call).ok_or_else(|| {
395                eyre::eyre!(
396                    "Unexpected raw CREATE in --batch mode at position {} — \
397                     this is a bug; CREATEs should have been rewritten by the inspector.",
398                    call_index + first_operation + 1
399                )
400            })?;
401            Ok(Call {
402                to,
403                value: tx.value().unwrap_or(U256::ZERO),
404                input: tx.input().cloned().unwrap_or_default(),
405            })
406        })
407        .collect()
408}
409
410fn validate_tempo_batch_request(
411    request: &TempoTransactionRequest,
412    sender: Address,
413    chain: u64,
414    calls: &[Call],
415) -> Result<()> {
416    if request.inner.from != Some(sender) {
417        bail!("batch request does not match its planned sender");
418    }
419    let expected = request
420        .clone()
421        .build_aa()
422        .map_err(|error| eyre::eyre!("invalid persisted batch request: {error}"))?;
423    if expected.chain_id != chain || expected.calls != calls {
424        bail!("batch request does not match its planned operations");
425    }
426    Ok(())
427}
428
429fn validate_tempo_batch_payload(
430    request: &TempoTransactionRequest,
431    payload: &[u8],
432    sender: Address,
433    chain: u64,
434    calls: &[Call],
435) -> Result<TxHash> {
436    validate_tempo_batch_request(request, sender, chain, calls)?;
437    let expected = request
438        .clone()
439        .build_aa()
440        .map_err(|error| eyre::eyre!("invalid persisted batch request: {error}"))?;
441    let envelope = TempoTxEnvelope::decode_2718_exact(payload)
442        .wrap_err("recovery plan contains an invalid signed batch payload")?;
443    validate_tempo_batch_envelope(&envelope, sender, chain, calls)?;
444    let TempoTxEnvelope::AA(signed) = &envelope else {
445        unreachable!();
446    };
447    if signed.tx() != &expected {
448        bail!("signed batch payload does not match its persisted request");
449    }
450    Ok(envelope.trie_hash())
451}
452
453fn validate_tempo_batch_envelope(
454    envelope: &TempoTxEnvelope,
455    sender: Address,
456    chain: u64,
457    calls: &[Call],
458) -> Result<()> {
459    let TempoTxEnvelope::AA(signed) = envelope else {
460        bail!("recovered batch transaction is not a Tempo transaction");
461    };
462    if signed.recover_signer().wrap_err("recovered batch transaction has an invalid signature")?
463        != sender
464    {
465        bail!("recovered batch transaction does not match its planned sender");
466    }
467    if signed.tx().chain_id != chain || signed.tx().calls != calls {
468        bail!("recovered batch transaction does not match its planned operations");
469    }
470    Ok(())
471}
472
473pub(crate) fn remaining_unsigned_transactions_for_recovery<N: Network>(
474    sequence: &ScriptSequenceKind<N>,
475) -> Vec<SignerScope>
476where
477    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
478{
479    sequence
480        .sequences()
481        .iter()
482        .enumerate()
483        .filter(|(sequence_index, _)| sequence.batch_attempt(*sequence_index).is_none())
484        .flat_map(|(sequence_index, deployment)| {
485            remaining_operation_indices(sequence, sequence_index).into_iter().filter_map(
486                move |index| {
487                    let tx = deployment.transactions[index].tx();
488                    // A transaction saved for its owners is signed by their approvals.
489                    (tx.is_unsigned()
490                        && sequence.signed_payload(sequence_index, index).is_none()
491                        && !deployment.awaiting_owners.iter().any(|entry| entry.index == index))
492                    .then(|| SignerScope {
493                        chain: deployment.chain,
494                        sender: tx.from().expect("missing from"),
495                    })
496                },
497            )
498        })
499        .collect()
500}
501
502/// Returns the operations of the sequence that are left to send or recover. From the first sequence
503/// with a recorded revert on, the script never reached operations that were not yet submitted, so
504/// only operations that were already submitted are left.
505pub(crate) fn remaining_operation_indices<N: Network>(
506    sequence: &ScriptSequenceKind<N>,
507    sequence_index: usize,
508) -> Vec<usize>
509where
510    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
511{
512    let after_revert = sequence.sequences()[..=sequence_index]
513        .iter()
514        .any(|deployment| !deployment.reverted.is_empty());
515    (0..sequence.sequences()[sequence_index].transactions.len())
516        .filter(|&index| {
517            !is_operation_completed(sequence, sequence_index, index)
518                && (!after_revert || is_operation_submitted(sequence, sequence_index, index))
519        })
520        .collect()
521}
522
523/// Returns the error for operations that resume must not send: the script stops at a failed call,
524/// so it never reached the operations without a submission in the first sequence with a recorded
525/// revert or in a later one.
526pub(crate) fn refused_after_revert<N: Network>(
527    sequence: &ScriptSequenceKind<N>,
528) -> Option<eyre::Report>
529where
530    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
531{
532    let reverted =
533        sequence.sequences().iter().position(|deployment| !deployment.reverted.is_empty())?;
534    let refused = (reverted..sequence.sequences().len()).any(|index| {
535        (0..sequence.sequences()[index].transactions.len()).any(|operation| {
536            !is_operation_completed(sequence, index, operation)
537                && !is_operation_submitted(sequence, index, operation)
538        })
539    });
540    refused.then(|| {
541        sequence.label_error(
542            reverted,
543            eyre::eyre!(
544                "transaction {} reverted, so the script would not have sent the operations after it; resume will not send them. Pass `--broadcast --start-fresh` to archive this broadcast and run the script again",
545                sequence.sequences()[reverted].reverted.iter().format(", ")
546            ),
547        )
548    })
549}
550
551/// Returns true if the operation has a receipt or a recorded revert for its own hash.
552fn is_operation_completed<N: Network>(
553    sequence: &ScriptSequenceKind<N>,
554    sequence_index: usize,
555    index: usize,
556) -> bool
557where
558    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
559{
560    let deployment = &sequence.sequences()[sequence_index];
561    let transaction = &deployment.transactions[index];
562    let hash = sequence
563        .signed_payload(sequence_index, index)
564        .map(|signed| signed.hash)
565        .or_else(|| match sequence.delegated_status(sequence_index, index) {
566            Some(DelegatedStatus::Pending { hash }) => Some(hash),
567            _ => None,
568        })
569        .or(transaction.hash)
570        .or_else(|| match transaction.tx() {
571            TransactionMaybeSigned::Signed { tx, .. } => Some(tx.trie_hash()),
572            TransactionMaybeSigned::Unsigned(_) => None,
573        });
574    hash.is_some_and(|hash| {
575        deployment.reverted.contains(&hash)
576            || deployment.receipts.iter().any(|receipt| receipt.transaction_hash() == hash)
577    })
578}
579
580/// Returns true if the operation was already submitted, or may have been: it has a recorded hash or
581/// a saved signed or delegated attempt.
582fn is_operation_submitted<N: Network>(
583    sequence: &ScriptSequenceKind<N>,
584    sequence_index: usize,
585    index: usize,
586) -> bool
587where
588    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
589{
590    sequence.sequences()[sequence_index].transactions[index].hash.is_some()
591        || sequence.signed_payload(sequence_index, index).is_some()
592        || sequence.delegated_status(sequence_index, index).is_some()
593}
594
595fn remaining_sender_addresses<N: Network>(sequence: &ScriptSequenceKind<N>) -> AddressHashSet
596where
597    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
598{
599    sequence
600        .sequences()
601        .iter()
602        .enumerate()
603        .flat_map(|(sequence_index, deployment)| {
604            remaining_operation_indices(sequence, sequence_index)
605                .into_iter()
606                .filter_map(|index| deployment.transactions[index].tx().from())
607        })
608        .collect()
609}
610
611/// Rejects preparing new transactions without the Tempo sponsor recorded when the deployment was
612/// created, so that resume never changes who pays.
613fn ensure_recorded_sponsor(recorded: Option<Address>, current: Option<Address>) -> Result<()> {
614    if let Some(recorded) = recorded
615        && current != Some(recorded)
616    {
617        eyre::bail!(
618            "this deployment is sponsored by {recorded}; pass `--tempo.sponsor {recorded}` with `--tempo.sponsor-signer` or `--tempo.sponsor-sig` to prepare its remaining transactions"
619        );
620    }
621    Ok(())
622}
623
624const fn should_broadcast_sequentially(
625    estimate_via_rpc: bool,
626    slow: bool,
627    required_signers: usize,
628    ordering_senders: usize,
629    batch_supported: bool,
630) -> bool {
631    estimate_via_rpc || slow || required_signers == 0 || ordering_senders != 1 || !batch_supported
632}
633
634/// Fees chosen once per sequence for its remaining unsigned operations.
635#[derive(Clone, Copy, Debug, PartialEq, Eq)]
636enum FeePlan {
637    /// Every remaining operation already has a signed payload, so no fees are set.
638    PreSigned,
639    /// Legacy transactions pay this gas price.
640    Legacy(u128),
641    /// EIP-1559 transactions pay these fees.
642    Eip1559(Eip1559Estimation),
643}
644
645impl FeePlan {
646    /// Sets the planned fees on an unsigned operation.
647    ///
648    /// # Panics
649    ///
650    /// Panics for `FeePlan::PreSigned`, which has no unsigned operation to price.
651    fn apply<N: Network>(self, tx: &mut N::TransactionRequest) {
652        match self {
653            Self::Legacy(gas_price) => tx.set_gas_price(gas_price),
654            Self::Eip1559(fees) => {
655                tx.set_max_priority_fee_per_gas(fees.max_priority_fee_per_gas);
656                tx.set_max_fee_per_gas(fees.max_fee_per_gas);
657            }
658            Self::PreSigned => unreachable!("pre-signed operations are not priced"),
659        }
660    }
661}
662
663/// Represents how to send _all_ transactions
664pub enum SendTransactionsKind<N: Network> {
665    /// Send via `eth_sendTransaction` and rely on the  `from` address being unlocked.
666    Unlocked(AddressHashSet),
667    /// Send a signed transaction via `eth_sendRawTransaction`, or via browser
668    Raw {
669        eth_wallets: AddressHashMap<EthereumWallet>,
670        browser: Option<BrowserSigner<N>>,
671        access_keys: HashMap<SignerScope, TempoAccountsWallet>,
672        configurable_accounts: HashMap<SignerScope, ConfigurableAccountSigner>,
673        offline_owners: HashMap<SignerScope, OfflineOwners>,
674    },
675}
676
677impl<N: Network> SendTransactionsKind<N> {
678    /// Returns the [`SendTransactionKind`] for the given address
679    ///
680    /// Returns an error if no matching signer is found or the address is not unlocked
681    pub fn for_sender(
682        &self,
683        chain: u64,
684        addr: &Address,
685        tx: N::TransactionRequest,
686    ) -> Result<SendTransactionKind<'_, N>> {
687        match self {
688            Self::Unlocked(unlocked) => {
689                if !unlocked.contains(addr) {
690                    bail!("Sender address {:?} is not unlocked", addr);
691                }
692                Ok(SendTransactionKind::Unlocked(tx))
693            }
694            Self::Raw {
695                eth_wallets,
696                browser,
697                access_keys,
698                configurable_accounts,
699                offline_owners,
700            } => {
701                let scope = SignerScope::new(chain, *addr);
702                if let Some(wallet) = access_keys.get(&scope) {
703                    Ok(SendTransactionKind::AccessKey(tx, Box::new(wallet.clone())))
704                } else if let Some(account) = configurable_accounts.get(&scope) {
705                    Ok(SendTransactionKind::ConfigurableAccount(tx, account))
706                } else if let Some(owners) = offline_owners.get(&scope) {
707                    Ok(SendTransactionKind::OfflineOwners(tx, owners))
708                } else if let Some(wallet) = eth_wallets.get(addr) {
709                    Ok(SendTransactionKind::Raw(tx, wallet))
710                } else if let Some(b) = browser
711                    && b.address() == *addr
712                {
713                    Ok(SendTransactionKind::Browser(tx, b))
714                } else {
715                    bail!("No matching signer for {:?} found", addr);
716                }
717            }
718        }
719    }
720}
721
722/// State after we have bundled all
723/// [`TransactionWithMetadata`] objects into a single [`ScriptSequenceKind`] object containing one
724/// or more script sequences.
725pub struct BundledState<FEN: FoundryEvmNetwork> {
726    pub args: ScriptArgs,
727    pub script_config: ScriptConfig<FEN>,
728    pub script_wallets: Wallets,
729    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
730    pub build_data: LinkedBuildData,
731    pub sequence: ScriptSequenceKind<FEN::Network>,
732    /// Error from the script run that `--resume` performed to collect missing signers.
733    pub resume_script_error: Option<String>,
734}
735
736impl<FEN: FoundryEvmNetwork> BundledState<FEN> {
737    pub async fn wait_for_pending(mut self) -> Result<Self> {
738        let progress = ScriptProgress::default();
739        let progress_ref = &progress;
740        let config = &self.script_config.config;
741        let submission_hashes = (0..self.sequence.sequences().len())
742            .map(|sequence| {
743                (
744                    self.sequence.submission_hashes(sequence),
745                    blocked_pending(self.sequence.sequences(), sequence),
746                )
747            })
748            .collect::<Vec<_>>();
749        let rpc_urls = (0..self.sequence.sequences().len())
750            .map(|sequence| self.sequence.rpc_url(sequence).to_owned())
751            .collect::<Vec<_>>();
752        let rpc_urls = &rpc_urls;
753        let futs = self
754            .sequence
755            .sequences_mut()
756            .iter_mut()
757            .zip(submission_hashes)
758            .enumerate()
759            .map(|(sequence_idx, (sequence, ((durable_hashes, replayable_hashes), blocked)))| async move {
760                let rpc_url = &rpc_urls[sequence_idx];
761                let provider =
762                    Arc::new(ProviderBuilder::from_config_with_url(config, rpc_url)?.build()?);
763                progress_ref
764                    .wait_for_pending(
765                        sequence_idx,
766                        sequence,
767                        &provider,
768                        self.script_config.config.transaction_timeout,
769                        self.args.confirmations,
770                        (&durable_hashes, &replayable_hashes),
771                        &blocked,
772                    )
773                    .await
774            })
775            .collect::<Vec<_>>();
776
777        let errors = join_all(futs)
778            .await
779            .into_iter()
780            .enumerate()
781            .filter_map(|(sequence_idx, result)| {
782                result.err().map(|err| self.sequence.label_error(sequence_idx, err))
783            })
784            .collect::<Vec<_>>();
785
786        self.sequence.save(true, false)?;
787
788        if !errors.is_empty() {
789            return Err(eyre::eyre!("{}", errors.iter().format("\n")));
790        }
791
792        Ok(self)
793    }
794
795    /// Broadcasts transactions from all sequences.
796    pub async fn broadcast(mut self) -> Result<BroadcastedState<FEN>> {
797        if self.script_config.tempo.expiring_nonce {
798            reject_expiring_call_before_create(self.sequence.sequences())?;
799        }
800        // Transactions saved for their owners are signed with their approvals before anything is
801        // sent, and are sent in order below.
802        owner_approvals::assemble(
803            &mut self.sequence,
804            &self.args.tempo_owner_signatures,
805            &self.script_config.config,
806        )
807        .await?;
808        // Only operations without a saved or delegated attempt are sponsored again.
809        let needs_sponsorship =
810            self.sequence.sequences().iter().enumerate().any(|(sequence_index, deployment)| {
811                remaining_operation_indices(&self.sequence, sequence_index).into_iter().any(
812                    |index| {
813                        deployment.transactions[index].tx().is_unsigned()
814                            && self.sequence.signed_payload(sequence_index, index).is_none()
815                            && self.sequence.delegated_status(sequence_index, index).is_none()
816                    },
817                )
818            });
819        if needs_sponsorship {
820            ensure_recorded_sponsor(self.sequence.sponsor(), self.script_config.tempo.sponsor)?;
821        }
822        let remaining_transactions = remaining_unsigned_transactions_for_recovery(&self.sequence);
823        let ordering_addresses = remaining_sender_addresses(&self.sequence);
824        let has_unprepared_transactions =
825            self.sequence.sequences().iter().enumerate().any(|(sequence_index, _)| {
826                remaining_operation_indices(&self.sequence, sequence_index)
827                    .into_iter()
828                    .any(|index| self.sequence.signed_payload(sequence_index, index).is_none())
829            });
830        let required_addresses =
831            remaining_transactions.iter().map(|tx| tx.sender).collect::<AddressHashSet>();
832
833        if required_addresses.contains(&Config::DEFAULT_SENDER) {
834            eyre::bail!(
835                "You seem to be using Foundry's default sender. Be sure to set your own --sender."
836            );
837        }
838
839        let send_kind = if required_addresses.is_empty() {
840            SendTransactionsKind::Raw {
841                eth_wallets: AddressHashMap::default(),
842                browser: None,
843                access_keys: HashMap::default(),
844                configurable_accounts: HashMap::default(),
845                offline_owners: HashMap::default(),
846            }
847        } else if self.args.unlocked {
848            SendTransactionsKind::Unlocked(required_addresses.clone())
849        } else {
850            let expected_session_sender = script_session_expected_sender_if_configured(
851                &self.script_config.tempo,
852                &required_addresses,
853            )?;
854
855            // For addresses without an explicit signer, try the Tempo Accounts store.
856            let mut access_keys: HashMap<SignerScope, TempoAccountsWallet> = HashMap::default();
857            if let Some(expected_session_sender) = expected_session_sender
858                && let Some(session) =
859                    self.script_config.tempo.session_signer_for_multi_wallet_any_chain(
860                        &self.args.wallets,
861                        Some(expected_session_sender),
862                    )?
863            {
864                insert_session_access_key_for_remaining_transactions(
865                    &mut access_keys,
866                    session,
867                    &remaining_transactions,
868                )?;
869            }
870
871            let signers: Vec<Address> = self
872                .script_wallets
873                .signers()
874                .map_err(|e| eyre::eyre!("{e}"))?
875                .into_iter()
876                .chain(self.browser_wallet.as_ref().map(|b| b.address()))
877                .collect();
878
879            let accounts_wallet = self
880                .script_config
881                .evm_opts
882                .networks
883                .is_tempo()
884                .then(TempoAccountsWallet::try_from_default_store)
885                .transpose()?
886                .flatten();
887
888            let mut missing_scopes = Vec::new();
889            for tx in &remaining_transactions {
890                let scope = *tx;
891                if !signers.contains(&tx.sender) && !access_keys.contains_key(&scope) {
892                    if let Some(wallet) = accounts_wallet.as_ref()
893                        && wallet.has_account(tx.sender)?
894                    {
895                        access_keys.insert(scope, wallet.clone().with_chain_id(tx.chain));
896                    } else {
897                        missing_scopes.push(scope);
898                    }
899                }
900            }
901            missing_scopes.sort_unstable_by_key(|scope| (scope.chain, scope.sender));
902            missing_scopes.dedup();
903
904            // A sender without its own signer may be a configurable account whose owners are
905            // among the wallets: they sign its transactions together. A sender with its own key
906            // may be an upgraded EOA, whose root key no longer signs once it has owners.
907            let wallet_signers = self
908                .script_wallets
909                .into_multi_wallet()
910                .into_signers()?
911                .into_values()
912                .map(Arc::new)
913                .collect::<Vec<_>>();
914            let mut configurable_accounts = HashMap::default();
915            let mut offline_owners = HashMap::default();
916            if self.script_config.evm_opts.networks.is_tempo() {
917                let tempo = &self.script_config.tempo;
918                // `--tempo.configurable-account` and `--tempo.config` describe one account: a
919                // sender with its own key that is not that account is only checked against the
920                // chain, and signs with the owners among the wallets and `--tempo.owner`.
921                let own_key_tempo = TempoOpts {
922                    configurable_account: None,
923                    configurable_account_config: None,
924                    ..tempo.clone()
925                };
926                let mut own_key_scopes = remaining_transactions
927                    .iter()
928                    .copied()
929                    .filter(|scope| {
930                        signers.contains(&scope.sender) && !access_keys.contains_key(scope)
931                    })
932                    .collect::<Vec<_>>();
933                own_key_scopes.sort_unstable_by_key(|scope| (scope.chain, scope.sender));
934                own_key_scopes.dedup();
935                let candidates = std::mem::take(&mut missing_scopes)
936                    .into_iter()
937                    .map(|scope| (scope, true))
938                    .chain(own_key_scopes.into_iter().map(|scope| (scope, false)));
939                for (scope, missing) in candidates {
940                    let rpc_url = (0..self.sequence.sequences().len())
941                        .find(|&i| self.sequence.sequences()[i].chain == scope.chain)
942                        .map(|i| self.sequence.rpc_url(i).to_owned());
943                    let account = match rpc_url {
944                        Some(rpc_url)
945                            if tempo.configurable_account.is_none_or(|a| a == scope.sender) =>
946                        {
947                            let provider = ProviderBuilder::<TempoNetwork>::from_config_with_url(
948                                &self.script_config.config,
949                                &rpc_url,
950                            )?
951                            .build()?;
952                            let explicit =
953                                missing || tempo.configurable_account == Some(scope.sender);
954                            // A sender with its own key signs with it unless the chain says it
955                            // is a configurable account, such as an upgraded EOA.
956                            let own_key_is_account = !explicit
957                                && detect_configurable_account(
958                                    &provider,
959                                    scope.sender,
960                                    &signers,
961                                    None,
962                                    false,
963                                    BlockId::latest(),
964                                )
965                                .await?
966                                .is_some();
967                            if explicit || own_key_is_account {
968                                let tempo = if explicit { tempo } else { &own_key_tempo };
969                                tempo
970                                    .configurable_account_owners(
971                                        &provider,
972                                        Some(scope.sender),
973                                        None,
974                                        &wallet_signers,
975                                        BlockId::latest(),
976                                    )
977                                    .await?
978                            } else {
979                                None
980                            }
981                        }
982                        _ => None,
983                    };
984                    // Owners that are not local approve the account's transactions elsewhere.
985                    match account {
986                        Some((account, config, keys)) => {
987                            let local = keys.iter().map(|key| key.address()).collect::<Vec<_>>();
988                            if reaches_threshold(&config, &local) {
989                                configurable_accounts.insert(
990                                    scope,
991                                    ConfigurableAccountSigner::new(account, config, keys, "")?,
992                                );
993                            } else {
994                                offline_owners
995                                    .insert(scope, OfflineOwners { account, config, keys });
996                            }
997                        }
998                        None if missing => missing_scopes.push(scope),
999                        None => {}
1000                    }
1001                }
1002            }
1003
1004            let mut missing_addresses =
1005                missing_scopes.iter().map(|scope| scope.sender).collect::<Vec<_>>();
1006            missing_addresses.sort_unstable();
1007            missing_addresses.dedup();
1008
1009            if !missing_addresses.is_empty() {
1010                let mut message = format!(
1011                    "No associated wallet for addresses: {missing_addresses:?}. Unlocked wallets: {signers:?}"
1012                );
1013                if let Some(error) = &self.resume_script_error {
1014                    message = format!("{message}\n{}", resume_script_failure(error));
1015                }
1016                eyre::bail!(message);
1017            }
1018
1019            // An owner key that a configurable account holds cannot also send on its own.
1020            let mut eth_wallets = AddressHashMap::<EthereumWallet>::default();
1021            for signer in wallet_signers {
1022                let address = signer.address();
1023                match Arc::into_inner(signer) {
1024                    Some(signer) => {
1025                        eth_wallets.insert(address, signer.into());
1026                    }
1027                    None if required_addresses.contains(&address) => eyre::bail!(
1028                        "{address} signs both as a sender and as an owner of a Tempo \
1029                         configurable account in this script, which is not supported; broadcast \
1030                         them in separate scripts"
1031                    ),
1032                    None => {}
1033                }
1034            }
1035
1036            // Checked before any chain is sent to, with the nonce key that each transaction is
1037            // sent with: the one of the Tempo options, or else the planned one.
1038            let tempo = &self.script_config.tempo;
1039            let offline_nonce_keys = self
1040                .sequence
1041                .sequences()
1042                .iter()
1043                .enumerate()
1044                .flat_map(|(i, sequence)| {
1045                    remaining_operation_indices(&self.sequence, i).into_iter().filter_map(|index| {
1046                        match sequence.transactions[index].tx() {
1047                            TransactionMaybeSigned::Unsigned(tx)
1048                                if tx.from().is_some_and(|from| {
1049                                    offline_owners
1050                                        .contains_key(&SignerScope::new(sequence.chain, from))
1051                                }) =>
1052                            {
1053                                Some(tempo.nonce_key.or(tx.nonce_key()).unwrap_or_default())
1054                            }
1055                            _ => None,
1056                        }
1057                    })
1058                })
1059                .collect::<Vec<_>>();
1060            let expiring_nonce =
1061                tempo.expiring_nonce || offline_nonce_keys.contains(&TEMPO_EXPIRING_NONCE_KEY);
1062            if !offline_owners.is_empty() && (tempo.sponsor.is_some() || expiring_nonce) {
1063                bail!(
1064                    "the owners of a Tempo configurable account sender approve its transactions \
1065                     on other machines, so they cannot be sponsored with --tempo.sponsor or use \
1066                     the expiring nonce key (--tempo.expiring-nonce, --tempo.expires or \
1067                     --tempo.nonce-key {TEMPO_EXPIRING_NONCE_KEY:#x}), whose validity window is too \
1068                     short for them"
1069                );
1070            }
1071            // Their nonces are fixed and checked against the account's protocol nonce.
1072            if let Some(key) = offline_nonce_keys.iter().find(|key| !key.is_zero()) {
1073                bail!(
1074                    "the owners of a Tempo configurable account sender approve its transactions \
1075                     on other machines, so its transactions use the protocol nonce, not \
1076                     --tempo.nonce-key {key:#x}"
1077                );
1078            }
1079
1080            SendTransactionsKind::Raw {
1081                eth_wallets,
1082                browser: self.browser_wallet,
1083                access_keys,
1084                configurable_accounts,
1085                offline_owners,
1086            }
1087        };
1088        if let Some(error) = &self.resume_script_error {
1089            sh_warn!("{}", resume_script_failure(error))?;
1090        }
1091
1092        let tempo_sponsor = if has_unprepared_transactions {
1093            self.script_config.tempo.sponsor_config().await?.map(Arc::new)
1094        } else {
1095            None
1096        };
1097        if tempo_sponsor.is_some()
1098            && self.script_config.tempo.sponsor_sig.is_some()
1099            && remaining_transactions.len() > 1
1100        {
1101            eyre::bail!(
1102                "--tempo.sponsor-sig can only sponsor one remaining script transaction; use --tempo.sponsor-signer for multi-transaction scripts"
1103            );
1104        }
1105
1106        let progress = ScriptProgress::default();
1107
1108        for i in 0..self.sequence.sequences().len() {
1109            // In multichain runs, errors from a sequence are prefixed with its chain.
1110            let broadcast_sequence = async {
1111                let sequence_offset = operation_ordinal(self.sequence.sequences(), i, 0);
1112                let remaining_indices = remaining_operation_indices(&self.sequence, i);
1113                // A transaction signed with its owners' approvals is recorded as a submission
1114                // attempt only when it is sent, in order.
1115                let signed_payloads = (0..self.sequence.sequences()[i].transactions.len())
1116                    .map(|index| match self.sequence.signed_payload(i, index) {
1117                        Some(signed) => Ok(Some((signed.payload.clone(), signed.hash))),
1118                        None if remaining_indices.contains(&index) => {
1119                            owner_approvals::approved_payload(&self.sequence.sequences()[i], index)
1120                        }
1121                        None => Ok(None),
1122                    })
1123                    .collect::<Result<Vec<_>>>()?;
1124                let rpc_url = self.sequence.rpc_url(i).to_owned();
1125                let mut sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
1126
1127                let provider = Arc::new(
1128                    ProviderBuilder::from_config_with_url(&self.script_config.config, &rpc_url)?
1129                        .build()?,
1130                );
1131                let unlocked_submission_provider = Arc::new(
1132                    ProviderBuilder::from_config_with_url(&self.script_config.config, &rpc_url)?
1133                        .max_retry(0)
1134                        .build()?,
1135                );
1136
1137                let seq_progress = progress.get_sequence_progress(i, sequence);
1138
1139                if !remaining_indices.is_empty() {
1140                    let is_legacy = Chain::from(sequence.chain).is_legacy() || self.args.legacy;
1141                    // Make a one-time gas price estimation
1142                    let all_signed =
1143                        remaining_indices.iter().all(|index| signed_payloads[*index].is_some());
1144                    let fee_plan = match (
1145                        all_signed,
1146                        is_legacy,
1147                        self.args.with_gas_price,
1148                        self.args.priority_gas_price,
1149                    ) {
1150                        (true, _, _, _) => FeePlan::PreSigned,
1151                        (false, true, Some(gas_price), _) => FeePlan::Legacy(gas_price.to()),
1152                        (false, true, None, _) => FeePlan::Legacy(provider.get_gas_price().await?),
1153                        (false, false, Some(max_fee_per_gas), Some(max_priority_fee_per_gas)) => {
1154                            let max_fee: u128 = max_fee_per_gas.to();
1155                            let max_priority: u128 = max_priority_fee_per_gas.to();
1156                            if max_priority > max_fee {
1157                                eyre::bail!(
1158                                    "--priority-gas-price ({max_priority}) cannot be higher than --with-gas-price ({max_fee})"
1159                                );
1160                            }
1161                            FeePlan::Eip1559(Eip1559Estimation {
1162                                max_fee_per_gas: max_fee,
1163                                max_priority_fee_per_gas: max_priority,
1164                            })
1165                        }
1166                        (false, false, _, _) => {
1167                            let fees = estimate_eip1559_fees(
1168                                &provider,
1169                                self.script_config.config.eip1559_fee_estimate,
1170                            )
1171                            .await
1172                            .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
1173
1174                            // Browser wallets may suggest their own tip; query it best-effort.
1175                            let browser_suggested_tip = if matches!(
1176                                &send_kind,
1177                                SendTransactionsKind::Raw { browser: Some(_), .. }
1178                            ) {
1179                                provider.get_max_priority_fee_per_gas().await.ok()
1180                            } else {
1181                                None
1182                            };
1183
1184                            let fees = resolve_broadcast_eip1559_fees(
1185                                fees,
1186                                self.args.with_gas_price.map(|p| p.to()),
1187                                self.args.priority_gas_price.map(|p| p.to()),
1188                                browser_suggested_tip,
1189                            )?;
1190
1191                            FeePlan::Eip1559(fees.estimation())
1192                        }
1193                    };
1194
1195                    // TIP-1106: from T12 the nonce of an expiring nonce transaction is an opaque
1196                    // discriminator. Each transaction gets its ordinal in the complete script plan,
1197                    // which is monotonic and stable across `--resume`, so that
1198                    // otherwise identical transactions keep distinct signing and replay
1199                    // hashes. Earlier hardforks only accept 0, which is also the
1200                    // fallback when the hardfork cannot be determined.
1201                    let tempo_hardfork = if self.script_config.evm_opts.networks.is_tempo() {
1202                        active_tempo_hardfork(provider.as_ref()).await.ok()
1203                    } else {
1204                        None
1205                    };
1206                    let expiring_nonce_discriminators = self.script_config.tempo.expiring_nonce
1207                        && tempo_hardfork.is_some_and(|fork| fork >= TempoHardfork::T12);
1208
1209                    // Iterate through transactions, matching the `from` field with the associated
1210                    // wallet. Then send the transaction. Panics if we find a unknown `from`
1211                    let sequence_chain = sequence.chain;
1212                    let mut transactions = Vec::with_capacity(remaining_indices.len());
1213                    for index in remaining_indices {
1214                        let tx_with_metadata = &sequence.transactions[index];
1215                        let is_fixed_gas_limit = tx_with_metadata.is_fixed_gas_limit;
1216
1217                        let kind = match (&signed_payloads[index], tx_with_metadata.tx().clone()) {
1218                            (Some((payload, hash)), _) => {
1219                                SendTransactionKind::PreparedRaw(payload.clone(), *hash)
1220                            }
1221                            (None, TransactionMaybeSigned::Signed { tx, .. }) => {
1222                                if tempo_sponsor.is_some() {
1223                                    eyre::bail!(
1224                                        "cannot attach Tempo sponsor signature to an already signed script transaction"
1225                                    );
1226                                }
1227                                SendTransactionKind::Signed(tx)
1228                            }
1229                            (None, TransactionMaybeSigned::Unsigned(mut tx)) => {
1230                                let from = tx.from().expect("No sender for onchain transaction!");
1231
1232                                tx.set_chain_id(sequence_chain);
1233
1234                                // Set TxKind::Create explicitly to satisfy `check_reqd_fields` in
1235                                // alloy
1236                                if tx.kind().is_none() {
1237                                    tx.set_create();
1238                                }
1239
1240                                fee_plan.apply::<FEN::Network>(&mut tx);
1241
1242                                // `vm.attachBlob` transactions also need a blob fee.
1243                                if tx.blob_sidecar().is_some()
1244                                    && tx.max_fee_per_blob_gas().is_none()
1245                                {
1246                                    tx.set_max_fee_per_blob_gas(
1247                                        provider.get_blob_base_fee().await?,
1248                                    );
1249                                }
1250
1251                                self.script_config.tempo.apply::<FEN::Network>(
1252                                    &mut tx,
1253                                    expiring_nonce_discriminators
1254                                        .then_some((sequence_offset + index) as u64),
1255                                );
1256
1257                                send_kind.for_sender(sequence_chain, &from, tx)?
1258                            }
1259                        };
1260                        transactions.push((kind, is_fixed_gas_limit, index));
1261                    }
1262                    // The transactions saved for owners on other machines are checked and their
1263                    // gas limits fixed before anything is sent, and nothing is sent from the
1264                    // first of them.
1265                    let awaiting_owners = owner_approvals::prepare(
1266                        &self.sequence,
1267                        i,
1268                        &provider,
1269                        &transactions,
1270                        self.args.gas_estimate_multiplier,
1271                    )
1272                    .await?;
1273                    sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
1274                    let offline = transactions
1275                        .iter()
1276                        .position(|(kind, ..)| {
1277                            matches!(kind, SendTransactionKind::OfflineOwners(..))
1278                        })
1279                        .unwrap_or(transactions.len());
1280                    let transactions = &transactions[..offline];
1281
1282                    let estimate_via_rpc = has_different_gas_calc(sequence.chain)
1283                        || self.script_config.evm_opts.networks.is_tempo()
1284                        || self.args.skip_simulation;
1285
1286                    // We only wait for a transaction receipt before sending the next transaction,
1287                    // if there is more than one signer. There would be no way of assuring their
1288                    // order otherwise.
1289                    // Or if the chain does not support batched transactions (eg. Arbitrum).
1290                    // Or if we need to invoke eth_estimateGas before sending transactions.
1291                    let sequential_broadcast = should_broadcast_sequentially(
1292                        estimate_via_rpc,
1293                        self.args.slow,
1294                        required_addresses.len(),
1295                        ordering_addresses.len(),
1296                        has_batch_support(sequence.chain),
1297                    ) || transactions.iter().any(|(kind, _, _)| {
1298                        matches!(
1299                            kind,
1300                            SendTransactionKind::Browser(..) | SendTransactionKind::Unlocked(..)
1301                        )
1302                    });
1303
1304                    // We send transactions and wait for receipts in batches of 100, since some
1305                    // networks cannot handle more than that.
1306                    let batch_size = if sequential_broadcast { 1 } else { 100 };
1307
1308                    for (batch_number, batch) in transactions.chunks(batch_size).enumerate() {
1309                        seq_progress.inner.write().set_status(&format!(
1310                            "Sending transactions [{} - {}]",
1311                            batch_number * batch_size,
1312                            batch_number * batch_size + std::cmp::min(batch_size, batch.len()) - 1
1313                        ));
1314
1315                        let mut prepared = Vec::with_capacity(batch.len());
1316                        for (kind, is_fixed_gas_limit, index) in batch {
1317                            // A pending operation can be confirmed while waiting on an earlier
1318                            // batch.
1319                            if is_operation_completed(&self.sequence, i, *index) {
1320                                continue;
1321                            }
1322                            kind.validate_expiring_create_nonce(
1323                                &provider,
1324                                &self.sequence.sequences()[i].transactions[*index],
1325                            )
1326                            .await?;
1327                            let mut kind = kind
1328                                .clone()
1329                                .prepare_for_durable_send(
1330                                    &provider,
1331                                    sequential_broadcast,
1332                                    *is_fixed_gas_limit,
1333                                    estimate_via_rpc,
1334                                    self.args.gas_estimate_multiplier,
1335                                    tempo_sponsor.as_deref(),
1336                                )
1337                                .await?;
1338                            if let PreparedTransaction::Raw(payload, hash) = &mut kind {
1339                                *hash = self.sequence.persist_signed_payload(
1340                                    i,
1341                                    *index,
1342                                    payload.clone(),
1343                                    tempo_hardfork.is_none_or(|fork| fork >= TempoHardfork::T1B),
1344                                )?;
1345                            }
1346                            prepared.push((kind, *index));
1347                        }
1348
1349                        let mut buffer = FuturesUnordered::new();
1350                        for (kind, index) in prepared {
1351                            if let Some(request) = kind.delegated_request() {
1352                                kind.validate_delegated_submission()?;
1353                                self.sequence.persist_delegated_request(
1354                                    i,
1355                                    index,
1356                                    request.clone(),
1357                                )?;
1358                            }
1359                            let provider = if matches!(kind, PreparedTransaction::Unlocked(_)) {
1360                                unlocked_submission_provider.clone()
1361                            } else {
1362                                provider.clone()
1363                            };
1364                            let mut pending = async move {
1365                                let res = kind.clone().send(provider).await;
1366                                (res, kind, 0, None, index)
1367                            }
1368                            .boxed();
1369                            if let Some(result) = pending.as_mut().now_or_never() {
1370                                buffer.push(futures::future::ready(result).boxed());
1371                            } else {
1372                                buffer.push(pending);
1373                            }
1374                        }
1375
1376                        'send: while let Some((mut res, kind, attempt, original_res, index)) =
1377                            buffer.next().await
1378                        {
1379                            if res.is_err()
1380                                && let PreparedTransaction::Raw(_, hash) = kind
1381                                && provider
1382                                    .get_transaction_by_hash(hash)
1383                                    .await
1384                                    .is_ok_and(|transaction| transaction.is_some())
1385                            {
1386                                res = Ok(hash);
1387                            }
1388                            if kind.delegated_request().is_some()
1389                                && let Err(error) = res
1390                            {
1391                                if kind.is_definite_non_submission(&error) {
1392                                    self.sequence.clear_delegated_request(i, index)?;
1393                                    return Err(error);
1394                                }
1395                                self.sequence.persist_delegated_status(
1396                                    i,
1397                                    index,
1398                                    DelegatedStatus::OutcomeUnknown,
1399                                )?;
1400                                bail!(
1401                                    "submission outcome for delegated operation {index} is unknown; refusing to risk a duplicate transaction"
1402                                );
1403                            }
1404                            if res.is_err() && attempt <= 3 {
1405                                // Try to resubmit the transaction
1406                                let provider = provider.clone();
1407                                let progress = seq_progress.inner.clone();
1408                                buffer.push(Box::pin(async move {
1409                                    debug!(err=?res, ?attempt, "retrying transaction ");
1410                                    let attempt = attempt + 1;
1411                                    progress.write().set_status(&format!(
1412                                        "retrying transaction {res:?} (attempt {attempt})"
1413                                    ));
1414                                    tokio::time::sleep(Duration::from_millis(1000 * attempt)).await;
1415                                    let r = kind.clone().send(provider).await;
1416                                    (r, kind, attempt, original_res.or(Some(res)), index)
1417                                }));
1418
1419                                continue 'send;
1420                            }
1421
1422                            // Preserve the original error if any
1423                            let tx_hash = res.wrap_err_with(|| {
1424                                    if let Some(original_res) = original_res {
1425                                        format!(
1426                                            "Failed to send transaction after {attempt} attempts {original_res:?}"
1427                                        )
1428                                    } else {
1429                                        "Failed to send transaction".to_string()
1430                                    }
1431                                })?;
1432                            if let PreparedTransaction::Raw(_, expected) = kind
1433                                && expected != tx_hash
1434                            {
1435                                bail!("RPC returned hash {tx_hash} for signed payload {expected}");
1436                            }
1437                            if kind.delegated_request().is_some() {
1438                                self.sequence.persist_delegated_status(
1439                                    i,
1440                                    index,
1441                                    DelegatedStatus::Pending { hash: tx_hash },
1442                                )?;
1443                            }
1444                            sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
1445                            sequence.add_pending(index, tx_hash);
1446
1447                            // Checkpoint save
1448                            self.sequence.save(true, false)?;
1449
1450                            seq_progress.inner.write().tx_sent(tx_hash);
1451                        }
1452
1453                        // Checkpoint save
1454                        self.sequence.save(true, false)?;
1455                        let (durable_hashes, replayable_hashes) =
1456                            self.sequence.submission_hashes(i);
1457                        let blocked = blocked_pending(self.sequence.sequences(), i);
1458                        sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
1459
1460                        let result = progress
1461                            .wait_for_pending(
1462                                i,
1463                                sequence,
1464                                &provider,
1465                                self.script_config.config.transaction_timeout,
1466                                self.args.confirmations,
1467                                (&durable_hashes, &replayable_hashes),
1468                                &blocked,
1469                            )
1470                            .await;
1471                        // Checkpoint save, including reverts recorded before a failure.
1472                        self.sequence.save(true, false)?;
1473                        result?;
1474                        self.sequence.ensure_delegated_outcomes_known(i)?;
1475                        sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
1476                    }
1477
1478                    if !awaiting_owners.is_empty() {
1479                        seq_progress.inner.write().set_status("Awaiting owner approvals");
1480                        seq_progress.inner.write().finish();
1481                        owner_approvals::export(&mut self.sequence, i, &provider, awaiting_owners)
1482                            .await?;
1483                        return Ok(true);
1484                    }
1485                }
1486
1487                let (total_gas, avg_gas_price, total_paid) = fee_totals(
1488                    sequence.receipts.iter().map(|r| (r.gas_used(), r.effective_gas_price())),
1489                );
1490                let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
1491                let avg_gas_price = avg_gas_price
1492                    .and_then(|avg| format_units(avg, 9).ok())
1493                    .unwrap_or_else(|| "N/A".to_string());
1494
1495                let token_symbol = NamedChain::try_from(sequence.chain)
1496                    .unwrap_or_default()
1497                    .native_currency_symbol()
1498                    .unwrap_or("ETH");
1499                // Reverted transactions have no stored receipt, so their fees are not included.
1500                let excluded = match sequence.reverted.len() {
1501                    0 => String::new(),
1502                    1 => ", excluding 1 reverted transaction".to_string(),
1503                    n => format!(", excluding {n} reverted transactions"),
1504                };
1505                seq_progress.inner.write().set_status(&format!(
1506                    "Total Paid: {} {} ({} gas * avg {} gwei{excluded})\n",
1507                    paid.trim_end_matches('0'),
1508                    token_symbol,
1509                    total_gas,
1510                    avg_gas_price.trim_end_matches('0').trim_end_matches('.')
1511                ));
1512                seq_progress.inner.write().finish();
1513                Ok::<_, eyre::Report>(false)
1514            };
1515            // Later operations wait for the transactions saved for their owners.
1516            if broadcast_sequence.await.map_err(|err| self.sequence.label_error(i, err))? {
1517                return Ok(BroadcastedState {
1518                    args: self.args,
1519                    script_config: self.script_config,
1520                    build_data: self.build_data,
1521                    sequence: self.sequence,
1522                });
1523            }
1524        }
1525
1526        // Submitted operations can lack a receipt when the endpoint stopped returning them.
1527        let unresolved = self
1528            .sequence
1529            .sequences()
1530            .iter()
1531            .enumerate()
1532            .filter_map(|(i, deployment)| {
1533                let hashes = remaining_operation_indices(&self.sequence, i)
1534                    .into_iter()
1535                    .filter_map(|index| deployment.transactions[index].hash)
1536                    .collect::<Vec<_>>();
1537                (!hashes.is_empty())
1538                    .then(|| format!("chain {}: {}", deployment.chain, hashes.iter().format(", ")))
1539            })
1540            .collect::<Vec<_>>();
1541        // Saved attempts after a recorded revert are recovered above, but the new work is refused
1542        // once they are resolved. Until then, the warning below points to `--resume`.
1543        if unresolved.is_empty()
1544            && let Some(err) = refused_after_revert(&self.sequence)
1545        {
1546            return Err(err);
1547        }
1548        if !shell::is_json() {
1549            sh_println!("\n\n==========================")?;
1550        }
1551        // Resume skips recorded reverts, so completing the remaining work is not a success.
1552        let reverted = self
1553            .sequence
1554            .sequences()
1555            .iter()
1556            .filter(|deployment| !deployment.reverted.is_empty())
1557            .map(|deployment| {
1558                format!("chain {}: {}", deployment.chain, deployment.reverted.iter().format(", "))
1559            })
1560            .collect::<Vec<_>>();
1561        if !unresolved.is_empty() {
1562            sh_warn!(
1563                "ONCHAIN EXECUTION INCOMPLETE: submitted transactions have no receipt:\n{}\nAdd `--resume` to your command to check them again and replay dropped signed transactions.",
1564                unresolved.join("\n")
1565            )?;
1566        } else if !reverted.is_empty() {
1567            sh_warn!(
1568                "ONCHAIN EXECUTION COMPLETE WITH REVERTED TRANSACTIONS:\n{}",
1569                reverted.join("\n")
1570            )?;
1571        } else if !shell::is_json() {
1572            sh_println!("\nONCHAIN EXECUTION COMPLETE & SUCCESSFUL.")?;
1573        }
1574
1575        Ok(BroadcastedState {
1576            args: self.args,
1577            script_config: self.script_config,
1578            build_data: self.build_data,
1579            sequence: self.sequence,
1580        })
1581    }
1582
1583    pub async fn verify_preflight_check(&self) -> Result<()> {
1584        if self.args.verify_external && self.script_config.config.offline {
1585            bail!("External contract verification is unavailable in offline mode");
1586        }
1587
1588        for sequence in self.sequence.sequences() {
1589            let chain: Chain = sequence.chain.into();
1590            // Resolve the API key: CLI arg first, then per-chain config, then global fallback.
1591            let etherscan_key = self
1592                .script_config
1593                .config
1594                .get_etherscan_api_key(Some(chain))
1595                .or_else(|| self.script_config.config.etherscan_api_key.clone());
1596            let api_key =
1597                self.args.verifier.resolve_api_key(etherscan_key.as_deref()).map(str::to_owned);
1598            let has_url = self.args.verifier.verifier_url.is_some();
1599            let is_explicit = self.args.verifier.is_explicitly_set();
1600            // Presence check: use the fully-resolved provider type so that implicit Etherscan
1601            // selection (key from env/config, no explicit --verifier flag) is validated too.
1602            self.args
1603                .verifier
1604                .resolve(api_key.as_deref(), Some(chain))
1605                .client(api_key.as_deref(), Some(chain), has_url, is_explicit)
1606                .wrap_err_with(|| {
1607                    format!("Verification preflight check failed for chain {}", sequence.chain)
1608                })?;
1609            // Connectivity check: validates credentials are actually accepted by the verifier.
1610            self.args
1611                .verifier
1612                .check_credentials(api_key.as_deref(), chain, &self.script_config.config)
1613                .await
1614                .wrap_err_with(|| {
1615                    format!("Verification preflight check failed for chain {}", sequence.chain)
1616                })?;
1617        }
1618
1619        Ok(())
1620    }
1621}
1622
1623impl BundledState<TempoEvmNetwork> {
1624    /// Broadcasts all transactions as a single Tempo batch transaction (type 0x76).
1625    ///
1626    /// This method collects all individual transactions from the script and combines them
1627    /// into a single batch transaction for atomic execution on Tempo.
1628    pub async fn broadcast_batch(mut self) -> Result<BroadcastedState<TempoEvmNetwork>> {
1629        // Batch mode only supports single chain for now
1630        if self.sequence.sequences().len() != 1 {
1631            bail!(
1632                "--batch mode only supports single-chain scripts. \
1633                 Use --multi without --batch for multi-chain."
1634            );
1635        }
1636
1637        let batch_resolution = if let Some(hash) = self.args.resume_tx_hash {
1638            self.sequence
1639                .restore_delegated_pending(DelegatedResolution::new(
1640                    self.args.resume_attempt,
1641                    Some(hash),
1642                    false,
1643                )?)?
1644                .map(|(_, _, attempt, hash)| (attempt, hash))
1645        } else {
1646            None
1647        };
1648        let mut recovered_batch = self
1649            .sequence
1650            .batch_attempt(0)
1651            .map(|(first, attempt, kind)| (first, attempt, kind.clone()));
1652
1653        let sequence = self.sequence.sequences().first().unwrap();
1654        let total_transactions = sequence.transactions.len();
1655        let completed_prefix = completed_transaction_prefix(sequence)?;
1656        let batch_start =
1657            recovered_batch.as_ref().map(|(first, _, _)| *first).unwrap_or(completed_prefix);
1658
1659        if batch_start == total_transactions {
1660            sh_println!("No transactions to broadcast in batch mode.")?;
1661            return Ok(BroadcastedState {
1662                args: self.args,
1663                script_config: self.script_config,
1664                build_data: self.build_data,
1665                sequence: self.sequence,
1666            });
1667        }
1668
1669        // Reject pre-signed transactions: a batch is a single atomic tx from one sender,
1670        // so any tx already signed by another key would silently be re-attributed.
1671        if let Some((idx, _)) =
1672            sequence.transactions().enumerate().find(|(_, tx)| !tx.is_unsigned())
1673        {
1674            bail!(
1675                "--batch cannot include pre-signed transactions (found at position {}); \
1676                 batch mode signs a single atomic transaction from one sender.",
1677                idx + 1
1678            );
1679        }
1680
1681        // Collect sender addresses - batch mode requires single sender
1682        let senders: AddressHashSet = sequence
1683            .transactions()
1684            .skip(batch_start)
1685            .filter(|tx| tx.is_unsigned())
1686            .filter_map(|tx| tx.from())
1687            .collect();
1688
1689        if senders.len() != 1 {
1690            bail!(
1691                "--batch mode requires all transactions to have the same sender. \
1692                 Found {} unique senders: {:?}",
1693                senders.len(),
1694                senders
1695            );
1696        }
1697
1698        let sender = *senders.iter().next().unwrap();
1699        let chain_id = sequence.chain;
1700        let calls = tempo_batch_calls(sequence, batch_start)?;
1701        if let Some((_, _, kind)) = &recovered_batch {
1702            match kind {
1703                AttemptKind::Signed { request: Some(request), payload } => {
1704                    let hash = validate_tempo_batch_payload(
1705                        request,
1706                        &payload.payload,
1707                        sender,
1708                        chain_id,
1709                        &calls,
1710                    )?;
1711                    if hash != payload.hash {
1712                        bail!("recovery plan batch payload does not match its hash");
1713                    }
1714                }
1715                AttemptKind::Delegated { request, .. } => {
1716                    validate_tempo_batch_request(request, sender, chain_id, &calls)?;
1717                }
1718                AttemptKind::Legacy { .. } => {}
1719                AttemptKind::Signed { request: None, .. } => {
1720                    bail!("recovery plan batch payload has no persisted request");
1721                }
1722            }
1723        }
1724
1725        let rpc_url = self.sequence.rpc_url(0).to_owned();
1726        if let Some((attempt_id, hash)) = batch_resolution {
1727            let provider = ProviderBuilder::<TempoNetwork>::from_config_with_url(
1728                &self.script_config.config,
1729                &rpc_url,
1730            )?
1731            .build()?;
1732            let transaction = provider
1733                .get_transaction_by_hash(hash)
1734                .await?
1735                .context("resolved transaction is not available from the recovery endpoint")?;
1736            self.sequence.resolve_delegated_hash(attempt_id, hash, &transaction)?;
1737            recovered_batch = self
1738                .sequence
1739                .batch_attempt(0)
1740                .map(|(first, attempt, kind)| (first, attempt, kind.clone()));
1741        }
1742
1743        let recovered_hash = recovered_batch.as_ref().and_then(|(_, _, kind)| match kind {
1744            AttemptKind::Signed { payload, .. } => Some(payload.hash),
1745            AttemptKind::Delegated { status: DelegatedStatus::Pending { hash }, .. }
1746            | AttemptKind::Legacy { hash } => Some(*hash),
1747            AttemptKind::Delegated { .. } => None,
1748        });
1749        if completed_prefix == total_transactions
1750            || recovered_hash
1751                .is_some_and(|hash| self.sequence.sequences()[0].reverted.contains(&hash))
1752        {
1753            sh_println!("No transactions to broadcast in batch mode.")?;
1754            return Ok(BroadcastedState {
1755                args: self.args,
1756                script_config: self.script_config,
1757                build_data: self.build_data,
1758                sequence: self.sequence,
1759            });
1760        }
1761
1762        if matches!(
1763            recovered_batch,
1764            Some((_, _, AttemptKind::Delegated { status: DelegatedStatus::OutcomeUnknown, .. }))
1765        ) {
1766            bail!(
1767                "submission outcome for delegated Tempo batch is unknown; refusing to risk a duplicate transaction"
1768            );
1769        }
1770
1771        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
1772
1773        if sender == Config::DEFAULT_SENDER {
1774            bail!(
1775                "You seem to be using Foundry's default sender. Be sure to set your own --sender."
1776            );
1777        }
1778
1779        let provider = Arc::new(
1780            ProviderBuilder::<TempoNetwork>::from_config_with_url(
1781                &self.script_config.config,
1782                &rpc_url,
1783            )?
1784            .build()?,
1785        );
1786
1787        if let Some((_, _, AttemptKind::Legacy { hash })) = &recovered_batch {
1788            let transaction = provider
1789                .get_transaction_by_hash(*hash)
1790                .await?
1791                .context("legacy batch transaction is not available for validation")?;
1792            if transaction.tx_hash() != *hash {
1793                bail!("legacy batch endpoint returned a transaction with the wrong hash");
1794            }
1795            validate_tempo_batch_envelope(transaction.as_ref(), sender, chain_id, &calls)?;
1796        }
1797
1798        // Resume detection happens before signer resolution, gas estimation, and sponsor attachment
1799        // so that recovering an already-submitted batch tx never requires the original
1800        // signer/sponsor or a fresh estimate.
1801        if recovered_batch.is_none()
1802            && (!sequence.pending.is_empty()
1803                || sequence.transactions.iter().skip(batch_start).any(|tx| tx.hash.is_some()))
1804        {
1805            bail!("batch progress exists without a durable submission attempt");
1806        }
1807
1808        if let Some(hash) = recovered_hash {
1809            let mut changed = false;
1810            for tx in sequence.transactions.iter_mut().skip(batch_start) {
1811                if tx.hash != Some(hash) {
1812                    tx.hash = Some(hash);
1813                    changed = true;
1814                }
1815            }
1816            if !sequence.receipts.iter().any(|receipt| receipt.transaction_hash() == hash)
1817                && !sequence.pending.contains(&hash)
1818            {
1819                sequence.pending.push(hash);
1820                changed = true;
1821            }
1822            if changed {
1823                self.sequence.save(true, false)?;
1824            }
1825        }
1826
1827        if let Some((_, _, AttemptKind::Signed { payload, .. })) = &recovered_batch
1828            && provider.get_transaction_receipt(payload.hash).await?.is_none()
1829            && provider.get_transaction_by_hash(payload.hash).await?.is_none()
1830        {
1831            send_tempo_batch_payload(provider.as_ref(), &payload.payload, payload.hash).await?;
1832        }
1833
1834        if let Some(tx_hash) = recovered_hash {
1835            sh_println!(
1836                "Resuming batch: tx {tx_hash:#x} already submitted, waiting for receipt..."
1837            )?;
1838
1839            let timeout = self.script_config.config.transaction_timeout;
1840            let receipt_result = tokio::time::timeout(
1841                Duration::from_secs(timeout),
1842                wait_for_batch_receipt(provider.as_ref(), tx_hash, self.args.confirmations),
1843            )
1844            .await;
1845
1846            match receipt_result {
1847                Ok(Ok(Some(receipt))) => {
1848                    Self::finish_batch(&mut self.sequence, receipt, tx_hash, batch_start, true)?;
1849                    return Ok(BroadcastedState {
1850                        args: self.args,
1851                        script_config: self.script_config,
1852                        build_data: self.build_data,
1853                        sequence: self.sequence,
1854                    });
1855                }
1856                Ok(Ok(None)) => {
1857                    bail!(
1858                        "Tempo batch {tx_hash:#x} is not currently visible; its pending hash remains checkpointed"
1859                    );
1860                }
1861                Ok(Err(e)) => return Err(e),
1862                Err(_) => {
1863                    return Err(eyre::eyre!(
1864                        "Timeout waiting for batch transaction receipt (tx: {tx_hash:#x}). \
1865                         The transaction hash remains checkpointed; run with --resume to retry."
1866                    ));
1867                }
1868            }
1869        }
1870
1871        ensure_recorded_sponsor(self.sequence.sponsor(), self.script_config.tempo.sponsor)?;
1872
1873        // Reborrow after the potential save above.
1874        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
1875
1876        let tempo_sponsor = self.script_config.tempo.sponsor_config().await?;
1877
1878        // Get wallet for signing
1879        enum BatchSigner {
1880            Unlocked,
1881            Wallet(EthereumWallet),
1882            TempoKeychain(Box<TempoAccountsWallet>),
1883        }
1884
1885        let mut batch_signer = if self.args.unlocked {
1886            BatchSigner::Unlocked
1887        } else if let Some(session) = self.script_config.tempo.session_signer_for_multi_wallet(
1888            &self.args.wallets,
1889            Some(sender),
1890            chain_id,
1891        )? {
1892            BatchSigner::TempoKeychain(Box::new(session.access_key))
1893        } else {
1894            let mut signers = self.script_wallets.into_multi_wallet().into_signers()?;
1895            if let Some(signer) = signers.remove(&sender) {
1896                BatchSigner::Wallet(EthereumWallet::new(signer))
1897            } else {
1898                // Try the Tempo Accounts store only for Tempo broadcasts.
1899                if self.script_config.evm_opts.networks.is_tempo()
1900                    && let Some(wallet) = TempoAccountsWallet::try_from_default_store()?
1901                    && wallet.has_account(sender)?
1902                {
1903                    BatchSigner::TempoKeychain(Box::new(wallet.with_chain_id(chain_id)))
1904                } else {
1905                    let mut message = format!("No wallet found for sender {sender}");
1906                    if let Some(error) = &self.resume_script_error {
1907                        message = format!("{message}\n{}", resume_script_failure(error));
1908                    }
1909                    bail!(message);
1910                }
1911            }
1912        };
1913        if let Some(error) = &self.resume_script_error {
1914            sh_warn!("{}", resume_script_failure(error))?;
1915        }
1916
1917        // CREATE2 deployer must exist on-chain for any rewritten CREATEs.
1918        let create2_deployer = self.script_config.evm_opts.create2_deployer;
1919        let needs_factory =
1920            sequence.transactions.iter().skip(batch_start).any(|tx| tx.call_kind.is_any_create());
1921        if needs_factory {
1922            let code = provider.get_code_at(create2_deployer).await?;
1923            if keccak256(&code) != DEFAULT_CREATE2_DEPLOYER_CODEHASH {
1924                bail!(
1925                    "CREATE2 deployer {create2_deployer:#x} is not deployed on this Tempo network; \
1926                     --batch requires it. Deploy it first and retry."
1927                );
1928            }
1929        }
1930
1931        sh_println!(
1932            "\n## Broadcasting batch transaction with {} call(s) to chain {}...",
1933            calls.len(),
1934            sequence.chain
1935        )?;
1936
1937        // Build the batch transaction request
1938        let nonce = provider.get_transaction_count(sender).await?;
1939
1940        // Batch transactions are Tempo-only and always use EIP-1559 style fees.
1941        let fees = estimate_eip1559_fees(&provider, self.script_config.config.eip1559_fee_estimate)
1942            .await?;
1943        let fees = resolve_broadcast_eip1559_fees(
1944            fees,
1945            self.args.with_gas_price.map(|p| p.to()),
1946            self.args.priority_gas_price.map(|p| p.to()),
1947            None,
1948        )?;
1949        let max_fee_per_gas = fees.max_fee_per_gas;
1950        let max_priority_fee_per_gas = fees.max_priority_fee_per_gas;
1951
1952        let mut batch_tx = TempoTransactionRequest {
1953            inner: TransactionRequest {
1954                from: Some(sender),
1955                to: None,
1956                value: None,
1957                input: Default::default(),
1958                nonce: Some(nonce),
1959                chain_id: Some(chain_id),
1960                max_fee_per_gas: Some(max_fee_per_gas),
1961                max_priority_fee_per_gas: Some(max_priority_fee_per_gas),
1962                ..Default::default()
1963            },
1964            // Keep the fee token recorded with the remaining calls; `apply` overrides it with
1965            // `--tempo.fee-token`.
1966            fee_token: match sequence.transactions[batch_start].tx() {
1967                TransactionMaybeSigned::Unsigned(tx) => tx.fee_token,
1968                TransactionMaybeSigned::Signed { .. } => None,
1969            },
1970            calls: calls.clone(),
1971            nonce_key: self.script_config.tempo.expiring_nonce.then_some(U256::MAX),
1972            valid_before: self.script_config.tempo.valid_before.and_then(NonZeroU64::new),
1973            ..Default::default()
1974        };
1975        self.script_config.tempo.apply::<TempoNetwork>(&mut batch_tx, None);
1976        let fee_token = if let Some(sponsor) = &tempo_sponsor {
1977            sponsor.resolve_and_set_fee_token(Some(provider.as_ref()), &mut batch_tx).await?;
1978            None
1979        } else {
1980            resolve_and_set_fee_token(Some(provider.as_ref()), &mut batch_tx, Some(sender)).await?
1981        };
1982
1983        if let BatchSigner::TempoKeychain(wallet) = &mut batch_signer {
1984            **wallet = batch_tx.prepare_with_tempo_wallet(provider.as_ref(), wallet).await?;
1985        }
1986
1987        // Estimate gas for the batch transaction
1988        estimate_gas(
1989            &mut batch_tx,
1990            provider.as_ref(),
1991            self.args.gas_estimate_multiplier,
1992            false,
1993            tempo_sponsor.is_some(),
1994        )
1995        .await?;
1996
1997        sh_println!("Estimated gas: {}", batch_tx.inner.gas.unwrap_or(0))?;
1998
1999        if let Some(sponsor) = &tempo_sponsor {
2000            sponsor.attach_and_print::<TempoNetwork>(&mut batch_tx, sender).await?;
2001        } else {
2002            maybe_print_fee_token(Some(provider.as_ref()), fee_token).await?;
2003        }
2004        batch_tx.prep_for_submission();
2005
2006        let _ = sequence;
2007
2008        // Sign and send.
2009        let signed_payload = match &batch_signer {
2010            BatchSigner::Wallet(wallet) => {
2011                Some(Bytes::from(batch_tx.clone().build(wallet).await?.encoded_2718()))
2012            }
2013            BatchSigner::TempoKeychain(wallet) => {
2014                Some(Bytes::from(batch_tx.clone().sign_with_tempo_wallet(wallet).await?))
2015            }
2016            BatchSigner::Unlocked => None,
2017        };
2018        let tx_hash = if let Some(payload) = signed_payload {
2019            validate_tempo_batch_payload(&batch_tx, &payload, sender, chain_id, &calls)?;
2020            let expected = self.sequence.persist_batch_signed_payload(
2021                0,
2022                batch_start,
2023                batch_tx,
2024                payload.clone(),
2025            )?;
2026            send_tempo_batch_payload(provider.as_ref(), &payload, expected).await?;
2027            expected
2028        } else {
2029            let provider = ProviderBuilder::<TempoNetwork>::from_config_with_url(
2030                &self.script_config.config,
2031                &rpc_url,
2032            )?
2033            .max_retry(0)
2034            .build()?;
2035            self.sequence.persist_batch_delegated_request(0, batch_start, batch_tx.clone())?;
2036            let (_, attempt_id, _) = self.sequence.batch_attempt(0).unwrap();
2037            let pending = match provider.send_transaction(batch_tx).await {
2038                Ok(pending) => pending,
2039                Err(error) => {
2040                    let error = eyre::Report::from(error);
2041                    if is_definite_unlocked_non_submission(&error) {
2042                        self.sequence.clear_delegated_request(0, batch_start)?;
2043                        return Err(error);
2044                    }
2045                    self.sequence.persist_delegated_status(
2046                        0,
2047                        batch_start,
2048                        DelegatedStatus::OutcomeUnknown,
2049                    )?;
2050                    return Err(error.wrap_err(format!(
2051                        "submission outcome for delegated Tempo batch attempt {attempt_id} is unknown; resolve it with --resume-attempt and --resume-tx-hash, or use --resume-retry only after proving it was not submitted"
2052                    )));
2053                }
2054            };
2055            let hash = *pending.tx_hash();
2056            self.sequence.persist_delegated_status(
2057                0,
2058                batch_start,
2059                DelegatedStatus::Pending { hash },
2060            )?;
2061            hash
2062        };
2063
2064        sh_println!("Batch transaction sent: {:#x}", tx_hash)?;
2065
2066        // Checkpoint: stamp the batch hash on all remaining transactions (so that resume
2067        // detection finds it regardless of which tx it inspects first), register one entry
2068        // in sequence.pending for drop/timeout tracking, then save.
2069        let sequence = self.sequence.sequences_mut().get_mut(0).unwrap();
2070        for tx in sequence.transactions.iter_mut().skip(batch_start) {
2071            tx.hash = Some(tx_hash);
2072        }
2073        if !sequence.pending.contains(&tx_hash) {
2074            sequence.pending.push(tx_hash);
2075        }
2076        self.sequence.save(true, false)?;
2077
2078        // Wait for receipt
2079        let timeout = self.script_config.config.transaction_timeout;
2080        let receipt = tokio::time::timeout(
2081            Duration::from_secs(timeout),
2082            wait_for_batch_receipt(provider.as_ref(), tx_hash, self.args.confirmations),
2083        )
2084        .await
2085        .map_err(|_| eyre::eyre!("Timeout waiting for batch transaction receipt (tx: {tx_hash:#x}). Run with --resume to retry."))??
2086        .ok_or_else(|| eyre::eyre!("Batch transaction {tx_hash:#x} was dropped from the mempool. Run with --resume to retry."))?;
2087
2088        Self::finish_batch(&mut self.sequence, receipt, tx_hash, batch_start, false)?;
2089        Ok(BroadcastedState {
2090            args: self.args,
2091            script_config: self.script_config,
2092            build_data: self.build_data,
2093            sequence: self.sequence,
2094        })
2095    }
2096
2097    fn finish_batch(
2098        sequences: &mut ScriptSequenceKind<TempoNetwork>,
2099        receipt: TempoTransactionReceipt,
2100        tx_hash: TxHash,
2101        batch_start: usize,
2102        resumed: bool,
2103    ) -> Result<()> {
2104        let sequence = sequences.sequences_mut().get_mut(0).unwrap();
2105        sequence.remove_pending(tx_hash);
2106        if !receipt.status() {
2107            if !sequence.reverted.contains(&tx_hash) {
2108                sequence.reverted.push(tx_hash);
2109            }
2110            sequences.save(true, false)?;
2111            bail!("Batch transaction failed (reverted)");
2112        }
2113        sh_println!("Batch transaction confirmed in block {}", receipt.block_number.unwrap_or(0))?;
2114
2115        // Receipts are pushed 1:1 with the remaining (not-yet-receipted) transactions.
2116        let remaining_len = sequence.transactions.len() - batch_start;
2117        // Only carry through contract_address for actual deployments; plain calls also
2118        // store the callee in `contract_address`, which would otherwise be copied into
2119        // the receipt and treated as a fresh deployment by downstream consumers
2120        // (broadcast JSON, verifier).
2121        let per_tx_addresses: Vec<Option<Address>> = sequence
2122            .transactions
2123            .iter()
2124            .skip(batch_start)
2125            .map(|tx| match tx.call_kind {
2126                CallKind::Create | CallKind::Create2 => tx.contract_address,
2127                _ => None,
2128            })
2129            .collect();
2130
2131        for (idx, addr) in per_tx_addresses.iter().enumerate() {
2132            if let Some(addr) = addr {
2133                sh_println!("  call[{idx}] deployed at: {addr:#x}")?;
2134            }
2135        }
2136
2137        // gasUsed reflects the whole batch; per-call attribution is unavailable from the receipt.
2138        for addr in &per_tx_addresses {
2139            let mut tx_receipt = receipt.clone();
2140            tx_receipt.contract_address = *addr;
2141            sequence.receipts.push(tx_receipt);
2142        }
2143
2144        let chain = sequence.chain;
2145        let _ = sequence;
2146
2147        sequences.save(true, false)?;
2148
2149        let total_gas = receipt.gas_used();
2150        let gas_price = receipt.effective_gas_price();
2151        let total_paid = u128::from(total_gas).saturating_mul(gas_price);
2152        let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
2153        let gas_price_gwei = format_units(gas_price, 9).unwrap_or_else(|_| "N/A".to_string());
2154
2155        let token_symbol = NamedChain::try_from(chain)
2156            .unwrap_or_default()
2157            .native_currency_symbol()
2158            .unwrap_or("ETH");
2159        let resumed =
2160            resumed.then(|| format!("\n(resumed from previous run, {remaining_len} tx(s))"));
2161        sh_println!(
2162            "\nTotal Paid: {} {} ({} gas * {} gwei){}",
2163            paid.trim_end_matches('0'),
2164            token_symbol,
2165            total_gas,
2166            gas_price_gwei.trim_end_matches('0').trim_end_matches('.'),
2167            resumed.as_deref().unwrap_or_default(),
2168        )?;
2169
2170        if !shell::is_json() {
2171            sh_println!("\n\n==========================")?;
2172            sh_println!("\nBATCH EXECUTION COMPLETE & SUCCESSFUL.")?;
2173            sh_println!(
2174                "All {} calls executed atomically in a single transaction.",
2175                remaining_len
2176            )?;
2177        }
2178
2179        Ok(())
2180    }
2181}
2182
2183async fn send_tempo_batch_payload(
2184    provider: &RootProvider<TempoNetwork>,
2185    payload: &[u8],
2186    expected: TxHash,
2187) -> Result<()> {
2188    match provider.send_raw_transaction(payload).await {
2189        Ok(pending) if *pending.tx_hash() == expected => Ok(()),
2190        Ok(pending) => {
2191            bail!("RPC returned hash {} for signed batch payload {expected}", pending.tx_hash())
2192        }
2193        Err(error) => {
2194            if provider.get_transaction_receipt(expected).await.ok().flatten().is_some()
2195                || provider.get_transaction_by_hash(expected).await.ok().flatten().is_some()
2196            {
2197                Ok(())
2198            } else {
2199                Err(error.into())
2200            }
2201        }
2202    }
2203}
2204
2205async fn wait_for_batch_receipt<N: Network>(
2206    provider: &RootProvider<N>,
2207    tx_hash: TxHash,
2208    confirmations: u64,
2209) -> Result<Option<N::ReceiptResponse>> {
2210    loop {
2211        if let Some(receipt) = provider.get_transaction_receipt(tx_hash).await?
2212            && is_mined_receipt_for(&receipt, tx_hash)
2213            && let Some(receipt_block) = receipt.block_number()
2214        {
2215            let latest_block = provider.get_block_number().await?;
2216            if latest_block >= receipt_block.saturating_add(confirmations.saturating_sub(1)) {
2217                return Ok(Some(receipt));
2218            }
2219        }
2220
2221        if provider.get_transaction_by_hash(tx_hash).await?.is_none() {
2222            return Ok(None);
2223        }
2224
2225        tokio::time::sleep(Duration::from_millis(500)).await;
2226    }
2227}
2228
2229/// Estimates and sets the gas limit of `tx`, which a Tempo fee payer signs afterwards when
2230/// `sponsored`.
2231pub async fn estimate_gas<N: Network, P: Provider<N>>(
2232    tx: &mut N::TransactionRequest,
2233    provider: &P,
2234    estimate_multiplier: u64,
2235    browser: bool,
2236    sponsored: bool,
2237) -> Result<()>
2238where
2239    N::TransactionRequest: FoundryTransactionBuilder<N>,
2240{
2241    // if already set, some RPC endpoints might simply return the gas value that is already
2242    // set in the request and omit the estimate altogether, so we remove it here
2243    tx.reset_gas_limit();
2244
2245    let mut request = if browser { tx.browser_wallet_gas_estimation_request() } else { tx.clone() };
2246    if sponsored {
2247        mark_sponsored_gas_estimation(provider, &mut request).await;
2248    }
2249    let estimate =
2250        provider.estimate_gas(request).await.wrap_err("Failed to estimate gas for tx")?;
2251    tx.set_gas_limit(apply_gas_estimate_multiplier(estimate, Some(estimate_multiplier))?);
2252    Ok(())
2253}
2254
2255fn reject_access_key_create<N: Network>(
2256    tx: &N::TransactionRequest,
2257    uses_access_key: bool,
2258) -> Result<()>
2259where
2260    N::TransactionRequest: FoundryTransactionBuilder<N>,
2261{
2262    if uses_access_key && tx.tempo_calls().iter().any(|(to, _)| to.is_create()) {
2263        bail!("Tempo access-key transactions cannot use CREATE");
2264    }
2265    Ok(())
2266}
2267
2268pub(crate) fn convert_tempo_aa_create<N: Network>(tx: &mut N::TransactionRequest)
2269where
2270    N::TransactionRequest: FoundryTransactionBuilder<N>,
2271{
2272    if tx.is_tempo_aa() {
2273        tx.convert_create_to_call();
2274    }
2275}
2276
2277/// Collection increments the sender's protocol nonce for CALLs, but expiring CALLs do not.
2278/// Reject a subsequent CREATE before submitting anything, since its simulated address is stale.
2279/// Called only when expiring nonce mode is enabled.
2280fn reject_expiring_call_before_create<N: Network>(sequences: &[ScriptSequence<N>]) -> Result<()>
2281where
2282    N::TransactionRequest: FoundryTransactionBuilder<N>,
2283{
2284    let mut called = HashSet::new();
2285    for sequence in sequences {
2286        for transaction in &sequence.transactions {
2287            let tx = transaction.tx();
2288            if let Some(sender) = tx.from() {
2289                let scope = (sequence.chain, sender);
2290                if tx.to().is_none() && called.contains(&scope) {
2291                    bail!(
2292                        "Tempo expiring nonce scripts cannot use CREATE after a CALL from the same sender on the same chain; use CREATE2 or disable --tempo.expiring-nonce"
2293                    );
2294                }
2295                let expiring = match tx {
2296                    TransactionMaybeSigned::Unsigned(request) => request.supports_fee_token(),
2297                    TransactionMaybeSigned::Signed { tx, .. } => {
2298                        <N::TransactionRequest as From<N::TxEnvelope>>::from(tx.clone()).nonce_key()
2299                            == Some(TEMPO_EXPIRING_NONCE_KEY)
2300                    }
2301                };
2302                if expiring && tx.to().is_some() {
2303                    called.insert(scope);
2304                }
2305            }
2306        }
2307    }
2308    Ok(())
2309}
2310
2311/// Returns the total gas used, the average gas price and the total fee paid in wei for the given
2312/// `(gas_used, effective_gas_price)` receipt pairs.
2313fn fee_totals(receipts: impl IntoIterator<Item = (u64, u128)>) -> (u64, Option<u128>, u128) {
2314    let (count, total_gas, total_gas_price, total_paid) =
2315        receipts.into_iter().fold((0u128, 0u64, 0u128, 0u128), |acc, (gas_used, gas_price)| {
2316            (
2317                acc.0 + 1,
2318                acc.1 + gas_used,
2319                acc.2.saturating_add(gas_price),
2320                acc.3.saturating_add(u128::from(gas_used).saturating_mul(gas_price)),
2321            )
2322        });
2323    (total_gas, total_gas_price.checked_div(count), total_paid)
2324}
2325
2326/// Describes the failed script run that `--resume` performed to collect missing signers.
2327fn resume_script_failure(error: &str) -> String {
2328    format!("Resume re-ran the script to collect signers, but it failed: {error}")
2329}
2330
2331impl<FEN: FoundryEvmNetwork> BroadcastedState<FEN> {
2332    /// Prints recorded creations with successful receipts, including factory deployments.
2333    pub(crate) fn print_deployed_contracts(&self) -> Result<()> {
2334        if shell::is_json() {
2335            return Ok(());
2336        }
2337
2338        for sequence in self.sequence.sequences() {
2339            let mined = sequence
2340                .receipts
2341                .iter()
2342                .map(|receipt| receipt.transaction_hash())
2343                .collect::<HashSet<_>>();
2344            let rows = sequence
2345                .transactions
2346                .iter()
2347                .filter(|tx| tx.hash.is_some_and(|hash| mined.contains(&hash)))
2348                .flat_map(|tx| {
2349                    let direct = tx.call_kind.is_any_create().then_some(tx).and_then(|tx| {
2350                        Some((
2351                            tx.label.as_deref(),
2352                            tx.contract_name.as_deref(),
2353                            tx.contract_address?,
2354                        ))
2355                    });
2356                    direct.into_iter().chain(tx.additional_contracts.iter().map(|contract| {
2357                        (
2358                            contract.label.as_deref(),
2359                            contract.contract_name.as_deref(),
2360                            contract.address,
2361                        )
2362                    }))
2363                })
2364                .map(|(label, name, address)| {
2365                    (label, name.filter(|name| !name.is_empty()).unwrap_or("-"), address)
2366                })
2367                .collect::<Vec<_>>();
2368            if rows.is_empty() {
2369                continue;
2370            }
2371
2372            let has_labels = rows.iter().any(|(label, ..)| label.is_some());
2373            let label_width = rows
2374                .iter()
2375                .map(|(label, ..)| label.map_or(1, |label| label.chars().count()))
2376                .max()
2377                .unwrap_or(0);
2378            let name_width =
2379                rows.iter().map(|(_, name, _)| name.chars().count()).max().unwrap_or(0);
2380            sh_status!("\nDeployed contracts (chain {}):", sequence.chain)?;
2381            for (label, name, address) in rows {
2382                if has_labels {
2383                    sh_status!(
2384                        "  {:<label_width$}  {name:<name_width$}  {address}",
2385                        label.unwrap_or("-")
2386                    )?;
2387                } else {
2388                    sh_status!("  {name:<name_width$}  {address}")?;
2389                }
2390            }
2391        }
2392        Ok(())
2393    }
2394}
2395
2396#[cfg(test)]
2397mod tests {
2398    use super::*;
2399    use crate::sequence::DelegatedAction;
2400    use alloy_consensus::{Eip658Value, Receipt, ReceiptEnvelope, ReceiptWithBloom, TxEnvelope};
2401    use alloy_network::Ethereum;
2402    use alloy_primitives::{B256, Bloom, address, hex};
2403    use alloy_provider::mock::Asserter;
2404    use alloy_rpc_types::TransactionReceipt;
2405    use foundry_common::tempo::PATH_USD_ADDRESS;
2406    use foundry_evm::{backend::Backend, core::evm::EthEvmNetwork, opts::EvmOpts};
2407
2408    const ROOT_PRIVATE_KEY: &str =
2409        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
2410    const ACCESS_KEY_PRIVATE_KEY: &str =
2411        "0x59c6995e998f97a5a004497e5da3b5d2b2b66a87f064d39c44da0b6d6e4f8ff0";
2412    const SIGNED_TX: &[u8] = &hex!(
2413        "02f86b0180843b9aca008502540be4008252089400000000000000000000000000000000000000016480c001a070d55e79ed3ac9fc8f51e78eb91fd054720d943d66633f2eb1bc960f0126b0eca052eda05a792680de3181e49bab4093541f75b49d1ecbe443077b3660c836016a"
2414    );
2415    const OTHER_SIGNED_TX: &[u8] = &hex!(
2416        "02f86b0180843b9aca008502540be4008252089400000000000000000000000000000000000000018080c001a0cce9a61187b5d18a89ecd27ec675e3b3f10d37f165627ef89a15a7fe76395ce8a07537f5bffb358ffbef22cda84b1c92f7211723f9e09ae037e81686805d3e5505"
2417    );
2418
2419    #[tokio::test(flavor = "multi_thread")]
2420    async fn next_nonce_uses_exact_fork_hash() {
2421        let (_api, handle) = anvil::spawn(anvil::NodeConfig::test()).await;
2422        let provider = handle.http_provider();
2423        let sender = handle.dev_accounts().next().unwrap();
2424        let recipient = Address::with_last_byte(1);
2425
2426        let receipt = provider
2427            .send_transaction(
2428                TransactionRequest::default().from(sender).to(recipient).value(U256::ONE).into(),
2429            )
2430            .await
2431            .unwrap()
2432            .get_receipt()
2433            .await
2434            .unwrap();
2435        let block_number = receipt.block_number.unwrap();
2436        let evm_opts = EvmOpts {
2437            fork_url: Some(handle.http_endpoint()),
2438            fork_block_number: Some(block_number),
2439            ..Default::default()
2440        };
2441        let (env, _, _) = evm_opts.env_with_fork_context::<EthEvmNetwork>().await.unwrap();
2442        let backend = Backend::<EthEvmNetwork>::spawn(
2443            evm_opts.get_fork(&Config::default(), 31337, None),
2444            env,
2445        )
2446        .unwrap();
2447        assert_eq!(backend.transaction_count(sender).await.unwrap(), 1);
2448
2449        provider
2450            .raw_request::<_, ()>("anvil_reorg".into(), (1_u64, Vec::<serde_json::Value>::new()))
2451            .await
2452            .unwrap();
2453        assert_eq!(provider.get_transaction_count(sender).number(block_number).await.unwrap(), 0);
2454
2455        match backend.transaction_count(sender).await {
2456            Ok(0) => panic!("the exact lookup fell back to the replacement block"),
2457            Ok(1) | Err(_) => {}
2458            Ok(nonce) => panic!("unexpected nonce: {nonce}"),
2459        }
2460    }
2461
2462    #[test]
2463    fn access_key_signer_takes_precedence_over_same_sender_wallet() {
2464        let root = foundry_wallets::utils::create_private_key_signer(ROOT_PRIVATE_KEY).unwrap();
2465        let root_address = root.address();
2466        let access_key =
2467            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
2468        let access_key_address = access_key.address();
2469        let mut eth_wallets = AddressHashMap::default();
2470        eth_wallets.insert(root_address, EthereumWallet::new(root));
2471        let mut access_keys = HashMap::default();
2472        access_keys.insert(
2473            SignerScope::new(4217, root_address),
2474            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217),
2475        );
2476        let send_kind = SendTransactionsKind::<Ethereum>::Raw {
2477            eth_wallets,
2478            browser: None,
2479            access_keys,
2480            configurable_accounts: HashMap::default(),
2481            offline_owners: HashMap::default(),
2482        };
2483
2484        let tx = TransactionRequest { from: Some(root_address), ..Default::default() };
2485        let sender = send_kind.for_sender(4217, &root_address, tx).unwrap();
2486
2487        match sender {
2488            SendTransactionKind::AccessKey(_, wallet) => {
2489                assert_eq!(wallet.key_id().unwrap(), access_key_address);
2490                assert_eq!(wallet.account(), root_address);
2491            }
2492            _ => panic!("expected access key signer"),
2493        }
2494    }
2495
2496    #[test]
2497    fn access_key_signer_is_scoped_to_chain() {
2498        let root = foundry_wallets::utils::create_private_key_signer(ROOT_PRIVATE_KEY).unwrap();
2499        let root_address = root.address();
2500        let access_key =
2501            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
2502        let mut eth_wallets = AddressHashMap::default();
2503        eth_wallets.insert(root_address, EthereumWallet::new(root));
2504        let mut access_keys = HashMap::default();
2505        access_keys.insert(
2506            SignerScope::new(4217, root_address),
2507            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217),
2508        );
2509        let send_kind = SendTransactionsKind::<Ethereum>::Raw {
2510            eth_wallets,
2511            browser: None,
2512            access_keys,
2513            configurable_accounts: HashMap::default(),
2514            offline_owners: HashMap::default(),
2515        };
2516
2517        let tx = TransactionRequest { from: Some(root_address), ..Default::default() };
2518        let sender = send_kind.for_sender(1, &root_address, tx).unwrap();
2519
2520        match sender {
2521            SendTransactionKind::Raw(_, wallet) => {
2522                assert_eq!(wallet.default_signer().address(), root_address);
2523            }
2524            _ => panic!("expected root wallet signer for non-session chain"),
2525        }
2526    }
2527
2528    #[test]
2529    fn recovered_signed_payload_does_not_require_a_signer() {
2530        let dir = tempfile::tempdir().unwrap();
2531        let mut sequence = ScriptSequence::<Ethereum> {
2532            chain: 1,
2533            transactions: [planned_tx(SIGNED_TX)].into(),
2534            ..Default::default()
2535        };
2536        sequence.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2537        let mut sequence = ScriptSequenceKind::new_single(sequence, false, None).unwrap();
2538        let payload = Bytes::from_static(SIGNED_TX);
2539        sequence.persist_signed_payload(0, 0, payload, true).unwrap();
2540
2541        assert!(remaining_unsigned_transactions_for_recovery(&sequence).is_empty());
2542    }
2543
2544    #[test]
2545    fn recovered_batch_attempt_does_not_require_a_signer() {
2546        let dir = tempfile::tempdir().unwrap();
2547        let sender = Address::repeat_byte(0x22);
2548        let mut deployment = ScriptSequence::<Ethereum> {
2549            chain: 1,
2550            transactions: [script_tx(sender)].into(),
2551            ..Default::default()
2552        };
2553        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2554        let mut sequence = ScriptSequenceKind::new_single(deployment, true, None).unwrap();
2555        sequence.persist_batch_delegated_request(0, 0, Default::default()).unwrap();
2556
2557        assert!(remaining_unsigned_transactions_for_recovery(&sequence).is_empty());
2558    }
2559
2560    #[test]
2561    fn batch_retry_clears_the_shared_delegated_attempt() {
2562        let dir = tempfile::tempdir().unwrap();
2563        let recovery_path = dir.path().join("cache.json.recovery.json");
2564        let mut deployment = ScriptSequence::<Ethereum> {
2565            chain: 1,
2566            transactions: [script_tx(Address::ZERO), script_tx(Address::ZERO)].into(),
2567            ..Default::default()
2568        };
2569        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2570        let mut sequence = ScriptSequenceKind::new_single(deployment, true, None).unwrap();
2571        sequence.persist_batch_delegated_request(0, 0, Default::default()).unwrap();
2572        let (_, attempt, _) = sequence.batch_attempt(0).unwrap();
2573
2574        sequence
2575            .restore_delegated_pending(DelegatedResolution::Attempt {
2576                attempt,
2577                action: Some(DelegatedAction::Retry),
2578            })
2579            .unwrap();
2580
2581        assert!(sequence.batch_attempt(0).is_none());
2582        drop(sequence);
2583        let recovery: serde_json::Value =
2584            foundry_common::fs::read_json_file(&recovery_path).unwrap();
2585        assert_eq!(recovery["deployments"][0]["operations"].as_array().unwrap().len(), 2);
2586        assert!(recovery["deployments"][0].get("attempts").is_none());
2587    }
2588
2589    #[test]
2590    fn recovered_sender_still_requires_sequential_ordering() {
2591        let dir = tempfile::tempdir().unwrap();
2592        let unsigned = Address::repeat_byte(0x22);
2593        let mut sequence = ScriptSequence::<Ethereum> {
2594            chain: 1,
2595            transactions: [planned_tx(SIGNED_TX), script_tx(unsigned)].into(),
2596            ..Default::default()
2597        };
2598        sequence.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2599        let mut sequence = ScriptSequenceKind::new_single(sequence, false, None).unwrap();
2600        sequence.persist_signed_payload(0, 0, Bytes::from_static(SIGNED_TX), true).unwrap();
2601
2602        let required = remaining_unsigned_transactions_for_recovery(&sequence);
2603        assert_eq!(required.iter().map(|tx| tx.sender).collect::<Vec<_>>(), [unsigned]);
2604        assert_eq!(remaining_sender_addresses(&sequence).len(), 2);
2605    }
2606
2607    #[test]
2608    fn signed_only_sequences_remain_sequential() {
2609        assert!(should_broadcast_sequentially(false, false, 0, 1, true));
2610        assert!(!should_broadcast_sequentially(false, false, 1, 1, true));
2611    }
2612
2613    #[test]
2614    fn browser_rejections_are_definite_non_submissions() {
2615        let rejected =
2616            eyre::Report::new(alloy_signer::Error::other(BrowserWalletError::Rejected {
2617                operation: "Transaction",
2618                reason: "Rejected by user".to_string(),
2619            }));
2620        assert!(is_definite_browser_non_submission(&rejected));
2621        let send_error = eyre::Report::new(alloy_signer::Error::other(
2622            BrowserWalletError::ServerError("replacement transaction underpriced".to_string()),
2623        ));
2624        assert!(!is_definite_browser_non_submission(&send_error));
2625        let not_connected =
2626            eyre::Report::new(alloy_signer::Error::other(BrowserWalletError::NotConnected));
2627        assert!(is_definite_browser_non_submission(&not_connected));
2628        let timeout = eyre::Report::new(alloy_signer::Error::other(BrowserWalletError::Timeout {
2629            operation: "Transaction",
2630        }));
2631        assert!(!is_definite_browser_non_submission(&timeout));
2632    }
2633
2634    #[test]
2635    fn only_anvil_no_signer_errors_are_definite_non_submissions() {
2636        assert!(is_unlocked_non_submission(-32602, "No Signer available"));
2637        assert!(!is_unlocked_non_submission(-32603, "No Signer available"));
2638        assert!(!is_unlocked_non_submission(-32602, "transaction rejected"));
2639    }
2640
2641    #[test]
2642    fn recovered_completion_is_matched_by_hash() {
2643        let dir = tempfile::tempdir().unwrap();
2644        let mut deployment = ScriptSequence::<Ethereum> {
2645            chain: 1,
2646            transactions: [planned_tx(SIGNED_TX), planned_tx(OTHER_SIGNED_TX)].into(),
2647            ..Default::default()
2648        };
2649        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2650        let mut sequence = ScriptSequenceKind::new_single(deployment, false, None).unwrap();
2651        sequence.persist_signed_payload(0, 0, Bytes::from_static(SIGNED_TX), true).unwrap();
2652        let second_hash = sequence
2653            .persist_signed_payload(0, 1, Bytes::from_static(OTHER_SIGNED_TX), true)
2654            .unwrap();
2655        let mut second_receipt = receipt();
2656        second_receipt.transaction_hash = second_hash;
2657        sequence.sequences_mut()[0].receipts.push(second_receipt);
2658
2659        assert_eq!(remaining_operation_indices(&sequence, 0), [0]);
2660    }
2661
2662    #[test]
2663    fn recorded_revert_leaves_only_submitted_operations() {
2664        let dir = tempfile::tempdir().unwrap();
2665        let mut deployment = ScriptSequence::<Ethereum> {
2666            chain: 1,
2667            transactions: [planned_tx(SIGNED_TX), planned_tx(OTHER_SIGNED_TX)].into(),
2668            ..Default::default()
2669        };
2670        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2671        let mut sequence = ScriptSequenceKind::new_single(deployment, false, None).unwrap();
2672        let reverted =
2673            sequence.persist_signed_payload(0, 0, Bytes::from_static(SIGNED_TX), true).unwrap();
2674        sequence.sequences_mut()[0].reverted.push(reverted);
2675        assert!(remaining_operation_indices(&sequence, 0).is_empty());
2676        assert!(refused_after_revert(&sequence).is_some());
2677
2678        // An attempt saved before the revert was recorded is recovered, and nothing is refused.
2679        sequence.persist_signed_payload(0, 1, Bytes::from_static(OTHER_SIGNED_TX), true).unwrap();
2680        assert_eq!(remaining_operation_indices(&sequence, 0), [1]);
2681        assert!(refused_after_revert(&sequence).is_none());
2682    }
2683
2684    #[test]
2685    fn externally_signed_completion_uses_the_persisted_hash() {
2686        let dir = tempfile::tempdir().unwrap();
2687        let sender = Address::repeat_byte(0x11);
2688        let mut deployment = ScriptSequence::<Ethereum> {
2689            chain: 1,
2690            transactions: [script_tx(sender), script_tx(sender)].into(),
2691            receipts: vec![receipt()],
2692            ..Default::default()
2693        };
2694        deployment.transactions[1].hash = Some(deployment.receipts[0].transaction_hash());
2695        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2696        let sequence = ScriptSequenceKind::new_single(deployment, false, None).unwrap();
2697
2698        assert_eq!(remaining_operation_indices(&sequence, 0), [0]);
2699    }
2700
2701    #[test]
2702    fn duplicate_receipts_do_not_complete_an_unsigned_operation() {
2703        let dir = tempfile::tempdir().unwrap();
2704        let mut deployment = ScriptSequence::<Ethereum> {
2705            chain: 1,
2706            transactions: [planned_tx(SIGNED_TX), planned_tx(OTHER_SIGNED_TX)].into(),
2707            ..Default::default()
2708        };
2709        deployment.paths = Some((dir.path().join("broadcast.json"), dir.path().join("cache.json")));
2710        let mut sequence = ScriptSequenceKind::new_single(deployment, false, None).unwrap();
2711        let first_hash =
2712            sequence.persist_signed_payload(0, 0, Bytes::from_static(SIGNED_TX), true).unwrap();
2713        let mut first_receipt = receipt();
2714        first_receipt.transaction_hash = first_hash;
2715        sequence.sequences_mut()[0].receipts = vec![first_receipt.clone(), first_receipt];
2716
2717        assert_eq!(remaining_operation_indices(&sequence, 0), [1]);
2718    }
2719
2720    #[test]
2721    fn completed_prefix_rejects_receipt_holes() {
2722        let hash = B256::repeat_byte(0x44);
2723        let mut later = script_tx(Address::ZERO);
2724        later.hash = Some(hash);
2725        let mut receipt = receipt();
2726        receipt.transaction_hash = hash;
2727        let sequence = ScriptSequence::<Ethereum> {
2728            transactions: [script_tx(Address::ZERO), later].into(),
2729            receipts: vec![receipt],
2730            ..Default::default()
2731        };
2732
2733        assert!(completed_transaction_prefix(&sequence).is_err());
2734    }
2735
2736    #[tokio::test]
2737    async fn access_key_sets_key_id_before_estimation() {
2738        let root_address = Address::repeat_byte(0x11);
2739        let access_key =
2740            foundry_wallets::utils::create_local_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
2741        let access_key_address = access_key.address();
2742        let access_key_wallet =
2743            TempoAccountsWallet::from_secp256k1(root_address, access_key, None).with_chain_id(4217);
2744        // An explicit fee token keeps preparation from querying the unreachable endpoint.
2745        let mut sender = SendTransactionKind::<TempoNetwork>::AccessKey(
2746            TempoTransactionRequest {
2747                inner: TransactionRequest { from: Some(root_address), ..Default::default() },
2748                fee_token: Some(PATH_USD_ADDRESS),
2749                ..Default::default()
2750            },
2751            Box::new(access_key_wallet),
2752        );
2753        let provider =
2754            RootProvider::<TempoNetwork>::new_http("http://localhost:8545".parse().unwrap());
2755
2756        sender.prepare(&provider, false, true, false, 100, None).await.unwrap();
2757
2758        match sender {
2759            SendTransactionKind::AccessKey(tx, _) => {
2760                assert_eq!(tx.key_id, Some(access_key_address));
2761            }
2762            _ => panic!("expected access key transaction"),
2763        }
2764    }
2765
2766    #[test]
2767    fn tempo_aa_create_moves_deployment_into_calls() {
2768        let mut tx = TempoTransactionRequest {
2769            inner: TransactionRequest { to: Some(TxKind::Create), ..Default::default() },
2770            fee_token: Some(address!("0x20c0000000000000000000000000000000000000")),
2771            ..Default::default()
2772        };
2773
2774        convert_tempo_aa_create::<TempoNetwork>(&mut tx);
2775
2776        assert!(tx.inner.to.is_none());
2777        assert_eq!(tx.calls.len(), 1);
2778        assert!(tx.calls[0].to.is_create());
2779    }
2780
2781    #[tokio::test]
2782    async fn signed_tempo_batch_is_bound_to_its_calls() {
2783        let signer = foundry_wallets::utils::create_private_key_signer(ROOT_PRIVATE_KEY).unwrap();
2784        let sender = signer.address();
2785        let wallet = EthereumWallet::new(signer);
2786        let calls = vec![Call {
2787            to: TxKind::Call(Address::repeat_byte(0x11)),
2788            value: U256::ONE,
2789            input: Bytes::new(),
2790        }];
2791        let request = TempoTransactionRequest {
2792            inner: TransactionRequest {
2793                from: Some(sender),
2794                nonce: Some(0),
2795                chain_id: Some(4217),
2796                gas: Some(21_000),
2797                max_fee_per_gas: Some(1),
2798                max_priority_fee_per_gas: Some(1),
2799                ..Default::default()
2800            },
2801            calls: calls.clone(),
2802            ..Default::default()
2803        };
2804        let payload = request.clone().build(&wallet).await.unwrap().encoded_2718();
2805
2806        assert!(validate_tempo_batch_payload(&request, &payload, sender, 4217, &calls).is_ok());
2807        let other_calls =
2808            vec![Call { to: TxKind::Call(Address::repeat_byte(0x22)), ..calls[0].clone() }];
2809        assert!(
2810            validate_tempo_batch_payload(&request, &payload, sender, 4217, &other_calls).is_err()
2811        );
2812
2813        let other_signer =
2814            foundry_wallets::utils::create_private_key_signer(ACCESS_KEY_PRIVATE_KEY).unwrap();
2815        let mut other_request = request.clone();
2816        other_request.inner.from = Some(other_signer.address());
2817        let other_payload =
2818            other_request.build(&EthereumWallet::new(other_signer)).await.unwrap().encoded_2718();
2819        assert!(
2820            validate_tempo_batch_payload(&request, &other_payload, sender, 4217, &calls).is_err()
2821        );
2822        let other_envelope = TempoTxEnvelope::decode_2718_exact(&other_payload).unwrap();
2823        assert!(validate_tempo_batch_envelope(&other_envelope, sender, 4217, &calls).is_err());
2824    }
2825
2826    #[test]
2827    fn tempo_access_key_create_is_rejected_before_preparation() {
2828        let tx = TempoTransactionRequest {
2829            inner: TransactionRequest { to: Some(TxKind::Create), ..Default::default() },
2830            ..Default::default()
2831        };
2832
2833        let error = reject_access_key_create::<TempoNetwork>(&tx, true).unwrap_err();
2834
2835        assert!(error.to_string().contains("Tempo access-key transactions cannot use CREATE"));
2836    }
2837
2838    #[test]
2839    fn expiring_nonce_create_preflight_tracks_chain_and_sender_across_sequences() {
2840        let sender = Address::with_last_byte(1);
2841        let transaction = |sender, to| {
2842            TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::<TempoNetwork>::new(
2843                TempoTransactionRequest {
2844                    inner: TransactionRequest { from: Some(sender), to, ..Default::default() },
2845                    ..Default::default()
2846                },
2847            ))
2848        };
2849        let mut sequences = [
2850            ScriptSequence {
2851                chain: 4217,
2852                transactions: [transaction(sender, Some(TxKind::Call(Address::with_last_byte(2))))]
2853                    .into(),
2854                ..Default::default()
2855            },
2856            ScriptSequence {
2857                chain: 4218,
2858                transactions: [transaction(sender, None)].into(),
2859                ..Default::default()
2860            },
2861            ScriptSequence {
2862                chain: 4217,
2863                transactions: [transaction(sender, None)].into(),
2864                ..Default::default()
2865            },
2866        ];
2867        assert_eq!(
2868            reject_expiring_call_before_create(&sequences).unwrap_err().to_string(),
2869            "Tempo expiring nonce scripts cannot use CREATE after a CALL from the same sender on the same chain; use CREATE2 or disable --tempo.expiring-nonce"
2870        );
2871        sequences[2].chain = 4219;
2872        reject_expiring_call_before_create(&sequences).unwrap();
2873        sequences[2].chain = 4217;
2874        sequences[2].transactions[0] = transaction(Address::with_last_byte(3), None);
2875        reject_expiring_call_before_create(&sequences).unwrap();
2876        sequences[2].transactions[0] =
2877            transaction(sender, Some(TxKind::Call(Address::with_last_byte(2))));
2878        reject_expiring_call_before_create(&sequences).unwrap();
2879
2880        let mut ethereum = ScriptSequence::<Ethereum> {
2881            chain: 1,
2882            transactions: [script_tx(sender), script_tx(sender)].into(),
2883            ..Default::default()
2884        };
2885        ethereum.transactions[0]
2886            .tx_mut()
2887            .as_unsigned_mut()
2888            .unwrap()
2889            .set_to(Address::with_last_byte(2));
2890        reject_expiring_call_before_create(&[ethereum]).unwrap();
2891    }
2892
2893    #[test]
2894    fn fee_totals_do_not_overflow_u64() {
2895        let gwei = 1_000_000_000;
2896        let receipts = [(30_000_000, 1_000 * gwei), (30_000_000, 2_000 * gwei)];
2897
2898        assert_eq!(
2899            fee_totals(receipts),
2900            (60_000_000, Some(1_500 * gwei), 90_000_000_000_000_000_000)
2901        );
2902    }
2903
2904    #[tokio::test]
2905    async fn batch_receipt_watcher_rejects_foreign_or_incomplete_receipts() {
2906        let hash = B256::repeat_byte(0x42);
2907        let receipt = |field: &str, value: serde_json::Value| {
2908            let mut receipt = serde_json::json!({
2909                "type": "0x02", "status": "0x1", "cumulativeGasUsed": "0x5208", "logs": [],
2910                "transactionHash": hash, "logsBloom": format!("{:#x}", Bloom::ZERO),
2911                "transactionIndex": "0x0", "blockHash": B256::ZERO, "blockNumber": "0x10",
2912                "gasUsed": "0x5208", "effectiveGasPrice": "0x1",
2913                "from": Address::ZERO, "to": Address::ZERO, "contractAddress": null
2914            });
2915            receipt[field] = value;
2916            receipt
2917        };
2918        // Bad receipts fall through to the transaction lookup; valid ones to the block number.
2919        let wait = async |receipt: serde_json::Value, next: serde_json::Value| {
2920            let asserter = Asserter::new();
2921            let provider: RootProvider<Ethereum> =
2922                alloy_provider::ProviderBuilder::default().connect_mocked_client(asserter.clone());
2923            asserter.push_success(&receipt);
2924            asserter.push_success(&next);
2925            wait_for_batch_receipt(&provider, hash, 1).await.unwrap()
2926        };
2927
2928        for (field, value) in [
2929            ("transactionHash", serde_json::json!(B256::repeat_byte(0x99))),
2930            ("blockHash", serde_json::Value::Null),
2931            ("transactionIndex", serde_json::Value::Null),
2932            ("blockNumber", serde_json::Value::Null),
2933        ] {
2934            let result = wait(receipt(field, value), serde_json::Value::Null).await;
2935            assert!(result.is_none(), "accepted receipt with bad {field}");
2936        }
2937        let accepted =
2938            wait(receipt("status", serde_json::json!("0x1")), serde_json::json!("0x10")).await;
2939        let accepted = accepted.unwrap();
2940        assert_eq!(accepted.transaction_hash(), hash);
2941    }
2942
2943    fn script_tx(from: Address) -> TransactionWithMetadata<Ethereum> {
2944        TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(TransactionRequest {
2945            from: Some(from),
2946            ..Default::default()
2947        }))
2948    }
2949
2950    fn planned_tx(payload: &[u8]) -> TransactionWithMetadata<Ethereum> {
2951        let envelope = TxEnvelope::decode_2718_exact(payload).unwrap();
2952        let from = envelope.recover_signer().unwrap();
2953        let mut request: TransactionRequest = envelope.into();
2954        request.from = Some(from);
2955        TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(request))
2956    }
2957
2958    fn receipt() -> TransactionReceipt {
2959        TransactionReceipt {
2960            inner: ReceiptEnvelope::Legacy(ReceiptWithBloom {
2961                receipt: Receipt {
2962                    status: Eip658Value::success(),
2963                    cumulative_gas_used: 0,
2964                    logs: vec![],
2965                },
2966                logs_bloom: Bloom::ZERO,
2967            }),
2968            transaction_hash: Default::default(),
2969            transaction_index: None,
2970            block_hash: None,
2971            block_number: None,
2972            gas_used: 0,
2973            effective_gas_price: 0,
2974            blob_gas_used: None,
2975            blob_gas_price: None,
2976            from: Address::ZERO,
2977            to: None,
2978            contract_address: None,
2979        }
2980    }
2981
2982    #[tokio::test]
2983    async fn expiring_create_checks_planned_nonce_including_durable_payloads() {
2984        let request = TempoTransactionRequest {
2985            inner: TransactionRequest {
2986                from: Some(Address::with_last_byte(1)),
2987                to: Some(TxKind::Create),
2988                nonce: Some(7),
2989                chain_id: Some(4217),
2990                gas: Some(100_000),
2991                max_fee_per_gas: Some(10),
2992                max_priority_fee_per_gas: Some(1),
2993                ..Default::default()
2994            },
2995            nonce_key: Some(TEMPO_EXPIRING_NONCE_KEY),
2996            valid_before: NonZeroU64::new(100),
2997            ..Default::default()
2998        };
2999        let planned = TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::<
3000            TempoNetwork,
3001        >::new(request.clone()));
3002        let mut request = request;
3003        // The discriminator differs from the planned protocol nonce.
3004        request.inner.nonce = Some(0);
3005        let envelope = TempoTxEnvelope::AA(
3006            request
3007                .clone()
3008                .build_aa()
3009                .unwrap()
3010                .into_signed(tempo_primitives::TempoSignature::default()),
3011        );
3012        let kinds = [
3013            SendTransactionKind::Unlocked(request.clone()),
3014            SendTransactionKind::Signed(envelope.clone()),
3015            SendTransactionKind::PreparedRaw(
3016                Bytes::from(envelope.encoded_2718()),
3017                envelope.trie_hash(),
3018            ),
3019        ];
3020        let sender = request.inner.from.unwrap();
3021        let mut signed_plan =
3022            TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::Signed {
3023                tx: envelope,
3024                from: sender,
3025            });
3026        signed_plan.contract_address = Some(sender.create(7));
3027        for kind in kinds {
3028            for planned in [&planned, &signed_plan] {
3029                for actual in [6, 7, 8] {
3030                    let asserter = Asserter::new();
3031                    let provider = alloy_provider::ProviderBuilder::<_, _, TempoNetwork>::default()
3032                        .connect_mocked_client(asserter.clone());
3033                    asserter.push_success(&format!("{actual:#x}"));
3034                    let result = kind.validate_expiring_create_nonce(&provider, planned).await;
3035                    if actual == 7 {
3036                        result.unwrap();
3037                    } else {
3038                        let expected = format!(
3039                            "CREATE address changed unexpectedly while sending transactions. Expected {} got {} from provider nonce.",
3040                            sender.create(7),
3041                            sender.create(actual)
3042                        );
3043                        assert_eq!(result.unwrap_err().to_string(), expected);
3044                    }
3045                }
3046            }
3047        }
3048        // Expiring CALLs have no protocol nonce to synchronize.
3049        request.inner.to = Some(TxKind::Call(Address::with_last_byte(2)));
3050        let provider = alloy_provider::ProviderBuilder::<_, _, TempoNetwork>::default()
3051            .connect_mocked_client(Asserter::new());
3052        SendTransactionKind::Unlocked(request.clone())
3053            .validate_expiring_create_nonce(
3054                &provider,
3055                &TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(request)),
3056            )
3057            .await
3058            .unwrap();
3059    }
3060
3061    #[tokio::test]
3062    async fn preparation_preserves_signed_payload_without_rpc() {
3063        let envelope = TxEnvelope::decode_2718_exact(SIGNED_TX).unwrap();
3064        let hash = envelope.trie_hash();
3065        let provider = alloy_provider::ProviderBuilder::new()
3066            .disable_recommended_fillers()
3067            .connect_mocked_client(Asserter::new());
3068        for input in [
3069            SendTransactionKind::<Ethereum>::Signed(envelope),
3070            SendTransactionKind::PreparedRaw(Bytes::from_static(SIGNED_TX), hash),
3071        ] {
3072            let prepared = input
3073                .prepare_for_durable_send(&provider, true, false, true, 130, None)
3074                .await
3075                .unwrap();
3076            let PreparedTransaction::Raw(payload, prepared_hash) = prepared else {
3077                panic!("signed transactions must become fixed raw submissions");
3078            };
3079            assert_eq!(payload.as_ref(), SIGNED_TX);
3080            assert_eq!(prepared_hash, hash);
3081        }
3082    }
3083
3084    #[tokio::test]
3085    async fn estimate_gas_multiplies_large_estimates_without_overflow() {
3086        for (estimate, multiplier, expected) in
3087            [(u64::MAX / 2, 130, Some(11_990_383_647_911_208_549)), (u64::MAX, 200, None)]
3088        {
3089            let asserter = Asserter::new();
3090            let provider: RootProvider<Ethereum> =
3091                alloy_provider::ProviderBuilder::default().connect_mocked_client(asserter.clone());
3092            asserter.push_success(&alloy_primitives::U64::from(estimate));
3093            let mut tx = alloy_rpc_types::TransactionRequest::default();
3094
3095            let result = estimate_gas(&mut tx, &provider, multiplier, false, false).await;
3096
3097            assert_eq!(result.is_ok(), expected.is_some());
3098            assert_eq!(tx.gas, expected);
3099        }
3100    }
3101}