Skip to main content

foundry_evm/inspectors/
stack.rs

1use super::{
2    Cheatcodes, CheatsConfig, ChiselState, CmpOperands, CustomPrintTracer, DebugRecorder,
3    EdgeCovConfig, EdgeCovInspector, EdgeCovKind, EdgeCoverage, Fuzzer, LineCoverageCollector,
4    LogCollector, RevertDiagnostic, ScriptExecutionInspector, TempoLabels, TracingInspector,
5};
6use alloy_consensus::transaction::Recovered;
7use alloy_network::TransactionBuilder;
8use alloy_primitives::{
9    Address, B256, Bytes, Log, TxKind, U256, keccak256,
10    map::{AddressHashMap, AddressMap, AddressSet, HashSet},
11};
12use evm2::{
13    EvmFeatures, ExecutedTx, ExecutionError, Inspector, InspectorConfig, OpcodeSet,
14    TxResultWithState,
15    ethereum::intrinsic_and_floor_gas,
16    evm::{DbResult, PendingState, PrewarmSet, State},
17    interpreter::{GasTracker, Host, InstrStop, MessageKind, op},
18    registry::HandlerError,
19};
20use eyre::WrapErr;
21use foundry_cheatcodes::{
22    CheatcodeAnalysis, CheatcodesBackend, CheatcodesExecutor, Wallets, message_result,
23};
24use foundry_common::{compile::Analysis, sh_warn};
25use foundry_config::FuzzCorpusConfig;
26use foundry_evm_core::{
27    backend::transaction_error,
28    constants::{CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER_CODEHASH},
29    evm::{
30        BlockEnvFor, DestructedAccount, EthEvmNetwork, EvmEnvFor, EvmFactoryFor, ExecutedNested,
31        FoundryEvmExt, FoundryEvmFactory, FoundryEvmFor, FoundryEvmNetwork, FoundryExecutionHooks,
32        FoundryTxConversion, InterpreterFor, MessageFor, MessageResultFor, PersistentWrite,
33        PreparedTx, SnapshotRestores, TransactionRequestFor, TxFor, TxResultFor, TypesFor,
34        destructed_accounts, evm_env, merge_pending_changes,
35        merge_untracked_pending_changes_with_warmth, put_transient, release_inspector,
36        take_transient, warm_accounts, warm_set,
37    },
38    precompiles::P256_VERIFY,
39    utils::tx_warm_addresses,
40};
41use foundry_evm_coverage::HitMaps;
42use foundry_evm_networks::arbitrum;
43use foundry_evm_traces::{SparsedTraceArena, TraceRequirements};
44use std::{
45    mem,
46    ops::{Deref, DerefMut},
47    sync::{Arc, atomic::AtomicBool},
48    time::Instant,
49};
50
51use crate::executors::{EarlyExit, EvmExecutionCancellation};
52
53#[derive(Clone, Debug)]
54#[must_use = "builders do nothing unless you call `build` on them"]
55pub struct InspectorStackBuilder<BLOCK: Clone> {
56    /// Solar compiler instance, to grant syntactic and semantic analysis capabilities.
57    pub analysis: Option<Analysis>,
58    /// The block environment.
59    ///
60    /// Used in the cheatcode handler to overwrite the block environment separately from the
61    /// execution block environment.
62    pub block: Option<BLOCK>,
63    /// The gas price.
64    ///
65    /// Used in the cheatcode handler to overwrite the gas price separately from the gas price
66    /// in the execution environment.
67    pub gas_price: Option<u128>,
68    /// The cheatcodes config.
69    pub cheatcodes: Option<Arc<CheatsConfig>>,
70    /// The fuzzer inspector and its state, if it exists.
71    pub fuzzer: Option<Fuzzer>,
72    /// Whether to enable tracing and revert diagnostics.
73    pub trace_requirements: TraceRequirements,
74    /// Whether logs should be collected.
75    /// - None for no log collection.
76    /// - Some(true) for realtime console.log-ing.
77    /// - Some(false) for log collection.
78    pub logs: Option<bool>,
79    /// Whether line coverage info should be collected.
80    pub line_coverage: Option<bool>,
81    /// Whether to print all opcode traces into the console. Useful for debugging the EVM.
82    pub print: Option<bool>,
83    /// The chisel state inspector.
84    pub chisel_state: Option<ChiselState>,
85    /// Whether to enable call isolation.
86    /// In isolation mode all top-level calls are executed as a separate transaction in a separate
87    /// EVM context, enabling more precise gas accounting and transaction state changes.
88    pub enable_isolation: bool,
89    /// Whether to prefetch the remote state of calls into fork contracts.
90    pub fork_prefetch: bool,
91    /// Concrete Tempo label inspector selected by the Tempo executor builder.
92    tempo_labels: Option<Box<TempoLabels>>,
93    /// Explicitly resolved additional cheatcode addresses.
94    pub extra_cheatcode_addresses: &'static [Address],
95    /// The wallets to set in the cheatcodes context.
96    pub wallets: Option<Wallets>,
97    /// The CREATE2 deployer address.
98    pub create2_deployer: Address,
99}
100
101impl<BLOCK: Clone> Default for InspectorStackBuilder<BLOCK> {
102    fn default() -> Self {
103        Self {
104            analysis: None,
105            block: None,
106            gas_price: None,
107            cheatcodes: None,
108            fuzzer: None,
109            trace_requirements: TraceRequirements::none(),
110            logs: None,
111            line_coverage: None,
112            print: None,
113            chisel_state: None,
114            enable_isolation: false,
115            fork_prefetch: false,
116            tempo_labels: None,
117            extra_cheatcode_addresses: &[],
118            wallets: None,
119            create2_deployer: Default::default(),
120        }
121    }
122}
123
124impl<BLOCK: Clone> InspectorStackBuilder<BLOCK> {
125    /// Create a new inspector stack builder.
126    #[inline]
127    pub fn new() -> Self {
128        Self::default()
129    }
130
131    /// Set the solar compiler instance that grants syntactic and semantic analysis capabilities
132    #[inline]
133    pub fn set_analysis(mut self, analysis: Analysis) -> Self {
134        self.analysis = Some(analysis);
135        self
136    }
137
138    /// Set the block environment.
139    #[inline]
140    pub fn block(mut self, block: BLOCK) -> Self {
141        self.block = Some(block);
142        self
143    }
144
145    /// Set the gas price.
146    #[inline]
147    pub const fn gas_price(mut self, gas_price: u128) -> Self {
148        self.gas_price = Some(gas_price);
149        self
150    }
151
152    /// Enable cheatcodes with the given config.
153    #[inline]
154    pub fn cheatcodes(mut self, config: Arc<CheatsConfig>) -> Self {
155        self.cheatcodes = Some(config);
156        self
157    }
158
159    /// Set the wallets.
160    #[inline]
161    pub fn wallets(mut self, wallets: Wallets) -> Self {
162        self.wallets = Some(wallets);
163        self
164    }
165
166    /// Set the fuzzer inspector.
167    #[inline]
168    pub fn fuzzer(mut self, fuzzer: Fuzzer) -> Self {
169        self.fuzzer = Some(fuzzer);
170        self
171    }
172
173    /// Set the Chisel inspector.
174    #[inline]
175    pub fn chisel_state(mut self, final_pc: Option<usize>) -> Self {
176        self.chisel_state = Some(ChiselState::new(final_pc));
177        self
178    }
179
180    /// Set the log collector, and whether to print the logs directly to stdout.
181    #[inline]
182    pub const fn logs(mut self, live_logs: bool) -> Self {
183        self.logs = Some(live_logs);
184        self
185    }
186
187    /// Set whether to collect line coverage information.
188    #[inline]
189    pub const fn line_coverage(mut self, yes: bool) -> Self {
190        self.line_coverage = Some(yes);
191        self
192    }
193
194    /// Set whether to enable the trace printer.
195    #[inline]
196    pub const fn print(mut self, yes: bool) -> Self {
197        self.print = Some(yes);
198        self
199    }
200
201    /// Set trace data requirements.
202    #[inline]
203    pub const fn trace_requirements(mut self, requirements: TraceRequirements) -> Self {
204        self.trace_requirements = self.trace_requirements.merge(requirements);
205        self
206    }
207
208    /// Set whether to enable the call isolation.
209    /// For description of call isolation, see [`InspectorStack::enable_isolation`].
210    #[inline]
211    pub const fn enable_isolation(mut self, yes: bool) -> Self {
212        self.enable_isolation = yes;
213        self
214    }
215
216    /// Set whether to prefetch the remote state of calls into fork contracts.
217    #[inline]
218    pub const fn fork_prefetch(mut self, yes: bool) -> Self {
219        self.fork_prefetch = yes;
220        self
221    }
222
223    /// Installs the Tempo label inspector.
224    #[inline]
225    pub(crate) fn tempo_labels(mut self, inspector: TempoLabels) -> Self {
226        self.tempo_labels = Some(Box::new(inspector));
227        self
228    }
229
230    /// Sets explicitly resolved additional cheatcode addresses.
231    #[inline]
232    pub const fn extra_cheatcode_addresses(mut self, addresses: &'static [Address]) -> Self {
233        self.extra_cheatcode_addresses = addresses;
234        self
235    }
236
237    #[inline]
238    pub const fn create2_deployer(mut self, create2_deployer: Address) -> Self {
239        self.create2_deployer = create2_deployer;
240        self
241    }
242
243    /// Builds the stack of inspectors to use when transacting/committing on the EVM.
244    pub fn build<FEN: FoundryEvmNetwork>(self) -> InspectorStack<FEN>
245    where
246        BLOCK: Into<BlockEnvFor<FEN>>,
247    {
248        let Self {
249            analysis,
250            block,
251            gas_price,
252            cheatcodes,
253            fuzzer,
254            trace_requirements,
255            logs,
256            line_coverage,
257            print,
258            chisel_state,
259            enable_isolation,
260            fork_prefetch,
261            tempo_labels,
262            extra_cheatcode_addresses,
263            wallets,
264            create2_deployer,
265        } = self;
266        let mut stack = InspectorStack::new();
267        // inspectors
268        if let Some(config) = cheatcodes {
269            let mut cheatcodes = Cheatcodes::new(config);
270            cheatcodes.set_extra_cheatcode_addresses(extra_cheatcode_addresses);
271            // Set analysis capabilities if they are provided
272            if let Some(analysis) = analysis {
273                stack.set_analysis(analysis.clone());
274                cheatcodes.core.set_analysis(CheatcodeAnalysis::new(analysis));
275            }
276            // Set wallets if they are provided
277            if let Some(wallets) = wallets {
278                cheatcodes.core.set_wallets(wallets);
279            }
280            stack.set_cheatcodes(cheatcodes);
281        }
282
283        if let Some(fuzzer) = fuzzer {
284            stack.set_fuzzer(fuzzer);
285        }
286        if let Some(chisel_state) = chisel_state {
287            stack.set_chisel(chisel_state);
288        }
289        stack.collect_line_coverage(line_coverage.unwrap_or(false));
290        stack.collect_logs(logs);
291        stack.print(print.unwrap_or(false));
292        stack.tracing_requirements(trace_requirements);
293
294        stack.enable_isolation(enable_isolation);
295        stack.fork_prefetch(fork_prefetch);
296        stack.inner.tempo_labels = tempo_labels;
297        stack.set_extra_cheatcode_addresses(extra_cheatcode_addresses);
298        stack.set_create2_deployer(create2_deployer);
299
300        // environment, must come after all of the inspectors
301        if let Some(block) = block {
302            stack.set_block(block.into());
303        }
304        if let Some(gas_price) = gas_price {
305            stack.set_gas_price(gas_price);
306        }
307
308        stack
309    }
310}
311
312/// Helper macro to call the same method on multiple inspectors without resorting to dynamic
313/// dispatch.
314#[macro_export]
315macro_rules! call_inspectors {
316    ([$($inspector:expr),+ $(,)?], |$id:ident $(,)?| $body:expr $(,)?) => {
317        $(
318            if let Some($id) = $inspector {
319                $crate::utils::cold_path();
320                $body;
321            }
322        )+
323    };
324    (#[ret] [$($inspector:expr),+ $(,)?], |$id:ident $(,)?| $body:expr $(,)?) => {{
325        $(
326            if let Some($id) = $inspector {
327                $crate::utils::cold_path();
328                if let Some(result) = $body {
329                    return result;
330                }
331            }
332        )+
333    }};
334}
335
336/// Runs an end hook on `$result` and returns whether it changed the frame's outcome from `$stop`:
337/// a different status or a revert with a different message.
338macro_rules! changed {
339    ($result:ident, $stop:ident, $call:expr) => {{
340        // Only a revert compares its output, so other outcomes skip the copy.
341        let previous_output = ($stop == InstrStop::Revert).then(|| $result.output.clone());
342        $call;
343        $result.stop != $stop
344            || previous_output.is_some_and(|previous_output| $result.output != previous_output)
345    }};
346}
347
348/// The collected results of [`InspectorStack`].
349pub struct InspectorData<FEN: FoundryEvmNetwork> {
350    pub logs: Vec<Log>,
351    pub labels: AddressHashMap<String>,
352    pub traces: Option<SparsedTraceArena>,
353    pub line_coverage: Option<HitMaps>,
354    pub edge_coverage: Option<EdgeCoverage>,
355    pub evm_cmp_values: Option<Vec<CmpOperands>>,
356    pub cheatcodes: Option<Box<Cheatcodes<FEN>>>,
357    pub chisel_state: Option<(Vec<U256>, Vec<u8>)>,
358    pub reverter: Option<Address>,
359}
360
361/// The root frame of a nested transaction that runs within a frame of the running transaction,
362/// such as an isolated call, the transaction of `vm.executeTransaction` or a transaction replayed
363/// by `vm.transact`.
364///
365/// A root frame that duplicates the surrounding frame skips the inspectors' call hooks, which the
366/// surrounding frame already ran, and starts at its depth, so the frames it starts keep their depth
367/// in the surrounding trace. An observed root frame is a new call one level below it.
368#[derive(Clone, Copy, Debug)]
369struct InnerRoot {
370    /// Depth of the surrounding frame.
371    depth: u16,
372    /// Sender of the nested transaction.
373    caller: Address,
374    /// Origin the nested transaction reads instead of its sender, such as the running
375    /// transaction's origin for an isolated call.
376    origin: Option<Address>,
377    /// Whether the root frame is a new call observed by the inspectors, such as a replayed
378    /// transaction's, rather than a duplicate of the surrounding frame.
379    observe: bool,
380}
381
382/// The opcodes at which execution cancellation is polled: every loop runs a jump, and every
383/// recursion runs a call or create.
384const CANCELLATION_POLL_OPCODES: OpcodeSet = {
385    let mut set = OpcodeSet::EMPTY;
386    set.insert(op::JUMP);
387    set.insert(op::JUMPI);
388    set.insert(op::CALL);
389    set.insert(op::CALLCODE);
390    set.insert(op::DELEGATECALL);
391    set.insert(op::STATICCALL);
392    set.insert(op::CREATE);
393    set.insert(op::CREATE2);
394    set
395};
396
397/// How many cancellation polls pass between reads of a campaign deadline.
398const DEADLINE_POLL_INTERVAL: u8 = 16;
399
400/// Bit of [`InspectorStackInner::stepped`]: a step inspector other than the cheatcodes stepped the
401/// running instruction and has a `step_end` hook.
402const STEPPED_STATIC: u8 = 1 << 0;
403
404/// Bit of [`InspectorStackInner::stepped`]: the cheatcodes stepped the running instruction.
405const STEPPED_CHEAT: u8 = 1 << 1;
406
407/// An inspector that calls multiple inspectors in sequence.
408///
409/// If a call to an inspector returns a value (indicating a stop or revert) the remaining inspectors
410/// are not called.
411///
412/// Stack is divided into [Cheatcodes] and `InspectorStackInner`. This is done to allow assembling
413/// [`InspectorStackRefMut`] inside [Cheatcodes] to allow usage of it as an evm2 [`Inspector`].
414/// This gives us ability to create and execute separate EVM frames from inside cheatcodes while
415/// still having access to entire stack of inspectors and correctly handling traces, logs,
416/// debugging info collection, etc.
417///
418/// The stack observes an execution through [`InspectorStack::as_inspector`], which pairs it with
419/// the backend the execution runs over.
420#[derive(Clone, Debug)]
421pub struct InspectorStack<FEN: FoundryEvmNetwork = EthEvmNetwork> {
422    pub cheatcodes: Option<Box<Cheatcodes<FEN>>>,
423    pub inner: InspectorStackInner,
424}
425
426#[cfg(test)]
427#[derive(Clone, Debug)]
428struct EarlyExitTestGate {
429    entered: std::sync::mpsc::Sender<()>,
430    release: Arc<std::sync::Mutex<std::sync::mpsc::Receiver<()>>>,
431    target_pc: usize,
432    notified: Arc<std::sync::atomic::AtomicBool>,
433}
434
435#[derive(Clone, Copy, Debug)]
436struct PendingCallTrace {
437    trace_idx: usize,
438    executed_address: Option<Address>,
439}
440
441/// All used inspectors besides [Cheatcodes].
442///
443/// See [`InspectorStack`].
444#[derive(Default, Clone, Debug)]
445pub struct InspectorStackInner {
446    /// Solar compiler instance, to grant syntactic and semantic analysis capabilities.
447    pub analysis: Option<Analysis>,
448
449    // Inspectors.
450    // These are boxed to reduce the size of the struct and slightly improve performance of the
451    // `if let Some` checks.
452    pub chisel_state: Option<Box<ChiselState>>,
453    pub debug_recorder: Option<Box<DebugRecorder>>,
454    pub edge_coverage: Option<Box<EdgeCovInspector>>,
455    pub fuzzer: Option<Box<Fuzzer>>,
456    pub line_coverage: Option<Box<LineCoverageCollector>>,
457    pub log_collector: Option<Box<LogCollector>>,
458    pub printer: Option<Box<CustomPrintTracer>>,
459    pub revert_diag: Option<Box<RevertDiagnostic>>,
460    pub script_execution_inspector: Option<Box<ScriptExecutionInspector>>,
461    pub tempo_labels: Option<Box<TempoLabels>>,
462    pub tracer: Option<Box<TracingInspector>>,
463
464    // FoundryInspectorExt and other internal data.
465    /// Whether to collect sancov edge coverage from instrumented native crates.
466    pub sancov_edges: bool,
467    /// Whether to capture sancov trace-cmp operands for dictionary injection.
468    pub sancov_trace_cmp: bool,
469    /// Whether the EVM executes the compiler-instrumented `EDGECOV` and `CMPLOG` opcodes, which
470    /// are undefined otherwise.
471    pub edgecov_opcode: bool,
472    /// Whether to collect `EDGECOV` hits as the call's edge coverage.
473    pub instrumented_edges: bool,
474    /// Whether to collect comparison operands from `CMPLOG` probes instead of the cmp-log
475    /// inspector.
476    pub instrumented_cmp_log: bool,
477    pub enable_isolation: bool,
478    /// Whether calls into fork contracts prefetch the remote state they are about to read, see
479    /// [`Backend::prefetch_call`](foundry_evm_core::backend::Backend::prefetch_call).
480    pub fork_prefetch: bool,
481    /// Additional addresses installed and recognized as cheatcode contracts.
482    pub extra_cheatcode_addresses: &'static [Address],
483    pub create2_deployer: Address,
484    /// Flag marking if we are in a nested transaction duplicating a frame of the running one.
485    pub in_inner_context: bool,
486    /// Depth of the frame the running nested transaction duplicates.
487    inner_root_depth: Option<u16>,
488    /// The root frame of the nested transaction about to start.
489    pending_inner_root: Option<InnerRoot>,
490    /// Synthetic CREATE depth corresponding to an outer top-level deployment.
491    synthetic_create_depth: Option<u16>,
492    /// Active fork and cheatcode fork epoch when the running isolated call started.
493    isolated_source_fork: Option<(Option<U256>, Option<u64>)>,
494    /// Warmth of the running isolated call when it succeeded after switching forks, even back to
495    /// the one it started on, captured before its transaction ended: its whole warm set, and the
496    /// accounts and slots it accessed or fork switches carried, without its transaction's base.
497    isolated_switch_warmth: Option<(PrewarmSet, AddressMap<HashSet<U256>>)>,
498    /// Whether the frame that just ended ran on a frame EVM with an in-flight environment change,
499    /// whose hooks already ran there. See `InspectorStackRefMut::env_handoff`.
500    env_handoff_ended: bool,
501    /// Accounts the running top-level transaction created, directly or through isolated calls,
502    /// with the forks it created them on.
503    tx_created: AddressMap<HashSet<Option<U256>>>,
504    /// Accounts the running nested transaction, from `executeTransaction` or an isolated call,
505    /// self-destructed, including the ones it created. Captured when its root frame ends, before
506    /// the transaction destroys them. An isolated call that replaces the running state, such as by
507    /// switching forks, still destroys them at once.
508    executed_destructs: Option<AddressMap<DestructedAccount>>,
509    /// Address that reverted the call, if any.
510    pub reverter: Option<Address>,
511    /// LIFO stack tracking the effective address of traced calls delegated to the EVM provider.
512    pending_call_traces: Vec<PendingCallTrace>,
513    /// Pending CREATE2 deployer validation error, returned after the create hooks of the other
514    /// inspectors so the trace stays balanced.
515    pending_create2_error: Option<Bytes>,
516    /// Counter for CREATE2 salt in `--batch` CREATE rewrites.
517    pub batch_create_counter: u64,
518    /// Whether the one-shot `--batch` rewrite warning has already been emitted.
519    pub batch_rewrite_warned: bool,
520    /// Per-inspector random seed mixed into `--batch` CREATE2 salts, ensuring re-runs
521    /// at identical on-chain state still produce distinct salts. Lazily initialized.
522    pub batch_rewrite_process_salt: Option<u64>,
523    /// Shared cancellation state for interruptible EVM execution.
524    execution_cancellation: Option<EvmExecutionCancellation>,
525    /// Counts cancellation polls; the deadline is read once every [`DEADLINE_POLL_INTERVAL`].
526    cancellation_poll_counter: u8,
527    /// Whether this inspector halted the current execution due to cancellation.
528    execution_cancelled: bool,
529    #[cfg(test)]
530    early_exit_test_gate: Option<EarlyExitTestGate>,
531    has_static_step_inspectors: bool,
532    has_static_step_end_inspectors: bool,
533    /// The opcodes the cheatcode step hooks run at, see [`Cheatcodes::hook_steps`]. Refreshed
534    /// where evm2 reads the inspector config again, when a frame starts and when a message
535    /// returns into it, since only cheatcode calls change it.
536    cheat_steps: OpcodeSet,
537    /// Whether the cheatcodes step `JUMPI` only to record it, see [`Cheatcodes::record_branch`].
538    cheat_records_branches: bool,
539    /// The opcodes the other step inspectors step, see [`Self::static_steps`]. Refreshed with
540    /// [`Self::cheat_steps`].
541    static_steps: OpcodeSet,
542    /// The opcodes of [`Self::static_steps`] that an inspector with a `step_end` hook steps.
543    static_end_steps: OpcodeSet,
544    /// The opcodes at which a step hook runs: every stepped opcode but the ones that only poll
545    /// the cancellation. Refreshed with [`Self::cheat_steps`].
546    hooked_steps: OpcodeSet,
547    /// Which hooks stepped the running instruction, as [`STEPPED_STATIC`] and [`STEPPED_CHEAT`].
548    stepped: u8,
549    /// [`Self::stepped`] of the instruction that made each message in flight. The frames of a
550    /// message overwrite [`Self::stepped`], and the instruction's `step_end` must run the static
551    /// hooks only if its `step` ran them.
552    suspended_stepped: Vec<u8>,
553}
554
555/// Mutable references to both parts of [InspectorStack] and the backend the execution runs over,
556/// implementing the evm2 [`Inspector`]. Obtained via [`InspectorStack::as_inspector`].
557pub struct InspectorStackRefMut<'a, FEN: FoundryEvmNetwork = EthEvmNetwork> {
558    pub cheatcodes: Option<&'a mut Cheatcodes<FEN>>,
559    pub inner: &'a mut InspectorStackInner,
560    /// The backend the execution runs over.
561    ///
562    /// Cheatcodes and call isolation are only active with a backend.
563    pub backend: &'a mut dyn CheatcodesBackend<FEN>,
564}
565
566impl<FEN: FoundryEvmNetwork> CheatcodesExecutor<FEN> for InspectorStackInner {
567    fn exec_message(
568        &mut self,
569        cheats: &mut Cheatcodes<FEN>,
570        backend: &mut dyn CheatcodesBackend<FEN>,
571        evm: &mut FoundryEvmFor<'_, FEN>,
572        message: &mut MessageFor<FEN>,
573    ) -> Result<MessageResultFor<FEN>, ExecutionError> {
574        let previous = self.synthetic_create_depth;
575        // A `deployCode` create called from the test contract duplicates a top-level deployment,
576        // so isolate it as well.
577        self.synthetic_create_depth = (message.depth == 2).then_some(2);
578        let env = evm_env(evm);
579        let result = self.execute_on_frame_evm(Some(cheats), backend, evm, env, message);
580        self.synthetic_create_depth = previous;
581        result
582    }
583
584    fn nested_transaction(
585        &mut self,
586        cheats: &mut Cheatcodes<FEN>,
587        backend: &mut dyn CheatcodesBackend<FEN>,
588        evm: &mut FoundryEvmFor<'_, FEN>,
589        depth: u16,
590        tx: &Recovered<TxFor<FEN>>,
591        env: Option<EvmEnvFor<FEN>>,
592    ) -> eyre::Result<TxResultFor<FEN>> {
593        let mut env = env.unwrap_or_else(|| evm_env(evm));
594        env.initial_call_depth = depth - TypesFor::<FEN>::tx_call_depth_offset(tx);
595        TypesFor::<FEN>::sync_transaction(evm);
596        let mut child = backend.backend().lifecycle().nested_evm(evm, tx, Some(env), None);
597        let previous = self.enter_inner_context(InnerRoot {
598            depth,
599            caller: tx.signer(),
600            origin: None,
601            observe: false,
602        });
603        // `ORIGIN` reads the nested transaction's signer, not the origin of an isolated call the
604        // transaction runs in.
605        let origin_override = cheats.origin_override.take();
606        let create2_redirects = cheats.pending_create2_redirects.len();
607        // The nested transaction has its own journal.
608        let snapshot_restores = mem::take(&mut cheats.snapshot_restores);
609        // The nested transaction's persistent writes refer to its own journal, so they are kept
610        // apart. Its root frame skips the cheatcode hooks, so they are handled below.
611        let outer_writes = mem::take(&mut cheats.persistent_writes);
612        let frame_rollback = cheats.frame_rollback.take();
613        let outer_destructs = self.executed_destructs.replace(AddressMap::default());
614        // The nested transaction's calls do not apply access lists to the running one.
615        let applied_access_list = cheats.applied_access_list.take();
616        child.set_inspector(InspectorStackRefMut {
617            cheatcodes: Some(&mut *cheats),
618            inner: &mut *self,
619            backend: &mut *backend,
620        });
621        let executed = child.transact(tx).map(ExecutedTx::detach);
622        // SAFETY: The nested EVM runs over the lifecycle's owned databases.
623        let mut child = unsafe { release_inspector(child) };
624        cheats.pending_create2_redirects.truncate(create2_redirects);
625        cheats.applied_access_list = applied_access_list;
626        let destructed = mem::replace(&mut self.executed_destructs, outer_destructs);
627        let result = match executed {
628            Ok(TxResultWithState { result, pending_state, .. }) => {
629                // A failed transaction keeps its nonce increment.
630                merge_untracked_pending_changes_with_warmth(
631                    evm.state_mut(),
632                    &mut child,
633                    pending_state,
634                    destructed.unwrap_or_default(),
635                )
636                .map(|persistent| (result, persistent))
637                .map_err(Into::into)
638            }
639            Err(err) => Err(transaction_error(err)),
640        };
641        drop(child);
642        // The merged changes include the writes of a successful transaction; a failed one rolled
643        // them back, so they are replayed over its merged changes. The writes it accepted
644        // outside its journal are dropped with its state.
645        let writes = mem::replace(&mut cheats.persistent_writes, outer_writes);
646        cheats.frame_rollback = frame_rollback;
647        let result = result.and_then(|(result, mut persistent)| {
648            if !result.is_success() {
649                let writes = writes
650                    .into_iter()
651                    .filter(|&(_, len, _)| len != 0)
652                    .map(|(.., write)| write)
653                    .collect::<Vec<_>>();
654                let applied = PersistentWrite::apply_all(&writes, evm.state_mut())?;
655                persistent.extend(
656                    writes.into_iter().filter(|write| !write.is_balance_or_nonce()).chain(applied),
657                );
658            }
659            cheats.record_persistent(usize::from(depth).saturating_sub(1), evm.state(), persistent);
660            Ok(result)
661        });
662        // The nested transaction's changes are not the running transaction's execution.
663        TypesFor::<FEN>::refresh_transaction(evm);
664        cheats.snapshot_restores = snapshot_restores;
665        cheats.origin_override = origin_override;
666        self.exit_inner_context(previous);
667        result
668    }
669
670    fn transact(
671        &mut self,
672        cheats: &mut Cheatcodes<FEN>,
673        backend: &mut dyn CheatcodesBackend<FEN>,
674        evm: &mut FoundryEvmFor<'_, FEN>,
675        depth: u16,
676        fork_id: Option<U256>,
677        transaction: B256,
678    ) -> eyre::Result<TxResultFor<FEN>> {
679        let (prepared, mut replay) = backend.backend().prepare_transact(
680            fork_id,
681            transaction,
682            evm,
683            depth + 1,
684            cheats.isolation_env.as_ref(),
685        )?;
686        let fork_id = replay.backend().active_fork_id();
687        let mut overrides = Default::default();
688        cheats.env_overrides.swap(fork_id, &mut overrides);
689        // The mined transaction starts with its own block's coinbase and its access list.
690        let tx_warm_addresses = mem::replace(
691            &mut cheats.tx_warm_addresses,
692            tx_warm_addresses(&prepared.env(), prepared.access_list()),
693        );
694        let executed = self.replay(cheats, &mut replay, evm, depth, prepared, false);
695        cheats.tx_warm_addresses = tx_warm_addresses;
696        cheats.env_overrides.swap(fork_id, &mut overrides);
697        drop(replay);
698        let mut executed = executed.wrap_err("backend: failed committing transaction")?;
699        cheats.record_persistent(
700            usize::from(depth).saturating_sub(1),
701            evm.state(),
702            executed.take_persistent(),
703        );
704        Ok(backend.backend_mut().store_executed(evm, executed))
705    }
706
707    fn transact_from_tx(
708        &mut self,
709        cheats: &mut Cheatcodes<FEN>,
710        backend: &mut dyn CheatcodesBackend<FEN>,
711        evm: &mut FoundryEvmFor<'_, FEN>,
712        depth: u16,
713        tx: &Recovered<TxFor<FEN>>,
714        env: Option<EvmEnvFor<FEN>>,
715    ) -> eyre::Result<TxResultFor<FEN>> {
716        let mut env = env.unwrap_or_else(|| evm_env(evm));
717        env.initial_call_depth = depth + 1 - TypesFor::<FEN>::tx_call_depth_offset(tx);
718        let (prepared, mut replay) = backend.backend().prepare_nested(tx.clone(), evm, Some(env));
719        let mut executed = self.replay(cheats, &mut replay, evm, depth, prepared, true)?;
720        drop(replay);
721        let caller_depth = usize::from(depth).saturating_sub(1);
722        cheats.record_persistent(caller_depth, evm.state(), executed.take_persistent());
723        cheats.record_accepted(caller_depth, executed.take_accepted());
724        Ok(backend.backend_mut().store_executed(evm, executed))
725    }
726
727    fn console_log(&mut self, msg: &str) {
728        if let Some(collector) = &mut self.log_collector {
729            collector.console_log(msg);
730        }
731    }
732
733    fn tracing_inspector(&mut self) -> Option<&mut TracingInspector> {
734        self.tracer.as_deref_mut()
735    }
736}
737
738impl<FEN: FoundryEvmNetwork> Default for InspectorStack<FEN> {
739    fn default() -> Self {
740        Self::new()
741    }
742}
743
744impl<FEN: FoundryEvmNetwork> InspectorStack<FEN> {
745    /// Creates a new inspector stack.
746    ///
747    /// Note that the stack is empty by default, and you must add inspectors to it.
748    /// This is done by calling the `set_*` methods on the stack directly, or by building the stack
749    /// with [`InspectorStack`].
750    #[inline]
751    pub fn new() -> Self {
752        Self { cheatcodes: None, inner: InspectorStackInner::default() }
753    }
754
755    /// Set the solar compiler instance.
756    #[inline]
757    pub fn set_analysis(&mut self, analysis: Analysis) {
758        self.analysis = Some(analysis);
759    }
760
761    /// Set the cancellation state checked during EVM execution.
762    #[inline]
763    pub(crate) fn set_early_exit(&mut self, early_exit: EarlyExit) {
764        self.set_execution_cancellation(EvmExecutionCancellation::early_exit(early_exit));
765    }
766
767    /// Stops EVM execution at `deadline`, or earlier on the process-wide early-exit signal.
768    #[inline]
769    pub fn set_execution_deadline(&mut self, early_exit: EarlyExit, deadline: Instant) {
770        self.set_execution_cancellation(EvmExecutionCancellation::campaign(
771            early_exit,
772            Arc::new(AtomicBool::new(false)),
773            Some(deadline),
774        ));
775    }
776
777    /// Set the complete cancellation state checked during EVM execution.
778    #[inline]
779    pub(crate) fn set_execution_cancellation(&mut self, cancellation: EvmExecutionCancellation) {
780        self.execution_cancellation = Some(cancellation);
781    }
782
783    /// Returns whether this inspector halted execution due to cancellation.
784    #[inline]
785    pub(crate) const fn execution_cancelled(&self) -> bool {
786        self.inner.execution_cancelled
787    }
788
789    #[cfg(test)]
790    pub(crate) fn set_early_exit_test_gate(
791        &mut self,
792        entered: std::sync::mpsc::Sender<()>,
793        release: std::sync::mpsc::Receiver<()>,
794        target_pc: usize,
795    ) {
796        self.early_exit_test_gate = Some(EarlyExitTestGate {
797            entered,
798            release: Arc::new(std::sync::Mutex::new(release)),
799            target_pc,
800            notified: Arc::new(std::sync::atomic::AtomicBool::new(false)),
801        });
802    }
803
804    /// Sets the block for the relevant inspectors.
805    #[inline]
806    pub fn set_block(&mut self, block: BlockEnvFor<FEN>) {
807        if let Some(cheatcodes) = &mut self.cheatcodes {
808            cheatcodes.block = Some(block);
809        }
810    }
811
812    /// Sets the gas price for the relevant inspectors.
813    #[inline]
814    pub fn set_gas_price(&mut self, gas_price: u128) {
815        if let Some(cheatcodes) = &mut self.cheatcodes {
816            cheatcodes.gas_price = Some(gas_price);
817        }
818    }
819
820    /// Set the cheatcodes inspector.
821    #[inline]
822    pub fn set_cheatcodes(&mut self, cheatcodes: Cheatcodes<FEN>) {
823        self.cheatcodes = Some(cheatcodes.into());
824    }
825
826    /// Set the fuzzer inspector.
827    #[inline]
828    pub fn set_fuzzer(&mut self, fuzzer: Fuzzer) {
829        self.fuzzer = Some(fuzzer.into());
830    }
831
832    /// Set the Chisel inspector.
833    #[inline]
834    pub fn set_chisel(&mut self, chisel: ChiselState) {
835        self.chisel_state = Some(chisel.into());
836        self.refresh_static_opcode_dispatch();
837    }
838
839    /// Set whether to enable the line coverage collector.
840    #[inline]
841    pub fn collect_line_coverage(&mut self, yes: bool) {
842        self.line_coverage = yes.then(Default::default);
843        self.refresh_static_step_dispatch();
844    }
845
846    /// Set whether to enable the edge coverage collector with default config.
847    #[inline]
848    pub fn collect_edge_coverage(&mut self, yes: bool) {
849        self.edge_coverage = yes.then(|| EdgeCovInspector::default().into());
850        self.refresh_static_step_dispatch();
851    }
852
853    /// Enable edge coverage with an explicit configuration.
854    #[inline]
855    pub fn collect_edge_coverage_with_edge_config(&mut self, config: EdgeCovConfig) {
856        self.edge_coverage = Some(EdgeCovInspector::with_config(config).into());
857        self.refresh_static_step_dispatch();
858    }
859
860    /// Configure the edge coverage collector from a [`FuzzCorpusConfig`].
861    ///
862    /// Derives both the on/off gate and [`EdgeCovConfig`] from `corpus`.
863    #[inline]
864    pub fn collect_edge_coverage_with_config(&mut self, corpus: &FuzzCorpusConfig) {
865        self.edge_coverage = corpus.collect_evm_edge_coverage().then(|| {
866            let kind = if corpus.evm_edge_coverage_collision_free() {
867                EdgeCovKind::CollisionFree
868            } else {
869                EdgeCovKind::Hash
870            };
871            let include_call_depth = corpus.evm_edge_coverage_include_call_depth();
872            EdgeCovInspector::with_config(EdgeCovConfig::new(kind, include_call_depth)).into()
873        });
874        self.inner.instrumented_edges = corpus.collect_instrumented_edges();
875        self.inner.instrumented_cmp_log = false;
876        self.inner.edgecov_opcode |= self.inner.instrumented_edges;
877        self.refresh_static_step_dispatch();
878    }
879
880    /// Set whether the EVM executes the compiler-instrumented `EDGECOV` and `CMPLOG` opcodes, so
881    /// that instrumented code also runs outside coverage-guided campaigns.
882    #[inline]
883    pub const fn enable_edgecov_opcode(&mut self, yes: bool) {
884        self.inner.edgecov_opcode = yes;
885    }
886
887    /// Drops the inspectors that only feed fuzz guidance: edge coverage, the fuzzer value
888    /// collector, and sancov collection. Calls whose coverage and collected values are never
889    /// merged back, such as invariant predicate checks, run faster without them.
890    #[inline]
891    pub fn disable_fuzz_instrumentation(&mut self) {
892        self.edge_coverage = None;
893        self.fuzzer = None;
894        self.sancov_edges = false;
895        self.sancov_trace_cmp = false;
896        self.instrumented_edges = false;
897        self.instrumented_cmp_log = false;
898        self.refresh_static_step_dispatch();
899    }
900
901    /// Set whether to collect EVM comparison operands.
902    #[inline]
903    pub fn collect_evm_cmp_log(&mut self, yes: bool) {
904        // Instrumented code logs its comparisons through `CMPLOG` probes, without an inspector
905        // stepping every opcode.
906        if self.inner.instrumented_edges {
907            self.inner.instrumented_cmp_log = yes;
908            return;
909        }
910        if yes {
911            self.edge_coverage
912                .get_or_insert_with(|| EdgeCovInspector::with_cmp_log_only().into())
913                .enable_cmp_log(true);
914        } else if let Some(edge_coverage) = &mut self.edge_coverage {
915            edge_coverage.enable_cmp_log(false);
916        }
917        self.refresh_static_step_dispatch();
918    }
919
920    /// Set whether to collect sancov edge coverage from instrumented native crates.
921    #[inline]
922    pub const fn collect_sancov_edges(&mut self, yes: bool) {
923        self.inner.sancov_edges = yes;
924    }
925
926    /// Set whether to capture sancov trace-cmp operands for dictionary injection.
927    #[inline]
928    pub const fn collect_sancov_trace_cmp(&mut self, yes: bool) {
929        self.inner.sancov_trace_cmp = yes;
930    }
931
932    /// Set whether to record the failure identity of each call, see
933    /// [`RawCallResult::failure_identity`](crate::executors::RawCallResult::failure_identity).
934    ///
935    /// Steps every instruction while set, so it is only meant for replays of a failure.
936    #[inline]
937    pub fn collect_failure_identity(&mut self, yes: bool) {
938        if let Some(cheatcodes) = &mut self.cheatcodes {
939            cheatcodes.failure_trace = yes.then(Default::default);
940        }
941    }
942
943    /// Set whether recording failure identities is paused, see [`Self::collect_failure_identity`].
944    ///
945    /// Calls made while paused still skip cheatcodes with effects outside the EVM, but do not step
946    /// every instruction and have no identity.
947    #[inline]
948    pub fn pause_failure_identity(&mut self, yes: bool) {
949        if let Some(trace) = self.cheatcodes.as_mut().and_then(|c| c.failure_trace.as_mut()) {
950            trace.paused = yes;
951        }
952    }
953
954    /// Returns whether a call skipped a cheatcode with effects outside the EVM while recording
955    /// failure identities, and clears it for the copies of this stack that share it.
956    pub fn take_skipped_host_effects(&self) -> bool {
957        self.cheatcodes
958            .as_ref()
959            .and_then(|c| c.failure_trace.as_ref())
960            .is_some_and(|trace| trace.take_skipped_host_effects())
961    }
962
963    /// Set whether to record the failure provenance of each call, see
964    /// [`RawCallResult::failure_provenance`](crate::executors::RawCallResult::failure_provenance).
965    ///
966    /// Only steps `JUMPI`, `REVERT` and `INVALID` and hashes the site of each call, so it can stay
967    /// set during campaigns.
968    #[inline]
969    pub fn collect_failure_provenance(&mut self, yes: bool) {
970        if let Some(cheatcodes) = &mut self.cheatcodes {
971            cheatcodes.failure_provenance = yes.then(Default::default);
972        }
973    }
974
975    /// Set whether to enable call isolation.
976    #[inline]
977    pub const fn enable_isolation(&mut self, yes: bool) {
978        self.inner.enable_isolation = yes;
979    }
980
981    /// Set whether calls into fork contracts prefetch the remote state they are about to read.
982    #[inline]
983    pub const fn fork_prefetch(&mut self, yes: bool) {
984        self.inner.fork_prefetch = yes;
985    }
986
987    /// Returns additional addresses installed and recognized as cheatcode contracts.
988    #[inline]
989    pub const fn extra_cheatcode_addresses(&self) -> &'static [Address] {
990        self.inner.extra_cheatcode_addresses
991    }
992
993    /// Sets additional addresses installed and recognized as cheatcode contracts.
994    #[inline]
995    pub const fn set_extra_cheatcode_addresses(&mut self, addresses: &'static [Address]) {
996        self.inner.extra_cheatcode_addresses = addresses;
997    }
998
999    /// Set the CREATE2 deployer address.
1000    #[inline]
1001    pub fn set_create2_deployer(&mut self, deployer: Address) {
1002        self.create2_deployer = deployer;
1003    }
1004
1005    /// Set whether to enable the log collector.
1006    /// - None for no log collection.
1007    /// - Some(true) for realtime console.log-ing.
1008    /// - Some(false) for log collection.
1009    #[inline]
1010    pub fn collect_logs(&mut self, live_logs: Option<bool>) {
1011        self.log_collector = live_logs.map(|live_logs| {
1012            Box::new(if live_logs {
1013                LogCollector::LiveLogs
1014            } else {
1015                LogCollector::Capture { logs: Vec::new() }
1016            })
1017        });
1018    }
1019
1020    /// Set whether to enable the trace printer.
1021    #[inline]
1022    pub fn print(&mut self, yes: bool) {
1023        self.printer = yes.then(Default::default);
1024        self.refresh_static_opcode_dispatch();
1025    }
1026
1027    /// Set trace data requirements.
1028    #[inline]
1029    pub fn tracing_requirements(&mut self, requirements: TraceRequirements) {
1030        let config = requirements.into_config();
1031        self.revert_diag = config.is_some().then(RevertDiagnostic::default).map(Into::into);
1032
1033        if let Some(config) = config {
1034            match &mut self.tracer {
1035                Some(tracer) => *tracer.config_mut() = config,
1036                None => self.tracer = Some(Box::new(TracingInspector::new(config))),
1037            }
1038        } else {
1039            self.tracer = None;
1040        }
1041        if requirements.debug_recording() {
1042            self.debug_recorder.get_or_insert_with(Default::default);
1043        } else {
1044            self.debug_recorder = None;
1045        }
1046        self.refresh_static_opcode_dispatch();
1047    }
1048
1049    /// Replaces the tracer, such as with one taken before changing the trace requirements.
1050    /// Revert diagnostics only annotate trace nodes, so they follow the tracer.
1051    #[inline]
1052    pub fn set_tracer(&mut self, tracer: Option<Box<TracingInspector>>) {
1053        if tracer.is_none() {
1054            self.revert_diag = None;
1055        } else if self.revert_diag.is_none() {
1056            self.revert_diag = Some(Default::default());
1057        }
1058        self.tracer = tracer;
1059        self.refresh_static_opcode_dispatch();
1060    }
1061
1062    /// Set whether to enable script execution inspector.
1063    #[inline]
1064    pub fn script(&mut self, script_address: Address) {
1065        self.script_execution_inspector.get_or_insert_with(Default::default).script_address =
1066            script_address;
1067        if let Some(cheatcodes) = &mut self.cheatcodes {
1068            cheatcodes.script_address = Some(script_address);
1069        }
1070        self.refresh_static_step_dispatch();
1071    }
1072
1073    /// Returns the stack as an evm2 inspector of an execution over `backend`.
1074    #[inline(always)]
1075    pub fn as_inspector<'a>(
1076        &'a mut self,
1077        backend: &'a mut dyn CheatcodesBackend<FEN>,
1078    ) -> InspectorStackRefMut<'a, FEN> {
1079        InspectorStackRefMut {
1080            cheatcodes: self.cheatcodes.as_deref_mut(),
1081            inner: &mut self.inner,
1082            backend,
1083        }
1084    }
1085
1086    /// Collects all the data gathered during inspection into a single struct.
1087    pub fn collect(self) -> InspectorData<FEN> {
1088        let Self {
1089            mut cheatcodes,
1090            inner:
1091                InspectorStackInner {
1092                    chisel_state,
1093                    mut debug_recorder,
1094                    line_coverage,
1095                    edge_coverage,
1096                    log_collector,
1097                    tempo_labels,
1098                    tracer,
1099                    revert_diag,
1100                    reverter,
1101                    ..
1102                },
1103        } = self;
1104
1105        let trace_diagnostics =
1106            revert_diag.map(|revert_diag| revert_diag.into_diagnostics()).unwrap_or_default();
1107
1108        let traces = tracer.map(|tracer| tracer.into_traces()).map(|arena| {
1109            let ignored = cheatcodes
1110                .as_mut()
1111                .map(|cheatcodes| {
1112                    let mut ignored = std::mem::take(&mut cheatcodes.ignored_traces.ignored);
1113
1114                    // If the last pause call was not resumed, ignore the rest of the trace
1115                    if let Some(last_pause_call) = cheatcodes.ignored_traces.last_pause_call {
1116                        ignored.insert(last_pause_call, (arena.nodes().len(), 0));
1117                    }
1118
1119                    ignored
1120                })
1121                .unwrap_or_default();
1122
1123            let mut traces = SparsedTraceArena {
1124                arena,
1125                ignored,
1126                diagnostics: trace_diagnostics,
1127                debug_steps: debug_recorder.as_deref_mut().map(DebugRecorder::finish),
1128            };
1129            traces.lift_single_top_level_call();
1130            traces
1131        });
1132
1133        let (edge_coverage, evm_cmp_values) = edge_coverage
1134            .map(|edge_coverage| {
1135                let (hitcount, cmp_values) = edge_coverage.into_parts();
1136                (Some(hitcount), (!cmp_values.is_empty()).then_some(cmp_values))
1137            })
1138            .unwrap_or_default();
1139
1140        InspectorData {
1141            logs: log_collector.and_then(|logs| logs.into_captured_logs()).unwrap_or_default(),
1142            labels: {
1143                let mut labels =
1144                    cheatcodes.as_ref().map(|c| c.core.labels.clone()).unwrap_or_default();
1145                if let Some(tempo_labels) = tempo_labels {
1146                    labels.extend(tempo_labels.labels);
1147                }
1148                labels
1149            },
1150            traces,
1151            line_coverage: line_coverage.map(|line_coverage| line_coverage.finish()),
1152            edge_coverage,
1153            evm_cmp_values,
1154            cheatcodes,
1155            chisel_state: chisel_state.and_then(|state| state.state),
1156            reverter,
1157        }
1158    }
1159}
1160
1161impl<FEN: FoundryEvmNetwork> InspectorStackRefMut<'_, FEN> {
1162    /// Whether the cheatcodes are active: installed, with a backend to run over.
1163    #[inline]
1164    fn cheats_and_backend(
1165        &mut self,
1166    ) -> Option<(&mut Cheatcodes<FEN>, &mut dyn CheatcodesBackend<FEN>, &mut InspectorStackInner)>
1167    {
1168        let cheats = self.cheatcodes.as_deref_mut()?;
1169        Some((cheats, &mut *self.backend, &mut *self.inner))
1170    }
1171
1172    /// Whether a frame at `depth` runs as an isolated transaction: a top-level frame one level
1173    /// below the transaction's root at `root`, or a synthetic `deployCode` create rewritten to a
1174    /// CREATE2 factory call.
1175    fn isolates(&self, root: u16, depth: u16) -> bool {
1176        self.inner.enable_isolation
1177            && !self.inner.in_inner_context
1178            && (depth == root + 1 || self.inner.synthetic_create_depth == Some(depth))
1179    }
1180
1181    /// Converts the result of a CREATE frame redirected to the CREATE2 factory, if `message` is
1182    /// one, into the result of the CREATE.
1183    fn finish_create2_redirect(
1184        &mut self,
1185        message: &MessageFor<FEN>,
1186        result: &mut MessageResultFor<FEN>,
1187    ) {
1188        if message.kind != MessageKind::Call {
1189            return;
1190        }
1191        let Some(cheats) = self.cheatcodes.as_deref_mut() else { return };
1192        if cheats.pending_create2_redirects.last().map(|(depth, ..)| *depth) != Some(message.depth)
1193        {
1194            return;
1195        }
1196        cheats.pending_create2_redirects.pop();
1197
1198        if result.stop.is_success() {
1199            match Address::try_from(result.output.as_ref()) {
1200                Ok(address) => {
1201                    result.created_address = Some(address);
1202                    result.output = Bytes::new();
1203                }
1204                Err(_) => {
1205                    result.stop = InstrStop::Revert;
1206                    result.output = "invalid CREATE2 factory output".into();
1207                    result.gas = GasTracker::new_with_execution_gas_and_reservoir(
1208                        message.gas_limit,
1209                        message.reservoir,
1210                    );
1211                    result.created_address = None;
1212                }
1213            }
1214        } else {
1215            result.created_address = None;
1216        }
1217    }
1218
1219    fn do_call_end(
1220        &mut self,
1221        interp: &mut InterpreterFor<'_, '_, FEN>,
1222        message: &MessageFor<FEN>,
1223        result: &mut MessageResultFor<FEN>,
1224    ) {
1225        let storage_hook_active =
1226            self.cheatcodes.as_deref().is_some_and(Cheatcodes::is_storage_hook_active);
1227        if !storage_hook_active && let Some(fuzzer) = &mut self.inner.fuzzer {
1228            Inspector::<TypesFor<FEN>>::call_end(&mut **fuzzer, interp, message, result);
1229        }
1230
1231        let stop = result.stop;
1232        let backend = Some(&mut *self.backend);
1233        let cheats = self.cheatcodes.as_deref_mut();
1234        'inspectors: {
1235            if let Some(tracer) = &mut self.inner.tracer
1236                && changed!(
1237                    result,
1238                    stop,
1239                    Inspector::<TypesFor<FEN>>::call_end(&mut **tracer, interp, message, result)
1240                )
1241            {
1242                break 'inspectors;
1243            }
1244            if let Some(recorder) = &mut self.inner.debug_recorder {
1245                Inspector::<TypesFor<FEN>>::call_end(&mut **recorder, interp, message, result);
1246            }
1247            if let (Some(cheats), Some(backend)) = (cheats, backend)
1248                && changed!(result, stop, cheats.call_end_hook(interp, message, result, backend))
1249            {
1250                break 'inspectors;
1251            }
1252            if let Some(printer) = &mut self.inner.printer
1253                && changed!(
1254                    result,
1255                    stop,
1256                    Inspector::<TypesFor<FEN>>::call_end(&mut **printer, interp, message, result)
1257                )
1258            {
1259                break 'inspectors;
1260            }
1261            if let Some(revert_diag) = &mut self.inner.revert_diag {
1262                Inspector::<TypesFor<FEN>>::call_end(&mut **revert_diag, interp, message, result);
1263            }
1264        }
1265
1266        // Record first address that reverted the call.
1267        if stop.is_frame_revert() && self.inner.reverter.is_none() {
1268            self.inner.reverter = Some(message.destination);
1269        }
1270    }
1271
1272    fn do_create_end(
1273        &mut self,
1274        interp: &mut InterpreterFor<'_, '_, FEN>,
1275        message: &MessageFor<FEN>,
1276        result: &mut MessageResultFor<FEN>,
1277    ) {
1278        let stop = result.stop;
1279        if !self.inner.in_inner_context
1280            && stop.is_success()
1281            && let Some(address) = result.created_address
1282        {
1283            let fork = self.backend.backend().active_fork_id();
1284            self.inner.tx_created.entry(address).or_default().insert(fork);
1285        }
1286        let backend = Some(&mut *self.backend);
1287        let cheats = self.cheatcodes.as_deref_mut();
1288        'inspectors: {
1289            if let Some(line_coverage) = &mut self.inner.line_coverage
1290                && changed!(
1291                    result,
1292                    stop,
1293                    Inspector::<TypesFor<FEN>>::create_end(
1294                        &mut **line_coverage,
1295                        interp,
1296                        message,
1297                        result
1298                    )
1299                )
1300            {
1301                break 'inspectors;
1302            }
1303            if let Some(tracer) = &mut self.inner.tracer
1304                && changed!(
1305                    result,
1306                    stop,
1307                    Inspector::<TypesFor<FEN>>::create_end(&mut **tracer, interp, message, result)
1308                )
1309            {
1310                break 'inspectors;
1311            }
1312            if let Some(recorder) = &mut self.inner.debug_recorder {
1313                Inspector::<TypesFor<FEN>>::create_end(&mut **recorder, interp, message, result);
1314            }
1315            if let (Some(cheats), Some(backend)) = (cheats, backend)
1316                && changed!(result, stop, cheats.create_end_hook(interp, message, result, backend))
1317            {
1318                break 'inspectors;
1319            }
1320            if let Some(printer) = &mut self.inner.printer {
1321                Inspector::<TypesFor<FEN>>::create_end(&mut **printer, interp, message, result);
1322            }
1323        }
1324    }
1325
1326    /// Executes `message` on a frame EVM with the spec and chain ID requested while the
1327    /// transaction is in flight, if they differ from the running EVM's.
1328    ///
1329    /// evm2 fixes the spec and chain ID of a running EVM, so a change deferred by an in-flight
1330    /// operation, such as `vm.chainId` or a fork switch, or requested by `vm.setEvmVersion`,
1331    /// moves new frames onto a frame EVM built with it while the running frames keep theirs, so the
1332    /// change applies to the frames started after it. The message's hooks run on the frame EVM.
1333    ///
1334    /// Cheatcode calls run on the running EVM: they execute no code, and the cheatcodes that read
1335    /// or change the environment act on the running EVM and the in-flight request.
1336    fn env_handoff(
1337        &mut self,
1338        interp: &mut InterpreterFor<'_, '_, FEN>,
1339        message: &mut MessageFor<FEN>,
1340    ) -> Option<MessageResultFor<FEN>> {
1341        if message.destination == CHEATCODE_ADDRESS
1342            || self.inner.extra_cheatcode_addresses.contains(&message.destination)
1343        {
1344            return None;
1345        }
1346        let backend = &mut *self.backend;
1347        let pending =
1348            backend.backend().lifecycle().pending_env().map(|env| (env.spec, env.chain_id()));
1349        let requested = self.cheatcodes.as_deref().and_then(|cheats| cheats.execution_evm_version);
1350        if pending.is_none() && requested.is_none() {
1351            return None;
1352        }
1353        let running = evm_env(interp.host());
1354        // Same precedence as the next transaction's environment: `vm.setEvmVersion` overrides
1355        // the pending spec.
1356        let (pending_spec, chain_id) = pending.unwrap_or((running.spec, running.chain_id()));
1357        let spec = requested.unwrap_or(pending_spec);
1358        if spec == running.spec && chain_id == running.chain_id() {
1359            return None;
1360        }
1361        let mut env = EvmFactoryFor::<FEN>::default().env_with_spec(running, spec);
1362        env.version.chain_id = chain_id;
1363        // The frame EVM's hooks see an interpreter for the message, so the step that started it
1364        // ends here, with the caller's.
1365        if let Some(recorder) = self.inner.debug_recorder.as_deref_mut() {
1366            recorder.end_step_before_frame(interp);
1367        }
1368        // The frame EVM's hooks see their own interpreter, not the caller's memory the input of
1369        // a call instruction's message is a range of.
1370        message.input = message.input.to_bytes(interp.memory()).into();
1371        // The new root interpreter describes the CREATE itself, so preserve its issuing code.
1372        let creator = (message.kind.is_create() && interp.message().depth < message.depth)
1373            .then_some(interp.message().code_address);
1374        let previous_creator = self
1375            .cheatcodes
1376            .as_deref_mut()
1377            .map(|cheats| mem::replace(&mut cheats.env_handoff_creator, creator));
1378        let evm = interp.host();
1379        let cheatcodes = self.cheatcodes.as_deref_mut();
1380        let result = self.inner.execute_on_frame_evm(cheatcodes, backend, evm, env, message);
1381        if let Some((cheats, previous)) = self.cheatcodes.as_deref_mut().zip(previous_creator) {
1382            cheats.env_handoff_creator = previous;
1383        }
1384        match result {
1385            Ok(result) => {
1386                // evm2 runs the end hooks right after this hook returns a result.
1387                self.inner.env_handoff_ended = true;
1388                Some(result)
1389            }
1390            Err(error) => {
1391                interp.fail(error);
1392                Some(message_result(message, InstrStop::Revert, Bytes::new()))
1393            }
1394        }
1395    }
1396
1397    /// Executes `message`, a top-level call or create of the running transaction, as a separate
1398    /// nested transaction, for precise gas accounting and transaction state changes.
1399    ///
1400    /// The nested transaction runs with a zero base fee and without fee charges, with the
1401    /// message's gas plus the transaction's intrinsic gas. Its state changes are merged into the
1402    /// running transaction as journaled writes, unless a cheatcode replaced the running state
1403    /// inside it, such as a state snapshot restoration or a fork switch, in which case the
1404    /// running transaction adopts the nested EVM's whole state.
1405    ///
1406    /// `precharged_state` is the account-creation state gas the CALL or CREATE opcode that created
1407    /// `message` already charged. It is credited as far as the nested transaction charges it again
1408    /// at its top level, which can differ when a prank or broadcast changed the destination.
1409    fn transact_inner(
1410        &mut self,
1411        interp: &mut InterpreterFor<'_, '_, FEN>,
1412        message: &MessageFor<FEN>,
1413        precharged_state: u64,
1414    ) -> MessageResultFor<FEN> {
1415        let precharged_state = if precharged_state == 0 {
1416            0
1417        } else {
1418            precharged_state.min(account_creation_state_gas::<FEN>(interp, message))
1419        };
1420        let tx_origin = interp.host().tx_env().origin;
1421        let is_create = matches!(message.kind, MessageKind::Create | MessageKind::Create2);
1422        let kind = if is_create { TxKind::Create } else { TxKind::Call(message.destination) };
1423        let input = message.input.to_bytes(interp.memory());
1424        let evm = interp.host();
1425        let version = *evm.version();
1426
1427        // Access lists do not exist before Berlin, including in isolated transactions.
1428        let access_list = self
1429            .cheatcodes
1430            .as_deref()
1431            .filter(|_| evm.spec_id() >= evm2::SpecId::BERLIN)
1432            .and_then(|cheats| cheats.core.access_list.clone());
1433        let (al_accounts, al_keys) = access_list.as_ref().map_or((0, 0), |list| {
1434            (list.len() as u64, list.iter().map(|item| item.storage_keys.len() as u64).sum())
1435        });
1436        let (intrinsic, floor) = intrinsic_and_floor_gas(
1437            &version,
1438            message.caller,
1439            kind,
1440            &input,
1441            al_accounts,
1442            al_keys,
1443            message.value,
1444        );
1445
1446        // Preserve the frame's regular gas and reservoir across the synthetic transaction
1447        // boundary, funding the precharged state gas from the reservoir. Raising the limit to an
1448        // EIP-7623 calldata floor above the frame's gas would give the frame more gas than it was
1449        // forwarded, so the nested transaction skips the floor, and the floor is charged to the
1450        // frame below.
1451        let mut env = evm_env(evm);
1452        let outer_env = env;
1453        let regular_limit = message.gas_limit.saturating_add(intrinsic);
1454        let mut gas_limit = regular_limit;
1455        if version.feature(EvmFeatures::EIP8037) {
1456            env.version.tx_gas_limit_cap = regular_limit;
1457            gas_limit =
1458                gas_limit.saturating_add(message.reservoir).saturating_add(precharged_state);
1459        }
1460        let skip_floor = floor > regular_limit;
1461        if skip_floor {
1462            env.set_feature(EvmFeatures::EIP7623, false);
1463        }
1464        if version.feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK) {
1465            gas_limit = gas_limit.min(env.block.gas_limit.saturating_to());
1466        }
1467        // The root keeps its depth in the surrounding trace, with a fresh call-depth budget.
1468        env.initial_call_depth = message.depth;
1469        let outer_basefee = env.block.basefee;
1470        env.block.basefee = U256::ZERO;
1471        env.set_feature(EvmFeatures::FEE_CHARGE, false);
1472        // A call without a fee charge skips the sender balance check, so an
1473        // underfunded value transfer fails in the call and keeps the nonce increment. An
1474        // underfunded create keeps the check, which leaves the nonce unchanged.
1475        if !is_create {
1476            env.set_feature(EvmFeatures::BALANCE_CHECK, false);
1477            env.set_feature(EvmFeatures::BALANCE_TOP_UP, false);
1478        }
1479
1480        let nonce = evm
1481            .state_mut()
1482            .account_info_untracked(&message.caller)
1483            .ok()
1484            .flatten()
1485            .map_or(0, |account| account.nonce);
1486        let mut request = TransactionRequestFor::<FEN>::default()
1487            .with_from(message.caller)
1488            .with_kind(kind)
1489            .with_input(input)
1490            .with_value(message.value)
1491            .with_nonce(nonce)
1492            .with_chain_id(env.chain_id())
1493            .with_gas_limit(gas_limit);
1494        if evm.spec_id() < evm2::SpecId::LONDON {
1495            request.set_gas_price(0);
1496        } else {
1497            request.set_max_fee_per_gas(0);
1498            request.set_max_priority_fee_per_gas(0);
1499        }
1500        if let Some(access_list) = access_list.clone() {
1501            request.set_access_list(access_list);
1502        }
1503        // A transaction that did not execute leaves the frame's reservoir untouched.
1504        let not_executed = |output: Bytes| {
1505            let mut outcome = message_result(message, InstrStop::Revert, output);
1506            outcome.gas = GasTracker::new_with_execution_gas_and_reservoir(
1507                message.gas_limit,
1508                message.reservoir,
1509            );
1510            outcome
1511        };
1512        let tx = match TypesFor::<FEN>::tx_from_request(request) {
1513            Ok(tx) => tx,
1514            Err(err) => return not_executed(err.to_string().into_bytes().into()),
1515        };
1516        env.initial_call_depth -= TypesFor::<FEN>::tx_call_depth_offset(&tx);
1517
1518        let backend = &mut *self.backend;
1519        let source_fork = backend.backend().active_fork_id();
1520        let epoch = self.cheatcodes.as_deref().map(|cheats| cheats.state_epoch);
1521        let fork_epoch = self.cheatcodes.as_deref().map(|cheats| cheats.fork_epoch);
1522        TypesFor::<FEN>::sync_transaction(evm);
1523        let mut child = backend.backend().lifecycle().nested_evm(evm, &tx, Some(env), None);
1524        // The nested transaction continues the running one's network extension state, such as
1525        // Monad's reserve balance context and tracker.
1526        *child.ext_mut() = evm.ext().clone();
1527        child.ext_mut().set_preserve_transaction_state(true);
1528        // Accounts the running transaction created and holds created on this fork, not ones it
1529        // created on another fork, stay created in the nested one, so that EIP-6780 SELFDESTRUCT
1530        // still deletes them, and keep the storage it holds for them. A revert past a fork switch
1531        // can drop the mark the switch restored, so an account created on this fork stays created
1532        // too, unless it is persistent, whose state can come from another fork. Only accounts the
1533        // running transaction loaded are checked, so checking loads no others.
1534        let state = evm.state_mut();
1535        let loaded = state
1536            .loaded_accounts()
1537            .map(|(address, _)| *address)
1538            .filter(|address| self.inner.tx_created.contains_key(address))
1539            .collect::<Vec<_>>();
1540        let held = loaded
1541            .into_iter()
1542            .filter(|address| {
1543                state.account(address).is_ok_and(|account| account.is_created())
1544                    || (self.inner.tx_created[address].contains(&source_fork)
1545                        && !backend.backend().is_persistent(address))
1546            })
1547            .collect::<AddressSet>();
1548        for address in &held {
1549            match child.state_mut().account(address) {
1550                Ok(mut account) => {
1551                    if account.exists() {
1552                        account.mark_created();
1553                    }
1554                }
1555                Err(_) => return not_executed(Bytes::new()),
1556            }
1557        }
1558
1559        // The nested transaction reads the running transaction's origin, cheatcodes route
1560        // environment changes through their opcode overrides while isolated, and fork revert
1561        // diagnostics compare against the nested transaction's target.
1562        let origin = self
1563            .cheatcodes
1564            .as_deref()
1565            .and_then(|cheats| cheats.origin_override)
1566            .unwrap_or(tx_origin);
1567        let previous_cheats = self.cheatcodes.as_deref_mut().map(|cheats| {
1568            let previous = cheats.origin_override.take();
1569            cheats.in_isolation_context = true;
1570            cheats.isolation_env = Some(outer_env);
1571            let root_call_target = mem::replace(
1572                &mut cheats.root_call_target,
1573                (!is_create).then_some(message.destination),
1574            );
1575            let tx_warm_addresses = mem::replace(
1576                &mut cheats.tx_warm_addresses,
1577                tx_warm_addresses(&env, access_list.as_ref()),
1578            );
1579            (previous, root_call_target, tx_warm_addresses)
1580        });
1581        let previous_inner = self.inner.enter_inner_context(InnerRoot {
1582            depth: message.depth,
1583            caller: message.caller,
1584            origin: (origin != message.caller).then_some(origin),
1585            observe: false,
1586        });
1587        let create2_redirects =
1588            self.cheatcodes.as_deref().map_or(0, |cheats| cheats.pending_create2_redirects.len());
1589        // The nested transaction has its own journal.
1590        let snapshot_restores =
1591            self.cheatcodes.as_deref_mut().map(|cheats| mem::take(&mut cheats.snapshot_restores));
1592
1593        let previous_source_fork =
1594            self.inner.isolated_source_fork.replace((source_fork, fork_epoch));
1595        // Taking warmth needs a mutable backend, which clones a borrowed one, so only take it
1596        // when there is any.
1597        let persistent_warmth = if backend.backend().lifecycle().has_persistent_warmth() {
1598            backend.backend_mut().take_persistent_warmth()
1599        } else {
1600            Vec::new()
1601        };
1602        // The accounts the call self-destructs keep their state until the running transaction ends,
1603        // unless the call replaces the running state, such as by switching forks.
1604        let outer_destructs = self.inner.executed_destructs.replace(AddressMap::default());
1605        child.set_inspector(InspectorStackRefMut {
1606            cheatcodes: self.cheatcodes.as_deref_mut(),
1607            inner: &mut *self.inner,
1608            backend: &mut *backend,
1609        });
1610        let executed = child.transact(&tx).map(|executed| executed.detach());
1611        // SAFETY: The nested EVM runs over the lifecycle's owned databases.
1612        let mut child = unsafe { release_inspector(child) };
1613        let destructed = mem::replace(&mut self.inner.executed_destructs, outer_destructs);
1614        self.inner.isolated_source_fork = previous_source_fork;
1615        if !persistent_warmth.is_empty() {
1616            backend.backend_mut().restore_persistent_warmth(persistent_warmth);
1617        }
1618        let switch_warmth = self.inner.isolated_switch_warmth.take();
1619
1620        self.inner.exit_inner_context(previous_inner);
1621        if let Some(cheats) = self.cheatcodes.as_deref_mut() {
1622            cheats.pending_create2_redirects.truncate(create2_redirects);
1623        }
1624        // A snapshot restoration that survived the nested transaction replaced its state.
1625        let restored = self.cheatcodes.as_deref_mut().zip(snapshot_restores).is_some_and(
1626            |(cheats, restores)| mem::replace(&mut cheats.snapshot_restores, restores).kept(),
1627        );
1628        if let (Some(cheats), Some((previous, root_call_target, tx_warm_addresses))) =
1629            (self.cheatcodes.as_deref_mut(), previous_cheats)
1630        {
1631            cheats.tx_warm_addresses = tx_warm_addresses;
1632            cheats.origin_override = previous;
1633            cheats.in_isolation_context = false;
1634            cheats.isolation_env = None;
1635            cheats.root_call_target = root_call_target;
1636        }
1637
1638        let executed = match executed {
1639            Ok(executed) => executed,
1640            // An underfunded create fails in its frame, without a nonce increment,
1641            // after its transaction paid the intrinsic gas.
1642            Err(HandlerError::InsufficientFunds { .. }) if is_create => {
1643                let mut outcome = not_executed(Bytes::new());
1644                if outcome.gas.spend(intrinsic.max(floor)).is_err() {
1645                    outcome.gas.spend_all();
1646                }
1647                return outcome;
1648            }
1649            // Should we match, encode and propagate error as a revert reason?
1650            Err(_) => return not_executed(Bytes::new()),
1651        };
1652        let mut result = executed.result;
1653        if skip_floor {
1654            result.floor_gas = floor;
1655        }
1656        // The accounts the call's state holds created, on the fork it ended on. A created account
1657        // the call self-destructed is kept until the running transaction ends.
1658        let fork = backend.backend().active_fork_id();
1659        let created = executed
1660            .pending_state
1661            .account_changes()
1662            .filter(|change| change.created && (change.current.is_some() || change.selfdestructed))
1663            .map(|change| change.address)
1664            .collect::<AddressSet>();
1665        for address in &created {
1666            self.inner.tx_created.entry(*address).or_default().insert(fork);
1667        }
1668
1669        let fork_changed = fork != source_fork;
1670        let replaced = restored
1671            || fork_changed
1672            || epoch != self.cheatcodes.as_deref().map(|cheats| cheats.state_epoch);
1673        // Accounts the running transaction holds cold, such as after `vm.cool` or a static call
1674        // cooled them, stay cold. Accounts it no longer holds, such as after a snapshot revert,
1675        // are imported warm.
1676        let state = evm.state_mut();
1677        let loaded = state.loaded_accounts().map(|(address, _)| *address).collect::<Vec<_>>();
1678        let cold = loaded
1679            .into_iter()
1680            .filter(|address| !state.account(address).is_ok_and(|account| account.is_warm()))
1681            .collect::<AddressSet>();
1682        let merged = if replaced {
1683            // Across another state replacement the running transaction keeps its warmth, and the
1684            // nested transaction's on success. A restored snapshot keeps the
1685            // running transaction's base warmth, a fork switch brings the nested transaction's
1686            // warmth, and a switch back to the starting fork keeps both.
1687            let warmth = if restored {
1688                Some(evm.state().prewarm_set().clone())
1689            } else if fork_changed {
1690                switch_warmth.map(|(warmth, _)| warmth)
1691            } else if let Some((_, accessed)) = switch_warmth {
1692                let mut warmth = warm_set(evm.state_mut());
1693                for (address, slots) in accessed {
1694                    warmth.warm_storage(&address, slots);
1695                }
1696                Some(warmth)
1697            } else {
1698                Some(warm_set(evm.state_mut()))
1699            };
1700            let warm =
1701                result.status.then(|| nested_warmth(child.state_mut(), &executed.pending_state));
1702            // Isolated calls never change the running transaction's transient storage.
1703            let transient = take_transient(evm.state_mut());
1704            child.overlay_db_mut().commit_pending(&executed.pending_state);
1705            // SAFETY: The nested EVM runs over the lifecycle's owned databases.
1706            unsafe { backend.backend().lifecycle().end_frame_evm(evm, child) };
1707            put_transient(evm.state_mut(), transient);
1708            if let Some(warmth) = warmth {
1709                *evm.state_mut().prewarm_set_mut() = warmth;
1710            } else if fork_changed && !restored {
1711                // Persistent slots the call had warmed when it switched forks stay warm after it
1712                // fails, without their accounts.
1713                let slots = backend.backend().lifecycle().switch_slots().clone();
1714                for (address, keys) in slots {
1715                    for key in keys {
1716                        let _ =
1717                            evm.state_mut().storage_slot(&address, key).map(|mut slot| slot.warm());
1718                    }
1719                }
1720            }
1721            // The new transaction overlay does not know which accounts the running transaction
1722            // holds created: the ones the call's state held created, the ones held created before
1723            // a call that kept the fork, and the ones it created on the fork the call ended on,
1724            // other than persistent accounts, whose state can come from another fork. Without the
1725            // mark, a later isolated call that loads them would merge them as new and wipe their
1726            // storage. Its database already holds their storage.
1727            for (address, forks) in &self.inner.tx_created {
1728                if (created.contains(address)
1729                    || (!fork_changed && held.contains(address))
1730                    || (forks.contains(&fork) && !backend.backend().is_persistent(address)))
1731                    && let Ok(mut account) = evm.state_mut().account(address)
1732                    && account.exists()
1733                {
1734                    account.mark_created();
1735                }
1736            }
1737            // Unless the call switched forks, the running transaction's state stays in place: it
1738            // keeps the warmth it had, except for accounts it holds cold.
1739            let keeps_cold = restored || !fork_changed;
1740            if keeps_cold {
1741                for address in &cold {
1742                    evm.state_mut().set_account_warm(address, false);
1743                }
1744            }
1745            let cold = if keeps_cold { cold } else { AddressSet::default() };
1746            warm.is_none_or(|warm| {
1747                warm_nested(evm.state_mut(), &executed.pending_state, warm, &cold).is_ok()
1748            })
1749        } else {
1750            let merged = merge_pending_changes(
1751                evm.state_mut(),
1752                &executed.pending_state,
1753                destructed.unwrap_or_default(),
1754                |_| true,
1755                None,
1756            )
1757            .and_then(|()| {
1758                let warm = nested_warmth(child.state_mut(), &executed.pending_state);
1759                warm_nested(evm.state_mut(), &executed.pending_state, warm, &cold)
1760            })
1761            .is_ok();
1762            // Keep cheatcode block changes and network extension state from the nested EVM.
1763            evm.set_block(*child.block());
1764            evm.ext_mut().replace_while_executing(child.ext().clone());
1765            merged
1766        };
1767        // The running transaction continues from the nested one's derived state, rebased onto
1768        // the merged state.
1769        evm.ext_mut().set_preserve_transaction_state(false);
1770        TypesFor::<FEN>::refresh_transaction(evm);
1771        let mut block = *evm.block();
1772        block.basefee = outer_basefee;
1773        evm.set_block(block);
1774
1775        // A failed transaction refunds its account-creation state gas, as the outer opcode does.
1776        let precharged_state = precharged_state.min(result.state_gas_spent());
1777        if let Some(cheats) = self.cheatcodes.as_deref_mut() {
1778            cheats
1779                .gas_metering
1780                .set_isolated_snapshot_gas_used(result.tx_gas_used(), precharged_state);
1781        }
1782
1783        // The transaction also pays its intrinsic gas and calldata floor, which can exceed the
1784        // gas forwarded to the frame. The frame then consumes its whole regular budget, as on an
1785        // exceptional halt.
1786        let mut gas =
1787            GasTracker::new_with_execution_gas_and_reservoir(message.gas_limit, message.reservoir);
1788        if gas.spend_state(result.state_gas_spent() - precharged_state).is_err()
1789            || gas.spend(result.execution_gas_spent()).is_err()
1790        {
1791            gas.spend_all();
1792        }
1793        let mut stop = result.stop;
1794        if !merged {
1795            stop = InstrStop::Revert;
1796        } else if result.status {
1797            gas.record_refund(result.final_refunded() as i64);
1798        }
1799
1800        // Pre-computed address for `expectRevert` reverter checks on reverted creates.
1801        let created_address = result
1802            .created_address
1803            .or_else(|| (is_create && stop.is_frame_revert()).then_some(message.destination));
1804        let mut outcome = message_result::<_, _>(message, stop, result.output);
1805        outcome.gas = gas;
1806        outcome.created_address = created_address;
1807        outcome
1808    }
1809
1810    /// Invoked at the beginning of a new top-level frame, at the EVM's initial call depth.
1811    fn top_level_frame_start(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1812        warm_arbitrum_system_contract::<FEN>(interp);
1813        self.inner.tx_created.clear();
1814        // A transaction that ended with an error skipped the end hooks that pop the suspended
1815        // steps; keep only the entry this frame's message just pushed.
1816        let stale = self.inner.suspended_stepped.len().saturating_sub(1);
1817        self.inner.suspended_stepped.drain(..stale);
1818        if let Some(cheatcodes) = &mut self.cheatcodes {
1819            cheatcodes.root_depth = usize::from(interp.host().initial_call_depth());
1820            // Transactions run from the test or script carry no access list.
1821            cheatcodes.tx_warm_addresses = tx_warm_addresses(&evm_env(interp.host()), None);
1822            cheatcodes.clear_storage_hook_mapping_slots();
1823            cheatcodes.snapshot_restores = SnapshotRestores::default();
1824            // A transaction that ended with an error did not drop its persistent writes.
1825            cheatcodes.persistent_writes.clear();
1826            cheatcodes.persistent_write_snapshots.clear();
1827        }
1828    }
1829
1830    /// Captures the accounts a nested transaction self-destructed, including the ones it created,
1831    /// when its root frame ends, before the transaction destroys them. See
1832    /// [`destructed_accounts`].
1833    fn capture_executed_destructs(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1834        if let Some(destructs) = &mut self.inner.executed_destructs {
1835            match destructed_accounts(interp.host().state_mut()) {
1836                Ok(captured) => *destructs = captured,
1837                Err(err) => {
1838                    let _ = interp.fail(err);
1839                }
1840            }
1841        }
1842    }
1843
1844    /// Captures the warmth of an isolated call whose root frame succeeded on another fork than it
1845    /// started on, before its transaction ends and clears it.
1846    fn capture_switch_warmth(
1847        &mut self,
1848        interp: &mut InterpreterFor<'_, '_, FEN>,
1849        result: &MessageResultFor<FEN>,
1850    ) {
1851        let backend = &*self.backend;
1852        let switched = self.inner.isolated_source_fork.is_some_and(|(source, epoch)| {
1853            backend.backend().active_fork_id() != source
1854                || epoch != self.cheatcodes.as_deref().map(|cheats| cheats.fork_epoch)
1855        });
1856        self.inner.isolated_switch_warmth = (switched && result.is_success()).then(|| {
1857            let state = interp.host().state_mut();
1858            let mut accessed = backend.backend().lifecycle().active().carried_warmth().clone();
1859            for (address, slots) in warm_accounts(state) {
1860                accessed.entry(address).or_default().extend(slots);
1861            }
1862            (warm_set(state), accessed)
1863        });
1864    }
1865
1866    /// Handles the root frame of a nested transaction, returning whether `message` is one that
1867    /// skips the inspectors' hooks.
1868    fn start_inner_root(
1869        &mut self,
1870        interp: &mut InterpreterFor<'_, '_, FEN>,
1871        message: &mut MessageFor<FEN>,
1872    ) -> bool {
1873        let Some(root) = self.inner.pending_inner_root.take_if(|root| {
1874            message.depth == root.depth + u16::from(root.observe) && root.caller == message.caller
1875        }) else {
1876            return false;
1877        };
1878        warm_arbitrum_system_contract::<FEN>(interp);
1879        if let Some(origin) = root.origin {
1880            interp.host().tx_env_mut().origin = origin;
1881        }
1882        if !root.observe
1883            && !matches!(message.kind, MessageKind::Create | MessageKind::Create2)
1884            && let Some(cheatcodes) = self.cheatcodes.as_deref()
1885        {
1886            // Transaction messages use the original target, so resolve function mocks here too.
1887            apply_mocked_function(cheatcodes, interp, message);
1888        }
1889        !root.observe
1890    }
1891
1892    // We take extra care in optimizing `step` and `step_end`, as they're are likely the most
1893    // hot functions in all of Foundry.
1894
1895    #[inline(always)]
1896    fn step_inlined(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1897        #[cfg(test)]
1898        if interp.opcode() == op::JUMPDEST
1899            && let Some(gate) = &self.inner.early_exit_test_gate
1900            && interp.pc() == gate.target_pc
1901            && !gate.notified.swap(true, std::sync::atomic::Ordering::Relaxed)
1902        {
1903            let _ = gate.entered.send(());
1904            let _ = gate
1905                .release
1906                .lock()
1907                .expect("early-exit test gate lock poisoned")
1908                .recv_timeout(std::time::Duration::from_secs(1));
1909        }
1910
1911        // Other inspectors may step every opcode; only the poll opcodes count as polls.
1912        if let Some(cancellation) = &self.inner.execution_cancellation
1913            && CANCELLATION_POLL_OPCODES.contains(interp.opcode())
1914        {
1915            let poll_deadline = self.inner.cancellation_poll_counter == 0;
1916            self.inner.cancellation_poll_counter =
1917                (self.inner.cancellation_poll_counter + 1) % DEADLINE_POLL_INTERVAL;
1918            if poll_deadline {
1919                // Reading the clock makes a call, which the other polls must not pay a frame for.
1920                return self.step_at_deadline_poll(interp);
1921            }
1922            if cancellation.should_stop(false) {
1923                return self.cancel_execution(interp);
1924            }
1925        }
1926        self.step_hooks(interp);
1927    }
1928
1929    /// Polls the cancellation and its deadline, then runs the step hooks.
1930    #[cold]
1931    #[inline(never)]
1932    fn step_at_deadline_poll(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1933        if self.inner.execution_cancellation.as_ref().is_some_and(|c| c.should_stop(true)) {
1934            return self.cancel_execution(interp);
1935        }
1936        self.step_hooks(interp);
1937    }
1938
1939    /// Stops the frame because the execution was cancelled.
1940    #[cold]
1941    #[inline(never)]
1942    const fn cancel_execution(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1943        self.inner.execution_cancelled = true;
1944        interp.set_stop(InstrStop::Stop);
1945    }
1946
1947    /// Runs the step hooks of the inspectors that step the instruction, if any does.
1948    ///
1949    /// The frame steps the union of every inspector's opcodes and the cancellation poll's, so the
1950    /// instructions stepped only for the poll return from here without a call.
1951    #[inline(always)]
1952    fn step_hooks(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1953        if self.inner.hooked_steps.contains(interp.opcode()) {
1954            return self.step_hooks_slow(interp);
1955        }
1956        self.inner.stepped = 0;
1957    }
1958
1959    /// Runs the step hooks of the inspectors that step the instruction.
1960    #[inline(never)]
1961    fn step_hooks_slow(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1962        // Most instructions stepped for the cheatcodes skip the other inspectors.
1963        let inner = &mut *self.inner;
1964        let static_stepped = inner.static_steps.contains(interp.opcode());
1965        let cheat_stepped = inner.cheat_steps.contains(interp.opcode());
1966        let static_end_stepped = inner.static_end_steps.contains(interp.opcode());
1967        inner.stepped = if static_end_stepped { STEPPED_STATIC } else { 0 }
1968            | if cheat_stepped { STEPPED_CHEAT } else { 0 };
1969        if static_stepped {
1970            let storage_hook_active =
1971                self.cheatcodes.as_deref().is_some_and(Cheatcodes::is_storage_hook_active);
1972            if !storage_hook_active {
1973                call_inspectors!(
1974                    [
1975                        // These are sorted in definition order.
1976                        &mut inner.edge_coverage,
1977                        &mut inner.line_coverage,
1978                    ],
1979                    |inspector| Inspector::<TypesFor<FEN>>::step(&mut **inspector, interp),
1980                );
1981            }
1982            // An inspector with a `step_end` hook steps only the opcodes its `step_end` runs at,
1983            // so that each `step` is paired.
1984            if static_end_stepped {
1985                call_inspectors!(
1986                    [
1987                        // These are sorted in definition order. Chisel dumps the running
1988                        // transaction, not a nested one such as `vm.executeTransaction`'s.
1989                        inner.chisel_state.as_mut().filter(|_| !inner.in_inner_context),
1990                        &mut inner.printer,
1991                        &mut inner.revert_diag,
1992                        &mut inner.script_execution_inspector,
1993                        &mut inner.tracer,
1994                        &mut inner.debug_recorder,
1995                    ],
1996                    |inspector| Inspector::<TypesFor<FEN>>::step(&mut **inspector, interp),
1997                );
1998            } else if let Some(script) = inner.script_execution_inspector.as_deref_mut() {
1999                Inspector::<TypesFor<FEN>>::step(script, interp);
2000            }
2001        }
2002
2003        // Other inspectors may step instructions the cheatcodes do not.
2004        if cheat_stepped {
2005            if let Some((cheats, backend, _)) = self.cheats_and_backend() {
2006                crate::utils::cold_path();
2007                cheats.step_hook(interp, backend);
2008            }
2009        } else if self.inner.cheat_records_branches
2010            && interp.opcode() == op::JUMPI
2011            && let Some(cheats) = self.cheatcodes.as_deref_mut()
2012        {
2013            cheats.record_branch(interp);
2014        }
2015
2016        // evm2 skips `step_end` if an inspector halted the frame in `step`. Only a stack with step
2017        // inspectors can hold a recorder, so other stacks skip the check.
2018        if static_end_stepped
2019            && let Some(recorder) = self.inner.debug_recorder.as_deref_mut()
2020            && interp.result().is_err()
2021        {
2022            recorder.end_step_not_run();
2023        }
2024    }
2025
2026    #[inline(always)]
2027    fn step_end_inlined(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2028        if self.inner.stepped != 0 {
2029            self.step_end_hooks(interp);
2030        }
2031    }
2032
2033    /// Runs the step end hooks of the inspectors that stepped the instruction.
2034    #[inline(never)]
2035    fn step_end_hooks(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2036        let inner = &mut *self.inner;
2037        if inner.stepped & STEPPED_STATIC != 0 {
2038            call_inspectors!(
2039                [
2040                    // These are sorted in definition order.
2041                    inner.chisel_state.as_mut().filter(|_| !inner.in_inner_context),
2042                    &mut inner.printer,
2043                    &mut inner.revert_diag,
2044                    &mut inner.tracer,
2045                    &mut inner.debug_recorder,
2046                ],
2047                |inspector| Inspector::<TypesFor<FEN>>::step_end(&mut **inspector, interp),
2048            );
2049        }
2050
2051        if self.inner.stepped & STEPPED_CHEAT != 0
2052            && let Some((cheats, backend, inner)) = self.cheats_and_backend()
2053        {
2054            crate::utils::cold_path();
2055            cheats.step_end_hook(interp, backend, inner);
2056        }
2057    }
2058
2059    /// Reads the opcodes the cheatcodes and the other step inspectors step again.
2060    fn refresh_cheat_steps(&mut self) {
2061        let cheats = self.cheatcodes.as_deref();
2062        let hook_steps = cheats.map_or(OpcodeSet::EMPTY, Cheatcodes::hook_steps);
2063        let records_branches = !hook_steps.contains(op::JUMPI)
2064            && cheats.is_some_and(|cheats| cheats.failure_provenance.is_some());
2065        let inner = &mut *self.inner;
2066        inner.cheat_steps = hook_steps;
2067        inner.cheat_records_branches = records_branches;
2068        (inner.static_steps, inner.static_end_steps) = inner.static_steps::<FEN>();
2069        inner.hooked_steps = hook_steps.union(inner.static_steps);
2070        if records_branches {
2071            inner.hooked_steps.insert(op::JUMPI);
2072        }
2073    }
2074
2075    /// Saves which hooks stepped the instruction that makes a message, before the frames of the
2076    /// message overwrite it. [`Self::restore_cheat_stepped`] takes it back when the message ends.
2077    #[inline]
2078    fn suspend_stepped(&mut self) {
2079        let inner = &mut *self.inner;
2080        inner.suspended_stepped.push(inner.stepped);
2081    }
2082
2083    /// Refreshes the stepped opcodes after a message's end hooks finish mutating the inspectors'
2084    /// state, and restores which hooks stepped the instruction that made the message.
2085    ///
2086    /// The static hooks are paired: the instruction's `step_end` runs them only if its `step`
2087    /// did. The message can change the cheatcode state, so the cheatcode `step_end` hook runs
2088    /// whenever the cheatcodes step any instruction.
2089    fn restore_cheat_stepped(&mut self) {
2090        self.refresh_cheat_steps();
2091        let inner = &mut *self.inner;
2092        let suspended = inner.suspended_stepped.pop().unwrap_or_default();
2093        inner.stepped = (suspended & STEPPED_STATIC)
2094            | if inner.cheat_steps == OpcodeSet::EMPTY { 0 } else { STEPPED_CHEAT };
2095    }
2096
2097    /// Rewrites a CREATE frame into a call to the CREATE2 factory if the cheatcodes request it.
2098    ///
2099    /// Returns whether the frame was rewritten. If the factory is missing or invalid, the error is
2100    /// returned by the create hook after the other inspectors observed the frame.
2101    fn redirect_create2(
2102        &mut self,
2103        interp: &mut InterpreterFor<'_, '_, FEN>,
2104        message: &mut MessageFor<FEN>,
2105    ) -> bool {
2106        let depth = usize::from(message.depth);
2107        if !self
2108            .cheatcodes
2109            .as_deref_mut()
2110            .is_some_and(|cheats| cheats.should_use_create2_factory(depth, message))
2111        {
2112            return false;
2113        }
2114
2115        // The default factory runtime forwards CALLVALUE into CREATE2, so payable deploys are
2116        // supported on both the explicit `new C{salt, value}` path and the `--batch` path.
2117        let salt = match message.kind {
2118            MessageKind::Create2 => message.salt.into(),
2119            // --batch: process_salt (random per run) + counter make each deploy unique.
2120            // The nonce is from the EVM frame caller (script contract), not the EOA.
2121            MessageKind::Create => {
2122                if !self.inner.batch_rewrite_warned {
2123                    let _ = sh_warn!(
2124                        "--batch rewrites CREATE → CREATE2 via the Arachnid factory; \
2125                         deployed addresses follow the CREATE2 formula and constructor \
2126                         msg.sender is the factory, not the EOA."
2127                    );
2128                    self.inner.batch_rewrite_warned = true;
2129                }
2130                let chain_id = interp.host().version().chain_id;
2131                let Ok(Some(account)) =
2132                    interp.host().state_mut().account_info_untracked(&message.caller)
2133                else {
2134                    return false;
2135                };
2136                self.inner.next_batch_create_salt(chain_id, account.nonce)
2137            }
2138            _ => return false,
2139        };
2140
2141        let create2_deployer = self.inner.create2_deployer;
2142        let initcode = message.input.to_bytes(interp.memory());
2143        let state = interp.host().state_mut();
2144        let Ok(mut account) = state.account(&create2_deployer) else { return false };
2145        let code_hash = account.code_hash();
2146        if code_hash == alloy_primitives::KECCAK256_EMPTY {
2147            self.inner.pending_create2_error =
2148                Some(format!("missing CREATE2 deployer: {create2_deployer}").into_bytes().into());
2149            return false;
2150        } else if code_hash != DEFAULT_CREATE2_DEPLOYER_CODEHASH {
2151            self.inner.pending_create2_error = Some("invalid CREATE2 deployer bytecode".into());
2152            return false;
2153        }
2154        let Ok(code) = account.load_code() else { return false };
2155        account.warm();
2156        drop(account);
2157
2158        let mut input = Vec::with_capacity(32 + initcode.len());
2159        input.extend_from_slice(&B256::from(salt).0);
2160        input.extend_from_slice(&initcode);
2161
2162        if let Some(cheats) = self.cheatcodes.as_deref_mut() {
2163            cheats.start_create2_redirect(interp, message);
2164        }
2165        message.kind = MessageKind::Call;
2166        message.destination = create2_deployer;
2167        message.call_target = create2_deployer;
2168        message.code_address = create2_deployer;
2169        message.code = code;
2170        message.input = Bytes::from(input).into();
2171        message.salt = B256::ZERO;
2172        true
2173    }
2174
2175    /// Closes the snapshot restoration frame `message` ran in, if any, undoing the restorations
2176    /// made inside it if it failed.
2177    fn end_snapshot_frame(
2178        &mut self,
2179        interp: &mut InterpreterFor<'_, '_, FEN>,
2180        message: &MessageFor<FEN>,
2181        result: &MessageResultFor<FEN>,
2182    ) {
2183        if let Some(cheats) = self.cheatcodes.as_deref_mut() {
2184            let evm = interp.host();
2185            let features = evm.version().features;
2186            let failed = !result.stop.is_success();
2187            let end = cheats.snapshot_restores.frame_end(
2188                evm.state_mut(),
2189                &mut cheats.persistent_writes,
2190                message.depth,
2191                failed,
2192                features,
2193            );
2194            // A frame ends here once per hook layer, and only the layer that opened it returns
2195            // its checkpoint.
2196            if let Some(checkpoint) = end {
2197                cheats.frame_rollback =
2198                    Some((usize::from(message.depth), checkpoint.journal_len()));
2199            }
2200        }
2201    }
2202}
2203
2204impl<FEN: FoundryEvmNetwork> Inspector<TypesFor<FEN>> for InspectorStackRefMut<'_, FEN> {
2205    #[inline]
2206    fn inspector_config(&self) -> InspectorConfig {
2207        let inner = &*self.inner;
2208        #[cfg(test)]
2209        if inner.early_exit_test_gate.is_some() {
2210            return InspectorConfig::new();
2211        }
2212        let mut steps = self.cheatcodes.as_deref().map_or(OpcodeSet::EMPTY, Cheatcodes::steps);
2213        if inner.execution_cancellation.is_some() {
2214            steps = steps.union(CANCELLATION_POLL_OPCODES);
2215        }
2216        // evm2 reads the config after every call, so the common case without other stepping
2217        // inspectors skips the union below.
2218        if !inner.has_static_step_inspectors && !inner.has_static_step_end_inspectors {
2219            return InspectorConfig::new().with_steps(steps);
2220        }
2221        InspectorConfig::new().with_steps(steps.union(inner.static_steps::<FEN>().0))
2222    }
2223
2224    fn initialize_interp(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2225        self.refresh_cheat_steps();
2226        let depth = interp.message().depth;
2227        if let Some(cheats) = self.cheatcodes.as_deref_mut()
2228            && let Some(checkpoint) = interp.host().frame_checkpoint()
2229        {
2230            cheats.snapshot_restores.frame_start(depth, checkpoint.clone());
2231        }
2232
2233        let inner = &mut *self.inner;
2234        call_inspectors!(
2235            [
2236                inner.chisel_state.as_mut().filter(|_| !inner.in_inner_context),
2237                &mut inner.line_coverage,
2238                &mut inner.tracer,
2239            ],
2240            |inspector| Inspector::<TypesFor<FEN>>::initialize_interp(&mut **inspector, interp),
2241        );
2242        if let Some(cheats) = self.cheatcodes.as_deref_mut() {
2243            cheats.initialize_interp_hook(interp);
2244        }
2245        let inner = &mut *self.inner;
2246        call_inspectors!(
2247            [&mut inner.script_execution_inspector, &mut inner.printer],
2248            |inspector| Inspector::<TypesFor<FEN>>::initialize_interp(&mut **inspector, interp),
2249        );
2250    }
2251
2252    fn step(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2253        self.step_inlined(interp);
2254    }
2255
2256    fn step_end(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2257        self.step_end_inlined(interp);
2258    }
2259
2260    fn log(&mut self, log: &Log, host: &mut FoundryEvmFor<'_, FEN>) {
2261        let inner = &mut *self.inner;
2262        // Network transaction hooks emit logs outside any frame, such as Tempo's 2D nonce
2263        // increment and fee settlement. The tracer counts them in the log index but does not
2264        // trace them.
2265        call_inspectors!([&mut inner.tracer, &mut inner.log_collector], |inspector| {
2266            Inspector::<TypesFor<FEN>>::log(&mut **inspector, log, host)
2267        });
2268        if let Some(cheats) = self.cheatcodes.as_deref_mut()
2269            && cheats.has_log_hooks()
2270        {
2271            crate::utils::cold_path();
2272            cheats.log_hook(log);
2273        }
2274        call_inspectors!([&mut self.inner.printer], |inspector| {
2275            Inspector::<TypesFor<FEN>>::log(&mut **inspector, log, host)
2276        });
2277    }
2278
2279    fn call(
2280        &mut self,
2281        interp: &mut InterpreterFor<'_, '_, FEN>,
2282        message: &mut MessageFor<FEN>,
2283    ) -> Option<MessageResultFor<FEN>> {
2284        self.suspend_stepped();
2285        if self.start_inner_root(interp, message) {
2286            return None;
2287        }
2288        if let Some(result) = self.env_handoff(interp, message) {
2289            return Some(result);
2290        }
2291        if let Some(provenance) =
2292            self.cheatcodes.as_mut().and_then(|c| c.failure_provenance.as_mut())
2293        {
2294            provenance.enter_frame::<FEN>(usize::from(message.depth), interp);
2295        }
2296
2297        let depth = message.depth;
2298        // A transaction handler can run the top-level calls below the transaction, such as
2299        // Tempo's for the calls of an AA transaction.
2300        let root = interp.host().initial_call_depth();
2301        if depth == root && !self.inner.in_inner_context {
2302            self.top_level_frame_start(interp);
2303        }
2304
2305        if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2306            revert_diag.frame_start();
2307        }
2308
2309        // Delegate calls run inside a call that was already simulated.
2310        if self.inner.fork_prefetch
2311            && matches!(message.kind, MessageKind::Call | MessageKind::StaticCall)
2312        {
2313            self.backend.backend().prefetch_call(
2314                message.caller,
2315                message.destination,
2316                message.value,
2317                message.input.to_bytes(interp.memory()),
2318                depth == root && !self.inner.in_inner_context,
2319            );
2320        }
2321
2322        let storage_hook_callback = self
2323            .cheatcodes
2324            .as_deref()
2325            .is_some_and(|cheatcodes| cheatcodes.is_storage_hook_callback(message));
2326        let storage_hook_active =
2327            self.cheatcodes.as_deref().is_some_and(Cheatcodes::is_storage_hook_active);
2328
2329        if !storage_hook_active
2330            && let Some(fuzzer) = &mut self.inner.fuzzer
2331            && let Some(output) = Inspector::<TypesFor<FEN>>::call(&mut **fuzzer, interp, message)
2332        {
2333            return Some(output);
2334        }
2335
2336        if let Some(tracer) = self.inner.tracer.as_deref_mut() {
2337            crate::utils::cold_path();
2338            let output = Inspector::<TypesFor<FEN>>::call(tracer, interp, message);
2339            let trace_idx = tracer.traces().nodes().len() - 1;
2340            self.inner
2341                .pending_call_traces
2342                .push(PendingCallTrace { trace_idx, executed_address: None });
2343            if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2344                revert_diag.set_trace_node(trace_idx);
2345            }
2346            if output.is_some() {
2347                return output;
2348            }
2349        }
2350        if let Some(recorder) = self.inner.debug_recorder.as_deref_mut() {
2351            Inspector::<TypesFor<FEN>>::call(recorder, interp, message);
2352        }
2353
2354        let inner = &mut *self.inner;
2355        call_inspectors!(
2356            #[ret]
2357            [
2358                &mut inner.log_collector,
2359                &mut inner.printer,
2360                &mut inner.revert_diag,
2361                &mut inner.tempo_labels
2362            ],
2363            |inspector| Inspector::<TypesFor<FEN>>::call(&mut **inspector, interp, message)
2364                .map(Some),
2365        );
2366
2367        // Storage hook callbacks are instrumentation frames, not user calls. Let evm2 execute the
2368        // callback after tracing it, but do not apply mocks, pranks, broadcasts, or isolation.
2369        if storage_hook_callback {
2370            if let Some(pending) = self.inner.pending_call_traces.last_mut() {
2371                pending.executed_address = Some(message.code_address);
2372            }
2373            return None;
2374        }
2375
2376        // The tracer records call inputs before cheatcodes apply caller overrides such as pranks
2377        // and broadcasts. Keep the trace lifecycle ordering, but remember the node so its caller
2378        // can be synchronized with the inputs that are actually executed.
2379        let trace_idx = self.inner.tracer.as_ref().map(|tracer| tracer.traces().nodes().len() - 1);
2380        let isolate = self.isolates(root, depth);
2381        let precharged_state = if isolate && depth == root + 1 && message.kind == MessageKind::Call
2382        {
2383            account_creation_state_gas::<FEN>(interp, message)
2384        } else {
2385            0
2386        };
2387        let mut cheatcode_outcome = None;
2388        if let Some((cheats, backend, inner)) = self.cheats_and_backend() {
2389            apply_mocked_function(cheats, interp, message);
2390            cheatcode_outcome = cheats.call_with_executor(
2391                interp,
2392                message,
2393                backend,
2394                inner,
2395                isolate && message.kind == MessageKind::Call,
2396            );
2397        }
2398
2399        if let Some(trace_idx) = trace_idx
2400            && let Some(tracer) = self.inner.tracer.as_deref_mut()
2401        {
2402            let caller = match message.kind {
2403                MessageKind::DelegateCall | MessageKind::CallCode => message.destination,
2404                _ => message.caller,
2405            };
2406            let node = &mut tracer.traces_mut().nodes_mut()[trace_idx];
2407            node.trace.caller = caller;
2408        }
2409
2410        if let Some(output) = cheatcode_outcome {
2411            return Some(output);
2412        }
2413
2414        if let Some(outcome) = handle_arbitrum_system_call::<FEN>(
2415            interp,
2416            message,
2417            self.backend.backend().active_fork_block_number(),
2418        ) {
2419            return Some(outcome);
2420        }
2421
2422        if let Some(pending) = self.inner.pending_call_traces.last_mut() {
2423            pending.executed_address = Some(message.code_address);
2424        }
2425
2426        if isolate {
2427            match message.kind {
2428                // Isolate CALLs.
2429                MessageKind::Call => {
2430                    return Some(self.transact_inner(interp, message, precharged_state));
2431                }
2432                // Mark accounts and storage cold before STATICCALLs.
2433                MessageKind::StaticCall => self.cool_for_static_call(interp),
2434                // Process other variants as usual.
2435                _ => {}
2436            }
2437        }
2438
2439        None
2440    }
2441
2442    fn call_end(
2443        &mut self,
2444        interp: &mut InterpreterFor<'_, '_, FEN>,
2445        message: &MessageFor<FEN>,
2446        result: &mut MessageResultFor<FEN>,
2447    ) {
2448        // A frame handed off to a frame EVM already ran its end hooks there.
2449        if mem::take(&mut self.inner.env_handoff_ended) {
2450            self.restore_cheat_stepped();
2451            return;
2452        }
2453        self.end_snapshot_frame(interp, message, result);
2454
2455        // The root frame of a nested transaction duplicates a frame whose hooks run in the
2456        // surrounding transaction.
2457        if self.inner.is_inner_context_root(message.depth) {
2458            self.capture_switch_warmth(interp, result);
2459            self.capture_executed_destructs(interp);
2460            self.restore_cheat_stepped();
2461            return;
2462        }
2463
2464        if let Some(pending) = self.inner.pending_call_traces.pop()
2465            && let Some(tracer) = self.inner.tracer.as_deref_mut()
2466        {
2467            let trace = &mut tracer.traces_mut().nodes_mut()[pending.trace_idx].trace;
2468            if trace.address == P256_VERIFY {
2469                trace.maybe_precompile = Some(
2470                    pending.executed_address == Some(P256_VERIFY)
2471                        && interp.host().precompiles().contains(&P256_VERIFY),
2472                );
2473            }
2474        }
2475
2476        self.do_call_end(interp, message, result);
2477
2478        if let Some(trace) = self.cheatcodes.as_mut().and_then(|c| c.failure_trace.as_mut()) {
2479            trace.finish_frame::<FEN>(usize::from(message.depth), result);
2480        }
2481        if let Some(provenance) =
2482            self.cheatcodes.as_mut().and_then(|c| c.failure_provenance.as_mut())
2483        {
2484            provenance.finish_frame::<FEN>(usize::from(message.depth), interp, result);
2485        }
2486        if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2487            revert_diag.frame_end();
2488        }
2489        self.restore_cheat_stepped();
2490    }
2491
2492    fn create(
2493        &mut self,
2494        interp: &mut InterpreterFor<'_, '_, FEN>,
2495        message: &mut MessageFor<FEN>,
2496    ) -> Option<MessageResultFor<FEN>> {
2497        self.suspend_stepped();
2498        if self.start_inner_root(interp, message) {
2499            return None;
2500        }
2501        if let Some(result) = self.env_handoff(interp, message) {
2502            return Some(result);
2503        }
2504
2505        // A CREATE redirected to the CREATE2 factory is observed as a call to the factory.
2506        if self.redirect_create2(interp, message) {
2507            // The call hook suspends the step again, and `create_end` ends it through `call_end`.
2508            self.inner.suspended_stepped.pop();
2509            return self.call(interp, message);
2510        }
2511        if let Some(provenance) =
2512            self.cheatcodes.as_mut().and_then(|c| c.failure_provenance.as_mut())
2513        {
2514            provenance.enter_frame::<FEN>(usize::from(message.depth), interp);
2515        }
2516
2517        let depth = message.depth;
2518        // A transaction handler can run the top-level calls below the transaction, such as
2519        // Tempo's for the calls of an AA transaction.
2520        let root = interp.host().initial_call_depth();
2521        if depth == root && !self.inner.in_inner_context {
2522            self.top_level_frame_start(interp);
2523        }
2524
2525        if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2526            revert_diag.frame_start();
2527        }
2528
2529        if let Some(tracer) = self.inner.tracer.as_deref_mut() {
2530            crate::utils::cold_path();
2531            let output = Inspector::<TypesFor<FEN>>::create(tracer, interp, message);
2532            let trace_idx = tracer.traces().nodes().len() - 1;
2533            if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2534                revert_diag.set_trace_node(trace_idx);
2535            }
2536            if output.is_some() {
2537                return output;
2538            }
2539        }
2540        if let Some(recorder) = self.inner.debug_recorder.as_deref_mut() {
2541            Inspector::<TypesFor<FEN>>::create(recorder, interp, message);
2542        }
2543
2544        if let Some(line_coverage) = &mut self.inner.line_coverage
2545            && let Some(output) =
2546                Inspector::<TypesFor<FEN>>::create(&mut **line_coverage, interp, message)
2547        {
2548            return Some(output);
2549        }
2550
2551        let trace_idx = self.inner.tracer.as_ref().map(|tracer| tracer.traces().nodes().len() - 1);
2552        // Pranks and broadcasts can change the creator and destination, so read the opcode's
2553        // charge first. A synthetic `deployCode` create carries the charge of the cheatcode.
2554        let precharged_state = if self.inner.synthetic_create_depth == Some(depth) {
2555            self.cheatcodes.as_deref().map_or(0, |cheats| cheats.deploy_code_create_state_gas)
2556        } else if depth == root + 1
2557            && message.kind == MessageKind::Create
2558            && self.inner.enable_isolation
2559            && !self.inner.in_inner_context
2560        {
2561            account_creation_state_gas::<FEN>(interp, message)
2562        } else {
2563            0
2564        };
2565        let mut cheatcode_outcome = None;
2566        if let Some((cheats, backend, _)) = self.cheats_and_backend() {
2567            cheatcode_outcome = cheats.create_hook(interp, message, backend);
2568        }
2569
2570        if let Some(trace_idx) = trace_idx
2571            && let Some(tracer) = self.inner.tracer.as_deref_mut()
2572        {
2573            tracer.traces_mut().nodes_mut()[trace_idx].trace.caller = message.caller;
2574        }
2575
2576        if let Some(output) = cheatcode_outcome {
2577            return Some(output);
2578        }
2579
2580        // If the CREATE2 deployer is invalid, return the error here, after the other inspectors
2581        // were notified, so tracing stays balanced.
2582        if let Some(error) = self.inner.pending_create2_error.take() {
2583            if let Some(cheats) = self.cheatcodes.as_deref_mut() {
2584                cheats.unrun_create_depth = Some(usize::from(depth));
2585            }
2586            return Some(message_result(message, InstrStop::Revert, error));
2587        }
2588
2589        if message.kind != MessageKind::Create2 && self.isolates(root, depth) {
2590            return Some(self.transact_inner(interp, message, precharged_state));
2591        }
2592
2593        None
2594    }
2595
2596    fn create_end(
2597        &mut self,
2598        interp: &mut InterpreterFor<'_, '_, FEN>,
2599        message: &MessageFor<FEN>,
2600        result: &mut MessageResultFor<FEN>,
2601    ) {
2602        // A frame handed off to a frame EVM already ran its end hooks there.
2603        if mem::take(&mut self.inner.env_handoff_ended) {
2604            self.restore_cheat_stepped();
2605            return;
2606        }
2607        // A redirected CREATE ends as the call to the factory, then becomes the CREATE result.
2608        if message.kind == MessageKind::Call {
2609            self.call_end(interp, message, result);
2610            self.finish_create2_redirect(message, result);
2611            return;
2612        }
2613
2614        self.end_snapshot_frame(interp, message, result);
2615
2616        if self.inner.is_inner_context_root(message.depth) {
2617            self.capture_switch_warmth(interp, result);
2618            self.capture_executed_destructs(interp);
2619            self.restore_cheat_stepped();
2620            return;
2621        }
2622
2623        self.do_create_end(interp, message, result);
2624
2625        if let Some(trace) = self.cheatcodes.as_mut().and_then(|c| c.failure_trace.as_mut()) {
2626            trace.finish_frame::<FEN>(usize::from(message.depth), result);
2627        }
2628        if let Some(provenance) =
2629            self.cheatcodes.as_mut().and_then(|c| c.failure_provenance.as_mut())
2630        {
2631            provenance.finish_frame::<FEN>(usize::from(message.depth), interp, result);
2632        }
2633        if let Some(revert_diag) = self.inner.revert_diag.as_deref_mut() {
2634            revert_diag.frame_end();
2635        }
2636        self.restore_cheat_stepped();
2637    }
2638
2639    fn selfdestruct(
2640        &mut self,
2641        contract: &Address,
2642        target: &Address,
2643        value: &U256,
2644        host: &mut FoundryEvmFor<'_, FEN>,
2645    ) {
2646        call_inspectors!([&mut self.inner.printer], |inspector| {
2647            Inspector::<TypesFor<FEN>>::selfdestruct(
2648                &mut **inspector,
2649                contract,
2650                target,
2651                value,
2652                host,
2653            )
2654        });
2655    }
2656}
2657
2658impl<FEN: FoundryEvmNetwork> InspectorStackRefMut<'_, FEN> {
2659    /// Cools the running transaction's loaded accounts and storage before an isolated STATICCALL,
2660    /// as for a separate transaction.
2661    ///
2662    /// Storage of accounts with arbitrary storage stays warm, so its generated values are kept.
2663    fn cool_for_static_call(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
2664        // The calling frame is the transaction's root, so its address is the recipient.
2665        let recipient = interp.message().destination;
2666        let is_precompile = interp.host().precompiles().contains(&recipient);
2667        let state = interp.host().state_mut();
2668        // Warmth carried across fork switches cools too.
2669        if let Some(prewarm) = self.backend.backend().lifecycle().tx_prewarm() {
2670            *state.prewarm_set_mut() = prewarm.clone();
2671        }
2672        // So does the persistent warmth the contexts recorded, which later switches restore.
2673        if self.backend.backend().lifecycle().has_persistent_warmth() {
2674            self.backend.backend_mut().take_persistent_warmth();
2675        }
2676        // The recipient cools like any other account the transaction loaded, unlike the addresses
2677        // `vm.cool` keeps warm.
2678        if !is_precompile
2679            && !self
2680                .cheatcodes
2681                .as_deref()
2682                .is_some_and(|cheats| cheats.tx_warm_addresses.contains(&recipient))
2683        {
2684            let backend = &mut *self.backend;
2685            // Only take a mutable backend, which clones a borrowed one, if the lifecycle tracks
2686            // the recipient's warmth.
2687            if backend.backend().lifecycle().tracks_prewarm(&recipient) {
2688                backend.backend_mut().remove_prewarm(state, &recipient);
2689            } else {
2690                state.prewarm_set_mut().remove(&recipient);
2691            }
2692        }
2693        // Accounts with arbitrary storage keep their warm slots, and stay warm if they have any.
2694        let arbitrary = self
2695            .cheatcodes
2696            .as_deref()
2697            .map(|cheats| {
2698                let loaded = state
2699                    .loaded_accounts()
2700                    .filter(|(address, _)| cheats.has_arbitrary_storage(address))
2701                    .map(|(address, slots)| (*address, slots.copied().collect::<Vec<_>>()))
2702                    .collect::<Vec<_>>();
2703                loaded
2704                    .into_iter()
2705                    .filter_map(|(address, mut slots)| {
2706                        let storage = state.storage(&address).ok()?;
2707                        slots.retain(|key| storage.is_warm(key));
2708                        (!slots.is_empty()).then_some((address, slots))
2709                    })
2710                    .collect::<Vec<_>>()
2711            })
2712            .unwrap_or_default();
2713        state.cool_loaded();
2714        for (address, slots) in arbitrary {
2715            state.set_account_warm(&address, true);
2716            for key in slots {
2717                state.set_storage_warm(&address, key, true);
2718            }
2719        }
2720    }
2721}
2722
2723impl<FEN: FoundryEvmNetwork> Deref for InspectorStack<FEN> {
2724    type Target = InspectorStackInner;
2725
2726    fn deref(&self) -> &Self::Target {
2727        &self.inner
2728    }
2729}
2730
2731impl<FEN: FoundryEvmNetwork> DerefMut for InspectorStack<FEN> {
2732    fn deref_mut(&mut self) -> &mut Self::Target {
2733        &mut self.inner
2734    }
2735}
2736
2737impl InspectorStackInner {
2738    #[inline]
2739    const fn refresh_static_opcode_dispatch(&mut self) {
2740        self.refresh_static_step_dispatch();
2741        self.refresh_static_step_end_dispatch();
2742    }
2743
2744    #[inline]
2745    const fn refresh_static_step_dispatch(&mut self) {
2746        self.has_static_step_inspectors = self.chisel_state.is_some()
2747            || self.edge_coverage.is_some()
2748            || self.line_coverage.is_some()
2749            || self.printer.is_some()
2750            || self.revert_diag.is_some()
2751            || self.script_execution_inspector.is_some()
2752            || self.tracer.is_some()
2753            || self.debug_recorder.is_some();
2754    }
2755
2756    #[inline]
2757    const fn refresh_static_step_end_dispatch(&mut self) {
2758        self.has_static_step_end_inspectors = self.chisel_state.is_some()
2759            || self.printer.is_some()
2760            || self.revert_diag.is_some()
2761            || self.tracer.is_some()
2762            || self.debug_recorder.is_some();
2763    }
2764
2765    /// Returns the union of the opcodes of every inspector the step hooks call besides the
2766    /// cheatcodes, and the part of it that the inspectors the `step_end` hook calls step. An
2767    /// inspector that does not declare its opcodes steps all of them.
2768    fn static_steps<FEN: FoundryEvmNetwork>(&self) -> (OpcodeSet, OpcodeSet) {
2769        if !self.has_static_step_inspectors && !self.has_static_step_end_inspectors {
2770            return (OpcodeSet::EMPTY, OpcodeSet::EMPTY);
2771        }
2772        let step_end_inspectors: [Option<&dyn Inspector<TypesFor<FEN>>>; 5] = [
2773            self.tracer.as_deref().map(|i| i as _),
2774            self.chisel_state.as_deref().map(|i| i as _),
2775            self.debug_recorder.as_deref().map(|i| i as _),
2776            self.printer.as_deref().map(|i| i as _),
2777            self.revert_diag.as_deref().map(|i| i as _),
2778        ];
2779        let step_inspectors: [Option<&dyn Inspector<TypesFor<FEN>>>; 3] = [
2780            self.edge_coverage.as_deref().map(|i| i as _),
2781            self.line_coverage.as_deref().map(|i| i as _),
2782            self.script_execution_inspector.as_deref().map(|i| i as _),
2783        ];
2784        let union = |mut steps: OpcodeSet, inspectors: &[Option<&dyn Inspector<TypesFor<FEN>>>]| {
2785            for inspector in inspectors.iter().flatten() {
2786                if steps == OpcodeSet::ALL {
2787                    break;
2788                }
2789                steps = steps.union(inspector.inspector_config().steps());
2790            }
2791            steps
2792        };
2793        let end_steps = union(OpcodeSet::EMPTY, &step_end_inspectors);
2794        (union(end_steps, &step_inspectors), end_steps)
2795    }
2796
2797    /// Derive the next `--batch` CREATE2 salt and advance the per-batch counter.
2798    /// The per-inspector random seed is lazily initialized on first use.
2799    fn next_batch_create_salt(&mut self, chain_id: u64, nonce: u64) -> U256 {
2800        let process_salt = *self.batch_rewrite_process_salt.get_or_insert_with(rand::random);
2801        let counter = self.batch_create_counter;
2802        self.batch_create_counter = counter.wrapping_add(1);
2803        compute_batch_create_salt(process_salt, chain_id, nonce, counter)
2804    }
2805
2806    /// Executes `message` of the transaction `evm` is running on a separate frame EVM with `env`,
2807    /// observed by the whole stack, such as for `deployCode` or an in-flight spec change.
2808    fn execute_on_frame_evm<FEN: FoundryEvmNetwork>(
2809        &mut self,
2810        mut cheatcodes: Option<&mut Cheatcodes<FEN>>,
2811        backend: &mut dyn CheatcodesBackend<FEN>,
2812        evm: &mut FoundryEvmFor<'_, FEN>,
2813        env: EvmEnvFor<FEN>,
2814        message: &mut MessageFor<FEN>,
2815    ) -> Result<MessageResultFor<FEN>, ExecutionError> {
2816        // SAFETY: `evm` runs over the lifecycle's owned databases, and so does the frame EVM,
2817        // which only lives for this call; its inspector is released before its state moves back.
2818        let mut frame = unsafe { backend.backend().lifecycle().begin_frame_evm(evm, env) };
2819        let create2_redirects =
2820            cheatcodes.as_deref().map_or(0, |cheats| cheats.pending_create2_redirects.len());
2821        frame.set_inspector(InspectorStackRefMut {
2822            cheatcodes: cheatcodes.as_deref_mut(),
2823            inner: self,
2824            backend,
2825        });
2826        let result = Host::execute_message(&mut frame, message);
2827        // SAFETY: See above.
2828        let frame = unsafe { release_inspector(frame) };
2829        // Drop redirects left behind if execution aborted before their frames ended.
2830        if let Some(cheats) = cheatcodes {
2831            cheats.pending_create2_redirects.truncate(create2_redirects);
2832        }
2833        // SAFETY: See above.
2834        unsafe { backend.backend().lifecycle().end_frame_evm(evm, frame) };
2835        result
2836    }
2837
2838    /// Whether this frame is the root of a nested transaction, duplicating a surrounding frame.
2839    fn is_inner_context_root(&self, depth: u16) -> bool {
2840        self.in_inner_context && self.inner_root_depth == Some(depth)
2841    }
2842
2843    /// Enters a nested transaction whose root frame duplicates a surrounding frame, returning the
2844    /// previous context to restore with [`Self::exit_inner_context`].
2845    const fn enter_inner_context(
2846        &mut self,
2847        root: InnerRoot,
2848    ) -> (bool, Option<u16>, Option<InnerRoot>) {
2849        let previous = (self.in_inner_context, self.inner_root_depth, self.pending_inner_root);
2850        self.in_inner_context = true;
2851        self.inner_root_depth = Some(root.depth);
2852        self.pending_inner_root = Some(root);
2853        previous
2854    }
2855
2856    /// Restores the context saved by [`Self::enter_inner_context`].
2857    const fn exit_inner_context(&mut self, previous: (bool, Option<u16>, Option<InnerRoot>)) {
2858        (self.in_inner_context, self.inner_root_depth, self.pending_inner_root) = previous;
2859    }
2860
2861    /// Executes a transaction replayed by the cheatcode call at `depth`, such as for
2862    /// `vm.transact`, observed by the whole stack with `cheats` active over the throwaway
2863    /// `backend` it was prepared with. Its root frame is a call below the cheatcode call.
2864    fn replay<FEN: FoundryEvmNetwork>(
2865        &mut self,
2866        cheats: &mut Cheatcodes<FEN>,
2867        backend: &mut dyn CheatcodesBackend<FEN>,
2868        evm: &mut FoundryEvmFor<'_, FEN>,
2869        depth: u16,
2870        prepared: PreparedTx<TypesFor<FEN>>,
2871        untracked: bool,
2872    ) -> eyre::Result<ExecutedNested<TypesFor<FEN>>> {
2873        let caller = prepared.tx().signer();
2874        let previous =
2875            self.enter_inner_context(InnerRoot { depth, caller, origin: None, observe: true });
2876        // The replay reads its own transaction environment, not the surrounding execution's.
2877        let origin_override = cheats.origin_override.take();
2878        let gas_price = cheats.gas_price.take();
2879        // The replayed transaction has its own journal.
2880        let snapshot_restores = mem::take(&mut cheats.snapshot_restores);
2881        let fork_id = backend.backend().active_fork_id();
2882        let (mut gas_price_override, mut blob_hashes_override) = (None, None);
2883        cheats.env_overrides.swap_transaction_overrides(
2884            fork_id,
2885            &mut gas_price_override,
2886            &mut blob_hashes_override,
2887        );
2888        let in_replay = mem::replace(&mut cheats.in_replay, true);
2889        let create2_redirects = cheats.pending_create2_redirects.len();
2890        let mut inspector =
2891            InspectorStackRefMut { cheatcodes: Some(&mut *cheats), inner: &mut *self, backend };
2892        let executed = prepared.execute(evm, Some(&mut inspector), untracked);
2893        cheats.pending_create2_redirects.truncate(create2_redirects);
2894        cheats.snapshot_restores = snapshot_restores;
2895        cheats.in_replay = in_replay;
2896        cheats.env_overrides.swap_transaction_overrides(
2897            fork_id,
2898            &mut gas_price_override,
2899            &mut blob_hashes_override,
2900        );
2901        cheats.origin_override = origin_override;
2902        cheats.gas_price = gas_price;
2903        self.exit_inner_context(previous);
2904        executed
2905    }
2906}
2907
2908/// Derive the CREATE2 salt used by `--batch` CREATE rewrites.
2909///
2910/// Mixes a per-inspector random seed, the chain id, the caller nonce, and a per-batch counter
2911/// so that two simulations launched at the same on-chain state produce distinct salts and
2912/// do not collide at the Arachnid factory.
2913fn compute_batch_create_salt(process_salt: u64, chain_id: u64, nonce: u64, counter: u64) -> U256 {
2914    let mut buf = [0u8; 32];
2915    buf[0..8].copy_from_slice(&process_salt.to_be_bytes());
2916    buf[8..16].copy_from_slice(&chain_id.to_be_bytes());
2917    buf[16..24].copy_from_slice(&nonce.to_be_bytes());
2918    buf[24..32].copy_from_slice(&counter.to_be_bytes());
2919    keccak256(buf).into()
2920}
2921
2922/// Redirects `message` to the implementation set with `vm.mockFunction`, if one matches.
2923fn apply_mocked_function<FEN: FoundryEvmNetwork>(
2924    cheatcodes: &Cheatcodes<FEN>,
2925    interp: &mut InterpreterFor<'_, '_, FEN>,
2926    message: &mut MessageFor<FEN>,
2927) {
2928    if let Some(mocks) = cheatcodes.core.mocked_functions.get(&message.code_address) {
2929        let input = message.input.as_bytes(interp.memory());
2930        // Check if any mock function set for call data or if catch-all mock function set
2931        // for selector.
2932        if let Some(target) =
2933            mocks.get(input).or_else(|| input.get(..4).and_then(|selector| mocks.get(selector)))
2934        {
2935            let target = *target;
2936            let code = interp
2937                .host()
2938                .state_mut()
2939                .account(&target)
2940                .and_then(|mut account| account.load_code())
2941                .expect("failed to load account");
2942            // Like the callee address, so cheatcodes such as `expectCall` observe the target.
2943            message.call_target = target;
2944            message.code_address = target;
2945            message.code = code;
2946        }
2947    }
2948}
2949
2950/// Returns the accounts still warm at the end of a nested transaction detached into `pending`,
2951/// with their warm storage slots, which reattaching it to `child` exposes. Accesses a revert undid
2952/// are cold; others stay warm, such as the accounts a `vm.executeTransaction` within it touched.
2953fn nested_warmth(child: &mut State<'_>, pending: &PendingState) -> AddressMap<HashSet<U256>> {
2954    child.set_pending_state(pending.clone());
2955    let warm = warm_accounts(child);
2956    child.clear_transaction_state();
2957    warm
2958}
2959
2960/// Warms in `state` the storage slots still warm in a nested transaction detached into `pending`,
2961/// and the accounts and slots in `warm`, its [`nested_warmth`], as accesses across an isolated call
2962/// boundary stay warm for the calling frame. Accounts in `cold` stay cold, but not their slots.
2963fn warm_nested(
2964    state: &mut State<'_>,
2965    pending: &PendingState,
2966    warm: AddressMap<HashSet<U256>>,
2967    cold: &AddressSet,
2968) -> DbResult<()> {
2969    // The running transaction holds every account the nested one loaded, cold unless warmed
2970    // below, so that a later failure leaves them cold.
2971    for change in pending.account_changes() {
2972        state.account(&change.address)?;
2973        // Slots stay warm even when their account is not in `warm`, such as a target created
2974        // earlier in the running transaction.
2975        for (key, slot) in &change.storage.slots {
2976            if slot.is_warm {
2977                state.storage_slot(&change.address, *key)?.warm();
2978            }
2979        }
2980    }
2981    for (address, slots) in warm {
2982        if !cold.contains(&address) {
2983            state.account(&address)?.warm();
2984        }
2985        for key in slots {
2986            state.storage_slot(&address, key)?.warm();
2987        }
2988    }
2989    Ok(())
2990}
2991
2992/// Returns the EIP-8037 account-creation state gas charged before running `message`, by its CALL
2993/// or CREATE opcode or at the top level of a transaction: a CREATE, or a value transfer, to an
2994/// empty account.
2995fn account_creation_state_gas<FEN: FoundryEvmNetwork>(
2996    interp: &mut InterpreterFor<'_, '_, FEN>,
2997    message: &MessageFor<FEN>,
2998) -> u64 {
2999    let evm = interp.host();
3000    let features = evm.version().features;
3001    let is_create = message.kind == MessageKind::Create;
3002    if !features.contains(EvmFeatures::EIP8037)
3003        || !(is_create || !message.value.is_zero())
3004        || !evm
3005            .state_mut()
3006            .account(&message.destination)
3007            .is_ok_and(|account| account.is_empty_for_new_account_gas(features))
3008    {
3009        return 0;
3010    }
3011    let gas_params = &evm.version().gas_params;
3012    if is_create { gas_params.create_state_gas() } else { gas_params.new_account_state_gas() }
3013}
3014
3015/// Warms Arbitrum's ArbSys like a precompile, as Nitro does, on Arbitrum chains.
3016fn warm_arbitrum_system_contract<FEN: FoundryEvmNetwork>(interp: &mut InterpreterFor<'_, '_, FEN>) {
3017    let evm = interp.host();
3018    if !arbitrum::is_arbitrum_chain(evm.version().chain_id) {
3019        return;
3020    }
3021    // Other selectors can still execute code at the address.
3022    evm.state_mut().prewarm(&arbitrum::ARB_SYS_ADDRESS);
3023}
3024
3025/// Answers `ArbSys.arbBlockNumber()` on Arbitrum chains.
3026fn handle_arbitrum_system_call<FEN: FoundryEvmNetwork>(
3027    interp: &mut InterpreterFor<'_, '_, FEN>,
3028    message: &MessageFor<FEN>,
3029    fork_block_number: Option<u64>,
3030) -> Option<MessageResultFor<FEN>> {
3031    if message.destination != arbitrum::ARB_SYS_ADDRESS
3032        || message.code_address != arbitrum::ARB_SYS_ADDRESS
3033        || !arbitrum::is_arbitrum_chain(interp.host().version().chain_id)
3034        || message.input.as_bytes(interp.memory()).get(..4)
3035            != Some(&arbitrum::ARB_BLOCK_NUMBER_SELECTOR[..])
3036    {
3037        return None;
3038    }
3039    let evm = interp.host();
3040
3041    // Forks report their L2 block, which the block env lacks on Arbitrum because `NUMBER` returns
3042    // the L1 block there. Without a fork the block env is read here to follow `vm.roll`.
3043    let block_number = fork_block_number.unwrap_or_else(|| evm.block().number.saturating_to());
3044    let Some((gas_cost, output)) = arbitrum::arb_block_number_call(message.gas_limit, block_number)
3045    else {
3046        let mut result = message_result(message, InstrStop::PrecompileOOG, Bytes::new());
3047        result.gas.spend_all();
3048        return Some(result);
3049    };
3050
3051    let mut result = message_result(message, InstrStop::Return, output);
3052    let _ = result.gas.spend(gas_cost);
3053    Some(result)
3054}
3055
3056#[cfg(test)]
3057mod tests {
3058    use super::*;
3059    use crate::executors::default_env;
3060    use foundry_evm_core::backend::Backend;
3061    use foundry_evm_traces::InternalTraceMode;
3062
3063    #[test]
3064    fn opcode_dispatch_defaults_to_no_static_inspectors() {
3065        let stack = InspectorStackInner::default();
3066
3067        assert!(!stack.has_static_step_inspectors);
3068        assert!(!stack.has_static_step_end_inspectors);
3069    }
3070
3071    #[test]
3072    fn opcode_dispatch_tracks_general_step_and_step_end_inspectors() {
3073        let mut stack = InspectorStack::<EthEvmNetwork>::new();
3074
3075        stack.print(true);
3076        assert!(stack.inner.has_static_step_inspectors);
3077        assert!(stack.inner.has_static_step_end_inspectors);
3078
3079        stack.print(false);
3080        assert!(!stack.inner.has_static_step_inspectors);
3081        assert!(!stack.inner.has_static_step_end_inspectors);
3082
3083        stack.tracing_requirements(TraceRequirements::none().with_calls(true));
3084        assert!(stack.inner.has_static_step_inspectors);
3085        assert!(stack.inner.has_static_step_end_inspectors);
3086
3087        stack.tracing_requirements(TraceRequirements::none());
3088        assert!(!stack.inner.has_static_step_inspectors);
3089        assert!(!stack.inner.has_static_step_end_inspectors);
3090
3091        stack.set_chisel(ChiselState::new(None));
3092        assert!(stack.inner.has_static_step_inspectors);
3093        assert!(stack.inner.has_static_step_end_inspectors);
3094    }
3095
3096    #[test]
3097    fn opcode_dispatch_tracks_script_and_edge_coverage_inspectors() {
3098        let mut stack = InspectorStack::<EthEvmNetwork>::new();
3099
3100        stack.script(Address::with_last_byte(1));
3101        assert!(stack.inner.has_static_step_inspectors);
3102        assert!(!stack.inner.has_static_step_end_inspectors);
3103
3104        let mut stack = InspectorStack::<EthEvmNetwork>::new();
3105        stack.collect_edge_coverage(true);
3106        assert!(stack.inner.has_static_step_inspectors);
3107        stack.collect_edge_coverage(false);
3108        assert!(!stack.inner.has_static_step_inspectors);
3109    }
3110
3111    #[test]
3112    fn inspector_config_unions_the_opcodes_the_hooks_need() {
3113        let mut backend = Backend::spawn(None, default_env::<EthEvmNetwork>()).unwrap();
3114        let mut stack = InspectorStack::<EthEvmNetwork>::new();
3115        let mut steps = |stack: &mut InspectorStack| {
3116            stack.as_inspector(&mut backend).inspector_config().steps()
3117        };
3118        let set = |opcodes: &[u8]| opcodes.iter().copied().collect::<OpcodeSet>();
3119
3120        stack.set_cheatcodes(Cheatcodes::new(Default::default()));
3121        assert_eq!(steps(&mut stack), OpcodeSet::EMPTY);
3122
3123        // Recording failure identities steps everything, only while set and not paused.
3124        stack.collect_failure_identity(true);
3125        assert_eq!(steps(&mut stack), OpcodeSet::ALL);
3126        stack.pause_failure_identity(true);
3127        assert_eq!(steps(&mut stack), OpcodeSet::EMPTY);
3128        stack.collect_failure_identity(false);
3129        assert_eq!(steps(&mut stack), OpcodeSet::EMPTY);
3130
3131        // Recording failure provenance only steps the instructions that end a frame early and the
3132        // branches that lead to them.
3133        stack.collect_failure_provenance(true);
3134        assert_eq!(steps(&mut stack), set(&[op::JUMPI, op::REVERT, op::INVALID]));
3135        stack.collect_failure_provenance(false);
3136        assert_eq!(steps(&mut stack), OpcodeSet::EMPTY);
3137
3138        // Without other stepping inspectors, the fuzzer steps nothing and cancellation polls at
3139        // jumps and calls.
3140        let mut campaign = stack.clone();
3141        campaign.set_fuzzer(Fuzzer::default());
3142        assert_eq!(steps(&mut campaign), OpcodeSet::EMPTY);
3143        campaign.set_execution_cancellation(EvmExecutionCancellation::early_exit(EarlyExit::new(
3144            false,
3145        )));
3146        assert_eq!(
3147            steps(&mut campaign),
3148            set(&[
3149                op::JUMP,
3150                op::JUMPI,
3151                op::CALL,
3152                op::CALLCODE,
3153                op::DELEGATECALL,
3154                op::STATICCALL,
3155                op::CREATE,
3156                op::CREATE2,
3157            ])
3158        );
3159
3160        // Call traces only step for the revert diagnostic.
3161        stack.tracing_requirements(TraceRequirements::none().with_calls(true));
3162        assert_eq!(steps(&mut stack), set(&[op::REVERT, op::EXTCODESIZE]));
3163
3164        stack.cheatcodes.as_mut().unwrap().recording_accesses = true;
3165        assert_eq!(steps(&mut stack), set(&[op::REVERT, op::EXTCODESIZE, op::SLOAD, op::SSTORE]));
3166        stack.cheatcodes.as_mut().unwrap().recording_accesses = false;
3167
3168        // Internal decoding records only jumps.
3169        stack.tracing_requirements(
3170            TraceRequirements::none().with_decode_internal(InternalTraceMode::Simple),
3171        );
3172        assert_eq!(steps(&mut stack), set(&[op::REVERT, op::EXTCODESIZE, op::JUMP, op::JUMPDEST]));
3173
3174        stack.tracing_requirements(TraceRequirements::none().with_all_steps(true));
3175        assert_eq!(steps(&mut stack), OpcodeSet::ALL);
3176        stack.tracing_requirements(TraceRequirements::none().with_state_changes(true));
3177        assert_eq!(steps(&mut stack), OpcodeSet::ALL);
3178
3179        // The fuzzer does not step, and cancellation polls at jumps and calls.
3180        stack.tracing_requirements(TraceRequirements::none().with_calls(true));
3181        stack.set_fuzzer(Fuzzer::default());
3182        assert_eq!(steps(&mut stack), set(&[op::REVERT, op::EXTCODESIZE]));
3183        stack.set_execution_cancellation(EvmExecutionCancellation::early_exit(EarlyExit::new(
3184            false,
3185        )));
3186        assert_eq!(
3187            steps(&mut stack),
3188            set(&[
3189                op::REVERT,
3190                op::EXTCODESIZE,
3191                op::JUMP,
3192                op::JUMPI,
3193                op::CALL,
3194                op::CALLCODE,
3195                op::DELEGATECALL,
3196                op::STATICCALL,
3197                op::CREATE,
3198                op::CREATE2,
3199            ])
3200        );
3201
3202        // Edge coverage steps jumps, and the script inspector steps `ADDRESS`.
3203        let mut campaign = InspectorStack::<EthEvmNetwork>::new();
3204        campaign.collect_edge_coverage(true);
3205        assert_eq!(steps(&mut campaign), set(&[op::JUMP, op::JUMPI]));
3206        campaign.script(Address::with_last_byte(1));
3207        assert_eq!(steps(&mut campaign), set(&[op::JUMP, op::JUMPI, op::ADDRESS]));
3208
3209        // An inspector without its own config steps every opcode.
3210        stack.print(true);
3211        assert_eq!(steps(&mut stack), OpcodeSet::ALL);
3212    }
3213
3214    #[test]
3215    fn revert_diagnostic_frames_remain_balanced() {
3216        let mut inspector = RevertDiagnostic::default();
3217        inspector.frame_start();
3218        inspector.set_trace_node(0);
3219        inspector.frame_start();
3220        inspector.set_trace_node(1);
3221        inspector.frame_end();
3222        inspector.frame_end();
3223
3224        assert!(inspector.into_diagnostics().is_empty());
3225    }
3226
3227    #[test]
3228    fn distinct_salts_across_simulations_at_same_nonce() {
3229        // Two "simulations" with different per-inspector seeds but identical on-chain state.
3230        let a = compute_batch_create_salt(0xabcd_ef01_2345_6789, 1, 5, 0);
3231        let b = compute_batch_create_salt(0x1122_3344_5566_7788, 1, 5, 0);
3232        assert_ne!(a, b);
3233    }
3234
3235    #[test]
3236    fn counter_changes_salt() {
3237        let a = compute_batch_create_salt(1, 1, 5, 0);
3238        let b = compute_batch_create_salt(1, 1, 5, 1);
3239        assert_ne!(a, b);
3240    }
3241
3242    #[test]
3243    fn chain_id_changes_salt() {
3244        let a = compute_batch_create_salt(1, 1, 5, 0);
3245        let b = compute_batch_create_salt(1, 2, 5, 0);
3246        assert_ne!(a, b);
3247    }
3248
3249    #[test]
3250    fn deterministic_for_same_inputs() {
3251        let a = compute_batch_create_salt(42, 1, 5, 7);
3252        let b = compute_batch_create_salt(42, 1, 5, 7);
3253        assert_eq!(a, b);
3254    }
3255
3256    #[test]
3257    fn distinct_create2_addresses_across_inspector_instances_at_same_onchain_state() {
3258        // Two fresh inspectors fed identical (chain_id, nonce) must produce CREATE2 addresses
3259        // that differ when routed through the same factory with the same init code.
3260        let factory = Address::with_last_byte(0x42);
3261        let init_code = b"\x60\x80\x60\x40".as_slice();
3262
3263        let mut a = InspectorStackInner::default();
3264        let mut b = InspectorStackInner::default();
3265        let salt_a = a.next_batch_create_salt(1, 5).to_be_bytes::<32>();
3266        let salt_b = b.next_batch_create_salt(1, 5).to_be_bytes::<32>();
3267
3268        let addr_a = factory.create2_from_code(salt_a, init_code);
3269        let addr_b = factory.create2_from_code(salt_b, init_code);
3270        assert_ne!(addr_a, addr_b);
3271    }
3272}