Skip to main content

foundry_cheatcodes/
inspector.rs

1//! Cheatcode EVM inspector.
2
3use crate::{
4    Cheatcode, CheatcodesBackend, CheatcodesCore, CheatsConfig, CheatsCtxt, Error, Result,
5    Vm::{self, AccountAccess},
6    evm::{
7        GasRecord, RecordAccess, append_storage_access, mark_account_accesses_reverted,
8        merge_recorded_frame,
9        mock::{self, MockCallDataContext, MockCallReturnData},
10        prank::Prank,
11        touch_account,
12    },
13    expected_emit::{self, ExpectedEmitTracker},
14    script::Broadcast,
15    test::{
16        assert::{FailureProvenance, FailureTrace},
17        assume::AssumeNoRevert,
18        expect::{self, ExpectedCallTracker, ExpectedCreate, ExpectedRevert, ExpectedRevertKind},
19        revert_handlers,
20    },
21    utils::IgnoredTraces,
22};
23use alloy_consensus::{BlobTransactionSidecarVariant, transaction::Recovered};
24use alloy_eips::eip7702::SignedAuthorization;
25use alloy_network::{Ethereum, Network, TransactionBuilder};
26use alloy_primitives::{
27    Address, B256, Bytes, Log, TxKind, U256, hex,
28    map::{AddressHashMap, HashMap, HashSet},
29};
30use alloy_rpc_types::AccessList;
31use alloy_sol_types::{SolCall, SolInterface};
32use evm2::{
33    EvmTypesHost, ExecutionError, OpcodeSet,
34    evm::{State, StateSnapshot},
35    interpreter::{
36        Gas, GasTracker, Host, InstrStop, Interpreter, MessageExt, MessageKind, MessageResultExt,
37        derive_create_destination, op,
38    },
39};
40use foundry_common::{
41    FoundryTransactionBuilder, SELECTOR_LEN, TransactionMaybeSigned,
42    mapping_slots::{
43        MappingSlots, PendingMappingHash, capture_hash as capture_mapping_hash,
44        record_hash as record_mapping_hash, step as mapping_step,
45    },
46};
47use foundry_evm_core::{
48    Breakpoints,
49    abi::Vm::stopExpectSafeMemoryCall,
50    backend::{LocalForkId, RevertDiagnostic},
51    constants::{CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS, MAGIC_ASSUME},
52    evm::{
53        BlockEnvFor, EthEvmNetwork, EvmEnvFor, FoundryEvmFor, FoundryEvmNetwork, InterpreterFor,
54        MessageFor, MessageResultFor, PersistentWrite, SnapshotRestores, SpecFor,
55        TransactionRequestFor, TxFor, TxResultFor, restore_access_warmth,
56    },
57    utils::opcodes,
58};
59use foundry_evm_traces::{
60    TracingInspector, TracingInspectorConfig, identifier::SignaturesIdentifier,
61};
62use itertools::Itertools;
63use rand::Rng;
64use std::{
65    cmp::max,
66    collections::{BTreeMap, VecDeque},
67    fmt::Debug,
68    ops::Range,
69    sync::{Arc, OnceLock, atomic::Ordering},
70};
71
72mod env_overrides;
73pub use env_overrides::EnvOverrideState;
74
75pub mod analysis;
76pub use analysis::CheatcodeAnalysis;
77
78/// Runs nested executions on behalf of cheatcodes.
79///
80/// The executor owns the inspectors besides [`Cheatcodes`], so nested executions are observed by
81/// the whole inspector stack: tracing, logs, coverage and cheatcodes themselves.
82pub trait CheatcodesExecutor<FEN: FoundryEvmNetwork> {
83    /// Executes `message` as a nested frame of the transaction `evm` is running, with `cheats`
84    /// active, such as for `deployCode` or storage-hook callbacks.
85    fn exec_message(
86        &mut self,
87        cheats: &mut Cheatcodes<FEN>,
88        backend: &mut dyn CheatcodesBackend<FEN>,
89        evm: &mut FoundryEvmFor<'_, FEN>,
90        message: &mut MessageFor<FEN>,
91    ) -> Result<MessageResultFor<FEN>, ExecutionError>;
92
93    /// Executes `tx` as a nested transaction of the transaction `evm` is running, with `env` or
94    /// the running environment, and merges its changes so that they survive reverts of the
95    /// enclosing calls, such as for `executeTransaction`. A failed transaction only keeps its nonce
96    /// increment.
97    ///
98    /// `depth` is the depth of the cheatcode call; the nested transaction's root frame duplicates
99    /// it, so its children run one level deeper.
100    fn nested_transaction(
101        &mut self,
102        cheats: &mut Cheatcodes<FEN>,
103        backend: &mut dyn CheatcodesBackend<FEN>,
104        evm: &mut FoundryEvmFor<'_, FEN>,
105        depth: u16,
106        tx: &Recovered<TxFor<FEN>>,
107        env: Option<EvmEnvFor<FEN>>,
108    ) -> eyre::Result<TxResultFor<FEN>>;
109
110    /// Replays a mined transaction of fork `fork_id`, or of the active fork, for `vm.transact`.
111    ///
112    /// The replayed transaction runs with `cheats` active over a throwaway copy of `backend`, so
113    /// its cheatcodes cannot modify `backend`. Its root frame is a call below the cheatcode call
114    /// at `depth`.
115    fn transact(
116        &mut self,
117        cheats: &mut Cheatcodes<FEN>,
118        backend: &mut dyn CheatcodesBackend<FEN>,
119        evm: &mut FoundryEvmFor<'_, FEN>,
120        depth: u16,
121        fork_id: Option<U256>,
122        transaction: B256,
123    ) -> eyre::Result<TxResultFor<FEN>>;
124
125    /// Executes a signed transaction as a nested transaction, such as for
126    /// `broadcastRawTransaction`.
127    ///
128    /// The transaction runs with `cheats` active over a throwaway copy of `backend`, in `env` or
129    /// the running environment for `None`. Its root frame is a call below the cheatcode call at
130    /// `depth`.
131    fn transact_from_tx(
132        &mut self,
133        cheats: &mut Cheatcodes<FEN>,
134        backend: &mut dyn CheatcodesBackend<FEN>,
135        evm: &mut FoundryEvmFor<'_, FEN>,
136        depth: u16,
137        tx: &Recovered<TxFor<FEN>>,
138        env: Option<EvmEnvFor<FEN>>,
139    ) -> eyre::Result<TxResultFor<FEN>>;
140
141    /// Simulates `console.log` invocation.
142    fn console_log(&mut self, msg: &str);
143
144    /// Returns a mutable reference to the tracing inspector if it is available.
145    fn tracing_inspector(&mut self) -> Option<&mut TracingInspector> {
146        None
147    }
148}
149
150/// Executes the given CREATE message as a nested frame with the whole inspector stack.
151pub(crate) fn exec_create<FEN: FoundryEvmNetwork>(
152    executor: &mut dyn CheatcodesExecutor<FEN>,
153    mut message: MessageFor<FEN>,
154    ccx: &mut CheatsCtxt<'_, '_, FEN>,
155) -> Result<MessageResultFor<FEN>> {
156    let nonce = ccx.evm.state_mut().account(&message.caller)?.nonce();
157    message.destination = derive_create_destination(
158        message.kind,
159        &message.caller,
160        &message.salt,
161        ccx.evm.message_input(&message),
162        nonce,
163    );
164    message.call_target = message.destination;
165    message.code_address = message.destination;
166    Ok(executor.exec_message(ccx.state, ccx.backend, ccx.evm, &mut message)?)
167}
168
169macro_rules! try_or_return {
170    ($e:expr) => {
171        match $e {
172            Some(v) => v,
173            None => return,
174        }
175    };
176}
177
178/// Returns the result of a message that did not execute, keeping its whole execution gas.
179///
180/// The result returns no state gas reservoir, which the caller adopts.
181pub fn message_result<M, E: Default>(
182    message: &MessageExt<M>,
183    stop: InstrStop,
184    output: Bytes,
185) -> MessageResultExt<E> {
186    MessageResultExt { stop, gas: GasTracker::new(message.gas_limit), output, ..Default::default() }
187}
188
189/// Stops the running frame with a revert carrying `output`, before its current instruction runs
190/// or after it ran.
191pub fn revert_frame<T: EvmTypesHost>(interp: &mut Interpreter<'_, '_, T>, output: &[u8]) {
192    let offset = interp.memory().len();
193    if interp.memory_mut().resize(offset, output.len()).is_err() {
194        interp.set_stop(InstrStop::MemoryLimitOOG);
195        return;
196    }
197    interp.memory_mut().set(offset, output);
198    let (Ok(start), Ok(end)) = (u32::try_from(offset), u32::try_from(offset + output.len())) else {
199        interp.set_stop(InstrStop::MemoryLimitOOG);
200        return;
201    };
202    interp.set_output(start..end);
203    interp.set_stop(InstrStop::Revert);
204}
205
206/// Returns the value a call message transfers, if it transfers one.
207///
208/// A static call transfers zero value, while a delegate call transfers none.
209pub(crate) fn transfer_value<E>(message: &MessageExt<E>) -> Option<U256> {
210    matches!(message.kind, MessageKind::Call | MessageKind::CallCode | MessageKind::StaticCall)
211        .then_some(message.value)
212}
213
214/// Helps collecting transactions from different forks.
215#[derive(Clone, Debug)]
216pub struct BroadcastableTransaction<N: Network = Ethereum> {
217    /// The optional RPC URL.
218    pub rpc: Option<String>,
219    /// The transaction to broadcast.
220    pub transaction: TransactionMaybeSigned<N>,
221    /// The CREATE address captured from account state for a pre-signed transaction.
222    pub contract_address: Option<Address>,
223}
224
225#[derive(Clone, Debug, Copy)]
226pub struct RecordDebugStepInfo {
227    /// The debug trace node index when the recording starts.
228    pub start_node_idx: usize,
229    /// The original tracer config when the recording starts.
230    pub original_tracer_config: TracingInspectorConfig,
231}
232
233/// A callback registered for a storage access hook.
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub struct StorageHook {
236    /// Contract that receives the callback.
237    pub callback_target: Address,
238    /// Callback function selector.
239    pub callback_selector: [u8; 4],
240}
241
242#[derive(Clone, Debug)]
243enum PendingStorageHook {
244    Load {
245        account: Address,
246        slot: U256,
247        hook: StorageHook,
248    },
249    Store {
250        account: Address,
251        slot: U256,
252        old_value: U256,
253        mapping: Option<(B256, Vec<B256>)>,
254        hook: StorageHook,
255    },
256}
257
258/// The storage-hook callback frame currently executing.
259#[derive(Clone, Debug)]
260struct ActiveStorageHook {
261    depth: u16,
262    callback_target: Address,
263    callback_input: Bytes,
264}
265
266#[derive(Clone, Debug)]
267struct StorageHookInspectorState {
268    accesses: RecordAccess,
269    recording_accesses: bool,
270    mapping_slots: Option<AddressHashMap<MappingSlots>>,
271    recorded_logs: Option<Vec<Vm::Log>>,
272    recorded_logs_generation: u64,
273    mocked_calls: HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
274    mocked_functions: HashMap<Address, HashMap<Bytes, Address>>,
275    expected_revert: Option<ExpectedRevert>,
276    assume_no_revert: Option<AssumeNoRevert>,
277    expected_calls: ExpectedCallTracker,
278    expected_emits: ExpectedEmitTracker,
279    expected_creates: Vec<ExpectedCreate>,
280}
281
282/// Holds gas metering state.
283#[derive(Clone, Debug, Default)]
284pub struct GasMetering {
285    /// True if gas metering is paused.
286    pub paused: bool,
287    /// True if gas metering was resumed or reset during the test.
288    /// Used to reconcile gas when frame ends (if spent less than refunded).
289    pub touched: bool,
290    /// True if gas metering should be reset to frame limit.
291    pub reset: bool,
292    /// Stores paused gas frames.
293    pub paused_frames: Vec<Gas>,
294
295    /// The group and name of the active snapshot.
296    pub active_gas_snapshot: Option<(String, String)>,
297
298    /// Cache of the amount of gas used in previous call.
299    /// This is used by the `lastCallGas` cheatcode.
300    pub last_call_gas: Option<crate::Vm::Gas>,
301    /// Gas used by `snapshotGasLastCall`.
302    pub(crate) last_call_snapshot_gas_used: u64,
303
304    /// Cache of the amount of gas used in previous call or create frame.
305    /// This is used by the `lastFrameGas` cheatcode.
306    pub last_frame_gas: Option<crate::Vm::Gas>,
307    /// Gas used by `snapshotGasLastFrame`.
308    pub(crate) last_frame_snapshot_gas_used: u64,
309
310    /// Post-refund gas used by the isolated transaction wrapping the current frame, and the
311    /// account-creation state gas in it that the outer opcode charged before entering the frame.
312    isolated_snapshot_gas_used: Option<(u64, u64)>,
313
314    /// Caller depth, gas charged to the last isolated frame, and the transaction gas that replaces
315    /// it in the next region sample at that depth.
316    pending_isolated_region_gas: Option<(usize, u64, u64)>,
317
318    /// True if gas recording is enabled.
319    pub recording: bool,
320    /// The gas used in the last frame.
321    pub last_gas_used: u64,
322    /// Gas records for the active snapshots.
323    pub gas_records: Vec<GasRecord>,
324}
325
326impl GasMetering {
327    /// Start the gas recording.
328    pub const fn start(&mut self) {
329        self.recording = true;
330        self.last_gas_used = 0;
331        self.pending_isolated_region_gas = None;
332    }
333
334    /// Stop the gas recording.
335    pub const fn stop(&mut self) {
336        self.recording = false;
337    }
338
339    /// Resume paused gas metering.
340    pub fn resume(&mut self) {
341        if self.paused {
342            self.paused = false;
343            self.touched = true;
344        }
345        self.paused_frames.clear();
346    }
347
348    /// Reset gas to limit.
349    pub fn reset(&mut self) {
350        self.paused = false;
351        self.touched = true;
352        self.reset = true;
353        self.paused_frames.clear();
354    }
355
356    /// Preserves the receipt gas of an isolated transaction for gas snapshots.
357    ///
358    /// `precharged_state` is the account-creation state gas in `gas_used` that the outer opcode
359    /// already charged before entering the isolated frame.
360    pub const fn set_isolated_snapshot_gas_used(&mut self, gas_used: u64, precharged_state: u64) {
361        self.isolated_snapshot_gas_used = Some((gas_used, precharged_state));
362    }
363
364    /// Takes the receipt gas of the isolated transaction that wrapped the ending frame.
365    ///
366    /// Region snapshots replace the gas charged to the frame with the transaction gas, without
367    /// changing the interpreter's gas. The transaction gas can be lower because of refunds, or
368    /// higher because of intrinsic gas that did not fit in the frame's budget.
369    const fn take_isolated_snapshot_gas_used(
370        &mut self,
371        depth: usize,
372        gas: &GasTracker,
373    ) -> Option<u64> {
374        let Some((gas_used, precharged_state)) = self.isolated_snapshot_gas_used.take() else {
375            return None;
376        };
377        if self.recording {
378            // The caller's sample already includes the precharged state gas.
379            self.pending_isolated_region_gas =
380                Some((depth, gas.spent(), gas_used.saturating_sub(precharged_state)));
381        }
382        Some(gas_used)
383    }
384}
385
386/// Holds data about arbitrary storage.
387#[derive(Clone, Debug, Default)]
388pub struct ArbitraryStorage {
389    /// Mapping of arbitrary storage addresses to generated values (slot, arbitrary value).
390    /// (SLOADs return random value if storage slot wasn't accessed).
391    /// Changed values are recorded and used to copy storage to different addresses.
392    values: HashMap<Address, HashMap<U256, U256>>,
393    /// Mapping of address with storage copied to arbitrary storage address source.
394    copies: HashMap<Address, Address>,
395    /// Address with storage slots that should be overwritten even if previously set.
396    overwrites: HashSet<Address>,
397    /// Storage slots explicitly written with `vm.store`, grouped by address.
398    explicit_slots: HashMap<Address, HashSet<U256>>,
399    /// Values drawn instead of random ones, by address and slot, so a replay reproduces a
400    /// symbolic counterexample.
401    replay_values: HashMap<(Address, U256), U256>,
402}
403
404impl ArbitraryStorage {
405    /// Marks an address with arbitrary storage.
406    pub fn mark_arbitrary(&mut self, address: &Address, overwrite: bool) {
407        self.values.insert(*address, HashMap::default());
408        self.explicit_slots.remove(address);
409        if overwrite {
410            self.overwrites.insert(*address);
411        } else {
412            self.overwrites.remove(address);
413        }
414    }
415
416    /// Maps an address that copies storage with the arbitrary storage address.
417    pub fn mark_copy(&mut self, from: &Address, to: &Address) {
418        if self.values.contains_key(from) {
419            self.copies.insert(*to, *from);
420            if let Some(slots) = self.explicit_slots.get(from).cloned() {
421                self.explicit_slots.insert(*to, slots);
422            } else {
423                self.explicit_slots.remove(to);
424            }
425        }
426    }
427
428    /// Marks a slot as explicitly written if the address has arbitrary or copied storage.
429    fn mark_explicit(&mut self, address: Address, slot: U256) {
430        if self.values.contains_key(&address) || self.copies.contains_key(&address) {
431            self.explicit_slots.entry(address).or_default().insert(slot);
432        }
433    }
434
435    /// Returns whether a slot was explicitly written for the given address.
436    fn is_explicit(&self, address: Address, slot: U256) -> bool {
437        self.explicit_slots.get(&address).is_some_and(|slots| slots.contains(&slot))
438    }
439
440    /// Returns addresses explicitly marked with arbitrary storage.
441    fn targets(&self) -> impl Iterator<Item = Address> + '_ {
442        self.values.keys().copied()
443    }
444
445    /// Returns addresses explicitly marked with arbitrary storage and whether nonzero slots are
446    /// overwritten.
447    fn target_overwrite_modes(&self) -> impl Iterator<Item = (Address, bool)> + '_ {
448        self.values.keys().map(|address| (*address, self.overwrites.contains(address)))
449    }
450
451    /// Returns addresses that copy storage from arbitrary-storage targets.
452    fn copied_targets(&self) -> impl Iterator<Item = Address> + '_ {
453        self.copies.keys().copied()
454    }
455
456    /// Returns copied arbitrary-storage targets and their source address.
457    fn copied_target_sources(&self) -> impl Iterator<Item = (Address, Address)> + '_ {
458        self.copies.iter().map(|(target, source)| (*target, *source))
459    }
460
461    /// Returns a cached arbitrary value for a slot.
462    fn cached_value(&self, address: Address, slot: U256) -> Option<U256> {
463        self.values.get(&address).and_then(|values| values.get(&slot)).copied()
464    }
465
466    /// Saves arbitrary storage value for a given address:
467    /// - store value in changed values cache.
468    /// - update account's storage with given value.
469    pub fn save(
470        &mut self,
471        state: &mut State<'_>,
472        address: Address,
473        slot: U256,
474        data: U256,
475    ) -> Result<(), evm2::DatabaseError> {
476        self.values.get_mut(&address).expect("missing arbitrary address entry").insert(slot, data);
477        state.storage_slot(&address, slot)?.set(data);
478        Ok(())
479    }
480
481    /// Copies arbitrary storage value from source address to the given target address:
482    /// - if a value is present in arbitrary values cache, then update target storage and return
483    ///   existing value.
484    /// - if no value was yet generated for given slot, then save new value in cache and update both
485    ///   source and target storages.
486    pub fn copy(
487        &mut self,
488        state: &mut State<'_>,
489        target: Address,
490        slot: U256,
491        new_value: U256,
492    ) -> Result<U256, evm2::DatabaseError> {
493        let source = self.copies.get(&target).expect("missing arbitrary copy target entry");
494        let storage_cache = self.values.get_mut(source).expect("missing arbitrary source storage");
495        let value = match storage_cache.get(&slot) {
496            Some(value) => *value,
497            None => {
498                storage_cache.insert(slot, new_value);
499                // Update source storage with new value.
500                state.storage_slot(source, slot)?.set(new_value);
501                new_value
502            }
503        };
504        // Update target storage with new value.
505        state.storage_slot(&target, slot)?.set(value);
506        Ok(value)
507    }
508}
509
510/// List of transactions that can be broadcasted.
511pub type BroadcastableTransactions<N> = VecDeque<BroadcastableTransaction<N>>;
512
513#[derive(Clone, Copy, Debug, PartialEq, Eq)]
514enum CreatedAccountsFrameKind {
515    Call,
516    Create,
517}
518
519#[derive(Clone, Copy, Debug)]
520struct CreatedAccountsFrame {
521    kind: CreatedAccountsFrameKind,
522    depth: usize,
523    checkpoint: usize,
524    /// Recorded log count when the frame started.
525    recorded_logs: usize,
526    /// Recorded log buffer generation when the frame started.
527    recorded_logs_generation: u64,
528}
529
530#[derive(Clone, Copy, Debug)]
531struct CreatedAccountChange {
532    fork_id: Option<LocalForkId>,
533    address: Address,
534    creation: usize,
535    previous: Option<usize>,
536    committed: bool,
537}
538
539#[derive(Clone, Debug)]
540struct CreatedAccountsSnapshot {
541    fork_id: Option<LocalForkId>,
542    bindings: AddressHashMap<usize>,
543}
544
545/// An EVM inspector that handles calls to various cheatcodes, each with their own behavior.
546///
547/// Cheatcodes can be called by contracts during execution to modify the VM environment, such as
548/// mocking addresses, signatures and altering call reverts.
549///
550/// Executing cheatcodes can be very powerful. Most cheatcodes are limited to evm internals, but
551/// there are also cheatcodes like `ffi` which can execute arbitrary commands or `writeFile` and
552/// `readFile` which can manipulate files of the filesystem. Therefore, several restrictions are
553/// implemented for these cheatcodes:
554/// - `ffi`, and file cheatcodes are _always_ opt-in (via foundry config) and never enabled by
555///   default: all respective cheatcode handlers implement the appropriate checks
556/// - File cheatcodes require explicit permissions which paths are allowed for which operation, see
557///   `Config.fs_permission`
558/// - Only permitted accounts are allowed to execute cheatcodes in forking mode, this ensures no
559///   contract deployed on the live network is able to execute cheatcodes by simply calling the
560///   cheatcode address: by default, the caller, test contract and newly deployed contracts are
561///   allowed to execute cheatcodes
562#[derive(Clone, Debug)]
563pub struct Cheatcodes<FEN: FoundryEvmNetwork = EthEvmNetwork> {
564    /// Engine-independent cheatcode state.
565    pub core: CheatcodesCore,
566
567    /// The block environment
568    ///
569    /// Used in the cheatcode handler to overwrite the block environment separately from the
570    /// execution block environment.
571    pub block: Option<BlockEnvFor<FEN>>,
572
573    /// The active fork block override updated by a fork-switching cheatcode.
574    ///
575    /// This persists fork changes made through a copy-on-write backend between invariant calls.
576    pub fork_block_number_override: Option<u64>,
577
578    /// Currently active EIP-7702 delegations that will be consumed when building the next
579    /// transaction. Set by `vm.attachDelegation()` and consumed via `.take()` during
580    /// transaction construction.
581    pub active_delegations: Vec<SignedAuthorization>,
582
583    /// The active EIP-4844 blob that will be attached to the next call.
584    pub active_blob_sidecar: Option<BlobTransactionSidecarVariant>,
585
586    /// The gas price.
587    ///
588    /// Executions run fee-less, so the `GASPRICE` opcode reads this value instead, unless
589    /// `vm.txGasPrice` overrides it.
590    pub gas_price: Option<u128>,
591
592    /// The fee token of the executed transactions, recorded in broadcast requests.
593    pub fee_token: Option<Address>,
594
595    /// The `tx.origin` set by a prank or broadcast, which the `ORIGIN` opcode reads instead of
596    /// the transaction's origin.
597    ///
598    /// evm2 borrows the transaction environment for the whole transaction, so origin changes are
599    /// applied at the opcode level.
600    pub origin_override: Option<Address>,
601
602    /// Whether the executing `ORIGIN` opcode reads [`Self::origin_override`].
603    pending_origin_override: bool,
604
605    /// Whether the executing `GASPRICE` opcode reads [`Self::gas_price`].
606    pending_gas_price: bool,
607
608    /// An `expectEmit` mismatch observed by the log hook, which reverts the emitting frame once
609    /// its `LOG` instruction finishes.
610    pending_emit_failure: Option<&'static str>,
611
612    /// Incremented whenever a cheatcode replaces the running state outside of a snapshot
613    /// restoration, such as a fork switch, so nested executions know to adopt the replaced state.
614    pub state_epoch: u64,
615
616    /// Incremented whenever a cheatcode switches or rolls forks, bumped together with
617    /// `state_epoch`.
618    pub fork_epoch: u64,
619
620    /// Running states replaced by snapshot restorations in the open frames of the running
621    /// transaction, reinstated when a frame that was open at the restoration fails.
622    pub snapshot_restores: SnapshotRestores,
623
624    /// Target of the root call of the running transaction, if it is a call.
625    ///
626    /// While an isolated call or create runs as a nested transaction, this is the target of that
627    /// transaction instead.
628    pub root_call_target: Option<Address>,
629
630    /// Call depth of the running transaction's top-level calls, set by the inspector stack when
631    /// each one starts.
632    ///
633    /// This is the EVM's initial call depth, which is zero unless the transaction handler runs
634    /// the calls below the transaction, such as Tempo's for the calls of an AA transaction.
635    /// Nested transactions, such as isolated calls and replays, keep the running transaction's.
636    pub root_depth: usize,
637
638    /// The EIP-3651 coinbase and access-list addresses the running transaction warmed when it
639    /// started, which `vm.cool` keeps warm.
640    ///
641    /// While an isolated call or create runs as a nested transaction, these are that
642    /// transaction's instead.
643    pub tx_warm_addresses: Vec<Address>,
644
645    /// Prank information, mapped to the call depth where pranks were added.
646    pub pranks: BTreeMap<usize, Prank>,
647
648    /// Expected revert information
649    pub expected_revert: Option<ExpectedRevert>,
650
651    /// Assume next call can revert and discard fuzz run if it does.
652    pub assume_no_revert: Option<AssumeNoRevert>,
653
654    /// Additional diagnostic for reverts
655    pub fork_revert_diagnostic: Option<RevertDiagnostic>,
656
657    /// Recorded storage reads and writes
658    pub accesses: RecordAccess,
659
660    /// Whether storage access recording is currently active
661    pub recording_accesses: bool,
662
663    /// Recorded account accesses (calls, creates) organized by relative call depth, where the
664    /// topmost vector corresponds to accesses at the depth at which account access recording
665    /// began. Each vector in the matrix represents a list of accesses at a specific call
666    /// depth. Once that call context has ended, the last vector is removed from the matrix and
667    /// merged into the previous vector.
668    pub recorded_account_diffs_stack: Option<Vec<Vec<AccountAccess>>>,
669
670    /// Account accesses performed by the test runner before user code can start recording.
671    pending_account_diffs: Option<Arc<[AccountAccess]>>,
672
673    /// Completed account accesses prepended to the active user recording session.
674    recorded_account_diffs_prefix: Option<Arc<[AccountAccess]>>,
675
676    /// Successfully created accounts in execution order.
677    created_accounts: Vec<Address>,
678
679    /// The creation currently represented by each address on each fork.
680    created_account_bindings: HashMap<(Option<LocalForkId>, Address), usize>,
681
682    /// Revertible changes to creation bindings made by EVM create frames.
683    created_account_changes: Vec<CreatedAccountChange>,
684
685    /// Creation-list and recorded-log checkpoints for frames observed by this inspector.
686    created_accounts_frames: Vec<CreatedAccountsFrame>,
687
688    /// Creation lists captured by state snapshots.
689    created_accounts_snapshots: HashMap<U256, CreatedAccountsSnapshot>,
690
691    /// The information of the debug step recording.
692    pub record_debug_steps_info: Option<RecordDebugStepInfo>,
693
694    /// Expected emits
695    pub expected_emits: ExpectedEmitTracker,
696    /// Expected creates
697    pub expected_creates: Vec<ExpectedCreate>,
698
699    /// Map of context depths to memory offset ranges that may be written to within the call depth.
700    pub allowed_mem_writes: HashMap<u64, Vec<Range<u64>>>,
701
702    /// Current broadcasting information
703    pub broadcast: Option<Broadcast>,
704
705    /// Scripting based transactions
706    pub broadcastable_transactions: BroadcastableTransactions<FEN::Network>,
707
708    /// Additional addresses recognized as cheatcode contracts by this executor.
709    pub extra_cheatcode_addresses: &'static [Address],
710
711    /// Revert payloads minted by the `skip` cheatcode during the current test call.
712    ///
713    /// A top-level revert is only classified as a skip when its data byte-equals one of these
714    /// payloads, so user-crafted `FOUNDRY::SKIP` revert data never skips a test on its own.
715    pub skip_payloads: Vec<Bytes>,
716
717    /// Writes that survive reverts of the enclosing calls, with the depth of the frame that made
718    /// them and the journal length right after them, replayed when that frame or an enclosing one
719    /// reverts and its rollback undid them. Writes accepted outside the journal have length zero,
720    /// see [`Self::record_accepted`].
721    pub persistent_writes: Vec<(usize, usize, PersistentWrite)>,
722
723    /// The depth of the frame that ended last and the journal length of its checkpoint, which a
724    /// failure rolls the frame back to, recorded by the inspector stack.
725    pub frame_rollback: Option<(usize, usize)>,
726
727    /// The number of persistent writes recorded when each snapshot of the running transaction
728    /// was taken, capped by the restorations that dropped some of them since.
729    pub persistent_write_snapshots: HashMap<U256, usize>,
730
731    /// Message of the first `vm.assert*` cheatcode that failed during the current call.
732    ///
733    /// Unlike the global failure slot, this survives reverts, so callers still see the failure
734    /// when the asserting call reverts afterwards.
735    pub failed_assertion: Option<String>,
736    /// Records failures by call site while set, so minimizers can tell failures apart.
737    pub failure_trace: Option<FailureTrace>,
738    /// Records where each call failed while set, so a replay can check it failed the same way.
739    pub failure_provenance: Option<FailureProvenance>,
740
741    /// Gas metering state.
742    pub gas_metering: GasMetering,
743
744    /// Contains gas snapshots made over the course of a test suite.
745    // **Note**: both must a BTreeMap to ensure the order of the keys is deterministic.
746    pub gas_snapshots: BTreeMap<String, BTreeMap<String, String>>,
747
748    /// The current program counter.
749    pub pc: usize,
750    /// Breakpoints supplied by the `breakpoint` cheatcode.
751    /// `char -> (address, pc)`
752    pub breakpoints: Breakpoints,
753
754    /// Ignored traces.
755    pub ignored_traces: IgnoredTraces,
756
757    /// SLOAD callbacks keyed by effective storage address.
758    storage_load_hooks: AddressHashMap<StorageHook>,
759    /// SSTORE callbacks keyed by effective storage address.
760    storage_store_hooks: AddressHashMap<StorageHook>,
761    /// Mapping SSTORE callbacks keyed by effective storage address and root slot.
762    mapping_storage_store_hooks: AddressHashMap<HashMap<B256, StorageHook>>,
763    /// Execution-local provenance used only by mapping storage hooks.
764    storage_hook_mapping_slots: AddressHashMap<MappingSlots>,
765    /// A 64-byte Keccak operation awaiting successful completion.
766    pending_mapping_hash: Option<PendingMappingHash>,
767    /// Whether any storage hook map contains a callback.
768    storage_hooks_registered: bool,
769    /// Matching storage access captured before the opcode executes.
770    pending_storage_hook: Option<PendingStorageHook>,
771    /// Synthetic callback frame currently executing.
772    active_storage_hook: Option<ActiveStorageHook>,
773
774    /// Deprecated cheatcodes mapped to the reason. Used to report warnings on test results.
775    pub deprecated: HashMap<&'static str, Option<&'static str>>,
776    /// Main script contract, when script execution protection is enabled.
777    pub script_address: Option<Address>,
778    /// Signatures identifier for decoding events and functions
779    signatures_identifier: OnceLock<Option<SignaturesIdentifier>>,
780    /// Used to determine whether the broadcasted call has dynamic gas limit.
781    pub dynamic_gas_limit: bool,
782    // Custom execution evm version.
783    pub execution_evm_version: Option<SpecFor<FEN>>,
784
785    /// Per-fork opcode environment overrides and their state-snapshot copies.
786    pub env_overrides: EnvOverrideState,
787
788    /// Per-state-snapshot copies of [`Self::fork_block_number_override`].
789    pub fork_block_number_override_snapshots: HashMap<U256, Option<u64>>,
790
791    /// Whether we are currently executing inside an isolation context, i.e. the nested
792    /// transaction an isolated call (`--isolate`, `--gas-report`) executes as.
793    ///
794    /// Cheatcodes that mutate the tx/block env consult this flag and route the change through
795    /// `EnvOverrides` instead of the actual env when `true`, so they don't fight with the
796    /// fee-accounting zeroing.
797    pub in_isolation_context: bool,
798
799    /// Environment of the transaction an isolated call runs in, while it runs.
800    ///
801    /// The isolated call's own nested transaction pays no fees; transactions that cheatcodes
802    /// execute inside it start from this environment instead.
803    pub isolation_env: Option<EvmEnvFor<FEN>>,
804
805    /// Whether a replay is running whose fork-context changes cannot be merged into its parent.
806    pub in_replay: bool,
807
808    /// Depth of the in-flight `deployCode` call, whose create frame runs one level deeper.
809    pub deploy_code_depth: Option<usize>,
810
811    /// Account-creation state gas the in-flight `deployCode` call already charged its caller for
812    /// its create frame.
813    pub deploy_code_create_state_gas: u64,
814
815    /// Output the in-flight `deployCode` call's constructor returned, which the EVM drops if
816    /// depositing it fails, and whether the constructor ran in an isolated call.
817    pub deploy_code_output: Option<(Bytes, bool)>,
818
819    /// The `vm.accessList` the running transaction last applied to a call or create. It replaces
820    /// the transaction's access list when computing its stipend.
821    pub applied_access_list: Option<AccessList>,
822
823    /// Depth of a create that a hook ended with a revert without running its frame.
824    pub unrun_create_depth: Option<usize>,
825
826    /// Code that issued the CREATE being handed off to a new frame EVM.
827    pub env_handoff_creator: Option<Address>,
828
829    /// Automatic CREATE2 redirects: factory call depth, original issuing code, and whether the
830    /// original create grants cheatcode access. The grant is resolved after caller overrides.
831    pub pending_create2_redirects: Vec<(u16, Option<Address>, bool)>,
832}
833
834// This is not derived because calling this in `fn new` with `..Default::default()` creates a second
835// `CheatsConfig` which is unused, and inside it `ProjectPathsConfig` is relatively expensive to
836// create.
837impl Default for Cheatcodes {
838    fn default() -> Self {
839        Self::new(Arc::default())
840    }
841}
842
843impl<FEN: FoundryEvmNetwork> Cheatcodes<FEN> {
844    /// Creates a new `Cheatcodes` with the given settings.
845    pub fn new(config: Arc<CheatsConfig>) -> Self {
846        Self {
847            core: CheatcodesCore::new(config),
848            extra_cheatcode_addresses: &[],
849            block: Default::default(),
850            fork_block_number_override: Default::default(),
851            active_delegations: Default::default(),
852            active_blob_sidecar: Default::default(),
853            gas_price: Default::default(),
854            fee_token: Default::default(),
855            origin_override: Default::default(),
856            pending_origin_override: Default::default(),
857            pending_gas_price: Default::default(),
858            pending_emit_failure: Default::default(),
859            state_epoch: Default::default(),
860            fork_epoch: Default::default(),
861            snapshot_restores: Default::default(),
862            root_call_target: Default::default(),
863            root_depth: Default::default(),
864            tx_warm_addresses: Default::default(),
865            pranks: Default::default(),
866            expected_revert: Default::default(),
867            assume_no_revert: Default::default(),
868            fork_revert_diagnostic: Default::default(),
869            accesses: Default::default(),
870            recording_accesses: Default::default(),
871            recorded_account_diffs_stack: Default::default(),
872            pending_account_diffs: Default::default(),
873            recorded_account_diffs_prefix: Default::default(),
874            created_accounts: Default::default(),
875            created_account_bindings: Default::default(),
876            created_account_changes: Default::default(),
877            created_accounts_frames: Default::default(),
878            created_accounts_snapshots: Default::default(),
879            record_debug_steps_info: Default::default(),
880            expected_emits: Default::default(),
881            expected_creates: Default::default(),
882            allowed_mem_writes: Default::default(),
883            broadcast: Default::default(),
884            broadcastable_transactions: Default::default(),
885            skip_payloads: Default::default(),
886            persistent_writes: Default::default(),
887            frame_rollback: Default::default(),
888            persistent_write_snapshots: Default::default(),
889            failed_assertion: None,
890            failure_trace: Default::default(),
891            failure_provenance: Default::default(),
892            gas_metering: Default::default(),
893            gas_snapshots: Default::default(),
894            pc: Default::default(),
895            breakpoints: Default::default(),
896            ignored_traces: Default::default(),
897            storage_load_hooks: Default::default(),
898            storage_store_hooks: Default::default(),
899            mapping_storage_store_hooks: Default::default(),
900            storage_hook_mapping_slots: Default::default(),
901            pending_mapping_hash: Default::default(),
902            storage_hooks_registered: Default::default(),
903            pending_storage_hook: Default::default(),
904            active_storage_hook: Default::default(),
905            deprecated: Default::default(),
906            script_address: Default::default(),
907            signatures_identifier: Default::default(),
908            dynamic_gas_limit: Default::default(),
909            execution_evm_version: None,
910            env_overrides: Default::default(),
911            fork_block_number_override_snapshots: Default::default(),
912            in_isolation_context: false,
913            isolation_env: None,
914            in_replay: false,
915            deploy_code_depth: None,
916            deploy_code_create_state_gas: 0,
917            deploy_code_output: None,
918            applied_access_list: None,
919            unrun_create_depth: None,
920            env_handoff_creator: None,
921            pending_create2_redirects: Vec::new(),
922        }
923    }
924
925    /// Sets additional addresses recognized as cheatcode contracts.
926    #[inline]
927    pub const fn set_extra_cheatcode_addresses(&mut self, addresses: &'static [Address]) {
928        self.extra_cheatcode_addresses = addresses;
929    }
930
931    /// Starts an internal account diff recording session for test runner setup.
932    pub fn start_internal_state_diff_recording(&mut self) -> bool {
933        if self.recorded_account_diffs_stack.is_some()
934            || self.recorded_account_diffs_prefix.is_some()
935        {
936            return false;
937        }
938        self.recorded_account_diffs_stack = Some(Default::default());
939        true
940    }
941
942    /// Stops an internal account diff recording session without leaving recording enabled.
943    pub fn stop_internal_state_diff_recording(&mut self) -> Vec<AccountAccess> {
944        self.recorded_account_diffs_stack.take().unwrap_or_default().into_iter().flatten().collect()
945    }
946
947    /// Makes account accesses captured by the test runner available to the next recording session.
948    pub fn set_pending_account_diffs(&mut self, accesses: Vec<AccountAccess>) {
949        self.pending_account_diffs = (!accesses.is_empty()).then(|| Arc::from(accesses));
950    }
951
952    /// Starts a user account diff recording session, including pending test runner accesses.
953    pub fn start_state_diff_recording(&mut self) {
954        self.recorded_account_diffs_prefix = self.pending_account_diffs.take();
955        self.recorded_account_diffs_stack = Some(Default::default());
956    }
957
958    /// Returns completed and active account accesses in execution order.
959    pub fn recorded_account_diffs(&self) -> impl Iterator<Item = &AccountAccess> {
960        self.recorded_account_diffs_with_boundaries().flatten()
961    }
962
963    /// Returns account accesses with a `None` boundary between completed runner accesses and the
964    /// active recording. Call frames must not be inherited across this boundary.
965    pub(crate) fn recorded_account_diffs_with_boundaries(
966        &self,
967    ) -> impl Iterator<Item = Option<&AccountAccess>> {
968        self.recorded_account_diffs_prefix
969            .iter()
970            .flat_map(|prefix| prefix.iter())
971            .map(Some)
972            .chain(std::iter::once(None))
973            .chain(self.recorded_account_diffs_stack.iter().flatten().flatten().map(Some))
974    }
975
976    /// Takes completed account accesses from the active user recording session.
977    pub fn take_recorded_account_diffs_prefix(&mut self) -> Vec<AccountAccess> {
978        self.recorded_account_diffs_prefix
979            .take()
980            .map(|prefix| prefix.as_ref().to_vec())
981            .unwrap_or_default()
982    }
983
984    /// Returns the current creation bound to each address on the given fork.
985    pub(crate) fn created_account_bindings(
986        &self,
987        fork_id: Option<LocalForkId>,
988    ) -> AddressHashMap<usize> {
989        self.created_account_bindings
990            .iter()
991            .filter_map(|(&(event_fork_id, address), &creation)| {
992                (event_fork_id == fork_id).then_some((address, creation))
993            })
994            .collect()
995    }
996
997    /// Returns successfully created accounts bound to the given fork in creation order.
998    pub(crate) fn created_accounts(&self, fork_id: Option<LocalForkId>) -> Vec<Address> {
999        let bindings = self.created_account_bindings(fork_id);
1000        self.created_accounts
1001            .iter()
1002            .enumerate()
1003            .filter_map(|(index, &address)| {
1004                (bindings.get(&address) == Some(&index)).then_some(address)
1005            })
1006            .collect()
1007    }
1008
1009    /// Records a successfully created account.
1010    pub(crate) fn record_created_account(
1011        &mut self,
1012        fork_id: Option<LocalForkId>,
1013        address: Address,
1014    ) {
1015        let creation = self.created_accounts.len();
1016        self.created_accounts.push(address);
1017        let previous = self.created_account_bindings.insert((fork_id, address), creation);
1018        self.created_account_changes.push(CreatedAccountChange {
1019            fork_id,
1020            address,
1021            creation,
1022            previous,
1023            committed: false,
1024        });
1025    }
1026
1027    /// Keeps creation bindings saved with an outgoing fork across later frame reverts.
1028    pub(crate) fn commit_created_account_changes(&mut self, fork_id: Option<LocalForkId>) {
1029        for change in &mut self.created_account_changes {
1030            if change.fork_id == fork_id {
1031                change.committed = true;
1032            }
1033        }
1034    }
1035
1036    /// Records shared pre-fork creations on a newly selected fork without replacing local ones.
1037    pub(crate) fn record_initial_created_accounts(
1038        &mut self,
1039        fork_id: Option<LocalForkId>,
1040        accounts: impl IntoIterator<Item = (Address, usize)>,
1041    ) {
1042        for (address, creation) in accounts {
1043            self.created_account_bindings.entry((fork_id, address)).or_insert(creation);
1044        }
1045    }
1046
1047    /// Records creations propagated to a fork with persistent account state.
1048    pub(crate) fn record_propagated_accounts(
1049        &mut self,
1050        fork_id: Option<LocalForkId>,
1051        accounts: impl IntoIterator<Item = (Address, usize)>,
1052    ) {
1053        self.created_account_bindings
1054            .extend(accounts.into_iter().map(|(address, creation)| ((fork_id, address), creation)));
1055    }
1056
1057    /// Captures creation ordering alongside a state snapshot.
1058    pub(crate) fn snapshot_created_accounts(
1059        &mut self,
1060        snapshot_id: U256,
1061        fork_id: Option<LocalForkId>,
1062    ) {
1063        let bindings = self.created_account_bindings(fork_id);
1064        self.created_accounts_snapshots
1065            .insert(snapshot_id, CreatedAccountsSnapshot { fork_id, bindings });
1066    }
1067
1068    /// Restores creation ordering from a state snapshot.
1069    pub(crate) fn revert_created_accounts(&mut self, snapshot_id: U256, remove: bool) {
1070        let snapshot = if remove {
1071            self.created_accounts_snapshots.remove(&snapshot_id)
1072        } else {
1073            self.created_accounts_snapshots.get(&snapshot_id).cloned()
1074        };
1075        if let Some(snapshot) = snapshot {
1076            self.created_account_bindings.retain(|(fork_id, _), _| *fork_id != snapshot.fork_id);
1077            self.created_account_bindings.extend(
1078                snapshot
1079                    .bindings
1080                    .into_iter()
1081                    .map(|(address, creation)| ((snapshot.fork_id, address), creation)),
1082            );
1083        }
1084    }
1085
1086    /// Deletes one captured creation-order snapshot.
1087    pub(crate) fn delete_created_accounts_snapshot(&mut self, snapshot_id: U256) {
1088        self.created_accounts_snapshots.remove(&snapshot_id);
1089    }
1090
1091    /// Deletes all captured creation-order snapshots.
1092    pub(crate) fn clear_created_accounts_snapshots(&mut self) {
1093        self.created_accounts_snapshots.clear();
1094    }
1095
1096    fn start_created_accounts_frame(
1097        &mut self,
1098        reset: bool,
1099        kind: CreatedAccountsFrameKind,
1100        depth: usize,
1101    ) {
1102        if reset {
1103            self.created_accounts.clear();
1104            self.created_account_bindings.clear();
1105            self.created_account_changes.clear();
1106            self.created_accounts_frames.clear();
1107            // Earlier snapshots contain no creations from the new root transaction.
1108            for snapshot in self.created_accounts_snapshots.values_mut() {
1109                snapshot.bindings.clear();
1110            }
1111        }
1112        self.created_accounts_frames.push(CreatedAccountsFrame {
1113            kind,
1114            depth,
1115            checkpoint: self.created_account_changes.len(),
1116            recorded_logs: self.core.recorded_logs.as_ref().map_or(0, Vec::len),
1117            recorded_logs_generation: self.core.recorded_logs_generation,
1118        });
1119    }
1120
1121    fn finish_created_accounts_frame(
1122        &mut self,
1123        success: bool,
1124        kind: CreatedAccountsFrameKind,
1125        depth: usize,
1126    ) {
1127        let Some(frame) = self
1128            .created_accounts_frames
1129            .last()
1130            .copied()
1131            .filter(|frame| frame.kind == kind && frame.depth == depth)
1132        else {
1133            return;
1134        };
1135        let checkpoint = frame.checkpoint;
1136        self.created_accounts_frames.pop();
1137        if !success {
1138            // Logs of a failed frame are reverted. If the buffer was replaced inside the frame,
1139            // every log it holds was recorded by the frame.
1140            if let Some(logs) = &mut self.core.recorded_logs {
1141                logs.truncate(
1142                    if frame.recorded_logs_generation == self.core.recorded_logs_generation {
1143                        frame.recorded_logs
1144                    } else {
1145                        0
1146                    },
1147                );
1148            }
1149            while self.created_account_changes.len() > checkpoint {
1150                let change = self.created_account_changes.pop().expect("length checked");
1151                if change.committed {
1152                    continue;
1153                }
1154                let key = (change.fork_id, change.address);
1155                if self.created_account_bindings.get(&key) != Some(&change.creation) {
1156                    continue;
1157                }
1158                if let Some(previous) = change.previous {
1159                    self.created_account_bindings.insert(key, previous);
1160                } else {
1161                    self.created_account_bindings.remove(&key);
1162                }
1163            }
1164        }
1165    }
1166
1167    /// Returns the configured prank at given depth or the first prank configured at a lower depth.
1168    /// For example, if pranks configured for depth 1, 3 and 5, the prank for depth 4 is the one
1169    /// configured at depth 3.
1170    pub fn get_prank(&self, depth: usize) -> Option<&Prank> {
1171        self.pranks.range(..=depth).last().map(|(_, prank)| prank)
1172    }
1173
1174    /// Adds a delegation to the active delegations list.
1175    pub fn add_delegation(&mut self, authorization: SignedAuthorization) {
1176        self.active_delegations.push(authorization);
1177    }
1178
1179    /// Returns the signatures identifier.
1180    pub fn signatures_identifier(&self) -> Option<&SignaturesIdentifier> {
1181        self.signatures_identifier
1182            .get_or_init(|| {
1183                if let Some(artifacts) = &self.core.config.available_artifacts {
1184                    return SignaturesIdentifier::new_offline_with_abis(
1185                        artifacts.values().map(|contract| &contract.abi),
1186                    )
1187                    .ok();
1188                }
1189                SignaturesIdentifier::new(true).ok()
1190            })
1191            .as_ref()
1192    }
1193
1194    /// Decodes the input data and applies the cheatcode.
1195    fn apply_cheatcode(
1196        &mut self,
1197        interp: &mut InterpreterFor<'_, '_, FEN>,
1198        message: &MessageFor<FEN>,
1199        backend: &mut dyn CheatcodesBackend<FEN>,
1200        gas: &mut GasTracker,
1201        executor: &mut dyn CheatcodesExecutor<FEN>,
1202    ) -> Result {
1203        let decoded = decode_cheatcode_call(message.input.as_bytes(interp.memory()))?;
1204
1205        let caller = message.caller;
1206
1207        // ensure the caller is allowed to execute cheatcodes,
1208        // but only if the backend is in forking mode
1209        let db = backend.backend();
1210        db.ensure_cheatcode_access_forking_mode(&caller)?;
1211        if interp.message().depth < message.depth {
1212            db.ensure_cheatcode_access_forking_mode(&interp.message().code_address)?;
1213        }
1214
1215        let result = apply_dispatch(
1216            &decoded,
1217            &mut CheatsCtxt {
1218                state: self,
1219                evm: interp.host(),
1220                backend,
1221                gas,
1222                caller,
1223                is_static: message.is_static(),
1224                depth: message.depth.into(),
1225            },
1226            executor,
1227        );
1228        if let Some(provenance) = &mut self.failure_provenance {
1229            provenance.finish_assertion();
1230        }
1231        result
1232    }
1233
1234    /// Decodes the input data and applies Monad-specific cheatcodes.
1235    #[cfg(feature = "monad")]
1236    fn apply_monad_cheatcode(
1237        &mut self,
1238        interp: &mut InterpreterFor<'_, '_, FEN>,
1239        message: &MessageFor<FEN>,
1240        backend: &mut dyn CheatcodesBackend<FEN>,
1241        gas: &mut GasTracker,
1242    ) -> Result {
1243        let caller = message.caller;
1244
1245        // ensure the caller is allowed to execute cheatcodes,
1246        // but only if the backend is in forking mode
1247        let db = backend.backend();
1248        db.ensure_cheatcode_access_forking_mode(&caller)?;
1249        if interp.message().depth < message.depth {
1250            db.ensure_cheatcode_access_forking_mode(&interp.message().code_address)?;
1251        }
1252
1253        let input = message.input.to_bytes(interp.memory());
1254        crate::monad::apply_monad_cheatcode(
1255            &mut CheatsCtxt {
1256                state: self,
1257                evm: interp.host(),
1258                backend,
1259                gas,
1260                caller,
1261                is_static: message.is_static(),
1262                depth: message.depth.into(),
1263            },
1264            &input,
1265        )
1266    }
1267
1268    /// Grants cheatcode access for top-level deployments or authorized callers, provided the
1269    /// code issuing the CREATE also has access while forked.
1270    ///
1271    /// Constructors need access before the new contract's runtime code has been deployed.
1272    fn allow_cheatcodes_on_create(
1273        &self,
1274        backend: &mut dyn CheatcodesBackend<FEN>,
1275        depth: usize,
1276        caller: Address,
1277        created_address: Address,
1278        creator: Option<Address>,
1279    ) {
1280        let allowed = self
1281            .pending_create2_redirects
1282            .last()
1283            .filter(|(factory_depth, ..)| usize::from(*factory_depth) + 1 == depth)
1284            .map_or_else(
1285                || {
1286                    Self::can_grant_cheatcodes_on_create(
1287                        backend,
1288                        depth - self.root_depth,
1289                        caller,
1290                        creator,
1291                    )
1292                },
1293                |(.., allowed)| *allowed,
1294            );
1295        if allowed && !backend.backend().has_cheatcode_access(&created_address) {
1296            backend.backend_mut().allow_cheatcode_access(created_address);
1297        }
1298    }
1299
1300    /// Maps the depth of the synthetic `deployCode` create frame, which runs in a nested EVM one
1301    /// level deeper, to the depth of the cheatcode call, where a native create would run.
1302    fn deploy_code_caller_depth(&self, depth: usize) -> usize {
1303        if self.deploy_code_depth.is_some_and(|d| d + 1 == depth) { depth - 1 } else { depth }
1304    }
1305
1306    /// Sets the `tx.origin` the `ORIGIN` opcode reads, given the transaction's own origin.
1307    pub(crate) fn set_origin(&mut self, tx_origin: Address, origin: Address) {
1308        self.origin_override = (origin != tx_origin).then_some(origin);
1309    }
1310
1311    /// Applies the configured `vm.accessList` to the running transaction on every call and
1312    /// create. Access lists do not exist before Berlin, and nested transactions, such as
1313    /// isolated calls, keep their own.
1314    fn apply_access_list(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1315        if let Some(access_list) = &self.core.access_list
1316            && !self.in_isolation_context
1317            && !self.in_replay
1318            && interp.host().spec_id() >= evm2::SpecId::BERLIN
1319        {
1320            self.applied_access_list = Some(access_list.clone());
1321        }
1322    }
1323
1324    /// Handles a call, accounting for whether the executor will isolate it as a transaction.
1325    ///
1326    /// If `isolate_call` is true, the executor owns the transaction nonce increment when the call
1327    /// proceeds to execution.
1328    pub fn call_with_executor(
1329        &mut self,
1330        interp: &mut InterpreterFor<'_, '_, FEN>,
1331        call: &mut MessageFor<FEN>,
1332        backend: &mut dyn CheatcodesBackend<FEN>,
1333        executor: &mut dyn CheatcodesExecutor<FEN>,
1334        isolate_call: bool,
1335    ) -> Option<MessageResultFor<FEN>> {
1336        let tx_origin = interp.host().tx_env().origin;
1337        let curr_depth = usize::from(call.depth);
1338        let is_root = curr_depth == self.root_depth;
1339        self.start_created_accounts_frame(is_root, CreatedAccountsFrameKind::Call, curr_depth);
1340        if is_root {
1341            self.root_call_target = Some(call.destination);
1342            self.applied_access_list = None;
1343        }
1344
1345        // At the root call to test function or script `run()`/`setUp()` functions, we are
1346        // decreasing sender nonce to ensure that it matches on-chain nonce once we start
1347        // broadcasting.
1348        if is_root {
1349            let result = interp.host().state_mut().account(&tx_origin).map(|mut account| {
1350                let prev = account.nonce();
1351                account.set_nonce(prev.saturating_sub(1));
1352                (prev, account.nonce())
1353            });
1354            match result {
1355                Ok((prev, nonce)) => {
1356                    trace!(target: "cheatcodes", sender=%tx_origin, nonce, prev, "corrected nonce");
1357                }
1358                Err(err) => {
1359                    return Some(message_result(
1360                        call,
1361                        InstrStop::Revert,
1362                        Error::from(err).abi_encode().into(),
1363                    ));
1364                }
1365            }
1366        }
1367
1368        let target = call.destination;
1369        // Cheatcodes return the gas they did not spend, as `message_result` does.
1370        let mut gas = GasTracker::new(call.gas_limit);
1371        if target == CHEATCODE_ADDRESS {
1372            // `vm.breakpoint` records the calling instruction, which frames running without
1373            // inspector steps do not track.
1374            self.pc = interp.pc();
1375            let (stop, output) =
1376                match self.apply_cheatcode(interp, call, backend, &mut gas, executor) {
1377                    Ok(retdata) => (InstrStop::Return, retdata.into()),
1378                    Err(err) => (InstrStop::Revert, err.abi_encode().into()),
1379                };
1380            return Some(MessageResultExt { stop, gas, output, ..Default::default() });
1381        }
1382
1383        #[cfg(feature = "monad")]
1384        if crate::monad::is_monad_cheatcode_call(self.extra_cheatcode_addresses, target) {
1385            let checkpoint = interp.host().state().checkpoint();
1386            let (stop, output) = match self.apply_monad_cheatcode(interp, call, backend, &mut gas) {
1387                Ok(retdata) => (InstrStop::Return, retdata.into()),
1388                Err(err) => {
1389                    let evm = interp.host();
1390                    let features = evm.version().features;
1391                    evm.state_mut().rollback(checkpoint, features);
1392                    (InstrStop::Revert, err.abi_encode().into())
1393                }
1394            };
1395            return Some(MessageResultExt { stop, gas, output, ..Default::default() });
1396        }
1397
1398        if target == HARDHAT_CONSOLE_ADDRESS {
1399            return None;
1400        }
1401
1402        // `expectRevert`: track max call depth. This is also done in `initialize_interp`, but
1403        // precompile calls don't create an interpreter frame so we must also track it here.
1404        // The callee executes at `curr_depth + 1`.
1405        if let Some(expected) = &mut self.expected_revert {
1406            expected.max_depth = max(curr_depth + 1, expected.max_depth);
1407        }
1408
1409        // Handle expected calls
1410        if let Some(expected) = self.core.expected_calls.get_mut(&call.call_target) {
1411            expect::observe_call(
1412                expected,
1413                call.input.as_bytes(interp.memory()),
1414                transfer_value(call),
1415                call.gas_limit,
1416                call.kind.into(),
1417            );
1418        }
1419
1420        // Apply our prank
1421        if let Some(prank) = self.get_prank(curr_depth).copied() {
1422            // Apply delegate call, `call.caller`` will not equal `prank.prank_caller`
1423            if prank.delegate_call
1424                && curr_depth == prank.depth
1425                && call.kind == MessageKind::DelegateCall
1426            {
1427                call.destination = prank.new_caller;
1428                call.caller = prank.new_caller;
1429                if let Some(new_origin) = prank.new_origin {
1430                    self.set_origin(tx_origin, new_origin);
1431                }
1432                if let Some(used) = prank.first_time_applied() {
1433                    self.pranks.insert(curr_depth, used);
1434                }
1435            }
1436
1437            if let Some(changes) = prank.changes_for(curr_depth, call.caller) {
1438                if let Some(new_caller) = changes.caller {
1439                    // Ensure new caller is loaded, warm and touched.
1440                    let _ = touch_account(interp.host().state_mut(), new_caller);
1441                    call.caller = new_caller;
1442                }
1443                if let Some(new_origin) = changes.origin {
1444                    self.set_origin(tx_origin, new_origin);
1445                }
1446                if let Some(used) = changes.used {
1447                    self.pranks.insert(curr_depth, used);
1448                }
1449            }
1450        }
1451
1452        // Handle mocked calls
1453        if let Some(mocks) = self.core.mocked_calls.get_mut(&call.call_target)
1454            && let Some(return_data_queue) = mock::find_mock_returns(
1455                mocks,
1456                &call.input.to_bytes(interp.memory()),
1457                transfer_value(call),
1458            )
1459            && let Some(return_data) = return_data_queue.front().map(|x| x.to_owned())
1460        {
1461            if let Some(value) = transfer_value(call) {
1462                let checkpoint = interp.host().state().checkpoint();
1463                let transferred =
1464                    interp.host().state_mut().transfer(&call.caller, &call.destination, &value);
1465                // A reverting mock checks the balance but keeps no transfer, and a failed
1466                // transfer keeps no partial debit.
1467                if return_data.reverts || !matches!(transferred, Ok(true)) {
1468                    let evm = interp.host();
1469                    let features = evm.version().features;
1470                    evm.state_mut().rollback(checkpoint, features);
1471                }
1472                match transferred {
1473                    Ok(true) => {}
1474                    Ok(false) => {
1475                        return Some(message_result(call, InstrStop::OutOfFunds, Bytes::new()));
1476                    }
1477                    Err(err) => {
1478                        return Some(message_result(
1479                            call,
1480                            InstrStop::Revert,
1481                            Error::from(err).abi_encode().into(),
1482                        ));
1483                    }
1484                }
1485            }
1486
1487            mock::advance_mock_returns(return_data_queue);
1488
1489            let stop = if return_data.reverts { InstrStop::Revert } else { InstrStop::Return };
1490            return Some(message_result(call, stop, return_data.data));
1491        }
1492
1493        self.apply_access_list(interp);
1494
1495        // Apply our broadcast
1496        if let Some(broadcast) = &mut self.broadcast {
1497            // Additional check as transfers in forge scripts seem to be estimated at 2300
1498            // by revm leading to "Intrinsic gas too low" failure when simulated on chain.
1499            let is_fixed_gas_limit = call.gas_limit >= 21_000 && !self.dynamic_gas_limit;
1500            self.dynamic_gas_limit = false;
1501
1502            // We only apply a broadcast *to a specific depth*.
1503            //
1504            // We do this because any subsequent contract calls *must* exist on chain and
1505            // we only want to grab *this* call, not internal ones. `deployCode` routed through
1506            // the CREATE2 factory runs one level deeper in a nested EVM.
1507            if (curr_depth == broadcast.depth || broadcast.deploy_from_code)
1508                && call.caller == broadcast.original_caller
1509            {
1510                // Delegatecalls and callcodes run in the caller's context and cannot be
1511                // represented as a transaction from the broadcaster.
1512                if matches!(call.kind, MessageKind::DelegateCall | MessageKind::CallCode) {
1513                    let msg = "`delegatecall`s and `callcode`s cannot be broadcast; use a regular `call` instead";
1514                    return Some(message_result(call, InstrStop::Revert, Error::encode(msg)));
1515                }
1516
1517                // Reset deploy from code flag for upcoming calls.
1518                broadcast.deploy_from_code = false;
1519
1520                // At the target depth we set `msg.sender` & tx.origin.
1521                // We are simulating the caller as being an EOA, so *both* must be set to the
1522                // broadcast.origin.
1523                let new_origin = broadcast.new_origin;
1524                let single_call = broadcast.single_call;
1525                self.set_origin(tx_origin, new_origin);
1526                call.caller = new_origin;
1527
1528                // Add a `legacy` transaction to the VecDeque. We use a legacy transaction here
1529                // because we only need the from, to, value, and data. We can later change this
1530                // into 1559, in the cli package, relatively easily once we
1531                // know the target chain supports EIP-1559.
1532                if !call.is_static() {
1533                    let input = call.input.to_bytes(interp.memory());
1534                    let evm = interp.host();
1535                    // Reading the nonce warms the broadcaster.
1536                    let nonce = match evm.state_mut().account(&new_origin) {
1537                        Ok(mut account) => {
1538                            account.warm();
1539                            account.nonce()
1540                        }
1541                        Err(err) => {
1542                            return Some(message_result(
1543                                call,
1544                                InstrStop::Revert,
1545                                Error::encode(err),
1546                            ));
1547                        }
1548                    };
1549                    let chain_id = self
1550                        .env_overrides
1551                        .get(backend.backend().active_fork_id())
1552                        .and_then(|overrides| overrides.chain_id)
1553                        .unwrap_or(evm.version().chain_id);
1554                    let rpc = backend.backend().active_fork_url();
1555
1556                    let mut tx_req = TransactionRequestFor::<FEN>::default()
1557                        .with_from(new_origin)
1558                        .with_to(target)
1559                        .with_value(transfer_value(call).unwrap_or_default())
1560                        .with_input(input)
1561                        .with_nonce(nonce)
1562                        .with_chain_id(chain_id);
1563                    if is_fixed_gas_limit {
1564                        tx_req.set_gas_limit(call.gas_limit)
1565                    }
1566
1567                    let active_delegations = std::mem::take(&mut self.active_delegations);
1568                    // Set active blob sidecar, if any.
1569                    if let Some(blob_sidecar) = self.active_blob_sidecar.take() {
1570                        // Ensure blob and delegation are not set for the same tx.
1571                        if !active_delegations.is_empty() {
1572                            let msg = "both delegation and blob are active; `attachBlob` and `attachDelegation` are not compatible";
1573                            return Some(message_result(
1574                                call,
1575                                InstrStop::Revert,
1576                                Error::encode(msg),
1577                            ));
1578                        }
1579                        tx_req.set_blob_sidecar(blob_sidecar);
1580                    }
1581
1582                    // Apply active EIP-7702 delegations, if any.
1583                    if !active_delegations.is_empty() {
1584                        match apply_authorization_nonces::<FEN>(
1585                            evm,
1586                            &active_delegations,
1587                            new_origin,
1588                            chain_id,
1589                        ) {
1590                            Ok(writes) => self.record_persistent(
1591                                curr_depth.saturating_sub(1),
1592                                evm.state(),
1593                                writes,
1594                            ),
1595                            Err(err) => {
1596                                return Some(message_result(
1597                                    call,
1598                                    InstrStop::Revert,
1599                                    err.abi_encode().into(),
1600                                ));
1601                            }
1602                        }
1603                        tx_req.set_authorization_list(active_delegations);
1604                    }
1605                    if let Some(fee_token) = self.fee_token {
1606                        tx_req.set_fee_token(fee_token);
1607                    }
1608                    self.broadcastable_transactions.push_back(BroadcastableTransaction {
1609                        rpc,
1610                        transaction: TransactionMaybeSigned::new(tx_req),
1611                        contract_address: None,
1612                    });
1613                    debug!(target: "cheatcodes", tx=?self.broadcastable_transactions.back().unwrap(), "broadcastable call");
1614
1615                    // Isolated transactions increment the nonce during execution. Nested
1616                    // broadcasts do not start a separate transaction and need this increment.
1617                    // The increment survives reverts of the enclosing calls. evm2 runs this hook
1618                    // before the call's checkpoint, so the increment belongs to the caller's frame.
1619                    let bump = if !isolate_call
1620                        && let Ok(mut account) = evm.state_mut().account(&new_origin)
1621                    {
1622                        let prev = account.nonce();
1623                        account.set_nonce(prev + 1);
1624                        debug!(target: "cheatcodes", address=%new_origin, nonce=prev+1, prev, "incremented nonce");
1625                        Some(PersistentWrite::nonce(&account, prev))
1626                    } else {
1627                        None
1628                    };
1629                    if let Some(write) = bump {
1630                        self.record_persistent(curr_depth.saturating_sub(1), evm.state(), [write]);
1631                    }
1632                } else if single_call {
1633                    let msg = "`staticcall`s are not allowed after `broadcast`; use `startBroadcast` instead";
1634                    return Some(message_result(call, InstrStop::Revert, Error::encode(msg)));
1635                }
1636            }
1637        }
1638
1639        // Record called accounts if `startStateDiffRecording` has been called
1640        if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
1641            // Determine if account is "initialized," ie, it has a non-zero balance, a non-zero
1642            // nonce, a non-zero KECCAK_EMPTY codehash, or non-empty code.
1643            let evm = interp.host();
1644            let state_account = recorded_call_state_account(call);
1645            let (initialized, old_balance, old_nonce) =
1646                match evm.state_mut().account(&state_account) {
1647                    Ok(mut account) => {
1648                        // The opcode already warmed a `DELEGATECALL` or `CALLCODE` callee, and a
1649                        // `vm.mockFunction` target is never accessed by the EVM, so keep it cold.
1650                        if state_account == call.destination {
1651                            account.warm();
1652                        }
1653                        (
1654                            account.get().is_some_and(|info| !info.is_empty()),
1655                            account.balance(),
1656                            account.nonce(),
1657                        )
1658                    }
1659                    Err(_) => (false, U256::ZERO, 0),
1660                };
1661            // Fork switches and `vm.chainId` take effect before the execution version changes.
1662            let chain_id = self
1663                .env_overrides
1664                .get(backend.backend().active_fork_id())
1665                .and_then(|overrides| overrides.chain_id)
1666                .unwrap_or(evm.version().chain_id);
1667
1668            let kind = match call.kind {
1669                MessageKind::CallCode => crate::Vm::AccountAccessKind::CallCode,
1670                MessageKind::DelegateCall => crate::Vm::AccountAccessKind::DelegateCall,
1671                MessageKind::StaticCall => crate::Vm::AccountAccessKind::StaticCall,
1672                _ => crate::Vm::AccountAccessKind::Call,
1673            };
1674
1675            // Record this call by pushing it to a new pending vector; all subsequent calls at
1676            // that depth will be pushed to the same vector. When the call ends, the
1677            // RecordedAccountAccess (and all subsequent RecordedAccountAccesses) will be
1678            // updated with the revert status of this call, since the EVM does not mark accounts
1679            // as "warm" if the call from which they were accessed is reverted
1680            let access = AccountAccess {
1681                chainInfo: crate::Vm::ChainInfo {
1682                    forkId: backend.backend().active_fork_id().unwrap_or_default(),
1683                    chainId: U256::from(chain_id),
1684                },
1685                accessor: call.caller,
1686                account: call.call_target,
1687                kind,
1688                initialized,
1689                oldBalance: old_balance,
1690                newBalance: U256::ZERO, // updated on call_end
1691                oldNonce: old_nonce,
1692                newNonce: 0, // updated on call_end
1693                value: call.value,
1694                data: call.input.to_bytes(interp.memory()),
1695                reverted: false,
1696                deployedCode: Bytes::new(),
1697                storageAccesses: vec![], // updated on step
1698                depth: curr_depth as u64,
1699            };
1700            recorded_account_diffs_stack.push(vec![access]);
1701        }
1702
1703        // The factory call keeps the original create's authorization after caller overrides.
1704        if let Some((depth, creator, allowed)) = self.pending_create2_redirects.last_mut()
1705            && *depth == call.depth
1706        {
1707            *allowed = Self::can_grant_cheatcodes_on_create(
1708                backend,
1709                curr_depth - self.root_depth,
1710                call.caller,
1711                *creator,
1712            );
1713        }
1714
1715        None
1716    }
1717
1718    /// Returns addresses explicitly marked with arbitrary storage.
1719    pub fn arbitrary_storage_targets(&self) -> impl Iterator<Item = Address> + '_ {
1720        self.core.arbitrary_storage.as_ref().into_iter().flat_map(ArbitraryStorage::targets)
1721    }
1722
1723    /// Returns addresses explicitly marked with arbitrary storage and whether nonzero slots are
1724    /// overwritten.
1725    pub fn arbitrary_storage_target_overwrite_modes(
1726        &self,
1727    ) -> impl Iterator<Item = (Address, bool)> + '_ {
1728        self.core
1729            .arbitrary_storage
1730            .as_ref()
1731            .into_iter()
1732            .flat_map(ArbitraryStorage::target_overwrite_modes)
1733    }
1734
1735    /// Returns addresses that copy storage from arbitrary-storage targets.
1736    pub fn arbitrary_storage_copied_targets(&self) -> impl Iterator<Item = Address> + '_ {
1737        self.core.arbitrary_storage.as_ref().into_iter().flat_map(ArbitraryStorage::copied_targets)
1738    }
1739
1740    /// Returns copied arbitrary-storage targets and their source address.
1741    pub fn arbitrary_storage_copied_target_sources(
1742        &self,
1743    ) -> impl Iterator<Item = (Address, Address)> + '_ {
1744        self.core
1745            .arbitrary_storage
1746            .as_ref()
1747            .into_iter()
1748            .flat_map(ArbitraryStorage::copied_target_sources)
1749    }
1750
1751    /// Sets the value that arbitrary storage draws for a slot instead of a random one, so a replay
1752    /// reproduces a symbolic counterexample. Slots that are never drawn keep their value.
1753    pub fn set_arbitrary_storage_replay_value(
1754        &mut self,
1755        address: Address,
1756        slot: U256,
1757        value: U256,
1758    ) {
1759        if let Some(storage) = &mut self.core.arbitrary_storage {
1760            storage.replay_values.insert((address, slot), value);
1761        }
1762    }
1763
1764    /// Draws a value for a slot of an arbitrary-storage address or copied target: its replay
1765    /// value, or a random one.
1766    pub(crate) fn draw_arbitrary_storage_value(&mut self, address: Address, slot: U256) -> U256 {
1767        self.core
1768            .arbitrary_storage
1769            .as_ref()
1770            .and_then(|storage| storage.replay_values.get(&(address, slot)).copied())
1771            .unwrap_or_else(|| self.core.rng().random())
1772    }
1773
1774    /// Marks a slot as explicitly written with `vm.store`.
1775    pub fn mark_arbitrary_storage_slot_explicit(&mut self, address: Address, slot: U256) {
1776        if let Some(storage) = &mut self.core.arbitrary_storage {
1777            storage.mark_explicit(address, slot);
1778        }
1779    }
1780
1781    /// Returns whether a slot was explicitly written with `vm.store`.
1782    pub fn is_arbitrary_storage_slot_explicit(&self, address: Address, slot: U256) -> bool {
1783        self.core
1784            .arbitrary_storage
1785            .as_ref()
1786            .is_some_and(|storage| storage.is_explicit(address, slot))
1787    }
1788
1789    /// Returns the value arbitrary storage generated for a slot of an arbitrary-storage address.
1790    pub fn cached_arbitrary_storage_value(&self, address: Address, slot: U256) -> Option<U256> {
1791        self.core.arbitrary_storage.as_ref().and_then(|storage| storage.cached_value(address, slot))
1792    }
1793
1794    /// Whether the given address has arbitrary storage.
1795    pub fn has_arbitrary_storage(&self, address: &Address) -> bool {
1796        self.core.arbitrary_storage.as_ref().is_some_and(|s| s.values.contains_key(address))
1797    }
1798
1799    /// Whether the given slot of address with arbitrary storage should be overwritten.
1800    /// True if address is marked as and overwrite and if no value was previously generated for
1801    /// given slot.
1802    pub fn should_overwrite_arbitrary_storage(
1803        &self,
1804        address: &Address,
1805        storage_slot: U256,
1806    ) -> bool {
1807        self.core.arbitrary_storage.as_ref().is_some_and(|storage| {
1808            storage.overwrites.contains(address)
1809                && storage
1810                    .values
1811                    .get(address)
1812                    .and_then(|arbitrary_values| arbitrary_values.get(&storage_slot))
1813                    .is_none()
1814        })
1815    }
1816
1817    /// Whether the given address is a copy of an address with arbitrary storage.
1818    pub fn is_arbitrary_storage_copy(&self, address: &Address) -> bool {
1819        self.core.arbitrary_storage.as_ref().is_some_and(|s| s.copies.contains_key(address))
1820    }
1821
1822    /// Registers an SLOAD callback, replacing the existing callback for `target`.
1823    pub fn register_storage_load_hook(
1824        &mut self,
1825        target: Address,
1826        callback_target: Address,
1827        callback_selector: [u8; 4],
1828    ) {
1829        self.storage_load_hooks.insert(target, StorageHook { callback_target, callback_selector });
1830        self.storage_hooks_registered = true;
1831    }
1832
1833    /// Registers an SSTORE callback, replacing the existing callback for `target`.
1834    pub fn register_storage_store_hook(
1835        &mut self,
1836        target: Address,
1837        callback_target: Address,
1838        callback_selector: [u8; 4],
1839    ) {
1840        self.storage_store_hooks.insert(target, StorageHook { callback_target, callback_selector });
1841        self.storage_hooks_registered = true;
1842    }
1843
1844    /// Registers a mapping SSTORE callback. Returns false when a raw hook conflicts.
1845    pub fn register_mapping_storage_store_hook(
1846        &mut self,
1847        target: Address,
1848        root_slot: B256,
1849        callback_target: Address,
1850        callback_selector: [u8; 4],
1851    ) -> bool {
1852        if self.storage_store_hooks.contains_key(&target) {
1853            return false;
1854        }
1855        self.storage_hook_mapping_slots.remove(&target);
1856        self.mapping_storage_store_hooks
1857            .entry(target)
1858            .or_default()
1859            .insert(root_slot, StorageHook { callback_target, callback_selector });
1860        self.storage_hooks_registered = true;
1861        true
1862    }
1863
1864    /// Returns registered mapping SSTORE callbacks.
1865    pub fn mapping_storage_store_hooks(
1866        &self,
1867    ) -> impl Iterator<Item = (Address, B256, StorageHook)> + '_ {
1868        self.mapping_storage_store_hooks
1869            .iter()
1870            .flat_map(|(target, hooks)| hooks.iter().map(|(root, hook)| (*target, *root, *hook)))
1871    }
1872
1873    /// Returns whether mapping hooks conflict with a raw store hook.
1874    pub fn has_mapping_storage_store_hooks(&self, target: Address) -> bool {
1875        self.mapping_storage_store_hooks.get(&target).is_some_and(|hooks| !hooks.is_empty())
1876    }
1877
1878    /// Returns registered SLOAD callbacks.
1879    pub fn storage_load_hooks(&self) -> impl Iterator<Item = (Address, StorageHook)> + '_ {
1880        self.storage_load_hooks.iter().map(|(target, hook)| (*target, *hook))
1881    }
1882
1883    /// Returns registered SSTORE callbacks.
1884    pub fn storage_store_hooks(&self) -> impl Iterator<Item = (Address, StorageHook)> + '_ {
1885        self.storage_store_hooks.iter().map(|(target, hook)| (*target, *hook))
1886    }
1887
1888    /// Returns whether any storage callback is registered.
1889    #[inline]
1890    pub const fn has_storage_hooks(&self) -> bool {
1891        self.storage_hooks_registered
1892    }
1893
1894    /// Clears execution-local mapping provenance while preserving hook registrations.
1895    pub fn clear_storage_hook_mapping_slots(&mut self) {
1896        self.storage_hook_mapping_slots.clear();
1897    }
1898
1899    /// Returns whether a synthetic storage-hook callback or one of its child calls is executing.
1900    #[inline]
1901    pub const fn is_storage_hook_active(&self) -> bool {
1902        self.active_storage_hook.is_some()
1903    }
1904
1905    /// Returns whether `call` is the synthetic callback for the active storage hook.
1906    pub fn is_storage_hook_callback(&self, call: &MessageFor<FEN>) -> bool {
1907        self.active_storage_hook.as_ref().is_some_and(|active| {
1908            call.depth == active.depth
1909                && call.caller == CHEATCODE_ADDRESS
1910                && call.destination == active.callback_target
1911                && call.input.as_owned() == Some(&active.callback_input)
1912        })
1913    }
1914
1915    /// Returns the opcodes the cheatcodes step: those of [`Self::hook_steps`], and `JUMPI` while
1916    /// failure provenance is collected.
1917    ///
1918    /// This is the only place that decides which instructions the cheatcodes step: the inspector
1919    /// asks the EVM for these opcodes, and skips the hooks for every other instruction.
1920    pub fn steps(&self) -> OpcodeSet {
1921        let steps = self.hook_steps();
1922        // Failure provenance records every branch, through [`Self::record_branch`].
1923        if self.failure_provenance.is_some() { steps.union(opcodes([op::JUMPI])) } else { steps }
1924    }
1925
1926    /// Returns the opcodes at which [`Self::step_hook`] and [`Self::step_end_hook`] must run. The
1927    /// other opcodes of [`Self::steps`] only need [`Self::record_branch`].
1928    pub fn hook_steps(&self) -> OpcodeSet {
1929        if self.is_storage_hook_active()
1930            || self.has_storage_hooks()
1931            || self.broadcast.is_some()
1932            || self.gas_metering.paused
1933            || self.gas_metering.reset
1934            || self.gas_metering.recording
1935            || self.core.arbitrary_storage.is_some()
1936            || self.deploy_code_depth.is_some()
1937            || self.failure_trace.as_ref().is_some_and(|trace| !trace.paused)
1938        {
1939            return OpcodeSet::ALL;
1940        }
1941        let mut steps = OpcodeSet::EMPTY;
1942        // After a resume or reset, the gas check runs when a frame returns or reverts.
1943        if self.gas_metering.touched {
1944            steps = steps.union(FRAME_END_OPCODES);
1945        }
1946        if self.recorded_account_diffs_stack.is_some() {
1947            steps = steps.union(STATE_DIFF_OPCODES);
1948        }
1949        if !self.allowed_mem_writes.is_empty() {
1950            steps = steps.union(MEMORY_OPCODES);
1951        }
1952        // Mapping recording reads the stored slot and the 32- or 64-byte hash that derives it.
1953        if self.core.mapping_slots.is_some() {
1954            steps = steps.union(opcodes([op::SSTORE, op::KECCAK256]));
1955        }
1956        // A log that fails `expectEmit` reverts its frame in the `step_end` of the instruction
1957        // that emitted it.
1958        if !self.expected_emits.is_empty() || self.pending_emit_failure.is_some() {
1959            steps = steps.union(LOG_EMITTING_OPCODES);
1960        }
1961        if self.recording_accesses {
1962            steps = steps.union(opcodes([op::SLOAD, op::SSTORE]));
1963        }
1964        // Origin and gas price overrides rewrite what these instructions push.
1965        if self.origin_override.is_some() || self.gas_price.is_some() {
1966            steps = steps.union(opcodes([op::ORIGIN, op::GASPRICE]));
1967        }
1968        if self.has_active_env_overrides() {
1969            steps = steps.union(opcodes([op::BASEFEE, op::GASPRICE, op::CHAINID, op::BLOBHASH]));
1970        }
1971        if self.failure_provenance.is_some() {
1972            steps = steps.union(opcodes([op::REVERT, op::INVALID]));
1973        }
1974        steps
1975    }
1976
1977    /// Records the `JUMPI` about to execute for the failure provenance, as [`Self::step_hook`]
1978    /// does. Fuzz campaigns step every `JUMPI` only for this, so it skips the other hooks.
1979    #[inline]
1980    pub fn record_branch(&mut self, interp: &InterpreterFor<'_, '_, FEN>) {
1981        if let Some(provenance) = &mut self.failure_provenance {
1982            provenance.record_jumpi(usize::from(interp.message().depth) + 1, interp.pc());
1983        }
1984    }
1985
1986    #[inline(always)]
1987    pub fn has_log_hooks(&self) -> bool {
1988        !self.expected_emits.is_empty() || self.core.recorded_logs.is_some()
1989    }
1990
1991    #[inline(always)]
1992    const fn has_active_env_overrides(&self) -> bool {
1993        self.env_overrides.is_any_set()
1994    }
1995
1996    /// Called after a frame interpreter has been initialized.
1997    pub fn initialize_interp_hook(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
1998        // When the first interpreter is initialized we've circumvented the balance and gas checks,
1999        // so we apply our actual block data with the correct fees and all.
2000        if let Some(block) = self.block.take() {
2001            interp.host().set_block(block);
2002        }
2003
2004        // Record gas for current frame.
2005        if self.gas_metering.paused {
2006            self.gas_metering.paused_frames.push(interp.gas());
2007        }
2008
2009        // `expectRevert`: track the max call depth during `expectRevert`
2010        if let Some(expected) = &mut self.expected_revert {
2011            expected.max_depth = max(usize::from(interp.message().depth) + 1, expected.max_depth);
2012        }
2013
2014        if let Some(trace) = &mut self.failure_trace {
2015            trace.enter_frame::<FEN>(interp, usize::from(interp.message().depth) + 1);
2016        }
2017    }
2018
2019    /// Called before each instruction in [`Self::steps`] executes.
2020    ///
2021    /// Kept out of line: it runs only while a cheatcode needs per-instruction work, and inlining
2022    /// it into the inspector's per-instruction hook enlarges that hook's frame for every opcode.
2023    #[inline(never)]
2024    pub fn step_hook(
2025        &mut self,
2026        interp: &mut InterpreterFor<'_, '_, FEN>,
2027        backend: &mut dyn CheatcodesBackend<FEN>,
2028    ) {
2029        self.pc = interp.pc();
2030
2031        let depth = usize::from(interp.message().depth) + 1;
2032        let opcode = interp.opcode();
2033
2034        if let Some(trace) = &mut self.failure_trace {
2035            trace.step::<FEN>(interp, depth);
2036        }
2037        if let Some(provenance) = &mut self.failure_provenance {
2038            match opcode {
2039                op::JUMPI => provenance.record_jumpi(depth, self.pc),
2040                op::REVERT | op::INVALID => provenance.record_revert::<FEN>(interp, depth),
2041                _ => {}
2042            }
2043        }
2044
2045        // Marks an `ORIGIN` or `GASPRICE` instruction whose pushed value `step_end` overrides.
2046        self.pending_origin_override = opcode == op::ORIGIN && self.origin_override.is_some();
2047        self.pending_gas_price = opcode == op::GASPRICE && self.gas_price.is_some();
2048
2049        if self.broadcast.is_some() {
2050            self.set_gas_limit_type(interp);
2051        }
2052
2053        // Broadcasting changes outgoing calls, not the caller of the script's current frame.
2054        // Only protect the broadcasting frame; callbacks into the script have their own caller.
2055        if opcode == op::CALLER
2056            && let Some(broadcast) = &self.broadcast
2057            && let Some(script_address) = self.script_address
2058            && depth == broadcast.depth
2059            && interp.message().destination == script_address
2060            && interp.message().code_address == script_address
2061            && interp.message().caller != broadcast.new_origin
2062        {
2063            let message = format!(
2064                "Usage of `msg.sender` inside a `broadcast` in script contract detected. \
2065                 `msg.sender` is `{:#x}`, not the broadcast sender `{:#x}`. \
2066                 Use the `--sender` flag or pass the deployer address directly instead.",
2067                interp.message().caller,
2068                broadcast.new_origin,
2069            );
2070            revert_frame(interp, message.as_bytes());
2071            return;
2072        }
2073
2074        // `pauseGasMetering`: pause / resume interpreter gas.
2075        if self.gas_metering.paused {
2076            self.meter_gas(interp);
2077        }
2078
2079        // `resetGasMetering`: reset interpreter gas.
2080        if self.gas_metering.reset {
2081            self.meter_gas_reset(interp);
2082        }
2083
2084        // `record`: record storage reads and writes.
2085        if self.recording_accesses {
2086            self.record_accesses(interp);
2087        }
2088
2089        // `startStateDiffRecording`: record granular ordered storage accesses.
2090        if self.recorded_account_diffs_stack.is_some() {
2091            self.record_state_diffs(interp, backend, depth);
2092        }
2093
2094        // `expectSafeMemory`: check if the current opcode is allowed to interact with memory.
2095        if !self.allowed_mem_writes.is_empty() {
2096            self.check_mem_opcodes(interp, depth as u64);
2097        }
2098
2099        if self.core.mapping_slots.is_some() || !self.mapping_storage_store_hooks.is_empty() {
2100            // `startMappingRecording`: record SSTORE.
2101            if let Some(mapping_slots) = &mut self.core.mapping_slots {
2102                mapping_step(mapping_slots, interp);
2103            }
2104
2105            let account = interp.message().destination;
2106            let mapping_hook_active = self.active_storage_hook.is_none()
2107                && self
2108                    .mapping_storage_store_hooks
2109                    .get(&account)
2110                    .is_some_and(|hooks| !hooks.is_empty());
2111            if mapping_hook_active {
2112                mapping_step(&mut self.storage_hook_mapping_slots, interp);
2113            }
2114            self.pending_mapping_hash = if self.core.mapping_slots.is_some() || mapping_hook_active
2115            {
2116                capture_mapping_hash(interp)
2117            } else {
2118                None
2119            };
2120        }
2121
2122        // `snapshotGas*`: take a snapshot of the current gas.
2123        if self.gas_metering.recording {
2124            self.meter_gas_record(interp, depth);
2125        }
2126
2127        // Capture the opcode for `step_end` to use, since by the time
2128        // `step_end` runs the PC has already advanced past it. Also peek the
2129        // BLOBHASH index now (still on top of stack before execution) so we
2130        // can look up the override later.
2131        if !self.env_overrides.is_empty() {
2132            let fork_id = backend.backend().active_fork_id();
2133            if let Some(env_overrides) =
2134                self.env_overrides.get_mut(fork_id).filter(|o| o.is_any_set())
2135            {
2136                // Always clear stale pending state first so a leftover value from
2137                // a prior step (e.g. when `peek` failed, or when an override
2138                // wasn't actually used) cannot leak into the next opcode.
2139                env_overrides.pending_opcode = None;
2140                env_overrides.pending_blobhash_index = None;
2141
2142                match opcode {
2143                    op::BASEFEE | op::GASPRICE | op::CHAINID => {
2144                        env_overrides.pending_opcode = Some(opcode);
2145                    }
2146                    op::BLOBHASH => {
2147                        env_overrides.pending_opcode = Some(opcode);
2148                        env_overrides.pending_blobhash_index =
2149                            interp.stack().peek(0).and_then(|index| index.try_into().ok());
2150                    }
2151                    _ => {}
2152                }
2153            }
2154        }
2155
2156        if self.active_storage_hook.is_none() {
2157            self.capture_storage_hook(interp);
2158        }
2159    }
2160
2161    /// Called after each instruction in [`Self::steps`] executes.
2162    ///
2163    /// Kept out of line for the same reason as [`Self::step_hook`].
2164    #[inline(never)]
2165    pub fn step_end_hook(
2166        &mut self,
2167        interp: &mut InterpreterFor<'_, '_, FEN>,
2168        backend: &mut dyn CheatcodesBackend<FEN>,
2169        executor: &mut dyn CheatcodesExecutor<FEN>,
2170    ) {
2171        // `deployCode`: keep the constructor's output, which it reports if depositing it fails.
2172        if let Some(depth) = self.deploy_code_depth
2173            && usize::from(interp.message().depth) == depth + 1
2174            && interp.message().kind.is_create()
2175            && interp.result() == Err(InstrStop::Return)
2176        {
2177            self.deploy_code_output =
2178                Some((Bytes::copy_from_slice(interp.output()), self.in_isolation_context));
2179        }
2180
2181        // `expectEmit`: a mismatched log reverts the frame that emitted it.
2182        if let Some(reason) = self.pending_emit_failure.take()
2183            && interp.result().is_ok()
2184        {
2185            revert_frame(interp, &Error::encode(reason));
2186            return;
2187        }
2188
2189        if self.gas_metering.paused {
2190            self.meter_gas_end(interp);
2191        }
2192
2193        if self.gas_metering.touched {
2194            self.meter_gas_check(interp);
2195        }
2196
2197        // `setArbitraryStorage` and `copyStorage`: add arbitrary values to storage.
2198        if self.core.arbitrary_storage.is_some() {
2199            self.arbitrary_storage_end(interp);
2200        }
2201
2202        if let Some(pending) = self.pending_mapping_hash.take()
2203            && interp.result().is_ok()
2204        {
2205            if let Some(mapping_slots) = &mut self.core.mapping_slots {
2206                record_mapping_hash(mapping_slots, interp, pending);
2207            }
2208            // Storage hooks resolve only mapping entries, whose slots are 64-byte hashes.
2209            if pending.size == 0x40
2210                && self
2211                    .mapping_storage_store_hooks
2212                    .get(&pending.address)
2213                    .is_some_and(|hooks| !hooks.is_empty())
2214                && self.active_storage_hook.is_none()
2215            {
2216                record_mapping_hash(&mut self.storage_hook_mapping_slots, interp, pending);
2217            }
2218        }
2219
2220        if self.active_storage_hook.is_none() {
2221            self.invoke_pending_storage_hook(interp, backend, executor);
2222        }
2223
2224        // Apply opcode-level overrides. We must only rewrite the stack if the opcode actually
2225        // completed successfully and pushed its result; otherwise (stack underflow on BLOBHASH,
2226        // OOG before push, etc.) the stack is in an error state and a blind `pop()+push()` would
2227        // corrupt the failing frame.
2228        let opcode_failed = interp.result().is_err();
2229        if std::mem::take(&mut self.pending_origin_override)
2230            && !opcode_failed
2231            && let Some(origin) = self.origin_override
2232        {
2233            Self::replace_top_of_stack(interp, origin.into_word().into());
2234        }
2235        // `vm.txGasPrice` overrides below take precedence.
2236        if std::mem::take(&mut self.pending_gas_price)
2237            && !opcode_failed
2238            && let Some(gas_price) = self.gas_price
2239        {
2240            Self::replace_top_of_stack(interp, U256::from(gas_price));
2241        }
2242        if !self.env_overrides.is_empty() {
2243            let fork_id = backend.backend().active_fork_id();
2244            if self.env_overrides.get(fork_id).is_some_and(|o| o.is_any_set()) {
2245                if opcode_failed {
2246                    if let Some(env_overrides) = self.env_overrides.get_mut(fork_id) {
2247                        env_overrides.pending_opcode = None;
2248                        env_overrides.pending_blobhash_index = None;
2249                    }
2250                } else {
2251                    self.apply_env_overrides(interp, fork_id);
2252                }
2253            }
2254        }
2255    }
2256
2257    /// Called when a log is emitted.
2258    pub fn log_hook(&mut self, log: &Log) {
2259        if !self.expected_emits.is_empty()
2260            && let Some(reason) = crate::expected_emit::observe_log(&mut self.expected_emits, log)
2261        {
2262            // The emitting frame reverts once its `LOG` instruction finishes.
2263            self.pending_emit_failure = Some(reason);
2264        }
2265
2266        // `recordLogs`
2267        record_logs(&mut self.core.recorded_logs, log);
2268    }
2269
2270    /// Records `writes` the frame at `depth` just made to `state`, see
2271    /// [`Self::persistent_writes`].
2272    pub fn record_persistent(
2273        &mut self,
2274        depth: usize,
2275        state: &State<'_>,
2276        writes: impl IntoIterator<Item = PersistentWrite>,
2277    ) {
2278        let len = state.checkpoint().journal_len();
2279        self.persistent_writes.extend(writes.into_iter().map(|write| (depth, len, write)));
2280    }
2281
2282    /// Records `writes` the frame at `depth` just accepted into the running state outside the
2283    /// journal, at journal length zero: no rollback undoes them, so only a failing frame that
2284    /// reinstates the state a snapshot restoration replaced replays them.
2285    pub fn record_accepted(
2286        &mut self,
2287        depth: usize,
2288        writes: impl IntoIterator<Item = PersistentWrite>,
2289    ) {
2290        self.persistent_writes.extend(writes.into_iter().map(|write| (depth, 0, write)));
2291    }
2292
2293    /// Retains `replaced`, the running state a revert to `snapshot_id` replaced, and drops the
2294    /// persistent writes recorded since the snapshot, which the restored state does not hold.
2295    /// `switched` is whether the revert switched to another fork.
2296    pub(crate) fn restore_persistent_writes(
2297        &mut self,
2298        snapshot_id: U256,
2299        replaced: StateSnapshot,
2300        remove: bool,
2301        switched: bool,
2302    ) {
2303        let len = if remove {
2304            self.persistent_write_snapshots.remove(&snapshot_id)
2305        } else {
2306            self.persistent_write_snapshots.get(&snapshot_id).copied()
2307        }
2308        .unwrap_or_default();
2309        self.snapshot_restores.capture(replaced, &self.persistent_writes, len);
2310        // Like a fork switch, a revert to a snapshot of another fork is a context switch.
2311        if switched {
2312            self.snapshot_restores.accept_writes();
2313        }
2314        // A snapshot of an earlier transaction holds none of this transaction's writes. Under the
2315        // inspector stack a failing frame reinstates the captured ledger, followed by the writes
2316        // recorded since, instead; this covers the stackless executor.
2317        self.persistent_writes.truncate(len);
2318        // The writes recorded from here on replace the dropped ones, so a later restoration to a
2319        // snapshot that counted those only keeps the writes kept here. The state it restores
2320        // already holds the others.
2321        let len = self.persistent_writes.len();
2322        for stored in self.persistent_write_snapshots.values_mut() {
2323            *stored = (*stored).min(len);
2324        }
2325    }
2326
2327    /// Replays the persistent writes made in the frame at `depth` or deeper after the frame
2328    /// failed and the writes were rolled back, as writes of the enclosing frame. A transaction's
2329    /// writes are dropped when its root frame ends, and a failed root frame does not replay the
2330    /// writes its rollback undid; a nested one merges its changes itself.
2331    fn replay_persistent_writes(
2332        &mut self,
2333        interp: &mut InterpreterFor<'_, '_, FEN>,
2334        depth: usize,
2335        success: bool,
2336    ) {
2337        if self.persistent_writes.is_empty() {
2338            return;
2339        }
2340        let root = usize::from(interp.host().initial_call_depth());
2341        let state = interp.host().state_mut();
2342        let mut failed = None;
2343        if !success && depth > root {
2344            // Without the frame's rollback, such as without the inspector stack, every journaled
2345            // write of the frame was undone. A context switch in the frame can leave later writes
2346            // below its checkpoint, which the rollback keeps.
2347            let rollback =
2348                self.frame_rollback.take().filter(|(end, _)| *end == depth).map(|(_, len)| len);
2349            let undone = |&(write_depth, len, _): &(usize, usize, PersistentWrite)| {
2350                write_depth >= depth && len > rollback.unwrap_or_default()
2351            };
2352            let writes = self.persistent_writes.iter().filter(|entry| undone(entry));
2353            let applied = PersistentWrite::apply_all(writes.map(|(_, _, write)| write), state);
2354            let len = state.checkpoint().journal_len();
2355            self.persistent_writes.retain_mut(|entry| {
2356                if !undone(entry) {
2357                    return true;
2358                }
2359                entry.1 = len;
2360                !entry.2.is_balance_or_nonce()
2361            });
2362            match applied {
2363                Ok(applied) => self
2364                    .persistent_writes
2365                    .extend(applied.into_iter().map(|write| (depth, len, write))),
2366                Err(err) => failed = Some(err),
2367            }
2368        }
2369        for (write_depth, ..) in &mut self.persistent_writes {
2370            // The parent owns the writes once the frame ends, so a failing sibling at the same
2371            // depth does not replay them again.
2372            if *write_depth >= depth && depth > root {
2373                *write_depth = depth - 1;
2374            }
2375        }
2376        if depth == root {
2377            self.persistent_writes.retain(|(write_depth, ..)| *write_depth < root);
2378        }
2379        if let Some(err) = failed {
2380            let _ = interp.fail(err);
2381        }
2382    }
2383
2384    /// Called after a call message executes.
2385    pub fn call_end_hook(
2386        &mut self,
2387        interp: &mut InterpreterFor<'_, '_, FEN>,
2388        call: &MessageFor<FEN>,
2389        outcome: &mut MessageResultFor<FEN>,
2390        backend: &mut dyn CheatcodesBackend<FEN>,
2391    ) {
2392        let curr_depth = usize::from(call.depth);
2393        self.replay_persistent_writes(interp, curr_depth, outcome.is_success());
2394        // Depth at which the caller resumes and applies the region snapshot correction.
2395        let isolated_snapshot_gas_used = self.gas_metering.take_isolated_snapshot_gas_used(
2396            self.deploy_code_caller_depth(curr_depth),
2397            &outcome.gas,
2398        );
2399        if self.is_storage_hook_callback(call) {
2400            return;
2401        }
2402
2403        let target = call.destination;
2404        let cheatcode_call = target == CHEATCODE_ADDRESS || target == HARDHAT_CONSOLE_ADDRESS;
2405        #[cfg(feature = "monad")]
2406        let cheatcode_call = cheatcode_call
2407            || crate::monad::is_monad_cheatcode_call(self.extra_cheatcode_addresses, target);
2408        let tx_origin = interp.host().tx_env().origin;
2409
2410        self.finish_created_accounts_frame(
2411            outcome.is_success(),
2412            CreatedAccountsFrameKind::Call,
2413            curr_depth,
2414        );
2415
2416        // Clean up pranks/broadcasts if it's not a cheatcode call end. We shouldn't do
2417        // it for cheatcode calls because they are not applied for cheatcodes in the `call` hook.
2418        // This should be placed before the revert handling, because we might exit early there
2419        if !cheatcode_call {
2420            // Clean up pranks
2421            if let Some(prank) = self.get_prank(curr_depth).copied()
2422                && curr_depth == prank.depth
2423            {
2424                self.set_origin(tx_origin, prank.prank_origin);
2425
2426                // Clean single-call prank once we have returned to the original depth
2427                if prank.single_call {
2428                    self.pranks.remove(&curr_depth);
2429                }
2430            }
2431
2432            // Clean up broadcast
2433            if let Some(broadcast) = self.broadcast.clone()
2434                && curr_depth == broadcast.depth
2435            {
2436                self.set_origin(tx_origin, broadcast.original_origin);
2437
2438                // Clean single-call broadcast once we have returned to the original depth
2439                if broadcast.single_call {
2440                    let _ = self.broadcast.take();
2441                }
2442            }
2443        }
2444
2445        // Handle assume no revert cheatcode.
2446        if let Some(assume_no_revert) = &mut self.assume_no_revert {
2447            // Record current reverter address before processing the expect revert if call reverted,
2448            // expect revert is set with expected reverter address and no actual reverter set yet.
2449            if outcome.stop.is_frame_revert() && assume_no_revert.reverted_by.is_none() {
2450                assume_no_revert.reverted_by = Some(target);
2451            }
2452
2453            // allow multiple cheatcode calls at the same depth
2454            if curr_depth <= assume_no_revert.depth && !cheatcode_call {
2455                // Discard run if we're at the same depth as cheatcode, call reverted, and no
2456                // specific reason was supplied
2457                if outcome.stop.is_frame_revert() {
2458                    let assume_no_revert = std::mem::take(&mut self.assume_no_revert).unwrap();
2459                    return match revert_handlers::handle_assume_no_revert(
2460                        &assume_no_revert,
2461                        outcome.stop,
2462                        &outcome.output,
2463                        &self.core.config.available_artifacts,
2464                    ) {
2465                        // if result is Ok, it was an anticipated revert; return an "assume" error
2466                        // to reject this run
2467                        Ok(_) => {
2468                            outcome.output = Error::from(MAGIC_ASSUME).abi_encode().into();
2469                        }
2470                        // if result is Error, it was an unanticipated revert; should revert
2471                        // normally
2472                        Err(error) => {
2473                            trace!(expected=?assume_no_revert, ?error, status=?outcome.stop, "Expected revert mismatch");
2474                            set_revert(outcome, error.abi_encode().into());
2475                        }
2476                    };
2477                }
2478                // Call didn't revert, reset `assume_no_revert` state.
2479                self.assume_no_revert = None;
2480            }
2481        }
2482
2483        // Handle expected reverts.
2484        if let Some(expected_revert) = &mut self.expected_revert {
2485            // Record current reverter address and call scheme before processing the expect revert
2486            // if call reverted.
2487            let call_failed = !outcome.is_success();
2488            if call_failed {
2489                // Record current reverter address if expect revert is set with expected reverter
2490                // address and no actual reverter was set yet or if we're expecting more than one
2491                // revert.
2492                if expected_revert.reverter.is_some()
2493                    && (expected_revert.reverted_by.is_none() || expected_revert.count > 1)
2494                {
2495                    expected_revert.reverted_by = Some(target);
2496                }
2497            }
2498
2499            if curr_depth <= expected_revert.depth {
2500                let needs_processing = expected_revert.needs_processing(
2501                    cheatcode_call,
2502                    call_failed,
2503                    curr_depth - self.root_depth,
2504                    self.core.config.internal_expect_revert,
2505                );
2506
2507                if needs_processing {
2508                    let mut expected_revert = std::mem::take(&mut self.expected_revert).unwrap();
2509                    let clear_last_frame_gas =
2510                        matches!(expected_revert.kind, ExpectedRevertKind::Default);
2511                    return match revert_handlers::handle_expect_revert(
2512                        cheatcode_call,
2513                        false,
2514                        self.core.config.internal_expect_revert,
2515                        &expected_revert,
2516                        outcome.stop,
2517                        outcome.output.clone(),
2518                        &self.core.config.available_artifacts,
2519                    ) {
2520                        Err(error) => {
2521                            trace!(expected=?expected_revert, ?error, status=?outcome.stop, "Expected revert mismatch");
2522                            set_revert(outcome, error.abi_encode().into());
2523                        }
2524                        Ok((_, retdata)) => {
2525                            expected_revert.actual_count += 1;
2526                            if expected_revert.actual_count < expected_revert.count {
2527                                self.expected_revert = Some(expected_revert);
2528                            }
2529                            if clear_last_frame_gas {
2530                                self.gas_metering.last_frame_gas = None;
2531                            }
2532                            set_return(outcome, retdata);
2533                        }
2534                    };
2535                }
2536
2537                // Flip `pending_processing` flag for cheatcode revert expectations, marking that
2538                // we've exited the `expectCheatcodeRevert` call scope
2539                if let ExpectedRevertKind::Cheatcode { pending_processing } =
2540                    &mut self.expected_revert.as_mut().unwrap().kind
2541                {
2542                    *pending_processing = false;
2543                }
2544            }
2545        }
2546
2547        // Exit early for calls to cheatcodes as other logic is not relevant for cheatcode
2548        // invocations
2549        if cheatcode_call {
2550            return;
2551        }
2552
2553        // Record the gas usage of the call, this allows the `lastFrameGas` cheatcode to
2554        // retrieve the gas usage of the last call or create.
2555        let frame_gas = frame_gas(outcome.stop, &outcome.gas);
2556        let snapshot_gas_used = isolated_snapshot_gas_used.unwrap_or_else(|| outcome.gas.spent());
2557        self.gas_metering.last_call_gas = Some(frame_gas.clone());
2558        self.gas_metering.last_frame_gas = Some(frame_gas);
2559        self.gas_metering.last_call_snapshot_gas_used = snapshot_gas_used;
2560        self.gas_metering.last_frame_snapshot_gas_used = snapshot_gas_used;
2561
2562        // If `startStateDiffRecording` has been called, update the `reverted` status of the
2563        // previous call depth's recorded accesses, if any
2564        if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
2565            // The root call cannot be recorded.
2566            if curr_depth > self.root_depth
2567                && let Some(mut last_recorded_depth) = recorded_account_diffs_stack.pop()
2568            {
2569                // Update the reverted status of all deeper calls if this call reverted, in
2570                // accordance with EVM behavior
2571                if outcome.stop.is_frame_revert() {
2572                    mark_account_accesses_reverted(&mut last_recorded_depth);
2573                }
2574
2575                if let Some(call_access) = last_recorded_depth.first_mut() {
2576                    // Assert that we're at the correct depth before recording post-call state
2577                    // changes. Depending on the depth the cheat was
2578                    // called at, there may not be any pending
2579                    // calls to update if execution has percolated up to a higher depth.
2580                    let state_account = recorded_call_state_account(call);
2581                    if call_access.depth == curr_depth as u64
2582                        && let Ok(mut account) = interp.host().state_mut().account(&state_account)
2583                    {
2584                        debug_assert!(access_is_call(call_access.kind));
2585                        if state_account == call.destination {
2586                            account.warm();
2587                        }
2588                        call_access.newBalance = account.balance();
2589                        call_access.newNonce = account.nonce();
2590                    }
2591                    merge_recorded_frame(recorded_account_diffs_stack, last_recorded_depth);
2592                }
2593            }
2594        }
2595
2596        // this will ensure we don't have false positives when trying to diagnose reverts in fork
2597        // mode
2598        let diag = self.fork_revert_diagnostic.take();
2599
2600        // If the call already reverted, preserve that primary failure and skip post-call
2601        // expect* validation so it cannot overwrite the original revert.
2602        if outcome.stop.is_frame_revert() {
2603            // if there's a revert and a previous call was diagnosed as fork related revert then we
2604            // can return a better error here
2605            if let Some(err) = diag {
2606                outcome.output = Error::encode(err.to_error_msg(&self.core.labels));
2607            }
2608            return;
2609        }
2610
2611        if let Some(unmet) = expected_emit::check_call_emits(
2612            &mut self.expected_emits,
2613            curr_depth,
2614            call.is_static(),
2615            outcome.is_success(),
2616        ) {
2617            set_revert(outcome, unmet.encode(|| self.signatures_identifier()));
2618            return;
2619        }
2620
2621        // try to diagnose reverts in multi-fork mode where a call is made to an address that does
2622        // not exist
2623        if let Some(test_contract) = self.root_call_target {
2624            // if a call to a different contract than the original test contract returned with
2625            // `Stop` we check if the contract actually exists on the active fork
2626            if backend.backend().is_forked_mode()
2627                && outcome.stop == InstrStop::Stop
2628                && target != test_contract
2629            {
2630                self.fork_revert_diagnostic =
2631                    backend.backend().diagnose_revert(target, interp.host());
2632            }
2633        }
2634
2635        // The root call is terminating.
2636        if curr_depth == self.root_depth {
2637            // Match expected calls
2638            if let Some(msg) =
2639                expect::first_unmet_call(&self.core.expected_calls, outcome.is_success())
2640            {
2641                set_revert(outcome, Error::encode(msg));
2642                return;
2643            }
2644
2645            // Check if we have any leftover expected emits
2646            if let Some(msg) =
2647                expected_emit::first_unmet_root_emit(&mut self.expected_emits, outcome.is_success())
2648            {
2649                set_revert(outcome, Error::encode(msg));
2650                return;
2651            }
2652
2653            // Check for leftover expected creates
2654            if let Some(msg) = expect::first_unmet_create(&self.expected_creates) {
2655                set_revert(outcome, Error::encode(msg));
2656            }
2657        }
2658    }
2659
2660    /// Called before a create message executes.
2661    pub fn create_hook(
2662        &mut self,
2663        interp: &mut InterpreterFor<'_, '_, FEN>,
2664        input: &mut MessageFor<FEN>,
2665        backend: &mut dyn CheatcodesBackend<FEN>,
2666    ) -> Option<MessageResultFor<FEN>> {
2667        let tx_origin = interp.host().tx_env().origin;
2668        let curr_depth = usize::from(input.depth);
2669        let creator = self.take_create_creator(interp, input);
2670        let is_root = curr_depth == self.root_depth;
2671        self.start_created_accounts_frame(is_root, CreatedAccountsFrameKind::Create, curr_depth);
2672        if is_root {
2673            self.root_call_target = None;
2674            self.applied_access_list = None;
2675        }
2676
2677        // Check if we should intercept this create
2678        if self.core.intercept_next_create_call {
2679            // Reset the flag
2680            self.core.intercept_next_create_call = false;
2681
2682            self.unrun_create_depth = Some(curr_depth);
2683            // Return a revert with the initcode as error data
2684            return Some(message_result(
2685                input,
2686                InstrStop::Revert,
2687                input.input.to_bytes(interp.memory()),
2688            ));
2689        }
2690
2691        let mut caller_changed = false;
2692
2693        // Apply our prank
2694        if let Some(prank) = self.get_prank(curr_depth)
2695            && let Some(changes) = prank.changes_for(curr_depth, input.caller)
2696        {
2697            if let Some(new_caller) = changes.caller {
2698                // Ensure new caller is loaded, warm and touched.
2699                let _ = touch_account(interp.host().state_mut(), new_caller);
2700                input.caller = new_caller;
2701                caller_changed = true;
2702            }
2703            if let Some(new_origin) = changes.origin {
2704                self.set_origin(tx_origin, new_origin);
2705            }
2706            if let Some(used) = changes.used {
2707                self.pranks.insert(curr_depth, used);
2708            }
2709        }
2710
2711        self.apply_access_list(interp);
2712
2713        // Apply our broadcast
2714        if let Some(broadcast) = self.broadcast.clone()
2715            && curr_depth >= broadcast.depth
2716            && input.caller == broadcast.original_caller
2717        {
2718            // Reading the nonce warms the broadcaster.
2719            let nonce = match interp.host().state_mut().account(&broadcast.new_origin) {
2720                Ok(mut account) => {
2721                    account.warm();
2722                    account.nonce()
2723                }
2724                Err(err) => {
2725                    return Some(message_result(input, InstrStop::Revert, Error::encode(err)));
2726                }
2727            };
2728
2729            self.set_origin(tx_origin, broadcast.new_origin);
2730
2731            if curr_depth == broadcast.depth || broadcast.deploy_from_code {
2732                // Reset deploy from code flag for upcoming calls;
2733                if let Some(broadcast) = &mut self.broadcast {
2734                    broadcast.deploy_from_code = false;
2735                }
2736
2737                input.caller = broadcast.new_origin;
2738                caller_changed = true;
2739
2740                let rpc = backend.backend().active_fork_url();
2741                let mut tx_req = TransactionRequestFor::<FEN>::default()
2742                    .with_from(broadcast.new_origin)
2743                    .with_kind(TxKind::Create)
2744                    .with_value(input.value)
2745                    .with_input(input.input.to_bytes(interp.memory()))
2746                    .with_nonce(nonce);
2747                if let Some(fee_token) = self.fee_token {
2748                    tx_req.set_fee_token(fee_token);
2749                }
2750                self.broadcastable_transactions.push_back(BroadcastableTransaction {
2751                    rpc,
2752                    transaction: TransactionMaybeSigned::new(tx_req),
2753                    contract_address: None,
2754                });
2755
2756                let kind = if input.kind == MessageKind::Create2 { "create2" } else { "create" };
2757                debug!(target: "cheatcodes", tx=?self.broadcastable_transactions.back().unwrap(), "broadcastable {kind}");
2758            }
2759        }
2760
2761        // The creator changed, so the created address derives from the new creator.
2762        if caller_changed && curr_depth > self.root_depth {
2763            let nonce = match interp.host().state_mut().account(&input.caller) {
2764                Ok(account) => account.nonce(),
2765                Err(err) => {
2766                    return Some(message_result(input, InstrStop::Revert, Error::encode(err)));
2767                }
2768            };
2769            input.destination = derive_create_destination(
2770                input.kind,
2771                &input.caller,
2772                &input.salt,
2773                input.input.as_bytes(interp.memory()),
2774                nonce,
2775            );
2776            input.call_target = input.destination;
2777        }
2778
2779        input.code_address = input.destination;
2780
2781        // Allow cheatcodes from the address of the new contract.
2782        let address = input.destination;
2783        self.allow_cheatcodes_on_create(backend, curr_depth, input.caller, address, creator);
2784
2785        self.record_created_account(backend.backend().active_fork_id(), address);
2786
2787        // If `recordAccountAccesses` has been called, record the create
2788        if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
2789            // Read without loading, warming or caching the account, so recording has no side
2790            // effects.
2791            let state = interp.host().state_mut();
2792            let info = if state.loaded_accounts().any(|(loaded, _)| *loaded == address) {
2793                state.account_info_untracked(&address)
2794            } else {
2795                let db = state.overlay_db_mut();
2796                match db.cache.accounts.get(&address) {
2797                    Some(info) => Ok(info.clone()),
2798                    None => db.db.get_account(&address),
2799                }
2800            };
2801            let old_balance = info.ok().flatten().map_or(U256::ZERO, |info| info.balance);
2802            recorded_account_diffs_stack.push(vec![AccountAccess {
2803                chainInfo: crate::Vm::ChainInfo {
2804                    forkId: backend.backend().active_fork_id().unwrap_or_default(),
2805                    chainId: self
2806                        .env_overrides
2807                        .get(backend.backend().active_fork_id())
2808                        .and_then(|overrides| overrides.chain_id)
2809                        .map(U256::from)
2810                        .unwrap_or(interp.host().tx_env().chain_id),
2811                },
2812                accessor: input.caller,
2813                account: address,
2814                kind: crate::Vm::AccountAccessKind::Create,
2815                initialized: true,
2816                oldBalance: old_balance,
2817                newBalance: old_balance, // updated on create_end
2818                oldNonce: 0,             // new contract starts with nonce 0
2819                newNonce: 1,             // updated on create_end (contracts start with nonce 1)
2820                value: input.value,
2821                data: input.input.to_bytes(interp.memory()),
2822                reverted: false,
2823                deployedCode: Bytes::new(), // updated on create_end
2824                storageAccesses: vec![],    // updated on create_end
2825                depth: curr_depth as u64,
2826            }]);
2827        }
2828
2829        None
2830    }
2831
2832    /// Called after a create message executes.
2833    pub fn create_end_hook(
2834        &mut self,
2835        interp: &mut InterpreterFor<'_, '_, FEN>,
2836        call: &MessageFor<FEN>,
2837        outcome: &mut MessageResultFor<FEN>,
2838        _backend: &mut dyn CheatcodesBackend<FEN>,
2839    ) {
2840        let curr_depth = usize::from(call.depth);
2841        let frame_ran = self.unrun_create_depth.take() != Some(curr_depth);
2842        self.replay_persistent_writes(interp, curr_depth, outcome.is_success());
2843        // Depth at which the caller resumes and applies the region snapshot correction.
2844        let isolated_snapshot_gas_used = self.gas_metering.take_isolated_snapshot_gas_used(
2845            self.deploy_code_caller_depth(curr_depth),
2846            &outcome.gas,
2847        );
2848        let tx_origin = interp.host().tx_env().origin;
2849
2850        self.finish_created_accounts_frame(
2851            outcome.is_success(),
2852            CreatedAccountsFrameKind::Create,
2853            curr_depth,
2854        );
2855
2856        // Clean up pranks
2857        if let Some(prank) = self.get_prank(curr_depth).copied()
2858            && curr_depth == prank.depth
2859        {
2860            self.set_origin(tx_origin, prank.prank_origin);
2861
2862            // Clean single-call prank once we have returned to the original depth
2863            if prank.single_call {
2864                self.pranks.remove(&curr_depth);
2865            }
2866        }
2867
2868        // Clean up broadcasts
2869        if let Some(broadcast) = self.broadcast.clone()
2870            && curr_depth == broadcast.depth
2871        {
2872            self.set_origin(tx_origin, broadcast.original_origin);
2873
2874            // Clean single-call broadcast once we have returned to the original depth
2875            if broadcast.single_call {
2876                std::mem::take(&mut self.broadcast);
2877            }
2878        }
2879
2880        // Handle expected reverts.
2881        if let Some(expected_revert) = &mut self.expected_revert {
2882            // Record the would-be deployed address as the reverter, picking the innermost
2883            // reverting CREATE: this hook runs at every depth, the deepest frame fires
2884            // first, and the `is_none()` lock pins it. For `count > 1` the lock is
2885            // released after each successful iteration (see below) so each iteration
2886            // independently records its own innermost CREATE.
2887            //
2888            // This intentionally differs from `call_end` for `count > 1`, where
2889            // legacy nested CALL handling reports the outermost call per iteration.
2890            //
2891            // Only creates whose frame ran and reverted count. A create rejected before its
2892            // frame starts (depth, balance, nonce, or a revert from `vm.interceptInitcode` or a
2893            // missing or invalid CREATE2 deployer) leaves the reverter to the surrounding
2894            // `call_end`, which records the caller.
2895            if outcome.stop.is_revert()
2896                && frame_ran
2897                && expected_revert.reverter.is_some()
2898                && expected_revert.reverted_by.is_none()
2899            {
2900                expected_revert.reverted_by =
2901                    Some(outcome.created_address.unwrap_or(call.destination));
2902            }
2903
2904            if curr_depth <= expected_revert.depth
2905                && matches!(expected_revert.kind, ExpectedRevertKind::Default)
2906            {
2907                let mut expected_revert = std::mem::take(&mut self.expected_revert).unwrap();
2908                return match revert_handlers::handle_expect_revert(
2909                    false,
2910                    true,
2911                    self.core.config.internal_expect_revert,
2912                    &expected_revert,
2913                    outcome.stop,
2914                    outcome.output.clone(),
2915                    &self.core.config.available_artifacts,
2916                ) {
2917                    Ok((address, retdata)) => {
2918                        expected_revert.actual_count += 1;
2919                        if expected_revert.actual_count < expected_revert.count {
2920                            // Reset so the next iteration's innermost CREATE wins again.
2921                            expected_revert.reverted_by = None;
2922                            self.expected_revert = Some(expected_revert.clone());
2923                        }
2924
2925                        set_return(outcome, retdata);
2926                        outcome.created_address = address;
2927                        self.gas_metering.last_frame_gas = None;
2928                    }
2929                    Err(err) => {
2930                        set_revert(outcome, err.abi_encode().into());
2931                    }
2932                };
2933            }
2934        }
2935
2936        if curr_depth > self.root_depth {
2937            // Record the gas usage of the create frame, this allows the `lastFrameGas` cheatcode to
2938            // retrieve the gas usage of the last call or create.
2939            self.gas_metering.last_frame_gas = Some(frame_gas(outcome.stop, &outcome.gas));
2940            self.gas_metering.last_frame_snapshot_gas_used =
2941                isolated_snapshot_gas_used.unwrap_or_else(|| outcome.gas.spent());
2942        }
2943
2944        // If `startStateDiffRecording` has been called, update the `reverted` status of the
2945        // previous call depth's recorded accesses, if any.
2946        if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack
2947            && let Some(mut last_depth) = recorded_account_diffs_stack.pop()
2948        {
2949            // Update the reverted status of all deeper calls if this call reverted, in
2950            // accordance with EVM behavior.
2951            if outcome.stop.is_frame_revert() {
2952                mark_account_accesses_reverted(&mut last_depth);
2953            }
2954
2955            if let Some(create_access) = last_depth.first_mut() {
2956                // Update post-create state only if recording began before this frame.
2957                if create_access.depth == curr_depth as u64 {
2958                    debug_assert_eq!(
2959                        create_access.kind as u8,
2960                        crate::Vm::AccountAccessKind::Create as u8
2961                    );
2962                    // `created_address` is set only on success. A create that failed inside its
2963                    // frame reads the would-be address instead; one rejected before its frame
2964                    // ran keeps the placeholder values.
2965                    let frame_ran = frame_ran
2966                        && !matches!(
2967                            outcome.stop,
2968                            InstrStop::CallTooDeep
2969                                | InstrStop::OutOfFunds
2970                                | InstrStop::NonceOverflow
2971                                | InstrStop::CreateCollision
2972                        );
2973                    if let Some(address) =
2974                        outcome.created_address.or(frame_ran.then_some(call.destination))
2975                        && let Ok(mut account) = interp.host().state_mut().account(&address)
2976                    {
2977                        create_access.newBalance = account.balance();
2978                        create_access.newNonce = account.nonce();
2979                        create_access.deployedCode = account
2980                            .load_code()
2981                            .map(|code| code.original_bytes())
2982                            .unwrap_or_default();
2983                    }
2984                }
2985            }
2986            merge_recorded_frame(recorded_account_diffs_stack, last_depth);
2987        }
2988
2989        // Match successful creates against expected_creates; a failed create deploys nothing.
2990        if !self.expected_creates.is_empty()
2991            && outcome.is_success()
2992            && let Some(address) = outcome.created_address
2993            && let Ok(mut account) = interp.host().state_mut().account(&address)
2994        {
2995            let bytecode =
2996                account.load_code().map(|code| code.original_bytes()).unwrap_or_default();
2997            expect::observe_create(
2998                &mut self.expected_creates,
2999                call.caller,
3000                || call.kind.into(),
3001                &bytecode,
3002            );
3003        }
3004    }
3005
3006    /// Determines whether the `DEFAULT_CREATE2_DEPLOYER` should be used for a CREATE message at
3007    /// `depth`.
3008    pub fn should_use_create2_factory(&mut self, depth: usize, message: &MessageFor<FEN>) -> bool {
3009        // Match the synthetic `deployCode` create at the depth of the cheatcode call, as for
3010        // native creates.
3011        let depth = self.deploy_code_caller_depth(depth);
3012        let target_depth = if let Some(prank) = &self.get_prank(depth) {
3013            prank.depth
3014        } else if let Some(broadcast) = &self.broadcast {
3015            broadcast.depth
3016        } else {
3017            1
3018        };
3019
3020        if depth != target_depth {
3021            return false;
3022        }
3023
3024        match message.kind {
3025            MessageKind::Create2 => {
3026                self.broadcast.is_some() || self.core.config.always_use_create_2_factory
3027            }
3028            MessageKind::Create => {
3029                self.core.config.batch_rewrite_creates && self.broadcast.is_some()
3030            }
3031            _ => false,
3032        }
3033    }
3034
3035    /// Returns the CREATE2 deployer address.
3036    pub fn create2_deployer(&self) -> Address {
3037        self.core.config.evm_opts.create2_deployer
3038    }
3039
3040    /// Preserves the original CREATE authorization before redirecting it to the factory.
3041    pub fn start_create2_redirect(
3042        &mut self,
3043        interp: &InterpreterFor<'_, '_, FEN>,
3044        message: &MessageFor<FEN>,
3045    ) {
3046        let creator = self.take_create_creator(interp, message);
3047        self.pending_create2_redirects.push((message.depth, creator, false));
3048    }
3049
3050    fn take_create_creator(
3051        &mut self,
3052        interp: &InterpreterFor<'_, '_, FEN>,
3053        input: &MessageFor<FEN>,
3054    ) -> Option<Address> {
3055        self.env_handoff_creator.take().or_else(|| {
3056            let message = interp.message();
3057            (message.depth < input.depth).then_some(message.code_address)
3058        })
3059    }
3060
3061    fn can_grant_cheatcodes_on_create(
3062        backend: &dyn CheatcodesBackend<FEN>,
3063        depth: usize,
3064        caller: Address,
3065        creator: Option<Address>,
3066    ) -> bool {
3067        let db = backend.backend();
3068        (depth <= 1 || db.has_cheatcode_access(&caller))
3069            && (!db.is_forked_mode() || creator.is_none_or(|code| db.has_cheatcode_access(&code)))
3070    }
3071
3072    #[cold]
3073    fn meter_gas(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
3074        if let Some(paused_gas) = self.gas_metering.paused_frames.last() {
3075            // Keep gas constant if paused.
3076            // Make sure we record the memory changes so that memory expansion is not paused.
3077            let memory = *interp.gas().memory();
3078            let mut gas = *paused_gas;
3079            gas.memory_mut().words_num = memory.words_num;
3080            gas.memory_mut().expansion_cost = memory.expansion_cost;
3081            interp.set_gas(gas);
3082        } else {
3083            // Record frame paused gas.
3084            self.gas_metering.paused_frames.push(interp.gas());
3085        }
3086    }
3087
3088    #[cold]
3089    fn meter_gas_record(&mut self, interp: &InterpreterFor<'_, '_, FEN>, curr_depth: usize) {
3090        if interp.result().is_ok() {
3091            let isolated_region_gas = match self.gas_metering.pending_isolated_region_gas {
3092                Some((depth, charged, used)) if depth == curr_depth => {
3093                    self.gas_metering.pending_isolated_region_gas = None;
3094                    Some((charged, used))
3095                }
3096                _ => None,
3097            };
3098            let spent = interp.gas().tracker().spent();
3099            self.gas_metering.gas_records.iter_mut().for_each(|record| {
3100                if curr_depth == record.depth {
3101                    // Skip the first opcode of the first call frame as it includes the gas cost of
3102                    // creating the snapshot.
3103                    if self.gas_metering.last_gas_used != 0 {
3104                        let mut gas_diff = spent.saturating_sub(self.gas_metering.last_gas_used);
3105                        if let Some((charged, used)) = isolated_region_gas {
3106                            gas_diff = gas_diff.saturating_sub(charged).saturating_add(used);
3107                        }
3108                        record.gas_used = record.gas_used.saturating_add(gas_diff);
3109                    }
3110
3111                    // Update `last_gas_used` to the current spent gas for the next iteration to
3112                    // compare against.
3113                    self.gas_metering.last_gas_used = spent;
3114                }
3115            });
3116        }
3117    }
3118
3119    #[cold]
3120    fn meter_gas_end(&mut self, interp: &InterpreterFor<'_, '_, FEN>) {
3121        // Remove recorded gas if we exit frame.
3122        if interp.result().is_err() {
3123            self.gas_metering.paused_frames.pop();
3124        }
3125    }
3126
3127    #[cold]
3128    const fn meter_gas_reset(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
3129        let current = interp.gas();
3130        let mut gas =
3131            Gas::new_with_execution_gas_and_reservoir(current.limit(), current.reservoir());
3132        gas.memory_mut().words_num = current.memory().words_num;
3133        gas.memory_mut().expansion_cost = current.memory().expansion_cost;
3134        interp.set_gas(gas);
3135        self.gas_metering.reset = false;
3136    }
3137
3138    #[cold]
3139    fn meter_gas_check(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
3140        // The caller discards the gas and refund of a halting frame, so whichever other hook steps
3141        // the halting instruction, its gas stays as the protocol leaves it.
3142        if interp.result().is_err_and(|stop| !stop.is_halt()) {
3143            // Reset gas if spent is less than refunded.
3144            // This can happen if gas was paused / resumed or reset.
3145            // https://github.com/foundry-rs/foundry/issues/4370
3146            let gas = interp.gas();
3147            if gas.spent() < u64::try_from(gas.refunded()).unwrap_or_default() {
3148                interp.set_gas(Gas::new_with_execution_gas_and_reservoir(
3149                    gas.limit(),
3150                    gas.reservoir(),
3151                ));
3152            }
3153        }
3154    }
3155
3156    /// Applies opcode-level overrides for `BASEFEE`, `GASPRICE`, `BLOBHASH` and `CHAINID`.
3157    ///
3158    /// Called from `step_end` *after* the opcode has executed and only when the
3159    /// opcode succeeded. The opcode pushed its result onto the stack; we replace the top
3160    /// of stack with the cheatcode-set override. evm2 borrows the transaction environment for
3161    /// the whole transaction, so `vm.txGasPrice`, `vm.blobhashes` and `vm.chainId` become visible
3162    /// to the running transaction this way; inside isolated calls `vm.fee` is applied this way
3163    /// as well, since their nested transactions zero the real fee fields.
3164    ///
3165    /// We can't read the just-executed opcode from the interpreter here because the PC has already
3166    /// advanced; instead `step` stashes it in `env_overrides.pending_opcode` for us.
3167    #[cold]
3168    fn apply_env_overrides(
3169        &mut self,
3170        interp: &mut InterpreterFor<'_, '_, FEN>,
3171        fork_id: Option<U256>,
3172    ) {
3173        let Some(env_overrides) = self.env_overrides.get_mut(fork_id) else { return };
3174        let Some(opcode) = env_overrides.pending_opcode.take() else { return };
3175        // Each overridden opcode pushed one value; replace it with the override.
3176        let value = match opcode {
3177            op::BASEFEE => env_overrides.basefee_override().map(U256::from),
3178            op::GASPRICE => env_overrides.gas_price_override().map(U256::from),
3179            op::CHAINID => env_overrides.chain_id.map(U256::from),
3180            // BLOBHASH popped the index captured in `step` and pushed the hash.
3181            op::BLOBHASH => env_overrides
3182                .pending_blobhash_index
3183                .take()
3184                .and_then(|index| env_overrides.blob_hash_override(index))
3185                .map(Into::into),
3186            _ => None,
3187        };
3188        if let Some(value) = value {
3189            Self::replace_top_of_stack(interp, value);
3190        }
3191    }
3192
3193    /// Replaces the top of the interpreter stack with `value`.
3194    ///
3195    /// The caller must only invoke this after a successful opcode that pushed
3196    /// a value onto the stack; the `pop()` is therefore expected to succeed.
3197    /// If it does not (e.g. because of a bug in the caller's success gating)
3198    /// we bail out instead of pushing on top of an unexpected stack, which
3199    /// would silently grow the stack and corrupt the frame.
3200    fn replace_top_of_stack(interp: &mut InterpreterFor<'_, '_, FEN>, value: U256) {
3201        let mut stack = interp.stack_mut();
3202        if stack.pop().is_err() {
3203            debug_assert!(false, "env override expected opcode result on stack");
3204            return;
3205        }
3206        let _ = stack.push(value);
3207    }
3208
3209    /// Generates or copies arbitrary values for storage slots.
3210    /// Invoked in inspector `step_end` (when the current opcode is not executed), if current opcode
3211    /// to execute is `SLOAD` and storage slot is cold.
3212    /// Ensures that in next step (when `SLOAD` opcode is executed) an arbitrary value is returned:
3213    /// - copies the existing arbitrary storage value (or the new generated one if no value in
3214    ///   cache) from mapped source address to the target address.
3215    /// - generates arbitrary value and saves it in target address storage.
3216    #[cold]
3217    fn arbitrary_storage_end(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
3218        if interp.result().is_err() || interp.opcode() != op::SLOAD {
3219            return;
3220        }
3221        let key = try_or_return!(interp.stack().peek(0));
3222        let target_address = interp.message().destination;
3223
3224        if self.is_arbitrary_storage_slot_explicit(target_address, key) {
3225            return;
3226        }
3227
3228        let state = interp.host().state_mut();
3229        let Ok(slot) = state.storage_slot(&target_address, key) else { return };
3230        let (is_cold, value) = (!slot.is_warm(), slot.current());
3231
3232        if (is_cold && value.is_zero())
3233            || self.should_overwrite_arbitrary_storage(&target_address, key)
3234        {
3235            let result = if self.has_arbitrary_storage(&target_address) {
3236                let arbitrary_value = self
3237                    .cached_arbitrary_storage_value(target_address, key)
3238                    .unwrap_or_else(|| self.draw_arbitrary_storage_value(target_address, key));
3239                self.core.arbitrary_storage.as_mut().unwrap().save(
3240                    state,
3241                    target_address,
3242                    key,
3243                    arbitrary_value,
3244                )
3245            } else if self.is_arbitrary_storage_copy(&target_address) {
3246                let arbitrary_value = self.draw_arbitrary_storage_value(target_address, key);
3247                self.core
3248                    .arbitrary_storage
3249                    .as_mut()
3250                    .unwrap()
3251                    .copy(state, target_address, key, arbitrary_value)
3252                    .map(drop)
3253            } else {
3254                Ok(())
3255            };
3256            if let Err(err) = result {
3257                let _ = interp.fail(err);
3258            }
3259        }
3260    }
3261
3262    fn take_storage_hook_inspector_state(&mut self) -> StorageHookInspectorState {
3263        StorageHookInspectorState {
3264            accesses: std::mem::take(&mut self.accesses),
3265            recording_accesses: std::mem::replace(&mut self.recording_accesses, false),
3266            mapping_slots: self.core.mapping_slots.take(),
3267            recorded_logs: self.core.recorded_logs.take(),
3268            recorded_logs_generation: self.core.recorded_logs_generation,
3269            mocked_calls: std::mem::take(&mut self.core.mocked_calls),
3270            mocked_functions: std::mem::take(&mut self.core.mocked_functions),
3271            expected_revert: self.expected_revert.take(),
3272            assume_no_revert: self.assume_no_revert.take(),
3273            expected_calls: std::mem::take(&mut self.core.expected_calls),
3274            expected_emits: std::mem::take(&mut self.expected_emits),
3275            expected_creates: std::mem::take(&mut self.expected_creates),
3276        }
3277    }
3278
3279    fn restore_storage_hook_inspector_state(&mut self, state: StorageHookInspectorState) {
3280        self.accesses = state.accesses;
3281        self.recording_accesses = state.recording_accesses;
3282        self.core.mapping_slots = state.mapping_slots;
3283        self.core.recorded_logs = state.recorded_logs;
3284        self.core.recorded_logs_generation = state.recorded_logs_generation;
3285        self.core.mocked_calls = state.mocked_calls;
3286        self.core.mocked_functions = state.mocked_functions;
3287        self.expected_revert = state.expected_revert;
3288        self.assume_no_revert = state.assume_no_revert;
3289        self.core.expected_calls = state.expected_calls;
3290        self.expected_emits = state.expected_emits;
3291        self.expected_creates = state.expected_creates;
3292    }
3293
3294    fn capture_storage_hook(&mut self, interp: &mut InterpreterFor<'_, '_, FEN>) {
3295        self.pending_storage_hook = None;
3296        if self.active_storage_hook.is_some() {
3297            return;
3298        }
3299        let account = interp.message().destination;
3300        match interp.opcode() {
3301            op::SLOAD => {
3302                let slot = try_or_return!(interp.stack().peek(0));
3303                let Some(hook) = self.storage_load_hooks.get(&account).copied() else { return };
3304                self.pending_storage_hook = Some(PendingStorageHook::Load { account, slot, hook });
3305            }
3306            op::SSTORE => {
3307                let slot = try_or_return!(interp.stack().peek(0));
3308                let (hook, mapping) = if let Some(hook) = self.storage_store_hooks.get(&account) {
3309                    (*hook, None)
3310                } else {
3311                    let Some(provenance) = self
3312                        .storage_hook_mapping_slots
3313                        .get(&account)
3314                        .and_then(|slots| slots.resolve(slot.into()))
3315                    else {
3316                        return;
3317                    };
3318                    let Some(hook) = self
3319                        .mapping_storage_store_hooks
3320                        .get(&account)
3321                        .and_then(|hooks| hooks.get(&provenance.root_slot))
3322                        .copied()
3323                    else {
3324                        return;
3325                    };
3326                    (hook, Some((provenance.root_slot, provenance.keys)))
3327                };
3328                let old_value =
3329                    match interp.host().state_mut().storage_slot_untracked(&account, &slot) {
3330                        Ok(value) => value,
3331                        Err(err) => {
3332                            let _ = interp.fail(err);
3333                            return;
3334                        }
3335                    };
3336                self.pending_storage_hook =
3337                    Some(PendingStorageHook::Store { account, slot, old_value, mapping, hook });
3338            }
3339            _ => {}
3340        }
3341    }
3342
3343    /// Calls the storage hook captured for the instruction that just executed, as a nested frame
3344    /// whose gas, return data and access warmth do not affect the hooked frame.
3345    fn invoke_pending_storage_hook(
3346        &mut self,
3347        interp: &mut InterpreterFor<'_, '_, FEN>,
3348        backend: &mut dyn CheatcodesBackend<FEN>,
3349        executor: &mut dyn CheatcodesExecutor<FEN>,
3350    ) {
3351        let Some(pending) = self.pending_storage_hook.take() else { return };
3352        if interp.result().is_err() {
3353            return;
3354        }
3355
3356        let (hook, input) = match pending {
3357            PendingStorageHook::Load { account, slot, hook } => {
3358                let value = try_or_return!(interp.stack().peek(0));
3359                let mut input = Vec::with_capacity(4 + 32 * 3);
3360                input.extend_from_slice(&hook.callback_selector);
3361                input.extend_from_slice(account.into_word().as_slice());
3362                input.extend_from_slice(&slot.to_be_bytes::<32>());
3363                input.extend_from_slice(&value.to_be_bytes::<32>());
3364                (hook, Bytes::from(input))
3365            }
3366            PendingStorageHook::Store { account, slot, old_value, mapping, hook } => {
3367                let new_value =
3368                    interp.host().state().get_storage(&account, &slot).unwrap_or_default();
3369                let mut input = Vec::with_capacity(4 + 32 * 4);
3370                input.extend_from_slice(&hook.callback_selector);
3371                input.extend_from_slice(account.into_word().as_slice());
3372                input.extend_from_slice(&slot.to_be_bytes::<32>());
3373                if let Some((root, keys)) = mapping {
3374                    input.extend_from_slice(root.as_slice());
3375                    input.extend_from_slice(&U256::from(32 * 6).to_be_bytes::<32>());
3376                    input.extend_from_slice(&old_value.to_be_bytes::<32>());
3377                    input.extend_from_slice(&new_value.to_be_bytes::<32>());
3378                    input.extend_from_slice(&U256::from(keys.len()).to_be_bytes::<32>());
3379                    for key in keys {
3380                        input.extend_from_slice(key.as_slice());
3381                    }
3382                } else {
3383                    input.extend_from_slice(&old_value.to_be_bytes::<32>());
3384                    input.extend_from_slice(&new_value.to_be_bytes::<32>());
3385                }
3386                (hook, Bytes::from(input))
3387            }
3388        };
3389
3390        let depth = interp.message().depth.saturating_add(1);
3391        let gas_limit = interp.gas().remaining();
3392        let evm = interp.host();
3393        let checkpoint = evm.state().checkpoint();
3394        let code = match evm
3395            .state_mut()
3396            .account(&hook.callback_target)
3397            .and_then(|mut account| account.load_code())
3398        {
3399            Ok(code) => code,
3400            Err(err) => {
3401                revert_frame(interp, &Error::encode(err));
3402                return;
3403            }
3404        };
3405        let mut message = MessageFor::<FEN> {
3406            kind: MessageKind::Call,
3407            depth,
3408            gas_limit,
3409            destination: hook.callback_target,
3410            call_target: hook.callback_target,
3411            caller: CHEATCODE_ADDRESS,
3412            input: input.clone().into(),
3413            code,
3414            code_address: hook.callback_target,
3415            ..Default::default()
3416        };
3417
3418        let inspector_state = self.take_storage_hook_inspector_state();
3419        self.active_storage_hook = Some(ActiveStorageHook {
3420            depth,
3421            callback_target: hook.callback_target,
3422            callback_input: input,
3423        });
3424        let result = executor.exec_message(self, backend, evm, &mut message);
3425        self.active_storage_hook = None;
3426        self.restore_storage_hook_inspector_state(inspector_state);
3427        // The callback is instrumentation: accesses it warmed stay cold for the hooked frame.
3428        restore_access_warmth(evm.state_mut(), &checkpoint);
3429
3430        match result {
3431            Ok(result) if result.is_success() => {}
3432            Ok(result) => revert_frame(interp, &result.output),
3433            Err(err) => {
3434                let _ = interp.fail(err);
3435            }
3436        }
3437    }
3438
3439    /// Records storage slots reads and writes.
3440    #[cold]
3441    fn record_accesses(&mut self, interp: &InterpreterFor<'_, '_, FEN>) {
3442        let access = &mut self.accesses;
3443        match interp.opcode() {
3444            op::SLOAD => {
3445                let key = try_or_return!(interp.stack().peek(0));
3446                access.record_read(interp.message().destination, key);
3447            }
3448            op::SSTORE => {
3449                let key = try_or_return!(interp.stack().peek(0));
3450                access.record_write(interp.message().destination, key);
3451            }
3452            _ => {}
3453        }
3454    }
3455
3456    #[cold]
3457    fn record_state_diffs(
3458        &mut self,
3459        interp: &mut InterpreterFor<'_, '_, FEN>,
3460        backend: &mut dyn CheatcodesBackend<FEN>,
3461        curr_depth: usize,
3462    ) {
3463        let opcode = interp.opcode();
3464        // Act only on stepped instructions, so that an arm missing from the set fails its test
3465        // instead of only working while another cheatcode steps every instruction.
3466        if !STATE_DIFF_OPCODES.contains(opcode) {
3467            return;
3468        }
3469        let Some(account_accesses) = &mut self.recorded_account_diffs_stack else { return };
3470        let accessor = interp.message().destination;
3471        let fork_id = backend.backend().active_fork_id();
3472        let chain_id = self
3473            .env_overrides
3474            .get(fork_id)
3475            .and_then(|overrides| overrides.chain_id)
3476            .map(U256::from)
3477            .unwrap_or(interp.host().tx_env().chain_id);
3478        let fork_id = fork_id.unwrap_or_default();
3479        let depth = curr_depth as u64;
3480        match opcode {
3481            op::SELFDESTRUCT => {
3482                // Ensure that we're not selfdestructing a context recording was initiated on
3483                let Some(last) = account_accesses.last_mut() else { return };
3484
3485                // get previous balance, nonce and initialized status of the target account
3486                let target = try_or_return!(interp.stack().peek(0));
3487                let target = Address::from_word(B256::from(target));
3488                let state = interp.host().state_mut();
3489                let (initialized, old_balance, old_nonce) = state
3490                    .account(&target)
3491                    .map(|mut account| {
3492                        account.warm();
3493                        (
3494                            account.get().is_some_and(|info| !info.is_empty()),
3495                            account.balance(),
3496                            account.nonce(),
3497                        )
3498                    })
3499                    .unwrap_or_default();
3500
3501                // load balance of this account
3502                let value = state
3503                    .account_info_untracked(&accessor)
3504                    .ok()
3505                    .flatten()
3506                    .map_or(U256::ZERO, |info| info.balance);
3507
3508                // register access for the target account
3509                last.push(crate::Vm::AccountAccess {
3510                    chainInfo: crate::Vm::ChainInfo { forkId: fork_id, chainId: chain_id },
3511                    accessor,
3512                    account: target,
3513                    kind: crate::Vm::AccountAccessKind::SelfDestruct,
3514                    initialized,
3515                    oldBalance: old_balance,
3516                    newBalance: old_balance + value,
3517                    oldNonce: old_nonce,
3518                    newNonce: old_nonce, // nonce doesn't change on selfdestruct
3519                    value,
3520                    data: Bytes::new(),
3521                    reverted: false,
3522                    deployedCode: Bytes::new(),
3523                    storageAccesses: vec![],
3524                    depth,
3525                });
3526            }
3527
3528            op::SLOAD => {
3529                let Some(last) = account_accesses.last_mut() else { return };
3530
3531                let key = try_or_return!(interp.stack().peek(0));
3532
3533                // Try to include present value for informational purposes, otherwise assume
3534                // it's not set (zero value). The read does not warm the slot for the actual
3535                // SLOAD opcode.
3536                let present_value = interp
3537                    .host()
3538                    .state_mut()
3539                    .storage_slot_untracked(&accessor, &key)
3540                    .unwrap_or_default();
3541                let access = crate::Vm::StorageAccess {
3542                    account: accessor,
3543                    slot: key.into(),
3544                    isWrite: false,
3545                    previousValue: present_value.into(),
3546                    newValue: present_value.into(),
3547                    reverted: false,
3548                };
3549                append_storage_access(last, access, depth);
3550            }
3551            op::SSTORE => {
3552                let Some(last) = account_accesses.last_mut() else { return };
3553
3554                let key = try_or_return!(interp.stack().peek(0));
3555                let value = try_or_return!(interp.stack().peek(1));
3556                // Try to load the slot's previous value, otherwise, assume it's not set (zero
3557                // value). The read does not warm the slot for the actual SSTORE opcode.
3558                let previous_value = interp
3559                    .host()
3560                    .state_mut()
3561                    .storage_slot_untracked(&accessor, &key)
3562                    .unwrap_or_default();
3563
3564                let access = crate::Vm::StorageAccess {
3565                    account: accessor,
3566                    slot: key.into(),
3567                    isWrite: true,
3568                    previousValue: previous_value.into(),
3569                    newValue: value.into(),
3570                    reverted: false,
3571                };
3572                append_storage_access(last, access, depth);
3573            }
3574
3575            // Record account accesses via the EXT family of opcodes
3576            op::EXTCODECOPY | op::EXTCODESIZE | op::EXTCODEHASH | op::BALANCE => {
3577                let kind = match opcode {
3578                    op::EXTCODECOPY => crate::Vm::AccountAccessKind::Extcodecopy,
3579                    op::EXTCODESIZE => crate::Vm::AccountAccessKind::Extcodesize,
3580                    op::EXTCODEHASH => crate::Vm::AccountAccessKind::Extcodehash,
3581                    op::BALANCE => crate::Vm::AccountAccessKind::Balance,
3582                    _ => unreachable!(),
3583                };
3584                let address =
3585                    Address::from_word(B256::from(try_or_return!(interp.stack().peek(0))));
3586                let (initialized, balance, nonce) = interp
3587                    .host()
3588                    .state_mut()
3589                    .account_info_untracked(&address)
3590                    .ok()
3591                    .flatten()
3592                    .map(|info| (!info.is_empty(), info.balance, info.nonce))
3593                    .unwrap_or_default();
3594                let account_access = crate::Vm::AccountAccess {
3595                    chainInfo: crate::Vm::ChainInfo { forkId: fork_id, chainId: chain_id },
3596                    accessor,
3597                    account: address,
3598                    kind,
3599                    initialized,
3600                    oldBalance: balance,
3601                    newBalance: balance,
3602                    oldNonce: nonce,
3603                    newNonce: nonce, // EXT* operations don't change nonce
3604                    value: U256::ZERO,
3605                    data: Bytes::new(),
3606                    reverted: false,
3607                    deployedCode: Bytes::new(),
3608                    storageAccesses: vec![],
3609                    depth,
3610                };
3611                // Record the EXT* call as an account access at the current depth
3612                // (future storage accesses will be recorded in a new "Resume" context)
3613                if let Some(last) = account_accesses.last_mut() {
3614                    last.push(account_access);
3615                } else {
3616                    account_accesses.push(vec![account_access]);
3617                }
3618            }
3619            _ => {}
3620        }
3621    }
3622
3623    /// Checks to see if the current opcode can either mutate directly or expand memory.
3624    ///
3625    /// If the opcode at the current program counter is a match, check if the modified memory lies
3626    /// within the allowed ranges. If not, revert and fail the test.
3627    #[cold]
3628    fn check_mem_opcodes(&self, interpreter: &mut InterpreterFor<'_, '_, FEN>, depth: u64) {
3629        // See `record_state_diffs`.
3630        if !MEMORY_OPCODES.contains(interpreter.opcode()) {
3631            return;
3632        }
3633        let Some(ranges) = self.allowed_mem_writes.get(&depth) else {
3634            return;
3635        };
3636
3637        // The `mem_opcode_match` macro is used to match the current opcode against a list of
3638        // opcodes that can mutate memory (either directly or expansion via reading). If the
3639        // opcode is a match, the memory offsets that are being written to are checked to be
3640        // within the allowed ranges. If not, the test is failed and the transaction is
3641        // reverted. For all opcodes that can mutate memory aside from MSTORE,
3642        // MSTORE8, and MLOAD, the size and destination offset are on the stack, and
3643        // the macro expands all of these cases. For MSTORE, MSTORE8, and MLOAD, the
3644        // size of the memory write is implicit, so these cases are hard-coded.
3645        macro_rules! mem_opcode_match {
3646            ($(($opcode:ident, $offset_depth:expr, $size_depth:expr, $writes:expr)),* $(,)?) => {
3647                match interpreter.opcode() {
3648                    ////////////////////////////////////////////////////////////////
3649                    //    OPERATIONS THAT CAN EXPAND/MUTATE MEMORY BY WRITING     //
3650                    ////////////////////////////////////////////////////////////////
3651
3652                    op::MSTORE => {
3653                        // The offset of the mstore operation is at the top of the stack.
3654                        let offset = try_or_return!(interpreter.stack().peek(0)).saturating_to::<u64>();
3655
3656                        // If none of the allowed ranges contain [offset, offset + 32), memory has been
3657                        // unexpectedly mutated.
3658                        if !ranges.iter().any(|range| {
3659                            range.contains(&offset) && range.contains(&(offset + 31))
3660                        }) {
3661                            // SPECIAL CASE: When the compiler attempts to store the selector for
3662                            // `stopExpectSafeMemory`, this is allowed. It will do so at the current free memory
3663                            // pointer, which could have been updated to the exclusive upper bound during
3664                            // execution.
3665                            let value = try_or_return!(interpreter.stack().peek(1)).to_be_bytes::<32>();
3666                            if value[..SELECTOR_LEN] == stopExpectSafeMemoryCall::SELECTOR {
3667                                return
3668                            }
3669
3670                            disallowed_mem_write(offset, 32, interpreter, ranges);
3671                            return
3672                        }
3673                    }
3674                    op::MSTORE8 => {
3675                        // The offset of the mstore8 operation is at the top of the stack.
3676                        let offset = try_or_return!(interpreter.stack().peek(0)).saturating_to::<u64>();
3677
3678                        // If none of the allowed ranges contain the offset, memory has been
3679                        // unexpectedly mutated.
3680                        if !ranges.iter().any(|range| range.contains(&offset)) {
3681                            disallowed_mem_write(offset, 1, interpreter, ranges);
3682                            return
3683                        }
3684                    }
3685
3686                    ////////////////////////////////////////////////////////////////
3687                    //        OPERATIONS THAT CAN EXPAND MEMORY BY READING        //
3688                    ////////////////////////////////////////////////////////////////
3689
3690                    op::MLOAD => {
3691                        // The offset of the mload operation is at the top of the stack
3692                        let offset = try_or_return!(interpreter.stack().peek(0)).saturating_to::<u64>();
3693
3694                        // If the offset being loaded is >= than the memory size, the
3695                        // memory is being expanded. If none of the allowed ranges contain
3696                        // [offset, offset + 32), memory has been unexpectedly mutated.
3697                        if offset >= interpreter.memory().len() as u64 && !ranges.iter().any(|range| {
3698                            range.contains(&offset) && range.contains(&(offset + 31))
3699                        }) {
3700                            disallowed_mem_write(offset, 32, interpreter, ranges);
3701                            return
3702                        }
3703                    }
3704
3705                    ////////////////////////////////////////////////////////////////
3706                    //          OPERATIONS WITH OFFSET AND SIZE ON STACK          //
3707                    ////////////////////////////////////////////////////////////////
3708
3709                    op::CALL => {
3710                        // The destination offset of the operation is the fifth element on the stack.
3711                        let dest_offset = try_or_return!(interpreter.stack().peek(5)).saturating_to::<u64>();
3712
3713                        // The size of the data that will be copied is the sixth element on the stack.
3714                        let size = try_or_return!(interpreter.stack().peek(6)).saturating_to::<u64>();
3715
3716                        // If none of the allowed ranges contain [dest_offset, dest_offset + size),
3717                        // memory outside of the expected ranges has been touched. If the opcode
3718                        // only reads from memory, this is okay as long as the memory is not expanded.
3719                        let fail_cond = !ranges.iter().any(|range| {
3720                            range.contains(&dest_offset) &&
3721                                range.contains(&(dest_offset + size.saturating_sub(1)))
3722                        });
3723
3724                        // If the failure condition is met, set the output buffer to a revert string
3725                        // that gives information about the allowed ranges and revert.
3726                        if fail_cond {
3727                            // SPECIAL CASE: When a call to `stopExpectSafeMemory` is performed, this is allowed.
3728                            // It allocated calldata at the current free memory pointer, and will attempt to read
3729                            // from this memory region to perform the call.
3730                            let to = Address::from_word(try_or_return!(interpreter.stack().peek(1)).to_be_bytes::<32>().into());
3731                            if to == CHEATCODE_ADDRESS {
3732                                let args_offset = try_or_return!(interpreter.stack().peek(3)).saturating_to::<usize>();
3733                                let args_size = try_or_return!(interpreter.stack().peek(4)).saturating_to::<usize>();
3734                                // CALL has not expanded input memory yet.
3735                                if args_size >= SELECTOR_LEN
3736                                    && args_offset.saturating_add(args_size) <= interpreter.memory().len()
3737                                {
3738                                    let memory_word = interpreter.memory().slice(args_offset, args_size);
3739                                    if memory_word[..SELECTOR_LEN] == stopExpectSafeMemoryCall::SELECTOR {
3740                                        return
3741                                    }
3742                                }
3743                            }
3744
3745                            disallowed_mem_write(dest_offset, size, interpreter, ranges);
3746                            return
3747                        }
3748                    }
3749
3750                    $(op::$opcode => {
3751                        // The destination offset of the operation.
3752                        let dest_offset = try_or_return!(interpreter.stack().peek($offset_depth)).saturating_to::<u64>();
3753
3754                        // The size of the data that will be copied.
3755                        let size = try_or_return!(interpreter.stack().peek($size_depth)).saturating_to::<u64>();
3756
3757                        // If none of the allowed ranges contain [dest_offset, dest_offset + size),
3758                        // memory outside of the expected ranges has been touched. If the opcode
3759                        // only reads from memory, this is okay as long as the memory is not expanded.
3760                        let fail_cond = !ranges.iter().any(|range| {
3761                                range.contains(&dest_offset) &&
3762                                    range.contains(&(dest_offset + size.saturating_sub(1)))
3763                            }) && ($writes ||
3764                                [dest_offset, (dest_offset + size).saturating_sub(1)].into_iter().any(|offset| {
3765                                    offset >= interpreter.memory().len() as u64
3766                                })
3767                            );
3768
3769                        // If the failure condition is met, set the output buffer to a revert string
3770                        // that gives information about the allowed ranges and revert.
3771                        if fail_cond {
3772                            disallowed_mem_write(dest_offset, size, interpreter, ranges);
3773                            return
3774                        }
3775                    })*
3776
3777                    _ => {}
3778                }
3779            }
3780        }
3781
3782        // Check if the current opcode can write to memory, and if so, check if the memory
3783        // being written to is registered as safe to modify.
3784        mem_opcode_match!(
3785            (CALLDATACOPY, 0, 2, true),
3786            (CODECOPY, 0, 2, true),
3787            (RETURNDATACOPY, 0, 2, true),
3788            (EXTCODECOPY, 1, 3, true),
3789            (CALLCODE, 5, 6, true),
3790            (STATICCALL, 4, 5, true),
3791            (DELEGATECALL, 4, 5, true),
3792            (KECCAK256, 0, 1, false),
3793            (LOG0, 0, 1, false),
3794            (LOG1, 0, 1, false),
3795            (LOG2, 0, 1, false),
3796            (LOG3, 0, 1, false),
3797            (LOG4, 0, 1, false),
3798            (CREATE, 1, 2, false),
3799            (CREATE2, 1, 2, false),
3800            (RETURN, 0, 1, false),
3801            (REVERT, 0, 1, false),
3802        );
3803    }
3804
3805    #[cold]
3806    fn set_gas_limit_type(&mut self, interpreter: &InterpreterFor<'_, '_, FEN>) {
3807        match interpreter.opcode() {
3808            // Both creation opcodes forward remaining gas, even when rewritten to factory calls.
3809            op::CREATE | op::CREATE2 => self.dynamic_gas_limit = true,
3810            op::CALL => {
3811                // If first element of the stack is close to current remaining gas then assume
3812                // dynamic gas limit.
3813                self.dynamic_gas_limit = try_or_return!(interpreter.stack().peek(0))
3814                    >= U256::from(interpreter.gas().remaining().saturating_sub(100))
3815            }
3816            _ => self.dynamic_gas_limit = false,
3817        }
3818    }
3819}
3820
3821/// Helper that expands memory, stores a revert string pertaining to a disallowed memory write,
3822/// and sets the return range to the revert string's location in memory.
3823///
3824/// This will set the interpreter's next action to a return with the revert string as the output.
3825/// And trigger a revert.
3826fn disallowed_mem_write<T: EvmTypesHost>(
3827    dest_offset: u64,
3828    size: u64,
3829    interpreter: &mut Interpreter<'_, '_, T>,
3830    ranges: &[Range<u64>],
3831) {
3832    let revert_string = format!(
3833        "memory write at offset 0x{:02X} of size 0x{:02X} not allowed; safe range: {}",
3834        dest_offset,
3835        size,
3836        ranges.iter().map(|r| format!("[0x{:02X}, 0x{:02X})", r.start, r.end)).join(" U ")
3837    );
3838
3839    revert_frame(interpreter, revert_string.as_bytes());
3840}
3841
3842/// The instructions during which the running frame can emit a log: `LOG*`, and the message and
3843/// self-destruct instructions, such as for logs of precompiles and value transfers.
3844const LOG_EMITTING_OPCODES: OpcodeSet = opcodes([
3845    op::LOG0,
3846    op::LOG1,
3847    op::LOG2,
3848    op::LOG3,
3849    op::LOG4,
3850    op::CALL,
3851    op::CALLCODE,
3852    op::DELEGATECALL,
3853    op::STATICCALL,
3854    op::CREATE,
3855    op::CREATE2,
3856    op::SELFDESTRUCT,
3857]);
3858
3859/// The instructions that end a frame with a result its caller reads: a halt discards the gas and
3860/// refund of the frame.
3861const FRAME_END_OPCODES: OpcodeSet = opcodes([op::STOP, op::RETURN, op::REVERT, op::SELFDESTRUCT]);
3862
3863/// The instructions that `startStateDiffRecording` records.
3864const STATE_DIFF_OPCODES: OpcodeSet = opcodes([
3865    op::SELFDESTRUCT,
3866    op::SLOAD,
3867    op::SSTORE,
3868    op::EXTCODECOPY,
3869    op::EXTCODESIZE,
3870    op::EXTCODEHASH,
3871    op::BALANCE,
3872]);
3873
3874/// The instructions that read or write memory, which `expectSafeMemory` checks.
3875const MEMORY_OPCODES: OpcodeSet = opcodes([
3876    op::MSTORE,
3877    op::MSTORE8,
3878    op::MLOAD,
3879    op::CALL,
3880    op::CALLDATACOPY,
3881    op::CODECOPY,
3882    op::RETURNDATACOPY,
3883    op::EXTCODECOPY,
3884    op::CALLCODE,
3885    op::STATICCALL,
3886    op::DELEGATECALL,
3887    op::KECCAK256,
3888    op::LOG0,
3889    op::LOG1,
3890    op::LOG2,
3891    op::LOG3,
3892    op::LOG4,
3893    op::CREATE,
3894    op::CREATE2,
3895    op::RETURN,
3896    op::REVERT,
3897]);
3898
3899/// Returns true if the kind of account access is a call.
3900const fn access_is_call(kind: crate::Vm::AccountAccessKind) -> bool {
3901    matches!(
3902        kind,
3903        crate::Vm::AccountAccessKind::Call
3904            | crate::Vm::AccountAccessKind::StaticCall
3905            | crate::Vm::AccountAccessKind::CallCode
3906            | crate::Vm::AccountAccessKind::DelegateCall
3907    )
3908}
3909
3910/// Returns the account whose balance and nonce a call's [`AccountAccess`] records.
3911///
3912/// `DELEGATECALL` and `CALLCODE` execute in the caller's context, so their callee's state does not
3913/// change. Other calls record the executing context, which a `vm.mockFunction` redirect keeps as
3914/// the original target while `call_target` becomes the mock.
3915const fn recorded_call_state_account<E>(call: &MessageExt<E>) -> Address {
3916    match call.kind {
3917        MessageKind::DelegateCall | MessageKind::CallCode => call.call_target,
3918        _ => call.destination,
3919    }
3920}
3921
3922/// Records a log into the recorded logs vector, if it exists.
3923fn record_logs(recorded_logs: &mut Option<Vec<Vm::Log>>, log: &Log) {
3924    if let Some(storage_recorded_logs) = recorded_logs {
3925        storage_recorded_logs.push(Vm::Log {
3926            topics: log.data.topics().to_vec(),
3927            data: log.data.data.clone(),
3928            emitter: log.address,
3929        });
3930    }
3931}
3932
3933/// Returns the [`spec::Cheatcode`] definition for a given [`spec::CheatcodeDef`] implementor.
3934const fn cheatcode_of<T: spec::CheatcodeDef>(_: &T) -> &'static spec::Cheatcode<'static> {
3935    T::CHEATCODE
3936}
3937
3938const fn cheatcode_id(cheat: &spec::Cheatcode<'static>) -> &'static str {
3939    cheat.func.id
3940}
3941
3942const fn cheatcode_signature(cheat: &spec::Cheatcode<'static>) -> &'static str {
3943    cheat.func.signature
3944}
3945
3946/// Decodes a cheatcode call, reporting an unknown selector as a `Vm` interface mismatch.
3947pub fn decode_cheatcode_call(input: &[u8]) -> alloy_sol_types::Result<Vm::VmCalls> {
3948    Vm::VmCalls::abi_decode(input).map_err(|e| {
3949        if let alloy_sol_types::Error::UnknownSelector { name: _, selector } = e {
3950            let msg = format!(
3951                "unknown cheatcode with selector {selector}; \
3952                 you may have a mismatch between the `Vm` interface (likely in `forge-std`) \
3953                 and the `forge` version"
3954            );
3955            return alloy_sol_types::Error::Other(std::borrow::Cow::Owned(msg));
3956        }
3957        e
3958    })
3959}
3960
3961/// Dispatches the cheatcode call to the appropriate function.
3962fn apply_dispatch<FEN: FoundryEvmNetwork>(
3963    calls: &Vm::VmCalls,
3964    ccx: &mut CheatsCtxt<'_, '_, FEN>,
3965    executor: &mut dyn CheatcodesExecutor<FEN>,
3966) -> Result {
3967    // Extract metadata for logging/deprecation via CheatcodeDef.
3968    macro_rules! get_cheatcode {
3969        ($($variant:ident),*) => {
3970            match calls {
3971                $(Vm::VmCalls::$variant(cheat) => cheatcode_of(cheat),)*
3972            }
3973        };
3974    }
3975    let cheat = vm_calls!(get_cheatcode);
3976
3977    let _guard = debug_span!(target: "cheatcodes", "apply", id = %cheatcode_id(cheat)).entered();
3978    trace!(target: "cheatcodes", cheat = %cheatcode_signature(cheat), "applying");
3979
3980    if let spec::Status::Deprecated(replacement) = cheat.status {
3981        ccx.state.deprecated.insert(cheatcode_signature(cheat), replacement);
3982    }
3983
3984    // Monomorphized dispatch: calls apply_full directly, no trait objects.
3985    macro_rules! dispatch {
3986        ($($variant:ident),*) => {
3987            match calls {
3988                $(Vm::VmCalls::$variant(cheat) => Cheatcode::apply_full(cheat, ccx, executor),)*
3989            }
3990        };
3991    }
3992    let result = if ccx.state.core.config.blocked_cheatcodes.contains(&cheat.func.selector_bytes) {
3993        Err(fmt_err!("disabled during restricted execution"))
3994    } else if let Some(trace) = &mut ccx.state.failure_trace
3995        && has_host_effects(calls)
3996    {
3997        // A replay must not repeat these effects and cannot reproduce these reads, so it skips
3998        // them and leaves this and later failures unidentified.
3999        trace.skipped_host_effects.store(true, Ordering::Relaxed);
4000        Ok(Default::default())
4001    } else if ccx.state.failure_trace.is_some() && matches!(calls, Vm::VmCalls::sleep(_)) {
4002        // A replay does not wait, which only `unixTime` could observe.
4003        Ok(Default::default())
4004    } else {
4005        vm_calls!(dispatch)
4006    }
4007    .map_err(|error| error.with_cheatcode_name(cheat));
4008
4009    trace!(
4010        target: "cheatcodes",
4011        return = %match &result {
4012            Ok(b) => hex::encode(b),
4013            Err(e) => e.to_string(),
4014        }
4015    );
4016
4017    result
4018}
4019
4020/// Returns whether `call` writes to files or environment variables, runs a command, sends an
4021/// arbitrary RPC request, creates a fork at the latest block, which can be newer than the
4022/// campaign's, prompts for input, or reads the clock, which skipped sleeps would make disagree
4023/// with the campaign's.
4024const fn has_host_effects(call: &Vm::VmCalls) -> bool {
4025    matches!(
4026        call,
4027        Vm::VmCalls::copyFile(_)
4028            | Vm::VmCalls::createDir(_)
4029            | Vm::VmCalls::createFork_0(_)
4030            | Vm::VmCalls::createSelectFork_0(_)
4031            | Vm::VmCalls::dumpState(_)
4032            | Vm::VmCalls::eth_getLogs(_)
4033            | Vm::VmCalls::eth_getProof(_)
4034            | Vm::VmCalls::ffi(_)
4035            | Vm::VmCalls::ffiBytes(_)
4036            | Vm::VmCalls::ffiString(_)
4037            | Vm::VmCalls::ffiUint(_)
4038            | Vm::VmCalls::getRawBlockHeader(_)
4039            | Vm::VmCalls::prompt(_)
4040            | Vm::VmCalls::promptAddress(_)
4041            | Vm::VmCalls::promptSecret(_)
4042            | Vm::VmCalls::promptSecretUint(_)
4043            | Vm::VmCalls::promptUint(_)
4044            | Vm::VmCalls::removeDir(_)
4045            | Vm::VmCalls::removeFile(_)
4046            | Vm::VmCalls::rpcJson_0(_)
4047            | Vm::VmCalls::rpcJson_1(_)
4048            | Vm::VmCalls::rpc_0(_)
4049            | Vm::VmCalls::rpc_1(_)
4050            | Vm::VmCalls::setEnv(_)
4051            | Vm::VmCalls::tryFfi(_)
4052            | Vm::VmCalls::unixTime(_)
4053            | Vm::VmCalls::writeFile(_)
4054            | Vm::VmCalls::writeFileBinary(_)
4055            | Vm::VmCalls::writeJson_0(_)
4056            | Vm::VmCalls::writeJson_1(_)
4057            | Vm::VmCalls::writeLine(_)
4058            | Vm::VmCalls::writeToml_0(_)
4059            | Vm::VmCalls::writeToml_1(_)
4060    )
4061}
4062
4063/// Returns the gas a frame used, as reported by `lastCallGas` and `lastFrameGas`.
4064const fn frame_gas(stop: InstrStop, gas: &GasTracker) -> Vm::Gas {
4065    // A halt consumes the regular gas restored while rolling back state gas.
4066    let regular_gas_spent = if stop.is_halt() {
4067        gas.spent()
4068    } else {
4069        gas.spent().saturating_sub(gas.state_gas_spilled())
4070    };
4071    Vm::Gas {
4072        gasLimit: gas.limit(),
4073        gasTotalUsed: regular_gas_spent,
4074        gasMemoryUsed: 0,
4075        gasRefunded: gas.refunded(),
4076        gasRemaining: gas.remaining(),
4077        gasStateUsed: if stop.is_success() { gas.state_gas_spent() } else { 0 },
4078    }
4079}
4080
4081/// Turns `outcome` into a revert with `output`.
4082fn set_revert<E>(outcome: &mut MessageResultExt<E>, output: Bytes) {
4083    outcome.stop = InstrStop::Revert;
4084    outcome.output = output;
4085}
4086
4087/// Turns `outcome` into a successful return with `output`.
4088fn set_return<E>(outcome: &mut MessageResultExt<E>, output: Bytes) {
4089    outcome.stop = InstrStop::Return;
4090    outcome.output = output;
4091}
4092
4093/// Bumps the nonces of the authorities of `authorizations` that the transaction will apply, as
4094/// EIP-7702 does, for a transaction that is broadcast but not executed.
4095fn apply_authorization_nonces<FEN: FoundryEvmNetwork>(
4096    evm: &mut FoundryEvmFor<'_, FEN>,
4097    authorizations: &[SignedAuthorization],
4098    sender: Address,
4099    chain_id: u64,
4100) -> Result<Vec<PersistentWrite>> {
4101    let mut writes = Vec::new();
4102    for auth in authorizations {
4103        if (!auth.chain_id.is_zero() && auth.chain_id != U256::from(chain_id))
4104            || auth.nonce() == u64::MAX
4105        {
4106            continue;
4107        }
4108        let Ok(authority) = auth.recover_authority() else { continue };
4109        // The authority code check is skipped because attaching the delegation already replaced
4110        // the local code that EIP-7702 validates.
4111        let mut account = evm.state_mut().account(&authority)?;
4112        account.touch();
4113        account.warm();
4114        // The sender nonce has not been incremented for the transaction yet.
4115        let nonce = account.nonce();
4116        if auth.nonce() == nonce + u64::from(authority == sender) {
4117            account.set_nonce(nonce + 1);
4118            writes.push(PersistentWrite::nonce(&account, nonce));
4119        }
4120    }
4121    Ok(writes)
4122}
4123
4124#[cfg(test)]
4125mod tests {
4126    use super::*;
4127    use env_overrides::EnvOverrides;
4128
4129    fn cheats(flag: bool, broadcast: Option<Broadcast>) -> Cheatcodes {
4130        let config = CheatsConfig { batch_rewrite_creates: flag, ..Default::default() };
4131        let mut cheats = Cheatcodes::new(Arc::new(config));
4132        cheats.broadcast = broadcast;
4133        cheats
4134    }
4135
4136    fn create_inputs() -> MessageFor<EthEvmNetwork> {
4137        MessageFor::<EthEvmNetwork> {
4138            kind: MessageKind::Create,
4139            gas_limit: 100_000,
4140            ..Default::default()
4141        }
4142    }
4143
4144    fn broadcast_at(depth: usize) -> Broadcast {
4145        Broadcast { depth, ..Default::default() }
4146    }
4147
4148    #[test]
4149    fn flag_off_with_broadcast_returns_false() {
4150        let mut cheats = cheats(false, Some(broadcast_at(1)));
4151        assert!(!cheats.should_use_create2_factory(1, &create_inputs()));
4152    }
4153
4154    #[test]
4155    fn flag_on_without_broadcast_returns_false() {
4156        let mut cheats = cheats(true, None);
4157        assert!(!cheats.should_use_create2_factory(1, &create_inputs()));
4158    }
4159
4160    #[test]
4161    fn flag_on_with_broadcast_depth_mismatch_returns_false() {
4162        let mut cheats = cheats(true, Some(broadcast_at(2)));
4163        assert!(!cheats.should_use_create2_factory(1, &create_inputs()));
4164    }
4165
4166    #[test]
4167    fn flag_on_with_broadcast_depth_match_returns_true() {
4168        let mut cheats = cheats(true, Some(broadcast_at(1)));
4169        assert!(cheats.should_use_create2_factory(1, &create_inputs()));
4170    }
4171
4172    #[test]
4173    fn default_cheatcodes_have_no_opcode_hooks() {
4174        let cheats = Cheatcodes::<EthEvmNetwork>::new(Arc::default());
4175        assert_eq!(cheats.steps(), OpcodeSet::EMPTY);
4176        assert!(!cheats.has_log_hooks());
4177    }
4178
4179    #[test]
4180    fn active_cheatcode_state_enables_opcode_hooks() {
4181        let mut cheats = Cheatcodes::<EthEvmNetwork>::new(Arc::default());
4182
4183        cheats.recording_accesses = true;
4184        assert_eq!(cheats.steps(), [op::SLOAD, op::SSTORE].into_iter().collect());
4185
4186        cheats.recording_accesses = false;
4187        cheats.gas_metering.touched = true;
4188        assert_eq!(cheats.steps(), opcodes([op::STOP, op::RETURN, op::REVERT, op::SELFDESTRUCT]));
4189
4190        cheats.gas_metering.touched = false;
4191        cheats.recorded_account_diffs_stack = Some(Vec::new());
4192        assert_eq!(
4193            cheats.steps(),
4194            opcodes([
4195                op::SELFDESTRUCT,
4196                op::SLOAD,
4197                op::SSTORE,
4198                op::EXTCODECOPY,
4199                op::EXTCODESIZE,
4200                op::EXTCODEHASH,
4201                op::BALANCE,
4202            ])
4203        );
4204
4205        cheats.recorded_account_diffs_stack = None;
4206        cheats.allowed_mem_writes.insert(1, Vec::new());
4207        assert_eq!(
4208            cheats.steps(),
4209            opcodes([
4210                op::MSTORE,
4211                op::MSTORE8,
4212                op::MLOAD,
4213                op::CALL,
4214                op::CALLDATACOPY,
4215                op::CODECOPY,
4216                op::RETURNDATACOPY,
4217                op::EXTCODECOPY,
4218                op::CALLCODE,
4219                op::STATICCALL,
4220                op::DELEGATECALL,
4221                op::KECCAK256,
4222                op::LOG0,
4223                op::LOG1,
4224                op::LOG2,
4225                op::LOG3,
4226                op::LOG4,
4227                op::CREATE,
4228                op::CREATE2,
4229                op::RETURN,
4230                op::REVERT,
4231            ])
4232        );
4233
4234        cheats.allowed_mem_writes.clear();
4235        cheats.core.mapping_slots = Some(Default::default());
4236        assert_eq!(cheats.steps(), [op::SSTORE, op::KECCAK256].into_iter().collect());
4237
4238        cheats.core.mapping_slots = None;
4239        cheats.gas_metering.paused = true;
4240        assert_eq!(cheats.steps(), OpcodeSet::ALL);
4241        cheats.gas_metering.paused = false;
4242
4243        cheats.register_storage_load_hook(Address::ZERO, Address::ZERO, [0; 4]);
4244        assert_eq!(cheats.steps(), OpcodeSet::ALL);
4245    }
4246
4247    #[test]
4248    fn combined_cheatcodes_step_every_opcode_any_needs() {
4249        let mut cheats = Cheatcodes::<EthEvmNetwork>::new(Arc::default());
4250        cheats.recording_accesses = true;
4251        cheats.gas_price = Some(1);
4252        cheats.env_overrides.update(None, |o| o.chain_id = Some(1));
4253        assert_eq!(
4254            cheats.steps(),
4255            [
4256                op::SLOAD,
4257                op::SSTORE,
4258                op::ORIGIN,
4259                op::GASPRICE,
4260                op::BASEFEE,
4261                op::CHAINID,
4262                op::BLOBHASH
4263            ]
4264            .into_iter()
4265            .collect()
4266        );
4267
4268        cheats.gas_metering.reset = true;
4269        assert_eq!(cheats.steps(), OpcodeSet::ALL);
4270    }
4271
4272    #[test]
4273    fn env_override_hook_predicates() {
4274        fn assert_hooks(cheats: &Cheatcodes, active: bool, case: &str) {
4275            let steps = if active {
4276                [op::BASEFEE, op::GASPRICE, op::CHAINID, op::BLOBHASH].into_iter().collect()
4277            } else {
4278                OpcodeSet::EMPTY
4279            };
4280            assert_eq!(cheats.steps(), steps, "{case}");
4281        }
4282
4283        let mut cheats = Cheatcodes::<EthEvmNetwork>::new(Arc::default());
4284        assert_hooks(&cheats, false, "empty map");
4285        let snapshot_id = U256::from(7);
4286        cheats.env_overrides.save_snapshot(snapshot_id);
4287
4288        cheats.env_overrides.update(None, |_| {});
4289        assert_hooks(&cheats, false, "inactive entry");
4290
4291        let active = [
4292            EnvOverrides { basefee: Some(1), ..Default::default() },
4293            EnvOverrides { implicit_basefee: Some(1), ..Default::default() },
4294            EnvOverrides { gas_price: Some(1), ..Default::default() },
4295            EnvOverrides { blob_hashes: Some(vec![B256::ZERO]), ..Default::default() },
4296            EnvOverrides { chain_id: Some(1), ..Default::default() },
4297        ];
4298        for overrides in active {
4299            let case = format!("{overrides:?}");
4300            cheats.env_overrides.update(None, |o| *o = overrides);
4301            assert_hooks(&cheats, true, &case);
4302        }
4303
4304        // Overrides on a fork that isn't active still enable the hooks.
4305        cheats.env_overrides.restore_snapshot(snapshot_id, false);
4306        cheats.env_overrides.update(Some(U256::from(1)), |o| o.basefee = Some(1));
4307        assert_hooks(&cheats, true, "override on another fork");
4308
4309        // Restoring a snapshot taken without overrides turns the hooks off.
4310        cheats.env_overrides.restore_snapshot(snapshot_id, false);
4311        assert_hooks(&cheats, false, "after restoring an empty snapshot");
4312    }
4313
4314    #[test]
4315    fn active_log_state_enables_log_hooks() {
4316        let mut cheats = Cheatcodes::<EthEvmNetwork>::new(Arc::default());
4317
4318        cheats.core.recorded_logs = Some(Default::default());
4319        assert!(cheats.has_log_hooks());
4320
4321        cheats.core.recorded_logs = None;
4322        cheats.expected_emits.push_back((
4323            crate::expected_emit::ExpectedEmit {
4324                depth: 0,
4325                log: None,
4326                checks: [false; 5],
4327                address: None,
4328                anonymous: false,
4329                found: false,
4330                count: 1,
4331                mismatch_error: None,
4332            },
4333            Default::default(),
4334        ));
4335        assert!(cheats.has_log_hooks());
4336    }
4337
4338    #[test]
4339    fn frame_gas_reports_settled_components() {
4340        for mut gas in [
4341            GasTracker::new(100_000),
4342            GasTracker::new_with_execution_gas_and_reservoir(100_000, 50_000),
4343        ] {
4344            gas.spend(1_000).unwrap();
4345            gas.spend_state(20_000).unwrap();
4346
4347            let reported = frame_gas(InstrStop::Stop, &gas);
4348            assert_eq!(reported.gasTotalUsed, 1_000);
4349            assert_eq!(reported.gasStateUsed, 20_000);
4350
4351            assert_eq!(frame_gas(InstrStop::Revert, &gas).gasStateUsed, 0);
4352        }
4353
4354        let mut gas = GasTracker::new(100_000);
4355        gas.refill_reservoir(20_000);
4356        assert_eq!(frame_gas(InstrStop::Stop, &gas).gasStateUsed, -20_000);
4357
4358        let mut gas = GasTracker::new(100_000);
4359        gas.spend_state(20_000).unwrap();
4360        gas.settle_gas(InstrStop::OutOfGas);
4361        let reported = frame_gas(InstrStop::OutOfGas, &gas);
4362        assert_eq!(reported.gasTotalUsed, 100_000);
4363        assert_eq!(reported.gasStateUsed, 0);
4364    }
4365
4366    #[test]
4367    fn set_arbitrary_storage_applies_through_core_context() {
4368        let mut cheats = cheats(false, None);
4369        let target = Address::repeat_byte(0x11);
4370        let slot = U256::from(7);
4371        assert_eq!(cheats.steps(), OpcodeSet::EMPTY);
4372
4373        Vm::setArbitraryStorage_1Call { target, overwrite: true }
4374            .apply_context(&mut cheats.core)
4375            .unwrap();
4376        assert_eq!(cheats.steps(), OpcodeSet::ALL);
4377        assert!(cheats.has_arbitrary_storage(&target));
4378        assert!(cheats.should_overwrite_arbitrary_storage(&target, slot));
4379
4380        cheats.mark_arbitrary_storage_slot_explicit(target, slot);
4381        cheats
4382            .core
4383            .arbitrary_storage
4384            .as_mut()
4385            .unwrap()
4386            .values
4387            .get_mut(&target)
4388            .unwrap()
4389            .insert(slot, U256::from(42));
4390        assert!(cheats.is_arbitrary_storage_slot_explicit(target, slot));
4391        assert_eq!(cheats.cached_arbitrary_storage_value(target, slot), Some(U256::from(42)));
4392
4393        // Re-registering clears the overwrite mode, explicit slots, and cached values.
4394        Vm::setArbitraryStorage_0Call { target }.apply_context(&mut cheats.core).unwrap();
4395        assert_eq!(
4396            cheats.arbitrary_storage_target_overwrite_modes().collect_vec(),
4397            [(target, false)]
4398        );
4399        assert!(!cheats.is_arbitrary_storage_slot_explicit(target, slot));
4400        assert_eq!(cheats.cached_arbitrary_storage_value(target, slot), None);
4401    }
4402}