Skip to main content

foundry_evm_core/evm/
lifecycle.rs

1//! Foundry's execution lifecycle over evm2: fork switching, snapshots and nested execution.
2//!
3//! evm2's [`State`] owns transaction scratch, journaling, warmth, transient storage, logs and the
4//! accepted overlay of the running context. This module owns everything Foundry layers on top:
5//! which backing database is active, the accepted state of every inactive fork, user-visible
6//! snapshots, and nested transactions.
7//!
8//! # Executions
9//!
10//! [`ExecutionLifecycle::create_evm`] builds an EVM over the active context without copying its
11//! accepted state: the EVM reads it through a shared view and its overlay only collects what the
12//! execution reads and writes. [`ExecutionLifecycle::park`] accepts the EVM's state back into the
13//! active context, after a commit; dropping the EVM instead discards it, as for calls. Lifecycle
14//! operations that capture or replace the running state (fork switches, snapshots, nested
15//! transactions) first materialize the view into the EVM's overlay, once.
16//!
17//! # Execution phases
18//!
19//! evm2 allows replacing state and the block environment while a transaction runs, but not the
20//! spec or runtime [`Version`](evm2::Version), which also carries the chain ID. Operations that
21//! need a different spec or chain ID while a transaction is in flight apply everything else at
22//! once and record the rest as the pending environment ([`ExecutionLifecycle::pending_env`]);
23//! [`ExecutionLifecycle::begin_transaction`] then applies it at the next transaction boundary.
24//! Until then, the inspector stack runs frames started after the change on a frame EVM built with
25//! the pending environment ([`ExecutionLifecycle::begin_frame_evm`]).
26//!
27//! Suspending a context accepts its in-flight writes, so a fork switch is not undone when an
28//! enclosing call reverts.
29
30use super::{
31    AcceptedView, BackingDb, EvmEnv, ForkInfo, ForkPosition, ForkRegistry, FoundryEvmExt,
32    FoundryEvmFactory, FoundryExecutionHooks, LifecycleSnapshot, Parked, StoredExt, evm_env,
33};
34use crate::{
35    backend::{RevertStateSnapshotAction, transaction_error},
36    state_snapshot::StateSnapshots,
37};
38use alloy_consensus::{Typed2718, transaction::Recovered};
39use alloy_eips::eip2930::AccessList;
40use alloy_primitives::{
41    Address, B256, KECCAK256_EMPTY, Log, U256, U512,
42    aliases::I512,
43    map::{AddressMap, AddressSet, Entry, HashMap, HashSet},
44};
45use evm2::{
46    Evm, EvmFeatures, EvmTypes, EvmTypesHost, ExecutedTx, Inspector, TxResult, TxResultWithState,
47    bytecode::Bytecode,
48    evm::{
49        AccountChanges, AccountFlags, AccountHandle, AccountInfo, Cache, CacheDB, DbResult,
50        DynDatabase, EmptyDB, JournalEntry, PendingState, PrewarmSet, State, StateCheckpoint,
51        StateSnapshot,
52    },
53};
54use std::{iter, mem, sync::Arc};
55
56/// Whether a lifecycle operation runs between transactions or inside one, such as from a
57/// cheatcode.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum ExecutionPhase {
60    /// Between transactions: every part of the environment can change.
61    Boundary,
62    /// Inside a running transaction.
63    InFlight,
64}
65
66/// A transaction prepared to execute as a nested transaction of the running one, such as for
67/// `vm.transact`, whose inspector may hold the lifecycle's owner while it runs.
68///
69/// Build it with [`ExecutionLifecycle::prepare_nested`] or
70/// [`ExecutionLifecycle::prepare_on_inactive`], run it with [`Self::execute`] and store its
71/// outcome with [`ExecutionLifecycle::store_executed`].
72pub struct PreparedTx<T: EvmTypesHost> {
73    executor: Evm<'static, T>,
74    tx: Recovered<T::Tx>,
75    /// The inactive context the transaction executes on, with the persistent accounts whose
76    /// changes merge back into the running transaction.
77    inactive: Option<(Option<U256>, AddressSet)>,
78    /// The fork whose canonical position and block cursor advance once the transaction executed.
79    cursor: Option<ForkCursor<T>>,
80    /// The transaction's EIP-2930 access list, if its caller recorded it.
81    access_list: Option<AccessList>,
82}
83
84/// A fork's canonical position and the network state retaining its block cursor.
85pub type ForkCursor<T> = (U256, ForkPosition, <T as EvmTypesHost>::EvmExt);
86
87impl<T: EvmTypes<Tx: Typed2718>> PreparedTx<T> {
88    /// Returns the transaction.
89    pub const fn tx(&self) -> &Recovered<T::Tx> {
90        &self.tx
91    }
92
93    /// Advances fork `id` to `position`, with the network state retaining its block `cursor`,
94    /// once the transaction executed.
95    pub fn set_cursor(&mut self, id: U256, position: ForkPosition, cursor: T::EvmExt) {
96        self.cursor = Some((id, position, cursor));
97    }
98
99    /// Returns the environment the transaction executes in.
100    pub const fn env(&self) -> EvmEnv<T> {
101        evm_env(&self.executor)
102    }
103
104    /// Returns the transaction's EIP-2930 access list, if recorded.
105    pub const fn access_list(&self) -> Option<&AccessList> {
106        self.access_list.as_ref()
107    }
108
109    /// Records the transaction's EIP-2930 access list.
110    pub fn set_access_list(&mut self, access_list: Option<AccessList>) {
111        self.access_list = access_list;
112    }
113
114    /// Executes the transaction observed by `inspector` and merges its changes into the running
115    /// transaction of `evm` as journaled writes: all of them on the running transaction's
116    /// context, where a failed transaction only keeps its nonce increment and fee payment, and
117    /// the changes to persistent accounts on an inactive context, which accepts the transaction
118    /// and whose resulting state the running transaction's other loaded accounts then take.
119    /// With `untracked`, changes on the active context survive reverts of the enclosing calls.
120    pub fn execute(
121        self,
122        evm: &mut Evm<'_, T>,
123        inspector: Option<&mut dyn Inspector<T>>,
124        untracked: bool,
125    ) -> eyre::Result<ExecutedNested<T>> {
126        let Self { executor, tx, inactive, cursor, access_list: _ } = self;
127        let mut executor: Evm<'_, T> = executor;
128        if let Some(inspector) = inspector {
129            executor.set_inspector(inspector);
130        }
131        let executed = executor.transact(&tx).map_err(transaction_error)?;
132        let Some((id, persistent)) = inactive else {
133            let (persistent, accepted) = if untracked {
134                merge_untracked_nested_changes(evm.state_mut(), &executed)?
135            } else {
136                let reloads = merge_changes(
137                    evm.state_mut(),
138                    executed.account_changes(),
139                    |_| true,
140                    None,
141                    None,
142                )?;
143                (reloads, Vec::new())
144            };
145            let result = executed.result().clone();
146            return Ok(ExecutedNested { result, context: None, cursor, persistent, accepted });
147        };
148        // The inactive context's code is not in the running transaction's database.
149        let TxResultWithState { result, pending_state, .. } = executed.detach();
150        let source = executor.state_mut().overlay_db_mut();
151        let reloads = merge_changes(
152            evm.state_mut(),
153            pending_state.account_changes(),
154            |address| persistent.contains(address),
155            None,
156            Some(source),
157        )?;
158        source.commit_pending(&pending_state);
159        rebase_loaded_accounts(evm.state_mut(), executor.state_mut(), &persistent)?;
160        executor.clear_inspector();
161        let cache = mem::take(&mut executor.state_mut().overlay_db_mut().cache);
162        Ok(ExecutedNested {
163            result,
164            context: Some((id, cache)),
165            cursor,
166            persistent: reloads,
167            accepted: Vec::new(),
168        })
169    }
170}
171
172/// The outcome of a [`PreparedTx`], to store with [`ExecutionLifecycle::store_executed`].
173#[must_use = "an inactive context's accepted state must be stored"]
174pub struct ExecutedNested<T: EvmTypesHost> {
175    result: TxResult<T>,
176    /// The inactive context the transaction was accepted on, with its new accepted state.
177    context: Option<(Option<U256>, Cache)>,
178    /// See [`PreparedTx::set_cursor`].
179    cursor: Option<ForkCursor<T>>,
180    /// Writes of an untracked merge, or the storage reloads of a tracked one, to replay when an
181    /// enclosing call reverts.
182    persistent: Vec<PersistentWrite>,
183    /// Changes of an untracked merge accepted into the running state, see
184    /// [`merge_untracked_nested_changes`].
185    accepted: Vec<PersistentWrite>,
186}
187
188impl<T: EvmTypesHost> ExecutedNested<T> {
189    /// Takes the fork cursor to advance, see [`PreparedTx::set_cursor`].
190    pub const fn take_cursor(&mut self) -> Option<ForkCursor<T>> {
191        self.cursor.take()
192    }
193
194    /// Takes the writes of an untracked merge or the storage reloads of a tracked one, see
195    /// [`PersistentWrite`].
196    pub fn take_persistent(&mut self) -> Vec<PersistentWrite> {
197        mem::take(&mut self.persistent)
198    }
199
200    /// Takes the changes of an untracked merge accepted into the running state.
201    pub fn take_accepted(&mut self) -> Vec<PersistentWrite> {
202        mem::take(&mut self.accepted)
203    }
204}
205
206/// A write that must survive reverts of the enclosing calls, such as a cheatcode's state edit. It
207/// is applied as a journaled write, and the owner replays it after each enclosing call that
208/// reverts. Balance and nonce writes replay as deltas, so they compose with value transfers and
209/// nonce bumps undone by the revert, saturating at their bounds, unless their [`Replay`] mode
210/// says otherwise.
211#[derive(Clone, Debug)]
212pub enum PersistentWrite {
213    /// Changes an account's balance.
214    Balance {
215        /// The account.
216        address: Address,
217        /// The change to the balance, added saturating at its bounds.
218        delta: I512,
219        /// The balance the write left.
220        balance: U256,
221        /// Whether the write adds `delta` or sets `balance`.
222        replay: Replay,
223    },
224    /// Changes an account's nonce.
225    Nonce {
226        /// The account.
227        address: Address,
228        /// The change to the nonce, added saturating at its bounds.
229        delta: i128,
230        /// The nonce the write left.
231        nonce: u64,
232        /// Whether the running transaction had created the account when the write was made. A
233        /// revert that undoes the creation also undoes the write. Unset for the reset of an
234        /// account a nested transaction created, which outlives the creation.
235        created: bool,
236        /// Whether the write adds `delta` or sets `nonce`.
237        replay: Replay,
238    },
239    /// Sets an account's code.
240    Code(Address, B256, Bytecode),
241    /// Wipes an account's storage.
242    Wipe(Address),
243    /// Sets a storage slot.
244    Slot(Address, U256, U256),
245    /// Marks an account self-destructed, so the running transaction destroys it when it ends.
246    Destruct(Address),
247    /// Reloads the slots that the running transaction read while a merged creation discarded an
248    /// account's storage, other than the listed ones it had loaded before, once a revert undid the
249    /// creation. evm2 keeps the zero those slots read, with a zero original, so they are reread
250    /// from the committed state as both their original and current values.
251    ReloadDiscarded(Address, Vec<U256>),
252}
253
254/// How a balance or nonce [`PersistentWrite`] replays, ordered by precedence when combined.
255#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
256pub enum Replay {
257    /// Adds its delta.
258    #[default]
259    Delta,
260    /// Adds its delta, except that a failing frame replaying it over the state a snapshot
261    /// restoration it followed replaced sets the value it left instead, see
262    /// [`PersistentWrite::reinstated`]. Writes that set a value, such as `deal`, replay this way.
263    Set,
264    /// Sets the value it left.
265    Absolute,
266}
267
268/// The state a nested transaction left an account in before the transaction ended and destroyed
269/// it, which the running transaction keeps until it ends itself.
270#[derive(Clone, Debug)]
271pub struct DestructedAccount {
272    info: AccountInfo,
273    code: Bytecode,
274    slots: Vec<(U256, U256)>,
275}
276
277/// Returns the accounts the running transaction in `state` self-destructed, with their state before
278/// the transaction ends and destroys them, such as at the end of the root frame of a nested
279/// transaction.
280pub fn destructed_accounts(state: &mut State<'_>) -> DbResult<AddressMap<DestructedAccount>> {
281    let loaded = loaded_slots(state);
282    let mut destructed = AddressMap::default();
283    for (address, keys) in loaded {
284        let code = {
285            let mut account = state.account(&address)?;
286            if !account.is_destructed() {
287                continue;
288            }
289            account.load_code()?
290        };
291        let Some(info) = state.account_info_untracked(&address)? else { continue };
292        let slots = keys
293            .into_iter()
294            .map(|key| Ok((key, state.storage_slot_untracked(&address, &key)?)))
295            .collect::<DbResult<_>>()?;
296        destructed.insert(address, DestructedAccount { info, code, slots });
297    }
298    Ok(destructed)
299}
300
301impl PersistentWrite {
302    /// Returns the write that changes the balance of `address` from `previous` to `balance`.
303    pub fn balance(address: Address, previous: U256, balance: U256) -> Self {
304        let widen = |value| I512::from_raw(U512::from(value));
305        Self::Balance {
306            address,
307            delta: widen(balance) - widen(previous),
308            balance,
309            replay: Replay::Delta,
310        }
311    }
312
313    /// Returns the nonce write that `account`, whose nonce was `previous`, just made.
314    pub fn nonce(account: &AccountHandle<'_, '_>, previous: u64) -> Self {
315        Self::Nonce {
316            address: account.address(),
317            delta: i128::from(account.nonce()) - i128::from(previous),
318            nonce: account.nonce(),
319            created: account.is_created(),
320            replay: Replay::Delta,
321        }
322    }
323
324    /// Returns the write with `replay` as its mode, if it is a balance or nonce write.
325    pub const fn with_replay(mut self, mode: Replay) -> Self {
326        if let Self::Balance { replay, .. } | Self::Nonce { replay, .. } = &mut self {
327            *replay = mode;
328        }
329        self
330    }
331
332    /// Returns the write to replay over the state a snapshot restoration it followed replaced,
333    /// which sets the value a [`Replay::Set`] write left.
334    pub const fn reinstated(self) -> Self {
335        match self {
336            Self::Balance { replay: Replay::Set, .. } | Self::Nonce { replay: Replay::Set, .. } => {
337                self.with_replay(Replay::Absolute)
338            }
339            write => write,
340        }
341    }
342
343    /// Applies the write to `state` as a journaled write.
344    pub fn apply(&self, state: &mut State<'_>) -> DbResult<()> {
345        match self {
346            Self::Balance { .. } | Self::Nonce { .. } => {
347                Self::apply_all([self], state)?;
348            }
349            Self::Code(address, code_hash, code) => {
350                state.account(address)?.set_code(*code_hash, code.clone());
351            }
352            Self::Wipe(address) => state.storage(address)?.wipe(),
353            Self::Slot(address, key, value) => state.storage_slot(address, *key)?.set(*value),
354            Self::Destruct(address) => state.account(address)?.mark_destructed(),
355            Self::ReloadDiscarded(address, loaded) => {
356                let keys = state
357                    .loaded_accounts()
358                    .find(|(account, _)| *account == address)
359                    .map(|(_, slots)| {
360                        slots.filter(|key| !loaded.contains(key)).copied().collect::<Vec<_>>()
361                    })
362                    .unwrap_or_default();
363                if keys.is_empty()
364                    || state.account(address)?.is_created()
365                    || state.storage(address)?.is_wiped()
366                {
367                    return Ok(());
368                }
369                for key in keys {
370                    // A slot read under the creation holds zero as its original and value.
371                    let slot = state.storage_slot(address, key)?;
372                    if !slot.original().is_zero() || !slot.current().is_zero() {
373                        continue;
374                    }
375                    state.reload_storage_slot(address, &key)?;
376                }
377            }
378        }
379        Ok(())
380    }
381
382    /// Returns whether the write is a balance or nonce write, which [`Self::apply_all`] combines
383    /// with the account's other ones.
384    pub const fn is_balance_or_nonce(&self) -> bool {
385        matches!(self, Self::Balance { .. } | Self::Nonce { .. })
386    }
387
388    /// Applies `writes` in order like [`Self::apply`], except that the balance and nonce deltas
389    /// of each account since its last absolute write of the kind are summed and saturated once,
390    /// instead of per write.
391    ///
392    /// Returns the balance and nonce changes the writes made, to record in their place, so that a
393    /// later replay keeps the saturation. Each change takes the highest [`Replay`] mode of the
394    /// writes it combines, so a change that includes an absolute write keeps setting the value it
395    /// left under enclosing rollbacks.
396    pub fn apply_all<'w>(
397        writes: impl IntoIterator<Item = &'w Self>,
398        state: &mut State<'_>,
399    ) -> DbResult<Vec<Self>> {
400        // The value of the last absolute write, if any, the deltas since, and the mode of the
401        // combined write.
402        let mut balances = AddressMap::<(Option<U256>, I512, Replay)>::default();
403        let mut nonces = AddressMap::<(Option<u64>, i128, Replay)>::default();
404        for write in writes {
405            match write {
406                Self::Balance { address, delta, balance, replay } => {
407                    let entry = balances.entry(*address).or_default();
408                    *entry = if *replay == Replay::Absolute {
409                        (Some(*balance), I512::ZERO, Replay::Absolute)
410                    } else {
411                        (entry.0, entry.1 + *delta, entry.2.max(*replay))
412                    };
413                }
414                Self::Nonce { address, delta, nonce, created, replay } => {
415                    if !*created || state.account(address)?.is_created() {
416                        let entry = nonces.entry(*address).or_default();
417                        *entry = if *replay == Replay::Absolute {
418                            (Some(*nonce), 0, Replay::Absolute)
419                        } else {
420                            (entry.0, entry.1 + delta, entry.2.max(*replay))
421                        };
422                    }
423                }
424                write => write.apply(state)?,
425            }
426        }
427        let mut applied = Vec::new();
428        for (address, (set, delta, replay)) in balances {
429            let mut account = state.account(&address)?;
430            let previous = account.balance();
431            let balance = I512::from_raw(U512::from(set.unwrap_or(previous))) + delta;
432            let balance = if balance.is_negative() {
433                U256::ZERO
434            } else {
435                U256::saturating_from(balance.into_raw())
436            };
437            account.set_balance(balance);
438            applied.push(Self::balance(address, previous, balance).with_replay(replay));
439        }
440        for (address, (set, delta, replay)) in nonces {
441            let mut account = state.account(&address)?;
442            let previous = account.nonce();
443            account.touch();
444            let nonce = (i128::from(set.unwrap_or(previous)) + delta).max(0);
445            account.set_nonce(u64::try_from(nonce).unwrap_or(u64::MAX));
446            applied.push(Self::nonce(&account, previous).with_replay(replay));
447        }
448        Ok(applied)
449    }
450}
451
452/// Fork, snapshot and nested-execution lifecycle for one EVM network family.
453pub struct ExecutionLifecycle<F: FoundryEvmFactory> {
454    factory: F,
455    forks: ForkRegistry<F::Types>,
456    snapshots: StateSnapshots<LifecycleSnapshot<F::Types>>,
457    pending_env: Option<EvmEnv<F::Types>>,
458    /// Base warm set of the running transaction from before a fork switch carried warmth into it.
459    tx_prewarm: Option<PrewarmSet>,
460    /// Transaction-start info of the persistent accounts a fork switch accepted the running
461    /// transaction's changes to.
462    tx_original: AddressMap<Option<AccountInfo>>,
463    /// Warm slots of persistent accounts the last fork switch carried into the next context.
464    switch_slots: AddressMap<HashSet<U256>>,
465}
466
467impl<F: FoundryEvmFactory> Clone for ExecutionLifecycle<F> {
468    fn clone(&self) -> Self {
469        Self {
470            factory: self.factory.clone(),
471            forks: self.forks.clone(),
472            snapshots: self.snapshots.clone(),
473            pending_env: self.pending_env,
474            tx_prewarm: self.tx_prewarm.clone(),
475            tx_original: self.tx_original.clone(),
476            switch_slots: self.switch_slots.clone(),
477        }
478    }
479}
480
481impl<F: FoundryEvmFactory> std::fmt::Debug for ExecutionLifecycle<F> {
482    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
483        f.debug_struct("ExecutionLifecycle").field("forks", &self.forks).finish_non_exhaustive()
484    }
485}
486
487impl<F: FoundryEvmFactory> ExecutionLifecycle<F> {
488    /// Creates a lifecycle whose active context is local execution over `db`.
489    pub fn new(factory: F, db: impl BackingDb, env: EvmEnv<F::Types>) -> Self {
490        let ext = factory.configure_for(&db, &env).evm_ext(&env);
491        Self {
492            factory,
493            forks: ForkRegistry::new(Parked::new(Box::new(db), env, ext)),
494            snapshots: StateSnapshots::default(),
495            pending_env: None,
496            tx_prewarm: None,
497            tx_original: AddressMap::default(),
498            switch_slots: AddressMap::default(),
499        }
500    }
501
502    /// Returns the factory.
503    pub const fn factory(&self) -> &F {
504        &self.factory
505    }
506
507    /// Replaces the factory used for EVMs built from now on.
508    pub fn set_factory(&mut self, factory: F) {
509        self.factory = factory;
510    }
511
512    /// Returns the fork registry.
513    pub const fn forks(&self) -> &ForkRegistry<F::Types> {
514        &self.forks
515    }
516
517    /// Returns the fork registry mutably, for persistent-account changes.
518    pub const fn forks_mut(&mut self) -> &mut ForkRegistry<F::Types> {
519        &mut self.forks
520    }
521
522    /// Returns the active context.
523    pub fn active(&self) -> &Parked<F::Types> {
524        self.forks.context(self.forks.active()).expect("active context exists")
525    }
526
527    /// Returns the active context mutably.
528    ///
529    /// Use it between executions only: a running EVM holds its own view of the context.
530    pub fn active_mut(&mut self) -> &mut Parked<F::Types> {
531        let active = self.forks.active();
532        self.forks.context_mut(active).expect("active context exists")
533    }
534
535    /// Records `value` as the accepted value of a slot the running transaction restored the
536    /// original of when it resumed the active context, such as after refreshing the slot from the
537    /// remote, so that a revert leaving the context keeps it.
538    pub fn refresh_switched_slot(&mut self, address: &Address, slot: U256, value: U256) {
539        if let Some(switched) = self.active_mut().switched.get_mut(address)
540            && let Some(accepted) = switched.get_mut(&slot)
541        {
542            *accepted = value;
543        }
544    }
545
546    /// Returns the active context's accepted state for modification between executions,
547    /// initializing the context first if it never ran.
548    pub fn accepted_mut(&mut self) -> &mut Cache {
549        if self.active().cache.is_none() {
550            let evm = self.create_evm();
551            self.park(evm);
552        }
553        Arc::make_mut(self.active_mut().cache.as_mut().expect("context is initialized"))
554    }
555
556    /// Returns a database reading the active context's accepted state over its backing database,
557    /// for reads between executions.
558    pub fn accepted_db(&self) -> impl BackingDb + use<F> {
559        self.active().accepted_db()
560    }
561
562    /// Returns whether a snapshot exists.
563    pub fn has_snapshot(&self, id: U256) -> bool {
564        self.snapshots.get(id).is_some()
565    }
566
567    /// Creates an EVM over the active context without copying its accepted state.
568    ///
569    /// A context that never ran is initialized first (network genesis, sentinels). Pass the EVM to
570    /// [`Self::park`] to accept its state, or drop it to discard it.
571    pub fn create_evm<'a>(&self) -> Evm<'a, F::Types> {
572        let context = self.active();
573        let db = context.db.clone_backing();
574        let env = context.env;
575        match &context.cache {
576            None => self.factory.create_evm(db, env),
577            Some(cache) => {
578                let factory = self.factory.configure_for(&db, &env);
579                let view = AcceptedView { cache: Arc::clone(cache), backing: db };
580                factory.new_evm_with_ext(view, env, context.ext.get())
581            }
582        }
583    }
584
585    /// Accepts `evm`'s state, environment and network extension state into the active context. A
586    /// fork keeps its own chain ID.
587    ///
588    /// Call this between transactions, with an EVM created by [`Self::create_evm`] whose
589    /// executions were committed. In-flight state that was not committed is discarded, and a
590    /// deferred environment change is applied first.
591    pub fn park(&mut self, evm: Evm<'_, F::Types>) {
592        self.accept(evm, true);
593    }
594
595    /// Like [`Self::park`], for an EVM whose executions were not committed, such as a call's: its
596    /// pending writes are discarded, but the accepted state it carries, such as after a fork
597    /// switch, is kept.
598    pub(crate) fn park_detached(&mut self, evm: Evm<'_, F::Types>) {
599        self.accept(evm, false);
600    }
601
602    /// Accepts `evm`'s state, environment and network extension state into the active context.
603    ///
604    /// An EVM that materialized its accepted state holds the context's whole accepted state, which
605    /// replaces the context's. One that still reads it through a shared view only holds what its
606    /// executions read and, if `committed`, wrote, which is merged into the context's; without
607    /// committed writes it only caches reads, so it is dropped rather than copying the shared
608    /// accepted state.
609    fn accept(&mut self, mut evm: Evm<'_, F::Types>, committed: bool) {
610        self.begin_transaction(&mut evm);
611        evm.state_mut().clear_transaction_state();
612        let is_view = AcceptedView::is(evm.database());
613        let local = mem::take(&mut evm.state_mut().overlay_db_mut().cache);
614        let env = evm_env(&evm);
615        let mut ext = evm.ext().clone();
616        // Permission to replay protocol history belongs to one transaction, not to the context.
617        ext.set_protocol_replay(false);
618        // Release the EVM's handle on the accepted state before updating it in place.
619        drop(evm);
620        let context = self.active_mut();
621        match (is_view, &mut context.cache) {
622            (true, Some(accepted)) => {
623                if committed {
624                    Arc::make_mut(accepted).merge(local);
625                }
626            }
627            _ => context.cache = Some(Arc::new(local)),
628        }
629        context.ext = StoredExt::new(&ext);
630        // Inactive contexts keep what they loaded and created until they finish a transaction
631        // themselves, and the local context keeps seeding forks.
632        context.loaded.clear();
633        context.created.clear();
634        self.store_env(env);
635    }
636
637    /// Materializes the accepted state `evm` reads through a shared view into its own overlay.
638    ///
639    /// Operations that capture or replace the running state call this first; it copies the
640    /// accepted state once per execution.
641    pub fn materialize(&self, evm: &mut Evm<'_, F::Types>) {
642        if !AcceptedView::is(evm.database()) {
643            return;
644        }
645        let context = self.active();
646        let mut cache = context.cache.as_deref().cloned().unwrap_or_default();
647        // Replace only the overlay's cache and backing database: `Evm::set_database` would also
648        // clear the overlay and the in-flight transaction state.
649        let overlay = evm.state_mut().overlay_db_mut();
650        cache.merge(mem::take(&mut overlay.cache));
651        overlay.cache = cache;
652        overlay.db = Box::new(context.db.clone_backing());
653        self.sync_database_policy(evm);
654    }
655
656    /// Registers a fork without selecting it and returns its local fork ID.
657    pub fn create_fork(
658        &mut self,
659        info: ForkInfo,
660        db: impl BackingDb,
661        env: EvmEnv<F::Types>,
662    ) -> U256 {
663        let ext = self.factory.configure_for(&db, &env).evm_ext(&env);
664        let mut context = Parked::new(Box::new(db), env, ext);
665        context.inherit_local(&self.forks.local);
666        self.forks.insert(info, context)
667    }
668
669    /// Makes `id` the running context, or the local context for `None`.
670    ///
671    /// Persistent accounts carry their accepted state into the target. Leaving the local context
672    /// makes what the running transaction loaded and created there the initial state of every
673    /// fork.
674    pub fn select_fork(
675        &mut self,
676        evm: &mut Evm<'_, F::Types>,
677        id: Option<U256>,
678        phase: ExecutionPhase,
679    ) -> eyre::Result<()> {
680        if self.forks.context(id).is_none() {
681            eyre::bail!("fork {} does not exist", id.unwrap_or_default());
682        }
683        if id == self.forks.active() {
684            return Ok(());
685        }
686        let suspended = self.suspend(evm);
687        if self.forks.active.is_none() {
688            let ForkRegistry { local, forks, .. } = &mut self.forks;
689            for entry in forks.values_mut() {
690                entry.context.inherit_local(local);
691            }
692        }
693        self.forks.active = id;
694        self.resume(evm, suspended, false, phase);
695        Ok(())
696    }
697
698    /// Makes `id` the active context, or the local context for `None`, without suspending the
699    /// running state: for a throwaway copy of the lifecycle whose transaction already runs over
700    /// `id`'s state, such as one prepared with [`Self::prepare_on_inactive`].
701    pub const fn activate_detached(&mut self, id: Option<U256>) {
702        self.forks.active = id;
703    }
704
705    /// Moves fork `id`, or the running context for `None`, onto a new backing database and
706    /// environment, such as a later block.
707    ///
708    /// The fork starts over from the initial fork state, keeping persistent accounts and accounts
709    /// created on the fork. Rolling the running context also keeps other loaded accounts, but
710    /// reloads only their info from the new database, discarding their pre-roll storage slots.
711    ///
712    /// With `cache`, the fork resumes with it as its accepted state, such as state replayed up to a
713    /// transaction.
714    pub fn roll_fork(
715        &mut self,
716        evm: &mut Evm<'_, F::Types>,
717        id: Option<U256>,
718        db: impl BackingDb,
719        env: EvmEnv<F::Types>,
720        cache: Option<Cache>,
721        phase: ExecutionPhase,
722    ) -> eyre::Result<()> {
723        let active = self.forks.active();
724        let id = id.or(active);
725        if id != active {
726            return self.replace_inactive(id, db, env, cache);
727        }
728        let ext = self.factory.configure_for(&db, &env).evm_ext(&env);
729        let mut suspended = self.suspend(evm);
730        for (address, slots) in &mut suspended.loaded {
731            if !suspended.created.contains(address) && !self.forks.is_persistent(address) {
732                slots.clear();
733            }
734        }
735        let mut context = Parked::new(Box::new(db), env, ext);
736        context.cache = cache.map(Arc::new);
737        context.inherit_local(&self.forks.local);
738        *self.active_mut() = context;
739        self.resume(evm, suspended, true, phase);
740        Ok(())
741    }
742
743    /// Moves the inactive fork `id`, or the local context for `None`, onto a new backing database
744    /// and environment, optionally with `cache` as its accepted state.
745    ///
746    /// The fork's accepted state is discarded except for persistent accounts and accounts created
747    /// on it, and the fork starts over from the initial fork state.
748    pub fn replace_inactive(
749        &mut self,
750        id: Option<U256>,
751        db: impl BackingDb,
752        env: EvmEnv<F::Types>,
753        cache: Option<Cache>,
754    ) -> eyre::Result<()> {
755        eyre::ensure!(id != self.forks.active(), "fork {} is active", id.unwrap_or_default());
756        let Some(previous) = self.forks.context(id) else {
757            eyre::bail!("fork {} does not exist", id.unwrap_or_default());
758        };
759        let ext = self.factory.configure_for(&db, &env).evm_ext(&env);
760        let mut context = Parked::new(Box::new(db), env, ext);
761        if let Some(mut cache) = cache {
762            if let Some(previous_cache) = &previous.cache {
763                self.forks.merge_persistent(previous_cache, &mut cache);
764                self.forks.merge_persistent_loaded(&previous.loaded, &mut context.loaded);
765            }
766            context.cache = Some(Arc::new(cache));
767        }
768        if id.is_some() {
769            context.inherit_local(&self.forks.local);
770        }
771        if let Some(previous_cache) = &previous.cache {
772            let loaded = previous
773                .loaded
774                .iter()
775                .filter(|(address, _)| previous.created.contains(*address))
776                .map(|(address, slots)| (*address, slots.clone()))
777                .collect();
778            context.inherit(&loaded, &previous.created, previous_cache);
779        }
780        *self.forks.context_mut(id).expect("context exists") = context;
781        Ok(())
782    }
783
784    /// Returns the environment change deferred by an in-flight operation, applied at the next
785    /// transaction.
786    pub const fn pending_env(&self) -> Option<&EvmEnv<F::Types>> {
787        self.pending_env.as_ref()
788    }
789
790    /// Returns the base warm set of the running transaction if a fork switch carried warmth into
791    /// its warm set, which cooling the transaction's state must restore.
792    pub const fn tx_prewarm(&self) -> Option<&PrewarmSet> {
793        self.tx_prewarm.as_ref()
794    }
795
796    /// Removes `address` from the running transaction's base warmth in `state` and in the
797    /// warmth that fork switches and isolated static calls restore, so it stays cold until it is
798    /// accessed again.
799    pub fn remove_prewarm(&mut self, state: &mut State<'_>, address: &Address) {
800        state.prewarm_set_mut().remove(address);
801        if let Some(prewarm) = &mut self.tx_prewarm {
802            prewarm.remove(address);
803        }
804        // Fork switches carry the state of persistent accounts but not their warmth, so a
805        // persistent account resumes cold in every context.
806        if self.forks.is_persistent(address) {
807            self.forks.local.warm.remove(address);
808            for entry in self.forks.forks.values_mut() {
809                entry.context.warm.remove(address);
810            }
811        } else {
812            self.active_mut().warm.remove(address);
813        }
814    }
815
816    /// Returns whether [`Self::remove_prewarm`] would change the lifecycle, not only `state`.
817    pub fn tracks_prewarm(&self, address: &Address) -> bool {
818        self.tx_prewarm.as_ref().is_some_and(|prewarm| prewarm.is_warm(address))
819            || iter::once(&self.forks.local)
820                .chain(self.forks.forks.values().map(|entry| &entry.context))
821                .any(|context| context.warm.contains_key(address))
822    }
823
824    /// Returns whether any context keeps warmth of a persistent account for the running
825    /// transaction, which [`Self::take_persistent_warmth`] would take.
826    pub fn has_persistent_warmth(&self) -> bool {
827        let ForkRegistry { local, forks, persistent, .. } = &self.forks;
828        iter::once(local)
829            .chain(forks.values().map(|entry| &entry.context))
830            .any(|context| context.warm.keys().any(|address| persistent.contains(address)))
831    }
832
833    /// Takes the warmth of persistent accounts that contexts kept for the running transaction, so
834    /// that a nested transaction, such as an isolated call, resumes them cold in every context.
835    /// Hand it back with [`Self::restore_persistent_warmth`] when the
836    /// nested transaction ends.
837    pub fn take_persistent_warmth(&mut self) -> Vec<(Option<U256>, AddressMap<HashSet<U256>>)> {
838        let ForkRegistry { local, forks, persistent, .. } = &mut self.forks;
839        let forks = forks.iter_mut().map(|(id, entry)| (Some(*id), &mut entry.context));
840        iter::once((None, local))
841            .chain(forks)
842            .map(|(id, context)| {
843                let (taken, kept) = mem::take(&mut context.warm)
844                    .into_iter()
845                    .partition::<AddressMap<_>, _>(|(address, _)| persistent.contains(address));
846                context.warm = kept;
847                (id, taken)
848            })
849            .collect()
850    }
851
852    /// Hands persistent warmth taken with [`Self::take_persistent_warmth`] back to its contexts.
853    pub fn restore_persistent_warmth(
854        &mut self,
855        warmth: Vec<(Option<U256>, AddressMap<HashSet<U256>>)>,
856    ) {
857        for (id, warm) in warmth {
858            if let Some(context) = self.forks.context_mut(id) {
859                for (address, slots) in warm {
860                    context.warm.entry(address).or_default().extend(slots);
861                }
862            }
863        }
864    }
865
866    /// Applies an environment change deferred by an in-flight operation and forgets the warmth
867    /// contexts kept from the previous transaction. Call before every transaction.
868    pub fn begin_transaction(&mut self, evm: &mut Evm<'_, F::Types>) {
869        self.tx_prewarm = None;
870        self.tx_original.clear();
871        self.forks.local.warm.clear();
872        self.forks.local.originals.clear();
873        self.forks.local.switched.clear();
874        self.forks.local.transient.clear();
875        for entry in self.forks.forks.values_mut() {
876            entry.context.warm.clear();
877            entry.context.originals.clear();
878            entry.context.switched.clear();
879            entry.context.transient.clear();
880        }
881        if let Some(mut env) = self.pending_env.take() {
882            env.block = *evm.block();
883            let db = self.forks.active_db();
884            self.factory.configure_for(&db, &env).set_env(evm, env);
885            self.sync_database_policy(evm);
886        }
887    }
888
889    /// Switches `evm` to `env`. The block applies at once; a spec or chain ID change applies at
890    /// once between transactions and is deferred to the next transaction while one is in flight.
891    pub fn set_env(
892        &mut self,
893        evm: &mut Evm<'_, F::Types>,
894        env: EvmEnv<F::Types>,
895        phase: ExecutionPhase,
896    ) {
897        let db = self.forks.active_db();
898        let factory = self.factory.configure_for(&db, &env);
899        self.apply_env(&factory, evm, env, phase)
900    }
901
902    /// Captures the running context and every fork, and returns the snapshot ID.
903    pub fn snapshot(&mut self, evm: &mut Evm<'_, F::Types>) -> U256 {
904        self.materialize(evm);
905        // A deferred spec or chain ID change, such as `vm.chainId`, is part of the environment.
906        let env = self.pending_env.map_or_else(
907            || evm_env(evm),
908            |mut env| {
909                env.block = *evm.block();
910                env
911            },
912        );
913        self.snapshots.insert(LifecycleSnapshot {
914            state: evm.state().snapshot(),
915            forks: self.forks.clone(),
916            env,
917            ext: StoredExt::new(evm.ext()),
918        })
919    }
920
921    /// Restores snapshot `id` and returns the running state it replaced, or `None` if it does not
922    /// exist.
923    ///
924    /// Logs emitted since the snapshot are kept. Only the context that was active at the snapshot
925    /// gets its state back and becomes active again; other contexts, persistent
926    /// accounts and forks created after the snapshot are left as they are.
927    /// The replaced state is materialized, so that a failing frame can reinstate it over a backing
928    /// database with [`SnapshotRestores`](super::SnapshotRestores).
929    pub fn revert(
930        &mut self,
931        evm: &mut Evm<'_, F::Types>,
932        id: U256,
933        action: RevertStateSnapshotAction,
934        phase: ExecutionPhase,
935    ) -> Option<StateSnapshot> {
936        let snapshot = if action.is_keep() {
937            self.snapshots.get(id).cloned()
938        } else {
939            self.snapshots.remove_at(id)
940        }?;
941        self.materialize(evm);
942        let LifecycleSnapshot { state, mut forks, env, ext } = snapshot;
943        let (replaced, logs) = if forks.active == self.forks.active {
944            (None, evm.state().logs().to_vec())
945        } else {
946            // Other contexts are not part of the snapshot. The running context keeps what reached
947            // its state before the running transaction and drops the transaction's changes.
948            let replaced = evm.state().snapshot();
949            let state = evm.state_mut();
950            let logs = mem::take(state.logs_mut());
951            state.clear_transaction_state();
952            let mut cache = mem::take(&mut state.overlay_db_mut().cache);
953            // Values accepted at the switch into the context stay accepted, as before their
954            // originals were restored.
955            for (address, slots) in mem::take(&mut self.active_mut().switched) {
956                cache.storage.entry(address).or_default().slots.extend(slots);
957            }
958            self.active_mut().cache = Some(Arc::new(cache));
959            (Some(replaced), logs)
960        };
961        match forks.active {
962            None => self.forks.local = forks.local,
963            Some(id) => {
964                let entry = forks.forks.remove(&id).expect("snapshot's active fork exists");
965                self.forks.forks.insert(id, entry);
966            }
967        }
968        self.forks.active = forks.active;
969        let db = self.forks.active_db();
970        let mut state = state.into_state(db.clone_backing());
971        *state.logs_mut() = logs;
972        let running = mem::replace(evm.state_mut(), state);
973        let replaced = replaced.unwrap_or_else(|| running.snapshot());
974        evm.ext_mut().replace_while_executing(ext.into_inner());
975        let factory = self.factory.configure_for(&db, &env);
976        self.apply_env(&factory, evm, env, phase);
977        Some(replaced)
978    }
979
980    /// Deletes a snapshot, returning whether it existed.
981    pub fn delete_snapshot(&mut self, id: U256) -> bool {
982        self.snapshots.remove_at(id).is_some()
983    }
984
985    /// Deletes every snapshot.
986    pub fn delete_snapshots(&mut self) {
987        self.snapshots.clear();
988    }
989
990    /// Builds the EVM a nested transaction of the running one executes on: a copy of the running
991    /// transaction's current state, with `env` or the running environment, and `ext` or network
992    /// extension state derived from the running EVM for `tx`.
993    pub fn nested_evm<'a>(
994        &self,
995        evm: &mut Evm<'_, F::Types>,
996        tx: &Recovered<<F::Types as EvmTypesHost>::Tx>,
997        env: Option<EvmEnv<F::Types>>,
998        ext: Option<<F::Types as EvmTypesHost>::EvmExt>,
999    ) -> Evm<'a, F::Types> {
1000        self.materialize(evm);
1001        let db = self.forks.active_db();
1002        // Copy the running state without its journal, so each nested transaction is independent
1003        // of how much the enclosing one already did.
1004        let state = evm.state().committed_copy(db.clone_backing());
1005        let ext = ext.unwrap_or_else(|| {
1006            let mut ext = evm.ext().clone();
1007            ext.for_next_transaction(tx);
1008            ext
1009        });
1010        let env = env.unwrap_or_else(|| evm_env(evm));
1011        let mut executor = self.factory.configure_for(&db, &env).new_evm_with_ext(db, env, ext);
1012        *executor.state_mut() = state;
1013        self.sync_database_policy(&mut executor);
1014        executor
1015    }
1016
1017    /// Moves the transaction `evm` is running onto a separate frame EVM executing with `env`,
1018    /// such as for `deployCode` or an in-flight spec change.
1019    ///
1020    /// Execute messages on the returned EVM with [`Host::execute_message`] and hand its state back
1021    /// with [`Self::end_frame_evm`]; `evm` must not execute in between.
1022    ///
1023    /// # Safety
1024    ///
1025    /// The running state of `evm` moves into the returned EVM, whose lifetime `'a` the caller
1026    /// chooses. Every database in that state must outlive `'a`: it must be one the lifecycle
1027    /// installed, all of which are owned (`'static`), not a database borrowed by the caller.
1028    ///
1029    /// [`Host::execute_message`]: evm2::interpreter::Host::execute_message
1030    pub unsafe fn begin_frame_evm<'a>(
1031        &self,
1032        evm: &mut Evm<'_, F::Types>,
1033        env: EvmEnv<F::Types>,
1034    ) -> Evm<'a, F::Types> {
1035        let db = self.forks.active_db();
1036        let factory = self.factory.configure_for(&db, &env);
1037        let mut frame = factory.new_evm_with_ext(EmptyDB::default(), env, evm.ext().clone());
1038        let state = mem::replace(evm.state_mut(), State::new(EmptyDB::default()));
1039        // SAFETY: `State`'s lifetime only bounds its databases, which the caller guarantees
1040        // outlive `'a`.
1041        *frame.state_mut() = unsafe { mem::transmute::<State<'_>, State<'a>>(state) };
1042        *frame.tx_env_mut() = mem::take(evm.tx_env_mut());
1043        self.sync_database_policy(&mut frame);
1044        frame
1045    }
1046
1047    /// Hands the state, transaction environment, block and network extension state of a frame EVM
1048    /// created with
1049    /// [`Self::begin_frame_evm`] back to `evm`, restoring `evm`'s empty-account policy on the
1050    /// active backing database.
1051    ///
1052    /// # Safety
1053    ///
1054    /// The running state of `frame` moves into `evm`. Every database in that state must outlive
1055    /// `evm`: it must be one the lifecycle installed, as for [`Self::begin_frame_evm`].
1056    pub unsafe fn end_frame_evm(&self, evm: &mut Evm<'_, F::Types>, mut frame: Evm<'_, F::Types>) {
1057        frame.clear_inspector();
1058        let state = mem::replace(frame.state_mut(), State::new(EmptyDB::default()));
1059        // SAFETY: `State`'s lifetime only bounds its databases, which the caller guarantees
1060        // outlive `evm`.
1061        *evm.state_mut() = unsafe { mem::transmute::<State<'_>, State<'_>>(state) };
1062        *evm.tx_env_mut() = mem::take(frame.tx_env_mut());
1063        *evm.ext_mut() = frame.ext().clone();
1064        evm.set_block(*frame.block());
1065        self.sync_database_policy(evm);
1066    }
1067
1068    /// Prepares `tx` to execute as a nested transaction of the running one on the EVM
1069    /// [`Self::nested_evm`] builds.
1070    pub fn prepare_nested(
1071        &self,
1072        evm: &mut Evm<'_, F::Types>,
1073        tx: Recovered<<F::Types as EvmTypesHost>::Tx>,
1074        env: Option<EvmEnv<F::Types>>,
1075        ext: Option<<F::Types as EvmTypesHost>::EvmExt>,
1076    ) -> PreparedTx<F::Types> {
1077        PreparedTx {
1078            executor: self.nested_evm(evm, &tx, env, ext),
1079            tx,
1080            inactive: None,
1081            cursor: None,
1082            access_list: None,
1083        }
1084    }
1085
1086    /// Prepares `tx` to execute on the inactive fork `id`, or the local context for `None`, and
1087    /// be accepted there, such as for `vm.transact` on another fork.
1088    ///
1089    /// Persistent accounts carry the running transaction's state into the fork, and the
1090    /// transaction's changes to them are merged back into the running transaction as journaled
1091    /// writes. The running transaction's other loaded accounts then take the fork's resulting
1092    /// state, see [`Self::rebase_onto_inactive`].
1093    pub fn prepare_on_inactive(
1094        &self,
1095        evm: &mut Evm<'_, F::Types>,
1096        id: Option<U256>,
1097        tx: Recovered<<F::Types as EvmTypesHost>::Tx>,
1098        env: Option<EvmEnv<F::Types>>,
1099        ext: Option<<F::Types as EvmTypesHost>::EvmExt>,
1100    ) -> eyre::Result<PreparedTx<F::Types>> {
1101        eyre::ensure!(id != self.forks.active(), "fork {} is active", id.unwrap_or_default());
1102        let Some(context) = self.forks.context(id) else {
1103            eyre::bail!("fork {} does not exist", id.unwrap_or_default());
1104        };
1105        let db = context.db.clone_backing();
1106        let env = env.unwrap_or(context.env);
1107        let ext = ext.unwrap_or_else(|| {
1108            let mut ext = context.ext.get();
1109            ext.for_next_transaction(&tx);
1110            ext
1111        });
1112        let factory = self.factory.configure_for(&db, &env);
1113        // A context that never ran gets its network genesis before the transaction.
1114        let is_forked = db.is_forked_mode();
1115        let mut executor = factory.new_evm_with_ext(db, env, ext);
1116        if let Some(cache) = &context.cache {
1117            executor.state_mut().overlay_db_mut().cache = Cache::clone(cache);
1118        }
1119        if context.cache.is_none() || context.needs_init {
1120            factory.initialize_evm(&mut executor, is_forked);
1121        }
1122
1123        // Carry the running transaction's accepted and in-flight persistent accounts over.
1124        self.materialize(evm);
1125        let mut running = evm.state().snapshot().into_state(self.forks.active_db());
1126        running.commit_transaction();
1127        self.forks.merge_persistent(
1128            &running.overlay_db().cache,
1129            &mut executor.state_mut().overlay_db_mut().cache,
1130        );
1131        let inactive = Some((id, self.forks.persistent.clone()));
1132        Ok(PreparedTx { executor, tx, inactive, cursor: None, access_list: None })
1133    }
1134
1135    /// Stores the outcome of a [`PreparedTx`]: an inactive context's new accepted state.
1136    pub fn store_executed(&mut self, executed: ExecutedNested<F::Types>) -> TxResult<F::Types> {
1137        let ExecutedNested { result, context, .. } = executed;
1138        if let Some((id, cache)) = context {
1139            let context = self.forks.context_mut(id).expect("prepared context exists");
1140            context.cache = Some(Arc::new(cache));
1141        }
1142        result
1143    }
1144
1145    /// Replaces the accounts the running transaction of `evm` loaded, except persistent ones,
1146    /// with their accepted state on the inactive fork `id`, or the local context for `None`, as
1147    /// journaled writes, such as after replaying transactions there.
1148    pub fn rebase_onto_inactive(
1149        &self,
1150        evm: &mut Evm<'_, F::Types>,
1151        id: Option<U256>,
1152    ) -> eyre::Result<()> {
1153        eyre::ensure!(id != self.forks.active(), "fork {} is active", id.unwrap_or_default());
1154        let Some(context) = self.forks.context(id) else {
1155            eyre::bail!("fork {} does not exist", id.unwrap_or_default());
1156        };
1157        let db = context.db.clone_backing();
1158        db.set_eip161(context.env.version.feature(EvmFeatures::EIP161));
1159        let mut source = State::new(db);
1160        if let Some(cache) = &context.cache {
1161            source.overlay_db_mut().cache = Cache::clone(cache);
1162        }
1163        rebase_loaded_accounts(evm.state_mut(), &mut source, &self.forks.persistent)?;
1164        Ok(())
1165    }
1166
1167    /// Accepts the running state and stores it, with the running environment, in the active
1168    /// context. A fork keeps its own chain ID. Returns what the running transaction carries into
1169    /// the next context.
1170    fn suspend(&mut self, evm: &mut Evm<'_, F::Types>) -> Suspended {
1171        // Fold the running transaction's execution so far into its network state before the
1172        // state is replaced.
1173        F::Types::sync_transaction(evm);
1174        let loaded_persistent = evm
1175            .state()
1176            .loaded_accounts()
1177            .map(|(address, _)| *address)
1178            .filter(|address| self.forks.is_persistent(address))
1179            .collect::<Vec<_>>();
1180        for address in loaded_persistent {
1181            if let Entry::Vacant(entry) = self.tx_original.entry(address) {
1182                // Read the accepted info without caching it, which would carry it into the next
1183                // context.
1184                let db = evm.overlay_db_mut();
1185                let info = match db.cache.accounts.get(&address) {
1186                    Some(info) => info.clone(),
1187                    None => db.db.get_account(&address).ok().flatten(),
1188                };
1189                entry.insert(info);
1190            }
1191        }
1192        let state = evm.state_mut();
1193        let loaded = loaded_slots(state);
1194        let mut warm = warm_accounts(state);
1195        let cold_slots = cold_account_warm_slots(state, &self.forks.persistent);
1196        let transient = take_transient(state);
1197        let context = self.active_mut();
1198        context.transient = transient;
1199        for (address, slots) in loaded {
1200            if state.account(&address).is_ok_and(|account| account.is_created()) {
1201                context.created.insert(address);
1202            }
1203            // Committing the running transaction below makes the slots' current values their
1204            // originals, so record the transaction-start ones SSTORE gas and refunds depend on.
1205            for key in &slots {
1206                if let Ok(slot) = state.storage_slot(&address, *key)
1207                    && slot.original() != slot.current()
1208                {
1209                    context.originals.entry(address).or_default().insert(*key, slot.original());
1210                }
1211            }
1212            context.loaded.entry(address).or_default().extend(slots);
1213        }
1214        // The running state holds the warmth the context resumed with in its prewarm set rather
1215        // than in loaded accounts. The context keeps it, and the next context carries what is
1216        // still warm of it, even if this visit did not touch it, but not what was cooled since,
1217        // such as by an isolated static call.
1218        let prewarm = state.prewarm_set();
1219        for (address, slots) in &context.warm {
1220            if prewarm.is_warm(address) {
1221                let slots = slots.iter().filter(|key| prewarm.is_storage_warm(address, key));
1222                warm.entry(*address).or_default().extend(slots);
1223            }
1224        }
1225        for (address, slots) in &warm {
1226            context.warm.entry(*address).or_default().extend(slots);
1227        }
1228        let is_view = AcceptedView::is(evm.database());
1229        let backing = self.active().db.clone_backing();
1230        let state = evm.state_mut();
1231        state.commit_transaction();
1232        let logs = mem::take(state.logs_mut());
1233        let prewarm = self.tx_prewarm.get_or_insert_with(|| state.prewarm_set().clone()).clone();
1234        // `resume` replaces the running state, so its committed overlay moves into the context's
1235        // accepted state and is shared with what the transaction carries over instead of being
1236        // copied. Dropping the EVM's view first leaves the context the only owner of a shared
1237        // accepted state, which is then updated in place.
1238        let overlay = state.overlay_db_mut();
1239        let local = mem::take(&mut overlay.cache);
1240        overlay.db = Box::new(backing);
1241        self.store_env(evm_env(evm));
1242        let ext = evm.ext().clone();
1243        let context = self.active_mut();
1244        let cache = match (is_view, context.cache.take()) {
1245            (true, Some(mut accepted)) => {
1246                Arc::make_mut(&mut accepted).merge(local);
1247                accepted
1248            }
1249            _ => Arc::new(local),
1250        };
1251        context.cache = Some(Arc::clone(&cache));
1252        context.switched.clear();
1253        context.ext = StoredExt::new(&ext);
1254        Suspended {
1255            cache,
1256            loaded: context.loaded.clone(),
1257            created: context.created.clone(),
1258            originals: context.originals.clone(),
1259            logs,
1260            prewarm,
1261            warm,
1262            cold_slots,
1263        }
1264    }
1265
1266    /// Installs the active context into `evm`, carrying persistent accounts, logs and base warmth
1267    /// over from the suspended context. With `carry`, the loaded and created accounts of the
1268    /// suspended context are carried over as well.
1269    fn resume(
1270        &mut self,
1271        evm: &mut Evm<'_, F::Types>,
1272        suspended: Suspended,
1273        carry: bool,
1274        phase: ExecutionPhase,
1275    ) {
1276        let Suspended {
1277            cache: source,
1278            loaded: source_loaded,
1279            created: source_created,
1280            originals: source_originals,
1281            logs,
1282            mut prewarm,
1283            warm: source_warm,
1284            cold_slots: source_cold_slots,
1285        } = suspended;
1286        if carry {
1287            self.active_mut().inherit(&source_loaded, &source_created, &source);
1288        }
1289        let context = self.active_mut();
1290        let fresh = mem::take(&mut context.needs_init) || context.cache.is_none();
1291        // The running EVM owns the active context's accepted state.
1292        let mut cache = context.cache.take().map(Arc::unwrap_or_clone).unwrap_or_default();
1293        let mut loaded = mem::take(&mut context.loaded);
1294        let db = context.db.clone_backing();
1295        let env = context.env;
1296        let ext = context.ext.get();
1297        self.forks.merge_persistent(&source, &mut cache);
1298        self.forks.merge_persistent_loaded(&source_loaded, &mut loaded);
1299        let persistent_created = source_created
1300            .into_iter()
1301            .filter(|address| self.forks.is_persistent(address))
1302            .collect::<Vec<_>>();
1303        let persistent = self.forks.persistent.clone();
1304        let context = self.active_mut();
1305        context.loaded = loaded;
1306        context.created.retain(|address| {
1307            !persistent.contains(address) || !source.accounts.contains_key(address)
1308        });
1309        context.created.extend(persistent_created);
1310        let created = context.created.clone();
1311        // A selected context resumes with its own warmth from this
1312        // transaction, and a rolled one warms every account the running transaction loaded, with
1313        // slots for created and persistent accounts. Persistent accounts keep their warmth.
1314        let mut warm = mem::take(&mut context.warm);
1315        if carry {
1316            for (address, slots) in &source_loaded {
1317                warm.entry(*address).or_default().extend(slots);
1318            }
1319        }
1320        self.switch_slots.clear();
1321        for address in &persistent {
1322            if let Some(slots) = source_warm.get(address) {
1323                warm.entry(*address).or_default().extend(slots);
1324                self.switch_slots.insert(*address, slots.clone());
1325            }
1326        }
1327        for (address, slots) in &warm {
1328            prewarm.warm_storage(address, slots.iter().copied());
1329        }
1330        self.active_mut().warm = warm;
1331        // Persistent and carried accounts keep the originals they suspended with, other accounts
1332        // the ones of their previous visit to this context. Records this context kept for
1333        // persistent accounts can predate the running transaction's baseline, such as that of an
1334        // isolated call, so the suspended context's records replace them.
1335        let mut originals = mem::take(&mut self.active_mut().originals);
1336        originals.retain(|address, _| !persistent.contains(address));
1337        for (address, slots) in source_originals {
1338            if persistent.contains(&address) || (carry && created.contains(&address)) {
1339                originals.entry(address).or_default().extend(slots);
1340            }
1341        }
1342
1343        let mut state = State::new(db.clone_backing());
1344        state.overlay_db_mut().cache = cache;
1345        *state.logs_mut() = logs;
1346        *state.prewarm_set_mut() = prewarm;
1347        *evm.state_mut() = state;
1348        // Before anything else journals, so a revert to a checkpoint taken before the switch keeps
1349        // as much of it as possible.
1350        put_transient(evm.state_mut(), mem::take(&mut self.active_mut().transient));
1351        evm.ext_mut().resume_context(ext);
1352
1353        let factory = self.factory.configure_for(&db, &env);
1354        self.apply_env(&factory, evm, env, phase);
1355        evm.warm_precompiles();
1356        if fresh {
1357            factory.initialize_evm(evm, db.is_forked_mode());
1358        }
1359        // After the network initialization, which can commit the overlay.
1360        self.active_mut().switched = restore_originals(evm.state_mut(), &originals);
1361        // The new transaction overlay does not know which accounts the transaction created, which
1362        // EIP-6780 `SELFDESTRUCT` depends on. Its database already holds their storage.
1363        for address in &created {
1364            if let Ok(mut account) = evm.state_mut().account(address)
1365                && account.exists()
1366            {
1367                account.mark_created();
1368            }
1369        }
1370        // Persistent slots warm while their account is cold, such as the test contract's after an
1371        // isolated static call cooled it, stay warm without warming the account, which the
1372        // prewarm set cannot express. Only slots this context caches, including the implicit zeros
1373        // of wiped storage, are loaded to warm them, so the switch reads nothing from the fork.
1374        let state = evm.state_mut();
1375        for (address, slots) in source_cold_slots {
1376            for key in slots {
1377                let cache = &state.overlay_db().cache;
1378                let cached = cache.accounts.contains_key(&address)
1379                    && cache
1380                        .storage
1381                        .get(&address)
1382                        .is_some_and(|storage| storage.wiped || storage.slots.contains_key(&key));
1383                if cached && state.storage_slot(&address, key).is_ok() {
1384                    state.set_storage_warm(&address, key, true);
1385                }
1386            }
1387        }
1388        F::Types::refresh_switched_transaction(evm, &self.tx_original);
1389    }
1390
1391    /// Applies `env`, deferring a spec or chain ID change while a transaction is in flight.
1392    fn apply_env(
1393        &mut self,
1394        factory: &F,
1395        evm: &mut Evm<'_, F::Types>,
1396        env: EvmEnv<F::Types>,
1397        phase: ExecutionPhase,
1398    ) {
1399        let current = evm_env(evm);
1400        self.sync_database_policy(evm);
1401        if current.spec == env.spec && current.chain_id() == env.chain_id() {
1402            evm.set_block(env.block);
1403            // `evm` can be a frame EVM that already runs the pending environment while the frames
1404            // it suspended do not, so the request stays pending for them.
1405            self.pending_env = match phase {
1406                ExecutionPhase::InFlight if self.pending_env.is_some() => Some(env),
1407                _ => None,
1408            };
1409            return;
1410        }
1411        match phase {
1412            ExecutionPhase::Boundary => {
1413                factory.set_env(evm, env);
1414                self.sync_database_policy(evm);
1415                self.pending_env = None;
1416            }
1417            ExecutionPhase::InFlight => {
1418                evm.set_block(env.block);
1419                self.pending_env = Some(env);
1420            }
1421        }
1422    }
1423
1424    /// Stores `env` as the active context's environment.
1425    ///
1426    /// A fork keeps the chain ID it was created or rolled with: a running change such as
1427    /// `vm.chainId` does not follow the fork to its next selection. The executor carries such a
1428    /// change to its next transaction instead.
1429    fn store_env(&mut self, mut env: EvmEnv<F::Types>) {
1430        let is_fork = self.forks.active().is_some();
1431        let context = self.active_mut();
1432        if is_fork {
1433            env.set_chain_id(context.env.chain_id());
1434        }
1435        context.env = env;
1436    }
1437
1438    /// Returns the warm slots of persistent accounts the last fork switch carried into the next
1439    /// context.
1440    pub const fn switch_slots(&self) -> &AddressMap<HashSet<U256>> {
1441        &self.switch_slots
1442    }
1443
1444    /// Returns the accounts loaded in the running transaction, including accounts loaded as
1445    /// absent and accounts loaded before fork switches, with their loaded slots.
1446    ///
1447    /// Accepted state the running transaction did not load is not included.
1448    pub fn loaded_state(&self, state: &State<'_>) -> AddressMap<HashSet<U256>> {
1449        let mut loaded = self.active().loaded.clone();
1450        for (address, slots) in state.loaded_accounts() {
1451            loaded.entry(*address).or_default().extend(slots);
1452        }
1453        loaded
1454    }
1455
1456    /// Returns the slots of `address` loaded in the running transaction, including before fork
1457    /// switches.
1458    pub fn loaded_storage(&self, state: &State<'_>, address: &Address) -> Vec<U256> {
1459        let mut slots =
1460            self.active().loaded.get(address).into_iter().flatten().copied().collect::<Vec<_>>();
1461        if let Some((_, loaded)) = state.loaded_accounts().find(|(loaded, _)| *loaded == address) {
1462            slots.extend(loaded);
1463        }
1464        slots.sort_unstable();
1465        slots.dedup();
1466        slots
1467    }
1468
1469    /// Returns storage keys retained from earlier context visits, attributed to their forks.
1470    /// These can be absent from the final pending state when an unchanged slot was read before
1471    /// a fork switch. Collect them before parking clears the active context's loaded keys.
1472    pub fn suspended_storage(&self) -> impl Iterator<Item = (Option<U256>, Address, U256)> + '_ {
1473        iter::once((None, &self.forks.local))
1474            .chain(self.forks.iter().map(|(id, entry)| (Some(id), &entry.context)))
1475            .flat_map(|(fork, context)| {
1476                context.loaded.iter().flat_map(move |(address, slots)| {
1477                    slots.iter().map(move |slot| (fork, *address, *slot))
1478                })
1479            })
1480    }
1481
1482    /// Rebinds the running state's backing handle to its EVM's empty-account policy without
1483    /// copying accepted state or changing another execution's policy.
1484    pub fn sync_database_policy(&self, evm: &mut Evm<'_, F::Types>) {
1485        let db = self.forks.active_db();
1486        db.set_eip161(evm.version().feature(EvmFeatures::EIP161));
1487        let overlay = evm.state_mut().overlay_db_mut();
1488        overlay.db = if AcceptedView::is(&*overlay.db) {
1489            Box::new(AcceptedView {
1490                cache: Arc::clone(self.active().cache.as_ref().expect("accepted view has a cache")),
1491                backing: db,
1492            })
1493        } else {
1494            Box::new(db)
1495        };
1496    }
1497}
1498
1499/// What a running transaction carries from a suspended context into the next one.
1500struct Suspended {
1501    /// The suspended context's accepted state, the source of persistent and carried accounts.
1502    cache: Arc<Cache>,
1503    /// Accounts and slots loaded in the suspended context.
1504    loaded: AddressMap<HashSet<U256>>,
1505    /// Accounts created in the suspended context.
1506    created: AddressSet,
1507    /// Transaction-start values of the slots changed in the suspended context.
1508    originals: AddressMap<HashMap<U256, U256>>,
1509    /// Logs of the running transaction.
1510    logs: Vec<Log>,
1511    /// Base warmth of the running transaction, such as its access list, without warmth carried
1512    /// by fork switches.
1513    prewarm: PrewarmSet,
1514    /// Accounts and slots warm in the running transaction.
1515    warm: AddressMap<HashSet<U256>>,
1516    /// Warm slots of persistent accounts the running transaction holds cold.
1517    cold_slots: AddressMap<HashSet<U256>>,
1518}
1519
1520/// Clears `evm`'s inspector and returns the EVM without the borrows the inspector held, such as
1521/// to park an EVM whose inspector borrowed the lifecycle's owner.
1522///
1523/// # Safety
1524///
1525/// An EVM's lifetime bounds its inspector, which is cleared, and its databases and precompiles.
1526/// Those must outlive `'b`, the lifetime the caller chooses: they must be ones Foundry's
1527/// factories and [`ExecutionLifecycle`] installed, all of which are owned (`'static`).
1528pub unsafe fn release_inspector<'b, T: EvmTypes>(mut evm: Evm<'_, T>) -> Evm<'b, T> {
1529    evm.clear_inspector();
1530    let evm = mem::ManuallyDrop::new(evm);
1531    // SAFETY: The inspector is cleared and the caller guarantees the databases and precompiles
1532    // outlive `'b`. The value is moved out exactly once and the original is never dropped.
1533    unsafe { std::ptr::read((&raw const *evm).cast::<Evm<'b, T>>()) }
1534}
1535
1536/// Applies a nested transaction's changes to the running transaction's `state` as journaled
1537/// writes and returns them as [`PersistentWrite`]s, for the caller to replay when an enclosing
1538/// call reverts, such as for `broadcastRawTransaction`.
1539///
1540/// Also returns the changes accepted into `state` instead, which no revert undoes, for the caller
1541/// to replay only when it discards the running state.
1542pub fn merge_untracked_nested_changes<T: EvmTypesHost>(
1543    state: &mut State<'_>,
1544    executed: &ExecutedTx<'_, '_, T>,
1545) -> DbResult<(Vec<PersistentWrite>, Vec<PersistentWrite>)> {
1546    // Accounts and slots the running transaction has not loaded start from the nested
1547    // transaction's writes.
1548    let unloaded = unloaded_changes(state, executed.account_changes());
1549    state.commit_source(&unloaded);
1550    let mut accepted = Vec::new();
1551    for change in unloaded.account_changes() {
1552        let address = change.address;
1553        let (balance, nonce) =
1554            change.original.map_or((U256::ZERO, 0), |info| (info.balance, info.nonce));
1555        if let Some(current) = change.current {
1556            if current.balance != balance {
1557                accepted.push(PersistentWrite::balance(address, balance, current.balance));
1558            }
1559            if current.nonce != nonce {
1560                accepted.push(PersistentWrite::Nonce {
1561                    address,
1562                    delta: i128::from(current.nonce) - i128::from(nonce),
1563                    nonce: current.nonce,
1564                    created: false,
1565                    replay: Replay::Delta,
1566                });
1567            }
1568        }
1569        accepted.extend(
1570            change
1571                .storage
1572                .changed_slots()
1573                .map(|(key, slot)| PersistentWrite::Slot(address, *key, slot.current)),
1574        );
1575    }
1576    let mut persistent = Vec::new();
1577    merge_changes(state, executed.account_changes(), |_| true, Some(&mut persistent), None)?;
1578    Ok((persistent, accepted))
1579}
1580
1581/// Applies the changes of a nested transaction that `child` ran and detached into `pending` to the
1582/// running transaction's `state` like [`merge_untracked_nested_changes`], and also warms the
1583/// accounts and slots the nested transaction left warm, such as for `executeTransaction`.
1584///
1585/// Accounts the running transaction had already loaded keep their warmth, and accesses the nested
1586/// transaction reverted stay cold. Like the merged changes, the warmth survives reverts of the
1587/// enclosing calls.
1588///
1589/// Existing accounts the nested transaction self-destructed take the state of `destructed`, see
1590/// [`destructed_accounts`], and are only marked self-destructed. Without one, their balance is
1591/// emptied and the rest of their state is kept.
1592pub fn merge_untracked_pending_changes_with_warmth<T: EvmTypes>(
1593    state: &mut State<'_>,
1594    child: &mut Evm<'_, T>,
1595    pending: PendingState,
1596    destructed: AddressMap<DestructedAccount>,
1597) -> DbResult<Vec<PersistentWrite>> {
1598    // The detached accounts keep their warmth, which reattaching them to `child` exposes.
1599    let child = child.state_mut();
1600    child.set_pending_state(pending.clone());
1601    let warm = warm_accounts(child);
1602    child.clear_transaction_state();
1603    // Warm before merging, so that the merge journals the warmth as the accounts' previous one and
1604    // reverts of the enclosing calls restore it.
1605    let loaded = state.loaded_accounts().map(|(address, _)| *address).collect::<AddressSet>();
1606    for (address, slots) in warm {
1607        state.account(&address)?;
1608        if !loaded.contains(&address) {
1609            state.set_account_warm(&address, true);
1610        }
1611        for key in slots {
1612            state.storage_slot(&address, key)?;
1613            state.set_storage_warm(&address, key, true);
1614        }
1615    }
1616    let mut persistent = Vec::new();
1617    merge_pending_changes(
1618        state,
1619        &pending,
1620        destructed,
1621        |change| !change.created,
1622        Some(&mut persistent),
1623    )?;
1624    Ok(persistent)
1625}
1626
1627/// Applies the changes of a nested transaction detached into `pending` to the running
1628/// transaction's `state` as journaled writes, so they revert with the enclosing call.
1629///
1630/// An account the nested transaction self-destructed and `kept` selects keeps the state the
1631/// transaction left it in until the running transaction ends and destroys it: it takes the state of
1632/// `destructed`, see [`destructed_accounts`], and is only marked self-destructed. Without one, its
1633/// balance is emptied and the rest of its state is kept.
1634pub fn merge_pending_changes(
1635    state: &mut State<'_>,
1636    pending: &PendingState,
1637    mut destructed: AddressMap<DestructedAccount>,
1638    kept: impl Fn(&AccountChanges<'_>) -> bool,
1639    mut persistent: Option<&mut Vec<PersistentWrite>>,
1640) -> DbResult<()> {
1641    let destroyed = pending
1642        .account_changes()
1643        .filter(|change| change.selfdestructed && kept(change))
1644        .map(|change| (change.address, change.created))
1645        .collect::<AddressMap<_>>();
1646    let filter = |address: &Address| !destroyed.contains_key(address);
1647    // Its tracked merges, of isolated calls, go into the transaction's root frame, which no
1648    // revert outlives, so they need no storage reloads.
1649    merge_changes(state, pending.account_changes(), filter, persistent.as_deref_mut(), None)?;
1650    for (address, created) in destroyed {
1651        if let Some(DestructedAccount { info, code, slots }) = destructed.remove(&address) {
1652            let code = || Ok(code);
1653            apply_account(
1654                state,
1655                address,
1656                Some(&info),
1657                code,
1658                false,
1659                false,
1660                slots,
1661                persistent.as_deref_mut(),
1662            )?;
1663        } else {
1664            let balance = state.account(&address)?.balance();
1665            // Self-destruction empties the balance whatever it was, so a replay sets it.
1666            let write = PersistentWrite::balance(address, balance, U256::ZERO)
1667                .with_replay(Replay::Absolute);
1668            write.apply(state)?;
1669            if let Some(persistent) = persistent.as_deref_mut() {
1670                persistent.push(write);
1671            }
1672        }
1673        // An account the nested transaction created stays created, so that EIP-6780
1674        // `SELFDESTRUCT` in a later call of the running transaction still destroys it.
1675        if created {
1676            let mut account = state.account(&address)?;
1677            if !account.is_created() {
1678                account.mark_created();
1679            }
1680        }
1681        let write = PersistentWrite::Destruct(address);
1682        write.apply(state)?;
1683        if let Some(persistent) = persistent.as_deref_mut() {
1684            persistent.push(write);
1685        }
1686    }
1687    Ok(())
1688}
1689
1690/// Returns the warmth of the running transaction in `state`: its base warm set and the accounts and
1691/// slots it warmed, for a transaction that continues in a replaced state.
1692pub fn warm_set(state: &mut State<'_>) -> PrewarmSet {
1693    let mut prewarm = state.prewarm_set().clone();
1694    for (address, slots) in warm_accounts(state) {
1695        prewarm.warm_storage(&address, slots);
1696    }
1697    prewarm
1698}
1699
1700/// Undoes, without journaling, the warmth that the running transaction in `state` gained since
1701/// `checkpoint`, keeping all other warmth, including unjournaled changes made since.
1702pub fn restore_access_warmth(state: &mut State<'_>, checkpoint: &StateCheckpoint) {
1703    let mut accounts = AddressSet::default();
1704    let mut slots = Vec::new();
1705    // A callback that reverted to a snapshot or switched forks can leave a shorter journal.
1706    for entry in state.journal().get(checkpoint.journal_len()..).unwrap_or_default() {
1707        match entry {
1708            // Any account mutation journals an entry; only one taken while cold means it was
1709            // warmed since.
1710            JournalEntry::AccountChange { address, previous_flags, .. }
1711                if !previous_flags.contains(AccountFlags::WARM) =>
1712            {
1713                accounts.insert(*address);
1714            }
1715            JournalEntry::StorageWarmed { address, key } => slots.push((*address, *key)),
1716            _ => {}
1717        }
1718    }
1719    for address in accounts {
1720        state.set_account_warm(&address, false);
1721    }
1722    for (address, key) in slots {
1723        state.set_storage_warm(&address, key, false);
1724    }
1725}
1726
1727/// Returns the accounts the running transaction in `state` loaded and that are warm, with their
1728/// warm slots.
1729pub fn warm_accounts(state: &mut State<'_>) -> AddressMap<HashSet<U256>> {
1730    let loaded = loaded_slots(state);
1731    let mut warm = AddressMap::default();
1732    for (address, slots) in loaded {
1733        if !state.account(&address).is_ok_and(|account| account.is_warm()) {
1734            continue;
1735        }
1736        let slots = slots
1737            .into_iter()
1738            .filter(|key| state.storage_slot(&address, *key).is_ok_and(|slot| slot.is_warm()))
1739            .collect();
1740        warm.insert(address, slots);
1741    }
1742    warm
1743}
1744
1745/// Returns the warm slots of the `persistent` accounts the running transaction in `state` loaded
1746/// but holds cold, such as the test contract after an isolated static call cooled it.
1747fn cold_account_warm_slots(
1748    state: &mut State<'_>,
1749    persistent: &AddressSet,
1750) -> AddressMap<HashSet<U256>> {
1751    let loaded = state
1752        .loaded_accounts()
1753        .filter(|(address, _)| persistent.contains(*address))
1754        .map(|(address, slots)| (*address, slots.copied().collect::<Vec<_>>()))
1755        .collect::<Vec<_>>();
1756    let mut warm = AddressMap::default();
1757    for (address, slots) in loaded {
1758        if state.account(&address).is_ok_and(|account| account.is_warm()) {
1759            continue;
1760        }
1761        let slots = slots
1762            .into_iter()
1763            .filter(|key| state.storage_slot(&address, *key).is_ok_and(|slot| slot.is_warm()))
1764            .collect::<HashSet<_>>();
1765        if !slots.is_empty() {
1766            warm.insert(address, slots);
1767        }
1768    }
1769    warm
1770}
1771
1772/// Removes and returns the transient storage of the running transaction in `state`, as address, key
1773/// and value, sorted so writing it back is deterministic.
1774pub fn take_transient(state: &mut State<'_>) -> Vec<(Address, U256, U256)> {
1775    // `tstore` journals every change and the journal is only cleared together with transient
1776    // storage, so the journal names every address that holds some.
1777    let addresses = state
1778        .journal()
1779        .iter()
1780        .filter_map(|entry| match entry {
1781            JournalEntry::TransientStorageChange { address, .. } => Some(*address),
1782            _ => None,
1783        })
1784        .collect::<AddressSet>();
1785    let mut transient = Vec::new();
1786    for address in addresses {
1787        for (key, value) in state.take_transient_storage(&address) {
1788            transient.push((address, key, value));
1789        }
1790    }
1791    transient.sort_unstable();
1792    transient
1793}
1794
1795/// Writes `transient` storage taken with [`take_transient`] into the running transaction in
1796/// `state`.
1797pub fn put_transient(state: &mut State<'_>, transient: Vec<(Address, U256, U256)>) {
1798    for (address, key, value) in transient {
1799        state.tstore(&address, &key, &value);
1800    }
1801}
1802
1803/// Turns the accepted values of the slots of `originals` in the fresh `state` back into pending
1804/// writes of the running transaction over their transaction-start values.
1805///
1806/// The accepted state takes the transaction-start values as well, since committing the
1807/// transaction only writes slots whose values differ from their originals. Returns the replaced
1808/// accepted values.
1809fn restore_originals(
1810    state: &mut State<'_>,
1811    originals: &AddressMap<HashMap<U256, U256>>,
1812) -> AddressMap<HashMap<U256, U256>> {
1813    let mut pending = PendingState::default();
1814    let mut switched = AddressMap::<HashMap<_, _>>::default();
1815    for (address, slots) in originals {
1816        let Ok(info) = state.account_info_untracked(address) else { continue };
1817        pending.insert_account(*address, info.clone(), info);
1818        for (key, original) in slots {
1819            if let Ok(current) = state.storage_slot_untracked(address, key) {
1820                pending.insert_storage(*address, *key, *original, current);
1821                switched.entry(*address).or_default().insert(*key, current);
1822                let cache = &mut state.overlay_db_mut().cache;
1823                cache.storage.entry(*address).or_default().slots.insert(*key, *original);
1824            }
1825        }
1826    }
1827    state.set_pending_state(pending);
1828    switched
1829}
1830
1831/// Applies a nested transaction's `changes` to the accounts selected by `filter` to `state` as
1832/// journaled writes, also recorded in `persistent` if given.
1833///
1834/// Changes only carry changed code, so the code of an account whose code hash differs from
1835/// `state`'s is read from `source`, the nested transaction's database. Without one, the nested
1836/// transaction ran over a copy of `state`, where an unchanged code hash is already `state`'s.
1837///
1838/// Returns a [`PersistentWrite::ReloadDiscarded`] for each account whose storage a journaled
1839/// creation discarded, for the caller to replay when an enclosing call reverts.
1840fn merge_changes<'c>(
1841    state: &mut State<'_>,
1842    changes: impl Iterator<Item = AccountChanges<'c>>,
1843    filter: impl Fn(&Address) -> bool,
1844    mut persistent: Option<&mut Vec<PersistentWrite>>,
1845    mut source: Option<&mut CacheDB<Box<dyn DynDatabase + '_>>>,
1846) -> DbResult<Vec<PersistentWrite>> {
1847    let mut reloads = Vec::new();
1848    for change in changes.filter(|change| change.is_changed()) {
1849        let address = change.address;
1850        if !filter(&address) {
1851            continue;
1852        }
1853        // An account the running transaction already created keeps the storage it holds.
1854        let created = change.created && !state.account(&address)?.is_created();
1855        // An account the nested transaction created starts from empty storage, as it did there.
1856        // Journaled writes discard it with the creation and zero its loaded slots, including the
1857        // ones it writes, which load first so that a revert of the enclosing call restores them.
1858        // Slots first read under the creation keep that zero, which the returned reload undoes.
1859        // Untracked writes, a destroyed account, and an account the running transaction holds
1860        // with code or a nonce wipe it instead.
1861        let tracked = created && persistent.is_none() && change.current.is_some();
1862        if tracked {
1863            for (key, _) in change.storage.changed_slots() {
1864                state.storage_slot(&address, *key)?;
1865            }
1866        }
1867        let discarded = tracked
1868            && state.create_account(&address, &address, &U256::ZERO, EvmFeatures::empty())?.is_ok();
1869        let zeroed = if discarded {
1870            let zeroed = state
1871                .loaded_accounts()
1872                .find(|(loaded, _)| **loaded == address)
1873                .map(|(_, slots)| slots.copied().collect::<Vec<_>>())
1874                .unwrap_or_default();
1875            reloads.push(PersistentWrite::ReloadDiscarded(address, zeroed.clone()));
1876            zeroed
1877        } else {
1878            Vec::new()
1879        };
1880        {
1881            let mut account = state.account(&address)?;
1882            account.touch();
1883            if created && !discarded {
1884                account.mark_created();
1885            }
1886        }
1887        let code = || match (change.code, change.current, source.as_deref_mut()) {
1888            (Some((_, code)), ..) => Ok(code.clone()),
1889            (None, Some(info), Some(source)) if !info.is_empty_code_hash() => {
1890                source.get_code_by_hash(&info.code_hash)
1891            }
1892            _ => Ok(Bytecode::default()),
1893        };
1894        let wiped = (created && !discarded) || change.current.is_none() || change.storage.wiped;
1895        let reset = change.created || change.current.is_none();
1896        let slots = zeroed
1897            .into_iter()
1898            .map(|key| (key, U256::ZERO))
1899            .chain(change.storage.changed_slots().map(|(key, slot)| (*key, slot.current)));
1900        apply_account(
1901            state,
1902            address,
1903            change.current,
1904            code,
1905            wiped,
1906            reset,
1907            slots,
1908            persistent.as_deref_mut(),
1909        )?;
1910    }
1911    Ok(reloads)
1912}
1913
1914/// Returns the `changes` to accounts and storage slots the running transaction in `state` has not
1915/// loaded, as a pending state to accept. Accounts that were created, self-destructed, wiped or
1916/// given code are left out.
1917fn unloaded_changes<'c>(
1918    state: &State<'_>,
1919    changes: impl Iterator<Item = AccountChanges<'c>>,
1920) -> PendingState {
1921    let loaded = state
1922        .loaded_accounts()
1923        .map(|(address, slots)| (*address, slots.copied().collect::<HashSet<_>>()))
1924        .collect::<AddressMap<_>>();
1925    let mut pending = PendingState::default();
1926    for change in changes.filter(|change| change.is_changed()) {
1927        if change.created
1928            || change.selfdestructed
1929            || change.storage.wiped
1930            || change.code.is_some()
1931            || change.current.is_none()
1932        {
1933            continue;
1934        }
1935        let loaded = loaded.get(&change.address);
1936        // A loaded account keeps its info, which merges as a journaled write.
1937        let current = if loaded.is_some() { change.original } else { change.current };
1938        pending.insert_account(change.address, change.original.cloned(), current.cloned());
1939        for (key, slot) in change.storage.changed_slots() {
1940            if !loaded.is_some_and(|slots| slots.contains(key)) {
1941                pending.insert_storage(change.address, *key, slot.original, slot.current);
1942            }
1943        }
1944    }
1945    pending
1946}
1947
1948/// Replaces the accounts the running transaction in `state` loaded, except persistent ones, with
1949/// their accepted state in `source`, as journaled writes: info and loaded storage slots.
1950///
1951/// Used after replaying transactions on a fork while another one is active.
1952fn rebase_loaded_accounts(
1953    state: &mut State<'_>,
1954    source: &mut State<'_>,
1955    persistent: &AddressSet,
1956) -> DbResult<()> {
1957    let loaded = state
1958        .loaded_accounts()
1959        .filter(|(address, _)| !persistent.contains(*address))
1960        .map(|(address, slots)| (*address, slots.copied().collect::<Vec<_>>()))
1961        .collect::<Vec<_>>();
1962    for (address, keys) in loaded {
1963        let info = source.account_info_untracked(&address)?;
1964        let slots = keys
1965            .into_iter()
1966            .map(|key| Ok((key, source.storage_slot_untracked(&address, &key)?)))
1967            .collect::<DbResult<Vec<_>>>()?;
1968        let code = || match info.as_ref().map(|info| (info.code_hash, &info.code)) {
1969            Some((code_hash, None)) if code_hash != KECCAK256_EMPTY => {
1970                source.overlay_db_mut().get_code_by_hash(&code_hash)
1971            }
1972            Some((_, code)) => Ok(code.clone().unwrap_or_default()),
1973            None => Ok(Bytecode::default()),
1974        };
1975        apply_account(state, address, info.as_ref(), code, false, false, slots, None)?;
1976    }
1977    Ok(())
1978}
1979
1980/// Sets the account at `address` in `state` to `info`, or to no account, and writes `slots` to
1981/// its storage after wiping it if `wiped`, as journaled writes, also recorded in `persistent` if
1982/// given. Fields that already hold their value are left alone; `code` is only built when the code
1983/// hash changes.
1984///
1985/// If `reset`, such as for an account the nested transaction created or destroyed, the nonce is
1986/// recorded as an absolute write even when it already holds its value, so that a replay does not
1987/// bring back the value it replaced, and so is the emptied balance of a destroyed account. A
1988/// created account keeps the balance it had, which may come from transfers a revert undoes.
1989///
1990/// A journaled wipe is not undone by a revert of the enclosing call: evm2 does not journal the
1991/// wipe marker, and slots the running transaction never loaded cannot be cleared one by one.
1992/// [`merge_changes`] discards the storage of tracked creations through the journaled creation
1993/// instead.
1994#[expect(clippy::too_many_arguments)]
1995fn apply_account(
1996    state: &mut State<'_>,
1997    address: Address,
1998    info: Option<&AccountInfo>,
1999    code: impl FnOnce() -> DbResult<Bytecode>,
2000    wiped: bool,
2001    reset: bool,
2002    slots: impl IntoIterator<Item = (U256, U256)>,
2003    mut persistent: Option<&mut Vec<PersistentWrite>>,
2004) -> DbResult<()> {
2005    let mut record = |write| {
2006        if let Some(persistent) = persistent.as_deref_mut() {
2007            persistent.push(write);
2008        }
2009    };
2010    {
2011        let mut account = state.account(&address)?;
2012        let (balance, nonce, code_hash) = info.map_or((U256::ZERO, 0, KECCAK256_EMPTY), |info| {
2013            (info.balance, info.nonce, info.code_hash)
2014        });
2015        let emptied = reset && info.is_none();
2016        if emptied || account.balance() != balance {
2017            let write = PersistentWrite::balance(address, account.balance(), balance);
2018            record(if emptied { write.with_replay(Replay::Absolute) } else { write });
2019            account.set_balance(balance);
2020        }
2021        if reset || account.nonce() != nonce {
2022            let previous = account.nonce();
2023            account.set_nonce(nonce);
2024            record(if reset {
2025                // Like the code, the reset outlives the creation flag a revert undoes.
2026                PersistentWrite::Nonce {
2027                    address,
2028                    delta: i128::from(nonce) - i128::from(previous),
2029                    nonce,
2030                    created: false,
2031                    replay: Replay::Absolute,
2032                }
2033            } else {
2034                PersistentWrite::nonce(&account, previous)
2035            });
2036        }
2037        if account.code_hash() != code_hash {
2038            let code = code()?;
2039            record(PersistentWrite::Code(address, code_hash, code.clone()));
2040            account.set_code(code_hash, code);
2041        }
2042    }
2043    if wiped {
2044        record(PersistentWrite::Wipe(address));
2045        state.storage(&address)?.wipe();
2046    }
2047    for (key, value) in slots {
2048        // A slot the account already holds, such as one the nested transaction only read, is not
2049        // a write.
2050        let mut slot = state.storage_slot(&address, key)?;
2051        if slot.current() != value {
2052            record(PersistentWrite::Slot(address, key, value));
2053            slot.set(value);
2054        }
2055    }
2056    Ok(())
2057}
2058
2059/// Returns the accounts `state` loaded with their loaded slots.
2060fn loaded_slots(state: &State<'_>) -> Vec<(Address, Vec<U256>)> {
2061    state.loaded_accounts().map(|(address, slots)| (*address, slots.copied().collect())).collect()
2062}