Skip to main content

foundry_evm_core/evm/
env.rs

1//! Execution environments and network extension state.
2
3use alloy_consensus::transaction::Recovered;
4use alloy_eips::eip4844::{BLOB_TX_MIN_BLOB_GASPRICE, fake_exponential};
5use alloy_primitives::{U256, map::AddressMap};
6use evm2::{Evm, EvmFeatures, EvmTypes, EvmTypesHost, Version, env::BlockEnv, evm::AccountInfo};
7use std::fmt::Debug;
8
9/// The spec, runtime version and block an EVM is built with.
10///
11/// Foundry's execution toggles map onto [`EvmFeatures`] of the [`Version`]:
12/// `disable_nonce_check` is `NONCE_CHECK`, `disable_balance_check` is `BALANCE_CHECK`,
13/// `disable_base_fee` is `BASE_FEE_CHECK`, `disable_block_gas_limit` is `BLOCK_GAS_LIMIT_CHECK`,
14/// `disable_eip3607` is `EIP3607`, `disable_fee_charge` is `FEE_CHARGE`,
15/// `disable_priority_fee_check` is `PRIORITY_FEE_CHECK` and `tx_chain_id_check` is
16/// `TX_CHAIN_ID_CHECK`. Size and memory limits are plain [`Version`] fields.
17pub struct EvmEnv<T: EvmTypesHost> {
18    /// Active network spec.
19    pub spec: T::SpecId,
20    /// Runtime version: chain ID, features, gas parameters and limits.
21    pub version: Version,
22    /// Block environment.
23    pub block: BlockEnv<T>,
24    /// Inspector-visible depth of top-level messages, such as a nested transaction's root.
25    pub initial_call_depth: u16,
26}
27
28impl<T: EvmTypesHost<SpecId: Debug>> Debug for EvmEnv<T> {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("EvmEnv")
31            .field("spec", &self.spec)
32            .field("version", &self.version)
33            .field("block", &self.block)
34            .field("initial_call_depth", &self.initial_call_depth)
35            .finish()
36    }
37}
38
39impl<T: EvmTypesHost> Clone for EvmEnv<T> {
40    fn clone(&self) -> Self {
41        *self
42    }
43}
44
45impl<T: EvmTypesHost> Copy for EvmEnv<T> {}
46
47impl<T: EvmTypesHost> EvmEnv<T> {
48    /// Creates an environment.
49    pub const fn new(spec: T::SpecId, version: Version, block: BlockEnv<T>) -> Self {
50        Self { spec, version, block, initial_call_depth: 0 }
51    }
52
53    /// Returns the chain ID.
54    pub const fn chain_id(&self) -> u64 {
55        self.version.chain_id
56    }
57
58    /// Sets the chain ID used by `CHAINID` and transaction validation.
59    pub const fn set_chain_id(&mut self, chain_id: u64) {
60        self.version.chain_id = chain_id;
61    }
62
63    /// Enables or disables `feature`.
64    pub const fn set_feature(&mut self, feature: EvmFeatures, enabled: bool) {
65        self.version.features.set(feature, enabled);
66    }
67
68    /// Sets the blob base fee from the excess blob gas.
69    pub fn set_blob_excess_gas(&mut self, excess_blob_gas: u64, base_fee_update_fraction: u64) {
70        self.block.blob_basefee = U256::from(fake_exponential(
71            BLOB_TX_MIN_BLOB_GASPRICE,
72            excess_blob_gas as u128,
73            base_fee_update_fraction as u128,
74        ));
75    }
76}
77
78/// Features Foundry toggles independently of the fork.
79pub const FOUNDRY_POLICY_FEATURES: EvmFeatures = {
80    let mut features = EvmFeatures::TX_CHAIN_ID_CHECK;
81    features.insert(EvmFeatures::NONCE_CHECK);
82    features.insert(EvmFeatures::BALANCE_CHECK);
83    features.insert(EvmFeatures::BALANCE_TOP_UP);
84    features.insert(EvmFeatures::BLOCK_GAS_LIMIT_CHECK);
85    features.insert(EvmFeatures::EIP3607);
86    features.insert(EvmFeatures::PRIORITY_FEE_CHECK);
87    features.insert(EvmFeatures::FEE_CHARGE);
88    features.insert(EvmFeatures::BASE_FEE_CHECK);
89    features.insert(EvmFeatures::CODE_SIZE_CHECK);
90    features
91};
92
93/// Returns `next` with Foundry's execution policy carried over from `current`.
94///
95/// `current_default` is the network's default version for the current spec. A policy feature or
96/// limit that differs from it was set by Foundry and survives the spec change; everything else,
97/// including gas parameters and fork features, comes from `next`.
98pub fn carry_execution_policy(
99    current_default: &Version,
100    current: &Version,
101    mut next: Version,
102) -> Version {
103    let disabled = current_default.features & FOUNDRY_POLICY_FEATURES & !current.features;
104    let enabled = current.features & FOUNDRY_POLICY_FEATURES & !current_default.features;
105    next.features = (next.features & !disabled) | enabled;
106    next.chain_id = current.chain_id;
107    macro_rules! carry_overridden {
108        ($($field:ident),*) => {$(
109            if current.$field != current_default.$field {
110                next.$field = current.$field;
111            }
112        )*};
113    }
114    carry_overridden!(
115        tx_gas_limit_cap,
116        tx_total_gas_cap,
117        memory_limit,
118        max_code_size,
119        max_initcode_size
120    );
121    // Every spec defaults the EIP-8037 total cap to `2^32 - 1`, so a disabled one always differs.
122    // Foundry disables the EIP-7825 cap with `u64::MAX`, which is also the default of specs
123    // before the cap, so a disabled cap survives moving to a spec that has one.
124    if current.tx_gas_limit_cap == u64::MAX {
125        next.tx_gas_limit_cap = u64::MAX;
126    }
127    next
128}
129
130/// Execution-family hooks for state Foundry changes outside ordinary EVM execution.
131///
132/// These operate on the running EVM, independently of factory configuration. evm2 still owns
133/// transaction and frame execution; the lifecycle and inspectors coordinate these hooks.
134pub trait FoundryExecutionHooks: EvmTypes {
135    /// Folds the running transaction's execution so far into network state derived from it, such
136    /// as Monad's reserve-balance tracker. Call it before Foundry changes that state outside
137    /// execution, then call [`Self::refresh_transaction`].
138    fn sync_transaction(_evm: &mut Evm<'_, Self>) {}
139
140    /// Rebases network state derived from the running transaction's state onto that state after
141    /// Foundry changed it outside execution, such as cheatcode writes and isolated calls. The
142    /// change itself is not execution: Monad's reserve-balance tracker recomputes the thresholds
143    /// of its tracked accounts without recording debits or credits.
144    fn refresh_transaction(_evm: &mut Evm<'_, Self>) {}
145
146    /// Like [`Self::refresh_transaction`], after a fork switch accepted the running transaction's
147    /// changes: `original` holds the transaction-start info of the persistent accounts it carried.
148    fn refresh_switched_transaction(
149        evm: &mut Evm<'_, Self>,
150        _original: &AddressMap<Option<AccountInfo>>,
151    ) {
152        Self::refresh_transaction(evm);
153    }
154
155    /// Returns how many levels below the transaction its handler runs `tx`'s top-level calls,
156    /// such as one for Tempo's AA transactions. A nested transaction lowers its initial call
157    /// depth by it, so its calls keep their depth in the surrounding trace.
158    fn tx_call_depth_offset(_tx: &Self::Tx) -> u16 {
159        0
160    }
161}
162
163/// Per-EVM network state, such as OP L1 block info or Monad's reserve-balance context.
164pub trait FoundryEvmExt<Tx>: SendableExt + Debug + Default + 'static {
165    /// Prepares the state for a standalone synthetic transaction.
166    fn for_transaction(&mut self, _tx: &Recovered<Tx>) {}
167
168    /// Prepares the state for the transaction at `index` of `current`, a block whose parent and
169    /// grandparent blocks contained `parent` and `grandparent`, such as when replaying a block.
170    fn for_block(
171        &mut self,
172        _grandparent: &[Recovered<Tx>],
173        _parent: &[Recovered<Tx>],
174        _current: &[Recovered<Tx>],
175        _index: usize,
176    ) {
177    }
178
179    /// Replaces the state of an EVM that may be executing with `ext`, such as one restored by a
180    /// snapshot revert, keeping the state of the frames still executing.
181    fn replace_while_executing(&mut self, ext: Self) {
182        *self = ext;
183    }
184
185    /// Returns whether `tx` is a canonical protocol transaction of the network, such as a Monad
186    /// staking syscall, which only executes with [`Self::set_protocol_replay`] enabled.
187    fn is_protocol_transaction(_tx: &Recovered<Tx>) -> bool {
188        false
189    }
190
191    /// Sets whether the next transaction continues the transaction state derived so far, such as
192    /// Monad's reserve-balance tracker, instead of starting its own. Isolated calls continue the
193    /// running transaction's.
194    fn set_preserve_transaction_state(&mut self, _preserve: bool) {}
195
196    /// Sets whether transactions from the network's protocol sender execute as protocol
197    /// transactions.
198    ///
199    /// Enable it only to replay trusted canonical chain history, after preparing the transaction
200    /// with [`Self::for_transaction`] or [`Self::for_block`], which disable it.
201    fn set_protocol_replay(&mut self, _enabled: bool) {}
202
203    /// Prepares the state for a synthetic transaction appended at the retained block cursor,
204    /// such as a test call or `vm.executeTransaction`.
205    ///
206    /// Networks without block-position state treat it as standalone (see
207    /// [`Self::for_transaction`]). The retained cursor itself does not move: only canonical
208    /// replays advance it, through [`Self::adopt_cursor`].
209    fn for_next_transaction(&mut self, tx: &Recovered<Tx>) {
210        self.for_transaction(tx);
211    }
212
213    /// Moves the retained block cursor to `cursor`'s, keeping the running transaction's own
214    /// position at the new cursor and every other state.
215    fn adopt_cursor(&mut self, _cursor: &Self) {}
216
217    /// Switches an EVM that may be executing to the parked context state `ext`, such as on a fork
218    /// switch.
219    ///
220    /// Networks whose context state is only a block cursor, such as Monad, keep the running
221    /// transaction's own state and adopt the context's cursor.
222    fn resume_context(&mut self, ext: Self) {
223        self.replace_while_executing(ext);
224    }
225}
226
227impl<Tx> FoundryEvmExt<Tx> for () {}
228
229/// Network extension state that can be copied without sharing thread-unsafe state.
230///
231/// Some extensions, such as Tempo's, share transaction-local state with their precompiles
232/// through `Rc`. [`StoredExt`] keeps such state outside a running EVM and across threads.
233///
234/// # Safety
235///
236/// [`Self::detached`] must return a value that shares no thread-unsafe state with `self` or any
237/// other value, and must not access thread-unsafe state of `self`.
238pub unsafe trait SendableExt: Clone {
239    /// Returns a copy that shares no thread-unsafe state with `self`.
240    fn detached(&self) -> Self {
241        self.clone()
242    }
243}
244
245// SAFETY: `()` holds no state.
246unsafe impl SendableExt for () {}
247
248/// Network extension state stored outside a running EVM, such as by a parked context or a
249/// snapshot.
250///
251/// The value enters and leaves only through [`SendableExt::detached`], so it never shares
252/// thread-unsafe state with another value and can move between threads.
253pub struct StoredExt<E>(E);
254
255impl<E: SendableExt> StoredExt<E> {
256    /// Stores a detached copy of `ext`.
257    pub fn new(ext: &E) -> Self {
258        Self(ext.detached())
259    }
260
261    /// Returns a detached copy of the stored state.
262    pub fn get(&self) -> E {
263        self.0.detached()
264    }
265
266    /// Returns the stored state.
267    pub fn into_inner(self) -> E {
268        self.0
269    }
270}
271
272impl<E: SendableExt> Clone for StoredExt<E> {
273    fn clone(&self) -> Self {
274        Self(self.0.detached())
275    }
276}
277
278impl<E> Debug for StoredExt<E> {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        f.debug_struct("StoredExt").finish_non_exhaustive()
281    }
282}
283
284// SAFETY: the stored value is created by `SendableExt::detached`, so no other value shares its
285// thread-unsafe state, and shared access only calls `detached`, which reads none of it.
286unsafe impl<E: SendableExt> Send for StoredExt<E> {}
287
288// SAFETY: see the `Send` implementation.
289unsafe impl<E: SendableExt> Sync for StoredExt<E> {}
290
291/// Network-only transaction outcome flags.
292///
293/// The shared `TxResult::stop` carries the outcome.
294pub trait FoundryTxResultExt: Clone + Debug + Default + 'static {
295    /// Returns whether an OP-stack deposit failed and kept only its mint and nonce bump.
296    fn is_failed_deposit(&self) -> bool {
297        false
298    }
299
300    /// Returns the number of leading call phases that committed in an included signed Base
301    /// EIP-8130 transaction.
302    ///
303    /// Other transactions, including EIP-8130 simulations, return `None`.
304    fn eip8130_committed_phases(&self) -> Option<u64> {
305        None
306    }
307}
308
309impl FoundryTxResultExt for () {}