Skip to main content

foundry_cheatcodes/inspector/
env_overrides.rs

1//! Cheatcode overrides of the `BASEFEE`, `GASPRICE`, `BLOBHASH` and `CHAINID` opcode values.
2
3use alloy_primitives::{B256, U256, map::HashMap};
4use foundry_evm_core::backend::LocalForkId;
5use std::mem;
6
7/// Env overrides keyed by fork ID (`None` is the local, non-forked state).
8type EnvOverridesByFork = HashMap<Option<LocalForkId>, EnvOverrides>;
9
10/// Environment overrides applied at the opcode level.
11///
12/// evm2 borrows the transaction environment for the whole transaction, and isolated calls run as
13/// nested transactions whose fee fields are zeroed for fee accounting, so cheatcodes that change
14/// the environment (`vm.fee`, `vm.txGasPrice`, `vm.blobhashes`, `vm.chainId`) cannot rely on the
15/// environment for the `BASEFEE`, `GASPRICE`, `BLOBHASH` and `CHAINID` opcodes. These overrides
16/// are applied in `step_end` to fix the value that was just pushed onto the stack, and
17/// `vm.getBlobhashes()` consults them too.
18///
19/// Transaction fee accounting and the chain ID used for transaction validation still follow the
20/// transaction environment.
21#[derive(Clone, Debug, Default)]
22pub struct EnvOverrides {
23    /// Override for the `BASEFEE` opcode (set via `vm.fee`).
24    pub basefee: Option<u64>,
25    /// Base fee restored from a snapshot during isolation, valid until the fork is rolled.
26    pub implicit_basefee: Option<u64>,
27    /// Override for the `GASPRICE` opcode (set via `vm.txGasPrice`).
28    pub gas_price: Option<u128>,
29    /// Override for the `BLOBHASH` opcode (set via `vm.blobhashes`).
30    pub blob_hashes: Option<Vec<B256>>,
31    /// Override for the `CHAINID` opcode (set via `vm.chainId`) until the next transaction, which
32    /// executes with the new chain ID.
33    pub chain_id: Option<u64>,
34    /// The opcode about to run (captured in `step`, consumed in `step_end`),
35    /// used to know what was just executed when `step_end` fires — at that
36    /// point `interpreter.bytecode.opcode()` already points at the *next*
37    /// instruction.
38    pub(super) pending_opcode: Option<u8>,
39    /// Pending index for the `BLOBHASH` opcode, captured in `step` (where
40    /// the index is still on top of the stack) for use in `step_end` (after
41    /// the opcode has consumed it and pushed the looked-up hash).
42    pub(super) pending_blobhash_index: Option<u64>,
43}
44
45impl EnvOverrides {
46    /// Whether any override is set.
47    #[inline]
48    pub const fn is_any_set(&self) -> bool {
49        self.basefee.is_some()
50            || self.implicit_basefee.is_some()
51            || self.gas_price.is_some()
52            || self.blob_hashes.is_some()
53            || self.chain_id.is_some()
54    }
55
56    /// Returns the value the `BASEFEE` opcode reads, if overridden.
57    #[inline]
58    pub fn basefee_override(&self) -> Option<u64> {
59        self.basefee.or(self.implicit_basefee)
60    }
61
62    /// Returns the value the `GASPRICE` opcode reads, if overridden.
63    #[inline]
64    pub const fn gas_price_override(&self) -> Option<u128> {
65        self.gas_price
66    }
67
68    /// Returns the hash the `BLOBHASH` opcode reads at `index`, if overridden.
69    ///
70    /// Out-of-range indices read the zero hash, per EIP-4844.
71    #[inline]
72    pub fn blob_hash_override(&self, index: u64) -> Option<B256> {
73        let blob_hashes = self.blob_hashes.as_ref()?;
74        Some(blob_hashes.get(index as usize).copied().unwrap_or_default())
75    }
76}
77
78/// Per-fork environment overrides and their state-snapshot copies.
79///
80/// Snapshot copies are required because backend snapshots do not include inspector state.
81#[derive(Clone, Debug, Default)]
82pub struct EnvOverrideState {
83    by_fork: EnvOverridesByFork,
84    snapshots: HashMap<U256, EnvOverridesByFork>,
85    /// Whether any fork has an override set, refreshed whenever `by_fork` changes, since the
86    /// per-instruction hooks read it.
87    any_set: bool,
88}
89
90impl EnvOverrideState {
91    /// Returns whether no fork has an override entry, active or not.
92    #[inline]
93    pub fn is_empty(&self) -> bool {
94        self.by_fork.is_empty()
95    }
96
97    /// Returns whether any fork, not only the active one, has an override set.
98    #[inline]
99    pub const fn is_any_set(&self) -> bool {
100        self.any_set
101    }
102
103    fn refresh_any_set(&mut self) {
104        self.any_set = self.by_fork.values().any(EnvOverrides::is_any_set);
105    }
106
107    /// Returns the overrides entry for `fork_id`, even if no override is set.
108    #[inline]
109    pub fn get(&self, fork_id: Option<LocalForkId>) -> Option<&EnvOverrides> {
110        self.by_fork.get(&fork_id)
111    }
112
113    /// Returns the overrides entry for `fork_id` mutably, without inserting one.
114    #[inline]
115    pub(super) fn get_mut(&mut self, fork_id: Option<LocalForkId>) -> Option<&mut EnvOverrides> {
116        self.by_fork.get_mut(&fork_id)
117    }
118
119    /// Updates the overrides for `fork_id`, inserting an empty entry first if absent.
120    pub(crate) fn update(
121        &mut self,
122        fork_id: Option<LocalForkId>,
123        f: impl FnOnce(&mut EnvOverrides),
124    ) {
125        f(self.by_fork.entry(fork_id).or_default());
126        self.refresh_any_set();
127    }
128
129    /// Clears the base fee restored for isolation on `fork_id`, without inserting an entry.
130    pub(crate) fn clear_implicit_basefee(&mut self, fork_id: Option<LocalForkId>) {
131        if let Some(overrides) = self.by_fork.get_mut(&fork_id) {
132            overrides.implicit_basefee = None;
133        }
134        self.refresh_any_set();
135    }
136
137    /// Saves all overrides under `snapshot_id`.
138    pub(crate) fn save_snapshot(&mut self, snapshot_id: U256) {
139        self.snapshots.insert(snapshot_id, self.by_fork.clone());
140    }
141
142    /// Restores the overrides saved under `snapshot_id`, deleting the copy if `delete` is set.
143    ///
144    /// Does nothing if no copy was saved under `snapshot_id`.
145    pub(crate) fn restore_snapshot(&mut self, snapshot_id: U256, delete: bool) {
146        let snapshot = if delete {
147            self.snapshots.remove(&snapshot_id)
148        } else {
149            self.snapshots.get(&snapshot_id).cloned()
150        };
151        if let Some(snapshot) = snapshot {
152            self.by_fork = snapshot;
153            self.refresh_any_set();
154        }
155    }
156
157    /// Deletes the copy saved under `snapshot_id`.
158    pub(crate) fn delete_snapshot(&mut self, snapshot_id: U256) {
159        self.snapshots.remove(&snapshot_id);
160    }
161
162    /// Deletes all saved copies.
163    pub(crate) fn clear_snapshots(&mut self) {
164        self.snapshots.clear();
165    }
166
167    /// Swaps transaction-specific opcode overrides without changing block overrides or snapshots.
168    pub fn swap_transaction_overrides(
169        &mut self,
170        fork_id: Option<LocalForkId>,
171        gas_price: &mut Option<u128>,
172        blob_hashes: &mut Option<Vec<B256>>,
173    ) {
174        let overrides = self.by_fork.entry(fork_id).or_default();
175        mem::swap(&mut overrides.gas_price, gas_price);
176        mem::swap(&mut overrides.blob_hashes, blob_hashes);
177        self.refresh_any_set();
178    }
179
180    /// Swaps a fork's current overrides without changing other forks or snapshot copies.
181    pub fn swap(&mut self, fork_id: Option<LocalForkId>, overrides: &mut EnvOverrides) {
182        mem::swap(self.by_fork.entry(fork_id).or_default(), overrides);
183        self.refresh_any_set();
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    const FORK: Option<LocalForkId> = Some(U256::from_limbs([1, 0, 0, 0]));
192    const SNAPSHOT: U256 = U256::from_limbs([7, 0, 0, 0]);
193
194    #[test]
195    fn override_values() {
196        let mut overrides = EnvOverrides::default();
197        assert_eq!(overrides.basefee_override(), None);
198        assert_eq!(overrides.gas_price_override(), None);
199        assert_eq!(overrides.blob_hash_override(0), None);
200
201        overrides.implicit_basefee = Some(1);
202        assert_eq!(overrides.basefee_override(), Some(1));
203        overrides.basefee = Some(2);
204        assert_eq!(overrides.basefee_override(), Some(2));
205
206        overrides.gas_price = Some(3);
207        assert_eq!(overrides.gas_price_override(), Some(3));
208
209        let hash = B256::repeat_byte(1);
210        overrides.blob_hashes = Some(vec![hash]);
211        assert_eq!(overrides.blob_hash_override(0), Some(hash));
212        assert_eq!(overrides.blob_hash_override(1), Some(B256::ZERO));
213        assert_eq!(overrides.blob_hash_override(u64::MAX), Some(B256::ZERO));
214    }
215
216    #[test]
217    fn tracks_overrides_on_every_fork() {
218        let mut state = EnvOverrideState::default();
219        assert!(state.is_empty());
220        assert!(!state.is_any_set());
221
222        state.update(FORK, |o| o.gas_price = Some(1));
223        assert!(!state.is_empty());
224        assert!(state.is_any_set());
225        assert_eq!(state.get(FORK).and_then(EnvOverrides::gas_price_override), Some(1));
226
227        state.update(None, |o| o.chain_id = Some(3));
228        assert!(state.get(None).is_some_and(EnvOverrides::is_any_set), "a chain ID is an override");
229        state.update(None, |o| o.chain_id = None);
230
231        state.clear_implicit_basefee(Some(U256::from(2)));
232        assert!(state.get(Some(U256::from(2))).is_none(), "clearing must not insert an entry");
233        state.update(FORK, |o| o.implicit_basefee = Some(2));
234        state.clear_implicit_basefee(FORK);
235        assert_eq!(state.get(FORK).and_then(EnvOverrides::basefee_override), None);
236    }
237
238    #[test]
239    fn restores_snapshots() {
240        let mut state = EnvOverrideState::default();
241        state.update(None, |o| o.basefee = Some(1));
242        state.save_snapshot(SNAPSHOT);
243
244        state.update(None, |o| o.basefee = Some(2));
245        state.restore_snapshot(SNAPSHOT, false);
246        assert_eq!(state.get(None).and_then(EnvOverrides::basefee_override), Some(1));
247
248        // A kept snapshot can be restored again.
249        state.update(None, |o| o.basefee = Some(3));
250        state.restore_snapshot(SNAPSHOT, true);
251        assert_eq!(state.get(None).and_then(EnvOverrides::basefee_override), Some(1));
252
253        // A deleted snapshot is gone, so restoring it leaves the overrides untouched.
254        state.update(None, |o| o.basefee = Some(4));
255        state.restore_snapshot(SNAPSHOT, false);
256        assert_eq!(state.get(None).and_then(EnvOverrides::basefee_override), Some(4));
257    }
258
259    #[test]
260    fn deletes_snapshots() {
261        let mut state = EnvOverrideState::default();
262        state.save_snapshot(SNAPSHOT);
263        state.save_snapshot(SNAPSHOT + U256::from(1));
264        state.update(None, |o| o.basefee = Some(1));
265
266        state.delete_snapshot(SNAPSHOT);
267        state.restore_snapshot(SNAPSHOT, false);
268        assert!(state.is_any_set());
269
270        state.clear_snapshots();
271        state.restore_snapshot(SNAPSHOT + U256::from(1), false);
272        assert!(state.is_any_set());
273    }
274}