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 §Behavior: 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/// secp256k1 group order `n`.
710const SECP256K1_N: [u8; 32] = [
711    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
712    0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41,
713];
714/// secp256k1 `n / 2`.
715const SECP256K1_N_HALF: [u8; 32] = [
716    0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
717    0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d, 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b, 0x20, 0xa0,
718];
719/// P-256 (secp256r1) group order `n`.
720const SECP256R1_N: [u8; 32] = [
721    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
722    0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
723];
724/// P-256 (secp256r1) `n / 2`.
725const SECP256R1_N_HALF: [u8; 32] = [
726    0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
727    0xde, 0x73, 0x7d, 0x56, 0xd3, 0x8b, 0xcf, 0x42, 0x79, 0xdc, 0xe5, 0x61, 0x7e, 0x31, 0x92, 0xa8,
728];
729
730/// True when the big-endian 32-byte scalar is in `(0, upper)`.
731fn scalar_below(scalar: &[u8], upper: &[u8; 32]) -> bool {
732    scalar.iter().any(|&b| b != 0) && scalar < &upper[..]
733}
734
735/// True when the big-endian 32-byte scalar is in `(0, upper]`.
736fn scalar_at_most(scalar: &[u8], upper: &[u8; 32]) -> bool {
737    scalar.iter().any(|&b| b != 0) && scalar <= &upper[..]
738}
739
740/// Validate every EIP-8141 outer signature against the canonical `sig_hash`.
741/// Returns false if any signature is malformed or invalid. Verification gas is
742/// intrinsic (already in `total_gas_limit`), so a scratch budget is used for the
743/// crypto precompiles and their deduction is ignored.
744#[expect(
745    clippy::indexing_slicing,
746    reason = "signature length is checked before each fixed-offset slice"
747)]
748pub fn validate_frame_signatures(
749    signatures: &[ethrex_common::types::FrameSignature],
750    sig_hash: ethrex_common::H256,
751    sender: ethrex_common::Address,
752    fork: Fork,
753    crypto: &dyn Crypto,
754) -> bool {
755    use ethrex_common::types::{
756        FRAME_SIG_SCHEME_ARBITRARY, FRAME_SIG_SCHEME_P256, FRAME_SIG_SCHEME_SECP256K1,
757    };
758    for sig in signatures {
759        // Resolve the signed message.
760        let msg: [u8; 32] = match sig.msg.len() {
761            0 => sig_hash.0,
762            32 => {
763                let mut m = [0u8; 32];
764                m.copy_from_slice(&sig.msg);
765                if m == [0u8; 32] {
766                    return false;
767                }
768                m
769            }
770            _ => return false,
771        };
772        let mut scratch_gas = u64::MAX;
773        match sig.scheme {
774            FRAME_SIG_SCHEME_SECP256K1 => {
775                if sig.signature.len() != 65 {
776                    return false;
777                }
778                let v = sig.signature[0];
779                let r = &sig.signature[1..33];
780                let s = &sig.signature[33..65];
781                // EIP-8141 requires a canonical signature: `v` is a bare recovery
782                // id (0 or 1), `0 < r < n`, and low-s per EIP-2 (`0 < s <= n/2`),
783                // so each signature has exactly one encoding.
784                if v > 1 || !scalar_below(r, &SECP256K1_N) || !scalar_at_most(s, &SECP256K1_N_HALF)
785                {
786                    return false;
787                }
788                // The ecrecover precompile takes `v` in EVM form (27 or 28).
789                let mut calldata = vec![0u8; 128];
790                calldata[..32].copy_from_slice(&msg);
791                calldata[63] = v.saturating_add(27);
792                calldata[64..96].copy_from_slice(r);
793                calldata[96..128].copy_from_slice(s);
794                let Ok(result) = crate::precompiles::ecrecover(
795                    &Bytes::from(calldata),
796                    &mut scratch_gas,
797                    fork,
798                    crypto,
799                ) else {
800                    return false;
801                };
802                if result.len() != 32 {
803                    return false;
804                }
805                let recovered = ethrex_common::Address::from_slice(&result[12..]);
806                if recovered == ethrex_common::Address::zero() {
807                    return false;
808                }
809                // Per EIP-8141, an absent signer resolves to tx.sender (used for
810                // introspection too); the recovered key must equal the resolved signer.
811                if recovered != sig.signer.unwrap_or(sender) {
812                    return false;
813                }
814            }
815            FRAME_SIG_SCHEME_P256 => {
816                if sig.signature.len() != 128 {
817                    return false;
818                }
819                let r = &sig.signature[0..32];
820                let s = &sig.signature[32..64];
821                let qx = &sig.signature[64..96];
822                let qy = &sig.signature[96..128];
823                // EIP-8141 requires `0 < r < n` and low-s (`0 < s <= n/2`) so each
824                // signature has one encoding. P256VERIFY itself accepts high-s, so
825                // signers must normalize `s` to `n - s` before use.
826                if !scalar_below(r, &SECP256R1_N) || !scalar_at_most(s, &SECP256R1_N_HALF) {
827                    return false;
828                }
829                // signer = keccak256(qx || qy)[12:]  (NO domain separator)
830                let mut pk = Vec::with_capacity(64);
831                pk.extend_from_slice(qx);
832                pk.extend_from_slice(qy);
833                let h = ethrex_crypto::keccak::keccak_hash(&pk);
834                // Per EIP-8141, an absent signer resolves to tx.sender (used for
835                // introspection too); the derived key must equal the resolved signer.
836                if ethrex_common::Address::from_slice(&h[12..]) != sig.signer.unwrap_or(sender) {
837                    return false;
838                }
839                let mut calldata = vec![0u8; 160];
840                calldata[..32].copy_from_slice(&msg);
841                calldata[32..64].copy_from_slice(r);
842                calldata[64..96].copy_from_slice(s);
843                calldata[96..128].copy_from_slice(qx);
844                calldata[128..160].copy_from_slice(qy);
845                let Ok(result) = crate::precompiles::p_256_verify(
846                    &Bytes::from(calldata),
847                    &mut scratch_gas,
848                    fork,
849                    crypto,
850                ) else {
851                    return false;
852                };
853                if result.len() != 32 || result[31] != 1 {
854                    return false;
855                }
856            }
857            FRAME_SIG_SCHEME_ARBITRARY => {
858                // ARBITRARY: no protocol crypto; the signer must be empty. A
859                // custom verifier reads the raw bytes via SIGPARAM 0x04.
860                if sig.signer.is_some() {
861                    return false;
862                }
863            }
864            _ => return false,
865        }
866    }
867    true
868}
869
870/// Find the end of the atomic batch containing `failed_idx`, per EIP-8141:
871/// a batch is a maximal contiguous run of frames whose ATOMIC_BATCH_FLAG is
872/// set, terminated by the first frame without the flag. Static validation
873/// guarantees no VERIFY frame carries the flag or terminates a batch, so every
874/// frame in the returned range is DEFAULT or SENDER. Returns the index of the
875/// 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: 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            frame_tx.sender,
1617            self.env.config.fork,
1618            self.crypto,
1619        ) {
1620            return Err(VMError::TxValidation(
1621                crate::errors::TxValidationError::InvalidFrameTransaction,
1622            ));
1623        }
1624
1625        // Tx-level rollback accumulator: if the tx is later declared invalid
1626        // after frames committed, restore `db.current_accounts_state` so the
1627        // payload builder (which reuses the shared db across txs) sees no
1628        // residue — same Err contract as non-frame `execute()`. The per-frame
1629        // backup is cleared between independent frames (and at batch entry), so
1630        // each frame's original values are absorbed here (first-seen-wins)
1631        // before that clear destroys them. Substate is per-VM and discarded on
1632        // Err, so it needs no snapshot.
1633        let mut tx_level_backup = crate::call_frame::CallFrameBackup {
1634            bal_checkpoint: self.db.bal_recorder.as_ref().map(|r| r.checkpoint()),
1635            ..Default::default()
1636        };
1637
1638        // ENTRY_POINT address used as caller for DEFAULT/VERIFY frames
1639        let entry_point = ethrex_common::types::frame_tx_entry_point();
1640
1641        let mut all_logs: Vec<Log> = Vec::new();
1642        let sum_frame_gas_limits: u64 = frame_tx
1643            .frames
1644            .iter()
1645            .map(|f| f.gas_limit)
1646            .fold(0u64, |acc, g| acc.saturating_add(g));
1647        let intrinsic_gas = total_gas_limit.saturating_sub(sum_frame_gas_limits);
1648        let mut total_gas_used: u64 = intrinsic_gas;
1649        let mut tx_invalid = false;
1650
1651        // Atomic batching state: track whether we're inside a batch and
1652        // which frames belong to it so we can revert them all on failure.
1653        let mut in_atomic_batch = false;
1654        let mut batch_start_idx: usize = 0;
1655        let mut batch_logs_start: usize = 0;
1656        let mut batch_approval_snapshot: (bool, Option<Address>) = (false, None);
1657        // EIP-8037: snapshot the shared `state_gas_used` at batch entry so a batch
1658        // revert (which unrolls every in-batch frame's state) also drops the state
1659        // gas those frames accumulated.
1660        let mut state_gas_used_at_batch_entry: i64 = 0;
1661        let mut skip_until_batch_end: Option<usize> = None; // skip remaining frames in a failed batch
1662
1663        // Execute frames sequentially
1664        for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
1665            // If we're skipping frames due to an atomic batch revert, record
1666            // the frame with status SKIPPED. Per EIP-8141, the
1667            // gas allotted to skipped frames is refunded at the end of the
1668            // transaction, so we record `gas_used = 0` and do NOT add the
1669            // frame's `gas_limit` to `total_gas_used`.
1670            //
1671            // Note (EIP-8141): an expiry verifier frame has flags
1672            // == 0, so it can only be a batch TERMINATOR, never a flagged
1673            // member. A failed batch therefore skips a trailing expiry frame
1674            // and its deadline is not checked at execution time. This is
1675            // benign, not a bypass: `compute_sig_hash` commits to the full
1676            // frame layout (modes, flags incl. the atomic-batch flag, targets,
1677            // and the expiry deadline), and the VERIFY signature is recovered
1678            // over that hash — so no relayer/proposer can wrap a signed tx's
1679            // expiry frame in a failing batch. Only the sender can build this
1680            // layout, and doing so merely disarms their own expiry. The normal
1681            // pattern (a standalone expiry VERIFY frame, not batched) is fully
1682            // enforced. The skip itself is spec-mandated batch semantics; do
1683            // not change it unilaterally — that would be a consensus divergence.
1684            if let Some(end_idx) = skip_until_batch_end {
1685                if frame_idx <= end_idx {
1686                    let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
1687                        InternalError::Custom("missing frame tx context".to_string()),
1688                    ))?;
1689                    ctx.current_frame_index = frame_idx;
1690                    ctx.frame_results.push((
1691                        ethrex_common::types::FRAME_RECEIPT_STATUS_SKIPPED,
1692                        0,
1693                        Vec::new(),
1694                    ));
1695                    if frame_idx == end_idx {
1696                        skip_until_batch_end = None;
1697                        in_atomic_batch = false;
1698                    }
1699                    continue;
1700                }
1701                skip_until_batch_end = None;
1702                in_atomic_batch = false;
1703            }
1704
1705            // Clear the outer call-frame backup at the start of each independent
1706            // frame so that a later frame's failure-path `restore_cache_state()`
1707            // only reverts that frame's own effects — not APPROVE/state deltas
1708            // produced by earlier, already-successful frames. Inside an open
1709            // atomic batch we keep accumulating, since a batch revert needs to
1710            // undo every in-batch frame's effects together.
1711            if !in_atomic_batch {
1712                // Absorb this frame's originals into the tx-level accumulator
1713                // before clearing, so an invalid-tx exit can still roll back
1714                // every committed frame's state (see `tx_level_backup`).
1715                tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
1716                self.current_call_frame.call_frame_backup.clear();
1717            }
1718
1719            // Start a new atomic batch if this frame has the batch flag
1720            // and we're not already in one.
1721            if !in_atomic_batch && frame.is_atomic_batch() {
1722                self.substate.push_backup(); // batch-level snapshot
1723                // The outer call-frame backup is already empty here: the
1724                // `!in_atomic_batch` block above absorbed it into
1725                // `tx_level_backup` and cleared it on entry to this frame, so
1726                // the batch starts accumulating a clean, self-contained set of
1727                // state changes that batch-revert can undo wholesale.
1728                in_atomic_batch = true;
1729                batch_start_idx = frame_idx;
1730                batch_logs_start = all_logs.len();
1731                state_gas_used_at_batch_entry = self.state_gas_used;
1732                // Snapshot approvals at batch entry: a batch revert must also
1733                // roll back approvals granted inside the batch (their balance
1734                // and nonce effects are reverted with the substate).
1735                batch_approval_snapshot = self
1736                    .frame_tx_context
1737                    .as_ref()
1738                    .map(|c| c.approval_snapshot())
1739                    .unwrap_or((false, None));
1740            }
1741
1742            let ctx =
1743                self.frame_tx_context
1744                    .as_mut()
1745                    .ok_or(VMError::Internal(InternalError::Custom(
1746                        "missing frame tx context".to_string(),
1747                    )))?;
1748            ctx.current_frame_index = frame_idx;
1749            ctx.approve_called_in_current_frame = false;
1750
1751            let target = frame.target.unwrap_or(sender);
1752
1753            // Determine caller and static mode per frame mode
1754            let (caller, is_static) = match frame.execution_mode() {
1755                FrameMode::Default => (entry_point, false),
1756                FrameMode::Verify => (entry_point, true),
1757                FrameMode::Sender => {
1758                    // SENDER mode requires sender_approved
1759                    let ctx = self.frame_tx_context.as_ref().ok_or(VMError::Internal(
1760                        InternalError::Custom("missing frame tx context".to_string()),
1761                    ))?;
1762                    if !ctx.sender_approved {
1763                        tx_invalid = true;
1764                        break;
1765                    }
1766                    (sender, false)
1767                }
1768            };
1769
1770            // Set env.origin for this frame (ORIGIN opcode reads this)
1771            self.env.origin = caller;
1772
1773            // Resolve any EIP-7702 delegation at the resolved target. For a non-delegated
1774            // target this is equivalent to `db.get_account_code(target)`; for a delegated
1775            // target it follows the 0xef0100 || addr indicator and returns the delegatee's
1776            // bytecode plus the resolved code_address. EIP-8141 §Execution step 1 requires
1777            // delegated targets to execute the delegatee's code while keeping ADDRESS/storage
1778            // tied to the delegator — which is why `to` below stays `target` but the
1779            // CallFrame receives the resolved `code_address`. Mirrors the pattern used at
1780            // top-level tx entry in default_hook::set_bytecode_and_code_address.
1781            //
1782            // access_cost is intentionally discarded: this frame entry is analogous to a
1783            // top-level tx entry (a call from 0xaa / tx.sender, not a CALL opcode), and
1784            // default_hook.rs drops the same cost there. EIP-8141 §Execution is silent on
1785            // billing the 7702 access cost for `resolved_target`, so we keep frame-entry
1786            // behavior consistent with tx-entry behavior.
1787            let (is_delegation_7702, _access_cost, code_address, bytecode) =
1788                crate::utils::eip7702_get_code(
1789                    self.db,
1790                    &mut self.substate,
1791                    target,
1792                    self.env.config.fork,
1793                )?;
1794
1795            // Mirror default_hook::set_bytecode_and_code_address: when delegation was
1796            // followed, record the delegatee (code_address) as touched in BAL so EIP-7928
1797            // reconstructors see the cross-address read.
1798            if is_delegation_7702 && let Some(recorder) = self.db.bal_recorder.as_mut() {
1799                recorder.record_touched_address(code_address);
1800            }
1801
1802            // Log count of the scope this frame's backup will be committed into.
1803            // The CallFrame branch below relies on `run_execution` having already
1804            // committed the frame (merging its logs up into this scope), then
1805            // slices `[substate_logs_before..]` to recover exactly this frame's
1806            // logs without re-committing.
1807            let substate_logs_before = self.substate.logs_len();
1808
1809            // Push substate backup for per-frame state isolation
1810            self.substate.push_backup();
1811
1812            // EIP-8141 top-level value transfer: the outer
1813            // frame call owns CALLVALUE delivery. We only CHECK affordability
1814            // here; the actual transfer runs inside whichever branch executes
1815            // the frame, so it is recorded in the backup that branch restores on
1816            // failure (fixes the value-leak where a reverting contract-target
1817            // SENDER frame kept the funds). Static validation guarantees only
1818            // SENDER frames reach here with a non-zero value.
1819            let value_transfer_reverted = if !frame.value.is_zero() {
1820                let sender_balance = self.db.get_account(sender)?.info.balance;
1821                frame_value_exceeds_balance(sender_balance, frame.value)
1822            } else {
1823                false
1824            };
1825
1826            // Performs the deferred SENDER-frame value transfer + EIP-7708 log.
1827            // Invoked in BOTH execution branches so the transfer is recorded in
1828            // the call_frame_backup that branch's failure path restores.
1829            macro_rules! do_frame_value_transfer {
1830                () => {
1831                    if !frame.value.is_zero() && !value_transfer_reverted {
1832                        self.transfer(sender, target, frame.value)?;
1833                        // EIP-7708 log parity with default_hook::transfer_value:
1834                        // only Amsterdam+ and only when sender != target.
1835                        if self.env.config.fork >= Fork::Amsterdam && sender != target {
1836                            let log =
1837                                crate::utils::create_eth_transfer_log(sender, target, frame.value);
1838                            self.substate.add_log(log);
1839                        }
1840                    }
1841                };
1842            }
1843
1844            // EIP-8037: capture state-gas accounting before the frame runs so a
1845            // reverted frame (which commits no state) can be rolled back to
1846            // contribute zero state gas. The reservoir/spill are captured too:
1847            // each frame is gas-isolated, so an inline state-gas refund (e.g. an
1848            // SSTORE 0->N->0 clear, which credits the reservoir) inside one frame
1849            // must NOT carry over to a later frame's charges — the reservoir is
1850            // reset to this entry value after the frame completes.
1851            let state_gas_used_at_frame_entry = self.state_gas_used;
1852            let state_gas_reservoir_at_frame_entry = self.state_gas_reservoir;
1853            let state_gas_spill_at_frame_entry = self.state_gas_spill;
1854
1855            let (frame_success, frame_gas_used, frame_logs) = if value_transfer_reverted {
1856                self.substate.revert_backup();
1857                self.restore_cache_state()?;
1858                (false, frame.gas_limit, Vec::new())
1859            } else if bytecode.is_empty() && !is_delegation_7702 {
1860                // Default code runs only when the target has NEITHER code NOR a delegation
1861                // indicator (EIP-8141 §Execution). After eip7702_get_code,
1862                // bytecode is the delegatee's code when delegated, so a delegation to an
1863                // empty delegatee still falls into the CallFrame branch below and returns
1864                // success without executing anything — NOT into the default-code path.
1865                // current_call_frame is the OUTER frame here; its backup is the
1866                // one this branch's failure path restores, so the deferred
1867                // transfer is correctly undone on a default-code revert.
1868                do_frame_value_transfer!();
1869                use crate::opcode_handlers::frame_tx::execute_default_code;
1870                match execute_default_code(self, frame, target) {
1871                    Ok((success, gas_used, logs)) => {
1872                        if success {
1873                            // Capture this frame's substate logs (incl. the
1874                            // EIP-7708 transfer log added by
1875                            // do_frame_value_transfer!) BEFORE commit_backup
1876                            // merges them into the parent — mirrors the
1877                            // CallFrame branch. execute_default_code returns its
1878                            // own logs separately, so include both.
1879                            let mut this_frame_logs = self.substate.current_logs();
1880                            this_frame_logs.extend(logs);
1881                            self.substate.commit_backup();
1882                            (true, gas_used, this_frame_logs)
1883                        } else {
1884                            self.substate.revert_backup();
1885                            self.restore_cache_state()?;
1886                            (false, gas_used, Vec::new())
1887                        }
1888                    }
1889                    Err(_) => {
1890                        self.substate.revert_backup();
1891                        self.restore_cache_state()?;
1892                        (false, frame.gas_limit, Vec::new())
1893                    }
1894                }
1895            } else {
1896                // Normal code execution via CallFrame. msg_value carries
1897                // `frame.value` so the contract sees the correct CALLVALUE
1898                // (EIP-8141 §Behavior), but `should_transfer_value` stays
1899                // false because the deferred `do_frame_value_transfer!()` below
1900                // (invoked after the frame swap) owns the transfer — the inner
1901                // CALL machinery must not move the funds a second time.
1902                let call_frame = CallFrame::new(
1903                    caller,                                    // msg_sender
1904                    target,                                    // to (delegator; ADDRESS/storage)
1905                    code_address,                              // code_address (delegatee when 7702)
1906                    bytecode,           // bytecode (delegatee's code when 7702)
1907                    frame.value,        // msg_value -- CALLVALUE
1908                    frame.data.clone(), // calldata
1909                    is_static,          // is_static
1910                    frame.gas_limit,    // gas_limit
1911                    0,                  // depth
1912                    false, // should_transfer_value (do_frame_value_transfer! handles it)
1913                    false, // is_create
1914                    0,     // ret_offset
1915                    0,     // ret_size
1916                    self.stack_pool.pop().unwrap_or_default(), // stack
1917                    Memory::default(), // memory
1918                );
1919
1920                let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
1921                let saved_call_frames = mem::take(&mut self.call_frames);
1922
1923                // current_call_frame is now the INNER frame, so the deferred
1924                // transfer records into the inner backup that the revert failure
1925                // path (self.substate.revert_backup + restore_cache_state)
1926                // restores — fixing the value-leak on a reverting SENDER frame.
1927                do_frame_value_transfer!();
1928
1929                let frame_result = self.run_execution();
1930
1931                let result = match frame_result {
1932                    Ok(ctx_result) => {
1933                        let gas_used = ctx_result.gas_used;
1934                        let success = ctx_result.is_success();
1935
1936                        if success {
1937                            // The inner frame is the initial call frame (call_frames
1938                            // was emptied above), so `run_execution` already ran
1939                            // `handle_state_backup` and committed this frame's backup,
1940                            // merging its logs up into the scope measured by
1941                            // `substate_logs_before`. Recover exactly this frame's logs
1942                            // by slicing off everything that predated it — do NOT commit
1943                            // again (a second commit would collapse an extra backup
1944                            // level, breaking atomic-batch rollback) and do NOT read
1945                            // `current_logs()` wholesale (it now also holds prior frames'
1946                            // logs, which would duplicate them into frame_receipts[i]).
1947                            let mut merged_logs = self.substate.current_logs();
1948                            let this_frame_logs = merged_logs.split_off(substate_logs_before);
1949                            (true, gas_used, this_frame_logs)
1950                        } else {
1951                            // A normal EVM revert reaches `handle_state_backup` inside
1952                            // `run_execution`, which already reverted the backup and
1953                            // restored the cache for this frame; repeating it here would
1954                            // revert an extra level.
1955                            (false, gas_used, Vec::new())
1956                        }
1957                    }
1958                    Err(_e) => {
1959                        // A `VMError` propagates out of `run_execution` before it reaches
1960                        // `handle_state_backup`, so this frame's backup is still live and
1961                        // must be reverted (and the cache restored) here.
1962                        self.substate.revert_backup();
1963                        self.restore_cache_state()?;
1964                        (false, frame.gas_limit, Vec::new())
1965                    }
1966                };
1967
1968                // Restore call frame state
1969                let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
1970                self.call_frames = saved_call_frames;
1971
1972                // When a frame succeeds inside an atomic batch, its state
1973                // changes must remain revertable at batch-revert time. Merge
1974                // the finished frame's backup into the outer call-frame backup
1975                // so that `restore_cache_state()` invoked by batch-revert can
1976                // undo them — and so the next clear-and-absorb folds them into
1977                // `tx_level_backup` too. Outside a batch, the finished frame's
1978                // backup never reaches the outer call frame, so absorb it
1979                // directly into `tx_level_backup` here; otherwise an invalid-tx
1980                // exit could not roll back this committed frame's state.
1981                if result.0 {
1982                    if in_atomic_batch {
1983                        self.merge_call_frame_backup_with_parent(
1984                            &finished_frame.call_frame_backup,
1985                        )?;
1986                    } else {
1987                        tx_level_backup.absorb(&finished_frame.call_frame_backup);
1988                    }
1989                }
1990
1991                self.stack_pool.push(finished_frame.stack);
1992
1993                result
1994            };
1995
1996            // EIP-8037: a failed frame's state changes were reverted above, so it
1997            // creates no state and must contribute zero state gas. Roll the shared
1998            // `state_gas_used` back to this frame's entry value (the cache/substate
1999            // were already restored in the failure arms). Successful frames keep
2000            // their accumulated state gas.
2001            if !frame_success {
2002                self.state_gas_used = state_gas_used_at_frame_entry;
2003            }
2004            // EIP-8037: frames are gas-isolated, so the state-gas reservoir/spill
2005            // must not leak across the frame boundary. A reservoir credit from an
2006            // inline refund inside this frame (or a reverted frame's inflated
2007            // reservoir) would otherwise subsidize the next frame's state charges
2008            // (drawn before any spill to gas_remaining). Reset both to this frame's
2009            // entry value unconditionally — a successful frame already folded its
2010            // inline refund into `state_gas_used`, so the leftover reservoir credit
2011            // is spent and must be dropped.
2012            self.state_gas_reservoir = state_gas_reservoir_at_frame_entry;
2013            self.state_gas_spill = state_gas_spill_at_frame_entry;
2014
2015            total_gas_used = total_gas_used
2016                .checked_add(frame_gas_used)
2017                .ok_or(VMError::Internal(InternalError::Overflow))?;
2018            all_logs.extend(frame_logs.clone());
2019
2020            // Store frame result in context
2021            let ctx =
2022                self.frame_tx_context
2023                    .as_mut()
2024                    .ok_or(VMError::Internal(InternalError::Custom(
2025                        "missing frame tx context".to_string(),
2026                    )))?;
2027            let status_code = if frame_success {
2028                ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS
2029            } else {
2030                ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE
2031            };
2032            ctx.frame_results
2033                .push((status_code, frame_gas_used, frame_logs));
2034
2035            // Atomic batch: if a frame in the batch reverted, revert the
2036            // batch-level snapshot and skip remaining frames in the batch.
2037            if in_atomic_batch && !frame_success {
2038                self.substate.revert_backup(); // revert batch-level snapshot
2039                self.restore_cache_state()?;
2040                // EIP-8037: the whole batch unrolled, so none of its frames created
2041                // state — drop the state gas accumulated since batch entry.
2042                self.state_gas_used = state_gas_used_at_batch_entry;
2043
2044                // Rewrite results for all frames in this batch (inclusive) as failed,
2045                // charging each frame its full gas_limit per EIP-8141.
2046                let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
2047                    InternalError::Custom("missing frame tx context".to_string()),
2048                ))?;
2049                for i in batch_start_idx..=frame_idx {
2050                    if let (Some(result), Some(batch_frame)) =
2051                        (ctx.frame_results.get_mut(i), frame_tx.frames.get(i))
2052                    {
2053                        let charged_gas = batch_frame.gas_limit;
2054                        total_gas_used = total_gas_used
2055                            .saturating_sub(result.1)
2056                            .saturating_add(charged_gas);
2057                        *result = (
2058                            ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE,
2059                            charged_gas,
2060                            Vec::new(),
2061                        );
2062                    }
2063                }
2064                // Roll back approvals granted inside the reverted batch.
2065                ctx.restore_approvals(batch_approval_snapshot);
2066                // Remove only logs from the batch, preserving pre-batch logs
2067                all_logs.truncate(batch_logs_start);
2068
2069                // Spec: a reverted VERIFY frame invalidates the transaction even
2070                // inside an atomic batch. The batch unroll above already rolled
2071                // back state/approvals; validity is a tx-level decision. (The
2072                // failing `frame` here is the one that triggered the revert.)
2073                if frame.execution_mode() == FrameMode::Verify {
2074                    tx_invalid = true;
2075                    break;
2076                }
2077
2078                // Find the end of this batch (the first frame at or after the
2079                // failing one without the flag)
2080                let batch_end = find_batch_end(&frame_tx.frames, frame_idx);
2081
2082                if batch_end > frame_idx {
2083                    skip_until_batch_end = Some(batch_end);
2084                } else {
2085                    in_atomic_batch = false;
2086                }
2087                self.substate.clear_transient_storage();
2088                continue;
2089            }
2090
2091            // If this is the last frame of a batch (a frame without the flag), commit the batch
2092            if in_atomic_batch && !frame.is_atomic_batch() {
2093                self.substate.commit_backup(); // commit batch-level snapshot
2094                in_atomic_batch = false;
2095            }
2096
2097            // VERIFY frame enforcement: a reverted
2098            // VERIFY frame invalidates the transaction. A VERIFY frame that
2099            // succeeds WITHOUT calling APPROVE is valid (e.g. the expiry
2100            // verifier frame). A reverted VERIFY frame invalidates the tx;
2101            // batched VERIFY reverts are handled in the atomic-batch-revert
2102            // branch above (which also sets tx_invalid).
2103            if frame.execution_mode() == FrameMode::Verify && !frame_success {
2104                tx_invalid = true;
2105                break;
2106            }
2107
2108            // Clear transient storage between frames
2109            self.substate.clear_transient_storage();
2110        }
2111
2112        // Post-execution, per EIP-8141: "verify that `payer` has been set
2113        // (i.e. `payer != None`). If `payer` is set, refund any unpaid gas to
2114        // the payer. If it is not, the whole transaction is invalid."
2115        let ctx =
2116            self.frame_tx_context
2117                .as_ref()
2118                .ok_or(VMError::Internal(InternalError::Custom(
2119                    "missing frame tx context".to_string(),
2120                )))?;
2121        if ctx.payer_address.is_none() {
2122            tx_invalid = true;
2123        }
2124
2125        if tx_invalid {
2126            // TX is invalid — Err must leave `db.current_accounts_state`
2127            // unchanged from before the tx (same contract as non-frame
2128            // `execute()`). Absorb the last live frame's backup (it has not
2129            // been cleared yet), then restore every absorbed frame's effects.
2130            // Substate is per-VM and discarded when this VM drops, so no
2131            // substate revert is needed.
2132            tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2133            crate::utils::restore_cache_state(self.db, tx_level_backup)?;
2134            return Err(VMError::TxValidation(
2135                crate::errors::TxValidationError::InvalidFrameTransaction,
2136            ));
2137        }
2138
2139        // Take ownership of frame context
2140        let ctx = self
2141            .frame_tx_context
2142            .take()
2143            .ok_or(VMError::Internal(InternalError::Custom(
2144                "missing frame tx context".to_string(),
2145            )))?;
2146        let payer = ctx.payer_address.unwrap_or(sender);
2147
2148        // EIP-8141 gas finalization. EIP-3529 storage refunds accumulate into a
2149        // single transaction-scoped counter across frames — `substate.refunded_gas`,
2150        // which a reverted frame or an unrolled atomic batch drops along with its
2151        // state changes — and are applied once here, capped at a fifth of the gas
2152        // used before refunds. The EIP-7623 calldata floor then applies to the frame
2153        // and signature data: the mandatory costs are always charged, and the data
2154        // cost is floored against what execution actually consumed.
2155        let mandatory_gas = frame_tx.mandatory_gas();
2156        let applied_refund = self
2157            .substate
2158            .refunded_gas
2159            .min(total_gas_used / crate::hooks::default_hook::MAX_REFUND_QUOTIENT);
2160        let data_and_execution = total_gas_used
2161            .saturating_sub(applied_refund)
2162            .saturating_sub(mandatory_gas);
2163        let total_gas_used =
2164            mandatory_gas.saturating_add(data_and_execution.max(frame_tx.calldata_floor_gas()));
2165
2166        // Gas refunds: the payer was debited the transaction's MAXIMUM cost at
2167        // APPROVE (max_fee-based gas + max-rate blob cost, `compute_tx_max_cost`,
2168        // §Gas Accounting). What the payer owes is the effective-rate cost of the
2169        // gas actually used plus the base-rate blob burn (EIP-4844 semantics);
2170        // everything above that is returned here. Intrinsic gas is inside
2171        // `total_gas_used`, so it stays non-refundable. When max_fee ==
2172        // effective_gas_price and max_fee_per_blob_gas == base_blob_fee this
2173        // reduces exactly to the old unused-frame-gas refund:
2174        // max·T + B − e·U − B = e·(T − U).
2175        let effective_gas_price = self.env.gas_price;
2176        let charged = crate::opcode_handlers::frame_tx::compute_tx_max_cost(&ctx)
2177            .map_err(|_| VMError::Internal(InternalError::Overflow))?;
2178        let blob_burn = crate::utils::calculate_blob_gas_cost(
2179            &ctx.tx.blob_versioned_hashes,
2180            self.env.base_blob_fee_per_gas,
2181        )?;
2182        let owed = effective_gas_price
2183            .checked_mul(U256::from(total_gas_used))
2184            .and_then(|gas_owed| gas_owed.checked_add(blob_burn))
2185            .ok_or(VMError::Internal(InternalError::Overflow))?;
2186        // charged >= owed always: effective <= max_fee (by construction of the
2187        // effective price), base_blob <= max_blob (blob-fee validity check), and
2188        // total_gas_used <= total_gas_limit (frames are bounded by their limits).
2189        let refund_amount = charged
2190            .checked_sub(owed)
2191            .ok_or(VMError::Internal(InternalError::Underflow))?;
2192
2193        self.increase_account_balance(payer, refund_amount)?;
2194
2195        // Pay coinbase. Mirror `pay_coinbase` on the normal-tx path so a frame
2196        // transaction has the same coinbase BlockAccessList / witness footprint:
2197        // EIP-7928 requires the coinbase to appear in the BAL for any user tx even
2198        // when the priority fee is zero, and EELS reads the coinbase account
2199        // unconditionally during fee transfer (so EIP-8025 witnesses record its
2200        // trie path even at zero fee). A frame tx is always a user tx (non-zero
2201        // effective gas price), unlike a system call.
2202        let priority_fee = effective_gas_price.saturating_sub(self.env.base_fee_per_gas);
2203        let coinbase_fee = priority_fee
2204            .checked_mul(U256::from(total_gas_used))
2205            .ok_or(VMError::Internal(InternalError::Overflow))?;
2206        if !effective_gas_price.is_zero()
2207            && let Some(recorder) = self.db.bal_recorder.as_mut()
2208        {
2209            recorder.record_touched_address(self.env.coinbase);
2210        }
2211        if coinbase_fee.is_zero() {
2212            // Zero priority fee: still read the coinbase so its witness/BAL trie
2213            // path (incl. an exclusion proof if absent) is recorded.
2214            self.db.get_account(self.env.coinbase)?;
2215        } else {
2216            self.increase_account_balance(self.env.coinbase, coinbase_fee)?;
2217        }
2218
2219        // EIP-8141: finalize self-destructs at tx end, mirroring the default
2220        // finalize hook ordering (refund -> coinbase -> delete). SELFDESTRUCT is
2221        // unrestricted during frame execution (the banned-opcode set only applies
2222        // to the mempool validation prefix), so a frame may mark same-tx-created
2223        // accounts for deletion (EIP-6780). Without this they leak into the
2224        // post-state. `iter_selfdestruct` walks the full substate chain, so a
2225        // single call here covers every committed frame. Any EIP-7708 burn logs
2226        // emitted (rare: only when a destroyed account later received ETH in the
2227        // same tx) are appended to the tx-level aggregate `all_logs`: the per-frame
2228        // consensus receipts have no slot for end-of-tx logs, but the header and
2229        // receipt blooms are derived from these aggregate logs (receipt.rs,
2230        // payload.rs), so they must be recorded there.
2231        //
2232        // KNOWN SPEC GAP (cross-client interop): these tx-end burn logs are in the
2233        // aggregate bloom but NOT in any per-frame consensus receipt, so a client
2234        // that re-derives the type-0x06 logs_bloom purely from the canonical
2235        // per-frame logs would compute a different bloom (part of the block hash).
2236        // ethrex producer and validator agree (both execute over the live
2237        // aggregate), so this is not an intra-client split; it only bites
2238        // cross-client and only for this rare destroy-after-receiving-ETH case.
2239        // EIP-7708 is silent on receipt placement and EIP-8141's frame receipt has
2240        // no tx-level logs slot, so the canonical home is genuinely undefined; do
2241        // not pin one (e.g. attribute to the last frame) unilaterally — confirm the
2242        // bloom-derivation rule against another client / the devnet first.
2243        let logs_before = self.substate.current_logs().len();
2244        crate::hooks::default_hook::delete_self_destruct_accounts(self)?;
2245        let mut logs_after = self.substate.current_logs();
2246        if logs_after.len() > logs_before {
2247            all_logs.extend(logs_after.split_off(logs_before));
2248        }
2249
2250        // Frame txs short-circuit the hook/finalize path, so the BackupHook never
2251        // runs and `db.tx_backup` stays None on the success path. A block builder
2252        // can execute a frame tx successfully and then reject it (e.g. the EIP-8037
2253        // 2D-gas overflow post-check, or an L2 invalid cross-chain message), calling
2254        // `undo_last_tx` — which needs the top-level backup to roll the committed
2255        // state back; otherwise the excluded tx's mutations leak into later txs and
2256        // the built block's state root diverges from re-execution. Populate it here
2257        // exactly as `BackupHook::finalize_execution` would: `tx_level_backup` holds
2258        // every committed frame's originals, and the outer call-frame backup now also
2259        // holds the refund/coinbase/self-destruct originals. Gated on
2260        // `preserve_top_level_backup` so it is set only when a hook reads it (L2);
2261        // on L1 the field is never consulted.
2262        if self.preserve_top_level_backup {
2263            tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2264            self.db.tx_backup = Some(tx_level_backup);
2265        }
2266
2267        // Derive top-level status from ALL frames: the transaction succeeded
2268        // only if every executed frame succeeded; a reverted or skipped frame of
2269        // ANY mode (SENDER, DEFAULT, VERIFY) yields a failed top-level status
2270        // (analogous to status 0 in standard transactions). This MUST match the
2271        // consensus-receipt derivation in `Receipt` decoding (receipt.rs), which
2272        // re-derives `succeeded` from the per-frame statuses ALONE — the
2273        // consensus `frame_receipt` carries no frame mode, so an all-frames rule
2274        // is the only definition the encode side (here) and a wire/trie decode
2275        // can compute identically. Deriving from SENDER frames only would make a
2276        // freshly-executed receipt's `status` disagree with the same receipt
2277        // decoded from consensus bytes. (A reverted VERIFY frame already
2278        // invalidated the tx above via `tx_invalid`; this additionally covers
2279        // reverted SENDER/DEFAULT frames, which do not.)
2280        let any_frame_reverted = ctx
2281            .frame_results
2282            .iter()
2283            .any(|(status, _, _)| *status != ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS);
2284
2285        let result = if any_frame_reverted {
2286            TxResult::Revert(VMError::RevertOpcode)
2287        } else {
2288            TxResult::Success
2289        };
2290
2291        // EIP-8037: report the transaction's net state gas (same formula as the
2292        // normal-tx path in default_hook). `total_gas_used` already includes the
2293        // state gas — it spilled into each frame's gas_remaining, exactly as for any
2294        // sub-TX_MAX_GAS_LIMIT transaction whose reservoir is 0 — so reporting
2295        // `state_gas_used` here lets the block-level regular/state split
2296        // (regular = gas_used - state_gas_used) attribute it to the state dimension
2297        // instead of billing the whole amount as regular gas.
2298        let state_gas_used =
2299            u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
2300
2301        // Unused frame gas in GAS UNITS for the report — distinct from the wei
2302        // refund above (which also returns the max-vs-effective fee delta).
2303        let frame_gas_used = total_gas_used.saturating_sub(intrinsic_gas);
2304        let gas_refund = sum_frame_gas_limits.saturating_sub(frame_gas_used);
2305
2306        let report = ExecutionReport {
2307            result,
2308            gas_used: total_gas_used,
2309            gas_spent: total_gas_used,
2310            gas_refunded: gas_refund,
2311            state_gas_used,
2312            output: Bytes::new(),
2313            logs: all_logs,
2314            payer_address: ctx.payer_address,
2315            frame_results: Some(ctx.frame_results),
2316        };
2317
2318        Ok(report)
2319    }
2320
2321    /// EIP-8141 mempool entry point: set up the frame-tx context and observer,
2322    /// then simulate the validation prefix.
2323    ///
2324    /// Performs the frame-tx preamble (static constraints, nonce, fee sanity,
2325    /// `FrameTxContext` init, outer-signature validation) — the same checks
2326    /// `execute_frame_tx` runs before any frame — then activates the
2327    /// [`ValidationObserver`](crate::validation_observer::ValidationObserver) for
2328    /// `sender` with the prefix's `deploy_index`, runs the prefix via
2329    /// [`VM::simulate_validation_prefix`], and returns the raw simulation
2330    /// result. Does NOT charge or refund gas. `canonical_paymaster_pay_frame`
2331    /// is the index of a canonical paymaster's pay frame (always `None` today,
2332    /// OQ1); when set, the access-restriction skip fires for that frame.
2333    pub fn run_frame_validation_prefix(
2334        &mut self,
2335        frame_indices: &[usize],
2336        deploy_index: Option<usize>,
2337        canonical_paymaster_pay_frame: Option<usize>,
2338    ) -> Result<PrefixSimResult, VMError> {
2339        use crate::validation_observer::ValidationObserver;
2340
2341        if self.env.config.fork < Fork::Hegota {
2342            return Err(VMError::TxValidation(
2343                crate::errors::TxValidationError::FrameTxPreFork,
2344            ));
2345        }
2346
2347        let frame_tx = match &self.tx {
2348            Transaction::FrameTransaction(ft) => ft.clone(),
2349            _ => {
2350                return Err(VMError::Internal(InternalError::Custom(
2351                    "run_frame_validation_prefix called on non-frame tx".to_string(),
2352                )));
2353            }
2354        };
2355
2356        let sender = frame_tx.sender;
2357
2358        if frame_tx.validate_static_constraints().is_err() {
2359            return Err(VMError::TxValidation(
2360                crate::errors::TxValidationError::InvalidFrameTransaction,
2361            ));
2362        }
2363
2364        let sender_info = self.db.get_account(sender)?.info.clone();
2365        if sender_info.nonce != frame_tx.nonce {
2366            return Err(VMError::TxValidation(
2367                crate::errors::TxValidationError::NonceMismatch {
2368                    expected: sender_info.nonce,
2369                    actual: frame_tx.nonce,
2370                },
2371            ));
2372        }
2373
2374        if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
2375            return Err(VMError::TxValidation(
2376                crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
2377                    priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
2378                    max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
2379                },
2380            ));
2381        }
2382
2383        if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
2384            return Err(VMError::TxValidation(
2385                crate::errors::TxValidationError::InsufficientMaxFeePerGas,
2386            ));
2387        }
2388
2389        let sig_hash = frame_tx.compute_sig_hash();
2390        let total_gas_limit = frame_tx.total_gas_limit();
2391        self.frame_tx_context = Some(FrameTxContext {
2392            sender_approved: false,
2393            payer_address: None,
2394            frame_results: Vec::new(),
2395            current_frame_index: 0,
2396            sig_hash,
2397            tx: frame_tx.clone(),
2398            approve_called_in_current_frame: false,
2399            total_gas_limit,
2400        });
2401
2402        if !validate_frame_signatures(
2403            &frame_tx.signatures,
2404            sig_hash,
2405            frame_tx.sender,
2406            self.env.config.fork,
2407            self.crypto,
2408        ) {
2409            return Err(VMError::TxValidation(
2410                crate::errors::TxValidationError::InvalidFrameTransaction,
2411            ));
2412        }
2413
2414        let expiry_verifier = ethrex_common::types::frame_tx_expiry_verifier();
2415        let mut observer = ValidationObserver::new(sender, deploy_index, expiry_verifier);
2416        observer.canonical_paymaster_pay_frame = canonical_paymaster_pay_frame;
2417        self.validation_observer = observer;
2418
2419        self.simulate_validation_prefix(frame_indices)
2420    }
2421
2422    /// EIP-8141 mempool validation-prefix simulation (local peer policy).
2423    ///
2424    /// Runs ONLY the validation-prefix frames (the verify/pay/deploy frames that
2425    /// must execute before the transaction's payer is established) of a frame
2426    /// transaction, under an active [`ValidationObserver`](crate::validation_observer::ValidationObserver),
2427    /// then stops as soon as the payer has been set. Reuses the real frame
2428    /// execution primitives (`eip7702_get_code`, `execute_default_code`,
2429    /// `run_execution`, substate backups, value transfer) over the DEFAULT/VERIFY
2430    /// subset that prefixes are restricted to (Phase 1 structural rules forbid
2431    /// SENDER and atomic-batch frames in the prefix), so it dispatches real
2432    /// opcodes through the real handlers — not a separate mini-EVM.
2433    ///
2434    /// `frame_indices` are the prefix frame indices (in order), as identified by
2435    /// `FrameTransaction::validation_prefix`; expiry-verifier frames interleaved
2436    /// in the prefix are run too (they may appear between prefix frames). The
2437    /// caller must have set `frame_tx_context` and activated the observer.
2438    ///
2439    /// Returns [`PrefixSimResult`] describing the outcome. Does NOT charge fees
2440    /// or refund gas (mempool simulation only); state changes accumulate in the
2441    /// shared `db` and are discarded by the caller (a fresh simulation database).
2442    pub fn simulate_validation_prefix(
2443        &mut self,
2444        frame_indices: &[usize],
2445    ) -> Result<PrefixSimResult, VMError> {
2446        let frame_tx = match &self.tx {
2447            Transaction::FrameTransaction(ft) => ft.clone(),
2448            _ => {
2449                return Err(VMError::Internal(InternalError::Custom(
2450                    "simulate_validation_prefix called on non-frame tx".to_string(),
2451                )));
2452            }
2453        };
2454
2455        let sender = frame_tx.sender;
2456        let entry_point = ethrex_common::types::frame_tx_entry_point();
2457
2458        let mut total_gas_used: u64 = 0;
2459        let mut any_revert = false;
2460        // The highest prefix-frame index we must run before stopping. We run the
2461        // prefix in source order, executing every frame from 0 up to and
2462        // including the last prefix index (covering interleaved expiry frames).
2463        let last_prefix_idx = frame_indices.iter().copied().max();
2464
2465        for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
2466            // Stop once the whole prefix has run (and the payer break below).
2467            if let Some(stop) = last_prefix_idx {
2468                if frame_idx > stop {
2469                    break;
2470                }
2471            } else {
2472                break;
2473            }
2474
2475            // Each independent prefix frame starts with a clean call-frame backup
2476            // so a later frame's failure only reverts its own effects.
2477            self.current_call_frame.call_frame_backup.clear();
2478
2479            let ctx =
2480                self.frame_tx_context
2481                    .as_mut()
2482                    .ok_or(VMError::Internal(InternalError::Custom(
2483                        "missing frame tx context".to_string(),
2484                    )))?;
2485            ctx.current_frame_index = frame_idx;
2486            ctx.approve_called_in_current_frame = false;
2487
2488            let target = frame.target.unwrap_or(sender);
2489
2490            // Sync observer per-frame fields before the frame runs.
2491            self.validation_observer.current_frame_index = frame_idx;
2492            self.validation_observer.current_frame_mode = frame.mode;
2493
2494            // Prefix frames are DEFAULT (deploy) or VERIFY only; both run with
2495            // ENTRY_POINT as caller (DEFAULT not static, VERIFY static).
2496            let (caller, is_static) = match frame.execution_mode() {
2497                FrameMode::Default => (entry_point, false),
2498                FrameMode::Verify => (entry_point, true),
2499                FrameMode::Sender => {
2500                    // Structural rules exclude SENDER frames from the prefix.
2501                    return Err(VMError::Internal(InternalError::Custom(
2502                        "SENDER frame in validation prefix".to_string(),
2503                    )));
2504                }
2505            };
2506
2507            self.env.origin = caller;
2508
2509            let (is_delegation_7702, _access_cost, code_address, bytecode) =
2510                crate::utils::eip7702_get_code(
2511                    self.db,
2512                    &mut self.substate,
2513                    target,
2514                    self.env.config.fork,
2515                )?;
2516
2517            self.substate.push_backup();
2518
2519            let value_transfer_reverted = if !frame.value.is_zero() {
2520                let sender_balance = self.db.get_account(sender)?.info.balance;
2521                frame_value_exceeds_balance(sender_balance, frame.value)
2522            } else {
2523                false
2524            };
2525
2526            let (frame_success, frame_gas_used) = if value_transfer_reverted {
2527                self.substate.revert_backup();
2528                self.restore_cache_state()?;
2529                (false, frame.gas_limit)
2530            } else if bytecode.is_empty() && !is_delegation_7702 {
2531                // Default-code path (target has neither code nor a delegation).
2532                if !frame.value.is_zero() {
2533                    self.transfer(sender, target, frame.value)?;
2534                }
2535                use crate::opcode_handlers::frame_tx::execute_default_code;
2536                match execute_default_code(self, frame, target) {
2537                    Ok((success, gas_used, _logs)) => {
2538                        if success {
2539                            self.substate.commit_backup();
2540                            (true, gas_used)
2541                        } else {
2542                            self.substate.revert_backup();
2543                            self.restore_cache_state()?;
2544                            (false, gas_used)
2545                        }
2546                    }
2547                    Err(_) => {
2548                        self.substate.revert_backup();
2549                        self.restore_cache_state()?;
2550                        (false, frame.gas_limit)
2551                    }
2552                }
2553            } else {
2554                // Normal code execution via a child CallFrame.
2555                let call_frame = CallFrame::new(
2556                    caller,
2557                    target,
2558                    code_address,
2559                    bytecode,
2560                    frame.value,
2561                    frame.data.clone(),
2562                    is_static,
2563                    frame.gas_limit,
2564                    0,
2565                    false,
2566                    false,
2567                    0,
2568                    0,
2569                    self.stack_pool.pop().unwrap_or_default(),
2570                    Memory::default(),
2571                );
2572
2573                let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2574                let saved_call_frames = mem::take(&mut self.call_frames);
2575
2576                if !frame.value.is_zero() {
2577                    self.transfer(sender, target, frame.value)?;
2578                }
2579
2580                let frame_result = self.run_execution();
2581
2582                let result = match frame_result {
2583                    Ok(ctx_result) => {
2584                        let gas_used = ctx_result.gas_used;
2585                        // The inner frame is the initial call frame, so `run_execution`
2586                        // already committed (success) or reverted + restored the cache
2587                        // (revert) this frame's backup via `handle_state_backup`. Only a
2588                        // `VMError` (the `Err` arm) leaves the backup live for us to undo.
2589                        (ctx_result.is_success(), gas_used)
2590                    }
2591                    Err(_e) => {
2592                        self.substate.revert_backup();
2593                        self.restore_cache_state()?;
2594                        (false, frame.gas_limit)
2595                    }
2596                };
2597
2598                let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2599                self.call_frames = saved_call_frames;
2600                self.stack_pool.push(finished_frame.stack);
2601
2602                result
2603            };
2604
2605            total_gas_used = total_gas_used
2606                .checked_add(frame_gas_used)
2607                .ok_or(VMError::Internal(InternalError::Overflow))?;
2608
2609            if !frame_success {
2610                any_revert = true;
2611            }
2612
2613            // A reverted prefix frame is fatal: the transaction can never reach a
2614            // valid payer through a reverted verify/pay/deploy frame.
2615            if !frame_success {
2616                break;
2617            }
2618
2619            self.substate.clear_transient_storage();
2620
2621            // Stop as soon as the payer has been set (the prefix is complete).
2622            if self
2623                .frame_tx_context
2624                .as_ref()
2625                .and_then(|c| c.payer_address)
2626                .is_some()
2627            {
2628                break;
2629            }
2630        }
2631
2632        let ctx =
2633            self.frame_tx_context
2634                .as_ref()
2635                .ok_or(VMError::Internal(InternalError::Custom(
2636                    "missing frame tx context".to_string(),
2637                )))?;
2638
2639        Ok(PrefixSimResult {
2640            any_revert,
2641            payer_address: ctx.payer_address,
2642            sender_approved: ctx.sender_approved,
2643            total_gas_used,
2644        })
2645    }
2646
2647    /// Must run after `prepare_execution` so EIP-7702 delegation is already resolved into
2648    /// `bytecode`.
2649    #[inline(always)]
2650    fn is_simple_transfer_fast_path(&self) -> bool {
2651        !self.current_call_frame.is_create
2652            && self.current_call_frame.bytecode.is_empty()
2653            // Privileged L2 txs can leave gas negative; let the slow path surface that as OOG.
2654            && self.current_call_frame.gas_remaining >= 0
2655            && self.tx.authorization_list().is_none()
2656            // Precompiles dispatch via run_execution even with empty bytecode.
2657            && !precompiles::is_precompile(
2658                &self.current_call_frame.to,
2659                self.env.config.fork,
2660                self.vm_type,
2661            )
2662    }
2663
2664    /// Main execution loop.
2665    pub fn run_execution(&mut self) -> Result<ContextResult, VMError> {
2666        // If gas is already exhausted (negative), fail immediately.
2667        // This can happen when intrinsic gas exceeds the gas limit in privileged L2 transactions.
2668        // Without this check, casting negative gas_remaining to u64 would wrap to a huge value.
2669        if self.current_call_frame.gas_remaining < 0 {
2670            return Ok(ContextResult {
2671                result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2672                gas_used: self.current_call_frame.gas_limit,
2673                gas_spent: self.current_call_frame.gas_limit,
2674                output: Bytes::new(),
2675            });
2676        }
2677
2678        // EIP-8037: the atomic prepare region rolled back (one of its charges — 7702
2679        // auth, CREATE/value NEW_ACCOUNT, recipient delegation-resolve — OOG'd).
2680        // Burn all gas and revert the tx rather than rejecting it as invalid (which
2681        // would wrongly invalidate the block). Mirrors EELS depth-0
2682        // `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`
2683        // (`interpreter.py:366-374`).
2684        if self.pending_prep_oog {
2685            return Ok(ContextResult {
2686                result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2687                gas_used: self.current_call_frame.gas_limit,
2688                gas_spent: self.current_call_frame.gas_limit,
2689                output: Bytes::new(),
2690            });
2691        }
2692
2693        // A charged value-to-not-alive NEW_ACCOUNT means the recipient was not yet alive
2694        // at tx start and the tx transfers value. If the recipient is a precompile that
2695        // then exceptionally halts/reverts, the account is never materialized, so the
2696        // charge is rolled back in the precompile branch below (mirrors EELS
2697        // `refill_frame_state_gas`). Set in-region by `prepare_execution`.
2698        let top_frame_new_account_charged = self.value_new_account_charged;
2699
2700        #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
2701        if precompiles::is_precompile(
2702            &self.current_call_frame.to,
2703            self.env.config.fork,
2704            self.vm_type,
2705        ) {
2706            // `execute_precompile` itself never touches state gas (it only mutates
2707            // `gas_remaining`; it has no access to `state_gas_used` / `state_gas_reservoir` /
2708            // `state_gas_spill`) — the assert below guards that. The in-region EIP-2780
2709            // value-to-not-alive NEW_ACCOUNT charge (`prepare_execution`),
2710            // however, IS frame state gas, and on an exceptional halt/revert it must be
2711            // rolled back (see below). `self` is borrowed by field rather than via
2712            // `&mut self.current_call_frame` so the refund call, which needs `&mut self`,
2713            // can run after `execute_precompile`.
2714            let state_gas_used_before_precompile = self.state_gas_used;
2715            let code_address = self.current_call_frame.code_address;
2716            let precompile_gas_limit = self.current_call_frame.gas_limit;
2717            let mut gas_remaining = self.current_call_frame.gas_remaining as u64;
2718            let result = Self::execute_precompile(
2719                code_address,
2720                &self.current_call_frame.calldata,
2721                precompile_gas_limit,
2722                &mut gas_remaining,
2723                self.env.config.fork,
2724                self.db.store.precompile_cache(),
2725                self.crypto,
2726            );
2727
2728            debug_assert_eq!(
2729                self.state_gas_used, state_gas_used_before_precompile,
2730                "precompile execution must not mutate state_gas_used"
2731            );
2732
2733            // EIP-8037 Amsterdam 2D accounting recomputes `block_gas_used` from
2734            // `raw_consumed = gas_limit - gas_remaining` inside `refund_sender`. On a
2735            // top-level precompile exceptional halt, `handle_precompile_result` already
2736            // sets `ContextResult.gas_used = gas_limit`, but `gas_remaining` retains the
2737            // untouched forwarded amount — under Amsterdam that would make the block
2738            // report only the intrinsic portion. Zero it so the block matches the
2739            // `gas_used = gas_limit` contract from `handle_precompile_result`, and roll
2740            // back the in-region value NEW_ACCOUNT charge (the recipient is never materialized
2741            // on halt) so the burned gas counts entirely as regular gas, matching EELS
2742            // `refill_frame_state_gas`. Pre-Amsterdam reads `ctx_result.gas_used` directly
2743            // and is unaffected by this path either way.
2744            if self.env.config.fork >= Fork::Amsterdam
2745                && let Ok(ctx) = &result
2746                && !ctx.is_success()
2747            {
2748                gas_remaining = 0;
2749                self.refund_new_account_state_gas(top_frame_new_account_charged)?;
2750            }
2751
2752            self.current_call_frame.gas_remaining = gas_remaining as i64;
2753
2754            return result;
2755        }
2756
2757        // Specialize the dispatch loop on whether a struct-log tracer is active.
2758        // The `!TRACED` variant compiles out every tracer branch and capture call,
2759        // leaving a minimal hot loop (the common, non-traced case).
2760        if self.opcode_tracer.active {
2761            self.run_dispatch::<true>()
2762        } else {
2763            self.run_dispatch::<false>()
2764        }
2765    }
2766
2767    /// Opcode dispatch loop, monomorphized over whether a struct-log tracer is
2768    /// active. With `TRACED = false` the compiler eliminates the tracer branches
2769    /// and the cold `trace_*_step` calls entirely, so the hot loop body stays
2770    /// minimal; the traced variant keeps the cold helpers out of line.
2771    fn run_dispatch<const TRACED: bool>(&mut self) -> Result<ContextResult, VMError> {
2772        let mut error = OnceCell::<VMError>::new();
2773
2774        #[cfg(feature = "perf_opcode_timings")]
2775        let mut timings = crate::timings::OPCODE_TIMINGS.lock().expect("poison");
2776
2777        // Copy the `&'static` table pointer once; it doesn't borrow `self`, so dispatch can still
2778        // pass `self` mutably to the handler without reloading the pointer each iteration.
2779        let opcode_table = self.opcode_table;
2780
2781        loop {
2782            // Capture pc BEFORE advance_pc() — this is the address of the current opcode.
2783            let pc_of_current_op = self.current_call_frame.pc;
2784            let opcode = self.current_call_frame.next_opcode();
2785            self.advance_pc();
2786
2787            // EIP-8141 mempool validation-trace observer (single branch on the
2788            // fast path when inactive). Enforces the banned-opcode set and the
2789            // sequential `GAS`-before-`*CALL` rule before the handler runs.
2790            if self.validation_observer.active {
2791                self.check_validation_banned_opcode(opcode);
2792            }
2793
2794            // Struct-log pre-step capture (compiled out entirely when !TRACED).
2795            let gas_before_op = if TRACED {
2796                self.trace_pre_step(opcode, pc_of_current_op)
2797            } else {
2798                0
2799            };
2800
2801            #[cfg(feature = "perf_opcode_timings")]
2802            let opcode_time_start = std::time::Instant::now();
2803
2804            #[allow(clippy::indexing_slicing, clippy::as_conversions)]
2805            let op_result = opcode_table[opcode as usize].call(self, &mut error);
2806
2807            #[cfg(feature = "perf_opcode_timings")]
2808            {
2809                let time = opcode_time_start.elapsed();
2810                timings.update(opcode, time);
2811            }
2812
2813            // Struct-log post-step (compiled out entirely when !TRACED).
2814            if TRACED {
2815                self.trace_post_step(gas_before_op, &error);
2816            }
2817
2818            let result = match op_result {
2819                OpcodeResult::Continue => continue,
2820                OpcodeResult::Halt => match error.take() {
2821                    None => self.handle_opcode_result()?,
2822                    Some(error) => self.handle_opcode_error(error)?,
2823                },
2824            };
2825
2826            // Return the ExecutionReport if the executed callframe was the first one.
2827            if self.is_initial_call_frame() {
2828                // Consume the backup (move it out) unless a `BackupHook` will read it afterward
2829                // to build the tx-level undo snapshot (L2 / stateless). On L1 nothing reads it
2830                // once the cache is restored, so cloning it would be dead work.
2831                self.handle_state_backup(&result, !self.preserve_top_level_backup)?;
2832                return Ok(result);
2833            }
2834
2835            // Handle interaction between child and parent callframe.
2836            self.handle_return(&result)?;
2837        }
2838    }
2839
2840    /// EIP-8141 validation-trace banned-opcode check (mempool simulation only).
2841    ///
2842    /// Called once per dispatch-loop iteration, AFTER the opcode is fetched and
2843    /// BEFORE the handler runs, gated by `self.validation_observer.active`. Byte
2844    /// values are pinned against `opcodes.rs`.
2845    ///
2846    /// Static bans: `ORIGIN`, `GASPRICE`, `BLOCKHASH`, `COINBASE`, `TIMESTAMP`
2847    /// (except when the current frame's target is EXPIRY_VERIFIER), `NUMBER`,
2848    /// `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBHASH`, `BLOBBASEFEE`, `INVALID`,
2849    /// `SELFDESTRUCT`, `BALANCE`, `SELFBALANCE`, `TLOAD`, `TSTORE`, and `CALLCODE`
2850    /// in non-deploy prefix frames (ERC-7562 bans CALLCODE in validation;
2851    /// DELEGATECALL is allowed subject to the CALL-family trace rules in the
2852    /// handlers). `SSTORE`/`CREATE`/`CREATE2` are allowed only inside the deploy
2853    /// frame and are enforced in their handlers (state-write rules), not here.
2854    ///
2855    /// Sequential `GAS` rule: `GAS` is allowed only immediately before a
2856    /// `*CALL` (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`). We detect this by
2857    /// remembering `last_opcode`: if the previous iteration was `GAS` and this
2858    /// opcode is NOT a `*CALL`, the prior `GAS` was illegal.
2859    pub fn check_validation_banned_opcode(&mut self, opcode: u8) {
2860        use crate::validation_observer::FrameSimViolation;
2861
2862        // Opcode bytes, pinned against `opcodes.rs`. The literal values are
2863        // asserted equal to the `Opcode` enum discriminants by
2864        // `validation_observer_opcode_byte_pins` below (avoids a `const`-context
2865        // `as` cast, which the workspace clippy config denies).
2866        const ORIGIN: u8 = 0x32;
2867        const GASPRICE: u8 = 0x3A;
2868        const BLOCKHASH: u8 = 0x40;
2869        const COINBASE: u8 = 0x41;
2870        const TIMESTAMP: u8 = 0x42;
2871        const NUMBER: u8 = 0x43;
2872        const PREVRANDAO: u8 = 0x44;
2873        const GASLIMIT: u8 = 0x45;
2874        const BASEFEE: u8 = 0x48;
2875        const BLOBHASH: u8 = 0x49;
2876        const BLOBBASEFEE: u8 = 0x4A;
2877        const INVALID: u8 = 0xFE;
2878        const SELFDESTRUCT: u8 = 0xFF;
2879        const BALANCE: u8 = 0x31;
2880        const SELFBALANCE: u8 = 0x47;
2881        const TLOAD: u8 = 0x5C;
2882        const TSTORE: u8 = 0x5D;
2883        const GAS: u8 = 0x5A;
2884        const CALL: u8 = 0xF1;
2885        const CALLCODE: u8 = 0xF2;
2886        const DELEGATECALL: u8 = 0xF4;
2887        const STATICCALL: u8 = 0xFA;
2888
2889        let is_call_family = matches!(opcode, CALL | CALLCODE | DELEGATECALL | STATICCALL);
2890
2891        // Sequential GAS rule: a `GAS` on the previous iteration is only legal if
2892        // THIS opcode is a `*CALL`. Evaluate before updating `last_opcode`.
2893        if self.validation_observer.last_opcode == GAS && !is_call_family {
2894            self.validation_observer
2895                .record_violation(FrameSimViolation::BannedOpcode(GAS));
2896        }
2897
2898        // Carry `GAS` forward for the next iteration's check; reset otherwise.
2899        self.validation_observer.last_opcode = if opcode == GAS { GAS } else { 0 };
2900
2901        let banned = match opcode {
2902            ORIGIN | GASPRICE | BLOCKHASH | COINBASE | NUMBER | PREVRANDAO | GASLIMIT | BASEFEE
2903            | BLOBHASH | BLOBBASEFEE | INVALID | SELFDESTRUCT | BALANCE | SELFBALANCE | TLOAD
2904            | TSTORE => true,
2905            // TIMESTAMP is permitted only when the currently executing contract
2906            // IS the EXPIRY_VERIFIER predeploy (checked by code_address so the
2907            // rule tracks the executing contract at every call depth, not just the
2908            // top-level frame target). A nested call FROM an expiry frame INTO
2909            // another contract is correctly banned; a nested call INTO the
2910            // predeploy from any frame is correctly allowed.
2911            TIMESTAMP => {
2912                self.current_call_frame.code_address != self.validation_observer.expiry_verifier
2913            }
2914            // CALLCODE is banned in non-deploy prefix frames (ERC-7562).
2915            CALLCODE => !self.validation_observer.in_deploy_frame(),
2916            _ => false,
2917        };
2918
2919        if banned {
2920            self.validation_observer
2921                .record_violation(FrameSimViolation::BannedOpcode(opcode));
2922        }
2923    }
2924
2925    /// EIP-8141 validation-trace `SLOAD` check (mempool simulation only).
2926    ///
2927    /// `SLOAD` is allowed only when the storage owner (`address`, the executing
2928    /// frame's `to`) is the transaction sender. Records the touched slot for the
2929    /// admission-time revalidation affected-set.
2930    pub fn validation_check_sload(&mut self, address: Address, slot: H256) {
2931        use crate::validation_observer::FrameSimViolation;
2932        if self.validation_observer.in_canonical_pay_frame() {
2933            return;
2934        }
2935        if address == self.validation_observer.sender {
2936            self.validation_observer.touched_sender_slots.push(slot);
2937        } else {
2938            self.validation_observer
2939                .record_violation(FrameSimViolation::StorageReadNonSender);
2940        }
2941    }
2942
2943    /// EIP-8141 validation-trace `SSTORE` check (mempool simulation only).
2944    ///
2945    /// `SSTORE` is allowed only inside the deploy frame AND only when the storage
2946    /// owner (`address`, the executing frame's `to`) is the transaction sender.
2947    pub fn validation_check_sstore(&mut self, address: Address, slot: H256) {
2948        use crate::validation_observer::FrameSimViolation;
2949        if self.validation_observer.in_canonical_pay_frame() {
2950            return;
2951        }
2952        if self.validation_observer.in_deploy_frame() && address == self.validation_observer.sender
2953        {
2954            self.validation_observer.touched_sender_slots.push(slot);
2955        } else {
2956            self.validation_observer
2957                .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
2958        }
2959    }
2960
2961    /// EIP-8141 validation-trace state-creation check for `CREATE`/`CREATE2`
2962    /// (mempool simulation only). Contract creation is a state write permitted
2963    /// only inside the deploy frame.
2964    pub fn validation_check_create(&mut self) {
2965        use crate::validation_observer::FrameSimViolation;
2966        if self.validation_observer.in_canonical_pay_frame() {
2967            return;
2968        }
2969        if !self.validation_observer.in_deploy_frame() {
2970            self.validation_observer
2971                .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
2972        }
2973    }
2974
2975    /// EIP-8141 validation-trace `CALL*`/`EXTCODE*` target check (mempool
2976    /// simulation only).
2977    ///
2978    /// The target must be an existing account or a precompile and must NOT be
2979    /// EIP-7702-delegated, except the sender running its own default code (the
2980    /// sender is exempt — its existence is a transaction precondition and it may
2981    /// have no code). `is_delegation_7702` is the flag already computed by
2982    /// `eip7702_get_code` in the CALL-family handlers, threaded in to avoid a
2983    /// second delegation resolution (and the `&mut VM` / `&mut db` borrow
2984    /// conflict a dispatch-loop stack-peek would create).
2985    pub fn validation_check_call_target(
2986        &mut self,
2987        target: Address,
2988        is_delegation_7702: bool,
2989    ) -> Result<(), VMError> {
2990        use crate::validation_observer::FrameSimViolation;
2991        if self.validation_observer.in_canonical_pay_frame() {
2992            return Ok(());
2993        }
2994        // The sender is always a legitimate target (its existence is a tx
2995        // precondition; it may legitimately have no code).
2996        if target == self.validation_observer.sender {
2997            return Ok(());
2998        }
2999        // A delegated target is disallowed in validation.
3000        if is_delegation_7702 {
3001            self.validation_observer
3002                .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3003            return Ok(());
3004        }
3005        // Precompiles are always valid targets.
3006        if precompiles::is_precompile(&target, self.env.config.fork, self.vm_type) {
3007            return Ok(());
3008        }
3009        // Otherwise the target must be an existing (non-empty) account.
3010        if self.db.get_account(target)?.is_empty() {
3011            self.validation_observer
3012                .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3013        }
3014        Ok(())
3015    }
3016
3017    /// EIP-8141 validation-trace `EXTCODE*` target check (mempool simulation
3018    /// only). Like [`VM::validation_check_call_target`], but resolves the
3019    /// EIP-7702 delegation flag itself (the EXTCODE handlers do not call
3020    /// `eip7702_get_code`). The `substate.add_accessed_address` warming the
3021    /// EXTCODE gas already performed has happened; resolving here only follows a
3022    /// delegation indicator to read its flag, mirroring the CALL-family path.
3023    pub fn validation_check_extcode_target(&mut self, target: Address) -> Result<(), VMError> {
3024        if self.validation_observer.in_canonical_pay_frame()
3025            || target == self.validation_observer.sender
3026        {
3027            return Ok(());
3028        }
3029        let (is_delegation_7702, _access_cost, _code_address, _bytecode) =
3030            crate::utils::eip7702_get_code(
3031                self.db,
3032                &mut self.substate,
3033                target,
3034                self.env.config.fork,
3035            )?;
3036        self.validation_check_call_target(target, is_delegation_7702)
3037    }
3038
3039    /// Struct-log pre-step capture, split out of the interpreter loop and kept
3040    /// cold + non-inlined so the hot dispatch loop stays small (this code is
3041    /// only reached when a struct-log tracer is active). Returns `gas_before`.
3042    #[cold]
3043    #[inline(never)]
3044    fn trace_pre_step(&mut self, opcode: u8, pc_of_current_op: usize) -> u64 {
3045        #[expect(
3046            clippy::as_conversions,
3047            reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3048        )]
3049        let gas_before = self.current_call_frame.gas_remaining.max(0) as u64;
3050        #[expect(
3051            clippy::as_conversions,
3052            reason = "call depth bounded by STACK_LIMIT=1024, fits in u32"
3053        )]
3054        let depth = (self.call_frames.len() as u32).saturating_add(1);
3055        let refund = self.substate.refunded_gas;
3056        let stack_view = self.collect_stack_for_trace();
3057        let mem_view = self.collect_memory_for_trace();
3058        // mem_size always reflects actual memory size, regardless of enable_memory.
3059        #[expect(
3060            clippy::as_conversions,
3061            reason = "memory size is bounded by gas; fits in u64"
3062        )]
3063        let mem_size_for_trace = self.current_call_frame.memory.len() as u64;
3064        let storage_kv = self.read_storage_for_trace(opcode);
3065        let return_data = if self.opcode_tracer.cfg.enable_return_data {
3066            self.current_call_frame.sub_return_data.clone()
3067        } else {
3068            Bytes::new()
3069        };
3070        #[expect(
3071            clippy::as_conversions,
3072            reason = "pc is usize, fits in u64 on supported targets"
3073        )]
3074        let pc_u64 = pc_of_current_op as u64;
3075        self.opcode_tracer.pre_step_capture(
3076            pc_u64,
3077            opcode,
3078            gas_before,
3079            depth,
3080            refund,
3081            &stack_view,
3082            &mem_view,
3083            mem_size_for_trace,
3084            &return_data,
3085            storage_kv,
3086        );
3087        gas_before
3088    }
3089
3090    /// Struct-log post-step: patch gas_cost, refund-after-op, and error into the
3091    /// buffered entry. Cold + non-inlined for the same reason as `trace_pre_step`.
3092    #[cold]
3093    #[inline(never)]
3094    fn trace_post_step(&mut self, gas_before_op: u64, error: &OnceCell<VMError>) {
3095        #[expect(
3096            clippy::as_conversions,
3097            reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3098        )]
3099        let gas_after = self.current_call_frame.gas_remaining.max(0) as u64;
3100        // Prefer the explicit opcode-overhead cost written by CALL/CREATE handlers;
3101        // fall back to the gas diff for all other opcodes.
3102        let gas_cost = self
3103            .opcode_tracer
3104            .last_opcode_gas_cost
3105            .take()
3106            .unwrap_or_else(|| gas_before_op.saturating_sub(gas_after));
3107        // refund-after-op matches geth's structLogger timing: for SSTORE and
3108        // (pre-London) SELFDESTRUCT, the refund counter shown is the value
3109        // *after* the opcode's accounting applied.
3110        let refund_after = self.substate.refunded_gas;
3111        let err_str = error.get().map(|e| e.to_string());
3112        self.opcode_tracer
3113            .finalize_step(gas_cost, refund_after, err_str.as_deref());
3114    }
3115
3116    /// Executes precompile and handles the output that it returns, generating a report.
3117    pub fn execute_precompile(
3118        code_address: H160,
3119        calldata: &Bytes,
3120        gas_limit: u64,
3121        gas_remaining: &mut u64,
3122        fork: Fork,
3123        cache: Option<&precompiles::PrecompileCache>,
3124        crypto: &dyn Crypto,
3125    ) -> Result<ContextResult, VMError> {
3126        Self::handle_precompile_result(
3127            precompiles::execute_precompile(
3128                code_address,
3129                calldata,
3130                gas_remaining,
3131                fork,
3132                cache,
3133                crypto,
3134            ),
3135            gas_limit,
3136            *gas_remaining,
3137        )
3138    }
3139
3140    /// True if external transaction is a contract creation
3141    pub fn is_create(&self) -> Result<bool, InternalError> {
3142        Ok(self.current_call_frame.is_create)
3143    }
3144
3145    /// Executes without making changes to the cache.
3146    pub fn stateless_execute(&mut self) -> Result<ExecutionReport, VMError> {
3147        // Add backup hook to restore state after execution. `add_hook` flips
3148        // `preserve_top_level_backup` on via `Hook::reads_top_level_backup`, so the backup is
3149        // cloned (not moved out) on the revert paths even though this VM was built with L1 `vm_type`.
3150        self.add_hook(BackupHook::default());
3151        let report = self.execute()?;
3152        // Restore cache to the state before execution.
3153        self.db.undo_last_transaction()?;
3154        Ok(report)
3155    }
3156
3157    fn prepare_execution(&mut self) -> Result<(), VMError> {
3158        // Clone each hook's `Rc` (cheap refcount bump) so the borrow on `self.hooks` is released
3159        // and `self` can be passed mutably — without `self.hooks.clone()`'s per-tx `Vec` realloc.
3160        // `self.hooks` is not mutated during the loop, so `get(i)` is always `Some` in range.
3161        for i in 0..self.hooks.len() {
3162            if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3163                hook.borrow_mut().prepare_execution(self)?;
3164            }
3165        }
3166
3167        Ok(())
3168    }
3169
3170    fn finalize_execution(
3171        &mut self,
3172        mut ctx_result: ContextResult,
3173    ) -> Result<ExecutionReport, VMError> {
3174        // EIP-8037: On top-level tx failure (REVERT, ExceptionalHalt, or OOG), the
3175        // execution portion of state gas has already been refilled into the reservoir by
3176        // the top-frame `refill_frame_state_gas` (seeded at the post-intrinsic baseline in
3177        // `add_intrinsic_gas` and fired on revert/halt in `handle_opcode_error` /
3178        // `handle_opcode_result`). The intrinsic portion stays in `state_gas_used` so block
3179        // accounting bills it. No reservoir-move is performed here. A create-tx collision
3180        // rolls its own in-region `NEW_ACCOUNT` charge (if any) back to the frame's entry
3181        // baseline inside `handle_create_transaction`'s collision branch, so there is
3182        // nothing left to refill here either (see that function).
3183        //
3184        // EIP-8037: there is no longer a separate create-failure `NEW_ACCOUNT`
3185        // refund here. The charge itself (`prepare_execution`) is now
3186        // conditioned on `get_pre_state_account(created_addr) == EMPTY_ACCOUNT`, so it
3187        // simply never fires for an already-alive target (positive balance implies
3188        // non-empty pre-state) and is rolled back by `handle_create_transaction` on
3189        // collision — matching EELS v7, which drops the created-target-alive output flag
3190        // entirely because `prepare_dispatch` never runs for a colliding create.
3191
3192        // See `prepare_execution`: per-hook `Rc::clone` avoids the `self.hooks.clone()` realloc.
3193        for i in 0..self.hooks.len() {
3194            if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3195                hook.borrow_mut()
3196                    .finalize_execution(self, &mut ctx_result)?;
3197            }
3198        }
3199
3200        self.tracer.exit_context(&ctx_result, true)?;
3201
3202        // Struct-log end-of-tx capture: record final output, gas used, and revert error.
3203        // gas matches geth's `executionResult.Gas` which is post-refund (`receipt.GasUsed`).
3204        if self.opcode_tracer.active {
3205            self.opcode_tracer.output = ctx_result.output.clone();
3206            self.opcode_tracer.gas_used = ctx_result.gas_spent;
3207            self.opcode_tracer.error = match ctx_result.result {
3208                TxResult::Revert(ref err) => Some(err.to_string()),
3209                _ => None,
3210            };
3211        }
3212
3213        // Only include logs if transaction succeeded. When a transaction reverts,
3214        // no logs should be emitted (including EIP-7708 Transfer logs).
3215        let logs = if ctx_result.is_success() {
3216            self.substate.extract_logs()
3217        } else {
3218            Vec::new()
3219        };
3220
3221        // EIP-8037: `state_gas_used` is already net (signed; credits decrement it
3222        // inline), so `tx_state_gas = intrinsic_state_gas + state_gas_used` exactly
3223        // (EELS `fork.py::process_transaction`, which no longer carries a separate
3224        // tx-level refund channel). Clamp at zero — `state_gas_used` may be negative when
3225        // inline refunds exceed gross charges.
3226        let net_state_gas_used: u64 =
3227            u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
3228
3229        let report = ExecutionReport {
3230            result: ctx_result.result.clone(),
3231            gas_used: ctx_result.gas_used,
3232            gas_spent: ctx_result.gas_spent,
3233            gas_refunded: self.substate.refunded_gas,
3234            state_gas_used: net_state_gas_used,
3235            output: std::mem::take(&mut ctx_result.output),
3236            logs,
3237            payer_address: None,
3238            frame_results: None,
3239        };
3240
3241        Ok(report)
3242    }
3243
3244    // ── Struct-log helper methods ─────────────────────────────────────────────
3245
3246    /// Collects the current stack in bottom-first order for struct-log emission.
3247    ///
3248    /// LEVM stack is top-first in memory (`values[offset]` = top), so we reverse
3249    /// the active slice to produce the bottom-first wire format geth uses.
3250    /// Returns an empty `Vec` when `cfg.disable_stack` is true.
3251    pub fn collect_stack_for_trace(&self) -> Vec<U256> {
3252        use crate::constants::STACK_LIMIT;
3253        if self.opcode_tracer.cfg.disable_stack {
3254            return Vec::new();
3255        }
3256        let s = &self.current_call_frame.stack;
3257        // offset <= STACK_LIMIT by stack invariant.
3258        s.values
3259            .get(s.offset..STACK_LIMIT)
3260            .map(|slice| slice.iter().rev().copied().collect())
3261            .unwrap_or_default()
3262    }
3263
3264    /// Collects the live memory bytes for the current frame.
3265    ///
3266    /// Returns an empty `Vec` when `cfg.enable_memory` is false or memory is empty.
3267    pub fn collect_memory_for_trace(&self) -> Vec<u8> {
3268        if !self.opcode_tracer.cfg.enable_memory {
3269            return Vec::new();
3270        }
3271        self.current_call_frame.memory.live_bytes()
3272    }
3273
3274    /// Pre-reads the storage key/value for the current SLOAD or SSTORE opcode.
3275    ///
3276    /// Returns `None` when:
3277    /// - `cfg.disable_storage` is set, or
3278    /// - `opcode` is not SLOAD (0x54) or SSTORE (0x55), or
3279    /// - the stack is empty (guard against underflow before the handler runs), or
3280    /// - the storage read fails for any reason (including `AccountNotFound` —
3281    ///   the trace omits the entry rather than emitting an ambiguous zero).
3282    ///
3283    /// For SLOAD: key = `stack.top`; value = the *current* stored value read from the DB.
3284    /// For SSTORE: key = `stack.top`, value = `stack[top-1]` (the new value being written).
3285    pub fn read_storage_for_trace(&mut self, opcode: u8) -> Option<(H256, H256)> {
3286        const SLOAD: u8 = 0x54;
3287        const SSTORE: u8 = 0x55;
3288
3289        if self.opcode_tracer.cfg.disable_storage {
3290            return None;
3291        }
3292        if opcode != SLOAD && opcode != SSTORE {
3293            return None;
3294        }
3295
3296        // Need at least one element on stack for SLOAD, two for SSTORE.
3297        use crate::constants::STACK_LIMIT;
3298        let offset = self.current_call_frame.stack.offset;
3299        if offset >= STACK_LIMIT {
3300            return None; // stack empty
3301        }
3302
3303        // SLOAD/SSTORE operate on the call's storage context (`to`), not the code's
3304        // address. Under DELEGATECALL/CALLCODE these differ.
3305        let addr = self.current_call_frame.to;
3306
3307        let stack_values = &self.current_call_frame.stack.values;
3308        let key_u256 = *stack_values.get(offset)?;
3309        let key = BigEndianHash::from_uint(&key_u256);
3310
3311        if opcode == SLOAD {
3312            // Omit the entry on any read failure (incl. account not yet cached);
3313            // a zero value would be indistinguishable from a legitimate never-written slot.
3314            let v = self.get_storage_value(addr, key).ok()?;
3315            let value = BigEndianHash::from_uint(&v);
3316            Some((key, value))
3317        } else {
3318            // SSTORE: need two stack elements.
3319            let next_offset = offset.checked_add(1)?;
3320            if next_offset >= STACK_LIMIT {
3321                return None;
3322            }
3323            // values[offset+1] is the new value being written (second from top = stack[top-1]).
3324            let value_u256 = *self.current_call_frame.stack.values.get(next_offset)?;
3325            let value = BigEndianHash::from_uint(&value_u256);
3326            Some((key, value))
3327        }
3328    }
3329}
3330
3331impl Substate {
3332    /// Initializes the VM substate, mainly adding addresses to the "accessed_addresses" field and the same with storage slots
3333    pub fn initialize(env: &Environment, tx: &Transaction) -> Result<Substate, VMError> {
3334        let fork = env.config.fork;
3335
3336        // Add sender and recipient to accessed accounts [https://www.evm.codes/about#access_list]
3337        // Precompiles are NO LONGER inserted here — they are warm by construction (see
3338        // `is_warm_precompile`), removing the ~20-entry floor that used to dominate this set. The
3339        // remaining working set is small (sender + coinbase + recipient + access-list/touched
3340        // addresses; real p99 ~7), so a capacity of 8 covers most txs with little waste.
3341        let mut initial_accessed_addresses =
3342            FxHashSet::with_capacity_and_hasher(8, Default::default());
3343        // Storage slots are ~98% empty (p95 0, p99 4), so `default()` (alloc-free until first
3344        // insert) beats pre-sizing, which would tax the common empty case.
3345        let mut initial_accessed_storage_slots: FxHashMap<Address, FxHashSet<H256>> =
3346            FxHashMap::default();
3347
3348        // Add Tx sender to accessed accounts
3349        initial_accessed_addresses.insert(env.origin);
3350
3351        // [EIP-3651] - Add coinbase to accessed accounts after Shanghai
3352        if fork >= Fork::Shanghai {
3353            initial_accessed_addresses.insert(env.coinbase);
3354        }
3355
3356        // Add access lists contents to accessed accounts and accessed storage slots.
3357        // Iterate by reference (`Address`/`H256` are `Copy`); the old `.clone()` deep-copied
3358        // the whole `Vec<(Address, Vec<H256>)>` per tx just to read it.
3359        for (address, keys) in tx.access_list() {
3360            initial_accessed_addresses.insert(*address);
3361            // 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
3362            let warm_slots = initial_accessed_storage_slots.entry(*address).or_default();
3363            for slot in keys {
3364                warm_slots.insert(*slot);
3365            }
3366        }
3367
3368        let substate = Substate::from_accesses(
3369            fork,
3370            initial_accessed_addresses,
3371            initial_accessed_storage_slots,
3372        );
3373
3374        Ok(substate)
3375    }
3376}
3377
3378// Test-support surface for the EIP-8037 state-gas reservoir/clamp-spill unit tests, which live
3379// in the `ethrex-test` crate (`test/tests/levm/eip8037_reservoir_tests.rs`) per the repo's
3380// test-location convention but must drive crate-private VM internals. Everything here is
3381// `#[doc(hidden)]` and exposes only what those tests touch: a fixture-free VM harness plus a
3382// handful of reservoir accessors. The harness builds the VM via struct literal to sidestep
3383// `VM::new`'s DB reads (which would pull `ethrex-storage`/`ethrex-blockchain` into levm and form
3384// a dependency cycle), keeping the two-pool arithmetic isolated.
3385#[doc(hidden)]
3386impl<'a> VM<'a> {
3387    /// Gas budget seeded into the harness top frame; large enough that spills never run it OOG.
3388    pub const STATE_GAS_HARNESS_FRAME_GAS: u64 = 1_000_000;
3389
3390    /// Builds a fixture-free VM on `fork` with a single top frame and the given starting
3391    /// `state_gas_reservoir`. `db`/`tx`/`crypto` are borrowed for the VM's lifetime but never
3392    /// read (the frame is built directly, so no account/storage/code loads occur).
3393    pub fn new_state_gas_harness(
3394        fork: Fork,
3395        db: &'a mut GeneralizedDatabase,
3396        tx: &'a Transaction,
3397        crypto: &'a dyn Crypto,
3398        state_gas_reservoir: u64,
3399    ) -> VM<'a> {
3400        let env = Environment {
3401            config: crate::environment::EVMConfig::new(
3402                fork,
3403                crate::environment::EVMConfig::canonical_values(fork),
3404            ),
3405            gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3406            block_gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3407            ..Default::default()
3408        };
3409        let current_call_frame = CallFrame::new(
3410            Address::default(),
3411            Address::default(),
3412            Address::default(),
3413            Code::default(),
3414            U256::zero(),
3415            Bytes::new(),
3416            false,
3417            Self::STATE_GAS_HARNESS_FRAME_GAS,
3418            0,
3419            true,
3420            false,
3421            0,
3422            0,
3423            Stack::default(),
3424            Memory::default(),
3425        );
3426        VM {
3427            call_frames: Vec::new(),
3428            current_call_frame,
3429            env,
3430            substate: Substate::default(),
3431            db,
3432            tx,
3433            hooks: Vec::new(),
3434            storage_original_values: FxHashMap::default(),
3435            tracer: LevmCallTracer::disabled(),
3436            opcode_tracer: LevmOpcodeTracer::disabled(),
3437            debug_mode: DebugMode::disabled(),
3438            stack_pool: Vec::new(),
3439            vm_type: VMType::L1,
3440            preserve_top_level_backup: false,
3441            state_gas_used: 0,
3442            state_gas_reservoir,
3443            state_gas_reservoir_initial: state_gas_reservoir,
3444            state_gas_spill: 0,
3445            cost_per_state_byte: 0,
3446            state_gas_new_account: 0,
3447            state_gas_storage_set: 0,
3448            state_gas_auth_base: 0,
3449            intrinsic_state_gas: 0,
3450            value_new_account_charged: false,
3451            prep_baseline_state_gas: 0,
3452            prep_baseline_reservoir: 0,
3453            prep_baseline_state_gas_spill: 0,
3454            prep_region_backup_marker: PrepareRegionBackupMarker::default(),
3455            pending_prep_oog: false,
3456            opcode_table: VM::build_opcode_table(fork),
3457            crypto,
3458            validation_observer: ValidationObserver::disabled(),
3459            frame_tx_context: None,
3460        }
3461    }
3462
3463    pub fn state_gas_reservoir(&self) -> u64 {
3464        self.state_gas_reservoir
3465    }
3466    pub fn state_gas_used(&self) -> i64 {
3467        self.state_gas_used
3468    }
3469    pub fn state_gas_spill(&self) -> u64 {
3470        self.state_gas_spill
3471    }
3472    pub fn state_gas_new_account(&self) -> u64 {
3473        self.state_gas_new_account
3474    }
3475    pub fn set_state_gas_new_account(&mut self, v: u64) {
3476        self.state_gas_new_account = v;
3477    }
3478    /// Seeds the post-intrinsic baseline (mirrors `add_intrinsic_gas`): both the VM-level
3479    /// `state_gas_used` and the top frame's entry snapshot.
3480    pub fn seed_state_gas_baseline(&mut self, used: i64) {
3481        self.state_gas_used = used;
3482        self.current_call_frame.state_gas_used_at_entry = used;
3483    }
3484    pub fn frame_state_gas_used_at_entry(&self) -> i64 {
3485        self.current_call_frame.state_gas_used_at_entry
3486    }
3487    pub fn frame_gas_remaining(&self) -> i64 {
3488        self.current_call_frame.gas_remaining
3489    }
3490    pub fn set_frame_gas_remaining(&mut self, v: i64) {
3491        self.current_call_frame.gas_remaining = v;
3492    }
3493    pub fn frame_state_gas_spilled(&self) -> u64 {
3494        self.current_call_frame.frame_state_gas_spilled
3495    }
3496}