Skip to main content

cast/cmd/
run.rs

1use super::{MAX_CONCURRENT_RPC_REQUESTS, fetch_code_via_rpc};
2use crate::{
3    debug::{ensure_remote_trace_context_unchanged, handle_traces, resolve_remote_trace_hardfork},
4    evm_version::probe_evm_version,
5    rpc_trace::{
6        call_frame_to_arena, call_tracer_config, is_method_not_found_error, is_missing_state_error,
7        is_missing_state_message,
8    },
9    traces::TraceKind,
10    utils::{
11        apply_chain_and_block_specific_env_changes_for_chain,
12        apply_chain_specific_tx_replay_env_changes_for_chain, block_env_from_header,
13    },
14};
15use alloy_consensus::{
16    BlockHeader, EthereumTxEnvelope, Transaction, TxEip4844Variant,
17    transaction::{Recovered, SignerRecoverable},
18};
19use alloy_eips::{BlockNumHash, eip7928::compute_block_access_list_hash};
20use alloy_network::{
21    AnyNetwork, AnyRpcBlock, AnyRpcTransaction, AnyTransactionReceipt, AnyTxEnvelope,
22    BlockResponse, Network, ReceiptResponse, TransactionResponse, primitives::HeaderResponse,
23};
24use alloy_primitives::{
25    Address, B256, Bytes, U256,
26    map::{AddressHashMap, AddressSet, B256HashMap},
27};
28use alloy_provider::{Provider, ext::DebugApi};
29use alloy_rpc_types::{
30    BlockId, BlockTransactions,
31    trace::geth::{CallFrame, GethDebugTracingOptions, GethTrace, PreStateConfig},
32};
33use alloy_transport::TransportError;
34use clap::Parser;
35use evm2::{
36    EvmFeatures,
37    evm::bal::{Bal, BlockAccessIndex},
38};
39use eyre::{Result, WrapErr};
40use foundry_cli::{
41    opts::{EtherscanOpts, RpcOpts, TracingArgs},
42    utils::{TraceResult, init_progress},
43};
44use foundry_common::{
45    SYSTEM_TRANSACTION_TYPE, is_known_system_sender,
46    provider::{ProviderBuilder, RetryProvider},
47    shell,
48};
49use foundry_compilers::artifacts::EvmVersion;
50use foundry_config::{
51    Config, TracingConfig,
52    figment::{
53        self, Metadata, Profile,
54        value::{Dict, Map},
55    },
56};
57use foundry_evm::{
58    core::evm::{
59        EthEvmNetwork, EvmEnvFor, EvmFactoryFor, FoundryEvmFactory, FoundryEvmNetwork,
60        FoundryTxConversion, TempoEvmNetwork, TxFor, TypesFor,
61    },
62    executors::{Executor, ExecutorBuilder, TracingExecutor},
63    hardforks::FoundryHardfork,
64    opts::EvmOpts,
65    traces::{InternalTraceMode, SparsedTraceArena, TraceContext, TraceRequirements},
66};
67use foundry_evm_networks::{NetworkConfigs, NetworkVariant, arbitrum};
68use futures::{StreamExt, TryFutureExt};
69use std::sync::Arc;
70
71#[cfg(feature = "base")]
72use foundry_evm::core::evm::BaseEvmNetwork;
73
74#[cfg(feature = "monad")]
75use foundry_common::MONAD_SYSTEM_ADDRESS;
76#[cfg(feature = "monad")]
77use foundry_evm::core::evm::{BlockContext, ChainFor, FoundryEvmExt, MonadEvmNetwork};
78
79#[cfg(feature = "optimism")]
80use foundry_evm::core::evm::OpEvmNetwork;
81
82/// Points at the remote trace when a transaction cannot be replayed locally.
83const REMOTE_TRACE_HINT: &str = "`--debug-trace-transaction` renders the node's own trace instead";
84
85/// CLI arguments for `cast run`.
86#[derive(Clone, Debug, Parser)]
87pub struct RunArgs {
88    /// The transaction hash.
89    tx_hash: String,
90
91    /// Opens the transaction in the debugger.
92    #[arg(long, short)]
93    debug: bool,
94
95    /// Print out opcode traces.
96    #[arg(long, short)]
97    trace_printer: bool,
98
99    /// Executes the transaction only with the state from the previous block.
100    ///
101    /// May result in different results than the live execution!
102    #[arg(long)]
103    quick: bool,
104
105    /// Do not use the block access list (BAL) of the transaction's block.
106    ///
107    /// If the node serves an EIP-7928 block access list, cast reads the transaction's prestate
108    /// from it instead of replaying the earlier transactions of the block. With this flag, the
109    /// block is always replayed.
110    #[arg(long)]
111    no_bal: bool,
112
113    /// Whether to attempt local replay of system transactions.
114    ///
115    /// Without this flag, ordinary block replay leaves out system transactions mined before the
116    /// target and warns about each one. ArbOS internal transactions (type `0x6a`) are always left
117    /// out without a warning. Replay support depends on the selected network. Canonical Monad
118    /// system transactions are replayed regardless of this flag.
119    #[arg(long, alias = "sys")]
120    replay_system_txes: bool,
121
122    /// Use debug_traceTransaction to fetch the prestate instead of replaying the block.
123    ///
124    /// This is significantly faster than replaying all previous transactions in the block, but
125    /// requires the node to expose the `debug_` namespace (most public RPCs don't). If the call
126    /// or response can't be used, cast silently falls back to the block access list, then to
127    /// replaying the block.
128    #[arg(long, default_value_t = false)]
129    prestate_tracer: bool,
130
131    /// Fetch the transaction's trace from the node via `debug_traceTransaction` (callTracer) and
132    /// render it, instead of re-executing the transaction locally.
133    ///
134    /// This skips the block replay entirely, so it is fast and reflects exactly what happened
135    /// on-chain, including chain-specific EVM behavior a local replay may not reproduce, but it
136    /// requires the node to expose the `debug_` namespace. The result is a call-tree view:
137    /// nested calls, value, gas, emitted logs and revert data. It does not provide the
138    /// opcode-level detail of a local run, so the local-execution-only flags (`--debug`,
139    /// `--decode-internal`, `--trace-printer`, `--quick`, `--no-bal`, `--prestate-tracer`,
140    /// `--evm-version`) do not apply.
141    #[arg(
142        long,
143        default_value_t = false,
144        conflicts_with_all = ["debug", "decode_internal", "trace_printer", "quick", "no_bal", "prestate_tracer", "evm_version"]
145    )]
146    debug_trace_transaction: bool,
147
148    #[command(flatten)]
149    tracing: TracingArgs,
150
151    /// Deprecated short alias for `--labels`.
152    #[arg(short = 'l', value_name = "ADDRESS:LABEL", hide = true)]
153    legacy_labels: Vec<String>,
154
155    #[command(flatten)]
156    etherscan: EtherscanOpts,
157
158    #[command(flatten)]
159    rpc: RpcOpts,
160
161    /// The EVM version to use.
162    ///
163    /// Overrides the version specified in the config.
164    #[arg(long)]
165    evm_version: Option<EvmVersion>,
166
167    /// Use current project artifacts for trace decoding.
168    #[arg(long, visible_alias = "la")]
169    pub with_local_artifacts: bool,
170
171    /// Disable block gas limit check.
172    ///
173    /// Always implied: a mined transaction already passed its chain's own check.
174    #[arg(long)]
175    pub disable_block_gas_limit: bool,
176
177    /// Enable the tx gas limit checks as imposed by Osaka (EIP-7825) and Amsterdam (EIP-8037).
178    #[arg(long)]
179    pub enable_tx_gas_limit: bool,
180}
181
182/// Target transaction resolved up front by [`RunArgs::fetch_target`], before any per-network
183/// preparation.
184struct TargetFetch {
185    tx: AnyRpcTransaction,
186    provider: RetryProvider,
187}
188
189/// Where the state right before the target transaction comes from.
190///
191/// `RunArgs::prepare` picks the first source that applies, in this order: `--quick`, a
192/// prestate trace (`--prestate-tracer`), the block's access list, and finally replaying the
193/// earlier transactions of the block.
194enum PrestateSource {
195    /// `--quick`: the target executes directly on the parent block's state.
196    ParentState,
197    /// The prestate returned by `debug_traceTransaction` was applied to the executor.
198    PrestateTrace,
199    /// The block access list of the target's block, from which the backend reads the writes of
200    /// the earlier transactions.
201    BlockAccessList(Arc<Bal>),
202    /// The transactions before the target in its block are replayed.
203    BlockReplay,
204}
205
206impl PrestateSource {
207    /// Whether the transactions before the target are executed by a block replay.
208    ///
209    /// Only the ordinary path reads a block access list; other paths, such as Monad's, still
210    /// replay the block prefix.
211    const fn replays_prefix(&self) -> bool {
212        matches!(self, Self::BlockAccessList(_) | Self::BlockReplay)
213    }
214}
215
216/// Chain-specific gas limits for transactions replayed by `cast run`.
217enum ReplayGasLimits {
218    Unchanged,
219    Nitro(B256HashMap<u64>),
220}
221
222/// State assembled by [`RunArgs::prepare`] and consumed by the network-specific `execute_*`
223/// methods below.
224struct PreparedRun<FEN: FoundryEvmNetwork> {
225    args: RunArgs,
226    config: Box<Config>,
227    tracing: TracingConfig,
228    tx: AnyRpcTransaction,
229    block: Option<AnyRpcBlock>,
230    evm_env: EvmEnvFor<FEN>,
231    executor: TracingExecutor<FEN>,
232    trace_context: TraceContext,
233    /// Where the state right before the target transaction comes from.
234    prestate: PrestateSource,
235    replay_gas_limits: ReplayGasLimits,
236    /// The target's receipt, which the replay is checked against.
237    receipt: Option<AnyTransactionReceipt>,
238    /// Provider of the Monad-specific `execute_monad` path.
239    #[cfg(feature = "monad")]
240    monad_provider: RetryProvider,
241}
242
243impl RunArgs {
244    fn resolve_tracing(&self, config: &TracingConfig, verbosity: u8) -> TracingConfig {
245        if self.debug_trace_transaction {
246            self.tracing.resolve_call_tracer(config, verbosity)
247        } else {
248            self.tracing.resolve(config, verbosity)
249        }
250    }
251
252    /// Applies the network and tracing options to `config` and returns the resolved tracing
253    /// config.
254    fn configure_tracing(&mut self, config: &mut Config, evm_opts: &EvmOpts) -> TracingConfig {
255        config.networks = evm_opts.networks;
256        self.tracing.labels.append(&mut self.legacy_labels);
257        config.tracing = self.resolve_tracing(&config.tracing, shell::verbosity());
258        config.tracing.clone()
259    }
260
261    /// Executes the transaction by replaying it
262    ///
263    /// This replays the entire block the transaction was mined in unless `quick` is set to true
264    /// or the node serves a block access list for the block.
265    ///
266    /// Note: This executes the transaction(s) as is: Cheatcodes are disabled
267    pub async fn run(self) -> Result<()> {
268        let figment = self.rpc.clone().into_figment(self.with_local_artifacts).merge(&self);
269        let (mut config, mut evm_opts) = super::load_cast_config_and_evm_opts(figment)?;
270        if config.eth_rpc_url.is_none()
271            && let Some(chain) = self.etherscan.chain
272        {
273            let alias = chain.to_string();
274            if config.rpc_endpoints.contains_key(&alias) {
275                config.eth_rpc_url = Some(alias);
276            }
277        }
278        evm_opts.fork_url = Some(config.get_rpc_url_or_localhost_http()?.into_owned());
279
280        // Auto-detect network from fork chain ID when not explicitly configured.
281        evm_opts.infer_network_from_fork().await?;
282
283        if self.debug_trace_transaction {
284            return self.remote_trace(config, evm_opts).await;
285        }
286
287        self.replay(config, evm_opts).await.map_err(|err| {
288            if err.chain().any(|cause| is_missing_state_message(&cause.to_string())) {
289                err.wrap_err(
290                    "the RPC endpoint does not have the historical state for the transaction's \
291                     block; use an archive endpoint",
292                )
293            } else {
294                err
295            }
296        })
297    }
298
299    /// Replays the transaction locally with the EVM of its network.
300    async fn replay(self, config: Box<Config>, evm_opts: EvmOpts) -> Result<()> {
301        match evm_opts.networks.execution_network() {
302            NetworkVariant::Tempo => {
303                self.run_with_evm(config, evm_opts, ExecutorBuilder::<TempoEvmNetwork>::new()).await
304            }
305            #[cfg(feature = "base")]
306            NetworkVariant::Base => {
307                self.run_with_evm(config, evm_opts, ExecutorBuilder::<BaseEvmNetwork>::new()).await
308            }
309            #[cfg(feature = "monad")]
310            NetworkVariant::Monad => {
311                let target = self.fetch_target(&config).await?;
312                let mut run = self
313                    .prepare::<MonadEvmNetwork>(
314                        config,
315                        evm_opts,
316                        target,
317                        ExecutorBuilder::<MonadEvmNetwork>::new(),
318                    )
319                    .await?;
320                let result = run.execute_monad().await?;
321                run.finish(result).await
322            }
323            #[cfg(feature = "optimism")]
324            NetworkVariant::Optimism => {
325                self.run_with_evm(config, evm_opts, ExecutorBuilder::<OpEvmNetwork>::new()).await
326            }
327            NetworkVariant::Ethereum => {
328                self.run_with_evm(config, evm_opts, ExecutorBuilder::<EthEvmNetwork>::new()).await
329            }
330        }
331    }
332
333    async fn run_with_evm<FEN: FoundryEvmNetwork>(
334        self,
335        config: Box<Config>,
336        evm_opts: EvmOpts,
337        executor_builder: ExecutorBuilder<FEN>,
338    ) -> Result<()> {
339        let target = self.fetch_target(&config).await?;
340        let endpoint_is_anvil = evm_opts
341            .fork_endpoint
342            .as_ref()
343            .is_some_and(|identity| identity.reported_hardfork.is_some());
344        if let Some(chain) = target.tx.chain_id().map(alloy_chains::Chain::from_id)
345            && chain.is_elastic()
346            && !endpoint_is_anvil
347        {
348            eyre::bail!(
349                "{chain} executes EraVM bytecode, which cannot be replayed locally; \
350                 {REMOTE_TRACE_HINT}"
351            );
352        }
353        if is_system_transaction(&target.tx) && !self.replay_system_txes {
354            eyre::bail!(
355                "{:?} is a system transaction.\nReplaying system transactions is currently not supported.",
356                target.tx.tx_hash()
357            );
358        }
359        let mut run = self.prepare::<FEN>(config, evm_opts, target, executor_builder).await?;
360        let result = run.execute_ordinary()?;
361        run.finish(result).await
362    }
363
364    /// `AnyNetwork` rather than `FEN::Network`: chains such as Arbitrum, Celo and the OP-stack
365    /// forks Foundry does not route to a dedicated network put transaction types the strict
366    /// Ethereum envelope cannot decode into every block, which would fail the full block fetch in
367    /// `prepare` for the whole chain. Execution still uses `FEN`.
368    async fn fetch_target(&self, config: &Config) -> Result<TargetFetch> {
369        let compute_units_per_second = if self.rpc.common.no_rpc_rate_limit {
370            Some(u64::MAX)
371        } else {
372            self.rpc.common.compute_units_per_second
373        };
374        let provider = ProviderBuilder::<AnyNetwork>::from_config(config)?
375            .compute_units_per_second_opt(compute_units_per_second)
376            .build()?;
377        let tx_hash = self.tx_hash.parse().wrap_err("invalid tx hash")?;
378        let tx = provider
379            .get_transaction_by_hash(tx_hash)
380            .await
381            .wrap_err_with(|| format!("tx not found: {tx_hash:?}"))?
382            .ok_or_else(|| eyre::eyre!("tx not found: {tx_hash:?}"))?;
383        ensure_requested_transaction(tx_hash, &tx)?;
384        Ok(TargetFetch { tx, provider })
385    }
386
387    /// Fetches the trace from the node via `debug_traceTransaction` (callTracer) instead of
388    /// re-executing the transaction locally. The node already holds the transaction's exact
389    /// pre-state and EVM rules, so this needs no block replay and no local executor; it also
390    /// handles system transactions.
391    async fn remote_trace(mut self, mut config: Box<Config>, evm_opts: EvmOpts) -> Result<()> {
392        let TargetFetch { tx, provider } = self.fetch_target(&config).await?;
393        let tx_hash = tx.tx_hash();
394        let tracing = self.configure_tracing(&mut config, &evm_opts);
395        let with_local_artifacts = self.with_local_artifacts;
396
397        let endpoint_identity = evm_opts.fork_endpoint_identity().await?;
398        let tx_inclusion = tx
399            .block_hash_num()
400            .ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))?;
401
402        let frame = call_tracer_frame(
403            provider
404                .debug_trace_transaction(
405                    tx_hash,
406                    GethDebugTracingOptions::call_tracer(call_tracer_config()),
407                )
408                .await,
409            "debug_traceTransaction",
410            "drop `--debug-trace-transaction` to re-execute the transaction locally",
411            "the transaction's block; use an archive endpoint",
412        )?;
413
414        let receipt = provider
415            .get_transaction_receipt(tx_hash)
416            .await?
417            .ok_or_else(|| eyre::eyre!("tx receipt not found: {:?}", tx_hash))?;
418        ensure_remote_transaction_inclusion(
419            tx_hash,
420            tx_inclusion,
421            receipt.block_hash_num(),
422            "transaction receipt",
423        )?;
424
425        let transaction_block = provider.get_block_by_hash(tx_inclusion.hash).await?;
426        ensure_remote_transaction_inclusion(
427            tx_hash,
428            tx_inclusion,
429            transaction_block.as_ref().map(block_num_hash),
430            "block fetched by hash",
431        )?;
432        let Some(transaction_block) = transaction_block else {
433            unreachable!("ensure_remote_transaction_inclusion errors when the block is missing")
434        };
435
436        let root_create_address = Transaction::to(&tx)
437            .is_none()
438            .then(|| receipt.contract_address().unwrap_or_else(|| tx.from().create(tx.nonce())));
439        let arena = SparsedTraceArena {
440            arena: call_frame_to_arena(&frame, root_create_address),
441            ignored: Default::default(),
442            diagnostics: Default::default(),
443            debug_steps: None,
444        };
445        let result = TraceResult {
446            success: receipt.status(),
447            traces: Some(vec![(TraceKind::Execution, arena)]),
448            gas_used: receipt.gas_used(),
449        };
450
451        // Local-artifact labeling matches deployed runtime bytecode against the project
452        // artifacts. There is no local executor on this path, so fetch the code over RPC for the
453        // addresses in the trace, at the transaction's block. Skip the extra round-trips unless
454        // local artifacts were requested.
455        let contracts_bytecode = if with_local_artifacts {
456            fetch_transaction_contracts_bytecode_via_rpc(
457                &provider,
458                &result,
459                tx_hash,
460                BlockId::hash(tx_inclusion.hash),
461            )
462            .await
463        } else {
464            Default::default()
465        };
466
467        // The remote node executed this trace, so its reported family is authoritative for
468        // decoding even when the caller selected a compatible local EVM implementation.
469        let chain = alloy_chains::Chain::from_id(endpoint_identity.source_chain_id);
470        let resolved_hardfork = resolve_remote_trace_hardfork(
471            config.hardfork,
472            &endpoint_identity,
473            Some(transaction_block.header().timestamp()),
474        );
475        let final_endpoint_identity = evm_opts.fork_endpoint_identity().await?;
476        ensure_remote_trace_context_unchanged(&endpoint_identity, &final_endpoint_identity)?;
477
478        let current_tx = provider.get_transaction_by_hash(tx_hash).await?;
479        if let Some(current_tx) = &current_tx {
480            ensure_requested_transaction(tx_hash, current_tx)?;
481        }
482        ensure_remote_transaction_inclusion(
483            tx_hash,
484            tx_inclusion,
485            current_tx.and_then(|tx| tx.block_hash_num()),
486            "transaction lookup",
487        )?;
488        let canonical_block = provider.get_block_by_number(tx_inclusion.number.into()).await?;
489        ensure_remote_transaction_inclusion(
490            tx_hash,
491            tx_inclusion,
492            canonical_block.as_ref().map(block_num_hash),
493            "canonical block lookup",
494        )?;
495        handle_traces(
496            result,
497            &config,
498            {
499                let context =
500                    TraceContext::new(chain, endpoint_identity.network_profile, resolved_hardfork);
501                context.with_hardfork(context.decoding_hardfork(&config))
502            },
503            &contracts_bytecode,
504            &tracing,
505            with_local_artifacts,
506            false,
507        )
508        .await
509    }
510
511    async fn prepare<FEN: FoundryEvmNetwork>(
512        mut self,
513        mut config: Box<Config>,
514        evm_opts: EvmOpts,
515        target: TargetFetch,
516        executor_builder: ExecutorBuilder<FEN>,
517    ) -> Result<PreparedRun<FEN>> {
518        let TargetFetch { tx, provider } = target;
519        let tx_hash = tx.tx_hash();
520        let tracing = self.configure_tracing(&mut config, &evm_opts);
521
522        let tx_block_number = tx
523            .block_number()
524            .ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))?;
525
526        // we need to fork off the parent block
527        config.fork_block_number = Some(tx_block_number - 1);
528
529        let create2_deployer = evm_opts.create2_deployer;
530        let fork_prefetch = evm_opts.fork_prefetch;
531        let (block, receipt, mut fork) = tokio::try_join!(
532            // fetch the block the transaction was mined in
533            provider.get_block(tx_block_number.into()).full().into_future().map_err(Into::into),
534            // The receipt only backs the check after the replay, so a failed lookup skips that
535            // check instead of failing the run.
536            async { Ok(provider.get_transaction_receipt(tx_hash).await.ok().flatten()) },
537            TracingExecutor::<FEN>::get_fork(&mut config, evm_opts)
538        )?;
539        let chain = fork.context().chain();
540        let networks = fork.context().networks();
541
542        let mut evm_version = self.evm_version;
543        // Mined transactions already passed the block gas limit check their chain applies, and
544        // some chains admit transactions whose gas limit exceeds it: BSC validator transactions
545        // carry a gas limit of `i64::MAX`. Re-applying the check can only reject a transaction
546        // the chain accepted.
547        fork.evm_env.set_feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK, false);
548
549        // By default do not enforce transaction gas limits imposed by Osaka (EIP-7825) and
550        // Amsterdam (EIP-8037).
551        // Users can opt-in to enable these limits by setting `enable_tx_gas_limit` to true.
552        if !self.enable_tx_gas_limit {
553            fork.evm_env.version.tx_gas_limit_cap = u64::MAX;
554            fork.evm_env.version.tx_total_gas_cap = u64::MAX;
555        }
556
557        // Replays enforce the chain's contract size limits rather than Foundry's unlimited
558        // default.
559        let default_version =
560            EvmFactoryFor::<FEN>::default().version(fork.evm_env.spec, fork.evm_env.chain_id());
561        fork.evm_env.version.max_code_size = default_version.max_code_size;
562        fork.evm_env.version.max_initcode_size = default_version.max_initcode_size;
563        fork.evm_env.block.number = U256::from(tx_block_number);
564
565        let mut parent_beacon_block_root = None;
566        if let Some(block) = &block {
567            fork.evm_env.block = block_env_from_header::<TypesFor<FEN>>(block.header());
568            parent_beacon_block_root = block.header().parent_beacon_block_root();
569
570            // Unless explicitly configured, resolve the correct spec for the block using the same
571            // approach as reth: walk known chain activation conditions to find the latest active
572            // fork. For unknown chains, probe the node for the features it executes at the block,
573            // falling back to a blob-gas heuristic if the node rejects the probe.
574            if evm_version.is_none()
575                && config.hardfork.is_none()
576                && FoundryHardfork::from_chain_and_timestamp(chain.id(), block.header().timestamp())
577                    .is_none()
578            {
579                let probed = probe_evm_version(&provider, BlockId::number(tx_block_number)).await;
580                evm_version = probed.or_else(|| {
581                    block.header().excess_blob_gas().is_some().then_some(EvmVersion::Cancun)
582                });
583            }
584            apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
585                &mut fork.evm_env,
586                block,
587                chain.id(),
588                config.networks,
589            );
590        }
591        fork.resolve_spec(&config, evm_version);
592        fork.extend_precompile_labels(&mut config);
593
594        apply_chain_specific_tx_replay_env_changes_for_chain(&mut fork.evm_env, chain.id());
595
596        let trace_context = fork.context();
597
598        let mut executor = fork.into_executor(
599            executor_builder,
600            TraceRequirements::none(),
601            create2_deployer,
602            None,
603        )?;
604        executor.inspector_mut().fork_prefetch(fork_prefetch);
605        // The fork is pinned to the parent block, but the replayed transactions execute in the
606        // target's block, which block queries such as Arbitrum's `ArbSys.arbBlockNumber()` must
607        // report.
608        executor.backend_mut().set_fork_block_number_override(tx_block_number);
609
610        let evm_env = *executor.evm_env();
611        // EIP-6780 activates with Cancun in every network family.
612        let is_cancun = evm_env.version.feature(EvmFeatures::EIP6780);
613
614        if let Some(parent_beacon_block_root) =
615            parent_beacon_block_root_for_network(networks, is_cancun, parent_beacon_block_root)
616        {
617            executor.apply_beacon_root(parent_beacon_block_root)?;
618        }
619
620        // Set the state to the moment right before the transaction.
621        //
622        // When `--prestate-tracer` is set, opportunistically try to fetch the prestate directly
623        // via `debug_traceTransaction` (much faster than replaying the block). This requires the
624        // `debug_` namespace, which most nodes don't expose, so it is opt-in and silently falls
625        // back to the block access list, then to replaying previous transactions in the block,
626        // if the call or parsing fails.
627        let mut prestate =
628            if self.quick { PrestateSource::ParentState } else { PrestateSource::BlockReplay };
629        if matches!(prestate, PrestateSource::BlockReplay) && self.prestate_tracer {
630            trace!(?tx_hash, "attempting to fetch prestate via debug_traceTransaction");
631            match provider
632                .debug_trace_transaction(
633                    tx_hash,
634                    GethDebugTracingOptions::prestate_tracer(PreStateConfig::default()),
635                )
636                .await
637            {
638                Ok(trace) => match trace.try_into_pre_state_frame() {
639                    Ok(pre_state_frame) => {
640                        executor.apply_prestate_trace(pre_state_frame.into_pre_state())?;
641                        prestate = PrestateSource::PrestateTrace;
642                        trace!("prestate trace applied successfully, skipping block replay");
643                    }
644                    Err(err) => {
645                        trace!(%err, "failed to parse prestate trace response");
646                    }
647                },
648                Err(err) => {
649                    trace!(?err, "debug_traceTransaction failed, falling back to block replay");
650                }
651            }
652        }
653
654        // A block access list (BAL) records every state write of the block by transaction index,
655        // so the target's prestate can be read from it instead of replaying the earlier
656        // transactions. Before Cancun, SELFDESTRUCT wipes storage the list does not enumerate.
657        // Explicit execution rules must replay the prefix: canonical writes may differ under
658        // the requested EVM version or hardfork.
659        if matches!(prestate, PrestateSource::BlockReplay)
660            && !self.no_bal
661            && self.evm_version.is_none()
662            && config.hardfork.is_none()
663            && is_cancun
664            && let Some(block) = &block
665            && let Some(bal) = fetch_block_access_list(&provider, block).await?
666        {
667            prestate = PrestateSource::BlockAccessList(bal);
668        }
669
670        let mut replay_tx_hashes = vec![tx_hash];
671        if matches!(prestate, PrestateSource::BlockReplay)
672            && let Some(block) = &block
673        {
674            replay_tx_hashes.extend(
675                full_transactions(block)?
676                    .iter()
677                    .take_while(|tx| tx.tx_hash() != tx_hash)
678                    .filter(|tx| {
679                        !is_arbos_internal_transaction(tx)
680                            && (!is_system_transaction(tx) || self.replay_system_txes)
681                    })
682                    .map(TransactionResponse::tx_hash),
683            );
684        }
685        let replay_gas_limits =
686            ReplayGasLimits::fetch(chain.id(), &provider, replay_tx_hashes).await?;
687
688        Ok(PreparedRun {
689            args: self,
690            config,
691            tracing,
692            tx,
693            block,
694            evm_env,
695            executor,
696            trace_context,
697            prestate,
698            replay_gas_limits,
699            receipt,
700            #[cfg(feature = "monad")]
701            monad_provider: provider,
702        })
703    }
704}
705
706/// Fetches the block access list of `block`, if the node serves one that matches the header.
707async fn fetch_block_access_list(
708    provider: &RetryProvider,
709    block: &AnyRpcBlock,
710) -> Result<Option<Arc<Bal>>> {
711    let header = block.header();
712    let bal = match provider.get_block_access_list(BlockId::hash(header.hash)).await {
713        Ok(Some(bal)) => bal,
714        Ok(None) => return Ok(None),
715        Err(err) => {
716            trace!(%err, "block access list unavailable, falling back to block replay");
717            return Ok(None);
718        }
719    };
720    if let Some(hash) = header.block_access_list_hash()
721        && compute_block_access_list_hash(&bal) != hash
722    {
723        sh_warn!(
724            "block access list of block {} does not match its header, replaying the block instead",
725            header.number()
726        )?;
727        return Ok(None);
728    }
729    Ok(Some(Arc::new(Bal::try_from(bal).wrap_err("invalid block access list")?)))
730}
731
732impl<FEN: FoundryEvmNetwork> PreparedRun<FEN> {
733    fn transaction(&self, tx: &AnyRpcTransaction) -> Result<Recovered<TxFor<FEN>>> {
734        match self.replay_gas_limits.apply(tx)? {
735            Some(tx) => TypesFor::<FEN>::tx_from_any_rpc(&tx),
736            None => TypesFor::<FEN>::tx_from_any_rpc(tx),
737        }
738    }
739
740    /// Prepares the executor for the target transaction: enables tracing and, when the sender
741    /// was forged, disables the balance check.
742    fn prepare_target(&mut self) {
743        let requirements = TraceRequirements::none()
744            .with_calls(true)
745            .with_debug_recording(self.args.debug)
746            .with_decode_internal(if self.tracing.decode_internal {
747                InternalTraceMode::Full
748            } else {
749                InternalTraceMode::None
750            })
751            .with_state_changes(self.tracing.verbosity > 4);
752        self.executor.set_trace_requirements(requirements);
753        self.executor.set_trace_printer(self.args.trace_printer);
754
755        let sender_is_forged = match &*self.tx.inner.inner {
756            AnyTxEnvelope::Ethereum(inner) => {
757                inner.recover_signer().is_ok_and(|signer| signer != self.tx.from())
758            }
759            AnyTxEnvelope::Unknown(_) => true,
760        };
761        if sender_is_forged {
762            self.evm_env.set_feature(EvmFeatures::BALANCE_CHECK, false);
763        }
764    }
765
766    /// Returns the index of the target transaction in its block.
767    fn target_index(&self) -> Result<usize> {
768        let Some(block) = &self.block else { return Ok(0) };
769        full_transactions(block)?
770            .iter()
771            .position(|candidate| candidate.tx_hash() == self.tx.tx_hash())
772            .ok_or_else(|| {
773                eyre::eyre!("transaction {:?} is missing from its block", self.tx.tx_hash())
774            })
775    }
776
777    /// Calls `f` for every transaction mined before the target, unless the block replay was
778    /// skipped (`--quick` or an applied prestate trace).
779    fn for_each_prefix_transaction(
780        &self,
781        target_index: usize,
782        mut f: impl FnMut(usize, &AnyRpcTransaction) -> Result<()>,
783    ) -> Result<()> {
784        if !self.prestate.replays_prefix() {
785            return Ok(());
786        }
787        sh_status!("Executing previous transactions from the block.")?;
788        let Some(block) = &self.block else { return Ok(()) };
789        let txs = full_transactions(block)?;
790        let pb = init_progress(txs.len() as u64, "tx");
791        for (index, tx) in txs.iter().take(target_index).enumerate() {
792            if let Some(to) = Transaction::to(tx) {
793                trace!(tx=?tx.tx_hash(), ?to, "preparing previous call transaction");
794            } else {
795                trace!(tx=?tx.tx_hash(), "preparing previous create transaction");
796            }
797            f(index, tx)?;
798            pb.set_position((index + 1) as u64);
799        }
800        Ok(())
801    }
802
803    fn trace_kind(&self) -> TraceKind {
804        if let Some(to) = Transaction::to(&self.tx) {
805            trace!(tx=?self.tx.tx_hash(), ?to, "executing call transaction");
806            TraceKind::Execution
807        } else {
808            trace!(tx=?self.tx.tx_hash(), "executing create transaction");
809            TraceKind::Deployment
810        }
811    }
812
813    fn execute_ordinary(&mut self) -> Result<TraceResult> {
814        // Decode the target transaction before replaying the block: an envelope this build
815        // can't decode should fail fast.
816        let target = self.transaction(&self.tx).wrap_err_with(|| {
817            format!(
818                "cannot replay transaction {:?} locally; {REMOTE_TRACE_HINT}",
819                self.tx.tx_hash()
820            )
821        })?;
822        let target_index = self.target_index()?;
823        self.prepare_target();
824
825        let mut replay = Vec::new();
826        if let PrestateSource::BlockAccessList(bal) = &self.prestate {
827            let bal = Arc::clone(bal);
828            // Index 0 holds the pre-block system writes and transaction `i` is index `i + 1`, so
829            // reads positioned at the target's own index see exactly the earlier writes.
830            trace!("reading prestate from block access list, skipping block replay");
831            self.executor
832                .backend_mut()
833                .set_bal(bal, BlockAccessIndex::new(target_index as u64 + 1));
834        } else {
835            let block_number = self.evm_env.block.number;
836            let replay_system_txes = self.args.replay_system_txes;
837            let mut skipped_system_txes = Vec::new();
838            self.for_each_prefix_transaction(target_index, |_, tx| {
839                // ArbOS internal transactions open every Arbitrum block, Orbit chains included,
840                // and also report batch postings mid-block. They update ArbOS bookkeeping, which
841                // the replay cannot execute, so they are left out without a warning.
842                if is_arbos_internal_transaction(tx) {
843                    return Ok(());
844                }
845                if !is_system_transaction(tx) || replay_system_txes {
846                    let replayed = self.transaction(tx).wrap_err_with(|| {
847                        format!(
848                            "Failed to prepare transaction: {:?} in block {}; `--quick` skips the \
849                             transactions before the target, and {REMOTE_TRACE_HINT}",
850                            tx.tx_hash(),
851                            block_number
852                        )
853                    })?;
854                    replay.push((tx.tx_hash(), replayed));
855                } else {
856                    skipped_system_txes.push(tx.tx_hash());
857                }
858                Ok(())
859            })?;
860            if !skipped_system_txes.is_empty() {
861                sh_warn!(
862                    "the replay skips system transactions before the target, so their state \
863                     changes are missing: {skipped_system_txes:?}; `--replay-system-txes` \
864                     attempts local replay where supported; {REMOTE_TRACE_HINT}"
865                )?;
866            }
867        }
868        let result = self.executor.transact_with_block_replay(
869            self.evm_env,
870            &target,
871            Transaction::kind(&self.tx),
872            &replay,
873        )?;
874        let trace_kind = self.trace_kind();
875        trace!(tx_hash=?self.tx.tx_hash(), "completed execution");
876        Ok(TraceResult::from_raw(result, trace_kind))
877    }
878
879    async fn finish(self, result: TraceResult) -> Result<()> {
880        let contracts_bytecode = fetch_contracts_bytecode_from_trace(&self.executor, &result)?;
881        let (success, gas_used) = (result.success, result.gas_used);
882        handle_traces(
883            result,
884            &self.config,
885            self.trace_context,
886            &contracts_bytecode,
887            &self.tracing,
888            self.args.with_local_artifacts,
889            self.args.debug,
890        )
891        .await?;
892        self.warn_on_receipt_mismatch(success, gas_used)
893    }
894
895    /// Warns when the replay does not reproduce the target's receipt.
896    ///
897    /// A replay diverges when the chain applies rules the local EVM does not model or the replay
898    /// starts from different state, and the trace alone gives no sign of it.
899    fn warn_on_receipt_mismatch(&self, success: bool, gas_used: u64) -> Result<()> {
900        let Some(receipt) = &self.receipt else { return Ok(()) };
901        let outcome = |success: bool| if success { "succeeded" } else { "reverted" };
902        let mut differences = Vec::new();
903        if receipt.status() != success {
904            differences.push(format!(
905                "it {} on-chain but {} in the replay",
906                outcome(receipt.status()),
907                outcome(success)
908            ));
909        }
910        if let Some(expected) = self.expected_replay_gas(receipt)
911            && expected != gas_used
912        {
913            differences
914                .push(format!("it used {expected} gas on-chain but {gas_used} in the replay"));
915        }
916        if differences.is_empty() {
917            return Ok(());
918        }
919        let hint = if self.args.quick {
920            "`--quick` skips the transactions before it in the block, which can change the result; \
921             run without it to replay them first"
922        } else {
923            "The chain may apply rules the replay does not model; `--debug-trace-transaction` \
924             shows the node's own trace if it exposes the `debug` namespace"
925        };
926        sh_warn!(
927            "the replay does not match the transaction's receipt: {}. {hint}.",
928            differences.join(", and ")
929        )
930    }
931
932    /// Returns the gas the replay should report for `receipt`, or `None` if the receipt does not
933    /// record the gas the transaction executed.
934    fn expected_replay_gas(&self, receipt: &AnyTransactionReceipt) -> Option<u64> {
935        // Monad charges the full gas limit and reports it as the gas used.
936        if self.trace_context.networks().is_monad() {
937            return None;
938        }
939        let gas_used = receipt.gas_used();
940        if arbitrum::is_arbitrum_chain(self.trace_context.chain().id()) {
941            // Nitro folds the L1 posting cost into the receipt's gas used.
942            let l1_gas_used =
943                parse_nitro_l1_gas_used(receipt.other_fields().get("gasUsedForL1")).ok()?;
944            return gas_used.checked_sub(l1_gas_used);
945        }
946        Some(gas_used)
947    }
948}
949
950#[cfg(feature = "monad")]
951impl PreparedRun<MonadEvmNetwork> {
952    async fn execute_monad(&mut self) -> Result<TraceResult> {
953        // Monad protocol system transactions replay as the protocol system calls they are; the
954        // replay rejects a non-canonical envelope from the system sender.
955        if self.tx.from() != MONAD_SYSTEM_ADDRESS
956            && is_system_transaction(&self.tx)
957            && !self.args.replay_system_txes
958        {
959            eyre::bail!(
960                "{:?} is a system transaction.\nReplaying system transactions is currently not supported.",
961                self.tx.tx_hash()
962            );
963        }
964        let block = self.block.as_ref().ok_or_else(|| {
965            eyre::eyre!(
966                "block {} is required to reconstruct transaction context",
967                self.evm_env.block.number
968            )
969        })?;
970        let block_context = BlockContext::<MonadEvmNetwork>::fetch(&self.monad_provider, block)
971            .await
972            .wrap_err_with(|| {
973                format!(
974                    "cannot replay transaction {:?} locally; {REMOTE_TRACE_HINT}",
975                    self.tx.tx_hash()
976                )
977            })?;
978        // Decode the target transaction before replaying the block: an envelope this build
979        // can't decode should fail fast, not after paying for the entire prior-transaction
980        // replay.
981        let target = self.transaction(&self.tx)?;
982        let target_index = self.target_index()?;
983        self.prepare_target();
984
985        let mut replay = Vec::new();
986        let replay_system_txes = self.args.replay_system_txes;
987        self.for_each_prefix_transaction(target_index, |_, tx| {
988            // Canonical protocol transactions always replay; other system transactions only
989            // with `--replay-system-txes`.
990            let replayed = self.transaction(tx)?;
991            if !is_system_transaction(tx)
992                || replay_system_txes
993                || ChainFor::<MonadEvmNetwork>::is_protocol_transaction(&replayed)
994            {
995                replay.push((tx.tx_hash(), replayed));
996            }
997            Ok(())
998        })?;
999        // The replay records each prefix transaction into the context, so it starts at the
1000        // beginning of the block; without a prefix, the target takes its own position.
1001        let position = if replay.is_empty() { target_index } else { 0 };
1002        let result = self.executor.transact_with_monad_block_replay(
1003            self.evm_env,
1004            &target,
1005            Transaction::kind(&self.tx),
1006            &replay,
1007            block_context.before_transaction(position)?,
1008        )?;
1009        Ok(TraceResult::from_raw(result, self.trace_kind()))
1010    }
1011}
1012
1013fn is_system_transaction(tx: &AnyRpcTransaction) -> bool {
1014    is_known_system_sender(tx.from()) || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
1015}
1016
1017fn is_arbos_internal_transaction(tx: &AnyRpcTransaction) -> bool {
1018    tx.transaction_type() == Some(arbitrum::ARBITRUM_INTERNAL_TX_TYPE)
1019}
1020
1021fn full_transactions(block: &AnyRpcBlock) -> Result<&[AnyRpcTransaction]> {
1022    let BlockTransactions::Full(txs) = block.transactions() else {
1023        eyre::bail!("Could not get block txs");
1024    };
1025    Ok(txs)
1026}
1027
1028impl ReplayGasLimits {
1029    async fn fetch(chain_id: u64, provider: &RetryProvider, tx_hashes: Vec<B256>) -> Result<Self> {
1030        if !foundry_evm_networks::arbitrum::is_arbitrum_chain(chain_id) {
1031            return Ok(Self::Unchanged);
1032        }
1033
1034        let mut requests = futures::stream::iter(tx_hashes)
1035            .map(|tx_hash| fetch_nitro_l1_gas_used(provider, tx_hash))
1036            .buffer_unordered(MAX_CONCURRENT_RPC_REQUESTS);
1037        let mut gas_used = B256HashMap::default();
1038        while let Some(result) = requests.next().await {
1039            let (tx_hash, l1_gas_used) = result?;
1040            gas_used.insert(tx_hash, l1_gas_used);
1041        }
1042        Ok(Self::Nitro(gas_used))
1043    }
1044
1045    /// Returns `tx` with its replay gas limit, or `None` if it replays unchanged.
1046    fn apply(&self, tx: &AnyRpcTransaction) -> Result<Option<AnyRpcTransaction>> {
1047        let Self::Nitro(l1_gas_used) = self else { return Ok(None) };
1048        let tx_hash = tx.tx_hash();
1049        let l1_gas_used = l1_gas_used
1050            .get(&tx_hash)
1051            .ok_or_else(|| eyre::eyre!("receipt not found for Nitro transaction {tx_hash:?}"))?;
1052        let gas_limit = nitro_execution_gas_limit(tx_hash, tx.gas_limit(), *l1_gas_used)?;
1053        let ty = alloy_eips::Typed2718::ty(&*tx.inner.inner);
1054        let mut tx = tx.clone();
1055        // The envelope keeps its signature and hash: the sender is taken from the RPC response.
1056        let AnyTxEnvelope::Ethereum(envelope) = tx.inner.inner.inner_mut() else {
1057            eyre::bail!(
1058                "cannot set the Nitro execution gas limit of transaction {tx_hash:?} of \
1059                 unsupported type {ty:#04x}"
1060            );
1061        };
1062        match envelope {
1063            EthereumTxEnvelope::Legacy(tx) => tx.tx_mut().gas_limit = gas_limit,
1064            EthereumTxEnvelope::Eip2930(tx) => tx.tx_mut().gas_limit = gas_limit,
1065            EthereumTxEnvelope::Eip1559(tx) => tx.tx_mut().gas_limit = gas_limit,
1066            EthereumTxEnvelope::Eip7702(tx) => tx.tx_mut().gas_limit = gas_limit,
1067            EthereumTxEnvelope::Eip4844(tx) => match tx.tx_mut() {
1068                TxEip4844Variant::TxEip4844(tx) => tx.gas_limit = gas_limit,
1069                TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx.gas_limit = gas_limit,
1070            },
1071        }
1072        Ok(Some(tx))
1073    }
1074}
1075
1076async fn fetch_nitro_l1_gas_used(provider: &RetryProvider, tx_hash: B256) -> Result<(B256, u64)> {
1077    let receipt = provider
1078        .get_transaction_receipt(tx_hash)
1079        .await?
1080        .ok_or_else(|| eyre::eyre!("receipt not found for Nitro transaction {tx_hash:?}"))?;
1081    let l1_gas_used = parse_nitro_l1_gas_used(receipt.other_fields().get("gasUsedForL1"))
1082        .wrap_err_with(|| format!("invalid Nitro poster gas for transaction {tx_hash:?}"))?;
1083    Ok((tx_hash, l1_gas_used))
1084}
1085
1086fn parse_nitro_l1_gas_used(field: Option<&serde_json::Value>) -> Result<u64> {
1087    let field = field.ok_or_else(|| eyre::eyre!("missing `gasUsedForL1` receipt field"))?;
1088    let value = serde_json::from_value::<U256>(field.clone())
1089        .wrap_err("malformed `gasUsedForL1` receipt field")?;
1090    value.try_into().map_err(|_| eyre::eyre!("`gasUsedForL1` value {value} exceeds u64::MAX"))
1091}
1092
1093fn nitro_execution_gas_limit(tx_hash: B256, gas_limit: u64, l1_gas_used: u64) -> Result<u64> {
1094    gas_limit.checked_sub(l1_gas_used).ok_or_else(|| {
1095        eyre::eyre!(
1096            "Nitro poster gas {l1_gas_used} exceeds gas limit {gas_limit} for transaction {tx_hash:?}"
1097        )
1098    })
1099}
1100
1101/// Returns the number and hash of a fetched block.
1102pub(super) fn block_num_hash<B: BlockResponse>(block: &B) -> BlockNumHash
1103where
1104    B::Header: HeaderResponse,
1105{
1106    BlockNumHash::new(block.header().number(), block.header().hash())
1107}
1108
1109/// Extracts the `callTracer` frame from a `debug_trace*` response.
1110///
1111/// Two RPC rejections deserve an actionable hint instead of the raw transport error, and they
1112/// need different fixes: a disabled `debug` namespace, and missing historical state, hit
1113/// whenever a full node has pruned the traced block.
1114pub(super) fn call_tracer_frame(
1115    response: Result<GethTrace, TransportError>,
1116    method: &str,
1117    local_hint: &str,
1118    missing_state_hint: &str,
1119) -> Result<CallFrame> {
1120    let trace = response.map_err(|err| -> eyre::Report {
1121        if is_method_not_found_error(&err) {
1122            eyre::eyre!(
1123                "the RPC endpoint does not support `{method}` (method not found); use a node with the `debug` namespace enabled (e.g. a local anvil/reth or an archive endpoint), or {local_hint}"
1124            )
1125        } else if is_missing_state_error(&err) {
1126            eyre::eyre!(
1127                "the RPC endpoint does not have the historical state for {missing_state_hint}"
1128            )
1129        } else {
1130            err.into()
1131        }
1132    })?;
1133    let GethTrace::CallTracer(frame) = trace else {
1134        eyre::bail!(
1135            "`{method}` did not return a callTracer frame; the RPC endpoint may not support the `callTracer`"
1136        );
1137    };
1138    Ok(frame)
1139}
1140
1141fn ensure_remote_transaction_inclusion(
1142    tx_hash: B256,
1143    expected: BlockNumHash,
1144    actual: Option<BlockNumHash>,
1145    source: &str,
1146) -> Result<()> {
1147    let Some(actual) = actual else {
1148        eyre::bail!(
1149            "transaction {tx_hash} changed inclusion while collecting its remote trace: {source} no longer reports it as mined; retry the command"
1150        );
1151    };
1152    if actual != expected {
1153        eyre::bail!(
1154            "transaction {tx_hash} changed inclusion while collecting its remote trace: expected block {} at {}, but {source} reported block {} at {}; retry the command",
1155            expected.hash,
1156            expected.number,
1157            actual.hash,
1158            actual.number,
1159        );
1160    }
1161
1162    Ok(())
1163}
1164
1165/// Ensures the RPC answered `eth_getTransactionByHash` with the requested transaction.
1166fn ensure_requested_transaction(requested: B256, tx: &AnyRpcTransaction) -> Result<()> {
1167    let returned = tx.tx_hash();
1168    eyre::ensure!(
1169        returned == requested,
1170        "RPC returned transaction {returned:?} for requested {requested:?}"
1171    );
1172    Ok(())
1173}
1174
1175const fn parent_beacon_block_root_for_network(
1176    networks: NetworkConfigs,
1177    is_cancun: bool,
1178    parent_beacon_block_root: Option<B256>,
1179) -> Option<B256> {
1180    if networks.is_monad() || !is_cancun {
1181        return None;
1182    }
1183
1184    // Chains that run a Cancun or later EVM without Ethereum's beacon chain, such as Polygon and
1185    // Scroll, never populate this header field and never deploy the EIP-4788 contract, so there
1186    // is no root to apply. Requiring one makes their blocks unreplayable.
1187    parent_beacon_block_root
1188}
1189
1190pub fn fetch_contracts_bytecode_from_trace<FEN: FoundryEvmNetwork>(
1191    executor: &Executor<FEN>,
1192    result: &TraceResult,
1193) -> Result<AddressHashMap<Bytes>> {
1194    let contracts_bytecode = trace_addresses(result)
1195        .filter_map(|addr| {
1196            // All relevant bytecodes should already be cached in the executor.
1197            let code = executor
1198                .backend()
1199                .basic(addr)
1200                .inspect_err(|e| _ = sh_warn!("Failed to fetch code for {addr}: {e}"))
1201                .ok()??
1202                .code?
1203                .original_bytes();
1204            (!code.is_empty()).then_some((addr, code))
1205        })
1206        .collect();
1207    Ok(contracts_bytecode)
1208}
1209
1210/// Fetches bytecode for a mined transaction at its exact transaction index.
1211///
1212/// The prestate tracer provides the code that existed immediately before the transaction, which
1213/// avoids reading end-of-block state for contracts changed or removed by later transactions. Any
1214/// address absent from the prestate (for example, a contract created by this transaction) falls
1215/// back to `eth_getCode` at the transaction's block.
1216async fn fetch_transaction_contracts_bytecode_via_rpc<N: Network, P: Provider<N>>(
1217    provider: &P,
1218    result: &TraceResult,
1219    tx_hash: B256,
1220    block: BlockId,
1221) -> AddressHashMap<Bytes> {
1222    let mut contracts_bytecode = AddressHashMap::default();
1223    let prestate_config = PreStateConfig { disable_storage: Some(true), ..Default::default() };
1224    match provider
1225        .debug_trace_transaction(tx_hash, GethDebugTracingOptions::prestate_tracer(prestate_config))
1226        .await
1227    {
1228        Ok(trace) => match trace.try_into_pre_state_frame() {
1229            Ok(prestate) => {
1230                for (&address, account) in prestate.pre_state() {
1231                    if let Some(code) = account.code.clone().filter(|code| !code.is_empty()) {
1232                        contracts_bytecode.insert(address, code);
1233                    }
1234                }
1235            }
1236            Err(err) => {
1237                let _ = sh_warn!("Failed to parse transaction prestate for local artifacts: {err}");
1238            }
1239        },
1240        Err(err) => {
1241            let _ = sh_warn!("Failed to fetch transaction prestate for local artifacts: {err}");
1242        }
1243    }
1244
1245    let missing_addresses = trace_addresses(result)
1246        .filter(|address| !contracts_bytecode.contains_key(address))
1247        .collect::<Vec<_>>();
1248    contracts_bytecode.extend(fetch_code_via_rpc(provider, missing_addresses, block).await);
1249    contracts_bytecode
1250}
1251
1252/// Returns the distinct non-zero addresses and callers seen in the traces of `result`.
1253pub(super) fn trace_addresses(result: &TraceResult) -> impl Iterator<Item = Address> {
1254    let mut addresses = AddressSet::default();
1255    for (_, trace) in result.traces.iter().flatten() {
1256        for node in trace.arena.nodes() {
1257            addresses.extend(
1258                [node.trace.address, node.trace.caller].into_iter().filter(|a| !a.is_zero()),
1259            );
1260        }
1261    }
1262    addresses.into_iter()
1263}
1264
1265impl figment::Provider for RunArgs {
1266    fn metadata(&self) -> Metadata {
1267        Metadata::named("RunArgs")
1268    }
1269
1270    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
1271        let mut map = Map::new();
1272
1273        if let Some(api_key) = &self.etherscan.key {
1274            map.insert("etherscan_api_key".into(), api_key.as_str().into());
1275        }
1276
1277        if let Some(evm_version) = self.evm_version {
1278            map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
1279        }
1280
1281        Ok(Map::from([(Config::selected_profile(), map)]))
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287
1288    use super::*;
1289
1290    #[test]
1291    fn http_wrapped_method_not_found_has_trace_guidance() {
1292        let error = alloy_transport::TransportErrorKind::http_error(
1293            403,
1294            r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"method disabled"}}"#.into(),
1295        );
1296        let error = call_tracer_frame(
1297            Err(error),
1298            "debug_traceTransaction",
1299            "replay locally",
1300            "this transaction",
1301        )
1302        .unwrap_err();
1303        assert_eq!(
1304            error.to_string(),
1305            "the RPC endpoint does not support `debug_traceTransaction` (method not found); use a node with the `debug` namespace enabled (e.g. a local anvil/reth or an archive endpoint), or replay locally"
1306        );
1307    }
1308
1309    #[test]
1310    fn parses_legacy_short_label_alias() {
1311        let address = Address::with_last_byte(1);
1312        let label = format!("{address}:alice");
1313        let args = RunArgs::parse_from(["cast run", "0x00", "-l", &label]);
1314
1315        assert_eq!(args.legacy_labels, vec![label]);
1316    }
1317
1318    #[test]
1319    fn debug_trace_transaction_accepts_label_and_render_flags() {
1320        let args = RunArgs::try_parse_from([
1321            "foundry-cli",
1322            "--debug-trace-transaction",
1323            "0x0000000000000000000000000000000000000000000000000000000000000000",
1324            "--label",
1325            "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045:vitalik.eth",
1326            "--disable-labels",
1327            "--trace-depth",
1328            "2",
1329            "--with-local-artifacts",
1330        ]);
1331        assert!(args.is_ok(), "--debug-trace-transaction must accept label/rendering flags");
1332    }
1333
1334    #[test]
1335    fn parent_beacon_block_root_is_applied_only_when_the_header_has_one() {
1336        let networks = NetworkConfigs::default();
1337        let root = Some(B256::repeat_byte(0x42));
1338        // Polygon and Scroll run a Cancun or later EVM without populating the header field.
1339        for (networks, is_cancun, root, expected) in [
1340            (networks, true, None, None),
1341            (networks, true, root, root),
1342            (networks, false, root, None),
1343            (networks, false, None, None),
1344            #[cfg(feature = "monad")]
1345            (NetworkConfigs::with_monad(), true, root, None),
1346            #[cfg(feature = "monad")]
1347            (NetworkConfigs::with_monad(), true, None, None),
1348        ] {
1349            assert_eq!(parent_beacon_block_root_for_network(networks, is_cancun, root), expected);
1350        }
1351    }
1352
1353    #[test]
1354    fn debug_trace_transaction_ignores_configured_internal_decoding() {
1355        let args = RunArgs::parse_from(["cast run", "0x00", "--debug-trace-transaction"]);
1356        let config = TracingConfig { decode_internal: true, ..Default::default() };
1357
1358        assert!(!args.resolve_tracing(&config, 0).decode_internal);
1359    }
1360
1361    #[test]
1362    fn parses_nitro_l1_gas_used() {
1363        let field = serde_json::json!("0x26ed52");
1364
1365        assert_eq!(parse_nitro_l1_gas_used(Some(&field)).unwrap(), 2_551_122);
1366        assert_eq!(nitro_execution_gas_limit(B256::ZERO, 2_733_748, 2_551_122).unwrap(), 182_626);
1367    }
1368
1369    #[test]
1370    fn rejects_invalid_nitro_gas() {
1371        assert_eq!(
1372            parse_nitro_l1_gas_used(None).unwrap_err().to_string(),
1373            "missing `gasUsedForL1` receipt field"
1374        );
1375
1376        let field = serde_json::json!("invalid");
1377        assert_eq!(
1378            parse_nitro_l1_gas_used(Some(&field)).unwrap_err().to_string(),
1379            "malformed `gasUsedForL1` receipt field"
1380        );
1381
1382        let field = serde_json::json!("0x10000000000000000");
1383        assert_eq!(
1384            parse_nitro_l1_gas_used(Some(&field)).unwrap_err().to_string(),
1385            "`gasUsedForL1` value 18446744073709551616 exceeds u64::MAX"
1386        );
1387
1388        let tx_hash = B256::repeat_byte(0x42);
1389        assert_eq!(
1390            nitro_execution_gas_limit(tx_hash, 100, 101).unwrap_err().to_string(),
1391            format!("Nitro poster gas 101 exceeds gas limit 100 for transaction {tx_hash:?}")
1392        );
1393    }
1394}