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