foundry_evm_core/backend/
mod.rs

1//! Foundry's main executor backend abstraction and implementation.
2
3use crate::{
4    AsEnvMut, Env, EnvMut, InspectorExt,
5    constants::{CALLER, CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, TEST_CONTRACT_ADDRESS},
6    evm::new_evm_with_inspector,
7    fork::{CreateFork, ForkId, MultiFork},
8    state_snapshot::StateSnapshots,
9    utils::{configure_tx_env, configure_tx_req_env},
10};
11use alloy_consensus::Typed2718;
12use alloy_evm::Evm;
13use alloy_genesis::GenesisAccount;
14use alloy_network::{AnyRpcBlock, AnyTxEnvelope, TransactionResponse};
15use alloy_primitives::{Address, B256, TxKind, U256, keccak256, uint};
16use alloy_rpc_types::{BlockNumberOrTag, Transaction, TransactionRequest};
17use eyre::Context;
18use foundry_common::{SYSTEM_TRANSACTION_TYPE, is_known_system_sender};
19pub use foundry_fork_db::{BlockchainDb, SharedBackend, cache::BlockchainDbMeta};
20use revm::{
21    Database, DatabaseCommit, JournalEntry,
22    bytecode::Bytecode,
23    context::JournalInner,
24    context_interface::{block::BlobExcessGasAndPrice, result::ResultAndState},
25    database::{CacheDB, DatabaseRef},
26    inspector::NoOpInspector,
27    precompile::{PrecompileSpecId, Precompiles},
28    primitives::{HashMap as Map, KECCAK_EMPTY, Log, hardfork::SpecId},
29    state::{Account, AccountInfo, EvmState, EvmStorageSlot},
30};
31use std::{
32    collections::{BTreeMap, HashMap, HashSet},
33    time::Instant,
34};
35
36mod diagnostic;
37pub use diagnostic::RevertDiagnostic;
38
39mod error;
40pub use error::{BackendError, BackendResult, DatabaseError, DatabaseResult};
41
42mod cow;
43pub use cow::CowBackend;
44
45mod in_memory_db;
46pub use in_memory_db::{EmptyDBWrapper, FoundryEvmInMemoryDB, MemDb};
47
48mod snapshot;
49pub use snapshot::{BackendStateSnapshot, RevertStateSnapshotAction, StateSnapshot};
50
51// A `revm::Database` that is used in forking mode
52type ForkDB = CacheDB<SharedBackend>;
53
54/// Represents a numeric `ForkId` valid only for the existence of the `Backend`.
55///
56/// The difference between `ForkId` and `LocalForkId` is that `ForkId` tracks pairs of `endpoint +
57/// block` which can be reused by multiple tests, whereas the `LocalForkId` is unique within a test
58pub type LocalForkId = U256;
59
60/// Represents the index of a fork in the created forks vector
61/// This is used for fast lookup
62type ForkLookupIndex = usize;
63
64/// All accounts that will have persistent storage across fork swaps.
65const DEFAULT_PERSISTENT_ACCOUNTS: [Address; 3] =
66    [CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, CALLER];
67
68/// `bytes32("failed")`, as a storage slot key into [`CHEATCODE_ADDRESS`].
69///
70/// Used by all `forge-std` test contracts and newer `DSTest` test contracts as a global marker for
71/// a failed test.
72pub const GLOBAL_FAIL_SLOT: U256 =
73    uint!(0x6661696c65640000000000000000000000000000000000000000000000000000_U256);
74
75pub type JournaledState = JournalInner<JournalEntry>;
76
77/// An extension trait that allows us to easily extend the `revm::Inspector` capabilities
78#[auto_impl::auto_impl(&mut)]
79pub trait DatabaseExt: Database<Error = DatabaseError> + DatabaseCommit {
80    /// Creates a new state snapshot at the current point of execution.
81    ///
82    /// A state snapshot is associated with a new unique id that's created for the snapshot.
83    /// State snapshots can be reverted: [DatabaseExt::revert_state], however, depending on the
84    /// [RevertStateSnapshotAction], it will keep the snapshot alive or delete it.
85    fn snapshot_state(&mut self, journaled_state: &JournaledState, env: &mut EnvMut<'_>) -> U256;
86
87    /// Reverts the snapshot if it exists
88    ///
89    /// Returns `true` if the snapshot was successfully reverted, `false` if no snapshot for that id
90    /// exists.
91    ///
92    /// **N.B.** While this reverts the state of the evm to the snapshot, it keeps new logs made
93    /// since the snapshots was created. This way we can show logs that were emitted between
94    /// snapshot and its revert.
95    /// This will also revert any changes in the `Env` and replace it with the captured `Env` of
96    /// `Self::snapshot_state`.
97    ///
98    /// Depending on [RevertStateSnapshotAction] it will keep the snapshot alive or delete it.
99    fn revert_state(
100        &mut self,
101        id: U256,
102        journaled_state: &JournaledState,
103        env: &mut EnvMut<'_>,
104        action: RevertStateSnapshotAction,
105    ) -> Option<JournaledState>;
106
107    /// Deletes the state snapshot with the given `id`
108    ///
109    /// Returns `true` if the snapshot was successfully deleted, `false` if no snapshot for that id
110    /// exists.
111    fn delete_state_snapshot(&mut self, id: U256) -> bool;
112
113    /// Deletes all state snapshots.
114    fn delete_state_snapshots(&mut self);
115
116    /// Creates and also selects a new fork
117    ///
118    /// This is basically `create_fork` + `select_fork`
119    fn create_select_fork(
120        &mut self,
121        fork: CreateFork,
122        env: &mut EnvMut<'_>,
123        journaled_state: &mut JournaledState,
124    ) -> eyre::Result<LocalForkId> {
125        let id = self.create_fork(fork)?;
126        self.select_fork(id, env, journaled_state)?;
127        Ok(id)
128    }
129
130    /// Creates and also selects a new fork
131    ///
132    /// This is basically `create_fork` + `select_fork`
133    fn create_select_fork_at_transaction(
134        &mut self,
135        fork: CreateFork,
136        env: &mut EnvMut<'_>,
137        journaled_state: &mut JournaledState,
138        transaction: B256,
139    ) -> eyre::Result<LocalForkId> {
140        let id = self.create_fork_at_transaction(fork, transaction)?;
141        self.select_fork(id, env, journaled_state)?;
142        Ok(id)
143    }
144
145    /// Creates a new fork but does _not_ select it
146    fn create_fork(&mut self, fork: CreateFork) -> eyre::Result<LocalForkId>;
147
148    /// Creates a new fork but does _not_ select it
149    fn create_fork_at_transaction(
150        &mut self,
151        fork: CreateFork,
152        transaction: B256,
153    ) -> eyre::Result<LocalForkId>;
154
155    /// Selects the fork's state
156    ///
157    /// This will also modify the current `Env`.
158    ///
159    /// **Note**: this does not change the local state, but swaps the remote state
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if no fork with the given `id` exists
164    fn select_fork(
165        &mut self,
166        id: LocalForkId,
167        env: &mut EnvMut<'_>,
168        journaled_state: &mut JournaledState,
169    ) -> eyre::Result<()>;
170
171    /// Updates the fork to given block number.
172    ///
173    /// This will essentially create a new fork at the given block height.
174    ///
175    /// # Errors
176    ///
177    /// Returns an error if not matching fork was found.
178    fn roll_fork(
179        &mut self,
180        id: Option<LocalForkId>,
181        block_number: u64,
182        env: &mut EnvMut<'_>,
183        journaled_state: &mut JournaledState,
184    ) -> eyre::Result<()>;
185
186    /// Updates the fork to given transaction hash
187    ///
188    /// This will essentially create a new fork at the block this transaction was mined and replays
189    /// all transactions up until the given transaction.
190    ///
191    /// # Errors
192    ///
193    /// Returns an error if not matching fork was found.
194    fn roll_fork_to_transaction(
195        &mut self,
196        id: Option<LocalForkId>,
197        transaction: B256,
198        env: &mut EnvMut<'_>,
199        journaled_state: &mut JournaledState,
200    ) -> eyre::Result<()>;
201
202    /// Fetches the given transaction for the fork and executes it, committing the state in the DB
203    fn transact(
204        &mut self,
205        id: Option<LocalForkId>,
206        transaction: B256,
207        env: Env,
208        journaled_state: &mut JournaledState,
209        inspector: &mut dyn InspectorExt,
210    ) -> eyre::Result<()>;
211
212    /// Executes a given TransactionRequest, commits the new state to the DB
213    fn transact_from_tx(
214        &mut self,
215        transaction: &TransactionRequest,
216        env: Env,
217        journaled_state: &mut JournaledState,
218        inspector: &mut dyn InspectorExt,
219    ) -> eyre::Result<()>;
220
221    /// Returns the `ForkId` that's currently used in the database, if fork mode is on
222    fn active_fork_id(&self) -> Option<LocalForkId>;
223
224    /// Returns the Fork url that's currently used in the database, if fork mode is on
225    fn active_fork_url(&self) -> Option<String>;
226
227    /// Whether the database is currently in forked mode.
228    fn is_forked_mode(&self) -> bool {
229        self.active_fork_id().is_some()
230    }
231
232    /// Ensures that an appropriate fork exists
233    ///
234    /// If `id` contains a requested `Fork` this will ensure it exists.
235    /// Otherwise, this returns the currently active fork.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error if the given `id` does not match any forks
240    ///
241    /// Returns an error if no fork exists
242    fn ensure_fork(&self, id: Option<LocalForkId>) -> eyre::Result<LocalForkId>;
243
244    /// Ensures that a corresponding `ForkId` exists for the given local `id`
245    fn ensure_fork_id(&self, id: LocalForkId) -> eyre::Result<&ForkId>;
246
247    /// Handling multiple accounts/new contracts in a multifork environment can be challenging since
248    /// every fork has its own standalone storage section. So this can be a common error to run
249    /// into:
250    ///
251    /// ```solidity
252    /// function testCanDeploy() public {
253    ///    vm.selectFork(mainnetFork);
254    ///    // contract created while on `mainnetFork`
255    ///    DummyContract dummy = new DummyContract();
256    ///    // this will succeed
257    ///    dummy.hello();
258    ///
259    ///    vm.selectFork(optimismFork);
260    ///
261    ///    vm.expectRevert();
262    ///    // this will revert since `dummy` contract only exists on `mainnetFork`
263    ///    dummy.hello();
264    /// }
265    /// ```
266    ///
267    /// If this happens (`dummy.hello()`), or more general, a call on an address that's not a
268    /// contract, revm will revert without useful context. This call will check in this context if
269    /// `address(dummy)` belongs to an existing contract and if not will check all other forks if
270    /// the contract is deployed there.
271    ///
272    /// Returns a more useful error message if that's the case
273    fn diagnose_revert(
274        &self,
275        callee: Address,
276        journaled_state: &JournaledState,
277    ) -> Option<RevertDiagnostic>;
278
279    /// Loads the account allocs from the given `allocs` map into the passed [JournaledState].
280    ///
281    /// Returns [Ok] if all accounts were successfully inserted into the journal, [Err] otherwise.
282    fn load_allocs(
283        &mut self,
284        allocs: &BTreeMap<Address, GenesisAccount>,
285        journaled_state: &mut JournaledState,
286    ) -> Result<(), BackendError>;
287
288    /// Copies bytecode, storage, nonce and balance from the given genesis account to the target
289    /// address.
290    ///
291    /// Returns [Ok] if data was successfully inserted into the journal, [Err] otherwise.
292    fn clone_account(
293        &mut self,
294        source: &GenesisAccount,
295        target: &Address,
296        journaled_state: &mut JournaledState,
297    ) -> Result<(), BackendError>;
298
299    /// Returns true if the given account is currently marked as persistent.
300    fn is_persistent(&self, acc: &Address) -> bool;
301
302    /// Revokes persistent status from the given account.
303    fn remove_persistent_account(&mut self, account: &Address) -> bool;
304
305    /// Marks the given account as persistent.
306    fn add_persistent_account(&mut self, account: Address) -> bool;
307
308    /// Removes persistent status from all given accounts.
309    #[auto_impl(keep_default_for(&, &mut, Rc, Arc, Box))]
310    fn remove_persistent_accounts(&mut self, accounts: impl IntoIterator<Item = Address>)
311    where
312        Self: Sized,
313    {
314        for acc in accounts {
315            self.remove_persistent_account(&acc);
316        }
317    }
318
319    /// Extends the persistent accounts with the accounts the iterator yields.
320    #[auto_impl(keep_default_for(&, &mut, Rc, Arc, Box))]
321    fn extend_persistent_accounts(&mut self, accounts: impl IntoIterator<Item = Address>)
322    where
323        Self: Sized,
324    {
325        for acc in accounts {
326            self.add_persistent_account(acc);
327        }
328    }
329
330    /// Grants cheatcode access for the given `account`
331    ///
332    /// Returns true if the `account` already has access
333    fn allow_cheatcode_access(&mut self, account: Address) -> bool;
334
335    /// Revokes cheatcode access for the given account
336    ///
337    /// Returns true if the `account` was previously allowed cheatcode access
338    fn revoke_cheatcode_access(&mut self, account: &Address) -> bool;
339
340    /// Returns `true` if the given account is allowed to execute cheatcodes
341    fn has_cheatcode_access(&self, account: &Address) -> bool;
342
343    /// Ensures that `account` is allowed to execute cheatcodes
344    ///
345    /// Returns an error if [`Self::has_cheatcode_access`] returns `false`
346    fn ensure_cheatcode_access(&self, account: &Address) -> Result<(), BackendError> {
347        if !self.has_cheatcode_access(account) {
348            return Err(BackendError::NoCheats(*account));
349        }
350        Ok(())
351    }
352
353    /// Same as [`Self::ensure_cheatcode_access()`] but only enforces it if the backend is currently
354    /// in forking mode
355    fn ensure_cheatcode_access_forking_mode(&self, account: &Address) -> Result<(), BackendError> {
356        if self.is_forked_mode() {
357            return self.ensure_cheatcode_access(account);
358        }
359        Ok(())
360    }
361
362    /// Set the blockhash for a given block number.
363    ///
364    /// # Arguments
365    ///
366    /// * `number` - The block number to set the blockhash for
367    /// * `hash` - The blockhash to set
368    ///
369    /// # Note
370    ///
371    /// This function mimics the EVM limits of the `blockhash` operation:
372    /// - It sets the blockhash for blocks where `block.number - 256 <= number < block.number`
373    /// - Setting a blockhash for the current block (number == block.number) has no effect
374    /// - Setting a blockhash for future blocks (number > block.number) has no effect
375    /// - Setting a blockhash for blocks older than `block.number - 256` has no effect
376    fn set_blockhash(&mut self, block_number: U256, block_hash: B256);
377}
378
379struct _ObjectSafe(dyn DatabaseExt);
380
381/// Provides the underlying `revm::Database` implementation.
382///
383/// A `Backend` can be initialised in two forms:
384///
385/// # 1. Empty in-memory Database
386/// This is the default variant: an empty `revm::Database`
387///
388/// # 2. Forked Database
389/// A `revm::Database` that forks off a remote client
390///
391///
392/// In addition to that we support forking manually on the fly.
393/// Additional forks can be created. Each unique fork is identified by its unique `ForkId`. We treat
394/// forks as unique if they have the same `(endpoint, block number)` pair.
395///
396/// When it comes to testing, it's intended that each contract will use its own `Backend`
397/// (`Backend::clone`). This way each contract uses its own encapsulated evm state. For in-memory
398/// testing, the database is just an owned `revm::InMemoryDB`.
399///
400/// Each `Fork`, identified by a unique id, uses completely separate storage, write operations are
401/// performed only in the fork's own database, `ForkDB`.
402///
403/// A `ForkDB` consists of 2 halves:
404///   - everything fetched from the remote is readonly
405///   - all local changes (instructed by the contract) are written to the backend's `db` and don't
406///     alter the state of the remote client.
407///
408/// # Fork swapping
409///
410/// Multiple "forks" can be created `Backend::create_fork()`, however only 1 can be used by the
411/// `db`. However, their state can be hot-swapped by swapping the read half of `db` from one fork to
412/// another.
413/// When swapping forks (`Backend::select_fork()`) we also update the current `Env` of the `EVM`
414/// accordingly, so that all `block.*` config values match
415///
416/// When another for is selected [`DatabaseExt::select_fork()`] the entire storage, including
417/// `JournaledState` is swapped, but the storage of the caller's and the test contract account is
418/// _always_ cloned. This way a fork has entirely separate storage but data can still be shared
419/// across fork boundaries via stack and contract variables.
420///
421/// # Snapshotting
422///
423/// A snapshot of the current overall state can be taken at any point in time. A snapshot is
424/// identified by a unique id that's returned when a snapshot is created. A snapshot can only be
425/// reverted _once_. After a successful revert, the same snapshot id cannot be used again. Reverting
426/// a snapshot replaces the current active state with the snapshot state, the snapshot is deleted
427/// afterwards, as well as any snapshots taken after the reverted snapshot, (e.g.: reverting to id
428/// 0x1 will delete snapshots with ids 0x1, 0x2, etc.)
429///
430/// **Note:** State snapshots work across fork-swaps, e.g. if fork `A` is currently active, then a
431/// snapshot is created before fork `B` is selected, then fork `A` will be the active fork again
432/// after reverting the snapshot.
433#[derive(Clone, Debug)]
434#[must_use]
435pub struct Backend {
436    /// The access point for managing forks
437    forks: MultiFork,
438    // The default in memory db
439    mem_db: FoundryEvmInMemoryDB,
440    /// The journaled_state to use to initialize new forks with
441    ///
442    /// The way [`JournaledState`] works is, that it holds the "hot" accounts loaded from the
443    /// underlying `Database` that feeds the Account and State data to the journaled_state so it
444    /// can apply changes to the state while the EVM executes.
445    ///
446    /// In a way the `JournaledState` is something like a cache that
447    /// 1. check if account is already loaded (hot)
448    /// 2. if not load from the `Database` (this will then retrieve the account via RPC in forking
449    ///    mode)
450    ///
451    /// To properly initialize we store the `JournaledState` before the first fork is selected
452    /// ([`DatabaseExt::select_fork`]).
453    ///
454    /// This will be an empty `JournaledState`, which will be populated with persistent accounts,
455    /// See [`Self::update_fork_db()`].
456    fork_init_journaled_state: JournaledState,
457    /// The currently active fork database
458    ///
459    /// If this is set, then the Backend is currently in forking mode
460    active_fork_ids: Option<(LocalForkId, ForkLookupIndex)>,
461    /// holds additional Backend data
462    inner: BackendInner,
463}
464
465impl Backend {
466    /// Creates a new Backend with a spawned multi fork thread.
467    ///
468    /// If `fork` is `Some` this will use a `fork` database, otherwise with an in-memory
469    /// database.
470    pub fn spawn(fork: Option<CreateFork>) -> eyre::Result<Self> {
471        Self::new(MultiFork::spawn(), fork)
472    }
473
474    /// Creates a new instance of `Backend`
475    ///
476    /// If `fork` is `Some` this will use a `fork` database, otherwise with an in-memory
477    /// database.
478    ///
479    /// Prefer using [`spawn`](Self::spawn) instead.
480    pub fn new(forks: MultiFork, fork: Option<CreateFork>) -> eyre::Result<Self> {
481        trace!(target: "backend", forking_mode=?fork.is_some(), "creating executor backend");
482        // Note: this will take of registering the `fork`
483        let inner = BackendInner {
484            persistent_accounts: HashSet::from(DEFAULT_PERSISTENT_ACCOUNTS),
485            ..Default::default()
486        };
487
488        let mut backend = Self {
489            forks,
490            mem_db: CacheDB::new(Default::default()),
491            fork_init_journaled_state: inner.new_journaled_state(),
492            active_fork_ids: None,
493            inner,
494        };
495
496        if let Some(fork) = fork {
497            let (fork_id, fork, _) = backend.forks.create_fork(fork)?;
498            let fork_db = ForkDB::new(fork);
499            let fork_ids = backend.inner.insert_new_fork(
500                fork_id.clone(),
501                fork_db,
502                backend.inner.new_journaled_state(),
503            );
504            backend.inner.launched_with_fork = Some((fork_id, fork_ids.0, fork_ids.1));
505            backend.active_fork_ids = Some(fork_ids);
506        }
507
508        trace!(target: "backend", forking_mode=? backend.active_fork_ids.is_some(), "created executor backend");
509
510        Ok(backend)
511    }
512
513    /// Creates a new instance of `Backend` with fork added to the fork database and sets the fork
514    /// as active
515    pub(crate) fn new_with_fork(
516        id: &ForkId,
517        fork: Fork,
518        journaled_state: JournaledState,
519    ) -> eyre::Result<Self> {
520        let mut backend = Self::spawn(None)?;
521        let fork_ids = backend.inner.insert_new_fork(id.clone(), fork.db, journaled_state);
522        backend.inner.launched_with_fork = Some((id.clone(), fork_ids.0, fork_ids.1));
523        backend.active_fork_ids = Some(fork_ids);
524        Ok(backend)
525    }
526
527    /// Creates a new instance with a `BackendDatabase::InMemory` cache layer for the `CacheDB`
528    pub fn clone_empty(&self) -> Self {
529        Self {
530            forks: self.forks.clone(),
531            mem_db: CacheDB::new(Default::default()),
532            fork_init_journaled_state: self.inner.new_journaled_state(),
533            active_fork_ids: None,
534            inner: Default::default(),
535        }
536    }
537
538    pub fn insert_account_info(&mut self, address: Address, account: AccountInfo) {
539        if let Some(db) = self.active_fork_db_mut() {
540            db.insert_account_info(address, account)
541        } else {
542            self.mem_db.insert_account_info(address, account)
543        }
544    }
545
546    /// Inserts a value on an account's storage without overriding account info
547    pub fn insert_account_storage(
548        &mut self,
549        address: Address,
550        slot: U256,
551        value: U256,
552    ) -> Result<(), DatabaseError> {
553        if let Some(db) = self.active_fork_db_mut() {
554            db.insert_account_storage(address, slot, value)
555        } else {
556            self.mem_db.insert_account_storage(address, slot, value)
557        }
558    }
559
560    /// Completely replace an account's storage without overriding account info.
561    ///
562    /// When forking, this causes the backend to assume a `0` value for all
563    /// unset storage slots instead of trying to fetch it.
564    pub fn replace_account_storage(
565        &mut self,
566        address: Address,
567        storage: Map<U256, U256>,
568    ) -> Result<(), DatabaseError> {
569        if let Some(db) = self.active_fork_db_mut() {
570            db.replace_account_storage(address, storage)
571        } else {
572            self.mem_db.replace_account_storage(address, storage)
573        }
574    }
575
576    /// Returns all snapshots created in this backend
577    pub fn state_snapshots(
578        &self,
579    ) -> &StateSnapshots<BackendStateSnapshot<BackendDatabaseSnapshot>> {
580        &self.inner.state_snapshots
581    }
582
583    /// Sets the address of the `DSTest` contract that is being executed
584    ///
585    /// This will also mark the caller as persistent and remove the persistent status from the
586    /// previous test contract address
587    ///
588    /// This will also grant cheatcode access to the test account
589    pub fn set_test_contract(&mut self, acc: Address) -> &mut Self {
590        trace!(?acc, "setting test account");
591        self.add_persistent_account(acc);
592        self.allow_cheatcode_access(acc);
593        self
594    }
595
596    /// Sets the caller address
597    pub fn set_caller(&mut self, acc: Address) -> &mut Self {
598        trace!(?acc, "setting caller account");
599        self.inner.caller = Some(acc);
600        self.allow_cheatcode_access(acc);
601        self
602    }
603
604    /// Sets the current spec id
605    pub fn set_spec_id(&mut self, spec_id: SpecId) -> &mut Self {
606        trace!(?spec_id, "setting spec ID");
607        self.inner.spec_id = spec_id;
608        self
609    }
610
611    /// Returns the set caller address
612    pub fn caller_address(&self) -> Option<Address> {
613        self.inner.caller
614    }
615
616    /// Failures occurred in state snapshots are tracked when the state snapshot is reverted.
617    ///
618    /// If an error occurs in a restored state snapshot, the test is considered failed.
619    ///
620    /// This returns whether there was a reverted state snapshot that recorded an error.
621    pub fn has_state_snapshot_failure(&self) -> bool {
622        self.inner.has_state_snapshot_failure
623    }
624
625    /// Sets the state snapshot failure flag.
626    pub fn set_state_snapshot_failure(&mut self, has_state_snapshot_failure: bool) {
627        self.inner.has_state_snapshot_failure = has_state_snapshot_failure
628    }
629
630    /// When creating or switching forks, we update the AccountInfo of the contract
631    pub(crate) fn update_fork_db(
632        &self,
633        active_journaled_state: &mut JournaledState,
634        target_fork: &mut Fork,
635    ) {
636        self.update_fork_db_contracts(
637            self.inner.persistent_accounts.iter().copied(),
638            active_journaled_state,
639            target_fork,
640        )
641    }
642
643    /// Merges the state of all `accounts` from the currently active db into the given `fork`
644    pub(crate) fn update_fork_db_contracts(
645        &self,
646        accounts: impl IntoIterator<Item = Address>,
647        active_journaled_state: &mut JournaledState,
648        target_fork: &mut Fork,
649    ) {
650        if let Some(db) = self.active_fork_db() {
651            merge_account_data(accounts, db, active_journaled_state, target_fork)
652        } else {
653            merge_account_data(accounts, &self.mem_db, active_journaled_state, target_fork)
654        }
655    }
656
657    /// Returns the memory db used if not in forking mode
658    pub fn mem_db(&self) -> &FoundryEvmInMemoryDB {
659        &self.mem_db
660    }
661
662    /// Returns true if the `id` is currently active
663    pub fn is_active_fork(&self, id: LocalForkId) -> bool {
664        self.active_fork_ids.map(|(i, _)| i == id).unwrap_or_default()
665    }
666
667    /// Returns `true` if the `Backend` is currently in forking mode
668    pub fn is_in_forking_mode(&self) -> bool {
669        self.active_fork().is_some()
670    }
671
672    /// Returns the currently active `Fork`, if any
673    pub fn active_fork(&self) -> Option<&Fork> {
674        self.active_fork_ids.map(|(_, idx)| self.inner.get_fork(idx))
675    }
676
677    /// Returns the currently active `Fork`, if any
678    pub fn active_fork_mut(&mut self) -> Option<&mut Fork> {
679        self.active_fork_ids.map(|(_, idx)| self.inner.get_fork_mut(idx))
680    }
681
682    /// Returns the currently active `ForkDB`, if any
683    pub fn active_fork_db(&self) -> Option<&ForkDB> {
684        self.active_fork().map(|f| &f.db)
685    }
686
687    /// Returns the currently active `ForkDB`, if any
688    pub fn active_fork_db_mut(&mut self) -> Option<&mut ForkDB> {
689        self.active_fork_mut().map(|f| &mut f.db)
690    }
691
692    /// Returns the current database implementation as a `&dyn` value.
693    #[inline(always)]
694    pub fn db(&self) -> &dyn Database<Error = DatabaseError> {
695        match self.active_fork_db() {
696            Some(fork_db) => fork_db,
697            None => &self.mem_db,
698        }
699    }
700
701    /// Returns the current database implementation as a `&mut dyn` value.
702    #[inline(always)]
703    pub fn db_mut(&mut self) -> &mut dyn Database<Error = DatabaseError> {
704        match self.active_fork_ids.map(|(_, idx)| &mut self.inner.get_fork_mut(idx).db) {
705            Some(fork_db) => fork_db,
706            None => &mut self.mem_db,
707        }
708    }
709
710    /// Creates a snapshot of the currently active database
711    pub(crate) fn create_db_snapshot(&self) -> BackendDatabaseSnapshot {
712        if let Some((id, idx)) = self.active_fork_ids {
713            let fork = self.inner.get_fork(idx).clone();
714            let fork_id = self.inner.ensure_fork_id(id).cloned().expect("Exists; qed");
715            BackendDatabaseSnapshot::Forked(id, fork_id, idx, Box::new(fork))
716        } else {
717            BackendDatabaseSnapshot::InMemory(self.mem_db.clone())
718        }
719    }
720
721    /// Since each `Fork` tracks logs separately, we need to merge them to get _all_ of them
722    pub fn merged_logs(&self, mut logs: Vec<Log>) -> Vec<Log> {
723        if let Some((_, active)) = self.active_fork_ids {
724            let mut all_logs = Vec::with_capacity(logs.len());
725
726            self.inner
727                .forks
728                .iter()
729                .enumerate()
730                .filter_map(|(idx, f)| f.as_ref().map(|f| (idx, f)))
731                .for_each(|(idx, f)| {
732                    if idx == active {
733                        all_logs.append(&mut logs);
734                    } else {
735                        all_logs.extend(f.journaled_state.logs.clone())
736                    }
737                });
738            return all_logs;
739        }
740
741        logs
742    }
743
744    /// Initializes settings we need to keep track of.
745    ///
746    /// We need to track these mainly to prevent issues when switching between different evms
747    pub(crate) fn initialize(&mut self, env: &Env) {
748        self.set_caller(env.tx.caller);
749        self.set_spec_id(env.evm_env.cfg_env.spec);
750
751        let test_contract = match env.tx.kind {
752            TxKind::Call(to) => to,
753            TxKind::Create => {
754                let nonce = self
755                    .basic_ref(env.tx.caller)
756                    .map(|b| b.unwrap_or_default().nonce)
757                    .unwrap_or_default();
758                env.tx.caller.create(nonce)
759            }
760        };
761        self.set_test_contract(test_contract);
762    }
763
764    /// Executes the configured test call of the `env` without committing state changes.
765    ///
766    /// Note: in case there are any cheatcodes executed that modify the environment, this will
767    /// update the given `env` with the new values.
768    #[instrument(name = "inspect", level = "debug", skip_all)]
769    pub fn inspect<I: InspectorExt>(
770        &mut self,
771        env: &mut Env,
772        inspector: &mut I,
773    ) -> eyre::Result<ResultAndState> {
774        self.initialize(env);
775        let mut evm = crate::evm::new_evm_with_inspector(self, env.to_owned(), inspector);
776
777        let res = evm.transact(env.tx.clone()).wrap_err("EVM error")?;
778
779        *env = evm.as_env_mut().to_owned();
780
781        Ok(res)
782    }
783
784    /// Returns true if the address is a precompile
785    pub fn is_existing_precompile(&self, addr: &Address) -> bool {
786        self.inner.precompiles().contains(addr)
787    }
788
789    /// Sets the initial journaled state to use when initializing forks
790    #[inline]
791    fn set_init_journaled_state(&mut self, journaled_state: JournaledState) {
792        trace!("recording fork init journaled_state");
793        self.fork_init_journaled_state = journaled_state;
794    }
795
796    /// Cleans up already loaded accounts that would be initialized without the correct data from
797    /// the fork.
798    ///
799    /// It can happen that an account is loaded before the first fork is selected, like
800    /// `getNonce(addr)`, which will load an empty account by default.
801    ///
802    /// This account data then would not match the account data of a fork if it exists.
803    /// So when the first fork is initialized we replace these accounts with the actual account as
804    /// it exists on the fork.
805    fn prepare_init_journal_state(&mut self) -> Result<(), BackendError> {
806        let loaded_accounts = self
807            .fork_init_journaled_state
808            .state
809            .iter()
810            .filter(|(addr, _)| !self.is_existing_precompile(addr) && !self.is_persistent(addr))
811            .map(|(addr, _)| addr)
812            .copied()
813            .collect::<Vec<_>>();
814
815        for fork in self.inner.forks_iter_mut() {
816            let mut journaled_state = self.fork_init_journaled_state.clone();
817            for loaded_account in loaded_accounts.iter().copied() {
818                trace!(?loaded_account, "replacing account on init");
819                let init_account =
820                    journaled_state.state.get_mut(&loaded_account).expect("exists; qed");
821
822                // here's an edge case where we need to check if this account has been created, in
823                // which case we don't need to replace it with the account from the fork because the
824                // created account takes precedence: for example contract creation in setups
825                if init_account.is_created() {
826                    trace!(?loaded_account, "skipping created account");
827                    continue;
828                }
829
830                // otherwise we need to replace the account's info with the one from the fork's
831                // database
832                let fork_account = Database::basic(&mut fork.db, loaded_account)?
833                    .ok_or(BackendError::MissingAccount(loaded_account))?;
834                init_account.info = fork_account;
835            }
836            fork.journaled_state = journaled_state;
837        }
838        Ok(())
839    }
840
841    /// Returns the block numbers required for replaying a transaction
842    fn get_block_number_and_block_for_transaction(
843        &self,
844        id: LocalForkId,
845        transaction: B256,
846    ) -> eyre::Result<(u64, AnyRpcBlock)> {
847        let fork = self.inner.get_fork_by_id(id)?;
848        let tx = fork.db.db.get_transaction(transaction)?;
849
850        // get the block number we need to fork
851        if let Some(tx_block) = tx.block_number {
852            let block = fork.db.db.get_full_block(tx_block)?;
853
854            // we need to subtract 1 here because we want the state before the transaction
855            // was mined
856            let fork_block = tx_block - 1;
857            Ok((fork_block, block))
858        } else {
859            let block = fork.db.db.get_full_block(BlockNumberOrTag::Latest)?;
860
861            let number = block.header.number;
862
863            Ok((number, block))
864        }
865    }
866
867    /// Replays all the transactions at the forks current block that were mined before the `tx`
868    ///
869    /// Returns the _unmined_ transaction that corresponds to the given `tx_hash`
870    pub fn replay_until(
871        &mut self,
872        id: LocalForkId,
873        mut env: Env,
874        tx_hash: B256,
875        journaled_state: &mut JournaledState,
876    ) -> eyre::Result<Option<Transaction<AnyTxEnvelope>>> {
877        trace!(?id, ?tx_hash, "replay until transaction");
878
879        let persistent_accounts = self.inner.persistent_accounts.clone();
880        let fork_id = self.ensure_fork_id(id)?.clone();
881
882        let fork = self.inner.get_fork_by_id_mut(id)?;
883        let full_block = fork.db.db.get_full_block(env.evm_env.block_env.number)?;
884
885        for tx in full_block.inner.transactions.txns() {
886            // System transactions such as on L2s don't contain any pricing info so we skip them
887            // otherwise this would cause reverts
888            if is_known_system_sender(tx.inner().inner.signer())
889                || tx.ty() == SYSTEM_TRANSACTION_TYPE
890            {
891                trace!(tx=?tx.tx_hash(), "skipping system transaction");
892                continue;
893            }
894
895            if tx.tx_hash() == tx_hash {
896                // found the target transaction
897                return Ok(Some(tx.inner.clone()));
898            }
899            trace!(tx=?tx.tx_hash(), "committing transaction");
900
901            commit_transaction(
902                &tx.inner,
903                &mut env.as_env_mut(),
904                journaled_state,
905                fork,
906                &fork_id,
907                &persistent_accounts,
908                &mut NoOpInspector,
909            )?;
910        }
911
912        Ok(None)
913    }
914}
915
916impl DatabaseExt for Backend {
917    fn snapshot_state(&mut self, journaled_state: &JournaledState, env: &mut EnvMut<'_>) -> U256 {
918        trace!("create snapshot");
919        let id = self.inner.state_snapshots.insert(BackendStateSnapshot::new(
920            self.create_db_snapshot(),
921            journaled_state.clone(),
922            env.to_owned(),
923        ));
924        trace!(target: "backend", "Created new snapshot {}", id);
925        id
926    }
927
928    fn revert_state(
929        &mut self,
930        id: U256,
931        current_state: &JournaledState,
932        current: &mut EnvMut<'_>,
933        action: RevertStateSnapshotAction,
934    ) -> Option<JournaledState> {
935        trace!(?id, "revert snapshot");
936        if let Some(mut snapshot) = self.inner.state_snapshots.remove_at(id) {
937            // Re-insert snapshot to persist it
938            if action.is_keep() {
939                self.inner.state_snapshots.insert_at(snapshot.clone(), id);
940            }
941
942            // https://github.com/foundry-rs/foundry/issues/3055
943            // Check if an error occurred either during or before the snapshot.
944            // DSTest contracts don't have snapshot functionality, so this slot is enough to check
945            // for failure here.
946            if let Some(account) = current_state.state.get(&CHEATCODE_ADDRESS)
947                && let Some(slot) = account.storage.get(&GLOBAL_FAIL_SLOT)
948                && !slot.present_value.is_zero()
949            {
950                self.set_state_snapshot_failure(true);
951            }
952
953            // merge additional logs
954            snapshot.merge(current_state);
955            let BackendStateSnapshot { db, mut journaled_state, env } = snapshot;
956            match db {
957                BackendDatabaseSnapshot::InMemory(mem_db) => {
958                    self.mem_db = mem_db;
959                }
960                BackendDatabaseSnapshot::Forked(id, fork_id, idx, mut fork) => {
961                    // there might be the case where the snapshot was created during `setUp` with
962                    // another caller, so we need to ensure the caller account is present in the
963                    // journaled state and database
964                    let caller = current.tx.caller;
965                    journaled_state.state.entry(caller).or_insert_with(|| {
966                        let caller_account = current_state
967                            .state
968                            .get(&caller)
969                            .map(|acc| acc.info.clone())
970                            .unwrap_or_default();
971
972                        if !fork.db.cache.accounts.contains_key(&caller) {
973                            // update the caller account which is required by the evm
974                            fork.db.insert_account_info(caller, caller_account.clone());
975                        }
976                        caller_account.into()
977                    });
978                    self.inner.revert_state_snapshot(id, fork_id, idx, *fork);
979                    self.active_fork_ids = Some((id, idx))
980                }
981            }
982
983            update_current_env_with_fork_env(&mut current.as_env_mut(), env);
984            trace!(target: "backend", "Reverted snapshot {}", id);
985
986            Some(journaled_state)
987        } else {
988            warn!(target: "backend", "No snapshot to revert for {}", id);
989            None
990        }
991    }
992
993    fn delete_state_snapshot(&mut self, id: U256) -> bool {
994        self.inner.state_snapshots.remove_at(id).is_some()
995    }
996
997    fn delete_state_snapshots(&mut self) {
998        self.inner.state_snapshots.clear()
999    }
1000
1001    fn create_fork(&mut self, create_fork: CreateFork) -> eyre::Result<LocalForkId> {
1002        trace!("create fork");
1003        let (fork_id, fork, _) = self.forks.create_fork(create_fork)?;
1004
1005        let fork_db = ForkDB::new(fork);
1006        let (id, _) =
1007            self.inner.insert_new_fork(fork_id, fork_db, self.fork_init_journaled_state.clone());
1008        Ok(id)
1009    }
1010
1011    fn create_fork_at_transaction(
1012        &mut self,
1013        fork: CreateFork,
1014        transaction: B256,
1015    ) -> eyre::Result<LocalForkId> {
1016        trace!(?transaction, "create fork at transaction");
1017        let id = self.create_fork(fork)?;
1018        let fork_id = self.ensure_fork_id(id).cloned()?;
1019        let mut env = self
1020            .forks
1021            .get_env(fork_id)?
1022            .ok_or_else(|| eyre::eyre!("Requested fork `{}` does not exit", id))?;
1023
1024        // we still need to roll to the transaction, but we only need an empty dummy state since we
1025        // don't need to update the active journaled state yet
1026        self.roll_fork_to_transaction(
1027            Some(id),
1028            transaction,
1029            &mut env.as_env_mut(),
1030            &mut self.inner.new_journaled_state(),
1031        )?;
1032
1033        Ok(id)
1034    }
1035
1036    /// Select an existing fork by id.
1037    /// When switching forks we copy the shared state
1038    fn select_fork(
1039        &mut self,
1040        id: LocalForkId,
1041        env: &mut EnvMut<'_>,
1042        active_journaled_state: &mut JournaledState,
1043    ) -> eyre::Result<()> {
1044        trace!(?id, "select fork");
1045        if self.is_active_fork(id) {
1046            // nothing to do
1047            return Ok(());
1048        }
1049
1050        // Update block number and timestamp of active fork (if any) with current env values,
1051        // in order to preserve values changed by using `roll` and `warp` cheatcodes.
1052        if let Some(active_fork_id) = self.active_fork_id() {
1053            self.forks.update_block(
1054                self.ensure_fork_id(active_fork_id).cloned()?,
1055                env.block.number,
1056                env.block.timestamp,
1057            )?;
1058        }
1059
1060        let fork_id = self.ensure_fork_id(id).cloned()?;
1061        let idx = self.inner.ensure_fork_index(&fork_id)?;
1062        let fork_env = self
1063            .forks
1064            .get_env(fork_id)?
1065            .ok_or_else(|| eyre::eyre!("Requested fork `{}` does not exit", id))?;
1066
1067        // If we're currently in forking mode we need to update the journaled_state to this point,
1068        // this ensures the changes performed while the fork was active are recorded
1069        if let Some(active) = self.active_fork_mut() {
1070            active.journaled_state = active_journaled_state.clone();
1071
1072            let caller = env.tx.caller;
1073            let caller_account = active.journaled_state.state.get(&env.tx.caller).cloned();
1074            let target_fork = self.inner.get_fork_mut(idx);
1075
1076            // depth 0 will be the default value when the fork was created
1077            if target_fork.journaled_state.depth == 0 {
1078                // Initialize caller with its fork info
1079                if let Some(mut acc) = caller_account {
1080                    let fork_account = Database::basic(&mut target_fork.db, caller)?
1081                        .ok_or(BackendError::MissingAccount(caller))?;
1082
1083                    acc.info = fork_account;
1084                    target_fork.journaled_state.state.insert(caller, acc);
1085                }
1086            }
1087        } else {
1088            // this is the first time a fork is selected. This means up to this point all changes
1089            // are made in a single `JournaledState`, for example after a `setup` that only created
1090            // different forks. Since the `JournaledState` is valid for all forks until the
1091            // first fork is selected, we need to update it for all forks and use it as init state
1092            // for all future forks
1093
1094            self.set_init_journaled_state(active_journaled_state.clone());
1095            self.prepare_init_journal_state()?;
1096
1097            // Make sure that the next created fork has a depth of 0.
1098            self.fork_init_journaled_state.depth = 0;
1099        }
1100
1101        {
1102            // update the shared state and track
1103            let mut fork = self.inner.take_fork(idx);
1104
1105            // Make sure all persistent accounts on the newly selected fork reflect same state as
1106            // the active db / previous fork.
1107            // This can get out of sync when multiple forks are created on test `setUp`, then a
1108            // fork is selected and persistent contract is changed. If first action in test is to
1109            // select a different fork, then the persistent contract state won't reflect changes
1110            // done in `setUp` for the other fork.
1111            // See <https://github.com/foundry-rs/foundry/issues/10296> and <https://github.com/foundry-rs/foundry/issues/10552>.
1112            let persistent_accounts = self.inner.persistent_accounts.clone();
1113            if let Some(db) = self.active_fork_db_mut() {
1114                for addr in persistent_accounts {
1115                    let Ok(db_account) = db.load_account(addr) else { continue };
1116
1117                    let Some(fork_account) = fork.journaled_state.state.get_mut(&addr) else {
1118                        continue;
1119                    };
1120
1121                    for (key, val) in &db_account.storage {
1122                        if let Some(fork_storage) = fork_account.storage.get_mut(key) {
1123                            fork_storage.present_value = *val;
1124                        }
1125                    }
1126                }
1127            }
1128
1129            // since all forks handle their state separately, the depth can drift
1130            // this is a handover where the target fork starts at the same depth where it was
1131            // selected. This ensures that there are no gaps in depth which would
1132            // otherwise cause issues with the tracer
1133            fork.journaled_state.depth = active_journaled_state.depth;
1134
1135            // another edge case where a fork is created and selected during setup with not
1136            // necessarily the same caller as for the test, however we must always
1137            // ensure that fork's state contains the current sender
1138            let caller = env.tx.caller;
1139            fork.journaled_state.state.entry(caller).or_insert_with(|| {
1140                let caller_account = active_journaled_state
1141                    .state
1142                    .get(&env.tx.caller)
1143                    .map(|acc| acc.info.clone())
1144                    .unwrap_or_default();
1145
1146                if !fork.db.cache.accounts.contains_key(&caller) {
1147                    // update the caller account which is required by the evm
1148                    fork.db.insert_account_info(caller, caller_account.clone());
1149                }
1150                caller_account.into()
1151            });
1152
1153            self.update_fork_db(active_journaled_state, &mut fork);
1154
1155            // insert the fork back
1156            self.inner.set_fork(idx, fork);
1157        }
1158
1159        self.active_fork_ids = Some((id, idx));
1160        // Update current environment with environment of newly selected fork.
1161        update_current_env_with_fork_env(env, fork_env);
1162
1163        Ok(())
1164    }
1165
1166    /// This is effectively the same as [`Self::create_select_fork()`] but updating an existing
1167    /// [ForkId] that is mapped to the [LocalForkId]
1168    fn roll_fork(
1169        &mut self,
1170        id: Option<LocalForkId>,
1171        block_number: u64,
1172        env: &mut EnvMut<'_>,
1173        journaled_state: &mut JournaledState,
1174    ) -> eyre::Result<()> {
1175        trace!(?id, ?block_number, "roll fork");
1176        let id = self.ensure_fork(id)?;
1177        let (fork_id, backend, fork_env) =
1178            self.forks.roll_fork(self.inner.ensure_fork_id(id).cloned()?, block_number)?;
1179        // this will update the local mapping
1180        self.inner.roll_fork(id, fork_id, backend)?;
1181
1182        if let Some((active_id, active_idx)) = self.active_fork_ids {
1183            // the currently active fork is the targeted fork of this call
1184            if active_id == id {
1185                // need to update the block's env settings right away, which is otherwise set when
1186                // forks are selected `select_fork`
1187                update_current_env_with_fork_env(env, fork_env);
1188
1189                // we also need to update the journaled_state right away, this has essentially the
1190                // same effect as selecting (`select_fork`) by discarding
1191                // non-persistent storage from the journaled_state. This which will
1192                // reset cached state from the previous block
1193                let mut persistent_addrs = self.inner.persistent_accounts.clone();
1194                // we also want to copy the caller state here
1195                persistent_addrs.extend(self.caller_address());
1196
1197                let active = self.inner.get_fork_mut(active_idx);
1198                active.journaled_state = self.fork_init_journaled_state.clone();
1199
1200                active.journaled_state.depth = journaled_state.depth;
1201                for addr in persistent_addrs {
1202                    merge_journaled_state_data(addr, journaled_state, &mut active.journaled_state);
1203                }
1204
1205                // Ensure all previously loaded accounts are present in the journaled state to
1206                // prevent issues in the new journalstate, e.g. assumptions that accounts are loaded
1207                // if the account is not touched, we reload it, if it's touched we clone it.
1208                //
1209                // Special case for accounts that are not created: we don't merge their state but
1210                // load it in order to reflect their state at the new block (they should explicitly
1211                // be marked as persistent if it is desired to keep state between fork rolls).
1212                for (addr, acc) in &journaled_state.state {
1213                    if acc.is_created() {
1214                        if acc.is_touched() {
1215                            merge_journaled_state_data(
1216                                *addr,
1217                                journaled_state,
1218                                &mut active.journaled_state,
1219                            );
1220                        }
1221                    } else {
1222                        let _ = active.journaled_state.load_account(&mut active.db, *addr);
1223                    }
1224                }
1225
1226                *journaled_state = active.journaled_state.clone();
1227            }
1228        }
1229        Ok(())
1230    }
1231
1232    fn roll_fork_to_transaction(
1233        &mut self,
1234        id: Option<LocalForkId>,
1235        transaction: B256,
1236        env: &mut EnvMut<'_>,
1237        journaled_state: &mut JournaledState,
1238    ) -> eyre::Result<()> {
1239        trace!(?id, ?transaction, "roll fork to transaction");
1240        let id = self.ensure_fork(id)?;
1241
1242        let (fork_block, block) =
1243            self.get_block_number_and_block_for_transaction(id, transaction)?;
1244
1245        // roll the fork to the transaction's parent block or latest if it's pending, because we
1246        // need to fork off the parent block's state for tx level forking and then replay the txs
1247        // before the tx in that block to get the state at the tx
1248        self.roll_fork(Some(id), fork_block, env, journaled_state)?;
1249
1250        // we need to update the env to the block
1251        update_env_block(env, &block);
1252
1253        // after we forked at the fork block we need to properly update the block env to the block
1254        // env of the tx's block
1255        let _ =
1256            self.forks.update_block_env(self.inner.ensure_fork_id(id).cloned()?, env.block.clone());
1257
1258        let env = env.to_owned();
1259
1260        // replay all transactions that came before
1261        self.replay_until(id, env, transaction, journaled_state)?;
1262
1263        Ok(())
1264    }
1265
1266    fn transact(
1267        &mut self,
1268        maybe_id: Option<LocalForkId>,
1269        transaction: B256,
1270        mut env: Env,
1271        journaled_state: &mut JournaledState,
1272        inspector: &mut dyn InspectorExt,
1273    ) -> eyre::Result<()> {
1274        trace!(?maybe_id, ?transaction, "execute transaction");
1275        let persistent_accounts = self.inner.persistent_accounts.clone();
1276        let id = self.ensure_fork(maybe_id)?;
1277        let fork_id = self.ensure_fork_id(id).cloned()?;
1278
1279        let tx = {
1280            let fork = self.inner.get_fork_by_id_mut(id)?;
1281            fork.db.db.get_transaction(transaction)?
1282        };
1283
1284        // This is a bit ambiguous because the user wants to transact an arbitrary transaction in
1285        // the current context, but we're assuming the user wants to transact the transaction as it
1286        // was mined. Usually this is used in a combination of a fork at the transaction's parent
1287        // transaction in the block and then the transaction is transacted:
1288        // <https://github.com/foundry-rs/foundry/issues/6538>
1289        // So we modify the env to match the transaction's block.
1290        let (_fork_block, block) =
1291            self.get_block_number_and_block_for_transaction(id, transaction)?;
1292        update_env_block(&mut env.as_env_mut(), &block);
1293
1294        let fork = self.inner.get_fork_by_id_mut(id)?;
1295        commit_transaction(
1296            &tx.inner,
1297            &mut env.as_env_mut(),
1298            journaled_state,
1299            fork,
1300            &fork_id,
1301            &persistent_accounts,
1302            inspector,
1303        )
1304    }
1305
1306    fn transact_from_tx(
1307        &mut self,
1308        tx: &TransactionRequest,
1309        mut env: Env,
1310        journaled_state: &mut JournaledState,
1311        inspector: &mut dyn InspectorExt,
1312    ) -> eyre::Result<()> {
1313        trace!(?tx, "execute signed transaction");
1314
1315        self.commit(journaled_state.state.clone());
1316
1317        let res = {
1318            configure_tx_req_env(&mut env.as_env_mut(), tx, None)?;
1319
1320            let mut db = self.clone();
1321            let mut evm = new_evm_with_inspector(&mut db, env.to_owned(), inspector);
1322            evm.journaled_state.depth = journaled_state.depth + 1;
1323            evm.transact(env.tx)?
1324        };
1325
1326        self.commit(res.state);
1327        update_state(&mut journaled_state.state, self, None)?;
1328
1329        Ok(())
1330    }
1331
1332    fn active_fork_id(&self) -> Option<LocalForkId> {
1333        self.active_fork_ids.map(|(id, _)| id)
1334    }
1335
1336    fn active_fork_url(&self) -> Option<String> {
1337        let fork = self.inner.issued_local_fork_ids.get(&self.active_fork_id()?)?;
1338        self.forks.get_fork_url(fork.clone()).ok()?
1339    }
1340
1341    fn ensure_fork(&self, id: Option<LocalForkId>) -> eyre::Result<LocalForkId> {
1342        if let Some(id) = id {
1343            if self.inner.issued_local_fork_ids.contains_key(&id) {
1344                return Ok(id);
1345            }
1346            eyre::bail!("Requested fork `{}` does not exit", id)
1347        }
1348        if let Some(id) = self.active_fork_id() { Ok(id) } else { eyre::bail!("No fork active") }
1349    }
1350
1351    fn ensure_fork_id(&self, id: LocalForkId) -> eyre::Result<&ForkId> {
1352        self.inner.ensure_fork_id(id)
1353    }
1354
1355    fn diagnose_revert(
1356        &self,
1357        callee: Address,
1358        journaled_state: &JournaledState,
1359    ) -> Option<RevertDiagnostic> {
1360        let active_id = self.active_fork_id()?;
1361        let active_fork = self.active_fork()?;
1362
1363        if self.inner.forks.len() == 1 {
1364            // we only want to provide additional diagnostics here when in multifork mode with > 1
1365            // forks
1366            return None;
1367        }
1368
1369        if !active_fork.is_contract(callee) && !is_contract_in_state(journaled_state, callee) {
1370            // no contract for `callee` available on current fork, check if available on other forks
1371            let mut available_on = Vec::new();
1372            for (id, fork) in self.inner.forks_iter().filter(|(id, _)| *id != active_id) {
1373                trace!(?id, address=?callee, "checking if account exists");
1374                if fork.is_contract(callee) {
1375                    available_on.push(id);
1376                }
1377            }
1378
1379            return if available_on.is_empty() {
1380                Some(RevertDiagnostic::ContractDoesNotExist {
1381                    contract: callee,
1382                    active: active_id,
1383                    persistent: self.is_persistent(&callee),
1384                })
1385            } else {
1386                // likely user error: called a contract that's not available on active fork but is
1387                // present other forks
1388                Some(RevertDiagnostic::ContractExistsOnOtherForks {
1389                    contract: callee,
1390                    active: active_id,
1391                    available_on,
1392                })
1393            };
1394        }
1395        None
1396    }
1397
1398    /// Loads the account allocs from the given `allocs` map into the passed [JournaledState].
1399    ///
1400    /// Returns [Ok] if all accounts were successfully inserted into the journal, [Err] otherwise.
1401    fn load_allocs(
1402        &mut self,
1403        allocs: &BTreeMap<Address, GenesisAccount>,
1404        journaled_state: &mut JournaledState,
1405    ) -> Result<(), BackendError> {
1406        // Loop through all of the allocs defined in the map and commit them to the journal.
1407        for (addr, acc) in allocs {
1408            self.clone_account(acc, addr, journaled_state)?;
1409        }
1410
1411        Ok(())
1412    }
1413
1414    /// Copies bytecode, storage, nonce and balance from the given genesis account to the target
1415    /// address.
1416    ///
1417    /// Returns [Ok] if data was successfully inserted into the journal, [Err] otherwise.
1418    fn clone_account(
1419        &mut self,
1420        source: &GenesisAccount,
1421        target: &Address,
1422        journaled_state: &mut JournaledState,
1423    ) -> Result<(), BackendError> {
1424        // Fetch the account from the journaled state. Will create a new account if it does
1425        // not already exist.
1426        let mut state_acc = journaled_state.load_account(self, *target)?;
1427
1428        // Set the account's bytecode and code hash, if the `bytecode` field is present.
1429        if let Some(bytecode) = source.code.as_ref() {
1430            state_acc.info.code_hash = keccak256(bytecode);
1431            let bytecode = Bytecode::new_raw(bytecode.0.clone().into());
1432            state_acc.info.code = Some(bytecode);
1433        }
1434
1435        // Set the account's storage, if the `storage` field is present.
1436        if let Some(storage) = source.storage.as_ref() {
1437            state_acc.storage = storage
1438                .iter()
1439                .map(|(slot, value)| {
1440                    let slot = U256::from_be_bytes(slot.0);
1441                    (
1442                        slot,
1443                        EvmStorageSlot::new_changed(
1444                            state_acc
1445                                .storage
1446                                .get(&slot)
1447                                .map(|s| s.present_value)
1448                                .unwrap_or_default(),
1449                            U256::from_be_bytes(value.0),
1450                        ),
1451                    )
1452                })
1453                .collect();
1454        }
1455        // Set the account's nonce and balance.
1456        state_acc.info.nonce = source.nonce.unwrap_or_default();
1457        state_acc.info.balance = source.balance;
1458
1459        // Touch the account to ensure the loaded information persists if called in `setUp`.
1460        journaled_state.touch(*target);
1461
1462        Ok(())
1463    }
1464
1465    fn add_persistent_account(&mut self, account: Address) -> bool {
1466        trace!(?account, "add persistent account");
1467        self.inner.persistent_accounts.insert(account)
1468    }
1469
1470    fn remove_persistent_account(&mut self, account: &Address) -> bool {
1471        trace!(?account, "remove persistent account");
1472        self.inner.persistent_accounts.remove(account)
1473    }
1474
1475    fn is_persistent(&self, acc: &Address) -> bool {
1476        self.inner.persistent_accounts.contains(acc)
1477    }
1478
1479    fn allow_cheatcode_access(&mut self, account: Address) -> bool {
1480        trace!(?account, "allow cheatcode access");
1481        self.inner.cheatcode_access_accounts.insert(account)
1482    }
1483
1484    fn revoke_cheatcode_access(&mut self, account: &Address) -> bool {
1485        trace!(?account, "revoke cheatcode access");
1486        self.inner.cheatcode_access_accounts.remove(account)
1487    }
1488
1489    fn has_cheatcode_access(&self, account: &Address) -> bool {
1490        self.inner.cheatcode_access_accounts.contains(account)
1491    }
1492
1493    fn set_blockhash(&mut self, block_number: U256, block_hash: B256) {
1494        if let Some(db) = self.active_fork_db_mut() {
1495            db.cache.block_hashes.insert(block_number.saturating_to(), block_hash);
1496        } else {
1497            self.mem_db.cache.block_hashes.insert(block_number.saturating_to(), block_hash);
1498        }
1499    }
1500}
1501
1502impl DatabaseRef for Backend {
1503    type Error = DatabaseError;
1504
1505    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
1506        if let Some(db) = self.active_fork_db() {
1507            db.basic_ref(address)
1508        } else {
1509            Ok(self.mem_db.basic_ref(address)?)
1510        }
1511    }
1512
1513    fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
1514        if let Some(db) = self.active_fork_db() {
1515            db.code_by_hash_ref(code_hash)
1516        } else {
1517            Ok(self.mem_db.code_by_hash_ref(code_hash)?)
1518        }
1519    }
1520
1521    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
1522        if let Some(db) = self.active_fork_db() {
1523            DatabaseRef::storage_ref(db, address, index)
1524        } else {
1525            Ok(DatabaseRef::storage_ref(&self.mem_db, address, index)?)
1526        }
1527    }
1528
1529    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
1530        if let Some(db) = self.active_fork_db() {
1531            db.block_hash_ref(number)
1532        } else {
1533            Ok(self.mem_db.block_hash_ref(number)?)
1534        }
1535    }
1536}
1537
1538impl DatabaseCommit for Backend {
1539    fn commit(&mut self, changes: Map<Address, Account>) {
1540        if let Some(db) = self.active_fork_db_mut() {
1541            db.commit(changes)
1542        } else {
1543            self.mem_db.commit(changes)
1544        }
1545    }
1546}
1547
1548impl Database for Backend {
1549    type Error = DatabaseError;
1550    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
1551        if let Some(db) = self.active_fork_db_mut() {
1552            Ok(db.basic(address)?)
1553        } else {
1554            Ok(self.mem_db.basic(address)?)
1555        }
1556    }
1557
1558    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
1559        if let Some(db) = self.active_fork_db_mut() {
1560            Ok(db.code_by_hash(code_hash)?)
1561        } else {
1562            Ok(self.mem_db.code_by_hash(code_hash)?)
1563        }
1564    }
1565
1566    fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
1567        if let Some(db) = self.active_fork_db_mut() {
1568            Ok(Database::storage(db, address, index)?)
1569        } else {
1570            Ok(Database::storage(&mut self.mem_db, address, index)?)
1571        }
1572    }
1573
1574    fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
1575        if let Some(db) = self.active_fork_db_mut() {
1576            Ok(db.block_hash(number)?)
1577        } else {
1578            Ok(self.mem_db.block_hash(number)?)
1579        }
1580    }
1581}
1582
1583/// Variants of a [revm::Database]
1584#[derive(Clone, Debug)]
1585pub enum BackendDatabaseSnapshot {
1586    /// Simple in-memory [revm::Database]
1587    InMemory(FoundryEvmInMemoryDB),
1588    /// Contains the entire forking mode database
1589    Forked(LocalForkId, ForkId, ForkLookupIndex, Box<Fork>),
1590}
1591
1592/// Represents a fork
1593#[derive(Clone, Debug)]
1594pub struct Fork {
1595    db: ForkDB,
1596    journaled_state: JournaledState,
1597}
1598
1599impl Fork {
1600    /// Returns true if the account is a contract
1601    pub fn is_contract(&self, acc: Address) -> bool {
1602        if let Ok(Some(acc)) = self.db.basic_ref(acc)
1603            && acc.code_hash != KECCAK_EMPTY
1604        {
1605            return true;
1606        }
1607        is_contract_in_state(&self.journaled_state, acc)
1608    }
1609}
1610
1611/// Container type for various Backend related data
1612#[derive(Clone, Debug)]
1613pub struct BackendInner {
1614    /// Stores the `ForkId` of the fork the `Backend` launched with from the start.
1615    ///
1616    /// In other words if [`Backend::spawn()`] was called with a `CreateFork` command, to launch
1617    /// directly in fork mode, this holds the corresponding fork identifier of this fork.
1618    pub launched_with_fork: Option<(ForkId, LocalForkId, ForkLookupIndex)>,
1619    /// This tracks numeric fork ids and the `ForkId` used by the handler.
1620    ///
1621    /// This is necessary, because there can be multiple `Backends` associated with a single
1622    /// `ForkId` which is only a pair of endpoint + block. Since an existing fork can be
1623    /// modified (e.g. `roll_fork`), but this should only affect the fork that's unique for the
1624    /// test and not the `ForkId`
1625    ///
1626    /// This ensures we can treat forks as unique from the context of a test, so rolling to another
1627    /// is basically creating(or reusing) another `ForkId` that's then mapped to the previous
1628    /// issued _local_ numeric identifier, that remains constant, even if the underlying fork
1629    /// backend changes.
1630    pub issued_local_fork_ids: HashMap<LocalForkId, ForkId>,
1631    /// tracks all the created forks
1632    /// Contains the index of the corresponding `ForkDB` in the `forks` vec
1633    pub created_forks: HashMap<ForkId, ForkLookupIndex>,
1634    /// Holds all created fork databases
1635    // Note: data is stored in an `Option` so we can remove it without reshuffling
1636    pub forks: Vec<Option<Fork>>,
1637    /// Contains state snapshots made at a certain point
1638    pub state_snapshots: StateSnapshots<BackendStateSnapshot<BackendDatabaseSnapshot>>,
1639    /// Tracks whether there was a failure in a snapshot that was reverted
1640    ///
1641    /// The Test contract contains a bool variable that is set to true when an `assert` function
1642    /// failed. When a snapshot is reverted, it reverts the state of the evm, but we still want
1643    /// to know if there was an `assert` that failed after the snapshot was taken so that we can
1644    /// check if the test function passed all asserts even across snapshots. When a snapshot is
1645    /// reverted we get the _current_ `revm::JournaledState` which contains the state that we can
1646    /// check if the `_failed` variable is set,
1647    /// additionally
1648    pub has_state_snapshot_failure: bool,
1649    /// Tracks the caller of the test function
1650    pub caller: Option<Address>,
1651    /// Tracks numeric identifiers for forks
1652    pub next_fork_id: LocalForkId,
1653    /// All accounts that should be kept persistent when switching forks.
1654    /// This means all accounts stored here _don't_ use a separate storage section on each fork
1655    /// instead the use only one that's persistent across fork swaps.
1656    pub persistent_accounts: HashSet<Address>,
1657    /// The configured spec id
1658    pub spec_id: SpecId,
1659    /// All accounts that are allowed to execute cheatcodes
1660    pub cheatcode_access_accounts: HashSet<Address>,
1661}
1662
1663impl BackendInner {
1664    pub fn ensure_fork_id(&self, id: LocalForkId) -> eyre::Result<&ForkId> {
1665        self.issued_local_fork_ids
1666            .get(&id)
1667            .ok_or_else(|| eyre::eyre!("No matching fork found for {}", id))
1668    }
1669
1670    pub fn ensure_fork_index(&self, id: &ForkId) -> eyre::Result<ForkLookupIndex> {
1671        self.created_forks
1672            .get(id)
1673            .copied()
1674            .ok_or_else(|| eyre::eyre!("No matching fork found for {}", id))
1675    }
1676
1677    pub fn ensure_fork_index_by_local_id(&self, id: LocalForkId) -> eyre::Result<ForkLookupIndex> {
1678        self.ensure_fork_index(self.ensure_fork_id(id)?)
1679    }
1680
1681    /// Returns the underlying fork mapped to the index
1682    #[track_caller]
1683    fn get_fork(&self, idx: ForkLookupIndex) -> &Fork {
1684        debug_assert!(idx < self.forks.len(), "fork lookup index must exist");
1685        self.forks[idx].as_ref().unwrap()
1686    }
1687
1688    /// Returns the underlying fork mapped to the index
1689    #[track_caller]
1690    fn get_fork_mut(&mut self, idx: ForkLookupIndex) -> &mut Fork {
1691        debug_assert!(idx < self.forks.len(), "fork lookup index must exist");
1692        self.forks[idx].as_mut().unwrap()
1693    }
1694
1695    /// Returns the underlying fork corresponding to the id
1696    #[track_caller]
1697    fn get_fork_by_id_mut(&mut self, id: LocalForkId) -> eyre::Result<&mut Fork> {
1698        let idx = self.ensure_fork_index_by_local_id(id)?;
1699        Ok(self.get_fork_mut(idx))
1700    }
1701
1702    /// Returns the underlying fork corresponding to the id
1703    #[track_caller]
1704    fn get_fork_by_id(&self, id: LocalForkId) -> eyre::Result<&Fork> {
1705        let idx = self.ensure_fork_index_by_local_id(id)?;
1706        Ok(self.get_fork(idx))
1707    }
1708
1709    /// Removes the fork
1710    fn take_fork(&mut self, idx: ForkLookupIndex) -> Fork {
1711        debug_assert!(idx < self.forks.len(), "fork lookup index must exist");
1712        self.forks[idx].take().unwrap()
1713    }
1714
1715    fn set_fork(&mut self, idx: ForkLookupIndex, fork: Fork) {
1716        self.forks[idx] = Some(fork)
1717    }
1718
1719    /// Returns an iterator over Forks
1720    pub fn forks_iter(&self) -> impl Iterator<Item = (LocalForkId, &Fork)> + '_ {
1721        self.issued_local_fork_ids
1722            .iter()
1723            .map(|(id, fork_id)| (*id, self.get_fork(self.created_forks[fork_id])))
1724    }
1725
1726    /// Returns a mutable iterator over all Forks
1727    pub fn forks_iter_mut(&mut self) -> impl Iterator<Item = &mut Fork> + '_ {
1728        self.forks.iter_mut().filter_map(|f| f.as_mut())
1729    }
1730
1731    /// Reverts the entire fork database
1732    pub fn revert_state_snapshot(
1733        &mut self,
1734        id: LocalForkId,
1735        fork_id: ForkId,
1736        idx: ForkLookupIndex,
1737        fork: Fork,
1738    ) {
1739        self.created_forks.insert(fork_id.clone(), idx);
1740        self.issued_local_fork_ids.insert(id, fork_id);
1741        self.set_fork(idx, fork)
1742    }
1743
1744    /// Updates the fork and the local mapping and returns the new index for the `fork_db`
1745    pub fn update_fork_mapping(
1746        &mut self,
1747        id: LocalForkId,
1748        fork_id: ForkId,
1749        db: ForkDB,
1750        journaled_state: JournaledState,
1751    ) -> ForkLookupIndex {
1752        let idx = self.forks.len();
1753        self.issued_local_fork_ids.insert(id, fork_id.clone());
1754        self.created_forks.insert(fork_id, idx);
1755
1756        let fork = Fork { db, journaled_state };
1757        self.forks.push(Some(fork));
1758        idx
1759    }
1760
1761    pub fn roll_fork(
1762        &mut self,
1763        id: LocalForkId,
1764        new_fork_id: ForkId,
1765        backend: SharedBackend,
1766    ) -> eyre::Result<ForkLookupIndex> {
1767        let fork_id = self.ensure_fork_id(id)?;
1768        let idx = self.ensure_fork_index(fork_id)?;
1769
1770        if let Some(active) = self.forks[idx].as_mut() {
1771            // we initialize a _new_ `ForkDB` but keep the state of persistent accounts
1772            let mut new_db = ForkDB::new(backend);
1773            for addr in self.persistent_accounts.iter().copied() {
1774                merge_db_account_data(addr, &active.db, &mut new_db);
1775            }
1776            active.db = new_db;
1777        }
1778        // update mappings
1779        self.issued_local_fork_ids.insert(id, new_fork_id.clone());
1780        self.created_forks.insert(new_fork_id, idx);
1781        Ok(idx)
1782    }
1783
1784    /// Inserts a _new_ `ForkDB` and issues a new local fork identifier
1785    ///
1786    /// Also returns the index where the `ForDB` is stored
1787    pub fn insert_new_fork(
1788        &mut self,
1789        fork_id: ForkId,
1790        db: ForkDB,
1791        journaled_state: JournaledState,
1792    ) -> (LocalForkId, ForkLookupIndex) {
1793        let idx = self.forks.len();
1794        self.created_forks.insert(fork_id.clone(), idx);
1795        let id = self.next_id();
1796        self.issued_local_fork_ids.insert(id, fork_id);
1797        let fork = Fork { db, journaled_state };
1798        self.forks.push(Some(fork));
1799        (id, idx)
1800    }
1801
1802    fn next_id(&mut self) -> U256 {
1803        let id = self.next_fork_id;
1804        self.next_fork_id += U256::from(1);
1805        id
1806    }
1807
1808    /// Returns the number of issued ids
1809    pub fn len(&self) -> usize {
1810        self.issued_local_fork_ids.len()
1811    }
1812
1813    /// Returns true if no forks are issued
1814    pub fn is_empty(&self) -> bool {
1815        self.issued_local_fork_ids.is_empty()
1816    }
1817
1818    pub fn precompiles(&self) -> &'static Precompiles {
1819        Precompiles::new(PrecompileSpecId::from_spec_id(self.spec_id))
1820    }
1821
1822    /// Returns a new, empty, `JournaledState` with set precompiles
1823    pub fn new_journaled_state(&self) -> JournaledState {
1824        let mut journal = {
1825            let mut journal_inner = JournalInner::new();
1826            journal_inner.set_spec_id(self.spec_id);
1827            journal_inner
1828        };
1829        journal.precompiles.extend(self.precompiles().addresses().copied());
1830        journal
1831    }
1832}
1833
1834impl Default for BackendInner {
1835    fn default() -> Self {
1836        Self {
1837            launched_with_fork: None,
1838            issued_local_fork_ids: Default::default(),
1839            created_forks: Default::default(),
1840            forks: vec![],
1841            state_snapshots: Default::default(),
1842            has_state_snapshot_failure: false,
1843            caller: None,
1844            next_fork_id: Default::default(),
1845            persistent_accounts: Default::default(),
1846            spec_id: SpecId::default(),
1847            // grant the cheatcode,default test and caller address access to execute cheatcodes
1848            // itself
1849            cheatcode_access_accounts: HashSet::from([
1850                CHEATCODE_ADDRESS,
1851                TEST_CONTRACT_ADDRESS,
1852                CALLER,
1853            ]),
1854        }
1855    }
1856}
1857
1858/// This updates the currently used env with the fork's environment
1859pub(crate) fn update_current_env_with_fork_env(current: &mut EnvMut<'_>, fork: Env) {
1860    *current.block = fork.evm_env.block_env;
1861    *current.cfg = fork.evm_env.cfg_env;
1862    current.tx.chain_id = fork.tx.chain_id;
1863}
1864
1865/// Clones the data of the given `accounts` from the `active` database into the `fork_db`
1866/// This includes the data held in storage (`CacheDB`) and kept in the `JournaledState`.
1867pub(crate) fn merge_account_data<ExtDB: DatabaseRef>(
1868    accounts: impl IntoIterator<Item = Address>,
1869    active: &CacheDB<ExtDB>,
1870    active_journaled_state: &mut JournaledState,
1871    target_fork: &mut Fork,
1872) {
1873    for addr in accounts.into_iter() {
1874        merge_db_account_data(addr, active, &mut target_fork.db);
1875        merge_journaled_state_data(addr, active_journaled_state, &mut target_fork.journaled_state);
1876    }
1877
1878    *active_journaled_state = target_fork.journaled_state.clone();
1879}
1880
1881/// Clones the account data from the `active_journaled_state`  into the `fork_journaled_state`
1882fn merge_journaled_state_data(
1883    addr: Address,
1884    active_journaled_state: &JournaledState,
1885    fork_journaled_state: &mut JournaledState,
1886) {
1887    if let Some(mut acc) = active_journaled_state.state.get(&addr).cloned() {
1888        trace!(?addr, "updating journaled_state account data");
1889        if let Some(fork_account) = fork_journaled_state.state.get_mut(&addr) {
1890            // This will merge the fork's tracked storage with active storage and update values
1891            fork_account.storage.extend(std::mem::take(&mut acc.storage));
1892            // swap them so we can insert the account as whole in the next step
1893            std::mem::swap(&mut fork_account.storage, &mut acc.storage);
1894        }
1895        fork_journaled_state.state.insert(addr, acc);
1896    }
1897}
1898
1899/// Clones the account data from the `active` db into the `ForkDB`
1900fn merge_db_account_data<ExtDB: DatabaseRef>(
1901    addr: Address,
1902    active: &CacheDB<ExtDB>,
1903    fork_db: &mut ForkDB,
1904) {
1905    trace!(?addr, "merging database data");
1906
1907    let Some(acc) = active.cache.accounts.get(&addr) else { return };
1908
1909    // port contract cache over
1910    if let Some(code) = active.cache.contracts.get(&acc.info.code_hash) {
1911        trace!("merging contract cache");
1912        fork_db.cache.contracts.insert(acc.info.code_hash, code.clone());
1913    }
1914
1915    // port account storage over
1916    use std::collections::hash_map::Entry;
1917    match fork_db.cache.accounts.entry(addr) {
1918        Entry::Vacant(vacant) => {
1919            trace!("target account not present - inserting from active");
1920            // if the fork_db doesn't have the target account
1921            // insert the entire thing
1922            vacant.insert(acc.clone());
1923        }
1924        Entry::Occupied(mut occupied) => {
1925            trace!("target account present - merging storage slots");
1926            // if the fork_db does have the system,
1927            // extend the existing storage (overriding)
1928            let fork_account = occupied.get_mut();
1929            fork_account.storage.extend(&acc.storage);
1930        }
1931    }
1932}
1933
1934/// Returns true of the address is a contract
1935fn is_contract_in_state(journaled_state: &JournaledState, acc: Address) -> bool {
1936    journaled_state
1937        .state
1938        .get(&acc)
1939        .map(|acc| acc.info.code_hash != KECCAK_EMPTY)
1940        .unwrap_or_default()
1941}
1942
1943/// Updates the env's block with the block's data
1944fn update_env_block(env: &mut EnvMut<'_>, block: &AnyRpcBlock) {
1945    env.block.timestamp = block.header.timestamp;
1946    env.block.beneficiary = block.header.beneficiary;
1947    env.block.difficulty = block.header.difficulty;
1948    env.block.prevrandao = Some(block.header.mix_hash.unwrap_or_default());
1949    env.block.basefee = block.header.base_fee_per_gas.unwrap_or_default();
1950    env.block.gas_limit = block.header.gas_limit;
1951    env.block.number = block.header.number;
1952    if let Some(excess_blob_gas) = block.header.excess_blob_gas {
1953        env.block.blob_excess_gas_and_price =
1954            Some(BlobExcessGasAndPrice::new(excess_blob_gas, false));
1955    }
1956}
1957
1958/// Executes the given transaction and commits state changes to the database _and_ the journaled
1959/// state, with an inspector.
1960fn commit_transaction(
1961    tx: &Transaction<AnyTxEnvelope>,
1962    env: &mut EnvMut<'_>,
1963    journaled_state: &mut JournaledState,
1964    fork: &mut Fork,
1965    fork_id: &ForkId,
1966    persistent_accounts: &HashSet<Address>,
1967    inspector: &mut dyn InspectorExt,
1968) -> eyre::Result<()> {
1969    configure_tx_env(env, tx);
1970
1971    let now = Instant::now();
1972    let res = {
1973        let fork = fork.clone();
1974        let journaled_state = journaled_state.clone();
1975        let depth = journaled_state.depth;
1976        let mut db = Backend::new_with_fork(fork_id, fork, journaled_state)?;
1977
1978        let mut evm = crate::evm::new_evm_with_inspector(&mut db as _, env.to_owned(), inspector);
1979        // Adjust inner EVM depth to ensure that inspectors receive accurate data.
1980        evm.journaled_state.depth = depth + 1;
1981        evm.transact(env.tx.clone()).wrap_err("backend: failed committing transaction")?
1982    };
1983    trace!(elapsed = ?now.elapsed(), "transacted transaction");
1984
1985    apply_state_changeset(res.state, journaled_state, fork, persistent_accounts)?;
1986    Ok(())
1987}
1988
1989/// Helper method which updates data in the state with the data from the database.
1990/// Does not change state for persistent accounts (for roll fork to transaction and transact).
1991pub fn update_state<DB: Database>(
1992    state: &mut EvmState,
1993    db: &mut DB,
1994    persistent_accounts: Option<&HashSet<Address>>,
1995) -> Result<(), DB::Error> {
1996    for (addr, acc) in state.iter_mut() {
1997        if !persistent_accounts.is_some_and(|accounts| accounts.contains(addr)) {
1998            acc.info = db.basic(*addr)?.unwrap_or_default();
1999            for (key, val) in &mut acc.storage {
2000                val.present_value = db.storage(*addr, *key)?;
2001            }
2002        }
2003    }
2004
2005    Ok(())
2006}
2007
2008/// Applies the changeset of a transaction to the active journaled state and also commits it in the
2009/// forked db
2010fn apply_state_changeset(
2011    state: Map<revm::primitives::Address, Account>,
2012    journaled_state: &mut JournaledState,
2013    fork: &mut Fork,
2014    persistent_accounts: &HashSet<Address>,
2015) -> Result<(), BackendError> {
2016    // commit the state and update the loaded accounts
2017    fork.db.commit(state);
2018
2019    update_state(&mut journaled_state.state, &mut fork.db, Some(persistent_accounts))?;
2020    update_state(&mut fork.journaled_state.state, &mut fork.db, Some(persistent_accounts))?;
2021
2022    Ok(())
2023}
2024
2025#[cfg(test)]
2026mod tests {
2027    use crate::{backend::Backend, fork::CreateFork, opts::EvmOpts};
2028    use alloy_primitives::{Address, U256};
2029    use alloy_provider::Provider;
2030    use foundry_common::provider::get_http_provider;
2031    use foundry_config::{Config, NamedChain};
2032    use foundry_fork_db::cache::{BlockchainDb, BlockchainDbMeta};
2033    use revm::database::DatabaseRef;
2034
2035    const ENDPOINT: Option<&str> = option_env!("ETH_RPC_URL");
2036
2037    #[tokio::test(flavor = "multi_thread")]
2038    async fn can_read_write_cache() {
2039        let Some(endpoint) = ENDPOINT else { return };
2040
2041        let provider = get_http_provider(endpoint);
2042
2043        let block_num = provider.get_block_number().await.unwrap();
2044
2045        let config = Config::figment();
2046        let mut evm_opts = config.extract::<EvmOpts>().unwrap();
2047        evm_opts.fork_block_number = Some(block_num);
2048
2049        let (env, _block) = evm_opts.fork_evm_env(endpoint).await.unwrap();
2050
2051        let fork = CreateFork {
2052            enable_caching: true,
2053            url: endpoint.to_string(),
2054            env: env.clone(),
2055            evm_opts,
2056        };
2057
2058        let backend = Backend::spawn(Some(fork)).unwrap();
2059
2060        // some rng contract from etherscan
2061        let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
2062
2063        let idx = U256::from(0u64);
2064        let _value = backend.storage_ref(address, idx);
2065        let _account = backend.basic_ref(address);
2066
2067        // fill some slots
2068        let num_slots = 10u64;
2069        for idx in 1..num_slots {
2070            let _ = backend.storage_ref(address, U256::from(idx));
2071        }
2072        drop(backend);
2073
2074        let meta = BlockchainDbMeta { block_env: env.evm_env.block_env, hosts: Default::default() };
2075
2076        let db = BlockchainDb::new(
2077            meta,
2078            Some(Config::foundry_block_cache_dir(NamedChain::Mainnet, block_num).unwrap()),
2079        );
2080        assert!(db.accounts().read().contains_key(&address));
2081        assert!(db.storage().read().contains_key(&address));
2082        assert_eq!(db.storage().read().get(&address).unwrap().len(), num_slots as usize);
2083    }
2084}