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