Skip to main content

ethrex_levm/
vm.rs

1use crate::{
2    TransientStorage,
3    account::LevmAccount,
4    call_frame::{CallFrame, Stack},
5    db::gen_db::GeneralizedDatabase,
6    debug::DebugMode,
7    environment::Environment,
8    errors::{
9        ContextResult, ExceptionalHalt, ExecutionReport, InternalError, OpcodeResult, TxResult,
10        VMError,
11    },
12    gas_cost::{
13        STATE_BYTES_PER_AUTH_BASE, STATE_BYTES_PER_NEW_ACCOUNT, STATE_BYTES_PER_STORAGE_SET,
14        cost_per_state_byte as compute_cost_per_state_byte,
15    },
16    hooks::{
17        backup_hook::BackupHook,
18        hook::{Hook, get_hooks},
19    },
20    memory::Memory,
21    opcode_tracer::LevmOpcodeTracer,
22    opcodes::OpCodeFn,
23    precompiles::{
24        self, SIZE_PRECOMPILES_CANCUN, SIZE_PRECOMPILES_PRAGUE, SIZE_PRECOMPILES_PRE_CANCUN,
25    },
26    tracing::LevmCallTracer,
27    validation_observer::ValidationObserver,
28};
29use bytes::Bytes;
30use ethrex_common::{
31    Address, BigEndianHash, H160, H256, U256,
32    tracing::CallType,
33    types::{
34        AccessListEntry, Code, Fork, Frame, FrameMode, Log, Transaction, TxType,
35        block_access_list::BlockAccessListCheckpoint, fee_config::FeeConfig,
36    },
37};
38use ethrex_crypto::Crypto;
39use rustc_hash::{FxHashMap, FxHashSet};
40use std::{
41    cell::{OnceCell, RefCell},
42    collections::{BTreeMap, BTreeSet},
43    mem,
44    rc::Rc,
45};
46
47/// Storage mapping from slot key to value.
48pub type Storage = FxHashMap<U256, H256>;
49
50/// Specifies whether the VM operates in L1 or L2 mode.
51#[derive(Debug, Clone, Copy, Default)]
52pub enum VMType {
53    /// Standard Ethereum L1 execution.
54    #[default]
55    L1,
56    /// L2 rollup execution with additional fee handling.
57    L2(FeeConfig),
58}
59
60/// Execution substate that tracks changes during transaction execution.
61///
62/// The substate maintains all information that may need to be reverted if a
63/// call fails, including:
64/// - Self-destructed accounts
65/// - Accessed addresses and storage slots (for EIP-2929 gas accounting)
66/// - Created accounts
67/// - Gas refunds
68/// - Transient storage (EIP-1153)
69/// - Event logs
70///
71/// # Backup Mechanism
72///
73/// The substate supports checkpointing via [`push_backup`] and restoration via
74/// [`revert_backup`] or commitment via [`commit_backup`]. This is used to handle
75/// nested calls where inner calls may fail and need to be reverted.
76///
77/// Most fields are private by design. The backup mechanism only works correctly
78/// if data modifications are append-only.
79#[derive(Debug, Default)]
80pub struct Substate {
81    /// Parent checkpoint for reverting on failure.
82    parent: Option<Box<Self>>,
83    /// Fork of the enclosing transaction. Lets the warmth helpers treat precompile addresses as
84    /// always-warm without occupying a hashset slot (EIP-2929). Constant for a tx, so it is
85    /// carried forward across `push_backup` checkpoints.
86    fork: Fork,
87    /// Accounts marked for self-destruction (deleted at end of transaction).
88    selfdestruct_set: FxHashSet<Address>,
89    /// Addresses accessed during execution (for EIP-2929 warm/cold gas costs).
90    /// Precompiles are NOT stored here; they are warm by construction (see `is_warm_precompile`).
91    accessed_addresses: FxHashSet<Address>,
92    /// Storage slots accessed per address (for EIP-2929 warm/cold gas costs).
93    accessed_storage_slots: FxHashMap<Address, FxHashSet<H256>>,
94    /// Accounts created during this transaction.
95    created_accounts: FxHashSet<Address>,
96    /// Accumulated gas refund (e.g., from storage clears).
97    pub refunded_gas: u64,
98    /// Transient storage (EIP-1153), cleared at end of transaction.
99    transient_storage: TransientStorage,
100    /// Event logs emitted during execution.
101    logs: Vec<Log>,
102}
103
104impl Substate {
105    pub fn from_accesses(
106        fork: Fork,
107        accessed_addresses: FxHashSet<Address>,
108        accessed_storage_slots: FxHashMap<Address, FxHashSet<H256>>,
109    ) -> Self {
110        Self {
111            parent: None,
112            fork,
113            selfdestruct_set: FxHashSet::default(),
114            accessed_addresses,
115            accessed_storage_slots,
116            created_accounts: FxHashSet::default(),
117            refunded_gas: 0,
118            transient_storage: TransientStorage::default(),
119            logs: Vec::new(),
120        }
121    }
122
123    /// Whether `address` is a precompile that the EVM treats as warm from the start of the tx
124    /// (EIP-2929), exactly matching the addresses `Substate::initialize` used to pre-seed.
125    ///
126    /// Replicates the pre-seed *precisely* — the contiguous range `0x01..=max_for_fork` plus the
127    /// post-Osaka P256VERIFY address `0x100` — and is intentionally `vm_type`-independent, since
128    /// the old pre-seed was too. (Using `precompiles::is_precompile`, which gates `0x100` on L2
129    /// for any fork, would change L2 pre-Osaka warmth — a consensus difference, not an opt.)
130    #[inline]
131    fn is_warm_precompile(&self, address: &Address) -> bool {
132        // Fast reject: every pre-seeded precompile has 18 leading zero bytes (max is `0x01_00`),
133        // so real contract/EOA addresses bail out here, off the hot warmth path.
134        if address.0[..18] != [0u8; 18] {
135            return false;
136        }
137        let n = u16::from_be_bytes([address.0[18], address.0[19]]);
138        let max_contiguous: u64 = match self.fork {
139            f if f >= Fork::Prague => SIZE_PRECOMPILES_PRAGUE,
140            f if f >= Fork::Cancun => SIZE_PRECOMPILES_CANCUN,
141            _ => SIZE_PRECOMPILES_PRE_CANCUN,
142        };
143        (n >= 1 && u64::from(n) <= max_contiguous) || (n == 0x100 && self.fork >= Fork::Osaka)
144    }
145
146    /// Push a checkpoint that can be either reverted or committed. All data up to this point is
147    /// still accessible.
148    pub fn push_backup(&mut self) {
149        let parent = mem::take(self);
150        self.refunded_gas = parent.refunded_gas;
151        // Carry the fork forward so child checkpoints keep the same precompile-warmth view.
152        self.fork = parent.fork;
153        self.parent = Some(Box::new(parent));
154    }
155
156    /// Pop and merge with the last backup.
157    ///
158    /// Does nothing if the substate has no backup.
159    pub fn commit_backup(&mut self) {
160        if let Some(parent) = self.parent.as_mut() {
161            let mut delta = mem::take(parent);
162            mem::swap(self, &mut delta);
163
164            self.selfdestruct_set.extend(delta.selfdestruct_set);
165            self.accessed_addresses.extend(delta.accessed_addresses);
166            for (address, slot_set) in delta.accessed_storage_slots {
167                self.accessed_storage_slots
168                    .entry(address)
169                    .or_default()
170                    .extend(slot_set);
171            }
172            self.created_accounts.extend(delta.created_accounts);
173            self.refunded_gas = delta.refunded_gas;
174            self.transient_storage.extend(delta.transient_storage);
175            self.logs.extend(delta.logs);
176        }
177    }
178
179    /// Discard current changes and revert to last backup.
180    ///
181    /// Does nothing if the substate has no backup.
182    pub fn revert_backup(&mut self) {
183        if let Some(parent) = self.parent.as_mut() {
184            *self = mem::take(parent);
185        }
186    }
187
188    /// Return an iterator over all selfdestruct addresses.
189    pub fn iter_selfdestruct(&self) -> impl Iterator<Item = &Address> {
190        struct Iter<'a> {
191            parent: Option<&'a Substate>,
192            iter: std::collections::hash_set::Iter<'a, Address>,
193        }
194
195        impl<'a> Iterator for Iter<'a> {
196            type Item = &'a Address;
197
198            fn next(&mut self) -> Option<Self::Item> {
199                let next_item = self.iter.next();
200                if next_item.is_none()
201                    && let Some(parent) = self.parent
202                {
203                    self.parent = parent.parent.as_deref();
204                    self.iter = parent.selfdestruct_set.iter();
205
206                    return self.next();
207                }
208
209                next_item
210            }
211        }
212
213        Iter {
214            parent: self.parent.as_deref(),
215            iter: self.selfdestruct_set.iter(),
216        }
217    }
218
219    /// Mark an address as selfdestructed and return whether is was already marked.
220    pub fn add_selfdestruct(&mut self, address: Address) -> bool {
221        if self.selfdestruct_set.contains(&address) {
222            return true;
223        }
224
225        let is_present = self
226            .parent
227            .as_ref()
228            .map(|parent| parent.is_selfdestruct(&address))
229            .unwrap_or_default();
230
231        is_present || !self.selfdestruct_set.insert(address)
232    }
233
234    /// Return whether an address is already marked as selfdestructed.
235    pub fn is_selfdestruct(&self, address: &Address) -> bool {
236        self.selfdestruct_set.contains(address)
237            || self
238                .parent
239                .as_ref()
240                .map(|parent| parent.is_selfdestruct(address))
241                .unwrap_or_default()
242    }
243
244    /// Build an access list from all accessed storage slots.
245    pub fn make_access_list(&self) -> Vec<AccessListEntry> {
246        let mut entries = BTreeMap::<Address, BTreeSet<H256>>::new();
247
248        let mut current = self;
249        loop {
250            for (address, slot_set) in &current.accessed_storage_slots {
251                entries
252                    .entry(*address)
253                    .or_default()
254                    .extend(slot_set.iter().copied());
255            }
256
257            current = match current.parent.as_deref() {
258                Some(x) => x,
259                None => break,
260            };
261        }
262
263        entries
264            .into_iter()
265            .map(|(address, storage_keys)| AccessListEntry {
266                address,
267                storage_keys: storage_keys.into_iter().collect(),
268            })
269            .collect()
270    }
271
272    /// Mark an address as accessed and return whether the slot was cold.
273    pub fn add_accessed_slot(&mut self, address: Address, key: H256) -> bool {
274        if self
275            .accessed_storage_slots
276            .get(&address)
277            .is_some_and(|set| set.contains(&key))
278        {
279            return false;
280        }
281
282        let is_present = self
283            .parent
284            .as_ref()
285            .map(|parent| parent.is_slot_accessed(&address, &key))
286            .unwrap_or_default();
287
288        // Note: Do not simplify this expression, it uses `||` to avoid executing the right hand
289        //   expression if not necessary.
290        #[expect(clippy::nonminimal_bool, reason = "order of evaluation matters")]
291        !(is_present
292            || !self
293                .accessed_storage_slots
294                .entry(address)
295                .or_default()
296                .insert(key))
297    }
298
299    /// Return whether an address has already been accessed.
300    pub fn is_slot_accessed(&self, address: &Address, key: &H256) -> bool {
301        self.accessed_storage_slots
302            .get(address)
303            .map(|slot_set| slot_set.contains(key))
304            .unwrap_or_default()
305            || self
306                .parent
307                .as_ref()
308                .map(|parent| parent.is_slot_accessed(address, key))
309                .unwrap_or_default()
310    }
311
312    /// Returns all accessed storage slots for a given address.
313    /// Used by SELFDESTRUCT to record storage reads in BAL per EIP-7928:
314    /// "SELFDESTRUCT: Include modified/read storage keys as storage_read"
315    pub fn get_accessed_storage_slots(&self, address: &Address) -> BTreeSet<H256> {
316        let mut slots = BTreeSet::new();
317
318        // Collect from current substate
319        if let Some(slot_set) = self.accessed_storage_slots.get(address) {
320            slots.extend(slot_set.iter().copied());
321        }
322
323        // Collect from parent substates recursively
324        if let Some(parent) = self.parent.as_ref() {
325            slots.extend(parent.get_accessed_storage_slots(address));
326        }
327
328        slots
329    }
330
331    /// Mark an address as accessed and return whether the address was cold.
332    pub fn add_accessed_address(&mut self, address: Address) -> bool {
333        // Precompiles are warm from tx start (EIP-2929) without occupying a hashset slot. Returns
334        // `false` (not cold) so cold-access gas is never charged — identical to the old pre-seed.
335        if self.is_warm_precompile(&address) {
336            return false;
337        }
338
339        if self.accessed_addresses.contains(&address) {
340            return false;
341        }
342
343        let is_present = self
344            .parent
345            .as_ref()
346            .map(|parent| parent.is_address_accessed(&address))
347            .unwrap_or_default();
348
349        // Note: Do not simplify this expression, it uses `||` to avoid executing the right hand
350        //   expression if not necessary.
351        #[expect(clippy::nonminimal_bool, reason = "order of evaluation matters")]
352        !(is_present || !self.accessed_addresses.insert(address))
353    }
354
355    /// Return whether an address has already been accessed.
356    pub fn is_address_accessed(&self, address: &Address) -> bool {
357        // Precompiles are always warm; the chain shares one `fork`, so this is consistent across
358        // sub-frame substates.
359        self.is_warm_precompile(address)
360            || self.accessed_addresses.contains(address)
361            || self
362                .parent
363                .as_ref()
364                .map(|parent| parent.is_address_accessed(address))
365                .unwrap_or_default()
366    }
367
368    /// Mark an address as a new account and return whether is was already marked.
369    pub fn add_created_account(&mut self, address: Address) -> bool {
370        if self.created_accounts.contains(&address) {
371            return true;
372        }
373
374        let is_present = self
375            .parent
376            .as_ref()
377            .map(|parent| parent.is_account_created(&address))
378            .unwrap_or_default();
379
380        is_present || !self.created_accounts.insert(address)
381    }
382
383    /// Return whether an address has already been marked as a new account.
384    pub fn is_account_created(&self, address: &Address) -> bool {
385        self.created_accounts.contains(address)
386            || self
387                .parent
388                .as_ref()
389                .map(|parent| parent.is_account_created(address))
390                .unwrap_or_default()
391    }
392
393    /// Return the data associated with a transient storage entry, or zero if not present.
394    pub fn get_transient(&self, to: &Address, key: &U256) -> U256 {
395        self.transient_storage
396            .get(&(*to, *key))
397            .copied()
398            .unwrap_or_else(|| {
399                self.parent
400                    .as_ref()
401                    .map(|parent| parent.get_transient(to, key))
402                    .unwrap_or_default()
403            })
404    }
405
406    /// Return the data associated with a transient storage entry, or zero if not present.
407    pub fn set_transient(&mut self, to: &Address, key: &U256, value: U256) {
408        self.transient_storage.insert((*to, *key), value);
409    }
410
411    /// Clear all transient storage (used between frames in frame transactions).
412    pub fn clear_transient_storage(&mut self) {
413        self.transient_storage.clear();
414    }
415
416    /// Extract all logs in order.
417    pub fn extract_logs(&self) -> Vec<Log> {
418        fn inner(substrate: &Substate, target: &mut Vec<Log>) {
419            if let Some(parent) = substrate.parent.as_deref() {
420                inner(parent, target);
421            }
422
423            target.extend_from_slice(&substrate.logs);
424        }
425
426        let mut logs = Vec::new();
427        inner(self, &mut logs);
428
429        logs
430    }
431
432    /// Return a clone of the current sub-substate's logs only, excluding parent logs.
433    /// Used by EIP-8141 frame execution to capture per-frame log deltas for
434    /// `frame_receipts[i].logs`. Must be called after `push_backup()` and before
435    /// `commit_backup()` to return only the logs emitted during the current scope.
436    pub fn current_logs(&self) -> Vec<Log> {
437        self.logs.clone()
438    }
439
440    /// Number of logs in the current scope, without cloning them. Used to slice
441    /// out a single frame's logs after `run_execution` has already committed the
442    /// frame's backup up into this scope.
443    pub fn logs_len(&self) -> usize {
444        self.logs.len()
445    }
446
447    /// Push a log record.
448    pub fn add_log(&mut self, log: Log) {
449        self.logs.push(log);
450    }
451}
452
453/// The LEVM (Lambda EVM) execution engine.
454///
455/// The VM executes Ethereum transactions by processing EVM bytecode. It maintains
456/// a call stack, memory, and tracks all state changes during execution.
457///
458/// # Execution Model
459///
460/// 1. Transaction is validated (nonce, balance, gas limit)
461/// 2. Initial call frame is created with transaction data
462/// 3. Opcodes are executed sequentially until completion or error
463/// 4. State changes are committed or reverted based on success
464///
465/// # Call Stack
466///
467/// Nested calls (CALL, DELEGATECALL, etc.) push new frames onto `call_frames`.
468/// Each frame has its own memory, stack, and execution context. The `current_call_frame`
469/// is always the active frame being executed.
470///
471/// # Hooks
472///
473/// The VM supports hooks for extending functionality (e.g., tracing, debugging).
474/// Hooks are called at various points during execution and implement pre/post-execution
475/// logic. L2-specific behavior (such as fee handling) is implemented via hooks.
476///
477/// # Example
478///
479/// ```ignore
480/// let mut vm = VM::new(env, db, &tx, tracer, vm_type, &NativeCrypto);
481/// let report = vm.execute()?;
482/// if report.is_success() {
483///     println!("Gas used: {}, Output: {:?}", report.gas_used, report.output);
484/// } else {
485///     println!("Transaction reverted");
486/// }
487/// ```
488/// EIP-8141 spec lines 346-347: the top-level `frame.value` transfer
489/// reverts the frame if the sender's balance is strictly less than the
490/// amount being sent. Factored out so the decision can be unit-tested
491/// without bringing up a full VM state.
492pub fn frame_value_exceeds_balance(sender_balance: U256, frame_value: U256) -> bool {
493    sender_balance < frame_value
494}
495
496/// Context for frame transaction (EIP-8141) execution.
497/// This is set when executing a frame transaction and is used by
498/// APPROVE, TXPARAM, FRAMEDATALOAD, and FRAMEDATACOPY opcodes.
499#[derive(Debug, Clone)]
500pub struct FrameTxContext {
501    /// Whether the sender has approved (APPROVE scope `APPROVE_EXECUTION` or
502    /// `APPROVE_EXECUTION_AND_PAYMENT`).
503    pub sender_approved: bool,
504    /// The address that approved payment, set by `APPROVE_PAYMENT` or
505    /// `APPROVE_EXECUTION_AND_PAYMENT`. Per the latest EIP-8141 spec this is the
506    /// single source of truth for whether payment has been approved: when this
507    /// is `Some(_)`, the transaction has a `payer`; when `None`, it does not.
508    pub payer_address: Option<Address>,
509    /// Per-frame execution results (status, gas_used, logs).
510    /// `status` is a `FRAME_RECEIPT_STATUS_*` code (0 = failure, 1 = success,
511    /// 3 = skipped due to failed atomic batch).
512    pub frame_results: Vec<(u8, u64, Vec<Log>)>,
513    /// Index of the currently executing frame
514    pub current_frame_index: usize,
515    /// The sig_hash of the frame transaction
516    pub sig_hash: H256,
517    /// The full frame transaction (for TXPARAM access)
518    pub tx: ethrex_common::types::FrameTransaction,
519    /// Whether APPROVE was called in the current frame
520    pub approve_called_in_current_frame: bool,
521    /// Cached `FrameTransaction::total_gas_limit()`. Computing it re-encodes
522    /// every frame and signature, so it must not run per-opcode (TXPARAM 0x06,
523    /// compute_tx_max_cost). Computed once at tx entry.
524    pub total_gas_limit: u64,
525}
526
527impl FrameTxContext {
528    /// Capture the approval state at atomic-batch entry. A batch revert rolls
529    /// back the payer's balance deduction and the sender nonce increment, so
530    /// approvals granted inside the batch must be rolled back with it —
531    /// otherwise a reverted APPROVE would leave the transaction authorized
532    /// by a frame whose effects no longer exist.
533    pub fn approval_snapshot(&self) -> (bool, Option<Address>) {
534        (self.sender_approved, self.payer_address)
535    }
536
537    /// Restore the approval state captured by `approval_snapshot` when the
538    /// enclosing atomic batch reverts. Approvals granted before the batch
539    /// are unaffected (the snapshot includes them).
540    pub fn restore_approvals(&mut self, snapshot: (bool, Option<Address>)) {
541        let (sender_approved, payer_address) = snapshot;
542        self.sender_approved = sender_approved;
543        self.payer_address = payer_address;
544    }
545}
546
547/// Snapshot of `call_frame_backup`'s key-space taken by [`VM::enter_prepare_region`]
548/// at the start of the atomic prepare region (EIP-8037 auth + prepare-dispatch
549/// charges). `original_accounts_info` / `original_account_storage_slots` are
550/// first-write-wins maps keyed by address, so a plain entry-count marker can't
551/// tell which keys are region-added; recording the pre-region key sets lets
552/// [`VM::fail_prepare_region`] revert exactly the region's writes while leaving
553/// the earlier sender nonce-bump / fee-deduction backup entries intact.
554/// `inserted_code_hashes` is an append-only `Vec`, so its pre-region length is
555/// enough to identify the region-added tail.
556#[derive(Debug, Default)]
557pub struct PrepareRegionBackupMarker {
558    /// Addresses already backed up in `original_accounts_info` before the region.
559    accounts: FxHashSet<Address>,
560    /// Addresses already backed up in `original_account_storage_slots` before the region.
561    storage: FxHashSet<Address>,
562    /// Length of `inserted_code_hashes` before the region.
563    code_hashes_len: usize,
564    /// Region-entry state of every account already backed up before the region
565    /// (notably the sender, post-fee/post-nonce). The marker excludes these from
566    /// the region rollback to preserve their pre-region writes, but first-write-wins
567    /// backup means an in-region write to one of them (e.g. a self-sponsored EIP-7702
568    /// authorization on the sender) leaves no new backup entry. `fail_prepare_region`
569    /// restores these to the captured state, reverting the in-region write while
570    /// keeping the pre-region nonce bump / fee deduction.
571    entry_state: FxHashMap<Address, LevmAccount>,
572    /// BAL recorder checkpoint at region entry, so an applied-then-reverted
573    /// delegation's code/nonce changes are discarded (demoted to an access-only
574    /// touch) rather than leaking into the block access list.
575    bal_checkpoint: Option<BlockAccessListCheckpoint>,
576}
577
578/// Result of [`VM::simulate_validation_prefix`] (EIP-8141 mempool simulation).
579#[derive(Debug, Clone)]
580pub struct PrefixSimResult {
581    /// Whether any prefix frame reverted (fatal for validation).
582    pub any_revert: bool,
583    /// The payer established by the prefix, if any.
584    pub payer_address: Option<Address>,
585    /// Whether the sender was approved by a verify/pay frame.
586    pub sender_approved: bool,
587    /// Total simulated gas used across the prefix frames.
588    pub total_gas_used: u64,
589}
590
591pub struct VM<'a> {
592    /// Stack of parent call frames (for nested calls).
593    pub call_frames: Vec<CallFrame>,
594    /// The currently executing call frame.
595    pub current_call_frame: CallFrame,
596    /// Block and transaction environment.
597    pub env: Environment,
598    /// Execution substate (accessed addresses, logs, refunds, etc.).
599    pub substate: Substate,
600    /// Database for reading/writing account state.
601    pub db: &'a mut GeneralizedDatabase,
602    /// The transaction being executed. Borrowed for the VM's lifetime (the caller owns it for at
603    /// least that long), avoiding a per-tx deep clone of the access/authorization lists.
604    pub tx: &'a Transaction,
605    /// Execution hooks for tracing and debugging.
606    pub hooks: Vec<Rc<RefCell<dyn Hook>>>,
607    /// Original storage values before transaction (for SSTORE gas calculation),
608    /// keyed first by account to avoid hashing the full tuple on each access.
609    pub storage_original_values: FxHashMap<Address, FxHashMap<H256, U256>>,
610    /// Call tracer for execution tracing.
611    pub tracer: LevmCallTracer,
612    /// Opcode (EIP-3155) tracer.  Disabled by default; zero overhead when inactive.
613    pub opcode_tracer: LevmOpcodeTracer,
614    /// EIP-8141 mempool validation-trace observer. Disabled by default; active
615    /// only during `simulate_frame_validation_prefix`. Read only behind
616    /// `if self.validation_observer.active`, so an inactive observer adds one
617    /// branch to the dispatch loop and nothing more (mirrors `opcode_tracer`).
618    pub validation_observer: ValidationObserver,
619    /// Debug mode for development diagnostics.
620    pub debug_mode: DebugMode,
621    /// Pool of reusable stacks to reduce allocations.
622    pub stack_pool: Vec<Stack>,
623    /// VM type (L1 or L2 with fee config).
624    pub vm_type: VMType,
625    /// Frame transaction context (EIP-8141). Set when executing a frame tx.
626    pub frame_tx_context: Option<FrameTxContext>,
627
628    /// Whether the top-level call-frame backup must be PRESERVED (deep-cloned) on the
629    /// revert / invalid-tx paths because a `BackupHook` will read it in `finalize_execution`
630    /// to build the tx-level undo snapshot. Derived from the installed `hooks` (via
631    /// [`Hook::reads_top_level_backup`]) rather than from `vm_type`, so it stays correct if
632    /// hook wiring changes; `add_hook` keeps it in sync for the `BackupHook` that
633    /// `stateless_execute` installs after construction. False for normal L1 block execution
634    /// (no `BackupHook`), where the backup is dead once the cache is restored and can be moved
635    /// out instead of cloned.
636    pub(crate) preserve_top_level_backup: bool,
637    /// EIP-8037: Accumulated state gas for this transaction (Amsterdam+).
638    /// Signed: goes negative when inline refunds exceed gross charges in the local frame
639    /// (e.g. SSTORE 0→x→0 restoration matching an ancestor's charge).
640    pub state_gas_used: i64,
641    /// EIP-8037: State gas reservoir pre-funded from excess gas_limit (Amsterdam+).
642    pub state_gas_reservoir: u64,
643    /// EIP-8037: Initial reservoir at tx start (before any execution). Captured in
644    /// add_intrinsic_gas so block-dimensional regular gas can be computed
645    /// independently of mid-tx reservoir activity (auth refunds, SSTORE credits).
646    pub state_gas_reservoir_initial: u64,
647    /// EIP-8037: Cumulative state gas that spilled to regular gas during execution
648    /// (when reservoir was insufficient). Subtracted when computing dimensional
649    /// regular gas for block accounting — EELS charge_state_gas spills don't
650    /// increment regular_gas_used.
651    pub state_gas_spill: u64,
652    /// EIP-8037: Dynamic cost per state byte (computed from block_gas_limit, Amsterdam+).
653    pub cost_per_state_byte: u64,
654    /// EIP-8037: State gas for new account creation (STATE_BYTES_PER_NEW_ACCOUNT * cost_per_state_byte).
655    pub state_gas_new_account: u64,
656    /// EIP-8037: State gas for storage slot creation (STATE_BYTES_PER_STORAGE_SET * cost_per_state_byte).
657    pub state_gas_storage_set: u64,
658    /// EIP-8037: State gas for the 23-byte EIP-7702 delegation indicator
659    /// (STATE_BYTES_PER_AUTH_BASE * cost_per_state_byte). Charged in-region by
660    /// `eip7702_set_access_code` (EELS `set_delegation`) once per authority when a
661    /// net-new delegation indicator is written, and never credited back.
662    pub state_gas_auth_base: u64,
663    /// EIP-8037: intrinsic state gas (`tx_env.intrinsic_state_gas` in EELS). Captured at
664    /// `add_intrinsic_gas` time. ethrex lumps intrinsic + execution into `state_gas_used`,
665    /// so on top-level error this field is what we leave behind when refunding the
666    /// execution portion to the reservoir — block accounting then bills the intrinsic
667    /// (matches EELS `tx_state_gas = intrinsic_state_gas + tx_output.state_gas_used`).
668    pub intrinsic_state_gas: u64,
669    /// EIP-8037: set by `prepare_execution` when the in-region value-to-not-alive
670    /// `NEW_ACCOUNT` charge fires (a value-bearing call to a not-yet-alive
671    /// recipient). Consumed once, at the top of `run_execution`, to decide
672    /// whether an Amsterdam precompile-halt must roll the charge back (the
673    /// recipient never materializes on halt).
674    pub value_new_account_charged: bool,
675    /// EIP-8037: `current_call_frame.state_gas_used_at_entry` captured by
676    /// `enter_prepare_region` right before the atomic prepare region (EIP-7702
677    /// auth + prepare-dispatch charges) begins. `fail_prepare_region` rewinds the
678    /// frame's `state_gas_used` back to this pre-region baseline on an internal OOG,
679    /// mirroring EELS `restore_tx_state(prep_snapshot)`.
680    pub prep_baseline_state_gas: i64,
681    /// EIP-8037: `state_gas_reservoir` captured by `enter_prepare_region`. The
682    /// `set_delegation` auth lock-in zeroes the frame spill, so `fail_prepare_region`
683    /// cannot reconstruct the pre-region reservoir from `refill_frame_state_gas`
684    /// arithmetic; it restores this captured value directly (EELS
685    /// `message.state_gas_reservoir = prep_reservoir`).
686    pub prep_baseline_reservoir: u64,
687    /// EIP-8037: cumulative `state_gas_spill` captured by `enter_prepare_region`, so
688    /// `fail_prepare_region` restores block-accounting spill to its pre-region value
689    /// (the region's spilled state gas is fully rolled back / burned as regular).
690    pub prep_baseline_state_gas_spill: u64,
691    /// EIP-8037: pre-region key-space snapshot of `call_frame_backup`, recorded by
692    /// `enter_prepare_region`. Lets `fail_prepare_region` revert only region-added
693    /// writes, leaving the sender nonce-bump / fee-deduction entries intact.
694    pub prep_region_backup_marker: PrepareRegionBackupMarker,
695    /// EIP-8037: set by `fail_prepare_region` when an internal OOG rolls back the
696    /// atomic prepare region. Consumed by `run_execution`, which turns it into a
697    /// full-gas revert `ContextResult` (mirrors EELS depth-0
698    /// `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`)
699    /// instead of a tx-level rejection `Err` that would wrongly invalidate the block.
700    pub pending_prep_oog: bool,
701    /// The opcode table mapping opcodes to opcode handlers for fast lookup.
702    /// A shared `&'static` reference to a per-fork table that is `const`-built once for the
703    /// whole process (immutable), so each VM holds only a pointer instead of a 2 KB inline copy.
704    pub(crate) opcode_table: &'static [OpCodeFn; 256],
705    /// Crypto provider for cryptographic operations.
706    pub crypto: &'a dyn Crypto,
707}
708
709/// Validate every EIP-8141 outer signature (spec commit fe0940cae2) against
710/// the canonical `sig_hash`. Returns false if any signature is malformed or
711/// invalid. Verification gas is intrinsic (already in `total_gas_limit`), so a
712/// scratch budget is used for the crypto precompiles and their deduction is
713/// ignored.
714#[expect(
715    clippy::indexing_slicing,
716    reason = "signature length is checked before each fixed-offset slice"
717)]
718pub fn validate_frame_signatures(
719    signatures: &[ethrex_common::types::FrameSignature],
720    sig_hash: ethrex_common::H256,
721    fork: Fork,
722    crypto: &dyn Crypto,
723) -> bool {
724    use ethrex_common::types::{FRAME_SIG_SCHEME_P256, FRAME_SIG_SCHEME_SECP256K1};
725    for sig in signatures {
726        // Resolve the signed message.
727        let msg: [u8; 32] = match sig.msg.len() {
728            0 => sig_hash.0,
729            32 => {
730                let mut m = [0u8; 32];
731                m.copy_from_slice(&sig.msg);
732                if m == [0u8; 32] {
733                    return false;
734                }
735                m
736            }
737            _ => return false,
738        };
739        let mut scratch_gas = u64::MAX;
740        match sig.scheme {
741            FRAME_SIG_SCHEME_SECP256K1 => {
742                if sig.signature.len() != 65 {
743                    return false;
744                }
745                let v = sig.signature[0];
746                let r = &sig.signature[1..33];
747                let s = &sig.signature[33..65];
748                // EIP-8141 defines verification as `signer == ecrecover(msg, v, r, s)`
749                // and does NOT mandate EIP-2 low-s, so a high-s frame signature is
750                // spec-valid and MUST be accepted here (this is the consensus
751                // block-execution path). Anti-malleability (low-s) is enforced as
752                // local mempool policy in `frame_signatures_are_low_s`, never at
753                // consensus — rejecting high-s here would diverge from a conformant
754                // client that accepts it.
755                let mut calldata = vec![0u8; 128];
756                calldata[..32].copy_from_slice(&msg);
757                calldata[63] = v;
758                calldata[64..96].copy_from_slice(r);
759                calldata[96..128].copy_from_slice(s);
760                let Ok(result) = crate::precompiles::ecrecover(
761                    &Bytes::from(calldata),
762                    &mut scratch_gas,
763                    fork,
764                    crypto,
765                ) else {
766                    return false;
767                };
768                if result.len() != 32 {
769                    return false;
770                }
771                let recovered = ethrex_common::Address::from_slice(&result[12..]);
772                if recovered == ethrex_common::Address::zero() || recovered != sig.signer {
773                    return false;
774                }
775            }
776            FRAME_SIG_SCHEME_P256 => {
777                if sig.signature.len() != 128 {
778                    return false;
779                }
780                let r = &sig.signature[0..32];
781                let s = &sig.signature[32..64];
782                let qx = &sig.signature[64..96];
783                let qy = &sig.signature[96..128];
784                // signer = keccak256(qx || qy)[12:]  (NO domain separator)
785                let mut pk = Vec::with_capacity(64);
786                pk.extend_from_slice(qx);
787                pk.extend_from_slice(qy);
788                let h = ethrex_crypto::keccak::keccak_hash(&pk);
789                if ethrex_common::Address::from_slice(&h[12..]) != sig.signer {
790                    return false;
791                }
792                let mut calldata = vec![0u8; 160];
793                calldata[..32].copy_from_slice(&msg);
794                calldata[32..64].copy_from_slice(r);
795                calldata[64..96].copy_from_slice(s);
796                calldata[96..128].copy_from_slice(qx);
797                calldata[128..160].copy_from_slice(qy);
798                let Ok(result) = crate::precompiles::p_256_verify(
799                    &Bytes::from(calldata),
800                    &mut scratch_gas,
801                    fork,
802                    crypto,
803                ) else {
804                    return false;
805                };
806                if result.len() != 32 || result[31] != 1 {
807                    return false;
808                }
809            }
810            _ => return false,
811        }
812    }
813    true
814}
815
816/// Local mempool anti-malleability policy (NOT consensus): returns `false` if any
817/// frame signature is high-s (`s > n/2`).
818///
819/// EIP-8141 verification is `signer == ecrecover(msg, v, r, s)` and does not
820/// mandate EIP-2 low-s, so a high-s signature is spec-valid and is accepted on the
821/// consensus block-execution path. But the raw signature bytes are committed to the
822/// transaction identity hash while being elided from the sig hash, so the malleated
823/// form `(v, r, s) -> (v^1, r, n-s)` (and the P256 `s -> n-s`) yields a second valid
824/// tx hash for the same logical transaction — a mempool dedup bypass. Admission
825/// rejects high-s so a malleated duplicate never occupies a pool slot; this gates
826/// only what this node admits/relays, never what it accepts in a block.
827///
828/// Signatures are assumed already structurally validated by
829/// [`validate_frame_signatures`]; malformed inputs conservatively return `false`.
830#[allow(
831    clippy::indexing_slicing,
832    reason = "signature length is checked before each fixed-offset slice"
833)]
834pub fn frame_signatures_are_low_s(signatures: &[ethrex_common::types::FrameSignature]) -> bool {
835    use ethrex_common::types::{FRAME_SIG_SCHEME_P256, FRAME_SIG_SCHEME_SECP256K1};
836    // secp256k1n/2 = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0
837    const SECP256K1_N_HALF: [u8; 32] = [
838        0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
839        0xff, 0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d, 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b,
840        0x20, 0xa0,
841    ];
842    // P-256 (secp256r1) n/2 = 0x7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8
843    const P256_N_HALF: [u8; 32] = [
844        0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
845        0xff, 0xde, 0x73, 0x7d, 0x56, 0xd3, 0x8b, 0xcf, 0x42, 0x79, 0xdc, 0xe5, 0x61, 0x7e, 0x31,
846        0x92, 0xa8,
847    ];
848    for sig in signatures {
849        match sig.scheme {
850            FRAME_SIG_SCHEME_SECP256K1 => {
851                if sig.signature.len() != 65 {
852                    return false;
853                }
854                if sig.signature[33..65] > SECP256K1_N_HALF[..] {
855                    return false;
856                }
857            }
858            FRAME_SIG_SCHEME_P256 => {
859                if sig.signature.len() != 128 {
860                    return false;
861                }
862                if sig.signature[32..64] > P256_N_HALF[..] {
863                    return false;
864                }
865            }
866            _ => return false,
867        }
868    }
869    true
870}
871
872/// Find the end of the atomic batch containing `failed_idx`, per EIP-8141:
873/// a batch is a maximal contiguous run of frames whose ATOMIC_BATCH_FLAG is
874/// set, terminated by the first frame without the flag — any mode (spec
875/// commit 8b61fdc4). Returns the index of the batch's terminating frame.
876///
877/// Exposed (hidden) for the `ethrex-test` crate's frame-batch unit tests; not
878/// part of the stable public API.
879#[doc(hidden)]
880pub fn find_batch_end(frames: &[Frame], failed_idx: usize) -> usize {
881    frames
882        .get(failed_idx..)
883        .and_then(|rest| rest.iter().position(|f| !f.is_atomic_batch()))
884        .map(|offset| failed_idx.saturating_add(offset))
885        .unwrap_or(failed_idx)
886}
887
888impl<'a> VM<'a> {
889    /// Constructs a VM, allocating a fresh 32 KB root call-frame stack.
890    ///
891    /// Hot block execution should prefer [`VM::new_pooled`], which draws the root stack from a
892    /// reusable pool instead of allocating + zeroing one per transaction.
893    pub fn new(
894        env: Environment,
895        db: &'a mut GeneralizedDatabase,
896        tx: &'a Transaction,
897        tracer: LevmCallTracer,
898        vm_type: VMType,
899        crypto: &'a dyn Crypto,
900    ) -> Result<Self, VMError> {
901        Self::new_with_root_stack(
902            env,
903            db,
904            tx,
905            tracer,
906            vm_type,
907            crypto,
908            Stack::default(),
909            Memory::default(),
910        )
911    }
912
913    /// Like [`VM::new`], but draws the root call-frame stack from `stack_pool` (falling back to a
914    /// fresh `Stack::default()` only when the pool is empty) and adopts the remaining pooled
915    /// stacks for sub-call frames. This avoids the per-tx 32 KB stack alloc+zero on a warm pool —
916    /// the dominant allocation for transfer-heavy blocks, where the root frame is the only frame.
917    ///
918    /// Pair with [`VM::reclaim_into`] after execution to return every stack (root + sub-frame)
919    /// to `stack_pool` and the root memory buffer to `memory_pool` so the next tx reuses them.
920    #[allow(clippy::too_many_arguments)]
921    pub fn new_pooled(
922        env: Environment,
923        db: &'a mut GeneralizedDatabase,
924        tx: &'a Transaction,
925        tracer: LevmCallTracer,
926        vm_type: VMType,
927        crypto: &'a dyn Crypto,
928        stack_pool: &mut Vec<Stack>,
929        memory_pool: &mut Vec<Memory>,
930    ) -> Result<Self, VMError> {
931        // Reuse a pooled stack for the root frame. `clear()` only resets the offset (no zeroing),
932        // which is sound because the EVM never reads stack slots it didn't write — the same
933        // invariant that already makes sub-frame pooling safe.
934        let mut root_stack = stack_pool.pop().unwrap_or_default();
935        root_stack.clear();
936        // Reuse a pooled root memory buffer (capacity retained from a prior tx, contents dropped).
937        // `reclaim_into` truncates it to length 0, so `resize`'s zero-fill invariant holds. Only
938        // the root buffer is pooled: sub-frame memories are `Rc` clones of it (`next_memory`).
939        let mut root_memory = memory_pool.pop().unwrap_or_default();
940        root_memory.reset_for_reuse();
941        let mut vm = Self::new_with_root_stack(
942            env,
943            db,
944            tx,
945            tracer,
946            vm_type,
947            crypto,
948            root_stack,
949            root_memory,
950        )?;
951        // Adopt the caller's pooled stacks for sub-frames; returned via `reclaim_into`.
952        mem::swap(&mut vm.stack_pool, stack_pool);
953        Ok(vm)
954    }
955
956    /// Returns this VM's reusable buffers to the caller's pools so the next transaction reuses
957    /// them instead of allocating: every stack (root call-frame stack plus any sub-frame stacks
958    /// still pooled internally) to `stack_pool`, and the root memory buffer to `memory_pool`.
959    /// Must run on both the success and error paths of [`VM::execute`].
960    pub fn reclaim_into(mut self, stack_pool: &mut Vec<Stack>, memory_pool: &mut Vec<Memory>) {
961        // Hand the internal sub-frame pool back to the caller first.
962        mem::swap(&mut self.stack_pool, stack_pool);
963        // Then reclaim the root frame's stack. Moving it out by value (VM/CallFrame have no Drop)
964        // avoids leaving a fresh 32 KB `Stack::default()` placeholder behind — which a
965        // `mem::take`/`mem::replace` against an empty pool would force, defeating the win on
966        // exactly the transfer-only blocks (no sub-frames ever seed the pool) we target.
967        let mut root_stack = self.current_call_frame.stack;
968        root_stack.clear();
969        stack_pool.push(root_stack);
970        // Reclaim the root memory buffer with its grown capacity. `reset_for_reuse` truncates it
971        // to length 0 (capacity kept) so the next tx's `resize` zero-fills correctly.
972        //
973        // Every call frame shares the same `Rc<RefCell<Vec<u8>>>` buffer, so on the error path the
974        // ancestor frames left in `call_frames` (error propagation unwinds out of `execute` without
975        // popping them) still hold clones. Drop them first so the buffer is `Rc`-unique on BOTH
976        // paths before we clear it — otherwise the clear would propagate to a frame still holding a
977        // reference. `CallFrame` has no `Drop` and these frames are never read again, so dropping
978        // them early is free.
979        self.call_frames.clear();
980        let mut root_memory = self.current_call_frame.memory;
981        debug_assert_eq!(
982            Rc::strong_count(&root_memory.buffer),
983            1,
984            "root memory buffer must be Rc-unique at reclaim; a frame is still holding it and \
985             would observe the reset_for_reuse clear",
986        );
987        root_memory.reset_for_reuse();
988        memory_pool.push(root_memory);
989    }
990
991    #[allow(clippy::too_many_arguments)]
992    fn new_with_root_stack(
993        env: Environment,
994        db: &'a mut GeneralizedDatabase,
995        tx: &'a Transaction,
996        tracer: LevmCallTracer,
997        vm_type: VMType,
998        crypto: &'a dyn Crypto,
999        root_stack: Stack,
1000        root_memory: Memory,
1001    ) -> Result<Self, VMError> {
1002        db.tx_backup = None; // If BackupHook is enabled, it will contain backup at the end of tx execution.
1003
1004        let mut substate = Substate::initialize(&env, tx)?;
1005
1006        let (callee, is_create) = Self::get_tx_callee(tx, db, &env, &mut substate)?;
1007
1008        let fork = env.config.fork;
1009
1010        #[expect(
1011            clippy::arithmetic_side_effects,
1012            reason = "byte-count constants are small (<200) and cpsb is bounded by block_gas_limit/year formula"
1013        )]
1014        let (cpsb, state_gas_new_account, state_gas_storage_set, state_gas_auth_base) =
1015            if fork >= Fork::Amsterdam {
1016                let cpsb = compute_cost_per_state_byte(env.block_gas_limit);
1017                (
1018                    cpsb,
1019                    STATE_BYTES_PER_NEW_ACCOUNT * cpsb,
1020                    STATE_BYTES_PER_STORAGE_SET * cpsb,
1021                    STATE_BYTES_PER_AUTH_BASE * cpsb,
1022                )
1023            } else {
1024                (0, 0, 0, 0)
1025            };
1026
1027        // Derive whether the top-level backup must be preserved from the installed hooks rather
1028        // than from `vm_type`. The flag's real meaning is "a hook reads the top-level backup in
1029        // `finalize_execution`," which today is the `BackupHook` on L2 / stateless. Deriving it
1030        // keeps the flag correct if hook wiring ever changes (e.g. a future `vm_type` that adds
1031        // `BackupHook`, or L2 dropping it), and `add_hook` keeps it in sync for the `BackupHook`
1032        // that `stateless_execute` installs after construction. L1 block execution installs no
1033        // `BackupHook` (see `l1_hooks`), so the backup is dead once the cache is restored.
1034        let hooks = get_hooks(&vm_type);
1035        let preserve_top_level_backup = hooks
1036            .iter()
1037            .any(|hook| hook.borrow().reads_top_level_backup());
1038
1039        let mut vm = Self {
1040            call_frames: Vec::new(),
1041            substate,
1042            db,
1043            tx,
1044            hooks,
1045            storage_original_values: FxHashMap::default(),
1046            tracer,
1047            opcode_tracer: LevmOpcodeTracer::disabled(),
1048            validation_observer: ValidationObserver::disabled(),
1049            debug_mode: DebugMode::disabled(),
1050            stack_pool: Vec::new(),
1051            vm_type,
1052            preserve_top_level_backup,
1053            state_gas_used: 0,
1054            state_gas_reservoir: 0,
1055            state_gas_reservoir_initial: 0,
1056            state_gas_spill: 0,
1057            cost_per_state_byte: cpsb,
1058            state_gas_new_account,
1059            state_gas_storage_set,
1060            state_gas_auth_base,
1061            intrinsic_state_gas: 0,
1062            value_new_account_charged: false,
1063            prep_baseline_state_gas: 0,
1064            prep_baseline_reservoir: 0,
1065            prep_baseline_state_gas_spill: 0,
1066            prep_region_backup_marker: PrepareRegionBackupMarker::default(),
1067            pending_prep_oog: false,
1068            current_call_frame: CallFrame::new(
1069                env.origin,
1070                callee,
1071                Address::default(), // Will be assigned at the end of prepare_execution
1072                Code::default(),    // Will be assigned at the end of prepare_execution
1073                tx.value(),
1074                tx.data().clone(),
1075                false,
1076                env.gas_limit,
1077                0,
1078                true,
1079                is_create,
1080                0,
1081                0,
1082                root_stack,
1083                root_memory,
1084            ),
1085            env,
1086            frame_tx_context: None,
1087            opcode_table: VM::build_opcode_table(fork),
1088            crypto,
1089        };
1090
1091        let call_type = if is_create {
1092            CallType::CREATE
1093        } else {
1094            CallType::CALL
1095        };
1096        vm.tracer.enter(
1097            call_type,
1098            vm.env.origin,
1099            callee,
1100            vm.tx.value(),
1101            vm.env.gas_limit,
1102            vm.tx.data(),
1103        );
1104
1105        #[cfg(feature = "debug")]
1106        {
1107            // Enable debug mode for printing in Solidity contracts.
1108            vm.debug_mode.enabled = true;
1109        }
1110
1111        Ok(vm)
1112    }
1113
1114    fn add_hook(&mut self, hook: impl Hook + 'static) {
1115        // Keep `preserve_top_level_backup` in sync: a hook added after construction (e.g. the
1116        // `BackupHook` in `stateless_execute`) may read the top-level backup in `finalize_execution`.
1117        self.preserve_top_level_backup |= hook.reads_top_level_backup();
1118        self.hooks.push(Rc::new(RefCell::new(hook)));
1119    }
1120
1121    /// EIP-8037: Charge state gas, drawing from reservoir first, spilling to gas_remaining if exhausted.
1122    ///
1123    /// Must only be called for Amsterdam+ forks. All call sites must guard with
1124    /// `fork >= Fork::Amsterdam` before invoking this method.
1125    #[expect(
1126        clippy::arithmetic_side_effects,
1127        reason = "arithmetic proven safe by min()"
1128    )]
1129    pub fn increase_state_gas(&mut self, gas: u64) -> Result<(), VMError> {
1130        debug_assert!(
1131            self.env.config.fork >= Fork::Amsterdam,
1132            "increase_state_gas called pre-Amsterdam"
1133        );
1134        // Draw from reservoir first; only spill to gas_remaining if reservoir exhausted
1135        let from_reservoir = self.state_gas_reservoir.min(gas);
1136        // Safe: from_reservoir <= gas
1137        let spill = gas - from_reservoir;
1138        if spill > 0 {
1139            // Charge spill from gas_remaining first — if OOG, return early
1140            // without mutating reservoir or state_gas_used (matches EELS behavior)
1141            self.current_call_frame.increase_consumed_gas(spill)?;
1142        }
1143        // Safe: from_reservoir = min(reservoir, gas) so reservoir >= from_reservoir
1144        self.state_gas_reservoir -= from_reservoir;
1145        // Only increment state_gas_used AFTER the charge succeeds.
1146        // state_gas_used is i64; tx gas_limit caps charges well below i64::MAX.
1147        self.state_gas_used = self
1148            .state_gas_used
1149            .checked_add(i64::try_from(gas).map_err(|_| InternalError::Overflow)?)
1150            .ok_or(InternalError::Overflow)?;
1151        // Track the spill for block-accounting: EELS charge_state_gas spills
1152        // don't count toward regular_gas_used for the regular dimension.
1153        self.state_gas_spill = self
1154            .state_gas_spill
1155            .checked_add(spill)
1156            .ok_or(InternalError::Overflow)?;
1157        // Per-frame spill: EELS charge_state_gas does `frame_state_gas_spilled += remainder`.
1158        // LIFO refund source; propagated to parent on child success.
1159        self.current_call_frame.frame_state_gas_spilled = self
1160            .current_call_frame
1161            .frame_state_gas_spilled
1162            .checked_add(spill)
1163            .ok_or(InternalError::Overflow)?;
1164        Ok(())
1165    }
1166
1167    /// EIP-8037 `credit_state_gas_refund`: refund `amount` LIFO, mirroring EELS. The portion
1168    /// spilled past the reservoir into this frame's `gas_remaining` (`frame_state_gas_spilled`)
1169    /// is returned to `gas_remaining` first; only the remainder flows to the shared reservoir.
1170    /// `state_gas_used` drops by the full `amount` (may go negative when the matching charge lives
1171    /// in an ancestor frame). Block accounting: both spill counters drop by the
1172    /// `gas_remaining`-credited portion only, never the full `amount`. Amsterdam+ only.
1173    #[expect(
1174        clippy::arithmetic_side_effects,
1175        reason = "subtractions proven safe by min()"
1176    )]
1177    pub fn credit_state_gas_refund(&mut self, amount: u64) -> Result<(), VMError> {
1178        debug_assert!(
1179            self.env.config.fork >= Fork::Amsterdam,
1180            "credit_state_gas_refund called pre-Amsterdam"
1181        );
1182        // LIFO: drain the frame's spill (gas borrowed from gas_remaining) first.
1183        let from_gas_left = self.current_call_frame.frame_state_gas_spilled.min(amount);
1184        // Return the spilled portion to gas_remaining (i64).
1185        self.current_call_frame.gas_remaining = self
1186            .current_call_frame
1187            .gas_remaining
1188            .checked_add(i64::try_from(from_gas_left).map_err(|_| InternalError::Overflow)?)
1189            .ok_or(InternalError::Overflow)?;
1190        // Safe: from_gas_left = min(spill, amount) <= frame_state_gas_spilled.
1191        self.current_call_frame.frame_state_gas_spilled -= from_gas_left;
1192        // Block accounting: the refilled spill is no longer regular gas.
1193        self.state_gas_spill = self
1194            .state_gas_spill
1195            .checked_sub(from_gas_left)
1196            .ok_or(InternalError::Underflow)?;
1197        // The remainder of the refund flows into the shared reservoir.
1198        // Safe: from_gas_left = min(spill, amount) <= amount.
1199        let to_reservoir = amount - from_gas_left;
1200        self.state_gas_reservoir = self
1201            .state_gas_reservoir
1202            .checked_add(to_reservoir)
1203            .ok_or(InternalError::Overflow)?;
1204        // state_gas_used always drops by the full amount (may go negative).
1205        self.state_gas_used = self
1206            .state_gas_used
1207            .checked_sub(i64::try_from(amount).map_err(|_| InternalError::Overflow)?)
1208            .ok_or(InternalError::Overflow)?;
1209        Ok(())
1210    }
1211
1212    /// Refund the EIP-8037 new-account state gas when `charged` is true. Used by the
1213    /// CALL paths where a value-bearing call to an empty account charged the new-account
1214    /// state gas but no account ends up created (insufficient balance, max depth, child
1215    /// revert / failed precompile).
1216    #[inline]
1217    pub fn refund_new_account_state_gas(&mut self, charged: bool) -> Result<(), VMError> {
1218        if charged {
1219            self.credit_state_gas_refund(self.state_gas_new_account)?;
1220        }
1221        Ok(())
1222    }
1223
1224    /// EIP-8037 `refill_frame_state_gas`: roll back this frame's state gas in LIFO
1225    /// order on revert or exceptional halt, mirroring EELS `refill_frame_state_gas`.
1226    ///
1227    /// `entry` is the value of `state_gas_used` when this frame began executing
1228    /// (`current_call_frame.state_gas_used_at_entry`). The frame's net charge is
1229    /// `frame_used = state_gas_used - entry`. Of that, `frame_state_gas_spilled` was
1230    /// drawn from `gas_remaining` (spilled past the reservoir) and the remainder came
1231    /// from the reservoir. LIFO refill returns the spilled portion to `gas_remaining`
1232    /// first and the rest to the reservoir, restoring the exact pools the charges drew
1233    /// from. `state_gas_used` is rolled back to `entry` and the per-frame spill counter
1234    /// is cleared.
1235    ///
1236    /// Revert-vs-halt equivalence (load-bearing): on revert, the spilled gas returns to
1237    /// `gas_remaining` (raising the sender refund / lowering raw_consumed) while
1238    /// `state_gas_spill` drops by the same amount, so the regular dimension in
1239    /// `refund_sender` (default_hook) drops by exactly the refilled spill. On exceptional
1240    /// halt the caller subsequently sets `gas_remaining = 0` and burns it to the regular
1241    /// dimension — but `state_gas_spill` was already decremented here, so the spilled gas
1242    /// stays counted as regular. Both paths are correct.
1243    ///
1244    /// Must only be called for Amsterdam+ forks.
1245    pub fn refill_frame_state_gas(&mut self, entry: i64) -> Result<(), VMError> {
1246        debug_assert!(
1247            self.env.config.fork >= Fork::Amsterdam,
1248            "refill_frame_state_gas called pre-Amsterdam"
1249        );
1250        // The frame's net state-gas charge since it began executing. May be
1251        // negative when the frame's inline refunds (e.g. an SSTORE clearing a
1252        // slot an ancestor set) exceeded its own gross charges.
1253        let frame_used = self
1254            .state_gas_used
1255            .checked_sub(entry)
1256            .ok_or(InternalError::Underflow)?;
1257        let spilled = self.current_call_frame.frame_state_gas_spilled;
1258        // LIFO invariant: any remaining spill is undrained own-charge, so it
1259        // implies frame_used >= 0. A net-negative frame_used only arises after
1260        // credit_state_gas_refund has already drained all spill (spilled == 0).
1261        debug_assert!(
1262            frame_used >= 0 || spilled == 0,
1263            "negative frame_used with positive spill violates LIFO invariant \
1264             (frame_used={frame_used}, spilled={spilled})"
1265        );
1266        // LIFO: return the spilled portion (borrowed from gas_remaining) first.
1267        self.current_call_frame.gas_remaining = self
1268            .current_call_frame
1269            .gas_remaining
1270            .checked_add(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1271            .ok_or(InternalError::Overflow)?;
1272        // The remainder (drawn from the reservoir) flows back to the reservoir.
1273        let to_reservoir = frame_used
1274            .checked_sub(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1275            .ok_or(InternalError::Overflow)?;
1276        // `to_reservoir` is negative in the cross-ancestor refund case
1277        // (frame_used < 0); clamp so the reservoir never goes negative.
1278        let reservoir_signed =
1279            i64::try_from(self.state_gas_reservoir).map_err(|_| InternalError::Overflow)?;
1280        self.state_gas_reservoir = u64::try_from(
1281            reservoir_signed
1282                .checked_add(to_reservoir)
1283                .ok_or(InternalError::Overflow)?
1284                .max(0),
1285        )
1286        .map_err(|_| InternalError::Overflow)?;
1287        // Roll back state_gas_used to the frame's entry baseline.
1288        self.state_gas_used = entry;
1289        // Block accounting: the refilled spill is no longer regular gas.
1290        self.state_gas_spill = self
1291            .state_gas_spill
1292            .checked_sub(spilled)
1293            .ok_or(InternalError::Underflow)?;
1294        self.current_call_frame.frame_state_gas_spilled = 0;
1295        Ok(())
1296    }
1297
1298    /// EIP-8037: enters the atomic prepare region (EELS `interpreter.py`'s depth-0
1299    /// `try` around `set_delegation` + `prepare_dispatch`, `interpreter.py:353-375`).
1300    /// Must be called in `prepare_execution`, after the sender nonce bump and fee
1301    /// deduction (those survive a region rollback) but before the type-4 auth
1302    /// handling (the first region charge). Captures the pre-region state-gas
1303    /// baseline and the `call_frame_backup` key-space so `fail_prepare_region` can
1304    /// later undo exactly the region's writes.
1305    pub fn enter_prepare_region(&mut self) {
1306        self.prep_baseline_state_gas = self.current_call_frame.state_gas_used_at_entry;
1307        self.prep_baseline_reservoir = self.state_gas_reservoir;
1308        self.prep_baseline_state_gas_spill = self.state_gas_spill;
1309        let backup = &self.current_call_frame.call_frame_backup;
1310        let accounts: FxHashSet<Address> = backup.original_accounts_info.keys().copied().collect();
1311        let storage: FxHashSet<Address> = backup
1312            .original_account_storage_slots
1313            .keys()
1314            .copied()
1315            .collect();
1316        let code_hashes_len = backup.inserted_code_hashes.len();
1317        // Capture the region-entry state of every already-backed-up account so a
1318        // self-sponsored EIP-7702 authorization (or any in-region write to a
1319        // pre-region-touched account) can be reverted without disturbing its
1320        // pre-region nonce/fee writes. See `PrepareRegionBackupMarker::entry_state`.
1321        let entry_state: FxHashMap<Address, LevmAccount> = accounts
1322            .iter()
1323            .filter_map(|address| {
1324                self.db
1325                    .current_accounts_state
1326                    .get(address)
1327                    .map(|account| (*address, account.clone()))
1328            })
1329            .collect();
1330        let bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1331        self.prep_region_backup_marker = PrepareRegionBackupMarker {
1332            accounts,
1333            storage,
1334            code_hashes_len,
1335            entry_state,
1336            bal_checkpoint,
1337        };
1338    }
1339
1340    /// EIP-8037: rolls back the atomic prepare region on an internal OOG from any of
1341    /// its charges (7702 auth, CREATE/value `NEW_ACCOUNT`, recipient delegation-resolve).
1342    /// Restores every `call_frame_backup` entry added since `enter_prepare_region`
1343    /// (leaving the earlier sender nonce-bump / fee-deduction entries untouched),
1344    /// refills the frame's state gas back to the pre-region baseline, and sets
1345    /// `pending_prep_oog` so `run_execution` turns this into a full-gas revert
1346    /// instead of a tx-level rejection `Err` (which would wrongly invalidate the
1347    /// block). Mirrors EELS `restore_tx_state(prep_snapshot)` + `refill_frame_state_gas`
1348    /// (`interpreter.py:366-374`).
1349    pub fn fail_prepare_region(&mut self) {
1350        let marker = std::mem::take(&mut self.prep_region_backup_marker);
1351        let mut backup = std::mem::take(&mut self.current_call_frame.call_frame_backup);
1352
1353        // Restore + drop every account backup entry added during the region.
1354        let region_accounts: Vec<Address> = backup
1355            .original_accounts_info
1356            .keys()
1357            .filter(|address| !marker.accounts.contains(*address))
1358            .copied()
1359            .collect();
1360        for address in region_accounts {
1361            if let Some(account) = backup.original_accounts_info.remove(&address)
1362                && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1363            {
1364                current_account.info = account.info;
1365                current_account.status = account.status;
1366                current_account.has_storage = account.has_storage;
1367                current_account.exists = account.exists;
1368            }
1369        }
1370
1371        // Restore + drop every storage backup entry added during the region.
1372        let region_storage: Vec<Address> = backup
1373            .original_account_storage_slots
1374            .keys()
1375            .filter(|address| !marker.storage.contains(*address))
1376            .copied()
1377            .collect();
1378        for address in region_storage {
1379            if let Some(slots) = backup.original_account_storage_slots.remove(&address)
1380                && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1381            {
1382                for (key, value) in slots {
1383                    current_account.storage.insert(key, value);
1384                }
1385            }
1386        }
1387
1388        // Evict codes the region inserted, mirroring `restore_cache_state`: a stale
1389        // by-hash cache entry would hide a later read of the same hash from the store.
1390        for code_hash in backup
1391            .inserted_code_hashes
1392            .split_off(marker.code_hashes_len)
1393        {
1394            self.db.codes.remove(&code_hash);
1395        }
1396
1397        self.current_call_frame.call_frame_backup = backup;
1398
1399        // Revert in-region writes to accounts that were already backed up before the
1400        // region (the marker filter above leaves these untouched to preserve their
1401        // pre-region nonce/fee writes, but first-write-wins backup means an in-region
1402        // write — e.g. a self-sponsored EIP-7702 authorization writing the sender's
1403        // delegation code + auth nonce bump — created no new backup entry). Restoring
1404        // to the region-entry snapshot undoes the in-region write while keeping the
1405        // pre-region writes baked into that snapshot. Mirrors EELS `restore_tx_state`.
1406        for (address, entry_account) in marker.entry_state {
1407            if let Some(current) = self.db.current_accounts_state.get_mut(&address) {
1408                current.info = entry_account.info;
1409                current.status = entry_account.status;
1410                current.has_storage = entry_account.has_storage;
1411                current.exists = entry_account.exists;
1412            }
1413        }
1414
1415        // Roll back the BAL recorder to region entry so an applied-then-reverted
1416        // delegation's code/nonce changes are discarded (demoted to an access-only
1417        // touch, matching EELS `restore_tx_state`). `restore` preserves touched
1418        // addresses — including the pre-charge authority touches recorded during
1419        // `set_delegation` — so a reverted authority still appears as an access.
1420        if let Some(checkpoint) = marker.bal_checkpoint
1421            && let Some(recorder) = self.db.bal_recorder.as_mut()
1422        {
1423            recorder.restore(checkpoint);
1424        }
1425
1426        // Rewind the state-gas machinery to the pre-region snapshot. The
1427        // `set_delegation` auth lock-in re-seeds `state_gas_used_at_entry` and zeroes
1428        // the frame spill, so `refill_frame_state_gas` (which derives the reservoir
1429        // credit from the frame spill) would leave the reservoir over-credited by the
1430        // locked-in auth state gas. Restore `state_gas_used`, the reservoir, and the
1431        // cumulative spill to the values captured by `enter_prepare_region`, and clear
1432        // the frame spill — this fully reverts the region's state charges (auth +
1433        // prepare-dispatch) regardless of the lock-in. Mirrors EELS
1434        // `restore_tx_state(prep_snapshot)` + `message.state_gas_reservoir = prep_reservoir`
1435        // (`interpreter.py:365-369`). `gas_remaining` is left as-is: the failing charge
1436        // already drove it negative, so `run_execution` burns all gas (EELS
1437        // `evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`).
1438        self.state_gas_used = self.prep_baseline_state_gas;
1439        self.state_gas_reservoir = self.prep_baseline_reservoir;
1440        self.state_gas_spill = self.prep_baseline_state_gas_spill;
1441        self.current_call_frame.frame_state_gas_spilled = 0;
1442        self.pending_prep_oog = true;
1443    }
1444
1445    /// Executes a whole external transaction. Performing validations at the beginning.
1446    pub fn execute(&mut self) -> Result<ExecutionReport, VMError> {
1447        // Detect frame transaction and branch to specialized execution
1448        if self.tx.tx_type() == TxType::Frame {
1449            return self.execute_frame_tx();
1450        }
1451
1452        if let Err(e) = self.prepare_execution() {
1453            // Restore cache to state previous to this Tx execution because this Tx is invalid.
1454            // Consume the backup unless a `BackupHook` will read it (L2 / stateless); on L1 it
1455            // is dead once the cache is restored.
1456            if self.preserve_top_level_backup {
1457                self.restore_cache_state()?;
1458            } else {
1459                self.restore_cache_state_consuming()?;
1460            }
1461            return Err(e);
1462        }
1463
1464        // Clear callframe backup so that changes made in prepare_execution are written in stone.
1465        // We want to apply these changes even if the Tx reverts. E.g. Incrementing sender nonce
1466        self.current_call_frame.call_frame_backup.clear();
1467
1468        // Empty bytecode would only execute STOP; skip the dispatch loop.
1469        // The BAL checkpoint below is intentionally skipped: a codeless transfer cannot
1470        // fail past this point and has no inner calls, so there's nothing to roll back.
1471        if self.is_simple_transfer_fast_path() {
1472            // EIP-8037: no `refill_frame_state_gas` needed here — a codeless transfer always
1473            // succeeds, runs no opcodes, and charges no execution state gas, so the frame's
1474            // `frame_state_gas_spilled` is 0 and `state_gas_used` equals its entry baseline.
1475            #[expect(clippy::as_conversions, reason = "gas_remaining is non-negative here")]
1476            let gas_used = self
1477                .current_call_frame
1478                .gas_limit
1479                .checked_sub(self.current_call_frame.gas_remaining as u64)
1480                .ok_or(InternalError::Underflow)?;
1481            let context_result = ContextResult {
1482                result: TxResult::Success,
1483                gas_used,
1484                gas_spent: gas_used,
1485                output: Bytes::new(),
1486            };
1487            return self.finalize_execution(context_result);
1488        }
1489
1490        // EIP-7928: Take a BAL checkpoint AFTER clearing the backup. This captures the state
1491        // after prepare_execution (nonce increment, etc.) but before actual execution.
1492        // When the top-level call fails, we restore to this checkpoint so that inner call
1493        // state changes (like value transfers) are reverted from the BAL.
1494        self.current_call_frame.call_frame_backup.bal_checkpoint =
1495            self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1496
1497        // EIP-8037: skip the CREATE nonce bump / endowment / collision check when the
1498        // atomic prepare region OOG'd (`pending_prep_oog`). EELS raises in
1499        // `prepare_dispatch` before `process_create_message` runs, so the contract is
1500        // never created — `run_execution` below emits the full-gas revert. Bumping the
1501        // nonce here would leave a phantom nonce=1 the region rollback can't reach.
1502        if !self.pending_prep_oog && self.is_create()? {
1503            // Create contract, reverting the Tx if address is already occupied.
1504            if let Some(context_result) = self.handle_create_transaction()? {
1505                let report = self.finalize_execution(context_result)?;
1506                return Ok(report);
1507            }
1508        }
1509
1510        self.substate.push_backup();
1511        let context_result = self.run_execution()?;
1512
1513        let report = self.finalize_execution(context_result)?;
1514
1515        Ok(report)
1516    }
1517
1518    /// Execute a frame transaction (EIP-8141).
1519    /// This bypasses the normal prepare/finalize hooks and orchestrates per-frame execution.
1520    fn execute_frame_tx(&mut self) -> Result<ExecutionReport, VMError> {
1521        use crate::errors::TxResult;
1522
1523        // EIP-8141 fork gating: reject frame transactions observed in a block or
1524        // submitted to any non-mempool entry point before Hegota activates.
1525        if self.env.config.fork < Fork::Hegota {
1526            return Err(VMError::TxValidation(
1527                crate::errors::TxValidationError::FrameTxPreFork,
1528            ));
1529        }
1530
1531        let frame_tx = match &self.tx {
1532            Transaction::FrameTransaction(ft) => ft.clone(),
1533            _ => unreachable!(),
1534        };
1535
1536        // Simplified validation (skip balance deduction, nonce increment, value transfer, EOA check)
1537        // Keep: gas limit checks, fee validation, nonce mismatch check.
1538        // The EOA-check skip is required by EIP-8141 §Transaction origination:
1539        // EIP-3607 must not apply to frame transactions, so the sender may have
1540        // contract code (SENDER frames legitimately originate from contract
1541        // accounts).
1542        let sender = frame_tx.sender;
1543
1544        // Validate static constraints (frame count, reserved modes, atomic batch flags)
1545        if let Err(_e) = frame_tx.validate_static_constraints() {
1546            return Err(VMError::TxValidation(
1547                crate::errors::TxValidationError::InvalidFrameTransaction,
1548            ));
1549        }
1550
1551        // Check nonce matches
1552        let sender_info = self.db.get_account(sender)?.info.clone();
1553        if sender_info.nonce != frame_tx.nonce {
1554            return Err(VMError::TxValidation(
1555                crate::errors::TxValidationError::NonceMismatch {
1556                    expected: sender_info.nonce,
1557                    actual: frame_tx.nonce,
1558                },
1559            ));
1560        }
1561
1562        // Check priority fee <= max fee
1563        if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
1564            return Err(VMError::TxValidation(
1565                crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
1566                    priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
1567                    max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
1568                },
1569            ));
1570        }
1571
1572        // Check max_fee >= base_fee
1573        if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
1574            return Err(VMError::TxValidation(
1575                crate::errors::TxValidationError::InsufficientMaxFeePerGas,
1576            ));
1577        }
1578
1579        // EIP-4844 INSUFFICIENT_MAX_FEE_PER_BLOB_GAS: a blob-carrying tx whose
1580        // max_fee_per_blob_gas is below the block's base blob fee is invalid. The
1581        // frame path is self-contained and never runs the default hook's
1582        // validate_max_fee_per_blob_gas, so it is enforced here. APPROVE charges
1583        // the blob fee at the base rate unconditionally, so without this a frame tx
1584        // below the base blob fee would execute and silently overpay rather than be
1585        // rejected — a divergence from a conformant client that rejects it.
1586        if !frame_tx.blob_versioned_hashes.is_empty()
1587            && frame_tx.max_fee_per_blob_gas < self.env.base_blob_fee_per_gas
1588        {
1589            return Err(VMError::TxValidation(
1590                crate::errors::TxValidationError::InsufficientMaxFeePerBlobGas {
1591                    base_fee_per_blob_gas: self.env.base_blob_fee_per_gas,
1592                    tx_max_fee_per_blob_gas: frame_tx.max_fee_per_blob_gas,
1593                },
1594            ));
1595        }
1596
1597        // Initialize FrameTxContext
1598        let sig_hash = frame_tx.compute_sig_hash();
1599        let total_gas_limit = frame_tx.total_gas_limit();
1600        self.frame_tx_context = Some(FrameTxContext {
1601            sender_approved: false,
1602            payer_address: None,
1603            frame_results: Vec::new(),
1604            current_frame_index: 0,
1605            sig_hash,
1606            tx: frame_tx.clone(),
1607            approve_called_in_current_frame: false,
1608            total_gas_limit,
1609        });
1610
1611        // EIP-8141 (spec commit fe0940cae2): every outer signature must validate
1612        // before any frame executes; otherwise the whole transaction is invalid.
1613        if !validate_frame_signatures(
1614            &frame_tx.signatures,
1615            sig_hash,
1616            self.env.config.fork,
1617            self.crypto,
1618        ) {
1619            return Err(VMError::TxValidation(
1620                crate::errors::TxValidationError::InvalidFrameTransaction,
1621            ));
1622        }
1623
1624        // Tx-level rollback accumulator: if the tx is later declared invalid
1625        // after frames committed, restore `db.current_accounts_state` so the
1626        // payload builder (which reuses the shared db across txs) sees no
1627        // residue — same Err contract as non-frame `execute()`. The per-frame
1628        // backup is cleared between independent frames (and at batch entry), so
1629        // each frame's original values are absorbed here (first-seen-wins)
1630        // before that clear destroys them. Substate is per-VM and discarded on
1631        // Err, so it needs no snapshot.
1632        let mut tx_level_backup = crate::call_frame::CallFrameBackup {
1633            bal_checkpoint: self.db.bal_recorder.as_ref().map(|r| r.checkpoint()),
1634            ..Default::default()
1635        };
1636
1637        // ENTRY_POINT address used as caller for DEFAULT/VERIFY frames
1638        let entry_point = ethrex_common::types::frame_tx_entry_point();
1639
1640        let mut all_logs: Vec<Log> = Vec::new();
1641        let sum_frame_gas_limits: u64 = frame_tx
1642            .frames
1643            .iter()
1644            .map(|f| f.gas_limit)
1645            .fold(0u64, |acc, g| acc.saturating_add(g));
1646        let intrinsic_gas = total_gas_limit.saturating_sub(sum_frame_gas_limits);
1647        let mut total_gas_used: u64 = intrinsic_gas;
1648        let mut tx_invalid = false;
1649
1650        // Atomic batching state: track whether we're inside a batch and
1651        // which frames belong to it so we can revert them all on failure.
1652        let mut in_atomic_batch = false;
1653        let mut batch_start_idx: usize = 0;
1654        let mut batch_logs_start: usize = 0;
1655        let mut batch_approval_snapshot: (bool, Option<Address>) = (false, None);
1656        // EIP-8037: snapshot the shared `state_gas_used` at batch entry so a batch
1657        // revert (which unrolls every in-batch frame's state) also drops the state
1658        // gas those frames accumulated.
1659        let mut state_gas_used_at_batch_entry: i64 = 0;
1660        let mut skip_until_batch_end: Option<usize> = None; // skip remaining frames in a failed batch
1661
1662        // Execute frames sequentially
1663        for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
1664            // If we're skipping frames due to an atomic batch revert, record
1665            // the frame with status SKIPPED. Per EIP-8141 (spec line 185), the
1666            // gas allotted to skipped frames is refunded at the end of the
1667            // transaction, so we record `gas_used = 0` and do NOT add the
1668            // frame's `gas_limit` to `total_gas_used`.
1669            //
1670            // Note (EIP-8141 @ 0b197156): an expiry verifier frame has flags
1671            // == 0, so it can only be a batch TERMINATOR, never a flagged
1672            // member. A failed batch therefore skips a trailing expiry frame
1673            // and its deadline is not checked at execution time. This is
1674            // benign, not a bypass: `compute_sig_hash` commits to the full
1675            // frame layout (modes, flags incl. the atomic-batch flag, targets,
1676            // and the expiry deadline), and the VERIFY signature is recovered
1677            // over that hash — so no relayer/proposer can wrap a signed tx's
1678            // expiry frame in a failing batch. Only the sender can build this
1679            // layout, and doing so merely disarms their own expiry. The normal
1680            // pattern (a standalone expiry VERIFY frame, not batched) is fully
1681            // enforced. The skip itself is spec-mandated batch semantics; do
1682            // not change it unilaterally — that would be a consensus divergence.
1683            if let Some(end_idx) = skip_until_batch_end {
1684                if frame_idx <= end_idx {
1685                    let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
1686                        InternalError::Custom("missing frame tx context".to_string()),
1687                    ))?;
1688                    ctx.current_frame_index = frame_idx;
1689                    ctx.frame_results.push((
1690                        ethrex_common::types::FRAME_RECEIPT_STATUS_SKIPPED,
1691                        0,
1692                        Vec::new(),
1693                    ));
1694                    if frame_idx == end_idx {
1695                        skip_until_batch_end = None;
1696                        in_atomic_batch = false;
1697                    }
1698                    continue;
1699                }
1700                skip_until_batch_end = None;
1701                in_atomic_batch = false;
1702            }
1703
1704            // Clear the outer call-frame backup at the start of each independent
1705            // frame so that a later frame's failure-path `restore_cache_state()`
1706            // only reverts that frame's own effects — not APPROVE/state deltas
1707            // produced by earlier, already-successful frames. Inside an open
1708            // atomic batch we keep accumulating, since a batch revert needs to
1709            // undo every in-batch frame's effects together.
1710            if !in_atomic_batch {
1711                // Absorb this frame's originals into the tx-level accumulator
1712                // before clearing, so an invalid-tx exit can still roll back
1713                // every committed frame's state (see `tx_level_backup`).
1714                tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
1715                self.current_call_frame.call_frame_backup.clear();
1716            }
1717
1718            // Start a new atomic batch if this frame has the batch flag
1719            // and we're not already in one.
1720            if !in_atomic_batch && frame.is_atomic_batch() {
1721                self.substate.push_backup(); // batch-level snapshot
1722                // The outer call-frame backup is already empty here: the
1723                // `!in_atomic_batch` block above absorbed it into
1724                // `tx_level_backup` and cleared it on entry to this frame, so
1725                // the batch starts accumulating a clean, self-contained set of
1726                // state changes that batch-revert can undo wholesale.
1727                in_atomic_batch = true;
1728                batch_start_idx = frame_idx;
1729                batch_logs_start = all_logs.len();
1730                state_gas_used_at_batch_entry = self.state_gas_used;
1731                // Snapshot approvals at batch entry: a batch revert must also
1732                // roll back approvals granted inside the batch (their balance
1733                // and nonce effects are reverted with the substate).
1734                batch_approval_snapshot = self
1735                    .frame_tx_context
1736                    .as_ref()
1737                    .map(|c| c.approval_snapshot())
1738                    .unwrap_or((false, None));
1739            }
1740
1741            let ctx =
1742                self.frame_tx_context
1743                    .as_mut()
1744                    .ok_or(VMError::Internal(InternalError::Custom(
1745                        "missing frame tx context".to_string(),
1746                    )))?;
1747            ctx.current_frame_index = frame_idx;
1748            ctx.approve_called_in_current_frame = false;
1749
1750            let target = frame.target.unwrap_or(sender);
1751
1752            // Determine caller and static mode per frame mode
1753            let (caller, is_static) = match frame.execution_mode() {
1754                FrameMode::Default => (entry_point, false),
1755                FrameMode::Verify => (entry_point, true),
1756                FrameMode::Sender => {
1757                    // SENDER mode requires sender_approved
1758                    let ctx = self.frame_tx_context.as_ref().ok_or(VMError::Internal(
1759                        InternalError::Custom("missing frame tx context".to_string()),
1760                    ))?;
1761                    if !ctx.sender_approved {
1762                        tx_invalid = true;
1763                        break;
1764                    }
1765                    (sender, false)
1766                }
1767            };
1768
1769            // Set env.origin for this frame (ORIGIN opcode reads this)
1770            self.env.origin = caller;
1771
1772            // Resolve any EIP-7702 delegation at the resolved target. For a non-delegated
1773            // target this is equivalent to `db.get_account_code(target)`; for a delegated
1774            // target it follows the 0xef0100 || addr indicator and returns the delegatee's
1775            // bytecode plus the resolved code_address. EIP-8141 §Execution step 1 requires
1776            // delegated targets to execute the delegatee's code while keeping ADDRESS/storage
1777            // tied to the delegator — which is why `to` below stays `target` but the
1778            // CallFrame receives the resolved `code_address`. Mirrors the pattern used at
1779            // top-level tx entry in default_hook::set_bytecode_and_code_address.
1780            //
1781            // access_cost is intentionally discarded: this frame entry is analogous to a
1782            // top-level tx entry (a call from 0xaa / tx.sender, not a CALL opcode), and
1783            // default_hook.rs drops the same cost there. EIP-8141 §Execution is silent on
1784            // billing the 7702 access cost for `resolved_target`, so we keep frame-entry
1785            // behavior consistent with tx-entry behavior.
1786            let (is_delegation_7702, _access_cost, code_address, bytecode) =
1787                crate::utils::eip7702_get_code(
1788                    self.db,
1789                    &mut self.substate,
1790                    target,
1791                    self.env.config.fork,
1792                )?;
1793
1794            // Mirror default_hook::set_bytecode_and_code_address: when delegation was
1795            // followed, record the delegatee (code_address) as touched in BAL so EIP-7928
1796            // reconstructors see the cross-address read.
1797            if is_delegation_7702 && let Some(recorder) = self.db.bal_recorder.as_mut() {
1798                recorder.record_touched_address(code_address);
1799            }
1800
1801            // Log count of the scope this frame's backup will be committed into.
1802            // The CallFrame branch below relies on `run_execution` having already
1803            // committed the frame (merging its logs up into this scope), then
1804            // slices `[substate_logs_before..]` to recover exactly this frame's
1805            // logs without re-committing.
1806            let substate_logs_before = self.substate.logs_len();
1807
1808            // Push substate backup for per-frame state isolation
1809            self.substate.push_backup();
1810
1811            // EIP-8141 top-level value transfer (spec lines 346-347): the outer
1812            // frame call owns CALLVALUE delivery. We only CHECK affordability
1813            // here; the actual transfer runs inside whichever branch executes
1814            // the frame, so it is recorded in the backup that branch restores on
1815            // failure (fixes the value-leak where a reverting contract-target
1816            // SENDER frame kept the funds). Static validation guarantees only
1817            // SENDER frames reach here with a non-zero value.
1818            let value_transfer_reverted = if !frame.value.is_zero() {
1819                let sender_balance = self.db.get_account(sender)?.info.balance;
1820                frame_value_exceeds_balance(sender_balance, frame.value)
1821            } else {
1822                false
1823            };
1824
1825            // Performs the deferred SENDER-frame value transfer + EIP-7708 log.
1826            // Invoked in BOTH execution branches so the transfer is recorded in
1827            // the call_frame_backup that branch's failure path restores.
1828            macro_rules! do_frame_value_transfer {
1829                () => {
1830                    if !frame.value.is_zero() && !value_transfer_reverted {
1831                        self.transfer(sender, target, frame.value)?;
1832                        // EIP-7708 log parity with default_hook::transfer_value:
1833                        // only Amsterdam+ and only when sender != target.
1834                        if self.env.config.fork >= Fork::Amsterdam && sender != target {
1835                            let log =
1836                                crate::utils::create_eth_transfer_log(sender, target, frame.value);
1837                            self.substate.add_log(log);
1838                        }
1839                    }
1840                };
1841            }
1842
1843            // EIP-8037: capture state-gas accounting before the frame runs so a
1844            // reverted frame (which commits no state) can be rolled back to
1845            // contribute zero state gas. The reservoir/spill are captured too:
1846            // each frame is gas-isolated, so an inline state-gas refund (e.g. an
1847            // SSTORE 0->N->0 clear, which credits the reservoir) inside one frame
1848            // must NOT carry over to a later frame's charges — the reservoir is
1849            // reset to this entry value after the frame completes.
1850            let state_gas_used_at_frame_entry = self.state_gas_used;
1851            let state_gas_reservoir_at_frame_entry = self.state_gas_reservoir;
1852            let state_gas_spill_at_frame_entry = self.state_gas_spill;
1853
1854            let (frame_success, frame_gas_used, frame_logs) = if value_transfer_reverted {
1855                self.substate.revert_backup();
1856                self.restore_cache_state()?;
1857                (false, frame.gas_limit, Vec::new())
1858            } else if bytecode.is_empty() && !is_delegation_7702 {
1859                // Default code runs only when the target has NEITHER code NOR a delegation
1860                // indicator (EIP-8141 §Execution lines 348-349). After eip7702_get_code,
1861                // bytecode is the delegatee's code when delegated, so a delegation to an
1862                // empty delegatee still falls into the CallFrame branch below and returns
1863                // success without executing anything — NOT into the default-code path.
1864                // current_call_frame is the OUTER frame here; its backup is the
1865                // one this branch's failure path restores, so the deferred
1866                // transfer is correctly undone on a default-code revert.
1867                do_frame_value_transfer!();
1868                use crate::opcode_handlers::frame_tx::execute_default_code;
1869                match execute_default_code(self, frame, target) {
1870                    Ok((success, gas_used, logs)) => {
1871                        if success {
1872                            // Capture this frame's substate logs (incl. the
1873                            // EIP-7708 transfer log added by
1874                            // do_frame_value_transfer!) BEFORE commit_backup
1875                            // merges them into the parent — mirrors the
1876                            // CallFrame branch. execute_default_code returns its
1877                            // own logs separately, so include both.
1878                            let mut this_frame_logs = self.substate.current_logs();
1879                            this_frame_logs.extend(logs);
1880                            self.substate.commit_backup();
1881                            (true, gas_used, this_frame_logs)
1882                        } else {
1883                            self.substate.revert_backup();
1884                            self.restore_cache_state()?;
1885                            (false, gas_used, Vec::new())
1886                        }
1887                    }
1888                    Err(_) => {
1889                        self.substate.revert_backup();
1890                        self.restore_cache_state()?;
1891                        (false, frame.gas_limit, Vec::new())
1892                    }
1893                }
1894            } else {
1895                // Normal code execution via CallFrame. msg_value carries
1896                // `frame.value` so the contract sees the correct CALLVALUE
1897                // (EIP-8141 spec line 346), but `should_transfer_value` stays
1898                // false because the deferred `do_frame_value_transfer!()` below
1899                // (invoked after the frame swap) owns the transfer — the inner
1900                // CALL machinery must not move the funds a second time.
1901                let call_frame = CallFrame::new(
1902                    caller,                                    // msg_sender
1903                    target,                                    // to (delegator; ADDRESS/storage)
1904                    code_address,                              // code_address (delegatee when 7702)
1905                    bytecode,           // bytecode (delegatee's code when 7702)
1906                    frame.value,        // msg_value -- CALLVALUE
1907                    frame.data.clone(), // calldata
1908                    is_static,          // is_static
1909                    frame.gas_limit,    // gas_limit
1910                    0,                  // depth
1911                    false, // should_transfer_value (do_frame_value_transfer! handles it)
1912                    false, // is_create
1913                    0,     // ret_offset
1914                    0,     // ret_size
1915                    self.stack_pool.pop().unwrap_or_default(), // stack
1916                    Memory::default(), // memory
1917                );
1918
1919                let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
1920                let saved_call_frames = mem::take(&mut self.call_frames);
1921
1922                // current_call_frame is now the INNER frame, so the deferred
1923                // transfer records into the inner backup that the revert failure
1924                // path (self.substate.revert_backup + restore_cache_state)
1925                // restores — fixing the value-leak on a reverting SENDER frame.
1926                do_frame_value_transfer!();
1927
1928                let frame_result = self.run_execution();
1929
1930                let result = match frame_result {
1931                    Ok(ctx_result) => {
1932                        let gas_used = ctx_result.gas_used;
1933                        let success = ctx_result.is_success();
1934
1935                        if success {
1936                            // The inner frame is the initial call frame (call_frames
1937                            // was emptied above), so `run_execution` already ran
1938                            // `handle_state_backup` and committed this frame's backup,
1939                            // merging its logs up into the scope measured by
1940                            // `substate_logs_before`. Recover exactly this frame's logs
1941                            // by slicing off everything that predated it — do NOT commit
1942                            // again (a second commit would collapse an extra backup
1943                            // level, breaking atomic-batch rollback) and do NOT read
1944                            // `current_logs()` wholesale (it now also holds prior frames'
1945                            // logs, which would duplicate them into frame_receipts[i]).
1946                            let mut merged_logs = self.substate.current_logs();
1947                            let this_frame_logs = merged_logs.split_off(substate_logs_before);
1948                            (true, gas_used, this_frame_logs)
1949                        } else {
1950                            // A normal EVM revert reaches `handle_state_backup` inside
1951                            // `run_execution`, which already reverted the backup and
1952                            // restored the cache for this frame; repeating it here would
1953                            // revert an extra level.
1954                            (false, gas_used, Vec::new())
1955                        }
1956                    }
1957                    Err(_e) => {
1958                        // A `VMError` propagates out of `run_execution` before it reaches
1959                        // `handle_state_backup`, so this frame's backup is still live and
1960                        // must be reverted (and the cache restored) here.
1961                        self.substate.revert_backup();
1962                        self.restore_cache_state()?;
1963                        (false, frame.gas_limit, Vec::new())
1964                    }
1965                };
1966
1967                // Restore call frame state
1968                let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
1969                self.call_frames = saved_call_frames;
1970
1971                // When a frame succeeds inside an atomic batch, its state
1972                // changes must remain revertable at batch-revert time. Merge
1973                // the finished frame's backup into the outer call-frame backup
1974                // so that `restore_cache_state()` invoked by batch-revert can
1975                // undo them — and so the next clear-and-absorb folds them into
1976                // `tx_level_backup` too. Outside a batch, the finished frame's
1977                // backup never reaches the outer call frame, so absorb it
1978                // directly into `tx_level_backup` here; otherwise an invalid-tx
1979                // exit could not roll back this committed frame's state.
1980                if result.0 {
1981                    if in_atomic_batch {
1982                        self.merge_call_frame_backup_with_parent(
1983                            &finished_frame.call_frame_backup,
1984                        )?;
1985                    } else {
1986                        tx_level_backup.absorb(&finished_frame.call_frame_backup);
1987                    }
1988                }
1989
1990                self.stack_pool.push(finished_frame.stack);
1991
1992                result
1993            };
1994
1995            // EIP-8037: a failed frame's state changes were reverted above, so it
1996            // creates no state and must contribute zero state gas. Roll the shared
1997            // `state_gas_used` back to this frame's entry value (the cache/substate
1998            // were already restored in the failure arms). Successful frames keep
1999            // their accumulated state gas.
2000            if !frame_success {
2001                self.state_gas_used = state_gas_used_at_frame_entry;
2002            }
2003            // EIP-8037: frames are gas-isolated, so the state-gas reservoir/spill
2004            // must not leak across the frame boundary. A reservoir credit from an
2005            // inline refund inside this frame (or a reverted frame's inflated
2006            // reservoir) would otherwise subsidize the next frame's state charges
2007            // (drawn before any spill to gas_remaining). Reset both to this frame's
2008            // entry value unconditionally — a successful frame already folded its
2009            // inline refund into `state_gas_used`, so the leftover reservoir credit
2010            // is spent and must be dropped.
2011            self.state_gas_reservoir = state_gas_reservoir_at_frame_entry;
2012            self.state_gas_spill = state_gas_spill_at_frame_entry;
2013
2014            total_gas_used = total_gas_used
2015                .checked_add(frame_gas_used)
2016                .ok_or(VMError::Internal(InternalError::Overflow))?;
2017            all_logs.extend(frame_logs.clone());
2018
2019            // Store frame result in context
2020            let ctx =
2021                self.frame_tx_context
2022                    .as_mut()
2023                    .ok_or(VMError::Internal(InternalError::Custom(
2024                        "missing frame tx context".to_string(),
2025                    )))?;
2026            let status_code = if frame_success {
2027                ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS
2028            } else {
2029                ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE
2030            };
2031            ctx.frame_results
2032                .push((status_code, frame_gas_used, frame_logs));
2033
2034            // Atomic batch: if a frame in the batch reverted, revert the
2035            // batch-level snapshot and skip remaining frames in the batch.
2036            if in_atomic_batch && !frame_success {
2037                self.substate.revert_backup(); // revert batch-level snapshot
2038                self.restore_cache_state()?;
2039                // EIP-8037: the whole batch unrolled, so none of its frames created
2040                // state — drop the state gas accumulated since batch entry.
2041                self.state_gas_used = state_gas_used_at_batch_entry;
2042
2043                // Rewrite results for all frames in this batch (inclusive) as failed,
2044                // charging each frame its full gas_limit per EIP-8141.
2045                let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
2046                    InternalError::Custom("missing frame tx context".to_string()),
2047                ))?;
2048                for i in batch_start_idx..=frame_idx {
2049                    if let (Some(result), Some(batch_frame)) =
2050                        (ctx.frame_results.get_mut(i), frame_tx.frames.get(i))
2051                    {
2052                        let charged_gas = batch_frame.gas_limit;
2053                        total_gas_used = total_gas_used
2054                            .saturating_sub(result.1)
2055                            .saturating_add(charged_gas);
2056                        *result = (
2057                            ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE,
2058                            charged_gas,
2059                            Vec::new(),
2060                        );
2061                    }
2062                }
2063                // Roll back approvals granted inside the reverted batch.
2064                ctx.restore_approvals(batch_approval_snapshot);
2065                // Remove only logs from the batch, preserving pre-batch logs
2066                all_logs.truncate(batch_logs_start);
2067
2068                // Spec: a reverted VERIFY frame invalidates the transaction even
2069                // inside an atomic batch. The batch unroll above already rolled
2070                // back state/approvals; validity is a tx-level decision. (The
2071                // failing `frame` here is the one that triggered the revert.)
2072                if frame.execution_mode() == FrameMode::Verify {
2073                    tx_invalid = true;
2074                    break;
2075                }
2076
2077                // Find the end of this batch (the first frame at or after the
2078                // failing one without the flag — any mode, spec commit 8b61fdc4)
2079                let batch_end = find_batch_end(&frame_tx.frames, frame_idx);
2080
2081                if batch_end > frame_idx {
2082                    skip_until_batch_end = Some(batch_end);
2083                } else {
2084                    in_atomic_batch = false;
2085                }
2086                self.substate.clear_transient_storage();
2087                continue;
2088            }
2089
2090            // If this is the last frame of a batch (a frame without the flag), commit the batch
2091            if in_atomic_batch && !frame.is_atomic_batch() {
2092                self.substate.commit_backup(); // commit batch-level snapshot
2093                in_atomic_batch = false;
2094            }
2095
2096            // VERIFY frame enforcement (spec commit 0b197156): a reverted
2097            // VERIFY frame invalidates the transaction. A VERIFY frame that
2098            // succeeds WITHOUT calling APPROVE is valid (e.g. the expiry
2099            // verifier frame). A reverted VERIFY frame invalidates the tx;
2100            // batched VERIFY reverts are handled in the atomic-batch-revert
2101            // branch above (which also sets tx_invalid).
2102            if frame.execution_mode() == FrameMode::Verify && !frame_success {
2103                tx_invalid = true;
2104                break;
2105            }
2106
2107            // Clear transient storage between frames
2108            self.substate.clear_transient_storage();
2109        }
2110
2111        // Post-execution: spec line 189 — "verify that `payer` has been set
2112        // (i.e. `payer != None`). If `payer` is set, refund any unpaid gas to
2113        // the payer. If it is not, the whole transaction is invalid."
2114        let ctx =
2115            self.frame_tx_context
2116                .as_ref()
2117                .ok_or(VMError::Internal(InternalError::Custom(
2118                    "missing frame tx context".to_string(),
2119                )))?;
2120        if ctx.payer_address.is_none() {
2121            tx_invalid = true;
2122        }
2123
2124        if tx_invalid {
2125            // TX is invalid — Err must leave `db.current_accounts_state`
2126            // unchanged from before the tx (same contract as non-frame
2127            // `execute()`). Absorb the last live frame's backup (it has not
2128            // been cleared yet), then restore every absorbed frame's effects.
2129            // Substate is per-VM and discarded when this VM drops, so no
2130            // substate revert is needed.
2131            tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2132            crate::utils::restore_cache_state(self.db, tx_level_backup)?;
2133            return Err(VMError::TxValidation(
2134                crate::errors::TxValidationError::InvalidFrameTransaction,
2135            ));
2136        }
2137
2138        // Take ownership of frame context
2139        let ctx = self
2140            .frame_tx_context
2141            .take()
2142            .ok_or(VMError::Internal(InternalError::Custom(
2143                "missing frame tx context".to_string(),
2144            )))?;
2145        let payer = ctx.payer_address.unwrap_or(sender);
2146
2147        // Gas refunds: the payer was debited the transaction's MAXIMUM cost at
2148        // APPROVE (max_fee-based gas + max-rate blob cost, `compute_tx_max_cost`,
2149        // spec line 387). What the payer owes is the effective-rate cost of the
2150        // gas actually used plus the base-rate blob burn (EIP-4844 semantics);
2151        // everything above that is returned here. Intrinsic gas is inside
2152        // `total_gas_used`, so it stays non-refundable. When max_fee ==
2153        // effective_gas_price and max_fee_per_blob_gas == base_blob_fee this
2154        // reduces exactly to the old unused-frame-gas refund:
2155        // max·T + B − e·U − B = e·(T − U).
2156        let effective_gas_price = self.env.gas_price;
2157        let charged = crate::opcode_handlers::frame_tx::compute_tx_max_cost(&ctx)
2158            .map_err(|_| VMError::Internal(InternalError::Overflow))?;
2159        let blob_burn = crate::utils::calculate_blob_gas_cost(
2160            &ctx.tx.blob_versioned_hashes,
2161            self.env.base_blob_fee_per_gas,
2162        )?;
2163        let owed = effective_gas_price
2164            .checked_mul(U256::from(total_gas_used))
2165            .and_then(|gas_owed| gas_owed.checked_add(blob_burn))
2166            .ok_or(VMError::Internal(InternalError::Overflow))?;
2167        // charged >= owed always: effective <= max_fee (by construction of the
2168        // effective price), base_blob <= max_blob (blob-fee validity check), and
2169        // total_gas_used <= total_gas_limit (frames are bounded by their limits).
2170        let refund_amount = charged
2171            .checked_sub(owed)
2172            .ok_or(VMError::Internal(InternalError::Underflow))?;
2173
2174        self.increase_account_balance(payer, refund_amount)?;
2175
2176        // Pay coinbase. Mirror `pay_coinbase` on the normal-tx path so a frame
2177        // transaction has the same coinbase BlockAccessList / witness footprint:
2178        // EIP-7928 requires the coinbase to appear in the BAL for any user tx even
2179        // when the priority fee is zero, and EELS reads the coinbase account
2180        // unconditionally during fee transfer (so EIP-8025 witnesses record its
2181        // trie path even at zero fee). A frame tx is always a user tx (non-zero
2182        // effective gas price), unlike a system call.
2183        let priority_fee = effective_gas_price.saturating_sub(self.env.base_fee_per_gas);
2184        let coinbase_fee = priority_fee
2185            .checked_mul(U256::from(total_gas_used))
2186            .ok_or(VMError::Internal(InternalError::Overflow))?;
2187        if !effective_gas_price.is_zero()
2188            && let Some(recorder) = self.db.bal_recorder.as_mut()
2189        {
2190            recorder.record_touched_address(self.env.coinbase);
2191        }
2192        if coinbase_fee.is_zero() {
2193            // Zero priority fee: still read the coinbase so its witness/BAL trie
2194            // path (incl. an exclusion proof if absent) is recorded.
2195            self.db.get_account(self.env.coinbase)?;
2196        } else {
2197            self.increase_account_balance(self.env.coinbase, coinbase_fee)?;
2198        }
2199
2200        // EIP-8141: finalize self-destructs at tx end, mirroring the default
2201        // finalize hook ordering (refund -> coinbase -> delete). SELFDESTRUCT is
2202        // unrestricted during frame execution (the banned-opcode set only applies
2203        // to the mempool validation prefix), so a frame may mark same-tx-created
2204        // accounts for deletion (EIP-6780). Without this they leak into the
2205        // post-state. `iter_selfdestruct` walks the full substate chain, so a
2206        // single call here covers every committed frame. Any EIP-7708 burn logs
2207        // emitted (rare: only when a destroyed account later received ETH in the
2208        // same tx) are appended to the tx-level aggregate `all_logs`: the per-frame
2209        // consensus receipts have no slot for end-of-tx logs, but the header and
2210        // receipt blooms are derived from these aggregate logs (receipt.rs,
2211        // payload.rs), so they must be recorded there.
2212        //
2213        // KNOWN SPEC GAP (cross-client interop): these tx-end burn logs are in the
2214        // aggregate bloom but NOT in any per-frame consensus receipt, so a client
2215        // that re-derives the type-0x06 logs_bloom purely from the canonical
2216        // per-frame logs would compute a different bloom (part of the block hash).
2217        // ethrex producer and validator agree (both execute over the live
2218        // aggregate), so this is not an intra-client split; it only bites
2219        // cross-client and only for this rare destroy-after-receiving-ETH case.
2220        // EIP-7708 is silent on receipt placement and EIP-8141's frame receipt has
2221        // no tx-level logs slot, so the canonical home is genuinely undefined; do
2222        // not pin one (e.g. attribute to the last frame) unilaterally — confirm the
2223        // bloom-derivation rule against another client / the devnet first.
2224        let logs_before = self.substate.current_logs().len();
2225        crate::hooks::default_hook::delete_self_destruct_accounts(self)?;
2226        let mut logs_after = self.substate.current_logs();
2227        if logs_after.len() > logs_before {
2228            all_logs.extend(logs_after.split_off(logs_before));
2229        }
2230
2231        // Frame txs short-circuit the hook/finalize path, so the BackupHook never
2232        // runs and `db.tx_backup` stays None on the success path. A block builder
2233        // can execute a frame tx successfully and then reject it (e.g. the EIP-8037
2234        // 2D-gas overflow post-check, or an L2 invalid cross-chain message), calling
2235        // `undo_last_tx` — which needs the top-level backup to roll the committed
2236        // state back; otherwise the excluded tx's mutations leak into later txs and
2237        // the built block's state root diverges from re-execution. Populate it here
2238        // exactly as `BackupHook::finalize_execution` would: `tx_level_backup` holds
2239        // every committed frame's originals, and the outer call-frame backup now also
2240        // holds the refund/coinbase/self-destruct originals. Gated on
2241        // `preserve_top_level_backup` so it is set only when a hook reads it (L2);
2242        // on L1 the field is never consulted.
2243        if self.preserve_top_level_backup {
2244            tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2245            self.db.tx_backup = Some(tx_level_backup);
2246        }
2247
2248        // Derive top-level status from ALL frames: the transaction succeeded
2249        // only if every executed frame succeeded; a reverted or skipped frame of
2250        // ANY mode (SENDER, DEFAULT, VERIFY) yields a failed top-level status
2251        // (analogous to status 0 in standard transactions). This MUST match the
2252        // consensus-receipt derivation in `Receipt` decoding (receipt.rs), which
2253        // re-derives `succeeded` from the per-frame statuses ALONE — the
2254        // consensus `frame_receipt` carries no frame mode, so an all-frames rule
2255        // is the only definition the encode side (here) and a wire/trie decode
2256        // can compute identically. Deriving from SENDER frames only would make a
2257        // freshly-executed receipt's `status` disagree with the same receipt
2258        // decoded from consensus bytes. (A reverted VERIFY frame already
2259        // invalidated the tx above via `tx_invalid`; this additionally covers
2260        // reverted SENDER/DEFAULT frames, which do not.)
2261        let any_frame_reverted = ctx
2262            .frame_results
2263            .iter()
2264            .any(|(status, _, _)| *status != ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS);
2265
2266        let result = if any_frame_reverted {
2267            TxResult::Revert(VMError::RevertOpcode)
2268        } else {
2269            TxResult::Success
2270        };
2271
2272        // EIP-8037: report the transaction's net state gas (same formula as the
2273        // normal-tx path in default_hook). `total_gas_used` already includes the
2274        // state gas — it spilled into each frame's gas_remaining, exactly as for any
2275        // sub-TX_MAX_GAS_LIMIT transaction whose reservoir is 0 — so reporting
2276        // `state_gas_used` here lets the block-level regular/state split
2277        // (regular = gas_used - state_gas_used) attribute it to the state dimension
2278        // instead of billing the whole amount as regular gas.
2279        let state_gas_used =
2280            u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
2281
2282        // Unused frame gas in GAS UNITS for the report — distinct from the wei
2283        // refund above (which also returns the max-vs-effective fee delta).
2284        let frame_gas_used = total_gas_used.saturating_sub(intrinsic_gas);
2285        let gas_refund = sum_frame_gas_limits.saturating_sub(frame_gas_used);
2286
2287        let report = ExecutionReport {
2288            result,
2289            gas_used: total_gas_used,
2290            gas_spent: total_gas_used,
2291            gas_refunded: gas_refund,
2292            state_gas_used,
2293            output: Bytes::new(),
2294            logs: all_logs,
2295            payer_address: ctx.payer_address,
2296            frame_results: Some(ctx.frame_results),
2297        };
2298
2299        Ok(report)
2300    }
2301
2302    /// EIP-8141 mempool entry point: set up the frame-tx context and observer,
2303    /// then simulate the validation prefix.
2304    ///
2305    /// Performs the frame-tx preamble (static constraints, nonce, fee sanity,
2306    /// `FrameTxContext` init, outer-signature validation) — the same checks
2307    /// `execute_frame_tx` runs before any frame — then activates the
2308    /// [`ValidationObserver`](crate::validation_observer::ValidationObserver) for
2309    /// `sender` with the prefix's `deploy_index`, runs the prefix via
2310    /// [`VM::simulate_validation_prefix`], and returns the raw simulation
2311    /// result. Does NOT charge or refund gas. `canonical_paymaster_pay_frame`
2312    /// is the index of a canonical paymaster's pay frame (always `None` today,
2313    /// OQ1); when set, the access-restriction skip fires for that frame.
2314    pub fn run_frame_validation_prefix(
2315        &mut self,
2316        frame_indices: &[usize],
2317        deploy_index: Option<usize>,
2318        canonical_paymaster_pay_frame: Option<usize>,
2319    ) -> Result<PrefixSimResult, VMError> {
2320        use crate::validation_observer::ValidationObserver;
2321
2322        if self.env.config.fork < Fork::Hegota {
2323            return Err(VMError::TxValidation(
2324                crate::errors::TxValidationError::FrameTxPreFork,
2325            ));
2326        }
2327
2328        let frame_tx = match &self.tx {
2329            Transaction::FrameTransaction(ft) => ft.clone(),
2330            _ => {
2331                return Err(VMError::Internal(InternalError::Custom(
2332                    "run_frame_validation_prefix called on non-frame tx".to_string(),
2333                )));
2334            }
2335        };
2336
2337        let sender = frame_tx.sender;
2338
2339        if frame_tx.validate_static_constraints().is_err() {
2340            return Err(VMError::TxValidation(
2341                crate::errors::TxValidationError::InvalidFrameTransaction,
2342            ));
2343        }
2344
2345        let sender_info = self.db.get_account(sender)?.info.clone();
2346        if sender_info.nonce != frame_tx.nonce {
2347            return Err(VMError::TxValidation(
2348                crate::errors::TxValidationError::NonceMismatch {
2349                    expected: sender_info.nonce,
2350                    actual: frame_tx.nonce,
2351                },
2352            ));
2353        }
2354
2355        if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
2356            return Err(VMError::TxValidation(
2357                crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
2358                    priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
2359                    max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
2360                },
2361            ));
2362        }
2363
2364        if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
2365            return Err(VMError::TxValidation(
2366                crate::errors::TxValidationError::InsufficientMaxFeePerGas,
2367            ));
2368        }
2369
2370        let sig_hash = frame_tx.compute_sig_hash();
2371        let total_gas_limit = frame_tx.total_gas_limit();
2372        self.frame_tx_context = Some(FrameTxContext {
2373            sender_approved: false,
2374            payer_address: None,
2375            frame_results: Vec::new(),
2376            current_frame_index: 0,
2377            sig_hash,
2378            tx: frame_tx.clone(),
2379            approve_called_in_current_frame: false,
2380            total_gas_limit,
2381        });
2382
2383        if !validate_frame_signatures(
2384            &frame_tx.signatures,
2385            sig_hash,
2386            self.env.config.fork,
2387            self.crypto,
2388        ) {
2389            return Err(VMError::TxValidation(
2390                crate::errors::TxValidationError::InvalidFrameTransaction,
2391            ));
2392        }
2393
2394        let expiry_verifier = ethrex_common::types::frame_tx_expiry_verifier();
2395        let mut observer = ValidationObserver::new(sender, deploy_index, expiry_verifier);
2396        observer.canonical_paymaster_pay_frame = canonical_paymaster_pay_frame;
2397        self.validation_observer = observer;
2398
2399        self.simulate_validation_prefix(frame_indices)
2400    }
2401
2402    /// EIP-8141 mempool validation-prefix simulation (local peer policy).
2403    ///
2404    /// Runs ONLY the validation-prefix frames (the verify/pay/deploy frames that
2405    /// must execute before the transaction's payer is established) of a frame
2406    /// transaction, under an active [`ValidationObserver`](crate::validation_observer::ValidationObserver),
2407    /// then stops as soon as the payer has been set. Reuses the real frame
2408    /// execution primitives (`eip7702_get_code`, `execute_default_code`,
2409    /// `run_execution`, substate backups, value transfer) over the DEFAULT/VERIFY
2410    /// subset that prefixes are restricted to (Phase 1 structural rules forbid
2411    /// SENDER and atomic-batch frames in the prefix), so it dispatches real
2412    /// opcodes through the real handlers — not a separate mini-EVM.
2413    ///
2414    /// `frame_indices` are the prefix frame indices (in order), as identified by
2415    /// `FrameTransaction::validation_prefix`; expiry-verifier frames interleaved
2416    /// in the prefix are run too (they may appear between prefix frames). The
2417    /// caller must have set `frame_tx_context` and activated the observer.
2418    ///
2419    /// Returns [`PrefixSimResult`] describing the outcome. Does NOT charge fees
2420    /// or refund gas (mempool simulation only); state changes accumulate in the
2421    /// shared `db` and are discarded by the caller (a fresh simulation database).
2422    pub fn simulate_validation_prefix(
2423        &mut self,
2424        frame_indices: &[usize],
2425    ) -> Result<PrefixSimResult, VMError> {
2426        let frame_tx = match &self.tx {
2427            Transaction::FrameTransaction(ft) => ft.clone(),
2428            _ => {
2429                return Err(VMError::Internal(InternalError::Custom(
2430                    "simulate_validation_prefix called on non-frame tx".to_string(),
2431                )));
2432            }
2433        };
2434
2435        let sender = frame_tx.sender;
2436        let entry_point = ethrex_common::types::frame_tx_entry_point();
2437
2438        let mut total_gas_used: u64 = 0;
2439        let mut any_revert = false;
2440        // The highest prefix-frame index we must run before stopping. We run the
2441        // prefix in source order, executing every frame from 0 up to and
2442        // including the last prefix index (covering interleaved expiry frames).
2443        let last_prefix_idx = frame_indices.iter().copied().max();
2444
2445        for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
2446            // Stop once the whole prefix has run (and the payer break below).
2447            if let Some(stop) = last_prefix_idx {
2448                if frame_idx > stop {
2449                    break;
2450                }
2451            } else {
2452                break;
2453            }
2454
2455            // Each independent prefix frame starts with a clean call-frame backup
2456            // so a later frame's failure only reverts its own effects.
2457            self.current_call_frame.call_frame_backup.clear();
2458
2459            let ctx =
2460                self.frame_tx_context
2461                    .as_mut()
2462                    .ok_or(VMError::Internal(InternalError::Custom(
2463                        "missing frame tx context".to_string(),
2464                    )))?;
2465            ctx.current_frame_index = frame_idx;
2466            ctx.approve_called_in_current_frame = false;
2467
2468            let target = frame.target.unwrap_or(sender);
2469
2470            // Sync observer per-frame fields before the frame runs.
2471            self.validation_observer.current_frame_index = frame_idx;
2472            self.validation_observer.current_frame_mode = frame.mode;
2473
2474            // Prefix frames are DEFAULT (deploy) or VERIFY only; both run with
2475            // ENTRY_POINT as caller (DEFAULT not static, VERIFY static).
2476            let (caller, is_static) = match frame.execution_mode() {
2477                FrameMode::Default => (entry_point, false),
2478                FrameMode::Verify => (entry_point, true),
2479                FrameMode::Sender => {
2480                    // Structural rules exclude SENDER frames from the prefix.
2481                    return Err(VMError::Internal(InternalError::Custom(
2482                        "SENDER frame in validation prefix".to_string(),
2483                    )));
2484                }
2485            };
2486
2487            self.env.origin = caller;
2488
2489            let (is_delegation_7702, _access_cost, code_address, bytecode) =
2490                crate::utils::eip7702_get_code(
2491                    self.db,
2492                    &mut self.substate,
2493                    target,
2494                    self.env.config.fork,
2495                )?;
2496
2497            self.substate.push_backup();
2498
2499            let value_transfer_reverted = if !frame.value.is_zero() {
2500                let sender_balance = self.db.get_account(sender)?.info.balance;
2501                frame_value_exceeds_balance(sender_balance, frame.value)
2502            } else {
2503                false
2504            };
2505
2506            let (frame_success, frame_gas_used) = if value_transfer_reverted {
2507                self.substate.revert_backup();
2508                self.restore_cache_state()?;
2509                (false, frame.gas_limit)
2510            } else if bytecode.is_empty() && !is_delegation_7702 {
2511                // Default-code path (target has neither code nor a delegation).
2512                if !frame.value.is_zero() {
2513                    self.transfer(sender, target, frame.value)?;
2514                }
2515                use crate::opcode_handlers::frame_tx::execute_default_code;
2516                match execute_default_code(self, frame, target) {
2517                    Ok((success, gas_used, _logs)) => {
2518                        if success {
2519                            self.substate.commit_backup();
2520                            (true, gas_used)
2521                        } else {
2522                            self.substate.revert_backup();
2523                            self.restore_cache_state()?;
2524                            (false, gas_used)
2525                        }
2526                    }
2527                    Err(_) => {
2528                        self.substate.revert_backup();
2529                        self.restore_cache_state()?;
2530                        (false, frame.gas_limit)
2531                    }
2532                }
2533            } else {
2534                // Normal code execution via a child CallFrame.
2535                let call_frame = CallFrame::new(
2536                    caller,
2537                    target,
2538                    code_address,
2539                    bytecode,
2540                    frame.value,
2541                    frame.data.clone(),
2542                    is_static,
2543                    frame.gas_limit,
2544                    0,
2545                    false,
2546                    false,
2547                    0,
2548                    0,
2549                    self.stack_pool.pop().unwrap_or_default(),
2550                    Memory::default(),
2551                );
2552
2553                let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2554                let saved_call_frames = mem::take(&mut self.call_frames);
2555
2556                if !frame.value.is_zero() {
2557                    self.transfer(sender, target, frame.value)?;
2558                }
2559
2560                let frame_result = self.run_execution();
2561
2562                let result = match frame_result {
2563                    Ok(ctx_result) => {
2564                        let gas_used = ctx_result.gas_used;
2565                        // The inner frame is the initial call frame, so `run_execution`
2566                        // already committed (success) or reverted + restored the cache
2567                        // (revert) this frame's backup via `handle_state_backup`. Only a
2568                        // `VMError` (the `Err` arm) leaves the backup live for us to undo.
2569                        (ctx_result.is_success(), gas_used)
2570                    }
2571                    Err(_e) => {
2572                        self.substate.revert_backup();
2573                        self.restore_cache_state()?;
2574                        (false, frame.gas_limit)
2575                    }
2576                };
2577
2578                let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2579                self.call_frames = saved_call_frames;
2580                self.stack_pool.push(finished_frame.stack);
2581
2582                result
2583            };
2584
2585            total_gas_used = total_gas_used
2586                .checked_add(frame_gas_used)
2587                .ok_or(VMError::Internal(InternalError::Overflow))?;
2588
2589            if !frame_success {
2590                any_revert = true;
2591            }
2592
2593            // A reverted prefix frame is fatal: the transaction can never reach a
2594            // valid payer through a reverted verify/pay/deploy frame.
2595            if !frame_success {
2596                break;
2597            }
2598
2599            self.substate.clear_transient_storage();
2600
2601            // Stop as soon as the payer has been set (the prefix is complete).
2602            if self
2603                .frame_tx_context
2604                .as_ref()
2605                .and_then(|c| c.payer_address)
2606                .is_some()
2607            {
2608                break;
2609            }
2610        }
2611
2612        let ctx =
2613            self.frame_tx_context
2614                .as_ref()
2615                .ok_or(VMError::Internal(InternalError::Custom(
2616                    "missing frame tx context".to_string(),
2617                )))?;
2618
2619        Ok(PrefixSimResult {
2620            any_revert,
2621            payer_address: ctx.payer_address,
2622            sender_approved: ctx.sender_approved,
2623            total_gas_used,
2624        })
2625    }
2626
2627    /// Must run after `prepare_execution` so EIP-7702 delegation is already resolved into
2628    /// `bytecode`.
2629    #[inline(always)]
2630    fn is_simple_transfer_fast_path(&self) -> bool {
2631        !self.current_call_frame.is_create
2632            && self.current_call_frame.bytecode.is_empty()
2633            // Privileged L2 txs can leave gas negative; let the slow path surface that as OOG.
2634            && self.current_call_frame.gas_remaining >= 0
2635            && self.tx.authorization_list().is_none()
2636            // Precompiles dispatch via run_execution even with empty bytecode.
2637            && !precompiles::is_precompile(
2638                &self.current_call_frame.to,
2639                self.env.config.fork,
2640                self.vm_type,
2641            )
2642    }
2643
2644    /// Main execution loop.
2645    pub fn run_execution(&mut self) -> Result<ContextResult, VMError> {
2646        // If gas is already exhausted (negative), fail immediately.
2647        // This can happen when intrinsic gas exceeds the gas limit in privileged L2 transactions.
2648        // Without this check, casting negative gas_remaining to u64 would wrap to a huge value.
2649        if self.current_call_frame.gas_remaining < 0 {
2650            return Ok(ContextResult {
2651                result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2652                gas_used: self.current_call_frame.gas_limit,
2653                gas_spent: self.current_call_frame.gas_limit,
2654                output: Bytes::new(),
2655            });
2656        }
2657
2658        // EIP-8037: the atomic prepare region rolled back (one of its charges — 7702
2659        // auth, CREATE/value NEW_ACCOUNT, recipient delegation-resolve — OOG'd).
2660        // Burn all gas and revert the tx rather than rejecting it as invalid (which
2661        // would wrongly invalidate the block). Mirrors EELS depth-0
2662        // `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`
2663        // (`interpreter.py:366-374`).
2664        if self.pending_prep_oog {
2665            return Ok(ContextResult {
2666                result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2667                gas_used: self.current_call_frame.gas_limit,
2668                gas_spent: self.current_call_frame.gas_limit,
2669                output: Bytes::new(),
2670            });
2671        }
2672
2673        // A charged value-to-not-alive NEW_ACCOUNT means the recipient was not yet alive
2674        // at tx start and the tx transfers value. If the recipient is a precompile that
2675        // then exceptionally halts/reverts, the account is never materialized, so the
2676        // charge is rolled back in the precompile branch below (mirrors EELS
2677        // `refill_frame_state_gas`). Set in-region by `prepare_execution`.
2678        let top_frame_new_account_charged = self.value_new_account_charged;
2679
2680        #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
2681        if precompiles::is_precompile(
2682            &self.current_call_frame.to,
2683            self.env.config.fork,
2684            self.vm_type,
2685        ) {
2686            // `execute_precompile` itself never touches state gas (it only mutates
2687            // `gas_remaining`; it has no access to `state_gas_used` / `state_gas_reservoir` /
2688            // `state_gas_spill`) — the assert below guards that. The in-region EIP-2780
2689            // value-to-not-alive NEW_ACCOUNT charge (`prepare_execution`),
2690            // however, IS frame state gas, and on an exceptional halt/revert it must be
2691            // rolled back (see below). `self` is borrowed by field rather than via
2692            // `&mut self.current_call_frame` so the refund call, which needs `&mut self`,
2693            // can run after `execute_precompile`.
2694            let state_gas_used_before_precompile = self.state_gas_used;
2695            let code_address = self.current_call_frame.code_address;
2696            let precompile_gas_limit = self.current_call_frame.gas_limit;
2697            let mut gas_remaining = self.current_call_frame.gas_remaining as u64;
2698            let result = Self::execute_precompile(
2699                code_address,
2700                &self.current_call_frame.calldata,
2701                precompile_gas_limit,
2702                &mut gas_remaining,
2703                self.env.config.fork,
2704                self.db.store.precompile_cache(),
2705                self.crypto,
2706            );
2707
2708            debug_assert_eq!(
2709                self.state_gas_used, state_gas_used_before_precompile,
2710                "precompile execution must not mutate state_gas_used"
2711            );
2712
2713            // EIP-8037 Amsterdam 2D accounting recomputes `block_gas_used` from
2714            // `raw_consumed = gas_limit - gas_remaining` inside `refund_sender`. On a
2715            // top-level precompile exceptional halt, `handle_precompile_result` already
2716            // sets `ContextResult.gas_used = gas_limit`, but `gas_remaining` retains the
2717            // untouched forwarded amount — under Amsterdam that would make the block
2718            // report only the intrinsic portion. Zero it so the block matches the
2719            // `gas_used = gas_limit` contract from `handle_precompile_result`, and roll
2720            // back the in-region value NEW_ACCOUNT charge (the recipient is never materialized
2721            // on halt) so the burned gas counts entirely as regular gas, matching EELS
2722            // `refill_frame_state_gas`. Pre-Amsterdam reads `ctx_result.gas_used` directly
2723            // and is unaffected by this path either way.
2724            if self.env.config.fork >= Fork::Amsterdam
2725                && let Ok(ctx) = &result
2726                && !ctx.is_success()
2727            {
2728                gas_remaining = 0;
2729                self.refund_new_account_state_gas(top_frame_new_account_charged)?;
2730            }
2731
2732            self.current_call_frame.gas_remaining = gas_remaining as i64;
2733
2734            return result;
2735        }
2736
2737        // Specialize the dispatch loop on whether a struct-log tracer is active.
2738        // The `!TRACED` variant compiles out every tracer branch and capture call,
2739        // leaving a minimal hot loop (the common, non-traced case).
2740        if self.opcode_tracer.active {
2741            self.run_dispatch::<true>()
2742        } else {
2743            self.run_dispatch::<false>()
2744        }
2745    }
2746
2747    /// Opcode dispatch loop, monomorphized over whether a struct-log tracer is
2748    /// active. With `TRACED = false` the compiler eliminates the tracer branches
2749    /// and the cold `trace_*_step` calls entirely, so the hot loop body stays
2750    /// minimal; the traced variant keeps the cold helpers out of line.
2751    fn run_dispatch<const TRACED: bool>(&mut self) -> Result<ContextResult, VMError> {
2752        let mut error = OnceCell::<VMError>::new();
2753
2754        #[cfg(feature = "perf_opcode_timings")]
2755        let mut timings = crate::timings::OPCODE_TIMINGS.lock().expect("poison");
2756
2757        // Copy the `&'static` table pointer once; it doesn't borrow `self`, so dispatch can still
2758        // pass `self` mutably to the handler without reloading the pointer each iteration.
2759        let opcode_table = self.opcode_table;
2760
2761        loop {
2762            // Capture pc BEFORE advance_pc() — this is the address of the current opcode.
2763            let pc_of_current_op = self.current_call_frame.pc;
2764            let opcode = self.current_call_frame.next_opcode();
2765            self.advance_pc();
2766
2767            // EIP-8141 mempool validation-trace observer (single branch on the
2768            // fast path when inactive). Enforces the banned-opcode set and the
2769            // sequential `GAS`-before-`*CALL` rule before the handler runs.
2770            if self.validation_observer.active {
2771                self.check_validation_banned_opcode(opcode);
2772            }
2773
2774            // Struct-log pre-step capture (compiled out entirely when !TRACED).
2775            let gas_before_op = if TRACED {
2776                self.trace_pre_step(opcode, pc_of_current_op)
2777            } else {
2778                0
2779            };
2780
2781            #[cfg(feature = "perf_opcode_timings")]
2782            let opcode_time_start = std::time::Instant::now();
2783
2784            #[allow(clippy::indexing_slicing, clippy::as_conversions)]
2785            let op_result = opcode_table[opcode as usize].call(self, &mut error);
2786
2787            #[cfg(feature = "perf_opcode_timings")]
2788            {
2789                let time = opcode_time_start.elapsed();
2790                timings.update(opcode, time);
2791            }
2792
2793            // Struct-log post-step (compiled out entirely when !TRACED).
2794            if TRACED {
2795                self.trace_post_step(gas_before_op, &error);
2796            }
2797
2798            let result = match op_result {
2799                OpcodeResult::Continue => continue,
2800                OpcodeResult::Halt => match error.take() {
2801                    None => self.handle_opcode_result()?,
2802                    Some(error) => self.handle_opcode_error(error)?,
2803                },
2804            };
2805
2806            // Return the ExecutionReport if the executed callframe was the first one.
2807            if self.is_initial_call_frame() {
2808                // Consume the backup (move it out) unless a `BackupHook` will read it afterward
2809                // to build the tx-level undo snapshot (L2 / stateless). On L1 nothing reads it
2810                // once the cache is restored, so cloning it would be dead work.
2811                self.handle_state_backup(&result, !self.preserve_top_level_backup)?;
2812                return Ok(result);
2813            }
2814
2815            // Handle interaction between child and parent callframe.
2816            self.handle_return(&result)?;
2817        }
2818    }
2819
2820    /// EIP-8141 validation-trace banned-opcode check (mempool simulation only).
2821    ///
2822    /// Called once per dispatch-loop iteration, AFTER the opcode is fetched and
2823    /// BEFORE the handler runs, gated by `self.validation_observer.active`. Byte
2824    /// values are pinned against `opcodes.rs`.
2825    ///
2826    /// Static bans: `ORIGIN`, `GASPRICE`, `BLOCKHASH`, `COINBASE`, `TIMESTAMP`
2827    /// (except when the current frame's target is EXPIRY_VERIFIER), `NUMBER`,
2828    /// `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBHASH`, `BLOBBASEFEE`, `INVALID`,
2829    /// `SELFDESTRUCT`, `BALANCE`, `SELFBALANCE`, `TLOAD`, `TSTORE`, and `CALLCODE`
2830    /// in non-deploy prefix frames (ERC-7562 bans CALLCODE in validation;
2831    /// DELEGATECALL is allowed subject to the CALL-family trace rules in the
2832    /// handlers). `SSTORE`/`CREATE`/`CREATE2` are allowed only inside the deploy
2833    /// frame and are enforced in their handlers (state-write rules), not here.
2834    ///
2835    /// Sequential `GAS` rule: `GAS` is allowed only immediately before a
2836    /// `*CALL` (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`). We detect this by
2837    /// remembering `last_opcode`: if the previous iteration was `GAS` and this
2838    /// opcode is NOT a `*CALL`, the prior `GAS` was illegal.
2839    pub fn check_validation_banned_opcode(&mut self, opcode: u8) {
2840        use crate::validation_observer::FrameSimViolation;
2841
2842        // Opcode bytes, pinned against `opcodes.rs`. The literal values are
2843        // asserted equal to the `Opcode` enum discriminants by
2844        // `validation_observer_opcode_byte_pins` below (avoids a `const`-context
2845        // `as` cast, which the workspace clippy config denies).
2846        const ORIGIN: u8 = 0x32;
2847        const GASPRICE: u8 = 0x3A;
2848        const BLOCKHASH: u8 = 0x40;
2849        const COINBASE: u8 = 0x41;
2850        const TIMESTAMP: u8 = 0x42;
2851        const NUMBER: u8 = 0x43;
2852        const PREVRANDAO: u8 = 0x44;
2853        const GASLIMIT: u8 = 0x45;
2854        const BASEFEE: u8 = 0x48;
2855        const BLOBHASH: u8 = 0x49;
2856        const BLOBBASEFEE: u8 = 0x4A;
2857        const INVALID: u8 = 0xFE;
2858        const SELFDESTRUCT: u8 = 0xFF;
2859        const BALANCE: u8 = 0x31;
2860        const SELFBALANCE: u8 = 0x47;
2861        const TLOAD: u8 = 0x5C;
2862        const TSTORE: u8 = 0x5D;
2863        const GAS: u8 = 0x5A;
2864        const CALL: u8 = 0xF1;
2865        const CALLCODE: u8 = 0xF2;
2866        const DELEGATECALL: u8 = 0xF4;
2867        const STATICCALL: u8 = 0xFA;
2868
2869        let is_call_family = matches!(opcode, CALL | CALLCODE | DELEGATECALL | STATICCALL);
2870
2871        // Sequential GAS rule: a `GAS` on the previous iteration is only legal if
2872        // THIS opcode is a `*CALL`. Evaluate before updating `last_opcode`.
2873        if self.validation_observer.last_opcode == GAS && !is_call_family {
2874            self.validation_observer
2875                .record_violation(FrameSimViolation::BannedOpcode(GAS));
2876        }
2877
2878        // Carry `GAS` forward for the next iteration's check; reset otherwise.
2879        self.validation_observer.last_opcode = if opcode == GAS { GAS } else { 0 };
2880
2881        let banned = match opcode {
2882            ORIGIN | GASPRICE | BLOCKHASH | COINBASE | NUMBER | PREVRANDAO | GASLIMIT | BASEFEE
2883            | BLOBHASH | BLOBBASEFEE | INVALID | SELFDESTRUCT | BALANCE | SELFBALANCE | TLOAD
2884            | TSTORE => true,
2885            // TIMESTAMP is permitted only when the currently executing contract
2886            // IS the EXPIRY_VERIFIER predeploy (checked by code_address so the
2887            // rule tracks the executing contract at every call depth, not just the
2888            // top-level frame target). A nested call FROM an expiry frame INTO
2889            // another contract is correctly banned; a nested call INTO the
2890            // predeploy from any frame is correctly allowed.
2891            TIMESTAMP => {
2892                self.current_call_frame.code_address != self.validation_observer.expiry_verifier
2893            }
2894            // CALLCODE is banned in non-deploy prefix frames (ERC-7562).
2895            CALLCODE => !self.validation_observer.in_deploy_frame(),
2896            _ => false,
2897        };
2898
2899        if banned {
2900            self.validation_observer
2901                .record_violation(FrameSimViolation::BannedOpcode(opcode));
2902        }
2903    }
2904
2905    /// EIP-8141 validation-trace `SLOAD` check (mempool simulation only).
2906    ///
2907    /// `SLOAD` is allowed only when the storage owner (`address`, the executing
2908    /// frame's `to`) is the transaction sender. Records the touched slot for the
2909    /// admission-time revalidation affected-set.
2910    pub fn validation_check_sload(&mut self, address: Address, slot: H256) {
2911        use crate::validation_observer::FrameSimViolation;
2912        if self.validation_observer.in_canonical_pay_frame() {
2913            return;
2914        }
2915        if address == self.validation_observer.sender {
2916            self.validation_observer.touched_sender_slots.push(slot);
2917        } else {
2918            self.validation_observer
2919                .record_violation(FrameSimViolation::StorageReadNonSender);
2920        }
2921    }
2922
2923    /// EIP-8141 validation-trace `SSTORE` check (mempool simulation only).
2924    ///
2925    /// `SSTORE` is allowed only inside the deploy frame AND only when the storage
2926    /// owner (`address`, the executing frame's `to`) is the transaction sender.
2927    pub fn validation_check_sstore(&mut self, address: Address, slot: H256) {
2928        use crate::validation_observer::FrameSimViolation;
2929        if self.validation_observer.in_canonical_pay_frame() {
2930            return;
2931        }
2932        if self.validation_observer.in_deploy_frame() && address == self.validation_observer.sender
2933        {
2934            self.validation_observer.touched_sender_slots.push(slot);
2935        } else {
2936            self.validation_observer
2937                .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
2938        }
2939    }
2940
2941    /// EIP-8141 validation-trace state-creation check for `CREATE`/`CREATE2`
2942    /// (mempool simulation only). Contract creation is a state write permitted
2943    /// only inside the deploy frame.
2944    pub fn validation_check_create(&mut self) {
2945        use crate::validation_observer::FrameSimViolation;
2946        if self.validation_observer.in_canonical_pay_frame() {
2947            return;
2948        }
2949        if !self.validation_observer.in_deploy_frame() {
2950            self.validation_observer
2951                .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
2952        }
2953    }
2954
2955    /// EIP-8141 validation-trace `CALL*`/`EXTCODE*` target check (mempool
2956    /// simulation only).
2957    ///
2958    /// The target must be an existing account or a precompile and must NOT be
2959    /// EIP-7702-delegated, except the sender running its own default code (the
2960    /// sender is exempt — its existence is a transaction precondition and it may
2961    /// have no code). `is_delegation_7702` is the flag already computed by
2962    /// `eip7702_get_code` in the CALL-family handlers, threaded in to avoid a
2963    /// second delegation resolution (and the `&mut VM` / `&mut db` borrow
2964    /// conflict a dispatch-loop stack-peek would create).
2965    pub fn validation_check_call_target(
2966        &mut self,
2967        target: Address,
2968        is_delegation_7702: bool,
2969    ) -> Result<(), VMError> {
2970        use crate::validation_observer::FrameSimViolation;
2971        if self.validation_observer.in_canonical_pay_frame() {
2972            return Ok(());
2973        }
2974        // The sender is always a legitimate target (its existence is a tx
2975        // precondition; it may legitimately have no code).
2976        if target == self.validation_observer.sender {
2977            return Ok(());
2978        }
2979        // A delegated target is disallowed in validation.
2980        if is_delegation_7702 {
2981            self.validation_observer
2982                .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
2983            return Ok(());
2984        }
2985        // Precompiles are always valid targets.
2986        if precompiles::is_precompile(&target, self.env.config.fork, self.vm_type) {
2987            return Ok(());
2988        }
2989        // Otherwise the target must be an existing (non-empty) account.
2990        if self.db.get_account(target)?.is_empty() {
2991            self.validation_observer
2992                .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
2993        }
2994        Ok(())
2995    }
2996
2997    /// EIP-8141 validation-trace `EXTCODE*` target check (mempool simulation
2998    /// only). Like [`VM::validation_check_call_target`], but resolves the
2999    /// EIP-7702 delegation flag itself (the EXTCODE handlers do not call
3000    /// `eip7702_get_code`). The `substate.add_accessed_address` warming the
3001    /// EXTCODE gas already performed has happened; resolving here only follows a
3002    /// delegation indicator to read its flag, mirroring the CALL-family path.
3003    pub fn validation_check_extcode_target(&mut self, target: Address) -> Result<(), VMError> {
3004        if self.validation_observer.in_canonical_pay_frame()
3005            || target == self.validation_observer.sender
3006        {
3007            return Ok(());
3008        }
3009        let (is_delegation_7702, _access_cost, _code_address, _bytecode) =
3010            crate::utils::eip7702_get_code(
3011                self.db,
3012                &mut self.substate,
3013                target,
3014                self.env.config.fork,
3015            )?;
3016        self.validation_check_call_target(target, is_delegation_7702)
3017    }
3018
3019    /// Struct-log pre-step capture, split out of the interpreter loop and kept
3020    /// cold + non-inlined so the hot dispatch loop stays small (this code is
3021    /// only reached when a struct-log tracer is active). Returns `gas_before`.
3022    #[cold]
3023    #[inline(never)]
3024    fn trace_pre_step(&mut self, opcode: u8, pc_of_current_op: usize) -> u64 {
3025        #[expect(
3026            clippy::as_conversions,
3027            reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3028        )]
3029        let gas_before = self.current_call_frame.gas_remaining.max(0) as u64;
3030        #[expect(
3031            clippy::as_conversions,
3032            reason = "call depth bounded by STACK_LIMIT=1024, fits in u32"
3033        )]
3034        let depth = (self.call_frames.len() as u32).saturating_add(1);
3035        let refund = self.substate.refunded_gas;
3036        let stack_view = self.collect_stack_for_trace();
3037        let mem_view = self.collect_memory_for_trace();
3038        // mem_size always reflects actual memory size, regardless of enable_memory.
3039        #[expect(
3040            clippy::as_conversions,
3041            reason = "memory size is bounded by gas; fits in u64"
3042        )]
3043        let mem_size_for_trace = self.current_call_frame.memory.len() as u64;
3044        let storage_kv = self.read_storage_for_trace(opcode);
3045        let return_data = if self.opcode_tracer.cfg.enable_return_data {
3046            self.current_call_frame.sub_return_data.clone()
3047        } else {
3048            Bytes::new()
3049        };
3050        #[expect(
3051            clippy::as_conversions,
3052            reason = "pc is usize, fits in u64 on supported targets"
3053        )]
3054        let pc_u64 = pc_of_current_op as u64;
3055        self.opcode_tracer.pre_step_capture(
3056            pc_u64,
3057            opcode,
3058            gas_before,
3059            depth,
3060            refund,
3061            &stack_view,
3062            &mem_view,
3063            mem_size_for_trace,
3064            &return_data,
3065            storage_kv,
3066        );
3067        gas_before
3068    }
3069
3070    /// Struct-log post-step: patch gas_cost, refund-after-op, and error into the
3071    /// buffered entry. Cold + non-inlined for the same reason as `trace_pre_step`.
3072    #[cold]
3073    #[inline(never)]
3074    fn trace_post_step(&mut self, gas_before_op: u64, error: &OnceCell<VMError>) {
3075        #[expect(
3076            clippy::as_conversions,
3077            reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3078        )]
3079        let gas_after = self.current_call_frame.gas_remaining.max(0) as u64;
3080        // Prefer the explicit opcode-overhead cost written by CALL/CREATE handlers;
3081        // fall back to the gas diff for all other opcodes.
3082        let gas_cost = self
3083            .opcode_tracer
3084            .last_opcode_gas_cost
3085            .take()
3086            .unwrap_or_else(|| gas_before_op.saturating_sub(gas_after));
3087        // refund-after-op matches geth's structLogger timing: for SSTORE and
3088        // (pre-London) SELFDESTRUCT, the refund counter shown is the value
3089        // *after* the opcode's accounting applied.
3090        let refund_after = self.substate.refunded_gas;
3091        let err_str = error.get().map(|e| e.to_string());
3092        self.opcode_tracer
3093            .finalize_step(gas_cost, refund_after, err_str.as_deref());
3094    }
3095
3096    /// Executes precompile and handles the output that it returns, generating a report.
3097    pub fn execute_precompile(
3098        code_address: H160,
3099        calldata: &Bytes,
3100        gas_limit: u64,
3101        gas_remaining: &mut u64,
3102        fork: Fork,
3103        cache: Option<&precompiles::PrecompileCache>,
3104        crypto: &dyn Crypto,
3105    ) -> Result<ContextResult, VMError> {
3106        Self::handle_precompile_result(
3107            precompiles::execute_precompile(
3108                code_address,
3109                calldata,
3110                gas_remaining,
3111                fork,
3112                cache,
3113                crypto,
3114            ),
3115            gas_limit,
3116            *gas_remaining,
3117        )
3118    }
3119
3120    /// True if external transaction is a contract creation
3121    pub fn is_create(&self) -> Result<bool, InternalError> {
3122        Ok(self.current_call_frame.is_create)
3123    }
3124
3125    /// Executes without making changes to the cache.
3126    pub fn stateless_execute(&mut self) -> Result<ExecutionReport, VMError> {
3127        // Add backup hook to restore state after execution. `add_hook` flips
3128        // `preserve_top_level_backup` on via `Hook::reads_top_level_backup`, so the backup is
3129        // cloned (not moved out) on the revert paths even though this VM was built with L1 `vm_type`.
3130        self.add_hook(BackupHook::default());
3131        let report = self.execute()?;
3132        // Restore cache to the state before execution.
3133        self.db.undo_last_transaction()?;
3134        Ok(report)
3135    }
3136
3137    fn prepare_execution(&mut self) -> Result<(), VMError> {
3138        // Clone each hook's `Rc` (cheap refcount bump) so the borrow on `self.hooks` is released
3139        // and `self` can be passed mutably — without `self.hooks.clone()`'s per-tx `Vec` realloc.
3140        // `self.hooks` is not mutated during the loop, so `get(i)` is always `Some` in range.
3141        for i in 0..self.hooks.len() {
3142            if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3143                hook.borrow_mut().prepare_execution(self)?;
3144            }
3145        }
3146
3147        Ok(())
3148    }
3149
3150    fn finalize_execution(
3151        &mut self,
3152        mut ctx_result: ContextResult,
3153    ) -> Result<ExecutionReport, VMError> {
3154        // EIP-8037: On top-level tx failure (REVERT, ExceptionalHalt, or OOG), the
3155        // execution portion of state gas has already been refilled into the reservoir by
3156        // the top-frame `refill_frame_state_gas` (seeded at the post-intrinsic baseline in
3157        // `add_intrinsic_gas` and fired on revert/halt in `handle_opcode_error` /
3158        // `handle_opcode_result`). The intrinsic portion stays in `state_gas_used` so block
3159        // accounting bills it. No reservoir-move is performed here. A create-tx collision
3160        // rolls its own in-region `NEW_ACCOUNT` charge (if any) back to the frame's entry
3161        // baseline inside `handle_create_transaction`'s collision branch, so there is
3162        // nothing left to refill here either (see that function).
3163        //
3164        // EIP-8037: there is no longer a separate create-failure `NEW_ACCOUNT`
3165        // refund here. The charge itself (`prepare_execution`) is now
3166        // conditioned on `get_pre_state_account(created_addr) == EMPTY_ACCOUNT`, so it
3167        // simply never fires for an already-alive target (positive balance implies
3168        // non-empty pre-state) and is rolled back by `handle_create_transaction` on
3169        // collision — matching EELS v7, which drops the created-target-alive output flag
3170        // entirely because `prepare_dispatch` never runs for a colliding create.
3171
3172        // See `prepare_execution`: per-hook `Rc::clone` avoids the `self.hooks.clone()` realloc.
3173        for i in 0..self.hooks.len() {
3174            if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3175                hook.borrow_mut()
3176                    .finalize_execution(self, &mut ctx_result)?;
3177            }
3178        }
3179
3180        self.tracer.exit_context(&ctx_result, true)?;
3181
3182        // Struct-log end-of-tx capture: record final output, gas used, and revert error.
3183        // gas matches geth's `executionResult.Gas` which is post-refund (`receipt.GasUsed`).
3184        if self.opcode_tracer.active {
3185            self.opcode_tracer.output = ctx_result.output.clone();
3186            self.opcode_tracer.gas_used = ctx_result.gas_spent;
3187            self.opcode_tracer.error = match ctx_result.result {
3188                TxResult::Revert(ref err) => Some(err.to_string()),
3189                _ => None,
3190            };
3191        }
3192
3193        // Only include logs if transaction succeeded. When a transaction reverts,
3194        // no logs should be emitted (including EIP-7708 Transfer logs).
3195        let logs = if ctx_result.is_success() {
3196            self.substate.extract_logs()
3197        } else {
3198            Vec::new()
3199        };
3200
3201        // EIP-8037: `state_gas_used` is already net (signed; credits decrement it
3202        // inline), so `tx_state_gas = intrinsic_state_gas + state_gas_used` exactly
3203        // (EELS `fork.py::process_transaction`, which no longer carries a separate
3204        // tx-level refund channel). Clamp at zero — `state_gas_used` may be negative when
3205        // inline refunds exceed gross charges.
3206        let net_state_gas_used: u64 =
3207            u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
3208
3209        let report = ExecutionReport {
3210            result: ctx_result.result.clone(),
3211            gas_used: ctx_result.gas_used,
3212            gas_spent: ctx_result.gas_spent,
3213            gas_refunded: self.substate.refunded_gas,
3214            state_gas_used: net_state_gas_used,
3215            output: std::mem::take(&mut ctx_result.output),
3216            logs,
3217            payer_address: None,
3218            frame_results: None,
3219        };
3220
3221        Ok(report)
3222    }
3223
3224    // ── Struct-log helper methods ─────────────────────────────────────────────
3225
3226    /// Collects the current stack in bottom-first order for struct-log emission.
3227    ///
3228    /// LEVM stack is top-first in memory (`values[offset]` = top), so we reverse
3229    /// the active slice to produce the bottom-first wire format geth uses.
3230    /// Returns an empty `Vec` when `cfg.disable_stack` is true.
3231    pub fn collect_stack_for_trace(&self) -> Vec<U256> {
3232        use crate::constants::STACK_LIMIT;
3233        if self.opcode_tracer.cfg.disable_stack {
3234            return Vec::new();
3235        }
3236        let s = &self.current_call_frame.stack;
3237        // offset <= STACK_LIMIT by stack invariant.
3238        s.values
3239            .get(s.offset..STACK_LIMIT)
3240            .map(|slice| slice.iter().rev().copied().collect())
3241            .unwrap_or_default()
3242    }
3243
3244    /// Collects the live memory bytes for the current frame.
3245    ///
3246    /// Returns an empty `Vec` when `cfg.enable_memory` is false or memory is empty.
3247    pub fn collect_memory_for_trace(&self) -> Vec<u8> {
3248        if !self.opcode_tracer.cfg.enable_memory {
3249            return Vec::new();
3250        }
3251        self.current_call_frame.memory.live_bytes()
3252    }
3253
3254    /// Pre-reads the storage key/value for the current SLOAD or SSTORE opcode.
3255    ///
3256    /// Returns `None` when:
3257    /// - `cfg.disable_storage` is set, or
3258    /// - `opcode` is not SLOAD (0x54) or SSTORE (0x55), or
3259    /// - the stack is empty (guard against underflow before the handler runs), or
3260    /// - the storage read fails for any reason (including `AccountNotFound` —
3261    ///   the trace omits the entry rather than emitting an ambiguous zero).
3262    ///
3263    /// For SLOAD: key = `stack.top`; value = the *current* stored value read from the DB.
3264    /// For SSTORE: key = `stack.top`, value = `stack[top-1]` (the new value being written).
3265    pub fn read_storage_for_trace(&mut self, opcode: u8) -> Option<(H256, H256)> {
3266        const SLOAD: u8 = 0x54;
3267        const SSTORE: u8 = 0x55;
3268
3269        if self.opcode_tracer.cfg.disable_storage {
3270            return None;
3271        }
3272        if opcode != SLOAD && opcode != SSTORE {
3273            return None;
3274        }
3275
3276        // Need at least one element on stack for SLOAD, two for SSTORE.
3277        use crate::constants::STACK_LIMIT;
3278        let offset = self.current_call_frame.stack.offset;
3279        if offset >= STACK_LIMIT {
3280            return None; // stack empty
3281        }
3282
3283        // SLOAD/SSTORE operate on the call's storage context (`to`), not the code's
3284        // address. Under DELEGATECALL/CALLCODE these differ.
3285        let addr = self.current_call_frame.to;
3286
3287        let stack_values = &self.current_call_frame.stack.values;
3288        let key_u256 = *stack_values.get(offset)?;
3289        let key = BigEndianHash::from_uint(&key_u256);
3290
3291        if opcode == SLOAD {
3292            // Omit the entry on any read failure (incl. account not yet cached);
3293            // a zero value would be indistinguishable from a legitimate never-written slot.
3294            let v = self.get_storage_value(addr, key).ok()?;
3295            let value = BigEndianHash::from_uint(&v);
3296            Some((key, value))
3297        } else {
3298            // SSTORE: need two stack elements.
3299            let next_offset = offset.checked_add(1)?;
3300            if next_offset >= STACK_LIMIT {
3301                return None;
3302            }
3303            // values[offset+1] is the new value being written (second from top = stack[top-1]).
3304            let value_u256 = *self.current_call_frame.stack.values.get(next_offset)?;
3305            let value = BigEndianHash::from_uint(&value_u256);
3306            Some((key, value))
3307        }
3308    }
3309}
3310
3311impl Substate {
3312    /// Initializes the VM substate, mainly adding addresses to the "accessed_addresses" field and the same with storage slots
3313    pub fn initialize(env: &Environment, tx: &Transaction) -> Result<Substate, VMError> {
3314        let fork = env.config.fork;
3315
3316        // Add sender and recipient to accessed accounts [https://www.evm.codes/about#access_list]
3317        // Precompiles are NO LONGER inserted here — they are warm by construction (see
3318        // `is_warm_precompile`), removing the ~20-entry floor that used to dominate this set. The
3319        // remaining working set is small (sender + coinbase + recipient + access-list/touched
3320        // addresses; real p99 ~7), so a capacity of 8 covers most txs with little waste.
3321        let mut initial_accessed_addresses =
3322            FxHashSet::with_capacity_and_hasher(8, Default::default());
3323        // Storage slots are ~98% empty (p95 0, p99 4), so `default()` (alloc-free until first
3324        // insert) beats pre-sizing, which would tax the common empty case.
3325        let mut initial_accessed_storage_slots: FxHashMap<Address, FxHashSet<H256>> =
3326            FxHashMap::default();
3327
3328        // Add Tx sender to accessed accounts
3329        initial_accessed_addresses.insert(env.origin);
3330
3331        // [EIP-3651] - Add coinbase to accessed accounts after Shanghai
3332        if fork >= Fork::Shanghai {
3333            initial_accessed_addresses.insert(env.coinbase);
3334        }
3335
3336        // Add access lists contents to accessed accounts and accessed storage slots.
3337        // Iterate by reference (`Address`/`H256` are `Copy`); the old `.clone()` deep-copied
3338        // the whole `Vec<(Address, Vec<H256>)>` per tx just to read it.
3339        for (address, keys) in tx.access_list() {
3340            initial_accessed_addresses.insert(*address);
3341            // Access lists can have different entries even for the same address, that's why we check if there's an existing set instead of considering it empty
3342            let warm_slots = initial_accessed_storage_slots.entry(*address).or_default();
3343            for slot in keys {
3344                warm_slots.insert(*slot);
3345            }
3346        }
3347
3348        let substate = Substate::from_accesses(
3349            fork,
3350            initial_accessed_addresses,
3351            initial_accessed_storage_slots,
3352        );
3353
3354        Ok(substate)
3355    }
3356}
3357
3358// Test-support surface for the EIP-8037 state-gas reservoir/clamp-spill unit tests, which live
3359// in the `ethrex-test` crate (`test/tests/levm/eip8037_reservoir_tests.rs`) per the repo's
3360// test-location convention but must drive crate-private VM internals. Everything here is
3361// `#[doc(hidden)]` and exposes only what those tests touch: a fixture-free VM harness plus a
3362// handful of reservoir accessors. The harness builds the VM via struct literal to sidestep
3363// `VM::new`'s DB reads (which would pull `ethrex-storage`/`ethrex-blockchain` into levm and form
3364// a dependency cycle), keeping the two-pool arithmetic isolated.
3365#[doc(hidden)]
3366impl<'a> VM<'a> {
3367    /// Gas budget seeded into the harness top frame; large enough that spills never run it OOG.
3368    pub const STATE_GAS_HARNESS_FRAME_GAS: u64 = 1_000_000;
3369
3370    /// Builds a fixture-free VM on `fork` with a single top frame and the given starting
3371    /// `state_gas_reservoir`. `db`/`tx`/`crypto` are borrowed for the VM's lifetime but never
3372    /// read (the frame is built directly, so no account/storage/code loads occur).
3373    pub fn new_state_gas_harness(
3374        fork: Fork,
3375        db: &'a mut GeneralizedDatabase,
3376        tx: &'a Transaction,
3377        crypto: &'a dyn Crypto,
3378        state_gas_reservoir: u64,
3379    ) -> VM<'a> {
3380        let env = Environment {
3381            config: crate::environment::EVMConfig::new(
3382                fork,
3383                crate::environment::EVMConfig::canonical_values(fork),
3384            ),
3385            gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3386            block_gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3387            ..Default::default()
3388        };
3389        let current_call_frame = CallFrame::new(
3390            Address::default(),
3391            Address::default(),
3392            Address::default(),
3393            Code::default(),
3394            U256::zero(),
3395            Bytes::new(),
3396            false,
3397            Self::STATE_GAS_HARNESS_FRAME_GAS,
3398            0,
3399            true,
3400            false,
3401            0,
3402            0,
3403            Stack::default(),
3404            Memory::default(),
3405        );
3406        VM {
3407            call_frames: Vec::new(),
3408            current_call_frame,
3409            env,
3410            substate: Substate::default(),
3411            db,
3412            tx,
3413            hooks: Vec::new(),
3414            storage_original_values: FxHashMap::default(),
3415            tracer: LevmCallTracer::disabled(),
3416            opcode_tracer: LevmOpcodeTracer::disabled(),
3417            debug_mode: DebugMode::disabled(),
3418            stack_pool: Vec::new(),
3419            vm_type: VMType::L1,
3420            preserve_top_level_backup: false,
3421            state_gas_used: 0,
3422            state_gas_reservoir,
3423            state_gas_reservoir_initial: state_gas_reservoir,
3424            state_gas_spill: 0,
3425            cost_per_state_byte: 0,
3426            state_gas_new_account: 0,
3427            state_gas_storage_set: 0,
3428            state_gas_auth_base: 0,
3429            intrinsic_state_gas: 0,
3430            value_new_account_charged: false,
3431            prep_baseline_state_gas: 0,
3432            prep_baseline_reservoir: 0,
3433            prep_baseline_state_gas_spill: 0,
3434            prep_region_backup_marker: PrepareRegionBackupMarker::default(),
3435            pending_prep_oog: false,
3436            opcode_table: VM::build_opcode_table(fork),
3437            crypto,
3438            validation_observer: ValidationObserver::disabled(),
3439            frame_tx_context: None,
3440        }
3441    }
3442
3443    pub fn state_gas_reservoir(&self) -> u64 {
3444        self.state_gas_reservoir
3445    }
3446    pub fn state_gas_used(&self) -> i64 {
3447        self.state_gas_used
3448    }
3449    pub fn state_gas_spill(&self) -> u64 {
3450        self.state_gas_spill
3451    }
3452    pub fn state_gas_new_account(&self) -> u64 {
3453        self.state_gas_new_account
3454    }
3455    pub fn set_state_gas_new_account(&mut self, v: u64) {
3456        self.state_gas_new_account = v;
3457    }
3458    /// Seeds the post-intrinsic baseline (mirrors `add_intrinsic_gas`): both the VM-level
3459    /// `state_gas_used` and the top frame's entry snapshot.
3460    pub fn seed_state_gas_baseline(&mut self, used: i64) {
3461        self.state_gas_used = used;
3462        self.current_call_frame.state_gas_used_at_entry = used;
3463    }
3464    pub fn frame_state_gas_used_at_entry(&self) -> i64 {
3465        self.current_call_frame.state_gas_used_at_entry
3466    }
3467    pub fn frame_gas_remaining(&self) -> i64 {
3468        self.current_call_frame.gas_remaining
3469    }
3470    pub fn set_frame_gas_remaining(&mut self, v: i64) {
3471        self.current_call_frame.gas_remaining = v;
3472    }
3473    pub fn frame_state_gas_spilled(&self) -> u64 {
3474        self.current_call_frame.frame_state_gas_spilled
3475    }
3476}