Skip to main content

foundry_evm_core/backend/
mod.rs

1//! Foundry's executor backend: RPC forks, persistent accounts, snapshots and cheatcode policy over
2//! evm2.
3//!
4//! # Execution contract
5//!
6//! [`Backend`] owns an [`ExecutionLifecycle`]: the accepted state of every execution context (the
7//! local database and each fork), the active selection, persistent accounts and snapshots. It does
8//! not implement a database trait; executions run on [`evm2::Evm`]s built from it:
9//!
10//! 1. [`Backend::create_evm`] builds an EVM over the active context. The EVM does not borrow the
11//!    backend: it reads the context's accepted state through a shared view.
12//! 2. While the EVM runs, the backend is free. Inspectors that implement cheatcodes hold `&mut
13//!    Backend` (or a [`CowBackend`]) for the duration of the execution, and call its operations
14//!    with the `&mut Evm` they receive from their hooks. Operations that act on the running
15//!    transaction, such as fork selection, snapshots, `vm.transact` or account refreshes, take that
16//!    EVM explicitly together with the [`ExecutionPhase`]; operations between executions, such as
17//!    [`Backend::insert_account_info`], do not.
18//! 3. After a committed execution, [`Backend::park`] accepts the EVM's state, environment and
19//!    network state back into the active context. Dropping the EVM instead discards everything it
20//!    did, as for calls.
21//!
22//! [`Backend::inspect_commit`] wraps these steps for executions that need no backend access from
23//! their inspector.
24
25use crate::{
26    constants::{CALLER, CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER},
27    evm::{
28        BackingDb, BlockContext, ChainFor, EthEvmNetwork, EvmEnvFor, EvmFactoryFor, ExecutedNested,
29        ExecutionLifecycle, ExecutionPhase, ForkDb, ForkInfo, ForkPosition, FoundryDatabase,
30        FoundryEvmExt, FoundryEvmFactory, FoundryEvmFor, FoundryEvmNetwork, FoundryExecutionHooks,
31        FoundryTxConversion, PersistentWrite, PreparedTx, SpecFor, StoredExt,
32        TransactionRequestFor, TxFor, TxResultFor, TypesFor, block_txs, evm_env, full_transactions,
33        merge_untracked_nested_changes,
34    },
35    fork::{BlockEnv, CreateFork, Fork as RemoteFork, ForkId, ForkResult, MultiFork},
36    opts::{EvmOpts, ExecutionSpecContext},
37    utils::{
38        apply_chain_and_block_specific_env_changes_for_chain,
39        apply_chain_specific_tx_replay_env_changes_for_chain, block_env_from_header,
40    },
41};
42use alloy_chains::{Chain, NamedChain};
43use alloy_consensus::{BlockHeader, Transaction as _, Typed2718, transaction::Recovered};
44use alloy_eips::BlockNumHash;
45use alloy_genesis::GenesisAccount;
46use alloy_network::{AnyNetwork, AnyRpcBlock, AnyRpcTransaction, TransactionResponse};
47use alloy_primitives::{
48    Address, B256, Bytes, ChainId, KECCAK256_EMPTY, TxKind, U256, keccak256,
49    map::{AddressMap, AddressSet, HashSet},
50    uint,
51};
52use alloy_rpc_types::{BlockNumberOrTag, BlockTransactions};
53use evm2::{
54    EvmFeatures, Inspector,
55    bytecode::Bytecode,
56    evm::{
57        AccountInfo, Cache, DbResult, DynDatabase, EmptyDB, InMemoryDB, PendingState, State,
58        StateSnapshot,
59        bal::{Bal, BlockAccessIndex},
60    },
61};
62use eyre::WrapErr;
63use foundry_common::{SYSTEM_TRANSACTION_TYPE, is_known_system_sender};
64use foundry_evm_networks::NetworkConfigs;
65pub use foundry_fork_db::{
66    AccountFetchPolicy, BlockchainDb, ForkBlock, ForkBlockEnv, SharedBackend,
67    cache::BlockchainDbMeta,
68};
69use std::{collections::BTreeMap, mem, sync::Arc, time::Instant};
70
71mod diagnostic;
72pub use diagnostic::RevertDiagnostic;
73
74mod bal;
75
76mod error;
77pub use error::{
78    BackendError, BackendResult, DatabaseError, DatabaseResult, TransactionValidationError,
79    handler_error, transaction_error,
80};
81
82mod cow;
83pub use cow::CowBackend;
84
85mod snapshot;
86pub use snapshot::RevertStateSnapshotAction;
87
88#[cfg(test)]
89mod tests;
90
91/// Represents a numeric `ForkId` valid only for the existence of the `Backend`.
92///
93/// The difference between `ForkId` and `LocalForkId` is that `ForkId` tracks pairs of `endpoint +
94/// block` which can be reused by multiple tests, whereas the `LocalForkId` is unique within a test
95pub type LocalForkId = U256;
96
97/// Backing database of an RPC fork: the shared fork cache, read by evm2.
98pub type RpcForkDb = ForkDb<SharedBackend<AnyNetwork, BlockEnv>>;
99
100/// All accounts that will have persistent storage across fork swaps.
101const DEFAULT_PERSISTENT_ACCOUNTS: [Address; 3] =
102    [CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, CALLER];
103
104/// `bytes32("failed")`, as a storage slot key into [`CHEATCODE_ADDRESS`].
105///
106/// Used by all `forge-std` test contracts and newer `DSTest` test contracts as a global marker for
107/// a failed test.
108pub const GLOBAL_FAIL_SLOT: U256 =
109    uint!(0x6661696c65640000000000000000000000000000000000000000000000000000_U256);
110
111/// Account field changed by an out-of-band fork RPC mutation.
112#[derive(Clone, Copy, Debug)]
113pub enum ForkAccountField {
114    Balance,
115    Nonce,
116    Code,
117}
118
119/// Block data required to execute or position a fork at a transaction.
120struct TransactionForkTarget {
121    /// Block whose state the transaction executes on.
122    fork_block: BlockNumHash,
123    /// The transaction.
124    transaction: AnyRpcTransaction,
125    /// Block containing the transaction, or the latest block for a pending transaction.
126    block: AnyRpcBlock,
127    /// Whether the transaction is mined.
128    mined: bool,
129    /// Index of the transaction in `block`, if it is mined.
130    index: Option<usize>,
131}
132
133/// Foundry's executor backend.
134///
135/// See the [module documentation](self) for the execution contract. Cloning a backend clones the
136/// accepted state of every context without copying it (contexts share their caches
137/// copy-on-write), which parallel fuzzing relies on.
138#[derive(Clone, Debug)]
139pub struct Backend<FEN: FoundryEvmNetwork = EthEvmNetwork> {
140    /// Network configuration of the executed chain.
141    networks: NetworkConfigs,
142    /// Manager of the remote fork caches.
143    forks: MultiFork,
144    /// Contexts, fork selection, persistent accounts and snapshots.
145    lifecycle: ExecutionLifecycle<EvmFactoryFor<FEN>>,
146    /// Accounts allowed to execute cheatcodes.
147    cheatcode_access: AddressSet,
148    /// Caller of the test.
149    caller: Option<Address>,
150    /// Whether a reverted state snapshot recorded a test failure.
151    has_state_snapshot_failure: bool,
152    /// Block number the active fork reports instead of its own.
153    fork_block_number_override: Option<u64>,
154    /// Block access list attached to EVMs created until the next park.
155    bal: Option<(Arc<Bal>, BlockAccessIndex)>,
156}
157
158impl<FEN: FoundryEvmNetwork> Backend<FEN> {
159    /// Creates a backend with a spawned fork manager.
160    ///
161    /// If `fork` is `Some`, execution starts on that fork with environment `env`, otherwise on an
162    /// empty local database.
163    pub fn spawn(fork: Option<CreateFork>, env: EvmEnvFor<FEN>) -> eyre::Result<Self> {
164        Self::new(MultiFork::spawn(), fork, env)
165    }
166
167    /// Resolves the fork once, configuring its environment before initializing network state.
168    pub fn spawn_fork(
169        fork: CreateFork,
170        configure_env: impl FnOnce(&mut EvmEnvFor<FEN>, ExecutionSpecContext),
171    ) -> eyre::Result<Self> {
172        Self::new_fork(MultiFork::spawn(), fork, configure_env)
173    }
174
175    /// Creates a backend that starts on `fork` at its resolved block's environment, or locally
176    /// with `local_env`.
177    pub fn spawn_source(fork: Option<CreateFork>, local_env: EvmEnvFor<FEN>) -> eyre::Result<Self> {
178        match fork {
179            Some(fork) => Self::spawn_fork(fork, |_, _| {}),
180            None => Self::spawn(None, local_env),
181        }
182    }
183
184    /// Like [`Self::spawn_fork`], using `forks` for remote fork caches.
185    fn new_fork(
186        forks: MultiFork,
187        fork: CreateFork,
188        configure_env: impl FnOnce(&mut EvmEnvFor<FEN>, ExecutionSpecContext),
189    ) -> eyre::Result<Self> {
190        let opts = &fork.evm_opts;
191        let resolved = forks.create_fork(fork.clone())?;
192        let context = resolved.fork.context();
193        let chain_id = opts.chain_id_override().unwrap_or(context.execution_chain_id);
194        let mut env = opts.fork_env_from_block::<FEN, AnyNetwork>(
195            chain_id,
196            context.source_chain_id,
197            &resolved.fork.block,
198        );
199        configure_env(
200            &mut env,
201            ExecutionSpecContext::fork(context.source_chain_id, context.hardfork),
202        );
203
204        let track = fork.evm_opts.networks.is_monad();
205        let mut backend = Self::with_fork_manager(forks, EmptyDB::default(), env);
206        let id = backend.insert_prepared_fork(fork.url, resolved, env, track)?;
207        let mut evm = backend.lifecycle.create_evm();
208        backend.lifecycle.select_fork(&mut evm, Some(id), ExecutionPhase::Boundary)?;
209        backend.lifecycle.park(evm);
210        Ok(backend)
211    }
212
213    /// Creates a backend that uses `forks` for remote fork caches.
214    ///
215    /// If `fork` is `Some`, execution starts on that fork with environment `env` exactly, otherwise
216    /// on an empty local database. Prefer [`Self::spawn`].
217    pub fn new(
218        forks: MultiFork,
219        fork: Option<CreateFork>,
220        env: EvmEnvFor<FEN>,
221    ) -> eyre::Result<Self> {
222        trace!(target: "backend", forking_mode=?fork.is_some(), "creating executor backend");
223        let mut backend = Self::with_fork_manager(forks, EmptyDB::default(), env);
224        if let Some(fork) = fork {
225            let track = fork.evm_opts.networks.is_monad();
226            let id = backend.insert_fork(fork, Some(env), track)?;
227            let mut evm = backend.lifecycle.create_evm();
228            backend.lifecycle.select_fork(&mut evm, Some(id), ExecutionPhase::Boundary)?;
229            backend.lifecycle.park(evm);
230        }
231        Ok(backend)
232    }
233
234    /// Creates a backend executing locally over `db`, such as an in-memory database.
235    pub fn with_db(db: impl BackingDb, env: EvmEnvFor<FEN>) -> Self {
236        Self::with_fork_manager(MultiFork::spawn(), db, env)
237    }
238
239    fn with_fork_manager(forks: MultiFork, db: impl BackingDb, env: EvmEnvFor<FEN>) -> Self {
240        let mut lifecycle = ExecutionLifecycle::new(EvmFactoryFor::<FEN>::default(), db, env);
241        for account in DEFAULT_PERSISTENT_ACCOUNTS {
242            lifecycle.forks_mut().add_persistent(account);
243        }
244        // Seed network state (genesis, sentinels) so reads between executions see it.
245        let evm = lifecycle.create_evm();
246        lifecycle.park(evm);
247        Self {
248            networks: NetworkConfigs::default(),
249            forks,
250            lifecycle,
251            cheatcode_access: AddressSet::default(),
252            caller: None,
253            has_state_snapshot_failure: false,
254            fork_block_number_override: None,
255            bal: None,
256        }
257    }
258
259    /// Clones execution state with an independent registry for newly created forks.
260    ///
261    /// Remote caches remain shared, but forks created by this execution are released with it.
262    pub fn clone_with_fork_scope(&self) -> eyre::Result<Self> {
263        let mut backend = self.clone();
264        backend.forks = self.forks.scoped()?;
265        Ok(backend)
266    }
267
268    /// Creates an empty local backend sharing this backend's fork manager and environment.
269    pub fn clone_empty(&self) -> Self {
270        self.clone_empty_with_env(self.lifecycle.active().env)
271    }
272
273    /// Creates an empty local backend sharing this backend's fork manager, with network state
274    /// seeded at `env`.
275    ///
276    /// Network state can depend on the hardfork, such as Tempo's genesis, so a test contract pinned
277    /// to another hardfork needs its own seed.
278    pub fn clone_empty_with_env(&self, env: EvmEnvFor<FEN>) -> Self {
279        let mut backend = Self::with_fork_manager(self.forks.clone(), EmptyDB::default(), env);
280        backend.set_networks(self.networks);
281        backend
282    }
283
284    /// Replaces this backend with one starting on `fork` at its resolved block's environment, or
285    /// locally with `local_env`, reusing the fork manager's remote caches.
286    pub fn replace_fork(
287        &mut self,
288        fork: Option<CreateFork>,
289        local_env: EvmEnvFor<FEN>,
290    ) -> eyre::Result<()> {
291        let networks = self.networks;
292        let forks = self.forks.clone();
293        *self = match fork {
294            Some(fork) => Self::new_fork(forks, fork, |_, _| {})?,
295            None => Self::new(forks, None, local_env)?,
296        };
297        self.set_networks(networks);
298        Ok(())
299    }
300
301    /// Returns the remote fork of the active context, if execution is forked over RPC.
302    pub fn fork(&self) -> Option<RemoteFork> {
303        self.active_fork_info()?.remote.clone()
304    }
305
306    /// Builds execution environments from this backend's selected remote block.
307    pub async fn env(
308        &self,
309        opts: &EvmOpts,
310    ) -> eyre::Result<(EvmEnvFor<FEN>, TransactionRequestFor<FEN>)> {
311        opts.env_at_fork::<FEN>(self.fork().as_ref()).await
312    }
313
314    /// Checks library-linking availability against this backend's remote state.
315    pub async fn can_use_create2_deployer(&self, deployer: Address) -> eyre::Result<bool> {
316        let Some(fork) = self.fork() else {
317            return Ok(deployer == DEFAULT_CREATE2_DEPLOYER);
318        };
319        let mut request = self
320            .active_fork_options()
321            .ok_or_else(|| eyre::eyre!("active fork configuration is unavailable"))?;
322        request.evm_opts.create2_deployer = deployer;
323        request.evm_opts.can_use_create2_deployer_at(Some(&fork)).await
324    }
325
326    /// Reads a sender nonce at this backend's remote block before local execution.
327    pub async fn transaction_count(&self, sender: Address) -> eyre::Result<u64> {
328        let request =
329            self.active_fork_options().ok_or_else(|| eyre::eyre!("backend is not forked"))?;
330        let fork = self.fork().ok_or_else(|| eyre::eyre!("backend is not forked over RPC"))?;
331        request.evm_opts.transaction_count_at_fork(sender, &fork).await
332    }
333
334    /// Returns the active network configuration.
335    pub const fn networks(&self) -> NetworkConfigs {
336        self.networks
337    }
338
339    /// Sets the active network configuration.
340    pub fn set_networks(&mut self, networks: NetworkConfigs) {
341        self.networks = networks;
342        let factory = self.lifecycle.factory().with_networks(networks);
343        self.lifecycle.set_factory(factory);
344    }
345
346    /// Sets the block number the active fork reports while executing transactions of that block
347    /// on top of its parent's state.
348    pub const fn set_fork_block_number_override(&mut self, block_number: u64) {
349        self.fork_block_number_override = Some(block_number);
350    }
351
352    /// Returns the EVM factory.
353    pub const fn factory(&self) -> &EvmFactoryFor<FEN> {
354        self.lifecycle.factory()
355    }
356
357    /// Returns the execution lifecycle, for read-only inspection of contexts and forks.
358    pub const fn lifecycle(&self) -> &ExecutionLifecycle<EvmFactoryFor<FEN>> {
359        &self.lifecycle
360    }
361
362    /// Returns the environment of the active context, as of the last park, with a fork's own chain
363    /// ID.
364    pub fn evm_env(&self) -> EvmEnvFor<FEN> {
365        self.lifecycle.active().env
366    }
367
368    /// Returns the environment of the active context for modification between executions.
369    pub fn evm_env_mut(&mut self) -> &mut EvmEnvFor<FEN> {
370        &mut self.lifecycle.active_mut().env
371    }
372
373    /// Sets the spec of the active context, keeping Foundry's execution policy.
374    pub fn set_spec_id(&mut self, spec: impl Into<SpecFor<FEN>>) -> &mut Self {
375        let env = self.evm_env();
376        *self.evm_env_mut() = self.lifecycle.factory().env_with_spec(env, spec.into());
377        self
378    }
379
380    // ---- Executions ----
381
382    /// Creates an EVM over the active context. See the [module documentation](self).
383    pub fn create_evm<'a>(&self) -> FoundryEvmFor<'a, FEN> {
384        let mut evm = self.lifecycle.create_evm();
385        self.apply_bal(&mut evm);
386        evm
387    }
388
389    /// Accepts a committed EVM's state, environment and network state into the active context,
390    /// and detaches the block access list set with [`Self::set_bal`].
391    pub fn park(&mut self, evm: FoundryEvmFor<'_, FEN>) {
392        self.lifecycle.park(evm);
393        self.bal = None;
394    }
395
396    /// Removes `address` from the running transaction's base warmth, see
397    /// [`ExecutionLifecycle::remove_prewarm`].
398    pub fn remove_prewarm(&mut self, state: &mut State<'_>, address: &Address) {
399        self.lifecycle.remove_prewarm(state, address);
400    }
401
402    /// Takes the persistent warmth contexts kept for the running transaction, see
403    /// [`ExecutionLifecycle::take_persistent_warmth`].
404    pub fn take_persistent_warmth(&mut self) -> Vec<(Option<U256>, AddressMap<HashSet<U256>>)> {
405        self.lifecycle.take_persistent_warmth()
406    }
407
408    /// Hands back persistent warmth taken with [`Self::take_persistent_warmth`].
409    pub fn restore_persistent_warmth(
410        &mut self,
411        warmth: Vec<(Option<U256>, AddressMap<HashSet<U256>>)>,
412    ) {
413        self.lifecycle.restore_persistent_warmth(warmth);
414    }
415
416    /// Executes `tx` over the active context with `inspector` and accepts its state.
417    pub fn inspect_commit<'a>(
418        &mut self,
419        tx: &Recovered<TxFor<FEN>>,
420        inspector: impl Inspector<TypesFor<FEN>> + 'a,
421    ) -> eyre::Result<TxResultFor<FEN>> {
422        let mut evm: FoundryEvmFor<'a, FEN> = self.create_evm();
423        evm.set_inspector(inspector);
424        evm.ext_mut().for_next_transaction(tx);
425        let result = evm.transact(tx).map_err(handler_error)?.commit();
426        evm.clear_inspector();
427        self.park(evm);
428        Ok(result)
429    }
430
431    /// Records the caller and test contract of the next test execution.
432    ///
433    /// The test contract is the call target, or the address `caller` creates at its current nonce.
434    pub fn initialize(&mut self, caller: Address, kind: TxKind) {
435        self.set_caller(caller);
436        let test_contract = match kind {
437            TxKind::Call(to) => to,
438            TxKind::Create => {
439                let nonce = self.basic(caller).ok().flatten().map_or(0, |account| account.nonce);
440                caller.create(nonce)
441            }
442        };
443        self.set_test_contract(test_contract);
444    }
445
446    // ---- Accepted state between executions ----
447
448    /// Returns an account of the active context's accepted state.
449    pub fn basic(&self, address: Address) -> DbResult<Option<AccountInfo>> {
450        let mut account = self.lifecycle.accepted_db().get_account(&address)?;
451        if let Some(account) = &mut account
452            && account.code.is_none()
453            && !account.is_empty_code_hash()
454        {
455            account.code = Some(self.code_by_hash(account.code_hash)?);
456        }
457        Ok(account)
458    }
459
460    /// Returns code of the active context's accepted state.
461    pub fn code_by_hash(&self, code_hash: B256) -> DbResult<Bytecode> {
462        self.lifecycle.accepted_db().get_code_by_hash(&code_hash)
463    }
464
465    /// Returns a storage slot of the active context's accepted state.
466    pub fn storage(&self, address: Address, slot: U256) -> DbResult<U256> {
467        self.lifecycle.accepted_db().get_storage(&address, &slot)
468    }
469
470    /// Returns a block hash of the active context.
471    pub fn block_hash(&self, number: U256) -> DbResult<B256> {
472        self.lifecycle.accepted_db().get_block_hash(&number)
473    }
474
475    /// Inserts account info into the active context's accepted state.
476    ///
477    /// Use this between executions only; a running EVM does not observe it.
478    pub fn insert_account_info(&mut self, address: Address, mut account: AccountInfo) {
479        let cache = self.lifecycle.accepted_mut();
480        if let Some(code) = account.code.take()
481            && !code.is_empty()
482        {
483            if account.is_empty_code_hash() || account.code_hash.is_zero() {
484                account.code_hash = code.hash_slow();
485            }
486            cache.contracts.insert(account.code_hash, code);
487        }
488        if account.code_hash.is_zero() {
489            account.code_hash = KECCAK256_EMPTY;
490        }
491        cache.accounts.insert(address, Some(account));
492    }
493
494    /// Inserts a value into an account's storage without overriding account info.
495    ///
496    /// Use this between executions only; a running EVM does not observe it.
497    pub fn insert_account_storage(&mut self, address: Address, slot: U256, value: U256) {
498        self.lifecycle.accepted_mut().storage.entry(address).or_default().slots.insert(slot, value);
499    }
500
501    /// Replaces an account's storage without overriding account info.
502    ///
503    /// When forking, every slot not in `storage` reads as zero instead of being fetched. Use this
504    /// between executions only; a running EVM does not observe it.
505    pub fn replace_account_storage(
506        &mut self,
507        address: Address,
508        storage: impl IntoIterator<Item = (U256, U256)>,
509    ) {
510        let account = self.lifecycle.accepted_mut().storage.entry(address).or_default();
511        account.wipe();
512        account.slots.extend(storage);
513    }
514
515    /// Switches the running `evm` to `env`, such as for `vm.chainId` or `vm.setEvmVersion`. See
516    /// [`ExecutionLifecycle::set_env`].
517    pub fn set_env(
518        &mut self,
519        evm: &mut FoundryEvmFor<'_, FEN>,
520        env: EvmEnvFor<FEN>,
521        phase: ExecutionPhase,
522    ) {
523        self.lifecycle.set_env(evm, env, phase);
524    }
525
526    /// Accepts a detached transaction's state, such as a call's, into the active context's
527    /// accepted state.
528    ///
529    /// Use this between executions only; a running EVM does not observe it.
530    pub fn commit_pending(&mut self, pending: &PendingState) {
531        let mut db =
532            InMemoryDB { cache: mem::take(self.lifecycle.accepted_mut()), ..Default::default() };
533        db.commit_pending(pending);
534        *self.lifecycle.accepted_mut() = db.cache;
535    }
536
537    // ---- Test configuration ----
538
539    /// Sets the address of the `DSTest` contract that is being executed.
540    ///
541    /// This marks the contract as persistent and grants it cheatcode access.
542    pub fn set_test_contract(&mut self, account: Address) -> &mut Self {
543        trace!(?account, "setting test account");
544        self.lifecycle.forks_mut().add_persistent(account);
545        self.cheatcode_access.insert(account);
546        self
547    }
548
549    /// Sets the caller address and grants it cheatcode access.
550    pub fn set_caller(&mut self, account: Address) -> &mut Self {
551        trace!(?account, "setting caller account");
552        self.caller = Some(account);
553        self.cheatcode_access.insert(account);
554        self
555    }
556
557    /// Returns whether a reverted state snapshot recorded a test failure.
558    ///
559    /// If an error occurs in a restored state snapshot, the test is considered failed.
560    pub const fn has_state_snapshot_failure(&self) -> bool {
561        self.has_state_snapshot_failure
562    }
563
564    /// Sets the state snapshot failure flag.
565    pub const fn set_state_snapshot_failure(&mut self, has_state_snapshot_failure: bool) {
566        self.has_state_snapshot_failure = has_state_snapshot_failure;
567    }
568
569    // ---- Persistent accounts and cheatcode access ----
570
571    /// Returns whether `account` persists across fork switches.
572    pub fn is_persistent(&self, account: &Address) -> bool {
573        self.lifecycle.forks().is_persistent(account)
574    }
575
576    /// Marks `account` as persistent across fork switches. Returns whether it was not yet.
577    pub fn add_persistent_account(&mut self, account: Address) -> bool {
578        trace!(?account, "add persistent account");
579        self.lifecycle.forks_mut().add_persistent(account)
580    }
581
582    /// Stops `account` from persisting across fork switches. Returns whether it was persistent.
583    pub fn remove_persistent_account(&mut self, account: &Address) -> bool {
584        trace!(?account, "remove persistent account");
585        self.lifecycle.forks_mut().remove_persistent(account)
586    }
587
588    /// Marks all `accounts` as persistent.
589    pub fn extend_persistent_accounts(&mut self, accounts: impl IntoIterator<Item = Address>) {
590        for account in accounts {
591            self.add_persistent_account(account);
592        }
593    }
594
595    /// Grants `account` cheatcode access. Returns whether it did not have access yet.
596    pub fn allow_cheatcode_access(&mut self, account: Address) -> bool {
597        trace!(?account, "allow cheatcode access");
598        self.cheatcode_access.insert(account)
599    }
600
601    /// Returns whether `account` has cheatcode access.
602    pub fn has_cheatcode_access(&self, account: &Address) -> bool {
603        self.cheatcode_access.contains(account)
604    }
605
606    /// Ensures that `account` has cheatcode access.
607    pub fn ensure_cheatcode_access(&self, account: &Address) -> Result<(), BackendError> {
608        if !self.has_cheatcode_access(account) {
609            return Err(BackendError::NoCheats(*account));
610        }
611        Ok(())
612    }
613
614    /// Like [`Self::ensure_cheatcode_access`], but only enforced while forked.
615    pub fn ensure_cheatcode_access_forking_mode(
616        &self,
617        account: &Address,
618    ) -> Result<(), BackendError> {
619        if self.is_forked_mode() {
620            return self.ensure_cheatcode_access(account);
621        }
622        Ok(())
623    }
624
625    // ---- Fork queries ----
626
627    /// Returns the active fork, or `None` for local execution.
628    pub const fn active_fork_id(&self) -> Option<LocalForkId> {
629        self.lifecycle.forks().active()
630    }
631
632    /// Returns whether execution is forked.
633    pub const fn is_forked_mode(&self) -> bool {
634        self.active_fork_id().is_some()
635    }
636
637    /// Returns whether `id` is the active fork.
638    pub fn is_active_fork(&self, id: LocalForkId) -> bool {
639        self.active_fork_id() == Some(id)
640    }
641
642    /// Returns the identity of the active fork.
643    pub fn active_fork_info(&self) -> Option<&ForkInfo> {
644        Some(&self.lifecycle.forks().get(self.active_fork_id()?)?.info)
645    }
646
647    /// Returns the RPC URL of the active fork.
648    pub fn active_fork_url(&self) -> Option<String> {
649        Some(self.active_fork_info()?.url.clone())
650    }
651
652    /// Returns the configuration the active fork was created with.
653    pub fn active_fork_options(&self) -> Option<CreateFork> {
654        self.forks.get_fork_options(self.active_fork_info()?.id.clone()).ok()?
655    }
656
657    /// Returns the source chain ID of the active fork, independent of chain ID overrides.
658    pub fn active_fork_source_chain_id(&self) -> Option<u64> {
659        self.lifecycle.active().db.active_fork_source_chain_id()
660    }
661
662    /// Returns the RPC block number of the active fork.
663    pub fn active_fork_block_number(&self) -> Option<u64> {
664        if let Some(block_number) = self.fork_block_number_override {
665            return Some(block_number);
666        }
667        self.active_fork_info()?.block
668    }
669
670    /// Returns `id`, or the active fork for `None`, if it exists.
671    pub fn ensure_fork(&self, id: Option<LocalForkId>) -> eyre::Result<LocalForkId> {
672        match id.or_else(|| self.active_fork_id()) {
673            Some(id) if self.lifecycle.forks().get(id).is_some() => Ok(id),
674            Some(id) => eyre::bail!("Requested fork `{id}` does not exist"),
675            None => eyre::bail!("No fork active"),
676        }
677    }
678
679    fn fork_info(&self, id: LocalForkId) -> eyre::Result<&ForkInfo> {
680        self.lifecycle
681            .forks()
682            .get(id)
683            .map(|entry| &entry.info)
684            .ok_or_else(|| eyre::eyre!("Requested fork `{id}` does not exist"))
685    }
686
687    fn set_fork_info(&mut self, id: LocalForkId, info: ForkInfo) {
688        self.lifecycle.forks_mut().get_mut(id).expect("fork exists").info = info;
689    }
690
691    fn fork_options(&self, id: &ForkId) -> eyre::Result<CreateFork> {
692        self.forks
693            .get_fork_options(id.clone())?
694            .ok_or_else(|| eyre::eyre!("Requested fork `{id}` does not exist"))
695    }
696
697    // ---- Fork lifecycle ----
698
699    /// Creates a fork without selecting it.
700    pub fn create_fork(&mut self, fork: CreateFork) -> eyre::Result<LocalForkId> {
701        trace!("create fork");
702        let track = self.tracks_position(&fork);
703        self.insert_fork(fork, None, track)
704    }
705
706    /// Creates a fork positioned right before `transaction` without selecting it.
707    pub fn create_fork_at_transaction(
708        &mut self,
709        fork: CreateFork,
710        transaction: B256,
711    ) -> eyre::Result<LocalForkId> {
712        trace!(?transaction, "create fork at transaction");
713        // The fork's cursor is derived from the transaction's block below.
714        let id = self.insert_fork(fork, None, false)?;
715        let spec = self.evm_env().spec;
716        let (db, env, cache, info, cursor, _) =
717            self.prepare_roll_to_transaction(id, transaction, spec)?;
718        self.lifecycle.replace_inactive(Some(id), db, env, cache)?;
719        self.set_fork_info(id, info);
720        if let Some((position, cursor)) = cursor {
721            self.retain_cursor(id, position, &cursor, None);
722        }
723        Ok(id)
724    }
725
726    /// Creates a fork and selects it.
727    pub fn create_select_fork(
728        &mut self,
729        fork: CreateFork,
730        evm: &mut FoundryEvmFor<'_, FEN>,
731        phase: ExecutionPhase,
732    ) -> eyre::Result<LocalForkId> {
733        let id = self.create_fork(fork)?;
734        self.select_fork(id, evm, phase)?;
735        Ok(id)
736    }
737
738    /// Creates a fork positioned right before `transaction` and selects it.
739    pub fn create_select_fork_at_transaction(
740        &mut self,
741        fork: CreateFork,
742        evm: &mut FoundryEvmFor<'_, FEN>,
743        phase: ExecutionPhase,
744        transaction: B256,
745    ) -> eyre::Result<LocalForkId> {
746        let id = self.create_fork_at_transaction(fork, transaction)?;
747        self.select_fork(id, evm, phase)?;
748        Ok(id)
749    }
750
751    /// Makes fork `id` the running context of `evm`.
752    ///
753    /// The running spec and fee-charge policy carry over to the fork; persistent accounts carry
754    /// their state into it.
755    pub fn select_fork(
756        &mut self,
757        id: LocalForkId,
758        evm: &mut FoundryEvmFor<'_, FEN>,
759        phase: ExecutionPhase,
760    ) -> eyre::Result<()> {
761        trace!(?id, "select fork");
762        self.ensure_fork(Some(id))?;
763        if self.is_active_fork(id) {
764            return Ok(());
765        }
766        let running = evm_env(evm);
767        let factory = self.lifecycle.factory().clone();
768        let context = self.lifecycle.forks_mut().context_mut(Some(id)).expect("fork exists");
769        let mut env = factory.env_with_spec(context.env, running.spec);
770        env.set_feature(EvmFeatures::FEE_CHARGE, running.version.feature(EvmFeatures::FEE_CHARGE));
771        context.env = env;
772        self.lifecycle.select_fork(evm, Some(id), phase)
773    }
774
775    /// Moves fork `id`, or the active fork for `None`, to `block_number`.
776    pub fn roll_fork(
777        &mut self,
778        id: Option<LocalForkId>,
779        block_number: u64,
780        evm: &mut FoundryEvmFor<'_, FEN>,
781        phase: ExecutionPhase,
782    ) -> eyre::Result<()> {
783        trace!(?id, ?block_number, "roll fork");
784        let id = self.ensure_fork(id)?;
785        let info = self.fork_info(id)?.clone();
786        let options = self.fork_options(&info.id)?;
787        let ForkResult { id: fork_id, backend, fork: remote } =
788            self.forks.roll_fork(info.id.clone(), block_number)?;
789        let env = self.fork_env(&options.evm_opts, &remote, &remote.block, evm_env(evm).spec);
790        // Resolve everything fallible before the fork moves.
791        let cursor = if self.tracks_position(&options) {
792            Some(self.block_end_cursor(&backend, &remote, &env)?)
793        } else {
794            None
795        };
796        let db = ForkDb::new(backend, remote.context().source_chain_id);
797        self.roll_lifecycle_fork(evm, id, db, env, None, phase)?;
798        let block = Some(remote.number());
799        self.set_fork_info(
800            id,
801            ForkInfo { id: fork_id, url: info.url, block, remote: Some(remote), position: None },
802        );
803        if let Some((position, cursor)) = cursor {
804            self.retain_cursor(id, position, &cursor, Some(evm));
805        }
806        Ok(())
807    }
808
809    /// Moves fork `id` onto `db` and `env` in the lifecycle.
810    ///
811    /// Rolling the active fork keeps the test caller's state like a persistent
812    /// account's, so a sender that is not persistent keeps changes such as `vm.deal`.
813    fn roll_lifecycle_fork(
814        &mut self,
815        evm: &mut FoundryEvmFor<'_, FEN>,
816        id: LocalForkId,
817        db: impl BackingDb,
818        env: EvmEnvFor<FEN>,
819        cache: Option<Cache>,
820        phase: ExecutionPhase,
821    ) -> eyre::Result<()> {
822        let active = self.is_active_fork(id);
823        let caller = self
824            .caller
825            .filter(|caller| active && self.lifecycle.forks_mut().add_persistent(*caller));
826        let result = self.lifecycle.roll_fork(evm, Some(id), db, env, cache, phase);
827        if let Some(caller) = caller {
828            self.lifecycle.forks_mut().remove_persistent(&caller);
829        }
830        result
831    }
832
833    /// Moves fork `id`, or the active fork for `None`, to the state right before `transaction`:
834    /// the transaction's block environment over its parent's state with the block's preceding
835    /// transactions replayed natively.
836    pub fn roll_fork_to_transaction(
837        &mut self,
838        id: Option<LocalForkId>,
839        transaction: B256,
840        evm: &mut FoundryEvmFor<'_, FEN>,
841        phase: ExecutionPhase,
842    ) -> eyre::Result<()> {
843        trace!(?id, ?transaction, "roll fork to transaction");
844        let id = self.ensure_fork(id)?;
845        let (db, env, cache, info, cursor, replayed) =
846            self.prepare_roll_to_transaction(id, transaction, evm_env(evm).spec)?;
847        self.roll_lifecycle_fork(evm, id, db, env, cache, phase)?;
848        self.set_fork_info(id, info);
849        if let Some((position, cursor)) = cursor {
850            self.retain_cursor(id, position, &cursor, Some(evm));
851        }
852        // Replaying the preceding transactions on another fork rebases the running transaction's
853        // loaded accounts onto their results.
854        if replayed && !self.is_active_fork(id) {
855            self.lifecycle.rebase_onto_inactive(evm, Some(id))?;
856            TypesFor::<FEN>::refresh_transaction(evm);
857        }
858        Ok(())
859    }
860
861    /// Prepares the mined `transaction` of fork `id`, or of the active fork for `None`, to execute
862    /// with its block's environment, such as for `vm.transact`, and returns it with the throwaway
863    /// backend it executes over. Store the outcome with [`Self::store_executed`].
864    ///
865    /// On the active fork the transaction runs as a nested transaction of the running one, whose
866    /// writes are journaled; on another fork it is accepted there and its changes to persistent
867    /// accounts are merged into the running transaction. Its root frame runs at `depth`.
868    ///
869    /// Cheatcodes running in the transaction see the throwaway backend with the target fork active
870    /// at the transaction's block; their changes to it are discarded.
871    ///
872    /// `isolation_env` is the environment of the transaction an isolated call runs in, whose fee
873    /// charge and sender balance checks apply on the active fork instead of the isolated call's.
874    pub fn prepare_transact(
875        &self,
876        id: Option<LocalForkId>,
877        transaction: B256,
878        evm: &mut FoundryEvmFor<'_, FEN>,
879        depth: u16,
880        isolation_env: Option<&EvmEnvFor<FEN>>,
881    ) -> eyre::Result<(PreparedTx<TypesFor<FEN>>, CowBackend<'_, FEN>)> {
882        trace!(?id, ?transaction, "execute transaction");
883        let id = self.ensure_fork(id)?;
884        let info = self.fork_info(id)?;
885        eyre::ensure!(
886            !info.remote.as_ref().is_some_and(|remote| remote.state_by_number),
887            "transaction replay requires hash-addressed state; create a transaction-targeted fork \
888             or disable fork_state_by_number"
889        );
890        let source_chain_id = self.fork_source_chain_id(id)?;
891
892        // The user transacts an arbitrary mined transaction in the current context; execute it
893        // as it was mined, in its block's environment.
894        // <https://github.com/foundry-rs/foundry/issues/6538>
895        let target = self.transaction_target(id, transaction)?;
896        let tx = TypesFor::<FEN>::tx_from_any_rpc(&target.transaction)?;
897        let active = self.is_active_fork(id);
898        let mut env = if active {
899            let mut env = evm_env(evm);
900            if let Some(outer) = isolation_env {
901                for feature in [
902                    EvmFeatures::FEE_CHARGE,
903                    EvmFeatures::BALANCE_CHECK,
904                    EvmFeatures::BALANCE_TOP_UP,
905                ] {
906                    env.set_feature(feature, outer.version.feature(feature));
907                }
908            }
909            env
910        } else {
911            self.lifecycle.forks().context(Some(id)).expect("fork exists").env
912        };
913        // The mined transaction is signed for its source chain, whatever chain ID the running
914        // transaction or the fork's environment uses.
915        env.set_chain_id(source_chain_id);
916        env.block = block_env_from_header::<TypesFor<FEN>>(&target.block.header);
917        apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
918            &mut env,
919            &target.block,
920            source_chain_id,
921            self.networks,
922        );
923        apply_chain_specific_tx_replay_env_changes_for_chain(&mut env, source_chain_id);
924        env.initial_call_depth = depth - TypesFor::<FEN>::tx_call_depth_offset(&tx);
925
926        // Networks with block-position state only replay the transaction that immediately follows
927        // the fork's canonical position, and advance the position past it.
928        let (ext, next) = if self.networks.is_monad() {
929            let index = target
930                .index
931                .ok_or_else(|| eyre::eyre!("transaction {transaction} has no block position"))?;
932            let transactions = full_transactions(&target.block)?;
933            let block = BlockNumHash::new(target.block.header.number(), target.block.header.hash);
934            let next = self
935                .fork_position(id)?
936                .after_transaction(
937                    block,
938                    target.block.header.parent_hash(),
939                    index,
940                    transactions.len(),
941                )
942                .ok_or_else(|| {
943                    eyre::eyre!(
944                        "transaction {transaction} does not immediately follow the canonical \
945                         position of fork {id}"
946                    )
947                })?;
948            let shared = self.shared_backend(id)?;
949            let context = block_context::<FEN>(&shared, &target.block)?;
950            let factory = self.lifecycle.factory();
951            let cursor = block_cursor::<FEN>(factory, &env, context.clone(), next)?;
952            let mut ext = factory.evm_ext(&env);
953            context.prepare(&mut ext, index);
954            // The mined transaction is trusted history: a protocol transaction replays as such,
955            // and a non-canonical envelope from the protocol sender is rejected.
956            ext.set_protocol_replay(true);
957            (Some(ext), Some((next, cursor)))
958        } else {
959            (None, None)
960        };
961        // The replayed transaction's changes are not the running transaction's execution.
962        TypesFor::<FEN>::sync_transaction(evm);
963        let mut prepared = if active {
964            self.lifecycle.prepare_nested(evm, tx, Some(env), ext)
965        } else {
966            self.lifecycle.prepare_on_inactive(evm, Some(id), tx, Some(env), ext)?
967        };
968        if let Some((position, cursor)) = next {
969            prepared.set_cursor(id, position, cursor);
970        }
971
972        prepared.set_access_list(target.transaction.access_list().cloned());
973        let mut backend = CowBackend::new_borrowed(self);
974        if !active {
975            // The prepared transaction already runs over the target fork's state.
976            backend.lifecycle.activate_detached(Some(id));
977        }
978        backend.fork_block_number_override = Some(target.block.header.number());
979        Ok((prepared, backend))
980    }
981
982    /// Executes `tx` as a nested transaction of the running one, in `env` or the running
983    /// environment for `None`, and merges its changes into the running transaction so that they
984    /// survive reverts of the enclosing calls.
985    pub fn transact_from_tx(
986        &mut self,
987        tx: &Recovered<TxFor<FEN>>,
988        evm: &mut FoundryEvmFor<'_, FEN>,
989        env: Option<EvmEnvFor<FEN>>,
990        inspector: Option<&mut dyn Inspector<TypesFor<FEN>>>,
991    ) -> eyre::Result<(TxResultFor<FEN>, Vec<PersistentWrite>)> {
992        trace!("execute signed transaction");
993        let mut executor = self.lifecycle.nested_evm(evm, tx, env, None);
994        if let Some(inspector) = inspector {
995            executor.set_inspector(inspector);
996        }
997        let executed = executor.transact(tx).map_err(transaction_error)?;
998        let (persistent, _) = merge_untracked_nested_changes(evm.state_mut(), &executed)?;
999        Ok((executed.result().clone(), persistent))
1000    }
1001
1002    /// Prepares [`Self::transact_from_tx`], such as for `vm.broadcastRawTransaction`, and returns
1003    /// it with the throwaway backend it executes over. Store the outcome with
1004    /// [`Self::store_executed`].
1005    ///
1006    /// Cheatcodes running in the transaction see the throwaway backend, a copy-on-write view of
1007    /// this one; their changes to it are discarded.
1008    pub fn prepare_nested(
1009        &self,
1010        tx: Recovered<TxFor<FEN>>,
1011        evm: &mut FoundryEvmFor<'_, FEN>,
1012        env: Option<EvmEnvFor<FEN>>,
1013    ) -> (PreparedTx<TypesFor<FEN>>, CowBackend<'_, FEN>) {
1014        trace!("execute signed transaction");
1015        // The nested transaction's changes are not the running transaction's execution.
1016        TypesFor::<FEN>::sync_transaction(evm);
1017        (self.lifecycle.prepare_nested(evm, tx, env, None), CowBackend::new_borrowed(self))
1018    }
1019
1020    /// Stores the outcome of a transaction prepared with [`Self::prepare_transact`] or
1021    /// [`Self::prepare_nested`].
1022    ///
1023    /// A replayed canonical transaction advances its fork's position; its changes merged into the
1024    /// running transaction `evm` are not the running transaction's execution.
1025    pub fn store_executed(
1026        &mut self,
1027        evm: &mut FoundryEvmFor<'_, FEN>,
1028        mut executed: ExecutedNested<TypesFor<FEN>>,
1029    ) -> TxResultFor<FEN> {
1030        let cursor = executed.take_cursor();
1031        let result = self.lifecycle.store_executed(executed);
1032        match cursor {
1033            Some((id, position, cursor)) if self.is_active_fork(id) => {
1034                self.retain_cursor(id, position, &cursor, Some(evm))
1035            }
1036            Some((id, position, cursor)) => {
1037                self.retain_cursor(id, position, &cursor, None);
1038                TypesFor::<FEN>::refresh_transaction(evm);
1039            }
1040            None => TypesFor::<FEN>::refresh_transaction(evm),
1041        }
1042        result
1043    }
1044
1045    // ---- Running-state operations ----
1046
1047    /// Explains a revert of a call to `callee` in multi-fork mode: whether `callee` has no code on
1048    /// the active fork, and on which other forks it does.
1049    ///
1050    /// Handling multiple accounts/new contracts in a multifork environment can be challenging since
1051    /// every fork has its own standalone storage section:
1052    ///
1053    /// ```solidity
1054    /// function testCanDeploy() public {
1055    ///    vm.selectFork(mainnetFork);
1056    ///    // contract created while on `mainnetFork`
1057    ///    DummyContract dummy = new DummyContract();
1058    ///    // this will succeed
1059    ///    dummy.hello();
1060    ///
1061    ///    vm.selectFork(optimismFork);
1062    ///
1063    ///    vm.expectRevert();
1064    ///    // this will revert since `dummy` contract only exists on `mainnetFork`
1065    ///    dummy.hello();
1066    /// }
1067    /// ```
1068    pub fn diagnose_revert(
1069        &self,
1070        callee: Address,
1071        evm: &mut FoundryEvmFor<'_, FEN>,
1072    ) -> Option<RevertDiagnostic> {
1073        let active = self.active_fork_id()?;
1074        if self.lifecycle.forks().len() == 1 {
1075            // Only diagnose in multi-fork mode with more than one fork.
1076            return None;
1077        }
1078        if is_contract(evm.read_account_info(&callee).ok().flatten()) {
1079            return None;
1080        }
1081        let available_on = self
1082            .lifecycle
1083            .forks()
1084            .iter()
1085            .filter(|(id, entry)| {
1086                *id != active
1087                    && is_contract(entry.context.accepted_db().get_account(&callee).ok().flatten())
1088            })
1089            .map(|(id, _)| id)
1090            .collect::<Vec<_>>();
1091        Some(if available_on.is_empty() {
1092            RevertDiagnostic::ContractDoesNotExist {
1093                contract: callee,
1094                active,
1095                persistent: self.is_persistent(&callee),
1096            }
1097        } else {
1098            RevertDiagnostic::ContractExistsOnOtherForks { contract: callee, active, available_on }
1099        })
1100    }
1101
1102    /// Loads genesis `allocs` into the running transaction as journaled writes.
1103    pub fn load_allocs(
1104        &self,
1105        allocs: &BTreeMap<Address, GenesisAccount>,
1106        evm: &mut FoundryEvmFor<'_, FEN>,
1107    ) -> Result<(), BackendError> {
1108        for (address, account) in allocs {
1109            self.clone_account(account, address, evm)?;
1110        }
1111        Ok(())
1112    }
1113
1114    /// Writes the code, storage, nonce and balance of `source` to `target` in the running
1115    /// transaction as journaled writes, and warms `target`. Code is kept when `source` has none.
1116    pub fn clone_account(
1117        &self,
1118        source: &GenesisAccount,
1119        target: &Address,
1120        evm: &mut FoundryEvmFor<'_, FEN>,
1121    ) -> Result<(), BackendError> {
1122        let state = evm.state_mut();
1123        {
1124            let mut account = state.account(target)?;
1125            if let Some(code) = &source.code {
1126                account.set_code(keccak256(code), Bytecode::new_raw(code.clone()));
1127            }
1128            account.set_balance(source.balance);
1129            account.set_nonce(source.nonce.unwrap_or_default());
1130            // Touch the account so the loaded information persists if called in `setUp`.
1131            account.touch();
1132            account.warm();
1133        }
1134        for (slot, value) in source.storage.iter().flatten() {
1135            let mut slot = state.storage_slot(target, (*slot).into())?;
1136            slot.warm();
1137            slot.set((*value).into());
1138        }
1139        Ok(())
1140    }
1141
1142    /// Sets the hash of block `number` in the running context.
1143    pub fn set_blockhash(&self, number: U256, hash: B256, evm: &mut FoundryEvmFor<'_, FEN>) {
1144        evm.state_mut().overlay_db_mut().insert_block_hash(&number, &hash);
1145    }
1146
1147    /// Refetches `field` of `address` from the active fork's remote, after an out-of-band RPC
1148    /// mutation, and updates the running context with it.
1149    ///
1150    /// Balance and nonce are overridden without journaling, so they survive reverts; code is set
1151    /// as a journaled write.
1152    pub fn refresh_fork_account(
1153        &self,
1154        address: Address,
1155        field: ForkAccountField,
1156        evm: &mut FoundryEvmFor<'_, FEN>,
1157    ) -> Result<(), BackendError> {
1158        if !self.is_forked_mode() {
1159            return Ok(());
1160        }
1161        trace!(?address, ?field, "refresh fork account");
1162        let db = &self.lifecycle.active().db;
1163        db.evict_account(&address);
1164        let mut refreshed = db.clone_backing().get_account(&address)?.unwrap_or_default();
1165        if matches!(field, ForkAccountField::Code) && refreshed.code.is_none() {
1166            refreshed.code = Some(db.clone_backing().get_code_by_hash(&refreshed.code_hash)?);
1167        }
1168
1169        self.lifecycle.materialize(evm);
1170        let state = evm.state_mut();
1171        let cache = &mut state.overlay_db_mut().cache;
1172        if let Some(Some(cached)) = cache.accounts.get_mut(&address) {
1173            match field {
1174                ForkAccountField::Balance => cached.balance = refreshed.balance,
1175                ForkAccountField::Nonce => cached.nonce = refreshed.nonce,
1176                ForkAccountField::Code => {
1177                    cached.code_hash = refreshed.code_hash;
1178                    if let Some(code) = &refreshed.code {
1179                        cache.contracts.insert(refreshed.code_hash, code.clone());
1180                    }
1181                }
1182            }
1183            cached.code = None;
1184        }
1185        let mut account = state.account(&address)?;
1186        match field {
1187            ForkAccountField::Balance => account.override_balance(refreshed.balance),
1188            ForkAccountField::Nonce => account.override_nonce(refreshed.nonce),
1189            ForkAccountField::Code => {
1190                account.set_code(refreshed.code_hash, refreshed.code.unwrap_or_default())
1191            }
1192        }
1193        Ok(())
1194    }
1195
1196    /// Refetches storage `slot` of `address` from the active fork's remote, after an out-of-band
1197    /// RPC mutation, and updates the running context with it.
1198    ///
1199    /// A slot the running transaction already loaded takes the refreshed value across reverts of
1200    /// the enclosing calls. Its transaction-start original is kept.
1201    pub fn refresh_fork_storage(
1202        &mut self,
1203        address: Address,
1204        slot: U256,
1205        evm: &mut FoundryEvmFor<'_, FEN>,
1206    ) -> Result<Option<PersistentWrite>, BackendError> {
1207        if !self.is_forked_mode() {
1208            return Ok(None);
1209        }
1210        trace!(?address, ?slot, "refresh fork storage");
1211        let db = &self.lifecycle.active().db;
1212        db.evict_storage(&address, &slot);
1213        let value = db.clone_backing().get_storage(&address, &slot)?;
1214
1215        self.lifecycle.materialize(evm);
1216        let state = evm.state_mut();
1217        if let Some(storage) = state.overlay_db_mut().cache.storage.get_mut(&address)
1218            && storage.slots.contains_key(&slot)
1219        {
1220            storage.slots.insert(slot, value);
1221        }
1222        let storage = state.storage(&address)?;
1223        let write = if storage.is_loaded(&slot) {
1224            storage.into_slot(slot)?.set(value);
1225            Some(PersistentWrite::Slot(address, slot, value))
1226        } else {
1227            None
1228        };
1229        self.lifecycle.refresh_switched_slot(&address, slot, value);
1230        Ok(write)
1231    }
1232
1233    /// Prefetches the remote state a call is about to read, if the active context is an RPC fork.
1234    ///
1235    /// A `top_level` call is simulated with the local state that differs from the remote, such as
1236    /// the test contract, as overrides. A nested call is simulated as is.
1237    pub fn prefetch_call(
1238        &self,
1239        caller: Address,
1240        target: Address,
1241        value: U256,
1242        input: Bytes,
1243        top_level: bool,
1244    ) {
1245        let context = self.lifecycle.active();
1246        context.db.prefetch_call(caller, target, value, input, context.cache.as_deref(), top_level);
1247    }
1248
1249    // ---- Snapshots ----
1250
1251    /// Captures the running context and every fork, and returns the snapshot ID.
1252    pub fn snapshot_state(&mut self, evm: &mut FoundryEvmFor<'_, FEN>) -> U256 {
1253        let id = self.lifecycle.snapshot(evm);
1254        trace!(target: "backend", "Created new snapshot {}", id);
1255        id
1256    }
1257
1258    /// Restores snapshot `id` and returns the running state it replaced, or returns `None` if it
1259    /// does not exist.
1260    ///
1261    /// Logs emitted since the snapshot, persistent accounts and forks created after it survive.
1262    /// A test failure recorded in the reverted state sets [`Self::has_state_snapshot_failure`].
1263    pub fn revert_state(
1264        &mut self,
1265        id: U256,
1266        evm: &mut FoundryEvmFor<'_, FEN>,
1267        action: RevertStateSnapshotAction,
1268        phase: ExecutionPhase,
1269    ) -> Option<StateSnapshot> {
1270        trace!(?id, "revert snapshot");
1271        if !self.lifecycle.has_snapshot(id) {
1272            warn!(target: "backend", "No snapshot to revert for {}", id);
1273            return None;
1274        }
1275        // DSTest contracts don't have snapshot functionality, so this slot is enough to check for
1276        // a failure during or before the snapshot.
1277        // <https://github.com/foundry-rs/foundry/issues/3055>
1278        if evm
1279            .state_mut()
1280            .storage_slot_untracked(&CHEATCODE_ADDRESS, &GLOBAL_FAIL_SLOT)
1281            .is_ok_and(|value| !value.is_zero())
1282        {
1283            self.has_state_snapshot_failure = true;
1284        }
1285        self.lifecycle.revert(evm, id, action, phase)
1286    }
1287
1288    /// Deletes a snapshot, returning whether it existed.
1289    pub fn delete_state_snapshot(&mut self, id: U256) -> bool {
1290        self.lifecycle.delete_snapshot(id)
1291    }
1292
1293    /// Deletes every snapshot.
1294    pub fn delete_state_snapshots(&mut self) {
1295        self.lifecycle.delete_snapshots();
1296    }
1297
1298    // ---- Internals ----
1299
1300    /// Registers an RPC fork, with `env` or the environment derived from its block, retaining
1301    /// its block cursor if `track`.
1302    fn insert_fork(
1303        &mut self,
1304        fork: CreateFork,
1305        env: Option<EvmEnvFor<FEN>>,
1306        track: bool,
1307    ) -> eyre::Result<LocalForkId> {
1308        let url = fork.url.clone();
1309        let opts = fork.evm_opts.clone();
1310        let resolved = self.forks.create_fork(fork)?;
1311        let env = env.unwrap_or_else(|| {
1312            let remote = &resolved.fork;
1313            self.fork_env(&opts, remote, &remote.block, self.lifecycle.active().env.spec)
1314        });
1315        self.insert_prepared_fork(url, resolved, env, track)
1316    }
1317
1318    /// Registers a resolved fork without refetching its block, retaining its block cursor if
1319    /// `track`.
1320    fn insert_prepared_fork(
1321        &mut self,
1322        url: String,
1323        resolved: ForkResult,
1324        env: EvmEnvFor<FEN>,
1325        track: bool,
1326    ) -> eyre::Result<LocalForkId> {
1327        let ForkResult { id, backend, fork: remote } = resolved;
1328        let cursor =
1329            if track { Some(self.block_end_cursor(&backend, &remote, &env)?) } else { None };
1330        let db = ForkDb::new(backend, remote.context().source_chain_id);
1331        let info = ForkInfo {
1332            id,
1333            url,
1334            block: Some(remote.number()),
1335            remote: Some(remote),
1336            position: None,
1337        };
1338        let id = self.lifecycle.create_fork(info, db, env);
1339        if let Some((position, cursor)) = cursor {
1340            self.retain_cursor(id, position, &cursor, None);
1341        }
1342        Ok(id)
1343    }
1344
1345    /// Returns whether forks created from `fork` retain their canonical block cursor.
1346    const fn tracks_position(&self, fork: &CreateFork) -> bool {
1347        self.networks.is_monad() || fork.evm_opts.networks.is_monad()
1348    }
1349
1350    /// Returns the canonical position of fork `id`: the one retained by a replay, or the end of
1351    /// its pinned block.
1352    fn fork_position(&self, id: LocalForkId) -> eyre::Result<ForkPosition> {
1353        let info = self.fork_info(id)?;
1354        info.position
1355            .or_else(|| info.remote.as_ref().map(|remote| ForkPosition::AfterBlock(remote.block())))
1356            .ok_or_else(|| eyre::eyre!("fork `{id}` has no canonical position"))
1357    }
1358
1359    /// Returns the position and block cursor at the end of `remote`'s pinned block.
1360    fn block_end_cursor(
1361        &self,
1362        backend: &SharedBackend<AnyNetwork, BlockEnv>,
1363        remote: &RemoteFork,
1364        env: &EvmEnvFor<FEN>,
1365    ) -> eyre::Result<(ForkPosition, ChainFor<FEN>)> {
1366        let block = match &remote.block.transactions {
1367            BlockTransactions::Full(_) => AnyRpcBlock::clone(&remote.block),
1368            _ => backend
1369                .get_full_block(remote.hash())
1370                .wrap_err_with(|| format!("failed to fetch fork block {}", remote.hash()))?,
1371        };
1372        eyre::ensure!(
1373            block.header.hash == remote.hash() && block.header.number() == remote.number(),
1374            "fork block {} ({}) changed",
1375            remote.number(),
1376            remote.hash()
1377        );
1378        let position = ForkPosition::AfterBlock(remote.block());
1379        let context = block_context::<FEN>(backend, &block)?;
1380        Ok((position, block_cursor::<FEN>(self.lifecycle.factory(), env, context, position)?))
1381    }
1382
1383    /// Retains `position` and its block `cursor` as fork `id`'s canonical position.
1384    ///
1385    /// The active fork's cursor lives in the running EVM: it moves under the running transaction,
1386    /// whose network state is rebased onto it. Synthetic transactions never call this.
1387    fn retain_cursor(
1388        &mut self,
1389        id: LocalForkId,
1390        position: ForkPosition,
1391        cursor: &ChainFor<FEN>,
1392        evm: Option<&mut FoundryEvmFor<'_, FEN>>,
1393    ) {
1394        if self.is_active_fork(id)
1395            && let Some(evm) = evm
1396        {
1397            evm.ext_mut().adopt_cursor(cursor);
1398            TypesFor::<FEN>::refresh_transaction(evm);
1399        } else {
1400            let context = self.lifecycle.forks_mut().context_mut(Some(id)).expect("fork exists");
1401            let mut ext = context.ext.get();
1402            ext.adopt_cursor(cursor);
1403            context.ext = StoredExt::new(&ext);
1404        }
1405        self.lifecycle.forks_mut().get_mut(id).expect("fork exists").info.position = Some(position);
1406    }
1407
1408    /// Returns the environment of `remote` at `block` with `spec`.
1409    fn fork_env(
1410        &self,
1411        opts: &EvmOpts,
1412        remote: &RemoteFork,
1413        block: &AnyRpcBlock,
1414        spec: SpecFor<FEN>,
1415    ) -> EvmEnvFor<FEN> {
1416        let context = remote.context();
1417        let chain_id = opts.chain_id_override().unwrap_or(context.execution_chain_id);
1418        let env =
1419            opts.fork_env_from_block::<FEN, AnyNetwork>(chain_id, context.source_chain_id, block);
1420        self.lifecycle.factory().env_with_spec(env, spec)
1421    }
1422
1423    fn fork_source_chain_id(&self, id: LocalForkId) -> eyre::Result<ChainId> {
1424        self.lifecycle
1425            .forks()
1426            .context(Some(id))
1427            .and_then(|context| context.db.active_fork_source_chain_id())
1428            .ok_or_else(|| eyre::eyre!("fork `{id}` is not backed by an RPC endpoint"))
1429    }
1430
1431    fn shared_backend(&self, id: LocalForkId) -> eyre::Result<SharedBackend<AnyNetwork, BlockEnv>> {
1432        let fork_id = self.fork_info(id)?.id.clone();
1433        self.forks
1434            .get_fork(fork_id.clone())?
1435            .ok_or_else(|| eyre::eyre!("fork `{fork_id}` is not backed by an RPC endpoint"))
1436    }
1437
1438    /// Fetches `transaction` and the block it executes in from fork `id`.
1439    fn transaction_target(
1440        &self,
1441        id: LocalForkId,
1442        transaction: B256,
1443    ) -> eyre::Result<TransactionForkTarget> {
1444        let backend = self.shared_backend(id)?;
1445        let tx = backend.get_transaction(transaction)?;
1446        let Some(tx_block) = tx.block_number() else {
1447            eyre::ensure!(
1448                !self.networks.is_monad(),
1449                "transaction {transaction} is pending and has no canonical block context"
1450            );
1451            let block = backend.get_full_block(BlockNumberOrTag::Latest)?;
1452            let fork_block = BlockNumHash::new(block.header.number(), block.header.hash);
1453            return Ok(TransactionForkTarget {
1454                fork_block,
1455                transaction: tx,
1456                block,
1457                mined: false,
1458                index: None,
1459            });
1460        };
1461        let tx_block_hash = tx
1462            .block_hash()
1463            .ok_or_else(|| eyre::eyre!("mined transaction is missing its block hash"))?;
1464        let block = backend.get_full_block(tx_block_hash)?;
1465        eyre::ensure!(
1466            block.header.number() == tx_block && block.header.hash == tx_block_hash,
1467            "transaction block changed: expected {tx_block} ({tx_block_hash}), got {} ({})",
1468            block.header.number(),
1469            block.header.hash
1470        );
1471        let transactions = full_transactions(&block)?;
1472        let index = transactions.iter().position(|tx| tx.tx_hash() == transaction);
1473        eyre::ensure!(
1474            index.is_some(),
1475            "transaction {transaction} is missing from block {}",
1476            block.header.number()
1477        );
1478        // Execute on the state before the block.
1479        let fork_block = BlockNumHash::new(
1480            tx_block
1481                .checked_sub(1)
1482                .ok_or_else(|| eyre::eyre!("cannot replay a transaction in the genesis block"))?,
1483            block.header.parent_hash(),
1484        );
1485        Ok(TransactionForkTarget { fork_block, transaction: tx, block, mined: true, index })
1486    }
1487
1488    /// Resolves the backing database, environment, replayed accepted state, identity, for
1489    /// networks with block-position state, canonical position and block cursor of fork `id`
1490    /// positioned right before `transaction`, and whether preceding transactions were replayed.
1491    #[expect(clippy::type_complexity)]
1492    fn prepare_roll_to_transaction(
1493        &self,
1494        id: LocalForkId,
1495        transaction: B256,
1496        spec: SpecFor<FEN>,
1497    ) -> eyre::Result<(
1498        RpcForkDb,
1499        EvmEnvFor<FEN>,
1500        Option<Cache>,
1501        ForkInfo,
1502        Option<(ForkPosition, ChainFor<FEN>)>,
1503        bool,
1504    )> {
1505        let info = self.fork_info(id)?.clone();
1506        let options = self.fork_options(&info.id)?;
1507        let target = self.transaction_target(id, transaction)?;
1508        let ForkResult { id: fork_id, backend, fork: remote } = self
1509            .forks
1510            .roll_fork_exact_with_bal(info.id.clone(), target.fork_block, target.mined)?;
1511        let source_chain_id = remote.context().source_chain_id;
1512        let env = self.fork_env(&options.evm_opts, &remote, &target.block, spec);
1513        let db = ForkDb::new(backend, source_chain_id);
1514        let mut cursor = None;
1515        let replayed = target.mined && target.index.is_some_and(|index| index > 0);
1516        let cache = if target.mined {
1517            let index = target.index.expect("mined transaction has a block position");
1518            let context = if self.networks.is_monad() {
1519                let context = block_context::<FEN>(db.inner(), &target.block)?;
1520                let block =
1521                    BlockNumHash::new(target.block.header.number(), target.block.header.hash);
1522                let position = ForkPosition::BeforeTransaction { block, index };
1523                cursor = Some((
1524                    position,
1525                    block_cursor::<FEN>(self.lifecycle.factory(), &env, context.clone(), position)?,
1526                ));
1527                Some(context)
1528            } else {
1529                None
1530            };
1531            Some(self.replay_until(&db, env, &target.block, index, context, source_chain_id)?)
1532        } else {
1533            None
1534        };
1535        let block = Some(target.block.header.number());
1536        let info =
1537            ForkInfo { id: fork_id, url: info.url, block, remote: Some(remote), position: None };
1538        Ok((db, env, cache, info, cursor, replayed))
1539    }
1540
1541    /// Replays the transactions of `block` before `index` over `db` and returns the resulting
1542    /// accepted state.
1543    ///
1544    /// `context` positions network state that depends on the block, such as Monad's. System
1545    /// transactions are skipped, except deposits and canonical protocol transactions, which
1546    /// networks that support them execute natively.
1547    fn replay_until(
1548        &self,
1549        db: &impl BackingDb,
1550        mut env: EvmEnvFor<FEN>,
1551        block: &AnyRpcBlock,
1552        index: usize,
1553        context: Option<BlockContext<FEN>>,
1554        source_chain_id: ChainId,
1555    ) -> eyre::Result<Cache> {
1556        let transactions = full_transactions(block)?;
1557        apply_chain_specific_tx_replay_env_changes_for_chain(&mut env, source_chain_id);
1558
1559        let now = Instant::now();
1560        let mut evm = self.lifecycle.factory().create_evm(db.clone_backing(), env);
1561        for (position, rpc_tx) in transactions[..index].iter().enumerate() {
1562            let is_system =
1563                is_known_system_sender(rpc_tx.from()) || rpc_tx.ty() == SYSTEM_TRANSACTION_TYPE;
1564            let tx = match TypesFor::<FEN>::tx_from_any_rpc(rpc_tx) {
1565                Ok(tx) => tx,
1566                // Deposits of networks without deposit support, and system envelopes without a
1567                // native representation.
1568                Err(_) if is_system => continue,
1569                Err(err) => return Err(err),
1570            };
1571            let is_protocol = ChainFor::<FEN>::is_protocol_transaction(&tx);
1572            if is_system && rpc_tx.ty() != SYSTEM_TRANSACTION_TYPE && !is_protocol {
1573                // Other system transactions have no native representation.
1574                continue;
1575            }
1576            match &context {
1577                Some(context) => context.prepare(evm.ext_mut(), position),
1578                None => evm.ext_mut().for_transaction(&tx),
1579            }
1580            // The canonical block is trusted history, so its protocol transactions replay.
1581            evm.ext_mut().set_protocol_replay(is_protocol);
1582            trace!(tx=?rpc_tx.tx_hash(), "committing transaction");
1583            let _ = evm
1584                .transact(&tx)
1585                .map_err(handler_error)
1586                .wrap_err("backend: failed replaying transaction")?
1587                .commit();
1588        }
1589        trace!(elapsed=?now.elapsed(), count=index, "replayed transactions");
1590        Ok(mem::take(&mut evm.state_mut().overlay_db_mut().cache))
1591    }
1592}
1593
1594/// Returns the transactions of `block` and its two ancestors, fetched through `backend`.
1595fn block_context<FEN: FoundryEvmNetwork>(
1596    backend: &SharedBackend<AnyNetwork, BlockEnv>,
1597    block: &AnyRpcBlock,
1598) -> eyre::Result<BlockContext<FEN>> {
1599    let parent = parent_block(backend, block)?;
1600    let grandparent =
1601        parent.as_ref().map(|parent| parent_block(backend, parent)).transpose()?.flatten();
1602    Ok(BlockContext::new(
1603        grandparent.as_ref().map(block_txs::<FEN>).transpose()?.unwrap_or_default(),
1604        parent.as_ref().map(block_txs::<FEN>).transpose()?.unwrap_or_default(),
1605        block_txs::<FEN>(block)?,
1606    ))
1607}
1608
1609/// Returns network state retaining the block cursor at `position`, whose block's transactions and
1610/// ancestors are `context`.
1611fn block_cursor<FEN: FoundryEvmNetwork>(
1612    factory: &EvmFactoryFor<FEN>,
1613    env: &EvmEnvFor<FEN>,
1614    mut context: BlockContext<FEN>,
1615    position: ForkPosition,
1616) -> eyre::Result<ChainFor<FEN>> {
1617    let mut ext = factory.evm_ext(env);
1618    match position {
1619        ForkPosition::AfterBlock(_) => {
1620            context.advance_block();
1621            context.prepare(&mut ext, 0);
1622        }
1623        ForkPosition::BeforeTransaction { index, .. } => {
1624            context.before_transaction(index)?.prepare(&mut ext, index);
1625        }
1626    }
1627    Ok(ext)
1628}
1629
1630/// Fetches the parent of `block`, or `None` for genesis.
1631fn parent_block(
1632    backend: &SharedBackend<AnyNetwork, BlockEnv>,
1633    block: &AnyRpcBlock,
1634) -> eyre::Result<Option<AnyRpcBlock>> {
1635    let parent_hash = block.header.parent_hash();
1636    if parent_hash.is_zero() {
1637        return Ok(None);
1638    }
1639    let parent = backend
1640        .get_full_block(parent_hash)
1641        .wrap_err_with(|| format!("failed to fetch ancestor block {parent_hash}"))?;
1642    eyre::ensure!(
1643        parent.header.hash == parent_hash
1644            && Some(parent.header.number()) == block.header.number().checked_sub(1),
1645        "ancestor block {parent_hash} does not match its child"
1646    );
1647    Ok(Some(parent))
1648}
1649
1650/// Returns whether `account` has code. A zero code hash, which no code hashes to, is not code.
1651fn is_contract(account: Option<AccountInfo>) -> bool {
1652    account.is_some_and(|account| !account.is_empty_code_hash() && !account.code_hash.is_zero())
1653}
1654
1655/// Returns the account-loading policy required by a fork source.
1656///
1657/// A recognized source chain ID is authoritative. The endpoint's execution profile is only a
1658/// source hint for custom chain IDs, where the chain ID cannot identify the RPC semantics, and for
1659/// local development chain IDs, which nodes of any family use, such as Anvil and Tempo dev nodes.
1660/// A dev node of another family that reports no Anvil node info therefore needs an execution
1661/// profile that matches it: selecting Tempo for it requires `eth_getAccountInfo`.
1662pub fn account_fetch_policy_for_source(
1663    source_chain_id: ChainId,
1664    network_profile: NetworkConfigs,
1665) -> AccountFetchPolicy {
1666    let source_chain = Chain::from_id(source_chain_id);
1667    let identifies_family = source_chain
1668        .named()
1669        .is_some_and(|chain| !matches!(chain, NamedChain::Dev | NamedChain::AnvilHardhat));
1670    let is_tempo = source_chain.is_tempo() || (!identifies_family && network_profile.is_tempo());
1671    if is_tempo {
1672        AccountFetchPolicy::RequireAccountInfoWithExtension
1673    } else {
1674        AccountFetchPolicy::Auto
1675    }
1676}