Skip to main content

foundry_evm_core/evm/
mod.rs

1//! Foundry's execution stack on [evm2](https://github.com/alloy-rs/evm2).
2//!
3//! [`FoundryEvmNetwork`] binds an Alloy network to a [`FoundryEvmFactory`], which owns the
4//! network's evm2 type family ([`EvmTypesHost`]): spec, transaction, block and result extensions,
5//! the transaction registry and the precompiles. One marker exists per network family:
6//! [`EthEvmNetwork`], [`OpEvmNetwork`], [`BaseEvmNetwork`], [`MonadEvmNetwork`] and
7//! [`TempoEvmNetwork`].
8//!
9//! Transactions stay network-native until execution (see [`tx`](self::TxPayload)).
10//! [`ExecutionLifecycle`] owns the accepted state that evm2's `State` does not.
11//!
12//! [`crate::backend::Backend`] layers RPC forks and Foundry's cheatcode policy on top of the
13//! lifecycle.
14
15use alloy_consensus::{SignableTransaction, Signed, transaction::SignerRecoverable};
16use alloy_eips::Typed2718;
17use alloy_network::Network;
18use alloy_primitives::Signature;
19use alloy_rlp::Decodable;
20use evm2::{
21    Evm, EvmTypes, EvmTypesHost, ExecutionConfig, TxResult, Version, env::BlockEnv,
22    evm::precompile::PrecompileProvider, registry::TxRegistry,
23};
24use foundry_common::{FoundryReceiptResponse, FoundryTransactionBuilder, fmt::UIfmt};
25use foundry_evm_hardforks::ExecutionSpec;
26use foundry_evm_networks::NetworkConfigs;
27use serde::{Deserialize, Serialize};
28use std::fmt::Debug;
29
30mod db;
31pub use db::*;
32
33mod env;
34pub use env::*;
35
36mod fork;
37pub use fork::*;
38
39mod lifecycle;
40pub use lifecycle::*;
41
42mod snapshot;
43pub use snapshot::*;
44
45mod tx;
46pub use tx::*;
47
48#[cfg(feature = "base")]
49pub mod base;
50pub mod eth;
51#[cfg(feature = "monad")]
52pub mod monad;
53#[cfg(feature = "optimism")]
54pub mod op;
55pub mod tempo;
56
57#[cfg(feature = "base")]
58pub use base::BaseEvmNetwork;
59pub use eth::*;
60#[cfg(feature = "monad")]
61pub use monad::MonadEvmNetwork;
62#[cfg(feature = "optimism")]
63pub use op::OpEvmNetwork;
64pub use tempo::TempoEvmNetwork;
65
66#[cfg(test)]
67pub(crate) mod tests;
68
69/// Binds an Alloy network to an evm2 factory.
70///
71/// The factory's type family owns conversion from native Alloy transactions through
72/// [`FoundryTxConversion`]. Requests and signed envelopes stay network-native until execution.
73pub trait FoundryEvmNetwork: Copy + Debug + Default + 'static {
74    /// Alloy network used for RPC, signing and broadcasting.
75    type Network: Network<
76            TxEnvelope: Decodable
77                            + SignerRecoverable
78                            + From<Signed<<Self::Network as Network>::UnsignedTx>>
79                            + for<'d> Deserialize<'d>
80                            + Serialize
81                            + UIfmt,
82            UnsignedTx: SignableTransaction<Signature>,
83            TransactionRequest: FoundryTransactionBuilder<Self::Network>
84                                    + Default
85                                    + for<'d> Deserialize<'d>
86                                    + Serialize,
87            ReceiptResponse: FoundryReceiptResponse,
88        >;
89
90    /// evm2 factory executing this network.
91    type EvmFactory: FoundryEvmFactory<Types: FoundryTxConversion<Self::Network>>;
92}
93
94/// Enables EIP-7702 delegation resolution on `version`.
95///
96/// Existing delegations resolve on every spec; only authorization processing is fork-gated, by
97/// the transaction registry.
98pub(crate) const fn with_eip7702_delegations(mut version: Version) -> Version {
99    version.features.insert(evm2::EvmFeatures::EIP7702);
100    version
101}
102
103/// Builds Foundry-configured EVMs for one evm2 [`EvmTypesHost`] family.
104///
105/// Implementors provide configuration (version, registry, precompiles, extension state).
106/// Construction and spec changes are provided on top, so every network
107/// builds its EVM the same way.
108pub trait FoundryEvmFactory: Clone + Debug + Default + Send + Sync + 'static {
109    /// evm2 type family: spec, transaction, block, EVM and result extensions.
110    type Types: FoundryExecutionHooks
111        + EvmTypesHost<
112            SpecId: ExecutionSpec + Default + Debug + PartialEq + Send + Sync + Unpin,
113            Tx: Typed2718 + Clone + Debug + Send + Sync,
114            BlockEnvExt: Copy + Debug + Default + Send + Sync + 'static,
115            EvmExt: FoundryEvmExt<<Self::Types as EvmTypesHost>::Tx>,
116            TxResultExt: FoundryTxResultExt,
117        >;
118
119    /// Returns the default runtime version for `spec` on `chain_id`.
120    fn version(&self, spec: SpecOf<Self>, chain_id: u64) -> Version;
121
122    /// Returns the execution config (dispatch tables) for `spec` with runtime `version`.
123    fn execution_config(
124        &self,
125        spec: SpecOf<Self>,
126        version: Version,
127    ) -> ExecutionConfig<Self::Types> {
128        ExecutionConfig::for_spec_and_version(spec, version)
129    }
130
131    /// Returns the transaction handler registry for `spec`.
132    fn tx_registry(&self, spec: SpecOf<Self>) -> TxRegistry<Self::Types, TxResult<Self::Types>>;
133
134    /// Returns the precompiles for `env`, sharing any accounting state held by `ext`.
135    fn precompiles(
136        &self,
137        env: &EvmEnv<Self::Types>,
138        ext: &<Self::Types as EvmTypesHost>::EvmExt,
139    ) -> Box<dyn PrecompileProvider<Self::Types>>;
140
141    /// Returns fresh extension state for an EVM built with `env`.
142    fn evm_ext(&self, _env: &EvmEnv<Self::Types>) -> <Self::Types as EvmTypesHost>::EvmExt {
143        Default::default()
144    }
145
146    /// Returns this factory configured for an EVM over `db`, such as Base's activation admin for
147    /// the fork's source chain.
148    fn configure_for<D: FoundryDatabase + ?Sized>(
149        &self,
150        _db: &D,
151        _env: &EvmEnv<Self::Types>,
152    ) -> Self {
153        self.clone()
154    }
155
156    /// Returns this factory configured for `networks`, such as Celo's transfer precompile on
157    /// Ethereum.
158    fn with_networks(&self, _networks: NetworkConfigs) -> Self {
159        self.clone()
160    }
161
162    /// Seeds network state into a newly created EVM, such as Tempo genesis or Base sentinels.
163    fn initialize_evm(&self, _evm: &mut Evm<'_, Self::Types>, _is_forked: bool) {}
164
165    /// Creates a Foundry-configured EVM without an inspector.
166    fn create_evm<'a>(
167        &self,
168        db: impl FoundryDatabase + 'a,
169        env: EvmEnv<Self::Types>,
170    ) -> Evm<'a, Self::Types> {
171        let factory = self.configure_for(&db, &env);
172        let is_forked = db.is_forked_mode();
173        let ext = factory.evm_ext(&env);
174        let mut evm = factory.new_evm_with_ext(db, env, ext);
175        factory.initialize_evm(&mut evm, is_forked);
176        evm
177    }
178
179    /// Creates a Foundry-configured EVM with fresh extension state, without seeding network state.
180    ///
181    /// For inherited extension state, configure the factory with [`Self::configure_for`] and use
182    /// [`Self::new_evm_with_ext`] instead.
183    fn new_evm<'a>(
184        &self,
185        db: impl FoundryDatabase + 'a,
186        env: EvmEnv<Self::Types>,
187    ) -> Evm<'a, Self::Types> {
188        let factory = self.configure_for(&db, &env);
189        let ext = factory.evm_ext(&env);
190        factory.new_evm_with_ext(db, env, ext)
191    }
192
193    /// Creates a Foundry-configured EVM with the given network extension state, such as the
194    /// running EVM's for a nested frame.
195    ///
196    /// The factory must already be configured for the source database and environment. This
197    /// neither reconfigures it nor seeds network state; `db` may be a temporary placeholder.
198    fn new_evm_with_ext<'a>(
199        &self,
200        db: impl FoundryDatabase + 'a,
201        env: EvmEnv<Self::Types>,
202        ext: <Self::Types as EvmTypesHost>::EvmExt,
203    ) -> Evm<'a, Self::Types> {
204        db.set_eip161(env.version.feature(evm2::EvmFeatures::EIP161));
205        let precompiles = self.precompiles(&env, &ext);
206        let EvmEnv { spec, version, block, initial_call_depth } = env;
207        let mut evm = Evm::new_with_execution_config_and_ext(
208            self.execution_config(spec, version),
209            spec,
210            block,
211            self.tx_registry(spec),
212            db,
213            precompiles,
214            ext,
215        );
216        evm.set_initial_call_depth(initial_call_depth);
217        evm
218    }
219
220    /// Returns `env` with `spec`, keeping Foundry's execution toggles and limits.
221    fn env_with_spec(&self, env: EvmEnv<Self::Types>, spec: SpecOf<Self>) -> EvmEnv<Self::Types> {
222        let current_default = self.version(env.spec, env.chain_id());
223        let next = self.version(spec, env.chain_id());
224        let version = carry_execution_policy(&current_default, &env.version, next);
225        // A nested transaction's root, such as a `vm.transact` replay, keeps its depth.
226        EvmEnv { version, spec, ..env }
227    }
228
229    /// Switches `evm` to `env`: its block, spec and chain ID, keeping Foundry's execution toggles
230    /// and limits.
231    ///
232    /// This rebuilds the dispatch tables, the transaction registry and the precompiles, so opcode
233    /// and precompile availability follows the new spec. It must not be called while `evm` is
234    /// executing.
235    fn set_env(&self, evm: &mut Evm<'_, Self::Types>, env: EvmEnv<Self::Types>) {
236        let current = *evm.version();
237        let current_default = self.version(evm.config_spec_id(), current.chain_id);
238        let next = self.version(env.spec, env.chain_id());
239        let mut version = carry_execution_policy(&current_default, &current, next);
240        version.chain_id = env.chain_id();
241        let EvmEnv { spec, block, .. } = env;
242        let precompiles = self.precompiles(&EvmEnv::new(spec, version, block), evm.ext());
243        evm.set_block_and_execution_config(
244            block,
245            self.execution_config(spec, version),
246            spec,
247            self.tx_registry(spec),
248            precompiles,
249        );
250    }
251}
252
253/// Returns the environment `evm` currently executes with.
254pub const fn evm_env<T: EvmTypes>(evm: &Evm<'_, T>) -> EvmEnv<T> {
255    EvmEnv {
256        spec: evm.config_spec_id(),
257        version: *evm.version(),
258        block: *evm.block(),
259        initial_call_depth: evm.initial_call_depth(),
260    }
261}
262
263/// Convenience type aliases for accessing associated types through [`FoundryEvmNetwork`].
264pub type EvmFactoryFor<FEN> = <FEN as FoundryEvmNetwork>::EvmFactory;
265pub type TypesFor<FEN> = <EvmFactoryFor<FEN> as FoundryEvmFactory>::Types;
266pub type SpecOf<F> = <<F as FoundryEvmFactory>::Types as EvmTypesHost>::SpecId;
267pub type SpecFor<FEN> = <TypesFor<FEN> as EvmTypesHost>::SpecId;
268pub type BlockEnvFor<FEN> = BlockEnv<TypesFor<FEN>>;
269pub type TxFor<FEN> = <TypesFor<FEN> as EvmTypesHost>::Tx;
270pub type EvmEnvFor<FEN> = EvmEnv<TypesFor<FEN>>;
271pub type ChainFor<FEN> = <TypesFor<FEN> as EvmTypesHost>::EvmExt;
272pub type TxResultFor<FEN> = TxResult<TypesFor<FEN>>;
273pub type FoundryEvmFor<'a, FEN> = Evm<'a, TypesFor<FEN>>;
274pub type InterpreterFor<'frame, 'host, FEN> =
275    evm2::interpreter::Interpreter<'frame, 'host, TypesFor<FEN>>;
276pub type MessageFor<FEN> = evm2::interpreter::Message<TypesFor<FEN>>;
277pub type MessageResultFor<FEN> = evm2::interpreter::MessageResult<TypesFor<FEN>>;
278pub type NetworkFor<FEN> = <FEN as FoundryEvmNetwork>::Network;
279pub type TxEnvelopeFor<FEN> = <NetworkFor<FEN> as Network>::TxEnvelope;
280pub type TransactionRequestFor<FEN> = <NetworkFor<FEN> as Network>::TransactionRequest;