Skip to main content

foundry_cheatcodes/
evm.rs

1//! Implementations of [`Evm`](spec::Group::Evm) cheatcodes.
2
3use crate::{
4    BroadcastableTransaction, Cheatcode, Cheatcodes, CheatcodesCore, CheatcodesExecutor,
5    CheatsCtxt, Error, Result, Vm::*, env::FORGE_CONTEXT, inspector::RecordDebugStepInfo,
6};
7use alloy_consensus::{Transaction as _, Typed2718, transaction::SignerRecoverable};
8use alloy_genesis::{Genesis, GenesisAccount};
9use alloy_primitives::{
10    Address, B256, Bytes, U256, b256, hex, keccak256,
11    map::{AddressMap, AddressSet, B256Map, HashMap},
12};
13use alloy_rlp::Decodable;
14use alloy_sol_types::{SolCall, SolValue};
15use evm2::{
16    EvmFeatures, SpecId,
17    bytecode::Bytecode,
18    evm::{DbResult, State, StorageSlotHandle},
19    interpreter::Host,
20    registry::HandlerError,
21};
22use foundry_common::{
23    EIP1967_IMPLEMENTATION_SLOT, TransactionMaybeSigned,
24    fs::{read_json_file, write_json_file},
25    slot_identifier::{
26        ENCODING_BYTES, ENCODING_DYN_ARRAY, ENCODING_INPLACE, ENCODING_MAPPING, SlotIdentifier,
27        SlotInfo, identify_eip1967_slot,
28    },
29    tempo::{TIP20_MAX_LOGO_URI_BYTES, Tip20LogoUriValidationError, validate_tip20_logo_uri},
30};
31use foundry_compilers::artifacts::{Storage, StorageLayout, StorageType};
32use foundry_evm_core::{
33    backend::{GLOBAL_FAIL_SLOT, RevertStateSnapshotAction, transaction_error},
34    constants::{CALLER, CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS, TEST_CONTRACT_ADDRESS},
35    eip2935::{
36        HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE, forward_fill_start,
37        history_storage_slot, history_storage_value,
38    },
39    evm::{
40        EvmEnvFor, EvmFactoryFor, ExecutionPhase, FoundryEvmFactory, FoundryEvmNetwork,
41        FoundryExecutionHooks, FoundryTxConversion, PersistentWrite, Replay, TxEnvelopeFor,
42        TxPayload, TypesFor, evm_env,
43    },
44};
45use foundry_evm_traces::TraceRequirements;
46use itertools::Itertools;
47use std::{
48    collections::{BTreeMap, btree_map::Entry},
49    fmt::Display,
50    path::{Component, Path},
51    str::FromStr,
52    sync::Arc,
53};
54
55mod record_debug_step;
56use foundry_common::fmt::format_token_raw;
57use foundry_config::{ExecutionSpec, evm_spec_id_from_str, fs_permissions::FsAccessKind};
58use record_debug_step::{convert_call_trace_ctx_to_debug_step, flatten_call_trace};
59use serde::{Serialize, Serializer, ser::SerializeMap};
60
61mod fork;
62pub(crate) mod mapping;
63pub(crate) mod mock;
64pub(crate) mod prank;
65
66/// JSON-serializable log entry for `getRecordedLogsJson`.
67#[derive(Serialize)]
68#[serde(rename_all = "camelCase")]
69struct LogJson {
70    /// The topics of the log, including the signature, if any.
71    topics: Vec<String>,
72    /// The raw data of the log, hex-encoded with 0x prefix.
73    data: String,
74    /// The address of the log's emitter.
75    emitter: String,
76}
77
78struct StateDump<'a>(&'a [(Address, GenesisAccount)]);
79
80impl Serialize for StateDump<'_> {
81    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
82    where
83        S: Serializer,
84    {
85        let mut map = serializer.serialize_map(Some(self.0.len()))?;
86        for (address, account) in self.0 {
87            map.serialize_entry(address, account)?;
88        }
89        map.end()
90    }
91}
92
93/// Records storage slots reads and writes.
94#[derive(Clone, Debug, Default)]
95pub struct RecordAccess {
96    /// Storage slots reads.
97    pub reads: HashMap<Address, Vec<U256>>,
98    /// Storage slots writes.
99    pub writes: HashMap<Address, Vec<U256>>,
100}
101
102impl RecordAccess {
103    /// Records a read access to a storage slot.
104    pub fn record_read(&mut self, target: Address, slot: U256) {
105        self.reads.entry(target).or_default().push(slot);
106    }
107
108    /// Records a write access to a storage slot.
109    ///
110    /// This also records a read internally as `SSTORE` does an implicit `SLOAD`.
111    pub fn record_write(&mut self, target: Address, slot: U256) {
112        self.record_read(target, slot);
113        self.writes.entry(target).or_default().push(slot);
114    }
115
116    /// Clears the recorded reads and writes.
117    pub fn clear(&mut self) {
118        // Also frees memory.
119        *self = Default::default();
120    }
121}
122
123/// Records the `snapshotGas*` cheatcodes.
124#[derive(Clone, Debug)]
125pub struct GasRecord {
126    /// The group name of the gas snapshot.
127    pub group: String,
128    /// The name of the gas snapshot.
129    pub name: String,
130    /// The total gas used in the gas snapshot.
131    pub gas_used: u64,
132    /// Depth at which the gas snapshot was taken.
133    pub depth: usize,
134}
135
136/// Storage slot diff info.
137#[derive(Serialize, Default)]
138#[serde(rename_all = "camelCase")]
139struct SlotStateDiff {
140    /// Initial storage value.
141    previous_value: B256,
142    /// Current storage value.
143    new_value: B256,
144    /// Storage layout metadata (variable name, type, offset).
145    /// Only present when contract has storage layout output, or for the EIP-1967 proxy slots.
146    /// This includes decoded values when available.
147    #[serde(skip_serializing_if = "Option::is_none", flatten)]
148    slot_info: Option<SlotInfo>,
149}
150
151/// Balance diff info.
152#[derive(Serialize, Default)]
153#[serde(rename_all = "camelCase")]
154struct BalanceDiff {
155    /// Initial storage value.
156    previous_value: U256,
157    /// Current storage value.
158    new_value: U256,
159}
160
161/// Nonce diff info.
162#[derive(Serialize, Default)]
163#[serde(rename_all = "camelCase")]
164struct NonceDiff {
165    /// Initial nonce value.
166    previous_value: u64,
167    /// Current nonce value.
168    new_value: u64,
169}
170
171/// Account state diff info.
172#[derive(Serialize, Default)]
173#[serde(rename_all = "camelCase")]
174struct AccountStateDiffs {
175    /// Address label, if any set.
176    label: Option<String>,
177    /// Contract identifier from artifact. e.g "src/Counter.sol:Counter"
178    contract: Option<String>,
179    /// Account balance changes.
180    balance_diff: Option<BalanceDiff>,
181    /// Account nonce changes.
182    nonce_diff: Option<NonceDiff>,
183    /// State changes, per slot.
184    state_diff: BTreeMap<B256, SlotStateDiff>,
185}
186
187impl Display for AccountStateDiffs {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> eyre::Result<(), std::fmt::Error> {
189        // Print changed account.
190        if let Some(label) = &self.label {
191            writeln!(f, "label: {label}")?;
192        }
193        if let Some(contract) = &self.contract {
194            writeln!(f, "contract: {contract}")?;
195        }
196        // Print balance diff if changed.
197        if let Some(balance_diff) = &self.balance_diff
198            && balance_diff.previous_value != balance_diff.new_value
199        {
200            writeln!(
201                f,
202                "- balance diff: {} → {}",
203                balance_diff.previous_value, balance_diff.new_value
204            )?;
205        }
206        // Print nonce diff if changed.
207        if let Some(nonce_diff) = &self.nonce_diff
208            && nonce_diff.previous_value != nonce_diff.new_value
209        {
210            writeln!(f, "- nonce diff: {} → {}", nonce_diff.previous_value, nonce_diff.new_value)?;
211        }
212        // Print state diff if any.
213        if !&self.state_diff.is_empty() {
214            writeln!(f, "- state diff:")?;
215            for (slot, slot_changes) in &self.state_diff {
216                match &slot_changes.slot_info {
217                    Some(slot_info)
218                        if slot_info.members.as_ref().is_some_and(|members| {
219                            members.iter().any(|member| member.decoded.is_some())
220                        }) =>
221                    {
222                        // Keep raw values because decoded members may omit unsupported fields.
223                        writeln!(
224                            f,
225                            "@ {slot} ({}, {}): {} → {}",
226                            slot_info.label,
227                            slot_info.slot_type,
228                            slot_changes.previous_value,
229                            slot_changes.new_value
230                        )?;
231                        for member in slot_info.members.iter().flatten() {
232                            let Some(decoded) = &member.decoded else { continue };
233                            writeln!(
234                                f,
235                                "    {} ({}): {} → {}",
236                                member.label,
237                                member.slot_type,
238                                format_token_raw(&decoded.previous_value),
239                                format_token_raw(&decoded.new_value)
240                            )?;
241                        }
242                    }
243                    Some(slot_info) => {
244                        if let Some(decoded) = &slot_info.decoded {
245                            // Have slot info with decoded values - show decoded values
246                            writeln!(
247                                f,
248                                "@ {slot} ({}, {}): {} → {}",
249                                slot_info.label,
250                                slot_info.slot_type,
251                                format_token_raw(&decoded.previous_value),
252                                format_token_raw(&decoded.new_value)
253                            )?;
254                        } else {
255                            // Have slot info but no decoded values - show raw hex values
256                            writeln!(
257                                f,
258                                "@ {slot} ({}, {}): {} → {}",
259                                slot_info.label,
260                                slot_info.slot_type,
261                                slot_changes.previous_value,
262                                slot_changes.new_value
263                            )?;
264                        }
265                    }
266                    None => {
267                        // No slot info - show raw hex values
268                        writeln!(
269                            f,
270                            "@ {slot}: {} → {}",
271                            slot_changes.previous_value, slot_changes.new_value
272                        )?;
273                    }
274                }
275            }
276        }
277
278        Ok(())
279    }
280}
281
282/// Storage writes to one account during a state-diff recording.
283#[derive(Default)]
284struct StorageWriters {
285    /// Chain id and fork id of the first write.
286    context: Option<(u64, U256)>,
287    /// Whether a later write happened on a different chain or fork.
288    mixed_contexts: bool,
289    /// Code address whose layout describes the latest write to each slot: the account itself, or
290    /// the implementation that wrote through a delegatecall. Unknown when a library's caller
291    /// was not recorded.
292    slots: B256Map<Option<Address>>,
293}
294
295impl StorageWriters {
296    /// Records a write to `slot` executed by the code at `writer`.
297    fn record(&mut self, context: (u64, U256), slot: B256, writer: Option<Address>) {
298        if *self.context.get_or_insert(context) != context {
299            self.mixed_contexts = true;
300        }
301        self.slots.insert(slot, writer);
302    }
303
304    /// Returns the chain id and fork id shared by every write, if any.
305    fn context(&self) -> Option<(u64, U256)> {
306        self.context.filter(|_| !self.mixed_contexts)
307    }
308}
309
310impl Cheatcode for addrCall {
311    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
312        let Self { privateKey } = self;
313        super::crypto::with_private_key_signer(state, privateKey, |wallet| {
314            Ok(wallet.address().abi_encode())
315        })
316    }
317}
318
319impl Cheatcode for getNonce_0Call {
320    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
321        let Self { account } = self;
322        get_nonce(ccx, account)
323    }
324}
325
326impl Cheatcode for getNonce_1Call {
327    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
328        let Self { wallet } = self;
329        get_nonce(ccx, &wallet.addr)
330    }
331}
332
333impl Cheatcode for loadCall {
334    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
335        let Self { target, slot } = *self;
336
337        ccx.evm.state_mut().account(&target)?.warm();
338        let (is_cold, mut value) = {
339            let mut slot = ccx
340                .evm
341                .state_mut()
342                .storage_slot(&target, slot.into())
343                .map_err(|e| fmt_err!("failed to load storage slot: {e}"))?;
344            (slot.warm(), slot.current())
345        };
346
347        if is_cold
348            && value.is_zero()
349            && !ccx.state.is_arbitrary_storage_slot_explicit(target, slot.into())
350        {
351            if ccx.state.has_arbitrary_storage(&target) {
352                // If storage slot is untouched and load from a target with arbitrary storage,
353                // then set random value for current slot.
354                let rand_value = ccx
355                    .state
356                    .cached_arbitrary_storage_value(target, slot.into())
357                    .unwrap_or_else(|| ccx.state.draw_arbitrary_storage_value(target, slot.into()));
358                ccx.state.core.arbitrary_storage.as_mut().unwrap().save(
359                    ccx.evm.state_mut(),
360                    target,
361                    slot.into(),
362                    rand_value,
363                )?;
364                value = rand_value;
365            } else if ccx.state.is_arbitrary_storage_copy(&target) {
366                // If storage slot is untouched and load from a target that copies storage from
367                // a source address with arbitrary storage, then copy existing arbitrary value.
368                // If no arbitrary value generated yet, then the random one is saved and set.
369                let rand_value = ccx.state.draw_arbitrary_storage_value(target, slot.into());
370                value = ccx.state.core.arbitrary_storage.as_mut().unwrap().copy(
371                    ccx.evm.state_mut(),
372                    target,
373                    slot.into(),
374                    rand_value,
375                )?;
376            }
377        }
378
379        Ok(value.abi_encode())
380    }
381}
382
383impl Cheatcode for loadTransientCall {
384    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
385        let Self { target, slot } = *self;
386        let value = ccx.evm.state_mut().tload(&target, &slot.into());
387        Ok(B256::from(value).abi_encode())
388    }
389}
390
391impl Cheatcode for loadAllocsCall {
392    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
393        let Self { pathToAllocsJson } = self;
394
395        let path = Path::new(pathToAllocsJson);
396        ensure!(path.exists(), "allocs file does not exist: {pathToAllocsJson}");
397
398        // Let's first assume we're reading a file with only the allocs.
399        let allocs: BTreeMap<Address, GenesisAccount> = match read_json_file(path) {
400            Ok(allocs) => allocs,
401            Err(_) => {
402                // Let's try and read from a genesis file, and extract allocs.
403                let genesis = read_json_file::<Genesis>(path)?;
404                genesis.alloc
405            }
406        };
407
408        // Then, load the allocs into the database.
409        TypesFor::<FEN>::sync_transaction(ccx.evm);
410        let (evm, db) = ccx.evm_db_mut();
411        db.load_allocs(&allocs, evm).map_err(|e| fmt_err!("failed to load allocs: {e}"))?;
412        TypesFor::<FEN>::refresh_transaction(ccx.evm);
413        Ok(Default::default())
414    }
415}
416
417impl Cheatcode for cloneAccountCall {
418    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
419        let Self { source, target } = self;
420
421        ccx.evm.state_mut().account(source)?.warm();
422        let slots = ccx.db().lifecycle().loaded_storage(ccx.evm.state(), source);
423        let genesis = genesis_account(ccx.evm.state_mut(), source, slots)?;
424        TypesFor::<FEN>::sync_transaction(ccx.evm);
425        let (evm, db) = ccx.evm_db_mut();
426        db.clone_account(&genesis, target, evm)?;
427        TypesFor::<FEN>::refresh_transaction(ccx.evm);
428        // Cloned account should persist in forked envs.
429        ccx.db_mut().add_persistent_account(*target);
430        Ok(Default::default())
431    }
432}
433
434impl Cheatcode for dumpStateCall {
435    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
436        let Self { pathToStateJson } = self;
437        let path =
438            ccx.state.core.config.ensure_path_allowed(pathToStateJson, FsAccessKind::Write)?;
439        ccx.state.core.config.ensure_not_foundry_toml(&path)?;
440
441        let fork_id = ccx.active_fork_id();
442        let state = ccx.evm.state_mut();
443        let created_accounts = ccx.state.created_accounts(fork_id);
444
445        // Do not include system account or empty accounts in the dump.
446        let skip = |key: &Address| {
447            key == &CHEATCODE_ADDRESS
448                || key == &CALLER
449                || key == &HARDHAT_CONSOLE_ADDRESS
450                || key == &TEST_CONTRACT_ADDRESS
451                || key == &ccx.caller
452                || key == &ccx.state.core.config.evm_opts.sender
453        };
454
455        let accounts = ccx.backend.backend().lifecycle().loaded_state(state);
456        let mut alloc = BTreeMap::new();
457        for (address, slots) in accounts {
458            if skip(&address)
459                || state.account_info_untracked(&address)?.is_none_or(|info| info.is_empty())
460            {
461                continue;
462            }
463            alloc.insert(address, genesis_account(state, &address, slots)?);
464        }
465
466        let mut ordered_alloc = Vec::with_capacity(alloc.len());
467        for address in created_accounts {
468            if let Some(account) = alloc.remove(&address) {
469                ordered_alloc.push((address, account));
470            }
471        }
472        ordered_alloc.extend(alloc);
473
474        write_json_file(&path, &StateDump(&ordered_alloc))?;
475        Ok(Default::default())
476    }
477}
478
479impl Cheatcode for recordCall {
480    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
481        let Self {} = self;
482        ccx.state.recording_accesses = true;
483        ccx.state.accesses.clear();
484        Ok(Default::default())
485    }
486}
487
488impl Cheatcode for stopRecordCall {
489    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
490        ccx.state.recording_accesses = false;
491        Ok(Default::default())
492    }
493}
494
495impl Cheatcode for accessesCall {
496    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
497        let Self { target } = *self;
498        let result = (
499            ccx.state.accesses.reads.entry(target).or_default().as_slice(),
500            ccx.state.accesses.writes.entry(target).or_default().as_slice(),
501        );
502        Ok(result.abi_encode_params())
503    }
504}
505
506impl Cheatcode for registerSloadHookCall {
507    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
508        let Self { target, callback } = *self;
509        ccx.state.register_storage_load_hook(target, ccx.caller, callback.0);
510        Ok(Default::default())
511    }
512}
513
514impl Cheatcode for registerSstoreHookCall {
515    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
516        let Self { target, callback } = *self;
517        if ccx.state.has_mapping_storage_store_hooks(target) {
518            bail!("cannot register raw SSTORE hook: mapping SSTORE hooks already exist for target");
519        }
520        ccx.state.register_storage_store_hook(target, ccx.caller, callback.0);
521        Ok(Default::default())
522    }
523}
524
525impl Cheatcode for registerMappingSstoreHookCall {
526    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
527        let Self { target, rootSlot, callback } = *self;
528        if !ccx.state.register_mapping_storage_store_hook(target, rootSlot, ccx.caller, callback.0)
529        {
530            bail!("cannot register mapping SSTORE hook: raw SSTORE hook already exists for target");
531        }
532        Ok(Default::default())
533    }
534}
535
536impl Cheatcode for recordLogsCall {
537    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
538        let Self {} = self;
539        state.recorded_logs = Some(Default::default());
540        state.recorded_logs_generation += 1;
541        Ok(Default::default())
542    }
543}
544
545impl Cheatcode for getRecordedLogsCall {
546    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
547        let Self {} = self;
548        state.recorded_logs_generation += 1;
549        Ok(state.recorded_logs.replace(Default::default()).unwrap_or_default().abi_encode())
550    }
551}
552
553impl Cheatcode for getRecordedLogsJsonCall {
554    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
555        let Self {} = self;
556        state.recorded_logs_generation += 1;
557        let logs = state.recorded_logs.replace(Default::default()).unwrap_or_default();
558        let json_logs: Vec<_> = logs
559            .into_iter()
560            .map(|log| LogJson {
561                topics: log.topics.iter().map(|t| format!("{t}")).collect(),
562                data: hex::encode_prefixed(&log.data),
563                emitter: format!("{}", log.emitter),
564            })
565            .collect();
566        Ok(serde_json::to_string(&json_logs)?.abi_encode())
567    }
568}
569
570impl Cheatcode for pauseGasMeteringCall {
571    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
572        let Self {} = self;
573        ccx.state.gas_metering.paused = true;
574        Ok(Default::default())
575    }
576}
577
578impl Cheatcode for resumeGasMeteringCall {
579    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
580        let Self {} = self;
581        ccx.state.gas_metering.resume();
582        Ok(Default::default())
583    }
584}
585
586impl Cheatcode for resetGasMeteringCall {
587    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
588        let Self {} = self;
589        ccx.state.gas_metering.reset();
590        Ok(Default::default())
591    }
592}
593
594impl Cheatcode for lastCallGasCall {
595    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
596        let Self {} = self;
597        let Some(last_call_gas) = &ccx.state.gas_metering.last_call_gas else {
598            bail!("no external call was made yet");
599        };
600        Ok(last_call_gas.abi_encode())
601    }
602}
603
604impl Cheatcode for lastFrameGasCall {
605    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
606        let Self {} = self;
607        let Some(last_frame_gas) = &ccx.state.gas_metering.last_frame_gas else {
608            bail!("no external call or create was made yet");
609        };
610        Ok(last_frame_gas.abi_encode())
611    }
612}
613
614impl Cheatcode for getChainIdCall {
615    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
616        let Self {} = self;
617        Ok(U256::from(ccx.chain_id()).abi_encode())
618    }
619}
620
621impl Cheatcode for chainIdCall {
622    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
623        let Self { newChainId } = self;
624        ensure!(*newChainId <= U256::from(u64::MAX), "chain ID must be less than 2^64");
625        let chain_id = newChainId.to();
626        // `CHAINID` reads the new chain ID right away; transaction validation uses it from the
627        // next transaction on.
628        let fork_id = ccx.active_fork_id();
629        ccx.state.env_overrides.update(fork_id, |o| o.chain_id = Some(chain_id));
630        let mut env = evm_env(ccx.evm);
631        env.set_chain_id(chain_id);
632        let (evm, db) = ccx.evm_db_mut();
633        // A chain ID change is deferred to the next transaction while one is in flight.
634        db.set_env(evm, env, ExecutionPhase::InFlight);
635        Ok(Default::default())
636    }
637}
638
639impl Cheatcode for coinbaseCall {
640    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
641        let Self { newCoinbase } = self;
642        ccx.update_block(|block| block.beneficiary = *newCoinbase);
643        Ok(Default::default())
644    }
645}
646
647impl Cheatcode for difficultyCall {
648    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
649        let Self { newDifficulty } = self;
650        ensure!(
651            ccx.spec().into() < SpecId::MERGE,
652            "`difficulty` is not supported after the Paris hard fork, use `prevrandao` instead; \
653             see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
654        );
655        ccx.update_block(|block| block.difficulty = *newDifficulty);
656        Ok(Default::default())
657    }
658}
659
660impl Cheatcode for feeCall {
661    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
662        let Self { newBasefee } = self;
663        ensure!(*newBasefee <= U256::from(u64::MAX), "base fee must be less than 2^64");
664        let basefee: u64 = newBasefee.saturating_to();
665        // Always record the override so `BASEFEE` reads the cheatcode value
666        // even inside the synthetic isolation transaction (which zeroes
667        // `block.basefee` for fee-accounting). See `EnvOverrides`.
668        let fork_id = ccx.active_fork_id();
669        ccx.state.env_overrides.update(fork_id, |o| o.basefee = Some(basefee));
670        // Outside isolation, also mutate the real env to preserve the
671        // historical behavior other code paths rely on.
672        if !ccx.state.in_isolation_context {
673            ccx.update_block(|block| block.basefee = U256::from(basefee));
674        }
675        Ok(Default::default())
676    }
677}
678
679impl Cheatcode for prevrandao_0Call {
680    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
681        let Self { newPrevrandao } = self;
682        ensure!(
683            ccx.spec().into() >= SpecId::MERGE,
684            "`prevrandao` is not supported before the Paris hard fork, use `difficulty` instead; \
685             see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
686        );
687        ccx.update_block(|block| block.prevrandao = (*newPrevrandao).into());
688        Ok(Default::default())
689    }
690}
691
692impl Cheatcode for prevrandao_1Call {
693    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
694        let Self { newPrevrandao } = self;
695        ensure!(
696            ccx.spec().into() >= SpecId::MERGE,
697            "`prevrandao` is not supported before the Paris hard fork, use `difficulty` instead; \
698             see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
699        );
700        ccx.update_block(|block| block.prevrandao = *newPrevrandao);
701        Ok(Default::default())
702    }
703}
704
705impl Cheatcode for blobhashesCall {
706    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
707        let Self { hashes } = self;
708        ensure!(
709            ccx.spec().into() >= SpecId::CANCUN,
710            "`blobhashes` is not supported before the Cancun hard fork; \
711             see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
712        );
713        // The transaction environment is fixed for the running transaction, so `BLOBHASH` reads
714        // the cheatcode value through an override. See `EnvOverrides`.
715        let fork_id = ccx.active_fork_id();
716        ccx.state.env_overrides.update(fork_id, |o| o.blob_hashes = Some(hashes.clone()));
717        Ok(Default::default())
718    }
719}
720
721impl Cheatcode for getBlobhashesCall {
722    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
723        let Self {} = self;
724        ensure!(
725            ccx.spec().into() >= SpecId::CANCUN,
726            "`getBlobhashes` is not supported before the Cancun hard fork; \
727             see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
728        );
729        let fork_id = ccx.active_fork_id();
730        let hashes = ccx
731            .state
732            .env_overrides
733            .get(fork_id)
734            .and_then(|o| o.blob_hashes.clone())
735            .unwrap_or_else(|| ccx.tx_blob_hashes());
736        Ok(hashes.abi_encode())
737    }
738}
739
740impl Cheatcode for rollCall {
741    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
742        let Self { newHeight } = self;
743        let current_height = ccx.block_number();
744        if ccx.spec().into() >= SpecId::PRAGUE && *newHeight > current_height {
745            let mut block_number = forward_fill_start(current_height, *newHeight);
746            while block_number < *newHeight {
747                let block_hash = Host::block_hash(ccx.evm, &block_number).unwrap_or_default();
748                set_eip2935_blockhash(ccx.evm.state_mut(), block_number, block_hash)?;
749                block_number += U256::ONE;
750            }
751        }
752        ccx.update_block(|block| block.number = *newHeight);
753        Ok(Default::default())
754    }
755}
756
757impl Cheatcode for getBlockNumberCall {
758    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
759        let Self {} = self;
760        Ok(ccx.block_number().abi_encode())
761    }
762}
763
764impl Cheatcode for rollSlotCall {
765    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
766        ensure!(
767            ccx.spec().into() >= SpecId::AMSTERDAM,
768            "`rollSlot` is not supported before the Amsterdam hard fork; \
769             see EIP-7843: https://eips.ethereum.org/EIPS/eip-7843"
770        );
771        ccx.update_block(|block| block.slot_num = U256::from(self.newSlotNumber));
772        Ok(Default::default())
773    }
774}
775
776impl Cheatcode for getSlotNumberCall {
777    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
778        ensure!(
779            ccx.spec().into() >= SpecId::AMSTERDAM,
780            "`getSlotNumber` is not supported before the Amsterdam hard fork; \
781             see EIP-7843: https://eips.ethereum.org/EIPS/eip-7843"
782        );
783        Ok(ccx.slot_num().abi_encode())
784    }
785}
786
787impl Cheatcode for txGasPriceCall {
788    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
789        let Self { newGasPrice } = self;
790        ensure!(*newGasPrice <= U256::from(u64::MAX), "gas price must be less than 2^64");
791        let gas_price: u128 = newGasPrice.saturating_to();
792        // The transaction environment is fixed for the running transaction, so `GASPRICE` reads
793        // the cheatcode value through an override; fee accounting keeps the transaction's gas
794        // price. See `EnvOverrides`.
795        let fork_id = ccx.active_fork_id();
796        ccx.state.env_overrides.update(fork_id, |o| o.gas_price = Some(gas_price));
797        Ok(Default::default())
798    }
799}
800
801impl Cheatcode for warpCall {
802    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
803        let Self { newTimestamp } = self;
804        ccx.update_block(|block| block.timestamp = *newTimestamp);
805        Ok(Default::default())
806    }
807}
808
809impl Cheatcode for getBlockTimestampCall {
810    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
811        let Self {} = self;
812        Ok(ccx.timestamp().abi_encode())
813    }
814}
815
816impl Cheatcode for blobBaseFeeCall {
817    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
818        let Self { newBlobBaseFee } = self;
819        ensure!(
820            ccx.spec().into() >= SpecId::CANCUN,
821            "`blobBaseFee` is not supported before the Cancun hard fork; \
822             see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
823        );
824
825        ensure!(*newBlobBaseFee <= U256::from(u128::MAX), "blob base fee must be less than 2^128");
826        ccx.update_block(|block| block.blob_basefee = *newBlobBaseFee);
827        Ok(Default::default())
828    }
829}
830
831impl Cheatcode for getBlobBaseFeeCall {
832    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
833        let Self {} = self;
834        Ok(ccx.evm.block().blob_basefee.abi_encode())
835    }
836}
837
838impl Cheatcode for dealCall {
839    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
840        let Self { account: address, newBalance: new_balance } = *self;
841        TypesFor::<FEN>::sync_transaction(ccx.evm);
842        let old_balance = {
843            let mut account = ccx.evm.state_mut().account(&address)?;
844            let old_balance = account.balance();
845            account.warm();
846            account.set_balance(new_balance);
847            old_balance
848        };
849        // The balance survives reverts of the enclosing calls.
850        let write =
851            PersistentWrite::balance(address, old_balance, new_balance).with_replay(Replay::Set);
852        ccx.state.record_persistent(ccx.caller_depth(), ccx.evm.state(), [write]);
853        TypesFor::<FEN>::refresh_transaction(ccx.evm);
854        Ok(Default::default())
855    }
856}
857
858impl Cheatcode for etchCall {
859    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
860        let Self { target, newRuntimeBytecode } = self;
861        ccx.ensure_not_precompile(target)?;
862        let bytecode = Bytecode::new_raw_checked(newRuntimeBytecode.clone())
863            .map_err(|e| fmt_err!("failed to create bytecode: {e}"))?;
864        let is_forked = ccx.is_forked_mode();
865        let features = ccx.evm.version().features;
866        let state = ccx.evm.state_mut();
867        // Clear synthetic history only in local mode. On forks, preserve storage as for other
868        // etched accounts; clearing the ring can require one synchronous RPC read per uncached
869        // slot.
870        if *target == HISTORY_STORAGE_ADDRESS
871            && !is_forked
872            && bytecode.hash_slow() != keccak256(&HISTORY_STORAGE_CODE)
873            && state.account(target)?.code_hash() == keccak256(&HISTORY_STORAGE_CODE)
874        {
875            clear_eip2935_history_storage(state, features)?;
876        }
877        let mut account = state.account(target)?;
878        account.warm();
879        account.set_code_slow(bytecode);
880        Ok(Default::default())
881    }
882}
883
884impl Cheatcode for resetNonceCall {
885    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
886        let Self { account: address } = *self;
887        let mut account = ccx.evm.state_mut().account(&address)?;
888        // Per EIP-161, contract nonces start at 1. EOAs, including EIP-7702 delegated ones, start
889        // at 0.
890        let is_eoa = account.is_empty_code_hash()
891            || account.code_hash().is_zero()
892            || account.load_code()?.is_eip7702();
893        drop(account);
894        let nonce = if is_eoa { 0 } else { 1 };
895        debug!(target: "cheatcodes", nonce, "reset");
896        set_persistent_nonce(ccx, address, nonce)
897    }
898}
899
900impl Cheatcode for setNonceCall {
901    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
902        let Self { account, newNonce } = *self;
903        // nonce must increment only
904        let current = ccx.evm.state_mut().account(&account)?.nonce();
905        ensure!(
906            newNonce >= current,
907            "new nonce ({newNonce}) must be strictly equal to or higher than the \
908             account's current nonce ({current})"
909        );
910        set_persistent_nonce(ccx, account, newNonce)
911    }
912}
913
914impl Cheatcode for setNonceUnsafeCall {
915    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
916        let Self { account, newNonce } = *self;
917        set_persistent_nonce(ccx, account, newNonce)
918    }
919}
920
921impl Cheatcode for storeCall {
922    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
923        let Self { target, slot, value } = *self;
924        ccx.ensure_not_precompile(&target)?;
925        let state = ccx.evm.state_mut();
926        touch_account(state, target)?;
927        warm_storage_slot(state, &target, slot.into())
928            .map_err(|e| fmt_err!("failed to store storage slot: {e}"))?
929            .set(value.into());
930        ccx.state.mark_arbitrary_storage_slot_explicit(target, slot.into());
931        // A `fail()` fails the call where it is made, like an assertion.
932        if target == CHEATCODE_ADDRESS && slot == B256::from(GLOBAL_FAIL_SLOT) && !value.is_zero() {
933            if let Some(trace) = &mut ccx.state.failure_trace {
934                trace.record_assertion(Self::SELECTOR, "", None);
935            }
936            if let Some(provenance) = &mut ccx.state.failure_provenance {
937                provenance.pending_assertion = Some(keccak256(Self::SELECTOR));
938            }
939        }
940        Ok(Default::default())
941    }
942}
943
944impl Cheatcode for storeTransientCall {
945    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
946        let Self { target, slot, value } = *self;
947        ccx.ensure_not_precompile(&target)?;
948        ccx.evm.state_mut().tstore(&target, &slot.into(), &value.into());
949        Ok(Default::default())
950    }
951}
952
953impl Cheatcode for setTip20LogoURICall {
954    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
955        let Self { token, newLogoURI } = self;
956        set_tip20_logo_uri(ccx, token, newLogoURI)
957    }
958}
959
960impl Cheatcode for setLogoURICall {
961    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
962        let Self { token, newLogoURI } = self;
963        set_tip20_logo_uri(ccx, token, newLogoURI)
964    }
965}
966
967impl Cheatcode for coolCall {
968    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
969        let Self { target } = self;
970        let slots = ccx.db().lifecycle().loaded_storage(ccx.evm.state(), target);
971        // Precompiles and the addresses the transaction warmed for its coinbase, access list and
972        // chain stay warm. The rest of the transaction-base
973        // warmth, such as the recipient, is cooled.
974        let keep = ccx.is_precompile(target) || ccx.state.tx_warm_addresses.contains(target);
975        if !keep {
976            let (evm, db) = ccx.evm_db_mut();
977            db.remove_prewarm(evm.state_mut(), target);
978        }
979        let state = ccx.evm.state_mut();
980        state.set_account_warm(target, false);
981        for slot in slots {
982            state.set_storage_warm(target, slot, false);
983        }
984        Ok(Default::default())
985    }
986}
987
988impl Cheatcode for accessListCall {
989    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
990        let Self { access } = self;
991        let access_list = access
992            .iter()
993            .map(|item| {
994                let keys = item.storageKeys.iter().map(|key| B256::from(*key)).collect_vec();
995                alloy_rpc_types::AccessListItem { address: item.target, storage_keys: keys }
996            })
997            .collect_vec();
998        state.access_list = Some(alloy_rpc_types::AccessList::from(access_list));
999        Ok(Default::default())
1000    }
1001}
1002
1003impl Cheatcode for noAccessListCall {
1004    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1005        let Self {} = self;
1006        // Set to empty option in order to override previous applied access list.
1007        if state.access_list.is_some() {
1008            state.access_list = Some(alloy_rpc_types::AccessList::default());
1009        }
1010        Ok(Default::default())
1011    }
1012}
1013
1014impl Cheatcode for warmSlotCall {
1015    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1016        let Self { target, slot } = *self;
1017        ccx.evm.state_mut().set_storage_warm(&target, slot.into(), true);
1018        Ok(Default::default())
1019    }
1020}
1021
1022impl Cheatcode for coolSlotCall {
1023    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1024        let Self { target, slot } = *self;
1025        ccx.evm.state_mut().set_storage_warm(&target, slot.into(), false);
1026        Ok(Default::default())
1027    }
1028}
1029
1030impl Cheatcode for isIsolateModeCall {
1031    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1032        let Self {} = self;
1033        Ok(state.config.isolate.abi_encode())
1034    }
1035}
1036
1037impl Cheatcode for readCallersCall {
1038    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1039        let Self {} = self;
1040        read_callers(ccx.state, &ccx.tx_caller(), ccx.depth())
1041    }
1042}
1043
1044impl Cheatcode for snapshotValue_0Call {
1045    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1046        let Self { name, value } = self;
1047        inner_value_snapshot(ccx, None, Some(name.clone()), value.to_string())
1048    }
1049}
1050
1051impl Cheatcode for snapshotValue_1Call {
1052    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1053        let Self { group, name, value } = self;
1054        inner_value_snapshot(ccx, Some(group.clone()), Some(name.clone()), value.to_string())
1055    }
1056}
1057
1058impl Cheatcode for snapshotGasLastCall_0Call {
1059    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1060        let Self { name } = self;
1061        if ccx.state.gas_metering.last_call_gas.is_none() {
1062            bail!("no external call was made yet");
1063        }
1064        let gas_used = ccx.state.gas_metering.last_call_snapshot_gas_used;
1065        inner_last_gas_snapshot(ccx, None, Some(name.clone()), gas_used)
1066    }
1067}
1068
1069impl Cheatcode for snapshotGasLastCall_1Call {
1070    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1071        let Self { name, group } = self;
1072        if ccx.state.gas_metering.last_call_gas.is_none() {
1073            bail!("no external call was made yet");
1074        }
1075        let gas_used = ccx.state.gas_metering.last_call_snapshot_gas_used;
1076        inner_last_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()), gas_used)
1077    }
1078}
1079
1080impl Cheatcode for snapshotGasLastFrame_0Call {
1081    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1082        let Self { name } = self;
1083        if ccx.state.gas_metering.last_frame_gas.is_none() {
1084            bail!("no external call or create was made yet");
1085        }
1086        let gas_used = ccx.state.gas_metering.last_frame_snapshot_gas_used;
1087        inner_last_gas_snapshot(ccx, None, Some(name.clone()), gas_used)
1088    }
1089}
1090
1091impl Cheatcode for snapshotGasLastFrame_1Call {
1092    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1093        let Self { name, group } = self;
1094        if ccx.state.gas_metering.last_frame_gas.is_none() {
1095            bail!("no external call or create was made yet");
1096        }
1097        let gas_used = ccx.state.gas_metering.last_frame_snapshot_gas_used;
1098        inner_last_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()), gas_used)
1099    }
1100}
1101
1102impl Cheatcode for startSnapshotGas_0Call {
1103    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1104        let Self { name } = self;
1105        inner_start_gas_snapshot(ccx, None, Some(name.clone()))
1106    }
1107}
1108
1109impl Cheatcode for startSnapshotGas_1Call {
1110    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1111        let Self { group, name } = self;
1112        inner_start_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()))
1113    }
1114}
1115
1116impl Cheatcode for stopSnapshotGas_0Call {
1117    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1118        let Self {} = self;
1119        inner_stop_gas_snapshot(ccx, None, None)
1120    }
1121}
1122
1123impl Cheatcode for stopSnapshotGas_1Call {
1124    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1125        let Self { name } = self;
1126        inner_stop_gas_snapshot(ccx, None, Some(name.clone()))
1127    }
1128}
1129
1130impl Cheatcode for stopSnapshotGas_2Call {
1131    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1132        let Self { group, name } = self;
1133        inner_stop_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()))
1134    }
1135}
1136
1137// Deprecated in favor of `snapshotStateCall`
1138impl Cheatcode for snapshotCall {
1139    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1140        let Self {} = self;
1141        inner_snapshot_state(ccx)
1142    }
1143}
1144
1145impl Cheatcode for snapshotStateCall {
1146    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1147        let Self {} = self;
1148        inner_snapshot_state(ccx)
1149    }
1150}
1151
1152// Deprecated in favor of `revertToStateCall`
1153impl Cheatcode for revertToCall {
1154    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1155        let Self { snapshotId } = self;
1156        inner_revert_to_state(ccx, *snapshotId)
1157    }
1158}
1159
1160impl Cheatcode for revertToStateCall {
1161    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1162        let Self { snapshotId } = self;
1163        inner_revert_to_state(ccx, *snapshotId)
1164    }
1165}
1166
1167// Deprecated in favor of `revertToStateAndDeleteCall`
1168impl Cheatcode for revertToAndDeleteCall {
1169    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1170        let Self { snapshotId } = self;
1171        inner_revert_to_state_and_delete(ccx, *snapshotId)
1172    }
1173}
1174
1175impl Cheatcode for revertToStateAndDeleteCall {
1176    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1177        let Self { snapshotId } = self;
1178        inner_revert_to_state_and_delete(ccx, *snapshotId)
1179    }
1180}
1181
1182// Deprecated in favor of `deleteStateSnapshotCall`
1183impl Cheatcode for deleteSnapshotCall {
1184    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1185        let Self { snapshotId } = self;
1186        let result = ccx.db_mut().delete_state_snapshot(*snapshotId);
1187        ccx.state.env_overrides.delete_snapshot(*snapshotId);
1188        ccx.state.fork_block_number_override_snapshots.remove(snapshotId);
1189        ccx.state.delete_created_accounts_snapshot(*snapshotId);
1190        Ok(result.abi_encode())
1191    }
1192}
1193
1194impl Cheatcode for deleteStateSnapshotCall {
1195    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1196        let Self { snapshotId } = self;
1197        let result = ccx.db_mut().delete_state_snapshot(*snapshotId);
1198        ccx.state.env_overrides.delete_snapshot(*snapshotId);
1199        ccx.state.fork_block_number_override_snapshots.remove(snapshotId);
1200        ccx.state.delete_created_accounts_snapshot(*snapshotId);
1201        Ok(result.abi_encode())
1202    }
1203}
1204
1205// Deprecated in favor of `deleteStateSnapshotsCall`
1206impl Cheatcode for deleteSnapshotsCall {
1207    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1208        let Self {} = self;
1209        ccx.db_mut().delete_state_snapshots();
1210        ccx.state.env_overrides.clear_snapshots();
1211        ccx.state.fork_block_number_override_snapshots.clear();
1212        ccx.state.clear_created_accounts_snapshots();
1213        Ok(Default::default())
1214    }
1215}
1216
1217impl Cheatcode for deleteStateSnapshotsCall {
1218    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1219        let Self {} = self;
1220        ccx.db_mut().delete_state_snapshots();
1221        ccx.state.env_overrides.clear_snapshots();
1222        ccx.state.fork_block_number_override_snapshots.clear();
1223        ccx.state.clear_created_accounts_snapshots();
1224        Ok(Default::default())
1225    }
1226}
1227
1228impl Cheatcode for startStateDiffRecordingCall {
1229    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1230        let Self {} = self;
1231        ccx.state.start_state_diff_recording();
1232        // Enable mapping recording to track mapping slot accesses
1233        ccx.state.core.mapping_slots.get_or_insert_default();
1234        Ok(Default::default())
1235    }
1236}
1237
1238impl Cheatcode for stopAndReturnStateDiffCall {
1239    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1240        let Self {} = self;
1241        get_state_diff(ccx.state)
1242    }
1243}
1244
1245impl Cheatcode for getStateDiffCall {
1246    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1247        let mut diffs = String::new();
1248        let state_diffs = get_recorded_state_diffs(ccx);
1249        for (address, state_diffs) in state_diffs {
1250            diffs.push_str(&format!("{address}\n"));
1251            diffs.push_str(&format!("{state_diffs}\n"));
1252        }
1253        Ok(diffs.abi_encode())
1254    }
1255}
1256
1257impl Cheatcode for getStateDiffJsonCall {
1258    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1259        let state_diffs = get_recorded_state_diffs(ccx);
1260        Ok(serde_json::to_string(&state_diffs)?.abi_encode())
1261    }
1262}
1263
1264impl Cheatcode for getStorageSlotsCall {
1265    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1266        let Self { target, variableName } = self;
1267
1268        let storage_layout = contract_storage_layout(ccx, *target)?;
1269        let (storage, storage_type) = find_storage_variable(&storage_layout, variableName)?;
1270
1271        if storage_type.encoding == ENCODING_MAPPING || storage_type.encoding == ENCODING_DYN_ARRAY
1272        {
1273            return Err(fmt_err!(
1274                "cannot get storage slots for variables with mapping or dynamic array types"
1275            ));
1276        }
1277
1278        let slot = U256::from_str(&storage.slot).map_err(|_| {
1279            fmt_err!("invalid slot {} format for variable {variableName}", storage.slot)
1280        })?;
1281
1282        let mut slots = Vec::new();
1283
1284        // Always push the base slot
1285        slots.push(slot);
1286
1287        if storage_type.encoding == ENCODING_INPLACE {
1288            // For inplace encoding, calculate the number of slots needed
1289            let num_bytes = U256::from_str(&storage_type.number_of_bytes).map_err(|_| {
1290                fmt_err!(
1291                    "invalid number_of_bytes {} for variable {variableName}",
1292                    storage_type.number_of_bytes
1293                )
1294            })?;
1295            let num_slots = num_bytes.div_ceil(U256::from(32));
1296            let num_slots = usize::try_from(num_slots).map_err(|_| {
1297                fmt_err!("number_of_bytes {} exceeds host usize", storage_type.number_of_bytes)
1298            })?;
1299
1300            // Start from 1 since base slot is already added
1301            for i in 1..num_slots {
1302                slots.push(slot + U256::from(i));
1303            }
1304        }
1305
1306        if storage_type.encoding == ENCODING_BYTES {
1307            // Try to check if it's a long bytes/string by reading the current storage
1308            // value
1309            if let Ok(value) =
1310                warm_storage_slot(ccx.evm.state_mut(), target, slot).map(|s| s.current())
1311            {
1312                let value_bytes = value.to_be_bytes::<32>();
1313                let length_byte = value_bytes[31];
1314                // Check if it's a long bytes/string (LSB is 1)
1315                if length_byte & 1 == 1 {
1316                    // Calculate data slots for long bytes/string
1317                    let length: U256 = value >> 1;
1318                    let length = usize::try_from(length)
1319                        .map_err(|_| fmt_err!("long bytes/string length exceeds host usize"))?;
1320                    let num_data_slots = length.div_ceil(32);
1321                    let data_start = Into::<U256>::into(keccak256(B256::from(slot).0));
1322
1323                    for i in 0..num_data_slots {
1324                        slots.push(data_start + U256::from(i));
1325                    }
1326                }
1327            }
1328        }
1329
1330        Ok(slots.abi_encode())
1331    }
1332}
1333
1334impl Cheatcode for getStorageSlotCall {
1335    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1336        let Self { target, variableName } = self;
1337
1338        let storage_layout = contract_storage_layout(ccx, *target)?;
1339        let (storage, storage_type) = find_storage_variable(&storage_layout, variableName)?;
1340
1341        let slot = U256::from_str(&storage.slot).map_err(|_| {
1342            fmt_err!("invalid slot {} format for variable {variableName}", storage.slot)
1343        })?;
1344        let offset = U256::try_from(storage.offset).map_err(|_| {
1345            fmt_err!("invalid offset {} for variable {variableName}", storage.offset)
1346        })?;
1347        let number_of_bytes = U256::from_str(&storage_type.number_of_bytes).map_err(|_| {
1348            fmt_err!(
1349                "invalid number_of_bytes {} for variable {variableName}",
1350                storage_type.number_of_bytes
1351            )
1352        })?;
1353
1354        Ok((slot, offset, number_of_bytes).abi_encode_params())
1355    }
1356}
1357
1358impl Cheatcode for getStorageAccessesCall {
1359    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1360        let mut storage_accesses = Vec::new();
1361
1362        for account_access in ccx.state.recorded_account_diffs() {
1363            storage_accesses.extend(account_access.storageAccesses.clone());
1364        }
1365
1366        Ok(storage_accesses.abi_encode())
1367    }
1368}
1369
1370impl Cheatcode for broadcastRawTransactionCall {
1371    fn apply_full<FEN: FoundryEvmNetwork>(
1372        &self,
1373        ccx: &mut CheatsCtxt<'_, '_, FEN>,
1374        executor: &mut dyn CheatcodesExecutor<FEN>,
1375    ) -> Result {
1376        let tx = TxEnvelopeFor::<FEN>::decode(&mut self.data.as_ref())
1377            .map_err(|err| fmt_err!("failed to decode RLP-encoded transaction: {err}"))?;
1378
1379        let sender =
1380            tx.recover_signer().map_err(|err| fmt_err!("failed to recover signer: {err}"))?;
1381        let from = sender;
1382        let contract_address = if tx.kind().is_create() {
1383            let mut account = ccx.evm.state_mut().account(&sender)?;
1384            account.warm();
1385            Some(sender.create(account.nonce()))
1386        } else {
1387            None
1388        };
1389
1390        let evm_tx = TypesFor::<FEN>::evm_tx(tx.clone(), sender, TxPayload::Signed)?;
1391        let overrides = ccx.state.env_overrides.get(ccx.active_fork_id());
1392        let chain_id = overrides.and_then(|o| o.chain_id);
1393        let custom_env = chain_id.is_some()
1394            || ccx.state.isolation_env.is_some()
1395            || ccx.spec() != ccx.evm.config_spec_id();
1396        let env = custom_env.then(|| {
1397            let mut env = ccx.evm_env();
1398            // Inside an isolated call, the transaction pays fees as in the transaction the call
1399            // runs in, with the requested spec's gas schedule and validation rules.
1400            if let Some(outer) = &ccx.state.isolation_env {
1401                env.version =
1402                    EvmFactoryFor::<FEN>::default().env_with_spec(*outer, env.spec).version;
1403                env.block.basefee = overrides
1404                    .and_then(|o| o.basefee_override())
1405                    .map_or(outer.block.basefee, U256::from);
1406            }
1407            // The transaction validates with a chain ID `vm.chainId` set in the running one.
1408            if let Some(chain_id) = chain_id {
1409                env.set_chain_id(chain_id);
1410            }
1411            env
1412        });
1413        let previous = enter_tx_warm_addresses(
1414            ccx.state,
1415            &env.unwrap_or_else(|| ccx.evm_env()),
1416            tx.access_list(),
1417        );
1418        let result = executor.transact_from_tx(
1419            ccx.state,
1420            ccx.backend,
1421            ccx.evm,
1422            ccx.depth as u16,
1423            &evm_tx,
1424            env,
1425        );
1426        ccx.state.tx_warm_addresses = previous;
1427        let _ = result?;
1428        ccx.state.state_epoch += 1;
1429
1430        if ccx.state.broadcast.is_some() {
1431            ccx.state.broadcastable_transactions.push_back(BroadcastableTransaction {
1432                rpc: ccx.active_fork_url(),
1433                transaction: TransactionMaybeSigned::Signed { tx, from },
1434                contract_address,
1435            });
1436        }
1437
1438        Ok(Default::default())
1439    }
1440}
1441
1442impl Cheatcode for setBlockhashCall {
1443    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1444        let Self { blockNumber, blockHash } = *self;
1445        ensure!(blockNumber <= U256::from(u64::MAX), "blockNumber must be less than 2^64");
1446        ensure!(
1447            blockNumber <= ccx.block_number(),
1448            "block number must be less than or equal to the current block number"
1449        );
1450
1451        let (evm, db) = ccx.evm_db_mut();
1452        db.set_blockhash(blockNumber, blockHash, evm);
1453        let current_block = ccx.block_number();
1454        if ccx.spec().into() >= SpecId::PRAGUE
1455            && blockNumber < current_block
1456            && current_block - blockNumber <= U256::from(HISTORY_SERVE_WINDOW)
1457        {
1458            set_eip2935_blockhash(ccx.evm.state_mut(), blockNumber, blockHash)?;
1459        }
1460
1461        Ok(Default::default())
1462    }
1463}
1464
1465impl Cheatcode for executeTransactionCall {
1466    fn apply_full<FEN: FoundryEvmNetwork>(
1467        &self,
1468        ccx: &mut CheatsCtxt<'_, '_, FEN>,
1469        executor: &mut dyn CheatcodesExecutor<FEN>,
1470    ) -> Result {
1471        // Block in script contexts.
1472        if let Some(ctx) = FORGE_CONTEXT.get()
1473            && *ctx == ForgeContext::ScriptGroup
1474        {
1475            return Err(fmt_err!("executeTransaction is not allowed in forge script"));
1476        }
1477
1478        // Decode the RLP-encoded signed transaction.
1479        let tx = TxEnvelopeFor::<FEN>::decode(&mut self.rawTx.as_ref())
1480            .map_err(|err| fmt_err!("failed to decode RLP-encoded transaction: {err}"))?;
1481
1482        ensure!(
1483            tx.ty() != 0x79,
1484            "EIP-8130 transactions are not supported by vm.executeTransaction"
1485        );
1486
1487        let sender =
1488            tx.recover_signer().map_err(|err| fmt_err!("failed to recover signer: {err}"))?;
1489        let created_address = tx.kind().is_create().then(|| sender.create(tx.nonce()));
1490        let access_list = tx.access_list().cloned();
1491        let value = tx.value();
1492        let tx = TypesFor::<FEN>::evm_tx(tx, sender, TxPayload::Signed)?;
1493
1494        // Execute in the running environment with realistic validation: no base fee or fee
1495        // payment, nonce checks, the spec's transaction gas limit cap, and an initcode limit
1496        // derived from the configured code size limit rather than the unlimited one used for
1497        // test contracts.
1498        let mut env = ccx.evm_env();
1499        env.block.basefee = U256::ZERO;
1500        env.set_feature(EvmFeatures::FEE_CHARGE, false);
1501        env.set_feature(EvmFeatures::NONCE_CHECK, true);
1502        // The transaction pays no fees, so the sender only needs to afford the value.
1503        env.set_feature(EvmFeatures::BALANCE_CHECK, false);
1504        env.set_feature(EvmFeatures::BALANCE_TOP_UP, false);
1505        let balance = ccx
1506            .evm
1507            .state_mut()
1508            .account_info_untracked(&sender)?
1509            .map_or(U256::ZERO, |account| account.balance);
1510        if balance < value {
1511            let err = transaction_error(HandlerError::InsufficientFunds { fee: value, balance });
1512            return Err(fmt_err!("transaction execution failed: {err}"));
1513        }
1514        // The nested transaction validates with a chain ID `vm.chainId` set in the running one.
1515        if let Some(chain_id) =
1516            ccx.state.env_overrides.get(ccx.active_fork_id()).and_then(|o| o.chain_id)
1517        {
1518            env.set_chain_id(chain_id);
1519        }
1520        let default_version = EvmFactoryFor::<FEN>::default().version(env.spec, env.chain_id());
1521        env.version.tx_gas_limit_cap = default_version.tx_gas_limit_cap;
1522        env.version.tx_total_gas_cap = default_version.tx_total_gas_cap;
1523        env.version.max_initcode_size = match ccx.state.core.config.evm_opts.env.code_size_limit {
1524            Some(code_size_limit) => code_size_limit.saturating_mul(2),
1525            None => default_version.max_initcode_size,
1526        };
1527
1528        if let Some(address) = created_address {
1529            let fork_id = ccx.active_fork_id();
1530            ccx.state.record_created_account(fork_id, address);
1531        }
1532
1533        let previous = enter_tx_warm_addresses(ccx.state, &env, access_list.as_ref());
1534        let res = executor.nested_transaction(
1535            ccx.state,
1536            ccx.backend,
1537            ccx.evm,
1538            ccx.depth as u16,
1539            &tx,
1540            Some(env),
1541        );
1542        ccx.state.tx_warm_addresses = previous;
1543        let res = res.map_err(|e| fmt_err!("transaction execution failed: {e}"))?;
1544
1545        // Return output bytes.
1546        if !res.status {
1547            if res.stop.is_revert() {
1548                return Err(fmt_err!(
1549                    "transaction reverted: {}",
1550                    hex::encode_prefixed(&res.output)
1551                ));
1552            }
1553            return Err(fmt_err!("transaction halted: {:?}", res.stop));
1554        }
1555
1556        Ok(res.output.abi_encode())
1557    }
1558}
1559
1560impl Cheatcode for startDebugTraceRecordingCall {
1561    fn apply_full<FEN: FoundryEvmNetwork>(
1562        &self,
1563        ccx: &mut CheatsCtxt<'_, '_, FEN>,
1564        executor: &mut dyn CheatcodesExecutor<FEN>,
1565    ) -> Result {
1566        let Some(tracer) = executor.tracing_inspector() else {
1567            return Err(Error::from("no tracer initiated, consider adding -vvv flag"));
1568        };
1569
1570        if ccx.state.record_debug_steps_info.is_some() {
1571            bail!("debug trace recording was already started");
1572        }
1573
1574        let mut info = RecordDebugStepInfo {
1575            // will be updated later
1576            start_node_idx: 0,
1577            // keep the original config to revert back later
1578            original_tracer_config: *tracer.config(),
1579        };
1580
1581        // turn on tracer debug configuration for recording
1582        *tracer.config_mut() =
1583            TraceRequirements::none().with_debug(true).into_config().expect("cannot be None");
1584
1585        // track where the recording starts
1586        if let Some(last_node) = tracer.traces().nodes().last() {
1587            info.start_node_idx = last_node.idx;
1588        }
1589
1590        ccx.state.record_debug_steps_info = Some(info);
1591        Ok(Default::default())
1592    }
1593}
1594
1595impl Cheatcode for stopAndReturnDebugTraceRecordingCall {
1596    fn apply_full<FEN: FoundryEvmNetwork>(
1597        &self,
1598        ccx: &mut CheatsCtxt<'_, '_, FEN>,
1599        executor: &mut dyn CheatcodesExecutor<FEN>,
1600    ) -> Result {
1601        let Some(tracer) = executor.tracing_inspector() else {
1602            return Err(Error::from("no tracer initiated, consider adding -vvv flag"));
1603        };
1604
1605        let Some(record_info) = ccx.state.record_debug_steps_info else {
1606            return Err(Error::from("nothing recorded"));
1607        };
1608
1609        // Use the trace nodes to flatten the call trace
1610        let root = tracer.traces();
1611        let steps = flatten_call_trace(0, root, record_info.start_node_idx);
1612
1613        let debug_steps: Vec<DebugStep> =
1614            steps.iter().map(|step| convert_call_trace_ctx_to_debug_step(step)).collect();
1615        // Free up memory by clearing the steps if they are not recorded outside of cheatcode usage.
1616        if !record_info.original_tracer_config.record_steps {
1617            tracer.traces_mut().nodes_mut().iter_mut().for_each(|node| {
1618                node.trace.steps = Vec::new();
1619                node.logs = Vec::new();
1620                node.ordering = Vec::new();
1621            });
1622        }
1623
1624        // Revert the tracer config to the one before recording
1625        tracer.update_config(|_config| record_info.original_tracer_config);
1626
1627        // Clean up the recording info
1628        ccx.state.record_debug_steps_info = None;
1629
1630        Ok(debug_steps.abi_encode())
1631    }
1632}
1633
1634impl Cheatcode for setEvmVersionCall {
1635    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1636        let Self { evm } = self;
1637        let spec_id = evm_spec_id_from_str(evm)
1638            .ok_or_else(|| Error::from(format!("invalid evm version {evm}")))?;
1639        ccx.state.execution_evm_version = Some(spec_id);
1640        Ok(Default::default())
1641    }
1642}
1643
1644impl Cheatcode for getEvmVersionCall {
1645    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1646        let spec = ccx.spec();
1647        Ok(spec.evm_version_name().to_lowercase().abi_encode())
1648    }
1649}
1650
1651pub(super) fn get_nonce<FEN: FoundryEvmNetwork>(
1652    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1653    address: &Address,
1654) -> Result {
1655    let mut account = ccx.evm.state_mut().account(address)?;
1656    account.warm();
1657    let nonce = account.nonce();
1658    Ok(nonce.abi_encode())
1659}
1660
1661fn inner_snapshot_state<FEN: FoundryEvmNetwork>(ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1662    let (evm, db) = ccx.evm_db_mut();
1663    let id = db.snapshot_state(evm);
1664    let fork_id = ccx.active_fork_id();
1665    ccx.state.env_overrides.save_snapshot(id);
1666    ccx.state.fork_block_number_override_snapshots.insert(id, ccx.state.fork_block_number_override);
1667    ccx.state.snapshot_created_accounts(id, fork_id);
1668    ccx.state.persistent_write_snapshots.insert(id, ccx.state.persistent_writes.len());
1669    Ok(id.abi_encode())
1670}
1671
1672/// Zeroes the restored base fee again inside an isolated call, whose fee accounting runs without
1673/// one, and keeps the restored value visible to `BASEFEE`.
1674fn restore_isolation_fee_accounting<FEN: FoundryEvmNetwork>(ccx: &mut CheatsCtxt<'_, '_, FEN>) {
1675    if !ccx.state.in_isolation_context {
1676        return;
1677    }
1678
1679    let basefee = ccx.basefee();
1680    if basefee != 0 {
1681        let fork_id = ccx.active_fork_id();
1682        ccx.state.env_overrides.update(fork_id, |o| {
1683            o.implicit_basefee.get_or_insert(basefee);
1684        });
1685        ccx.update_block(|block| block.basefee = U256::ZERO);
1686    }
1687}
1688
1689fn inner_revert_to_state<FEN: FoundryEvmNetwork>(
1690    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1691    snapshot_id: U256,
1692) -> Result {
1693    let fork_id = ccx.active_fork_id();
1694    let (evm, db) = ccx.evm_db_mut();
1695    if let Some(replaced) = db.revert_state(
1696        snapshot_id,
1697        evm,
1698        RevertStateSnapshotAction::RevertKeep,
1699        ExecutionPhase::InFlight,
1700    ) {
1701        let switched = ccx.active_fork_id() != fork_id;
1702        ccx.state.restore_persistent_writes(snapshot_id, replaced, false, switched);
1703        // A restore can make a different path look like the recorded one, so its identity is
1704        // unknown.
1705        if let Some(trace) = &mut ccx.state.failure_trace {
1706            trace.unidentified = true;
1707        }
1708        // `RevertKeep` keeps the backend snapshot alive for further
1709        // reverts, so keep our matching env-overrides copy too.
1710        ccx.state.env_overrides.restore_snapshot(snapshot_id, false);
1711        if let Some(&fork_block_number) =
1712            ccx.state.fork_block_number_override_snapshots.get(&snapshot_id)
1713        {
1714            ccx.state.fork_block_number_override = fork_block_number;
1715        }
1716        ccx.state.revert_created_accounts(snapshot_id, false);
1717        restore_isolation_fee_accounting(ccx);
1718        Ok(true.abi_encode())
1719    } else {
1720        Ok(false.abi_encode())
1721    }
1722}
1723
1724fn inner_revert_to_state_and_delete<FEN: FoundryEvmNetwork>(
1725    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1726    snapshot_id: U256,
1727) -> Result {
1728    let fork_id = ccx.active_fork_id();
1729    let (evm, db) = ccx.evm_db_mut();
1730    if let Some(replaced) = db.revert_state(
1731        snapshot_id,
1732        evm,
1733        RevertStateSnapshotAction::RevertRemove,
1734        ExecutionPhase::InFlight,
1735    ) {
1736        let switched = ccx.active_fork_id() != fork_id;
1737        ccx.state.restore_persistent_writes(snapshot_id, replaced, true, switched);
1738        if let Some(trace) = &mut ccx.state.failure_trace {
1739            trace.unidentified = true;
1740        }
1741        ccx.state.env_overrides.restore_snapshot(snapshot_id, true);
1742        if let Some(fork_block_number) =
1743            ccx.state.fork_block_number_override_snapshots.remove(&snapshot_id)
1744        {
1745            ccx.state.fork_block_number_override = fork_block_number;
1746        }
1747        ccx.state.revert_created_accounts(snapshot_id, true);
1748        restore_isolation_fee_accounting(ccx);
1749        Ok(true.abi_encode())
1750    } else {
1751        Ok(false.abi_encode())
1752    }
1753}
1754
1755fn inner_value_snapshot<FEN: FoundryEvmNetwork>(
1756    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1757    group: Option<String>,
1758    name: Option<String>,
1759    value: String,
1760) -> Result {
1761    let (group, name) = derive_snapshot_name(ccx, group, name)?;
1762
1763    ccx.state.gas_snapshots.entry(group).or_default().insert(name, value);
1764
1765    Ok(Default::default())
1766}
1767
1768fn inner_last_gas_snapshot<FEN: FoundryEvmNetwork>(
1769    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1770    group: Option<String>,
1771    name: Option<String>,
1772    value: u64,
1773) -> Result {
1774    let (group, name) = derive_snapshot_name(ccx, group, name)?;
1775
1776    ccx.state.gas_snapshots.entry(group).or_default().insert(name, value.to_string());
1777
1778    Ok(value.abi_encode())
1779}
1780
1781fn inner_start_gas_snapshot<FEN: FoundryEvmNetwork>(
1782    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1783    group: Option<String>,
1784    name: Option<String>,
1785) -> Result {
1786    // Revert if there is an active gas snapshot as we can only have one active snapshot at a time.
1787    if let Some((group, name)) = &ccx.state.gas_metering.active_gas_snapshot {
1788        bail!("gas snapshot was already started with group: {group} and name: {name}");
1789    }
1790
1791    let (group, name) = derive_snapshot_name(ccx, group, name)?;
1792
1793    ccx.state.gas_metering.gas_records.push(GasRecord {
1794        group: group.clone(),
1795        name: name.clone(),
1796        gas_used: 0,
1797        depth: ccx.depth(),
1798    });
1799
1800    ccx.state.gas_metering.active_gas_snapshot = Some((group, name));
1801
1802    ccx.state.gas_metering.start();
1803
1804    Ok(Default::default())
1805}
1806
1807fn inner_stop_gas_snapshot<FEN: FoundryEvmNetwork>(
1808    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1809    group: Option<String>,
1810    name: Option<String>,
1811) -> Result {
1812    // If group and name are not provided, use the last snapshot group and name.
1813    let (group, name) = group
1814        .zip(name)
1815        .or_else(|| ccx.state.gas_metering.active_gas_snapshot.clone())
1816        .ok_or_else(|| fmt_err!("no active gas snapshot; call `startGasSnapshot` first"))?;
1817
1818    if let Some(record) = ccx
1819        .state
1820        .gas_metering
1821        .gas_records
1822        .iter_mut()
1823        .find(|record| record.group == group && record.name == name)
1824    {
1825        // Calculate the gas used since the snapshot was started.
1826        // We subtract 171 from the gas used to account for gas used by the snapshot itself.
1827        let value = record.gas_used.saturating_sub(171);
1828
1829        ccx.state
1830            .gas_snapshots
1831            .entry(group.clone())
1832            .or_default()
1833            .insert(name.clone(), value.to_string());
1834
1835        // Stop the gas metering.
1836        ccx.state.gas_metering.stop();
1837
1838        // Remove the gas record.
1839        ccx.state
1840            .gas_metering
1841            .gas_records
1842            .retain(|record| record.group != group && record.name != name);
1843
1844        // Clear last snapshot cache if we have an exact match.
1845        if let Some((snapshot_group, snapshot_name)) = &ccx.state.gas_metering.active_gas_snapshot
1846            && snapshot_group == &group
1847            && snapshot_name == &name
1848        {
1849            ccx.state.gas_metering.active_gas_snapshot = None;
1850        }
1851
1852        Ok(value.abi_encode())
1853    } else {
1854        bail!("no gas snapshot was started with the name: {name} in group: {group}");
1855    }
1856}
1857
1858// Derives the snapshot group and name from the provided group and name or the running contract.
1859fn derive_snapshot_name<FEN: FoundryEvmNetwork>(
1860    ccx: &CheatsCtxt<'_, '_, FEN>,
1861    group: Option<String>,
1862    name: Option<String>,
1863) -> Result<(String, String)> {
1864    let group = match group {
1865        Some(group) => {
1866            ensure!(
1867                is_valid_snapshot_group(&group),
1868                "invalid snapshot group name `{group}`: expected a relative path without empty, `.` or `..` components"
1869            );
1870            group
1871        }
1872        None => {
1873            ccx.state.core.config.running_artifact.clone().expect("expected running contract").name
1874        }
1875    };
1876    let name = name.unwrap_or_else(|| "default".to_string());
1877    Ok((group, name))
1878}
1879
1880/// Returns whether `group` is a relative path without empty or dot components.
1881fn is_valid_snapshot_group(group: &str) -> bool {
1882    // Check the original components because `Path::components` normalizes dots and separators.
1883    group.split(std::path::is_separator).all(|component| {
1884        matches!(Path::new(component).components().next(), Some(Component::Normal(name)) if name == component)
1885    })
1886}
1887
1888/// Reads the current caller information and returns the current [CallerMode], `msg.sender` and
1889/// `tx.origin`.
1890///
1891/// Depending on the current caller mode, one of the following results will be returned:
1892/// - If there is an active prank:
1893///     - caller_mode will be equal to:
1894///         - [CallerMode::Prank] if the prank has been set with `vm.prank(..)`.
1895///         - [CallerMode::RecurrentPrank] if the prank has been set with `vm.startPrank(..)`.
1896///     - `msg.sender` will be equal to the address set for the prank.
1897///     - `tx.origin` will be equal to the default sender address unless an alternative one has been
1898///       set when configuring the prank.
1899///
1900/// - If there is an active broadcast:
1901///     - caller_mode will be equal to:
1902///         - [CallerMode::Broadcast] if the broadcast has been set with `vm.broadcast(..)`.
1903///         - [CallerMode::RecurrentBroadcast] if the broadcast has been set with
1904///           `vm.startBroadcast(..)`.
1905///     - `msg.sender` and `tx.origin` will be equal to the address provided when setting the
1906///       broadcast.
1907///
1908/// - If no caller modification is active:
1909///     - caller_mode will be equal to [CallerMode::None],
1910///     - `msg.sender` and `tx.origin` will be equal to the default sender address.
1911fn read_callers<FEN: FoundryEvmNetwork>(
1912    state: &Cheatcodes<FEN>,
1913    default_sender: &Address,
1914    call_depth: usize,
1915) -> Result {
1916    let mut mode = CallerMode::None;
1917    let mut new_caller = default_sender;
1918    let mut new_origin = default_sender;
1919    if let Some(prank) = state.get_prank(call_depth) {
1920        mode = if prank.single_call { CallerMode::Prank } else { CallerMode::RecurrentPrank };
1921        new_caller = &prank.new_caller;
1922        if let Some(new) = &prank.new_origin {
1923            new_origin = new;
1924        }
1925    } else if let Some(broadcast) = &state.broadcast {
1926        mode = if broadcast.single_call {
1927            CallerMode::Broadcast
1928        } else {
1929            CallerMode::RecurrentBroadcast
1930        };
1931        new_caller = &broadcast.new_origin;
1932        new_origin = &broadcast.new_origin;
1933    }
1934
1935    Ok((mode, new_caller, new_origin).abi_encode_params())
1936}
1937
1938/// Ensures the account is loaded, warm and touched.
1939pub(super) fn touch_account(state: &mut State<'_>, addr: Address) -> Result<()> {
1940    let mut account = state.account(&addr)?;
1941    account.touch();
1942    account.warm();
1943    Ok(())
1944}
1945
1946/// Sets the nonce of `address`, as a write that survives reverts of the enclosing calls.
1947fn set_persistent_nonce<FEN: FoundryEvmNetwork>(
1948    ccx: &mut CheatsCtxt<'_, '_, FEN>,
1949    address: Address,
1950    nonce: u64,
1951) -> Result {
1952    let mut account = ccx.evm.state_mut().account(&address)?;
1953    account.touch();
1954    account.warm();
1955    let previous = account.nonce();
1956    account.set_nonce(nonce);
1957    let write = PersistentWrite::nonce(&account, previous).with_replay(Replay::Set);
1958    drop(account);
1959    ccx.state.record_persistent(ccx.caller_depth(), ccx.evm.state(), [write]);
1960    Ok(Default::default())
1961}
1962
1963/// Loads the storage slot and marks it warm, as an `SLOAD` or `SSTORE` of it would.
1964fn warm_storage_slot<'s, 'db>(
1965    state: &'s mut State<'db>,
1966    address: &'s Address,
1967    key: U256,
1968) -> DbResult<StorageSlotHandle<'s, 'db>> {
1969    let mut slot = state.storage_slot(address, key)?;
1970    slot.warm();
1971    Ok(slot)
1972}
1973
1974/// Writes `block_hash` to the EIP-2935 history storage, if the history contract is deployed.
1975///
1976/// Writes do not warm the history account or slot.
1977fn set_eip2935_blockhash(
1978    state: &mut State<'_>,
1979    block_number: U256,
1980    block_hash: B256,
1981) -> Result<()> {
1982    if state.account(&HISTORY_STORAGE_ADDRESS)?.code_hash() != keccak256(&HISTORY_STORAGE_CODE) {
1983        return Ok(());
1984    }
1985    state
1986        .storage_slot(&HISTORY_STORAGE_ADDRESS, history_storage_slot(block_number))
1987        .map_err(|e| fmt_err!("failed to store EIP-2935 history slot: {e}"))?
1988        .set(history_storage_value(block_hash));
1989    Ok(())
1990}
1991
1992/// Installs the addresses a nested transaction in `env` with `access_list` warms when it starts
1993/// and that `vm.cool` keeps warm, returning the running transaction's.
1994fn enter_tx_warm_addresses<FEN: FoundryEvmNetwork>(
1995    state: &mut Cheatcodes<FEN>,
1996    env: &EvmEnvFor<FEN>,
1997    access_list: Option<&alloy_rpc_types::AccessList>,
1998) -> Vec<Address> {
1999    std::mem::replace(
2000        &mut state.tx_warm_addresses,
2001        foundry_evm_core::utils::tx_warm_addresses(env, access_list),
2002    )
2003}
2004
2005/// Clears the EIP-2935 history ring buffer with journaled writes, so that reverting the enclosing
2006/// frame restores the previous history storage.
2007///
2008/// Warmth is preserved: slots that were cold stay cold. A database error reverts any partial
2009/// clearing.
2010fn clear_eip2935_history_storage(state: &mut State<'_>, features: EvmFeatures) -> Result<()> {
2011    let checkpoint = state.checkpoint();
2012    for slot in 0..HISTORY_SERVE_WINDOW {
2013        match state.storage_slot(&HISTORY_STORAGE_ADDRESS, U256::from(slot)) {
2014            Ok(mut slot) => slot.set(U256::ZERO),
2015            Err(e) => {
2016                state.rollback(checkpoint, features);
2017                return Err(fmt_err!("failed to clear EIP-2935 history slot: {e}"));
2018            }
2019        }
2020    }
2021    Ok(())
2022}
2023
2024// Tempo TIP-1026 stores logoURI in TIP-20 storage slot 5, reusing the
2025// previously-unused domainSeparator slot. This mirrors Tempo's
2026// crates/precompiles/tests/storage_tests/solidity/testdata/tip20.layout.json
2027// fixture, where `logoUri` has slot "5".
2028const TIP20_LOGO_URI_SLOT_INDEX: u64 = 5;
2029
2030fn set_tip20_logo_uri<FEN: FoundryEvmNetwork>(
2031    ccx: &mut CheatsCtxt<'_, '_, FEN>,
2032    token: &Address,
2033    new_logo_uri: &str,
2034) -> Result {
2035    validate_tip20_logo_uri(new_logo_uri).map_err(|err| match err {
2036        Tip20LogoUriValidationError::LogoURITooLong => fmt_err!("LogoURITooLong"),
2037        Tip20LogoUriValidationError::InvalidLogoURI => fmt_err!("InvalidLogoURI"),
2038    })?;
2039    ccx.ensure_not_precompile(token)?;
2040    let state = ccx.evm.state_mut();
2041    touch_account(state, *token)?;
2042    store_solidity_string(
2043        state,
2044        *token,
2045        U256::from(TIP20_LOGO_URI_SLOT_INDEX),
2046        new_logo_uri.as_bytes(),
2047    )
2048}
2049
2050fn store_solidity_string(
2051    state: &mut State<'_>,
2052    target: Address,
2053    base_slot: U256,
2054    bytes: &[u8],
2055) -> Result {
2056    cleanup_long_string_tail(state, target, base_slot, bytes.len())?;
2057
2058    if bytes.len() <= 31 {
2059        warm_storage_slot(state, &target, base_slot)
2060            .map_err(|e| fmt_err!("failed to store TIP-20 logo URI: {e}"))?
2061            .set(encode_short_string(bytes));
2062        return Ok(Default::default());
2063    }
2064
2065    warm_storage_slot(state, &target, base_slot)
2066        .map_err(|e| fmt_err!("failed to store TIP-20 logo URI length: {e}"))?
2067        .set(U256::from(bytes.len() * 2 + 1));
2068
2069    let slot_start = solidity_dynamic_data_slot(base_slot);
2070    for (index, chunk) in bytes.chunks(32).enumerate() {
2071        let mut chunk_bytes = [0u8; 32];
2072        chunk_bytes[..chunk.len()].copy_from_slice(chunk);
2073        warm_storage_slot(state, &target, slot_start + U256::from(index))
2074            .map_err(|e| fmt_err!("failed to store TIP-20 logo URI data: {e}"))?
2075            .set(U256::from_be_bytes(chunk_bytes));
2076    }
2077
2078    Ok(Default::default())
2079}
2080
2081fn cleanup_long_string_tail(
2082    state: &mut State<'_>,
2083    target: Address,
2084    base_slot: U256,
2085    new_len: usize,
2086) -> Result<()> {
2087    let previous = warm_storage_slot(state, &target, base_slot)
2088        .map_err(|e| fmt_err!("failed to load previous TIP-20 logo URI: {e}"))?
2089        .current();
2090    if !is_long_string(previous) {
2091        return Ok(());
2092    }
2093
2094    let Some(previous_len) = long_string_length(previous) else {
2095        return Ok(());
2096    };
2097    let previous_chunks = string_chunks(previous_len);
2098    let new_chunks = if new_len > 31 { string_chunks(new_len) } else { 0 };
2099    if previous_chunks <= new_chunks {
2100        return Ok(());
2101    }
2102
2103    let slot_start = solidity_dynamic_data_slot(base_slot);
2104    for index in new_chunks..previous_chunks {
2105        warm_storage_slot(state, &target, slot_start + U256::from(index))
2106            .map_err(|e| fmt_err!("failed to clear previous TIP-20 logo URI data: {e}"))?
2107            .set(U256::ZERO);
2108    }
2109
2110    Ok(())
2111}
2112
2113fn encode_short_string(bytes: &[u8]) -> U256 {
2114    let mut storage_bytes = [0u8; 32];
2115    storage_bytes[..bytes.len()].copy_from_slice(bytes);
2116    storage_bytes[31] =
2117        u8::try_from(bytes.len() * 2).expect("short Solidity string length tag fits in u8");
2118    U256::from_be_bytes(storage_bytes)
2119}
2120
2121fn solidity_dynamic_data_slot(base_slot: U256) -> U256 {
2122    Into::<U256>::into(keccak256(base_slot.to_be_bytes::<32>()))
2123}
2124
2125const fn is_long_string(slot_value: U256) -> bool {
2126    (slot_value.to_be_bytes::<32>()[31] & 1) != 0
2127}
2128
2129fn long_string_length(slot_value: U256) -> Option<usize> {
2130    let length: U256 = (slot_value - U256::ONE) >> 1;
2131    usize::try_from(length).ok().filter(|length| *length <= TIP20_MAX_LOGO_URI_BYTES)
2132}
2133
2134const fn string_chunks(byte_length: usize) -> usize {
2135    byte_length.div_ceil(32)
2136}
2137
2138/// Consumes recorded account accesses and returns them as an abi encoded
2139/// array of [AccountAccess]. If there are no accounts were
2140/// recorded as accessed, an abi encoded empty array is returned.
2141///
2142/// In the case where `stopAndReturnStateDiff` is called at a lower
2143/// depth than `startStateDiffRecording`, multiple `Vec<RecordedAccountAccesses>`
2144/// will be flattened, preserving the order of the accesses.
2145fn get_state_diff<FEN: FoundryEvmNetwork>(state: &mut Cheatcodes<FEN>) -> Result {
2146    let mut res = state.take_recorded_account_diffs_prefix();
2147    res.extend(
2148        state
2149            .recorded_account_diffs_stack
2150            .replace(Default::default())
2151            .unwrap_or_default()
2152            .into_iter()
2153            .flatten(),
2154    );
2155    Ok(res.abi_encode())
2156}
2157
2158/// Marks a reverted frame's account accesses, including their storage accesses, as reverted.
2159pub(crate) fn mark_account_accesses_reverted(accesses: &mut [AccountAccess]) {
2160    for access in accesses {
2161        access.reverted = true;
2162        for storage_access in &mut access.storageAccesses {
2163            storage_access.reverted = true;
2164        }
2165    }
2166}
2167
2168/// Moves a finished frame's account accesses into the enclosing recorded frame, or back onto the
2169/// stack when no enclosing frame was recorded, preserving the order of the accesses.
2170pub(crate) fn merge_recorded_frame(
2171    stack: &mut Vec<Vec<AccountAccess>>,
2172    mut accesses: Vec<AccountAccess>,
2173) {
2174    if let Some(parent) = stack.last_mut() {
2175        parent.append(&mut accesses);
2176    } else {
2177        stack.push(accesses);
2178    }
2179}
2180
2181/// Appends an AccountAccess that resumes the recording of the current context.
2182pub(crate) fn append_storage_access(
2183    last: &mut Vec<AccountAccess>,
2184    storage_access: crate::Vm::StorageAccess,
2185    storage_depth: u64,
2186) {
2187    // Assert that there's an existing record for the current context.
2188    if !last.is_empty() && last.first().unwrap().depth < storage_depth {
2189        // Three cases to consider:
2190        // 1. If there hasn't been a context switch since the start of this context, then add the
2191        //    storage access to the current context record.
2192        // 2. If there's an existing Resume record for this context, then add the storage access to
2193        //    it. A deeper Resume record belongs to a subcall that already returned.
2194        // 3. Otherwise, create a new Resume record based on the current context.
2195        if last.len() == 1 {
2196            last.first_mut().unwrap().storageAccesses.push(storage_access);
2197        } else {
2198            let depth = last.first().unwrap().depth;
2199            let last_record = last.last_mut().unwrap();
2200            if last_record.kind as u8 == crate::Vm::AccountAccessKind::Resume as u8
2201                && last_record.depth == depth
2202            {
2203                last_record.storageAccesses.push(storage_access);
2204            } else {
2205                let entry = last.first().unwrap();
2206                let resume_record = crate::Vm::AccountAccess {
2207                    chainInfo: crate::Vm::ChainInfo {
2208                        forkId: entry.chainInfo.forkId,
2209                        chainId: entry.chainInfo.chainId,
2210                    },
2211                    accessor: entry.accessor,
2212                    account: entry.account,
2213                    kind: crate::Vm::AccountAccessKind::Resume,
2214                    initialized: entry.initialized,
2215                    storageAccesses: vec![storage_access],
2216                    reverted: entry.reverted,
2217                    // The remaining fields are defaults
2218                    oldBalance: U256::ZERO,
2219                    newBalance: U256::ZERO,
2220                    oldNonce: 0,
2221                    newNonce: 0,
2222                    value: U256::ZERO,
2223                    data: Bytes::new(),
2224                    deployedCode: Bytes::new(),
2225                    depth: entry.depth,
2226                };
2227                last.push(resume_record);
2228            }
2229        }
2230    }
2231}
2232
2233/// Creates a `GenesisAccount` from the account at `address` and its known storage.
2234fn genesis_account(
2235    state: &mut State<'_>,
2236    address: &Address,
2237    slots: impl IntoIterator<Item = U256>,
2238) -> Result<GenesisAccount> {
2239    let (nonce, balance, code) = {
2240        let mut account = state.account(address)?;
2241        (account.nonce(), account.balance(), account.load_code()?)
2242    };
2243    let mut storage = BTreeMap::new();
2244    for slot in slots {
2245        storage.insert(B256::from(slot), B256::from(state.storage_slot_untracked(address, &slot)?));
2246    }
2247    Ok(GenesisAccount {
2248        nonce: Some(nonce),
2249        balance,
2250        code: Some(code.original_bytes()),
2251        storage: Some(storage),
2252        ..Default::default()
2253    })
2254}
2255
2256/// Helper function to returns state diffs recorded for each changed account.
2257fn get_recorded_state_diffs<FEN: FoundryEvmNetwork>(
2258    ccx: &mut CheatsCtxt<'_, '_, FEN>,
2259) -> BTreeMap<Address, AccountStateDiffs> {
2260    let mut state_diffs: BTreeMap<Address, AccountStateDiffs> = BTreeMap::default();
2261    let current_context = (ccx.chain_id(), ccx.active_fork_id().unwrap_or_default());
2262
2263    // A delegatecall into a library writes with its caller's layout. Identify libraries from their
2264    // artifacts in the current context; other code retains its recorded address.
2265    let delegated_code = ccx
2266        .state
2267        .recorded_account_diffs()
2268        .filter(|access| {
2269            matches!(access.kind, AccountAccessKind::DelegateCall | AccountAccessKind::CallCode)
2270                && (access.chainInfo.chainId.to::<u64>(), access.chainInfo.forkId)
2271                    == current_context
2272        })
2273        .map(|access| access.account)
2274        .collect::<AddressSet>();
2275    let libraries = delegated_code
2276        .into_iter()
2277        .filter(|&address| {
2278            get_contract_data(ccx, address, false).is_some_and(|(_, data)| data.is_library())
2279        })
2280        .collect::<AddressSet>();
2281
2282    // First, collect all unique addresses we need to look up, and attribute every storage write to
2283    // the code whose layout describes it.
2284    let mut addresses_to_lookup = AddressSet::default();
2285    let mut writers = AddressMap::<StorageWriters>::default();
2286    // Open call frames, innermost last, with their recorded context and layout writer.
2287    let mut frames = Vec::<(u64, (u64, U256), Option<Address>)>::new();
2288    for account_access in ccx.state.recorded_account_diffs_with_boundaries() {
2289        let Some(account_access) = account_access else {
2290            frames.clear();
2291            continue;
2292        };
2293        let depth = account_access.depth;
2294        let context =
2295            (account_access.chainInfo.chainId.to::<u64>(), account_access.chainInfo.forkId);
2296        match account_access.kind {
2297            AccountAccessKind::Resume => {
2298                while frames.last().is_some_and(|&(frame_depth, _, _)| frame_depth > depth) {
2299                    frames.pop();
2300                }
2301            }
2302            AccountAccessKind::Call
2303            | AccountAccessKind::StaticCall
2304            | AccountAccessKind::Create
2305            | AccountAccessKind::DelegateCall
2306            | AccountAccessKind::CallCode => {
2307                while frames.last().is_some_and(|&(frame_depth, _, _)| frame_depth >= depth) {
2308                    frames.pop();
2309                }
2310                let code = account_access.account;
2311                let writer = if context == current_context && libraries.contains(&code) {
2312                    // Recording can start inside a call, leaving its code identity unknown.
2313                    // The delegatecall's accessor is msg.sender, not the executing caller.
2314                    frames
2315                        .last()
2316                        .filter(|&&(frame_depth, frame_context, _)| {
2317                            frame_depth + 1 == depth && frame_context == context
2318                        })
2319                        .and_then(|&(_, _, writer)| writer)
2320                } else {
2321                    Some(code)
2322                };
2323                frames.push((depth, context, writer));
2324            }
2325            _ => {}
2326        }
2327
2328        if !account_access.storageAccesses.is_empty()
2329            || account_access.oldBalance != account_access.newBalance
2330        {
2331            addresses_to_lookup.insert(account_access.account);
2332            let writer = frames.last().and_then(|&(_, _, writer)| writer);
2333            for storage_access in &account_access.storageAccesses {
2334                if storage_access.isWrite && !storage_access.reverted {
2335                    addresses_to_lookup.insert(storage_access.account);
2336                    writers.entry(storage_access.account).or_default().record(
2337                        context,
2338                        storage_access.slot,
2339                        writer,
2340                    );
2341                }
2342            }
2343        }
2344    }
2345
2346    // Look up contract names and storage layouts for all addresses
2347    let mut contract_names = AddressMap::default();
2348    let mut storage_layouts = AddressMap::default();
2349    for address in addresses_to_lookup {
2350        if let Some((artifact_id, contract_data)) = get_contract_data(ccx, address, false) {
2351            contract_names.insert(address, artifact_id.identifier());
2352
2353            // Also get storage layout if available
2354            if let Some(storage_layout) = &contract_data.storage_layout {
2355                storage_layouts.insert(address, storage_layout.clone());
2356            }
2357        }
2358    }
2359
2360    // A delegatecall writes the caller's storage with the callee's layout, so each slot is decoded
2361    // with the layout of the code that wrote it last. Local artifacts identify code only in the
2362    // journal that recorded the writes; otherwise fetch the exact code on the chain where they
2363    // occurred, if enabled. This remains correct for historical forks and upgraded proxies.
2364    let decode_external_storage = ccx.state.core.config.decode_external_storage;
2365    // Storage owner and delegated writer to the writer's layout.
2366    let mut delegated_layouts = HashMap::<(Address, Address), _>::default();
2367    let mut external_requests = BTreeMap::<u64, AddressSet>::new();
2368    let mut external_targets = Vec::new();
2369    for (&storage_address, writers) in &writers {
2370        let Some(context) = writers.context() else {
2371            // The state-diff output has no chain dimension. If writes to one address came from
2372            // different chains, decoding it with any layout would be misleading.
2373            contract_names.remove(&storage_address);
2374            storage_layouts.remove(&storage_address);
2375            continue;
2376        };
2377        let (chain_id, _) = context;
2378        let recorded_context_is_current = context == current_context;
2379        if !recorded_context_is_current {
2380            contract_names.remove(&storage_address);
2381            storage_layouts.remove(&storage_address);
2382        }
2383
2384        for writer in writers.slots.values().flatten().copied().collect::<AddressSet>() {
2385            if writer == storage_address {
2386                if storage_layouts.contains_key(&storage_address) {
2387                    continue;
2388                }
2389            } else if recorded_context_is_current
2390                && let Some((_, contract_data)) = get_contract_data(ccx, writer, false)
2391                && let Some(layout) = &contract_data.storage_layout
2392            {
2393                delegated_layouts.insert((storage_address, writer), layout.clone());
2394                continue;
2395            }
2396            if decode_external_storage {
2397                external_requests.entry(chain_id).or_default().insert(writer);
2398                external_targets.push((storage_address, chain_id, writer));
2399            }
2400        }
2401    }
2402
2403    for (chain_id, addresses) in external_requests {
2404        let external = crate::external_storage::storage_layouts(
2405            &ccx.state.core.config.external_sources,
2406            foundry_config::Chain::from(chain_id),
2407            addresses.into_iter().collect(),
2408        );
2409        for &(storage_address, target_chain_id, writer) in &external_targets {
2410            if target_chain_id == chain_id
2411                && let Some((name, layout)) = external.get(&writer)
2412            {
2413                if writer == storage_address {
2414                    contract_names.insert(storage_address, name.clone());
2415                    storage_layouts.insert(storage_address, layout.clone());
2416                } else {
2417                    delegated_layouts.insert((storage_address, writer), layout.clone());
2418                }
2419            }
2420        }
2421    }
2422
2423    let new_account_diff = |address: &Address| AccountStateDiffs {
2424        label: ccx.state.core.labels.get(address).cloned(),
2425        contract: contract_names.get(address).cloned(),
2426        ..Default::default()
2427    };
2428
2429    // Now process the records
2430    ccx.state
2431        .recorded_account_diffs()
2432        .filter(|account_access| {
2433            !account_access.storageAccesses.is_empty()
2434                || account_access.oldBalance != account_access.newBalance
2435                || (!account_access.reverted && account_access.oldNonce != account_access.newNonce)
2436        })
2437        .for_each(|account_access| {
2438            // Record account balance diffs.
2439            if account_access.oldBalance != account_access.newBalance {
2440                let account_diff = state_diffs
2441                    .entry(account_access.account)
2442                    .or_insert_with(|| new_account_diff(&account_access.account));
2443                // Update balance diff. Do not overwrite the initial balance if already set.
2444                if let Some(diff) = &mut account_diff.balance_diff {
2445                    diff.new_value = account_access.newBalance;
2446                } else {
2447                    account_diff.balance_diff = Some(BalanceDiff {
2448                        previous_value: account_access.oldBalance,
2449                        new_value: account_access.newBalance,
2450                    });
2451                }
2452            }
2453
2454            // Record account nonce diffs.
2455            if account_access.oldNonce != account_access.newNonce && !account_access.reverted {
2456                let account_diff = state_diffs
2457                    .entry(account_access.account)
2458                    .or_insert_with(|| new_account_diff(&account_access.account));
2459                // Update nonce diff. Do not overwrite the initial nonce if already set.
2460                if let Some(diff) = &mut account_diff.nonce_diff {
2461                    diff.new_value = account_access.newNonce;
2462                } else {
2463                    account_diff.nonce_diff = Some(NonceDiff {
2464                        previous_value: account_access.oldNonce,
2465                        new_value: account_access.newNonce,
2466                    });
2467                }
2468            }
2469
2470            // Collect all storage accesses for this account
2471            let raw_changes_by_slot = account_access
2472                .storageAccesses
2473                .iter()
2474                .filter_map(|access| {
2475                    (access.isWrite && !access.reverted)
2476                        .then_some((access.slot, (access.previousValue, access.newValue)))
2477                })
2478                .collect::<BTreeMap<_, _>>();
2479
2480            // Record account state diffs.
2481            for storage_access in &account_access.storageAccesses {
2482                if storage_access.isWrite && !storage_access.reverted {
2483                    let account_diff = state_diffs
2484                        .entry(storage_access.account)
2485                        .or_insert_with(|| new_account_diff(&storage_access.account));
2486                    let layout = match writers
2487                        .get(&storage_access.account)
2488                        .and_then(|writers| writers.slots.get(&storage_access.slot))
2489                    {
2490                        Some(&Some(writer)) if writer != storage_access.account => {
2491                            delegated_layouts.get(&(storage_access.account, writer))
2492                        }
2493                        Some(Some(_)) => storage_layouts.get(&storage_access.account),
2494                        _ => None,
2495                    };
2496                    // Update state diff. Do not overwrite the initial value if already set.
2497                    let entry = match account_diff.state_diff.entry(storage_access.slot) {
2498                        Entry::Vacant(slot_state_diff) => {
2499                            // Get storage layout info for this slot
2500                            // Include mapping slots if available for the account
2501                            let mapping_slots = ccx
2502                                .state
2503                                .core
2504                                .mapping_slots
2505                                .as_ref()
2506                                .and_then(|slots| slots.get(&storage_access.account));
2507
2508                            let slot_info = layout.and_then(|layout| {
2509                                let decoder = SlotIdentifier::new(layout.clone());
2510                                decoder.identify(&storage_access.slot, mapping_slots).or_else(
2511                                    || {
2512                                        // Create a map of new values for bytes/string
2513                                        // identification. These values are used to determine
2514                                        // the length of the data which helps determine how many
2515                                        // slots to search
2516                                        let current_base_slot_values = raw_changes_by_slot
2517                                            .iter()
2518                                            .map(|(slot, (_, new_val))| (*slot, *new_val))
2519                                            .collect::<B256Map<_>>();
2520                                        decoder.identify_bytes_or_string(
2521                                            &storage_access.slot,
2522                                            &current_base_slot_values,
2523                                        )
2524                                    },
2525                                )
2526                            });
2527                            // Proxies write the EIP-1967 slots from assembly constants, which no
2528                            // layout covers.
2529                            let slot_info =
2530                                slot_info.or_else(|| identify_eip1967_slot(&storage_access.slot));
2531
2532                            slot_state_diff.insert(SlotStateDiff {
2533                                previous_value: storage_access.previousValue,
2534                                new_value: storage_access.newValue,
2535                                slot_info,
2536                            })
2537                        }
2538                        Entry::Occupied(slot_state_diff) => {
2539                            let entry = slot_state_diff.into_mut();
2540                            entry.new_value = storage_access.newValue;
2541                            entry
2542                        }
2543                    };
2544
2545                    // Update decoded values if we have slot info
2546                    if let Some(slot_info) = &mut entry.slot_info {
2547                        slot_info.decode_values(entry.previous_value, storage_access.newValue);
2548                        if slot_info.is_bytes_or_string() {
2549                            slot_info.decode_bytes_or_string_values(
2550                                &storage_access.slot,
2551                                &raw_changes_by_slot,
2552                            );
2553                        }
2554                    }
2555                }
2556            }
2557        });
2558    state_diffs
2559}
2560
2561/// EIP-1822 UUPS implementation storage slot: keccak256("PROXIABLE")
2562const EIP1822_PROXIABLE_SLOT: B256 =
2563    b256!("0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7");
2564
2565/// Helper function to get the contract data from the deployed code at an address.
2566fn get_contract_data<'a, FEN: FoundryEvmNetwork>(
2567    ccx: &'a mut CheatsCtxt<'_, '_, FEN>,
2568    address: Address,
2569    detect_proxy: bool,
2570) -> Option<(&'a foundry_compilers::ArtifactId, &'a foundry_common::contracts::ContractData)> {
2571    // Check if we have available artifacts to match against
2572    let artifacts = ccx.state.core.config.available_artifacts.as_ref()?;
2573
2574    // Try to load the account and get its code
2575    let mut account = ccx.evm.state_mut().account(&address).ok()?;
2576    account.warm();
2577    let code = account.load_code().ok()?;
2578
2579    // Skip if code is empty
2580    if code.is_empty() {
2581        return None;
2582    }
2583
2584    // Try to find the artifact by deployed code
2585    let code_bytes = code.original_bytes();
2586    if let Some(result) = artifacts.find_by_deployed_code_exact(&code_bytes) {
2587        return Some(result);
2588    }
2589
2590    // Fall back to known proxy artifacts when exact matching is impossible.
2591    let contains_slot = |slot: B256| code_bytes.windows(32).any(|word| word == slot.as_slice());
2592    let find_by_suffix =
2593        |suffix: &str| artifacts.iter().find(|(a, _)| a.identifier().ends_with(suffix));
2594    if detect_proxy
2595        && contains_slot(EIP1967_IMPLEMENTATION_SLOT)
2596        && let Some(result) = find_by_suffix(":TransparentUpgradeableProxy")
2597    {
2598        return Some(result);
2599    } else if detect_proxy
2600        && contains_slot(EIP1822_PROXIABLE_SLOT)
2601        && let Some(result) = find_by_suffix(":UUPSUpgradeable")
2602    {
2603        return Some(result);
2604    }
2605
2606    // Fallback to fuzzy matching if exact match fails
2607    artifacts.find_by_deployed_code(&code_bytes)
2608}
2609
2610/// Returns the storage layout of the contract at `target`.
2611fn contract_storage_layout<FEN: FoundryEvmNetwork>(
2612    ccx: &mut CheatsCtxt<'_, '_, FEN>,
2613    target: Address,
2614) -> Result<Arc<StorageLayout>> {
2615    let storage_layout = get_contract_data(ccx, target, true)
2616        .and_then(|(_, data)| data.storage_layout.clone())
2617        .ok_or_else(|| fmt_err!("Storage layout not available for contract at {target}. Try compiling contracts with `--extra-output storageLayout`"))?;
2618
2619    trace!(storage = ?storage_layout.storage, "fetched storage");
2620
2621    Ok(storage_layout)
2622}
2623
2624/// Finds a variable by its label in `storage_layout`, returning its storage entry and type.
2625///
2626/// An exact match takes precedence, since Solidity names are case-sensitive; otherwise the label
2627/// is matched case-insensitively.
2628fn find_storage_variable<'a>(
2629    storage_layout: &'a StorageLayout,
2630    variable_name: &str,
2631) -> Result<(&'a Storage, &'a StorageType)> {
2632    let storage = storage_layout
2633        .storage
2634        .iter()
2635        .find(|s| s.label == variable_name)
2636        .or_else(|| {
2637            let variable_name_lower = variable_name.to_lowercase();
2638            storage_layout.storage.iter().find(|s| s.label.to_lowercase() == variable_name_lower)
2639        })
2640        .ok_or_else(|| fmt_err!("variable '{variable_name}' not found in storage layout"))?;
2641
2642    let storage_type = storage_layout
2643        .types
2644        .get(&storage.storage_type)
2645        .ok_or_else(|| fmt_err!("storage type not found for variable {variable_name}"))?;
2646
2647    Ok((storage, storage_type))
2648}
2649
2650#[cfg(test)]
2651mod tests {
2652    use super::*;
2653
2654    #[test]
2655    fn state_diff_preserves_raw_values_with_partial_decoding() {
2656        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
2657            "storage": [
2658                { "astId": 1, "contract": "C", "label": "data", "offset": 0, "slot": "0", "type": "t_struct" }
2659            ],
2660            "types": {
2661                "t_struct": {
2662                    "encoding": "inplace", "label": "struct C.Data", "numberOfBytes": "32",
2663                    "members": [
2664                        { "astId": 2, "contract": "C", "label": "amount", "offset": 0, "slot": "0", "type": "t_amount" },
2665                        { "astId": 3, "contract": "C", "label": "paused", "offset": 16, "slot": "0", "type": "t_bool" }
2666                    ]
2667                },
2668                "t_amount": { "encoding": "inplace", "label": "Amount", "numberOfBytes": "16" },
2669                "t_bool": { "encoding": "inplace", "label": "bool", "numberOfBytes": "1" }
2670            }
2671        }))
2672        .unwrap();
2673        let identifier = SlotIdentifier::new(Arc::new(layout));
2674        let mut slot_info = identifier.identify(&B256::ZERO, None).unwrap();
2675        let new_value = B256::from(U256::from(1));
2676        slot_info.decode_values(B256::ZERO, new_value);
2677        let diffs = AccountStateDiffs {
2678            state_diff: BTreeMap::from([(
2679                B256::ZERO,
2680                SlotStateDiff { previous_value: B256::ZERO, new_value, slot_info: Some(slot_info) },
2681            )]),
2682            ..Default::default()
2683        };
2684
2685        assert_eq!(
2686            diffs.to_string(),
2687            "- state diff:\n\
2688@ 0x0000000000000000000000000000000000000000000000000000000000000000 (data, (bool,)): 0x0000000000000000000000000000000000000000000000000000000000000000 → 0x0000000000000000000000000000000000000000000000000000000000000001\n    paused (bool): false → false\n"
2689        );
2690    }
2691
2692    #[test]
2693    fn validates_snapshot_groups() {
2694        for group in [
2695            "Group",
2696            "a.b",
2697            "group with spaces",
2698            "..hidden",
2699            "core/someContract",
2700            "periphery/someContract.v1",
2701        ] {
2702            assert!(is_valid_snapshot_group(group), "expected `{group}` to be valid");
2703        }
2704        for group in [
2705            "",
2706            ".",
2707            "..",
2708            "../settings",
2709            "./a",
2710            "/tmp/settings",
2711            "a/",
2712            "a/.",
2713            "a/./b",
2714            "a/../b",
2715            "a//b",
2716        ] {
2717            assert!(!is_valid_snapshot_group(group), "expected `{group}` to be invalid");
2718        }
2719
2720        #[cfg(unix)]
2721        assert!(is_valid_snapshot_group(r"core\someContract"));
2722
2723        #[cfg(windows)]
2724        {
2725            assert!(is_valid_snapshot_group(r"core\someContract"));
2726            for group in [r"C:\settings", r"C:settings", r"\settings", r"core\..\settings", "a:b"] {
2727                assert!(!is_valid_snapshot_group(group), "expected `{group}` to be invalid");
2728            }
2729        }
2730    }
2731}