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).
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 (block, receipt, mut fork) = tokio::try_join!(
531            // fetch the block the transaction was mined in
532            provider.get_block(tx_block_number.into()).full().into_future().map_err(Into::into),
533            // The receipt only backs the check after the replay, so a failed lookup skips that
534            // check instead of failing the run.
535            async { Ok(provider.get_transaction_receipt(tx_hash).await.ok().flatten()) },
536            TracingExecutor::<FEN>::get_fork(&mut config, evm_opts)
537        )?;
538        let chain = fork.context().chain();
539        let networks = fork.context().networks();
540
541        let mut evm_version = self.evm_version;
542        // Mined transactions already passed the block gas limit check their chain applies, and
543        // some chains admit transactions whose gas limit exceeds it: BSC validator transactions
544        // carry a gas limit of `i64::MAX`. Re-applying the check can only reject a transaction
545        // the chain accepted.
546        fork.evm_env.set_feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK, false);
547
548        // By default do not enforce transaction gas limits imposed by Osaka (EIP-7825).
549        // Users can opt-in to enable these limits by setting `enable_tx_gas_limit` to true.
550        if !self.enable_tx_gas_limit {
551            fork.evm_env.version.tx_gas_limit_cap = u64::MAX;
552        }
553
554        // Replays enforce the chain's contract size limits rather than Foundry's unlimited
555        // default.
556        let default_version =
557            EvmFactoryFor::<FEN>::default().version(fork.evm_env.spec, fork.evm_env.chain_id());
558        fork.evm_env.version.max_code_size = default_version.max_code_size;
559        fork.evm_env.version.max_initcode_size = default_version.max_initcode_size;
560        fork.evm_env.block.number = U256::from(tx_block_number);
561
562        let mut parent_beacon_block_root = None;
563        if let Some(block) = &block {
564            fork.evm_env.block = block_env_from_header::<TypesFor<FEN>>(block.header());
565            parent_beacon_block_root = block.header().parent_beacon_block_root();
566
567            // Unless explicitly configured, resolve the correct spec for the block using the same
568            // approach as reth: walk known chain activation conditions to find the latest active
569            // fork. For unknown chains, probe the node for the features it executes at the block,
570            // falling back to a blob-gas heuristic if the node rejects the probe.
571            if evm_version.is_none()
572                && config.hardfork.is_none()
573                && FoundryHardfork::from_chain_and_timestamp(chain.id(), block.header().timestamp())
574                    .is_none()
575            {
576                let probed = probe_evm_version(&provider, BlockId::number(tx_block_number)).await;
577                evm_version = probed.or_else(|| {
578                    block.header().excess_blob_gas().is_some().then_some(EvmVersion::Cancun)
579                });
580            }
581            apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
582                &mut fork.evm_env,
583                block,
584                chain.id(),
585                config.networks,
586            );
587        }
588        fork.resolve_spec(&config, evm_version);
589        fork.extend_precompile_labels(&mut config);
590
591        apply_chain_specific_tx_replay_env_changes_for_chain(&mut fork.evm_env, chain.id());
592
593        let trace_context = fork.context();
594
595        let mut executor = fork.into_executor(
596            executor_builder,
597            TraceRequirements::none(),
598            create2_deployer,
599            None,
600        )?;
601        // The fork is pinned to the parent block, but the replayed transactions execute in the
602        // target's block, which block queries such as Arbitrum's `ArbSys.arbBlockNumber()` must
603        // report.
604        executor.backend_mut().set_fork_block_number_override(tx_block_number);
605
606        let evm_env = *executor.evm_env();
607        // EIP-6780 activates with Cancun in every network family.
608        let is_cancun = evm_env.version.feature(EvmFeatures::EIP6780);
609
610        if let Some(parent_beacon_block_root) =
611            parent_beacon_block_root_for_network(networks, is_cancun, parent_beacon_block_root)
612        {
613            executor.apply_beacon_root(parent_beacon_block_root)?;
614        }
615
616        // Set the state to the moment right before the transaction.
617        //
618        // When `--prestate-tracer` is set, opportunistically try to fetch the prestate directly
619        // via `debug_traceTransaction` (much faster than replaying the block). This requires the
620        // `debug_` namespace, which most nodes don't expose, so it is opt-in and silently falls
621        // back to the block access list, then to replaying previous transactions in the block,
622        // if the call or parsing fails.
623        let mut prestate =
624            if self.quick { PrestateSource::ParentState } else { PrestateSource::BlockReplay };
625        if matches!(prestate, PrestateSource::BlockReplay) && self.prestate_tracer {
626            trace!(?tx_hash, "attempting to fetch prestate via debug_traceTransaction");
627            match provider
628                .debug_trace_transaction(
629                    tx_hash,
630                    GethDebugTracingOptions::prestate_tracer(PreStateConfig::default()),
631                )
632                .await
633            {
634                Ok(trace) => match trace.try_into_pre_state_frame() {
635                    Ok(pre_state_frame) => {
636                        executor.apply_prestate_trace(pre_state_frame.into_pre_state())?;
637                        prestate = PrestateSource::PrestateTrace;
638                        trace!("prestate trace applied successfully, skipping block replay");
639                    }
640                    Err(err) => {
641                        trace!(%err, "failed to parse prestate trace response");
642                    }
643                },
644                Err(err) => {
645                    trace!(?err, "debug_traceTransaction failed, falling back to block replay");
646                }
647            }
648        }
649
650        // A block access list (BAL) records every state write of the block by transaction index,
651        // so the target's prestate can be read from it instead of replaying the earlier
652        // transactions. Before Cancun, SELFDESTRUCT wipes storage the list does not enumerate.
653        // Explicit execution rules must replay the prefix: canonical writes may differ under
654        // the requested EVM version or hardfork.
655        if matches!(prestate, PrestateSource::BlockReplay)
656            && !self.no_bal
657            && self.evm_version.is_none()
658            && config.hardfork.is_none()
659            && is_cancun
660            && let Some(block) = &block
661            && let Some(bal) = fetch_block_access_list(&provider, block).await?
662        {
663            prestate = PrestateSource::BlockAccessList(bal);
664        }
665
666        let mut replay_tx_hashes = vec![tx_hash];
667        if matches!(prestate, PrestateSource::BlockReplay)
668            && let Some(block) = &block
669        {
670            replay_tx_hashes.extend(
671                full_transactions(block)?
672                    .iter()
673                    .take_while(|tx| tx.tx_hash() != tx_hash)
674                    .filter(|tx| {
675                        !is_arbos_internal_transaction(tx)
676                            && (!is_system_transaction(tx) || self.replay_system_txes)
677                    })
678                    .map(TransactionResponse::tx_hash),
679            );
680        }
681        let replay_gas_limits =
682            ReplayGasLimits::fetch(chain.id(), &provider, replay_tx_hashes).await?;
683
684        Ok(PreparedRun {
685            args: self,
686            config,
687            tracing,
688            tx,
689            block,
690            evm_env,
691            executor,
692            trace_context,
693            prestate,
694            replay_gas_limits,
695            receipt,
696            #[cfg(feature = "monad")]
697            monad_provider: provider,
698        })
699    }
700}
701
702/// Fetches the block access list of `block`, if the node serves one that matches the header.
703async fn fetch_block_access_list(
704    provider: &RetryProvider,
705    block: &AnyRpcBlock,
706) -> Result<Option<Arc<Bal>>> {
707    let header = block.header();
708    let bal = match provider.get_block_access_list(BlockId::hash(header.hash)).await {
709        Ok(Some(bal)) => bal,
710        Ok(None) => return Ok(None),
711        Err(err) => {
712            trace!(%err, "block access list unavailable, falling back to block replay");
713            return Ok(None);
714        }
715    };
716    if let Some(hash) = header.block_access_list_hash()
717        && compute_block_access_list_hash(&bal) != hash
718    {
719        sh_warn!(
720            "block access list of block {} does not match its header, replaying the block instead",
721            header.number()
722        )?;
723        return Ok(None);
724    }
725    Ok(Some(Arc::new(Bal::try_from(bal).wrap_err("invalid block access list")?)))
726}
727
728impl<FEN: FoundryEvmNetwork> PreparedRun<FEN> {
729    fn transaction(&self, tx: &AnyRpcTransaction) -> Result<Recovered<TxFor<FEN>>> {
730        match self.replay_gas_limits.apply(tx)? {
731            Some(tx) => TypesFor::<FEN>::tx_from_any_rpc(&tx),
732            None => TypesFor::<FEN>::tx_from_any_rpc(tx),
733        }
734    }
735
736    /// Prepares the executor for the target transaction: enables tracing and, when the sender
737    /// was forged, disables the balance check.
738    fn prepare_target(&mut self) {
739        let requirements = TraceRequirements::none()
740            .with_calls(true)
741            .with_debug_recording(self.args.debug)
742            .with_decode_internal(if self.tracing.decode_internal {
743                InternalTraceMode::Full
744            } else {
745                InternalTraceMode::None
746            })
747            .with_state_changes(self.tracing.verbosity > 4);
748        self.executor.set_trace_requirements(requirements);
749        self.executor.set_trace_printer(self.args.trace_printer);
750
751        let sender_is_forged = match &*self.tx.inner.inner {
752            AnyTxEnvelope::Ethereum(inner) => {
753                inner.recover_signer().is_ok_and(|signer| signer != self.tx.from())
754            }
755            AnyTxEnvelope::Unknown(_) => true,
756        };
757        if sender_is_forged {
758            self.evm_env.set_feature(EvmFeatures::BALANCE_CHECK, false);
759        }
760    }
761
762    /// Returns the index of the target transaction in its block.
763    fn target_index(&self) -> Result<usize> {
764        let Some(block) = &self.block else { return Ok(0) };
765        full_transactions(block)?
766            .iter()
767            .position(|candidate| candidate.tx_hash() == self.tx.tx_hash())
768            .ok_or_else(|| {
769                eyre::eyre!("transaction {:?} is missing from its block", self.tx.tx_hash())
770            })
771    }
772
773    /// Calls `f` for every transaction mined before the target, unless the block replay was
774    /// skipped (`--quick` or an applied prestate trace).
775    fn for_each_prefix_transaction(
776        &self,
777        target_index: usize,
778        mut f: impl FnMut(usize, &AnyRpcTransaction) -> Result<()>,
779    ) -> Result<()> {
780        if !self.prestate.replays_prefix() {
781            return Ok(());
782        }
783        sh_status!("Executing previous transactions from the block.")?;
784        let Some(block) = &self.block else { return Ok(()) };
785        let txs = full_transactions(block)?;
786        let pb = init_progress(txs.len() as u64, "tx");
787        for (index, tx) in txs.iter().take(target_index).enumerate() {
788            if let Some(to) = Transaction::to(tx) {
789                trace!(tx=?tx.tx_hash(), ?to, "preparing previous call transaction");
790            } else {
791                trace!(tx=?tx.tx_hash(), "preparing previous create transaction");
792            }
793            f(index, tx)?;
794            pb.set_position((index + 1) as u64);
795        }
796        Ok(())
797    }
798
799    fn trace_kind(&self) -> TraceKind {
800        if let Some(to) = Transaction::to(&self.tx) {
801            trace!(tx=?self.tx.tx_hash(), ?to, "executing call transaction");
802            TraceKind::Execution
803        } else {
804            trace!(tx=?self.tx.tx_hash(), "executing create transaction");
805            TraceKind::Deployment
806        }
807    }
808
809    fn execute_ordinary(&mut self) -> Result<TraceResult> {
810        // Decode the target transaction before replaying the block: an envelope this build
811        // can't decode should fail fast.
812        let target = self.transaction(&self.tx).wrap_err_with(|| {
813            format!(
814                "cannot replay transaction {:?} locally; {REMOTE_TRACE_HINT}",
815                self.tx.tx_hash()
816            )
817        })?;
818        let target_index = self.target_index()?;
819        self.prepare_target();
820
821        let mut replay = Vec::new();
822        if let PrestateSource::BlockAccessList(bal) = &self.prestate {
823            let bal = Arc::clone(bal);
824            // Index 0 holds the pre-block system writes and transaction `i` is index `i + 1`, so
825            // reads positioned at the target's own index see exactly the earlier writes.
826            trace!("reading prestate from block access list, skipping block replay");
827            self.executor
828                .backend_mut()
829                .set_bal(bal, BlockAccessIndex::new(target_index as u64 + 1));
830        } else {
831            let block_number = self.evm_env.block.number;
832            let replay_system_txes = self.args.replay_system_txes;
833            let mut skipped_system_txes = Vec::new();
834            self.for_each_prefix_transaction(target_index, |_, tx| {
835                // ArbOS internal transactions open every Arbitrum block, Orbit chains included,
836                // and also report batch postings mid-block. They update ArbOS bookkeeping, which
837                // the replay cannot execute, so they are left out without a warning.
838                if is_arbos_internal_transaction(tx) {
839                    return Ok(());
840                }
841                if !is_system_transaction(tx) || replay_system_txes {
842                    let replayed = self.transaction(tx).wrap_err_with(|| {
843                        format!(
844                            "Failed to prepare transaction: {:?} in block {}; `--quick` skips the \
845                             transactions before the target, and {REMOTE_TRACE_HINT}",
846                            tx.tx_hash(),
847                            block_number
848                        )
849                    })?;
850                    replay.push((tx.tx_hash(), replayed));
851                } else {
852                    skipped_system_txes.push(tx.tx_hash());
853                }
854                Ok(())
855            })?;
856            if !skipped_system_txes.is_empty() {
857                sh_warn!(
858                    "the replay skips system transactions before the target, so their state \
859                     changes are missing: {skipped_system_txes:?}; `--replay-system-txes` \
860                     attempts local replay where supported; {REMOTE_TRACE_HINT}"
861                )?;
862            }
863        }
864        let result = self.executor.transact_with_block_replay(
865            self.evm_env,
866            &target,
867            Transaction::kind(&self.tx),
868            &replay,
869        )?;
870        let trace_kind = self.trace_kind();
871        trace!(tx_hash=?self.tx.tx_hash(), "completed execution");
872        Ok(TraceResult::from_raw(result, trace_kind))
873    }
874
875    async fn finish(self, result: TraceResult) -> Result<()> {
876        let contracts_bytecode = fetch_contracts_bytecode_from_trace(&self.executor, &result)?;
877        let (success, gas_used) = (result.success, result.gas_used);
878        handle_traces(
879            result,
880            &self.config,
881            self.trace_context,
882            &contracts_bytecode,
883            &self.tracing,
884            self.args.with_local_artifacts,
885            self.args.debug,
886        )
887        .await?;
888        self.warn_on_receipt_mismatch(success, gas_used)
889    }
890
891    /// Warns when the replay does not reproduce the target's receipt.
892    ///
893    /// A replay diverges when the chain applies rules the local EVM does not model or the replay
894    /// starts from different state, and the trace alone gives no sign of it.
895    fn warn_on_receipt_mismatch(&self, success: bool, gas_used: u64) -> Result<()> {
896        let Some(receipt) = &self.receipt else { return Ok(()) };
897        let outcome = |success: bool| if success { "succeeded" } else { "reverted" };
898        let mut differences = Vec::new();
899        if receipt.status() != success {
900            differences.push(format!(
901                "it {} on-chain but {} in the replay",
902                outcome(receipt.status()),
903                outcome(success)
904            ));
905        }
906        if let Some(expected) = self.expected_replay_gas(receipt)
907            && expected != gas_used
908        {
909            differences
910                .push(format!("it used {expected} gas on-chain but {gas_used} in the replay"));
911        }
912        if differences.is_empty() {
913            return Ok(());
914        }
915        let hint = if self.args.quick {
916            "`--quick` skips the transactions before it in the block, which can change the result; \
917             run without it to replay them first"
918        } else {
919            "The chain may apply rules the replay does not model; `--debug-trace-transaction` \
920             shows the node's own trace if it exposes the `debug` namespace"
921        };
922        sh_warn!(
923            "the replay does not match the transaction's receipt: {}. {hint}.",
924            differences.join(", and ")
925        )
926    }
927
928    /// Returns the gas the replay should report for `receipt`, or `None` if the receipt does not
929    /// record the gas the transaction executed.
930    fn expected_replay_gas(&self, receipt: &AnyTransactionReceipt) -> Option<u64> {
931        // Monad charges the full gas limit and reports it as the gas used.
932        if self.trace_context.networks().is_monad() {
933            return None;
934        }
935        let gas_used = receipt.gas_used();
936        if arbitrum::is_arbitrum_chain(self.trace_context.chain().id()) {
937            // Nitro folds the L1 posting cost into the receipt's gas used.
938            let l1_gas_used =
939                parse_nitro_l1_gas_used(receipt.other_fields().get("gasUsedForL1")).ok()?;
940            return gas_used.checked_sub(l1_gas_used);
941        }
942        Some(gas_used)
943    }
944}
945
946#[cfg(feature = "monad")]
947impl PreparedRun<MonadEvmNetwork> {
948    async fn execute_monad(&mut self) -> Result<TraceResult> {
949        // Monad protocol system transactions replay as the protocol system calls they are; the
950        // replay rejects a non-canonical envelope from the system sender.
951        if self.tx.from() != MONAD_SYSTEM_ADDRESS
952            && is_system_transaction(&self.tx)
953            && !self.args.replay_system_txes
954        {
955            eyre::bail!(
956                "{:?} is a system transaction.\nReplaying system transactions is currently not supported.",
957                self.tx.tx_hash()
958            );
959        }
960        let block = self.block.as_ref().ok_or_else(|| {
961            eyre::eyre!(
962                "block {} is required to reconstruct transaction context",
963                self.evm_env.block.number
964            )
965        })?;
966        let block_context = BlockContext::<MonadEvmNetwork>::fetch(&self.monad_provider, block)
967            .await
968            .wrap_err_with(|| {
969                format!(
970                    "cannot replay transaction {:?} locally; {REMOTE_TRACE_HINT}",
971                    self.tx.tx_hash()
972                )
973            })?;
974        // Decode the target transaction before replaying the block: an envelope this build
975        // can't decode should fail fast, not after paying for the entire prior-transaction
976        // replay.
977        let target = self.transaction(&self.tx)?;
978        let target_index = self.target_index()?;
979        self.prepare_target();
980
981        let mut replay = Vec::new();
982        let replay_system_txes = self.args.replay_system_txes;
983        self.for_each_prefix_transaction(target_index, |_, tx| {
984            // Canonical protocol transactions always replay; other system transactions only
985            // with `--replay-system-txes`.
986            let replayed = self.transaction(tx)?;
987            if !is_system_transaction(tx)
988                || replay_system_txes
989                || ChainFor::<MonadEvmNetwork>::is_protocol_transaction(&replayed)
990            {
991                replay.push((tx.tx_hash(), replayed));
992            }
993            Ok(())
994        })?;
995        // The replay records each prefix transaction into the context, so it starts at the
996        // beginning of the block; without a prefix, the target takes its own position.
997        let position = if replay.is_empty() { target_index } else { 0 };
998        let result = self.executor.transact_with_monad_block_replay(
999            self.evm_env,
1000            &target,
1001            Transaction::kind(&self.tx),
1002            &replay,
1003            block_context.before_transaction(position)?,
1004        )?;
1005        Ok(TraceResult::from_raw(result, self.trace_kind()))
1006    }
1007}
1008
1009fn is_system_transaction(tx: &AnyRpcTransaction) -> bool {
1010    is_known_system_sender(tx.from()) || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
1011}
1012
1013fn is_arbos_internal_transaction(tx: &AnyRpcTransaction) -> bool {
1014    tx.transaction_type() == Some(arbitrum::ARBITRUM_INTERNAL_TX_TYPE)
1015}
1016
1017fn full_transactions(block: &AnyRpcBlock) -> Result<&[AnyRpcTransaction]> {
1018    let BlockTransactions::Full(txs) = block.transactions() else {
1019        eyre::bail!("Could not get block txs");
1020    };
1021    Ok(txs)
1022}
1023
1024impl ReplayGasLimits {
1025    async fn fetch(chain_id: u64, provider: &RetryProvider, tx_hashes: Vec<B256>) -> Result<Self> {
1026        if !foundry_evm_networks::arbitrum::is_arbitrum_chain(chain_id) {
1027            return Ok(Self::Unchanged);
1028        }
1029
1030        let mut requests = futures::stream::iter(tx_hashes)
1031            .map(|tx_hash| fetch_nitro_l1_gas_used(provider, tx_hash))
1032            .buffer_unordered(MAX_CONCURRENT_RPC_REQUESTS);
1033        let mut gas_used = B256HashMap::default();
1034        while let Some(result) = requests.next().await {
1035            let (tx_hash, l1_gas_used) = result?;
1036            gas_used.insert(tx_hash, l1_gas_used);
1037        }
1038        Ok(Self::Nitro(gas_used))
1039    }
1040
1041    /// Returns `tx` with its replay gas limit, or `None` if it replays unchanged.
1042    fn apply(&self, tx: &AnyRpcTransaction) -> Result<Option<AnyRpcTransaction>> {
1043        let Self::Nitro(l1_gas_used) = self else { return Ok(None) };
1044        let tx_hash = tx.tx_hash();
1045        let l1_gas_used = l1_gas_used
1046            .get(&tx_hash)
1047            .ok_or_else(|| eyre::eyre!("receipt not found for Nitro transaction {tx_hash:?}"))?;
1048        let gas_limit = nitro_execution_gas_limit(tx_hash, tx.gas_limit(), *l1_gas_used)?;
1049        let ty = alloy_eips::Typed2718::ty(&*tx.inner.inner);
1050        let mut tx = tx.clone();
1051        // The envelope keeps its signature and hash: the sender is taken from the RPC response.
1052        let AnyTxEnvelope::Ethereum(envelope) = tx.inner.inner.inner_mut() else {
1053            eyre::bail!(
1054                "cannot set the Nitro execution gas limit of transaction {tx_hash:?} of \
1055                 unsupported type {ty:#04x}"
1056            );
1057        };
1058        match envelope {
1059            EthereumTxEnvelope::Legacy(tx) => tx.tx_mut().gas_limit = gas_limit,
1060            EthereumTxEnvelope::Eip2930(tx) => tx.tx_mut().gas_limit = gas_limit,
1061            EthereumTxEnvelope::Eip1559(tx) => tx.tx_mut().gas_limit = gas_limit,
1062            EthereumTxEnvelope::Eip7702(tx) => tx.tx_mut().gas_limit = gas_limit,
1063            EthereumTxEnvelope::Eip4844(tx) => match tx.tx_mut() {
1064                TxEip4844Variant::TxEip4844(tx) => tx.gas_limit = gas_limit,
1065                TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx.gas_limit = gas_limit,
1066            },
1067        }
1068        Ok(Some(tx))
1069    }
1070}
1071
1072async fn fetch_nitro_l1_gas_used(provider: &RetryProvider, tx_hash: B256) -> Result<(B256, u64)> {
1073    let receipt = provider
1074        .get_transaction_receipt(tx_hash)
1075        .await?
1076        .ok_or_else(|| eyre::eyre!("receipt not found for Nitro transaction {tx_hash:?}"))?;
1077    let l1_gas_used = parse_nitro_l1_gas_used(receipt.other_fields().get("gasUsedForL1"))
1078        .wrap_err_with(|| format!("invalid Nitro poster gas for transaction {tx_hash:?}"))?;
1079    Ok((tx_hash, l1_gas_used))
1080}
1081
1082fn parse_nitro_l1_gas_used(field: Option<&serde_json::Value>) -> Result<u64> {
1083    let field = field.ok_or_else(|| eyre::eyre!("missing `gasUsedForL1` receipt field"))?;
1084    let value = serde_json::from_value::<U256>(field.clone())
1085        .wrap_err("malformed `gasUsedForL1` receipt field")?;
1086    value.try_into().map_err(|_| eyre::eyre!("`gasUsedForL1` value {value} exceeds u64::MAX"))
1087}
1088
1089fn nitro_execution_gas_limit(tx_hash: B256, gas_limit: u64, l1_gas_used: u64) -> Result<u64> {
1090    gas_limit.checked_sub(l1_gas_used).ok_or_else(|| {
1091        eyre::eyre!(
1092            "Nitro poster gas {l1_gas_used} exceeds gas limit {gas_limit} for transaction {tx_hash:?}"
1093        )
1094    })
1095}
1096
1097/// Returns the number and hash of a fetched block.
1098pub(super) fn block_num_hash<B: BlockResponse>(block: &B) -> BlockNumHash
1099where
1100    B::Header: HeaderResponse,
1101{
1102    BlockNumHash::new(block.header().number(), block.header().hash())
1103}
1104
1105/// Extracts the `callTracer` frame from a `debug_trace*` response.
1106///
1107/// Two RPC rejections deserve an actionable hint instead of the raw transport error, and they
1108/// need different fixes: a disabled `debug` namespace, and missing historical state, hit
1109/// whenever a full node has pruned the traced block.
1110pub(super) fn call_tracer_frame(
1111    response: Result<GethTrace, TransportError>,
1112    method: &str,
1113    local_hint: &str,
1114    missing_state_hint: &str,
1115) -> Result<CallFrame> {
1116    let trace = response.map_err(|err| -> eyre::Report {
1117        if is_method_not_found_error(&err) {
1118            eyre::eyre!(
1119                "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}"
1120            )
1121        } else if is_missing_state_error(&err) {
1122            eyre::eyre!(
1123                "the RPC endpoint does not have the historical state for {missing_state_hint}"
1124            )
1125        } else {
1126            err.into()
1127        }
1128    })?;
1129    let GethTrace::CallTracer(frame) = trace else {
1130        eyre::bail!(
1131            "`{method}` did not return a callTracer frame; the RPC endpoint may not support the `callTracer`"
1132        );
1133    };
1134    Ok(frame)
1135}
1136
1137fn ensure_remote_transaction_inclusion(
1138    tx_hash: B256,
1139    expected: BlockNumHash,
1140    actual: Option<BlockNumHash>,
1141    source: &str,
1142) -> Result<()> {
1143    let Some(actual) = actual else {
1144        eyre::bail!(
1145            "transaction {tx_hash} changed inclusion while collecting its remote trace: {source} no longer reports it as mined; retry the command"
1146        );
1147    };
1148    if actual != expected {
1149        eyre::bail!(
1150            "transaction {tx_hash} changed inclusion while collecting its remote trace: expected block {} at {}, but {source} reported block {} at {}; retry the command",
1151            expected.hash,
1152            expected.number,
1153            actual.hash,
1154            actual.number,
1155        );
1156    }
1157
1158    Ok(())
1159}
1160
1161/// Ensures the RPC answered `eth_getTransactionByHash` with the requested transaction.
1162fn ensure_requested_transaction(requested: B256, tx: &AnyRpcTransaction) -> Result<()> {
1163    let returned = tx.tx_hash();
1164    eyre::ensure!(
1165        returned == requested,
1166        "RPC returned transaction {returned:?} for requested {requested:?}"
1167    );
1168    Ok(())
1169}
1170
1171const fn parent_beacon_block_root_for_network(
1172    networks: NetworkConfigs,
1173    is_cancun: bool,
1174    parent_beacon_block_root: Option<B256>,
1175) -> Option<B256> {
1176    if networks.is_monad() || !is_cancun {
1177        return None;
1178    }
1179
1180    // Chains that run a Cancun or later EVM without Ethereum's beacon chain, such as Polygon and
1181    // Scroll, never populate this header field and never deploy the EIP-4788 contract, so there
1182    // is no root to apply. Requiring one makes their blocks unreplayable.
1183    parent_beacon_block_root
1184}
1185
1186pub fn fetch_contracts_bytecode_from_trace<FEN: FoundryEvmNetwork>(
1187    executor: &Executor<FEN>,
1188    result: &TraceResult,
1189) -> Result<AddressHashMap<Bytes>> {
1190    let contracts_bytecode = trace_addresses(result)
1191        .filter_map(|addr| {
1192            // All relevant bytecodes should already be cached in the executor.
1193            let code = executor
1194                .backend()
1195                .basic(addr)
1196                .inspect_err(|e| _ = sh_warn!("Failed to fetch code for {addr}: {e}"))
1197                .ok()??
1198                .code?
1199                .original_bytes();
1200            (!code.is_empty()).then_some((addr, code))
1201        })
1202        .collect();
1203    Ok(contracts_bytecode)
1204}
1205
1206/// Fetches bytecode for a mined transaction at its exact transaction index.
1207///
1208/// The prestate tracer provides the code that existed immediately before the transaction, which
1209/// avoids reading end-of-block state for contracts changed or removed by later transactions. Any
1210/// address absent from the prestate (for example, a contract created by this transaction) falls
1211/// back to `eth_getCode` at the transaction's block.
1212async fn fetch_transaction_contracts_bytecode_via_rpc<N: Network, P: Provider<N>>(
1213    provider: &P,
1214    result: &TraceResult,
1215    tx_hash: B256,
1216    block: BlockId,
1217) -> AddressHashMap<Bytes> {
1218    let mut contracts_bytecode = AddressHashMap::default();
1219    let prestate_config = PreStateConfig { disable_storage: Some(true), ..Default::default() };
1220    match provider
1221        .debug_trace_transaction(tx_hash, GethDebugTracingOptions::prestate_tracer(prestate_config))
1222        .await
1223    {
1224        Ok(trace) => match trace.try_into_pre_state_frame() {
1225            Ok(prestate) => {
1226                for (&address, account) in prestate.pre_state() {
1227                    if let Some(code) = account.code.clone().filter(|code| !code.is_empty()) {
1228                        contracts_bytecode.insert(address, code);
1229                    }
1230                }
1231            }
1232            Err(err) => {
1233                let _ = sh_warn!("Failed to parse transaction prestate for local artifacts: {err}");
1234            }
1235        },
1236        Err(err) => {
1237            let _ = sh_warn!("Failed to fetch transaction prestate for local artifacts: {err}");
1238        }
1239    }
1240
1241    let missing_addresses = trace_addresses(result)
1242        .filter(|address| !contracts_bytecode.contains_key(address))
1243        .collect::<Vec<_>>();
1244    contracts_bytecode.extend(fetch_code_via_rpc(provider, missing_addresses, block).await);
1245    contracts_bytecode
1246}
1247
1248/// Returns the distinct non-zero addresses and callers seen in the traces of `result`.
1249pub(super) fn trace_addresses(result: &TraceResult) -> impl Iterator<Item = Address> {
1250    let mut addresses = AddressSet::default();
1251    for (_, trace) in result.traces.iter().flatten() {
1252        for node in trace.arena.nodes() {
1253            addresses.extend(
1254                [node.trace.address, node.trace.caller].into_iter().filter(|a| !a.is_zero()),
1255            );
1256        }
1257    }
1258    addresses.into_iter()
1259}
1260
1261impl figment::Provider for RunArgs {
1262    fn metadata(&self) -> Metadata {
1263        Metadata::named("RunArgs")
1264    }
1265
1266    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
1267        let mut map = Map::new();
1268
1269        if let Some(api_key) = &self.etherscan.key {
1270            map.insert("etherscan_api_key".into(), api_key.as_str().into());
1271        }
1272
1273        if let Some(evm_version) = self.evm_version {
1274            map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
1275        }
1276
1277        Ok(Map::from([(Config::selected_profile(), map)]))
1278    }
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283
1284    use super::*;
1285
1286    #[test]
1287    fn http_wrapped_method_not_found_has_trace_guidance() {
1288        let error = alloy_transport::TransportErrorKind::http_error(
1289            403,
1290            r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"method disabled"}}"#.into(),
1291        );
1292        let error = call_tracer_frame(
1293            Err(error),
1294            "debug_traceTransaction",
1295            "replay locally",
1296            "this transaction",
1297        )
1298        .unwrap_err();
1299        assert_eq!(
1300            error.to_string(),
1301            "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"
1302        );
1303    }
1304
1305    #[test]
1306    fn parses_legacy_short_label_alias() {
1307        let address = Address::with_last_byte(1);
1308        let label = format!("{address}:alice");
1309        let args = RunArgs::parse_from(["cast run", "0x00", "-l", &label]);
1310
1311        assert_eq!(args.legacy_labels, vec![label]);
1312    }
1313
1314    #[test]
1315    fn debug_trace_transaction_accepts_label_and_render_flags() {
1316        let args = RunArgs::try_parse_from([
1317            "foundry-cli",
1318            "--debug-trace-transaction",
1319            "0x0000000000000000000000000000000000000000000000000000000000000000",
1320            "--label",
1321            "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045:vitalik.eth",
1322            "--disable-labels",
1323            "--trace-depth",
1324            "2",
1325            "--with-local-artifacts",
1326        ]);
1327        assert!(args.is_ok(), "--debug-trace-transaction must accept label/rendering flags");
1328    }
1329
1330    #[test]
1331    fn parent_beacon_block_root_is_applied_only_when_the_header_has_one() {
1332        let networks = NetworkConfigs::default();
1333        let root = Some(B256::repeat_byte(0x42));
1334        // Polygon and Scroll run a Cancun or later EVM without populating the header field.
1335        for (networks, is_cancun, root, expected) in [
1336            (networks, true, None, None),
1337            (networks, true, root, root),
1338            (networks, false, root, None),
1339            (networks, false, None, None),
1340            #[cfg(feature = "monad")]
1341            (NetworkConfigs::with_monad(), true, root, None),
1342            #[cfg(feature = "monad")]
1343            (NetworkConfigs::with_monad(), true, None, None),
1344        ] {
1345            assert_eq!(parent_beacon_block_root_for_network(networks, is_cancun, root), expected);
1346        }
1347    }
1348
1349    #[test]
1350    fn debug_trace_transaction_ignores_configured_internal_decoding() {
1351        let args = RunArgs::parse_from(["cast run", "0x00", "--debug-trace-transaction"]);
1352        let config = TracingConfig { decode_internal: true, ..Default::default() };
1353
1354        assert!(!args.resolve_tracing(&config, 0).decode_internal);
1355    }
1356
1357    #[test]
1358    fn parses_nitro_l1_gas_used() {
1359        let field = serde_json::json!("0x26ed52");
1360
1361        assert_eq!(parse_nitro_l1_gas_used(Some(&field)).unwrap(), 2_551_122);
1362        assert_eq!(nitro_execution_gas_limit(B256::ZERO, 2_733_748, 2_551_122).unwrap(), 182_626);
1363    }
1364
1365    #[test]
1366    fn rejects_invalid_nitro_gas() {
1367        assert_eq!(
1368            parse_nitro_l1_gas_used(None).unwrap_err().to_string(),
1369            "missing `gasUsedForL1` receipt field"
1370        );
1371
1372        let field = serde_json::json!("invalid");
1373        assert_eq!(
1374            parse_nitro_l1_gas_used(Some(&field)).unwrap_err().to_string(),
1375            "malformed `gasUsedForL1` receipt field"
1376        );
1377
1378        let field = serde_json::json!("0x10000000000000000");
1379        assert_eq!(
1380            parse_nitro_l1_gas_used(Some(&field)).unwrap_err().to_string(),
1381            "`gasUsedForL1` value 18446744073709551616 exceeds u64::MAX"
1382        );
1383
1384        let tx_hash = B256::repeat_byte(0x42);
1385        assert_eq!(
1386            nitro_execution_gas_limit(tx_hash, 100, 101).unwrap_err().to_string(),
1387            format!("Nitro poster gas 101 exceeds gas limit 100 for transaction {tx_hash:?}")
1388        );
1389    }
1390}