Skip to main content

ethrex_levm/
utils.rs

1use crate::{
2    EVMConfig, Environment,
3    account::{AccountStatus, LevmAccount},
4    call_frame::CallFrameBackup,
5    constants::*,
6    db::gen_db::GeneralizedDatabase,
7    errors::{ExceptionalHalt, InternalError, TxValidationError, VMError},
8    gas_cost::{
9        self, ACCOUNT_WRITE_AMSTERDAM, BLOB_GAS_PER_BLOB, CREATE_BASE_COST,
10        PER_AUTH_BASE_COST_AMSTERDAM, STANDARD_TOKEN_COST, WARM_ADDRESS_ACCESS_COST,
11        cold_account_access_cost, floor_tokens_in_access_list, total_cost_floor_per_token,
12        tx_base_cost,
13    },
14    vm::{Substate, VM},
15};
16use ExceptionalHalt::OutOfGas;
17use bytes::Bytes;
18use ethrex_common::types::Log;
19use ethrex_common::{
20    Address, H256, U256,
21    evm::calculate_create_address,
22    types::{Account, Code, Fork, Transaction, fake_exponential, tx_fields::*},
23    utils::{keccak, u256_to_big_endian},
24};
25use ethrex_common::{types::TxKind, utils::u256_from_big_endian_const};
26use ethrex_rlp;
27use rustc_hash::{FxHashMap, FxHashSet};
28pub type Storage = FxHashMap<U256, H256>;
29
30// ================== Address related functions ======================
31/// Converts address (H160) to word (U256)
32pub fn address_to_word(address: Address) -> U256 {
33    let mut word = [0u8; 32];
34
35    for (word_byte, address_byte) in word.iter_mut().skip(12).zip(address.as_bytes().iter()) {
36        *word_byte = *address_byte;
37    }
38
39    u256_from_big_endian_const(word)
40}
41
42/// Calculates the address of a new contract using the CREATE2 opcode as follows
43///
44/// initialization_code = memory[offset:offset+size]
45///
46/// address = keccak256(0xff || sender_address || salt || keccak256(initialization_code))[12:]
47pub fn calculate_create2_address(
48    sender_address: Address,
49    initialization_code: &[u8],
50    salt: U256,
51) -> Result<Address, InternalError> {
52    let init_code_hash = keccak(initialization_code);
53
54    let generated_address = Address::from_slice(
55        keccak(
56            [
57                &[0xff],
58                sender_address.as_bytes(),
59                &salt.to_big_endian(),
60                init_code_hash.as_bytes(),
61            ]
62            .concat(),
63        )
64        .as_bytes()
65        .get(12..)
66        .ok_or(InternalError::Slicing)?,
67    );
68    Ok(generated_address)
69}
70
71// ================== Backup related functions =======================
72
73/// Restore the state of the cache to the state it in the callframe backup.
74/// Also restores BAL recorder state changes (but not touched_addresses) per EIP-7928.
75pub fn restore_cache_state(
76    db: &mut GeneralizedDatabase,
77    callframe_backup: CallFrameBackup,
78) -> Result<(), VMError> {
79    for (address, account) in callframe_backup.original_accounts_info {
80        if let Some(current_account) = db.current_accounts_state.get_mut(&address) {
81            current_account.info = account.info;
82            current_account.status = account.status;
83            current_account.has_storage = account.has_storage;
84            current_account.exists = account.exists;
85        }
86    }
87
88    for (address, storage) in callframe_backup.original_account_storage_slots {
89        // This call to `get_account_mut` should never return None, because we are looking up accounts
90        // that had their storage modified, which means they should be in the cache. That's why
91        // we return an internal error in case we haven't found it.
92        let account = db
93            .current_accounts_state
94            .get_mut(&address)
95            .ok_or(InternalError::AccountNotFound)?;
96
97        for (key, value) in storage {
98            account.storage.insert(key, value);
99        }
100    }
101
102    // Evict codes the reverted frame(s) deployed: a stale by-hash cache entry
103    // would serve a later read of the same hash (from a pre-existing account)
104    // without hitting the store, hiding the read from execution-witness
105    // recording (EIP-8025). Only hashes that were NOT cached before the frame
106    // are tracked, so committed or store-loaded codes are never evicted; codes the
107    // block access list provided meanwhile are kept (see `evict_reverted_code`).
108    for code_hash in callframe_backup.inserted_code_hashes {
109        db.evict_reverted_code(&code_hash);
110    }
111
112    // Restore BAL recorder to checkpoint (but keep touched_addresses per EIP-7928)
113    if let Some(checkpoint) = callframe_backup.bal_checkpoint
114        && let Some(recorder) = db.bal_recorder.as_mut()
115    {
116        recorder.restore(checkpoint);
117    }
118
119    Ok(())
120}
121
122// ================= Blob hash related functions =====================
123pub fn get_base_fee_per_blob_gas(
124    block_excess_blob_gas: Option<u64>,
125    evm_config: &EVMConfig,
126) -> Result<U256, VMError> {
127    let base_fee_update_fraction = evm_config.blob_schedule.base_fee_update_fraction;
128    let excess_blob_gas = block_excess_blob_gas.unwrap_or_default();
129
130    fake_exponential(
131        MIN_BASE_FEE_PER_BLOB_GAS.into(),
132        excess_blob_gas.into(),
133        base_fee_update_fraction,
134    )
135    .map_err(|err| VMError::Internal(InternalError::FakeExponentialError(err)))
136}
137
138/// Gets the max blob gas cost for a transaction that a user is
139/// willing to pay.
140pub fn get_max_blob_gas_price(
141    tx_blob_hashes: &[H256],
142    tx_max_fee_per_blob_gas: Option<U256>,
143) -> Result<U256, VMError> {
144    let blobhash_amount: u64 = tx_blob_hashes
145        .len()
146        .try_into()
147        .map_err(|_| InternalError::TypeConversion)?;
148
149    let blob_gas_used: u64 = blobhash_amount
150        .checked_mul(BLOB_GAS_PER_BLOB)
151        .unwrap_or_default();
152
153    let max_blob_gas_cost = tx_max_fee_per_blob_gas
154        .unwrap_or_default()
155        .checked_mul(blob_gas_used.into())
156        .ok_or(InternalError::Overflow)?;
157
158    Ok(max_blob_gas_cost)
159}
160/// Calculate the actual blob gas cost.
161pub fn calculate_blob_gas_cost(
162    tx_blob_hashes: &[H256],
163    base_blob_fee_per_gas: U256,
164) -> Result<U256, VMError> {
165    let blobhash_amount: u64 = tx_blob_hashes
166        .len()
167        .try_into()
168        .map_err(|_| InternalError::TypeConversion)?;
169
170    let blob_gas_used: u64 = blobhash_amount
171        .checked_mul(BLOB_GAS_PER_BLOB)
172        .unwrap_or_default();
173
174    let blob_gas_used: U256 = blob_gas_used.into();
175    let blob_fee: U256 = blob_gas_used
176        .checked_mul(base_blob_fee_per_gas)
177        .ok_or(InternalError::Overflow)?;
178
179    Ok(blob_fee)
180}
181
182// ==================== Word related functions =======================
183pub fn word_to_address(word: U256) -> Address {
184    Address::from_slice(&u256_to_big_endian(word)[12..])
185}
186
187// ================== EIP-7702 related functions =====================
188
189pub fn code_has_delegation(code: &[u8]) -> Result<bool, VMError> {
190    // Delegate to the canonical predicate in `ethrex-common` so the
191    // EIP-7702 designation check (`0xef0100 || address`, exactly 23 bytes)
192    // has a single source of truth. Signature kept as `&[u8]` for callers.
193    Ok(ethrex_common::types::is_eip7702_delegation(code))
194}
195
196/// Gets the address inside the bytecode if it has been
197/// delegated as the EIP7702 determines.
198pub fn get_authorized_address_from_code(code: &[u8]) -> Result<Address, VMError> {
199    if code_has_delegation(code)? {
200        let address_bytes = &code
201            .get(SET_CODE_DELEGATION_BYTES.len()..)
202            .ok_or(InternalError::Slicing)?;
203        // It shouldn't panic when doing Address::from_slice()
204        // because the length is checked inside the code_has_delegation() function
205        let address = Address::from_slice(address_bytes);
206        Ok(address)
207    } else {
208        // if we end up here, it means that the address wasn't previously delegated.
209        Err(InternalError::AccountNotDelegated.into())
210    }
211}
212
213pub fn eip7702_recover_address(
214    auth_tuple: &AuthorizationTuple,
215    crypto: &dyn ethrex_crypto::Crypto,
216) -> Result<Option<Address>, VMError> {
217    use ethrex_rlp::encode::RLPEncode;
218
219    if auth_tuple.s_signature > *SECP256K1_ORDER_OVER2 || U256::zero() >= auth_tuple.s_signature {
220        return Ok(None);
221    }
222    if auth_tuple.r_signature > *SECP256K1_ORDER || U256::zero() >= auth_tuple.r_signature {
223        return Ok(None);
224    }
225    if auth_tuple.y_parity != U256::one() && auth_tuple.y_parity != U256::zero() {
226        return Ok(None);
227    }
228
229    let mut rlp_buf = Vec::with_capacity(128);
230    rlp_buf.push(MAGIC);
231    (auth_tuple.chain_id, auth_tuple.address, auth_tuple.nonce).encode(&mut rlp_buf);
232    let msg = crypto.keccak256(&rlp_buf);
233
234    let y_parity: u8 =
235        TryInto::<u8>::try_into(auth_tuple.y_parity).map_err(|_| InternalError::TypeConversion)?;
236
237    let mut sig = [0u8; 65];
238    sig[..32].copy_from_slice(&auth_tuple.r_signature.to_big_endian());
239    sig[32..64].copy_from_slice(&auth_tuple.s_signature.to_big_endian());
240    sig[64] = y_parity;
241
242    match crypto.recover_signer(&sig, &msg) {
243        Ok(address) => Ok(Some(address)),
244        Err(_) => Ok(None),
245    }
246}
247
248/// Gets code of an account, returning early if it's not a delegated account, otherwise
249/// Returns tuple (is_delegated, eip7702_cost, code_address, code).
250/// Notice that it also inserts the delegated account to the "accessed accounts" set.
251///
252/// Where:
253/// - `is_delegated`: True if account is a delegated account.
254/// - `eip7702_cost`: Cost of accessing the delegated account (if any)
255/// - `code_address`: Code address (if delegated, returns the delegated address)
256/// - `code`: Bytecode of the code_address, what the EVM will execute.
257pub fn eip7702_get_code(
258    db: &mut GeneralizedDatabase,
259    accrued_substate: &mut Substate,
260    address: Address,
261    fork: Fork,
262) -> Result<(bool, u64, Address, Code), VMError> {
263    let (bytecode, delegation) = eip7702_peek_delegation(db, accrued_substate, address, fork)?;
264    let Some((auth_address, access_cost)) = delegation else {
265        return Ok((false, 0, address, bytecode.unwrap_or_default()));
266    };
267
268    accrued_substate.add_accessed_address(auth_address);
269    let authorized_bytecode = db.get_account_code(auth_address)?.clone();
270
271    Ok((true, access_cost, auth_address, authorized_bytecode))
272}
273
274/// A call target's code (`None` when it has none) and, when it is an EIP-7702
275/// delegation, the delegate address with its access cost.
276pub type PeekedCode = (Option<Code>, Option<(Address, u64)>);
277
278/// First half of [`eip7702_get_code`]: read `address`'s code and detect a
279/// delegation designation WITHOUT touching the delegate account.
280///
281/// Returns `address`'s code and, when delegated, the delegate address with
282/// its warm/cold access cost (computed from the current substate, not
283/// recorded). CALL-family opcodes use this to gas-check the delegation
284/// access cost before reading the delegate (EELS order); reading it earlier
285/// would leak the delegate account into execution witnesses on OOG.
286pub fn eip7702_peek_delegation(
287    db: &mut GeneralizedDatabase,
288    substate: &Substate,
289    address: Address,
290    fork: Fork,
291) -> Result<PeekedCode, VMError> {
292    let account = db.get_account(address)?;
293    // An account without code (an EOA or a precompile) cannot carry a delegation
294    // designation. Calls to precompiles take this path every time, so skip the
295    // code-cache lookup and the clone and drop of the empty `Code` entry, and
296    // return no code at all.
297    if !account.has_code() {
298        return Ok((None, None));
299    }
300    let code_hash = account.info.code_hash;
301    let bytecode = db.get_code(code_hash)?.clone();
302    if !code_has_delegation(bytecode.code())? {
303        return Ok((Some(bytecode), None));
304    }
305    let auth_address = get_authorized_address_from_code(bytecode.code())?;
306    let access_cost = if substate.is_address_accessed(&auth_address) {
307        WARM_ADDRESS_ACCESS_COST
308    } else {
309        // EIP-8038 (glamsterdam-devnet-6): cold account access is repriced
310        // 2600 -> 3000 at Amsterdam, so the 7702 delegate-access cost must be
311        // fork-dependent rather than the flat COLD_ADDRESS_ACCESS_COST.
312        cold_account_access_cost(fork)
313    };
314    Ok((Some(bytecode), Some((auth_address, access_cost))))
315}
316
317/// Precomputed intrinsic-gas components for a transaction.
318///
319/// Computed once per tx in the prepare-execution hook and reused by
320/// [`VM::validate_min_gas_limit`](crate::hooks::default_hook::validate_min_gas_limit)
321/// and [`VM::add_intrinsic_gas`]. Previously the full calldata / access-list /
322/// auth-list walk ran 2-3x per tx (once in each function, plus the pre-Amsterdam
323/// floor's own `tx_calldata`).
324#[derive(Clone, Copy, Debug)]
325pub struct IntrinsicGas {
326    /// Regular (EIP-8037) intrinsic-gas arm.
327    pub regular: u64,
328    /// State (EIP-8037, Amsterdam+) intrinsic-gas arm; always 0 pre-Amsterdam.
329    pub state: u64,
330    /// `gas_cost::tx_calldata` over `current_call_frame.calldata`. Reused by the
331    /// pre-Amsterdam floor check (same byte string, same point in execution).
332    pub calldata_cost: u64,
333}
334
335impl<'a> VM<'a> {
336    /// Applies the EIP-7702 authorizations and charges their state-dependent costs at
337    /// the top frame, mirroring EELS `set_delegation`
338    /// (`amsterdam/vm/eoa_delegation.py::set_delegation`).
339    ///
340    /// Amsterdam+ (EIP-8037/8038): the per-auth intrinsic regular charge is only
341    /// `REGULAR_PER_AUTH_BASE_COST`; the state-dependent charges are levied here, in the
342    /// atomic prepare region (so an OOG rolls the whole region back and burns all gas
343    /// rather than rejecting the tx). Per valid authorization, in EELS order:
344    /// - `NEW_ACCOUNT` (state) when the authority's account leaf does not yet exist;
345    /// - `ACCOUNT_WRITE` (regular) when this is the transaction's first write to
346    ///   the authority's leaf (the sender's leaf was written at inclusion, and the
347    ///   recipient's when `value > 0`, so those pay nothing here — a self-sponsored
348    ///   authority and repeated authorizations on one authority pay `ACCOUNT_WRITE` at
349    ///   most once);
350    /// - `AUTH_BASE` (state) when a net-new delegation indicator is written (the
351    ///   authority was not delegated before the tx and none was set for it earlier in
352    ///   the tx). Charged at most once per authority and never credited back.
353    ///
354    /// On any `OutOfGas` from a charge, `fail_prepare_region` rolls back the region and
355    /// this returns `Ok` (the full-gas revert is emitted by `run_execution`); it never
356    /// propagates an `Err` (that would wrongly invalidate the block).
357    ///
358    /// Pre-Amsterdam keeps the legacy per-auth model: `PER_EMPTY_ACCOUNT_COST` was
359    /// charged at intrinsic and `REFUND_AUTH_PER_EXISTING_ACCOUNT` is credited here for
360    /// an authority that already exists in the trie.
361    pub fn eip7702_set_access_code(&mut self) -> Result<(), VMError> {
362        let amsterdam = self.env.config.fork >= Fork::Amsterdam;
363
364        // Pre-Amsterdam existing-authority refund accumulator.
365        let mut refunded_gas: u64 = 0;
366
367        // EELS `delegated_before_tx`: whether each authority was already delegated at
368        // tx start. The first time an authority is seen its code is still the pre-tx
369        // code (auth processing runs before execution), so we cache it then.
370        let mut delegated_before_tx: FxHashMap<Address, bool> = FxHashMap::default();
371
372        // EELS `set_delegation` bookkeeping (Amsterdam+ only):
373        // - `written_accounts`: leaves this tx has already written. The sender's leaf
374        //   was written at inclusion (nonce bump + fee deduction); the recipient's when
375        //   value is transferred. An authority already in this set pays no ACCOUNT_WRITE.
376        // - `delegation_set_for`: authorities a delegation indicator was set for earlier
377        //   in this tx (so AUTH_BASE is charged at most once per authority).
378        let mut written_accounts: FxHashSet<Address> = FxHashSet::default();
379        let mut delegation_set_for: FxHashSet<Address> = FxHashSet::default();
380        if amsterdam {
381            written_accounts.insert(self.env.origin);
382            if !self.tx.value().is_zero() {
383                written_accounts.insert(self.current_call_frame.to);
384            }
385        }
386
387        // IMPORTANT:
388        // If any of the below steps fail, immediately stop processing that tuple and continue to the next tuple in the list. It will in the case of multiple tuples for the same authority, set the code using the address in the last valid occurrence.
389        // If transaction execution results in failure (any exceptional condition or code reverting), setting delegation designations is not rolled back (unless the atomic prepare region OOGs, which rolls back everything).
390        for auth_tuple in self.tx.authorization_list().cloned().unwrap_or_default() {
391            let chain_id_not_equals_this_chain_id = auth_tuple.chain_id != self.env.chain_id;
392            let chain_id_not_zero = !auth_tuple.chain_id.is_zero();
393
394            // 1. Verify the chain id is either 0 or the chain’s current ID.
395            if chain_id_not_zero && chain_id_not_equals_this_chain_id {
396                continue;
397            }
398
399            // 2. Verify the nonce is less than 2**64 - 1.
400            // NOTE: nonce is a u64, it's always less than or equal to u64::MAX
401            if auth_tuple.nonce == u64::MAX {
402                continue;
403            }
404
405            // 3. authority = ecrecover(keccak(MAGIC || rlp([chain_id, address, nonce])), y_parity, r, s)
406            //      s value must be less than or equal to secp256k1n/2, as specified in EIP-2.
407            let Some(authority_address) = eip7702_recover_address(&auth_tuple, self.crypto)? else {
408                continue;
409            };
410
411            // 4. Add authority to accessed_addresses (as defined in EIP-2929).
412            let authority_account = self.db.get_account(authority_address)?;
413            let authority_exists = authority_account.exists;
414            let authority_info = authority_account.info.clone();
415            let authority_code = self.db.get_code(authority_info.code_hash)?;
416            self.substate.add_accessed_address(authority_address);
417
418            // 5. Verify the code of authority is either empty or already delegated.
419            // Check this BEFORE recording to BAL so we can release the borrow on authority_code.
420            let authority_code_is_empty = authority_code.is_empty();
421            let delegated_now = code_has_delegation(authority_code.code())?;
422            let empty_or_delegated = authority_code_is_empty || delegated_now;
423            // First sighting of an authority captures its pre-tx delegation state
424            // (EELS `delegated_before_tx` from `get_pre_state_account`).
425            let pre_delegated = *delegated_before_tx
426                .entry(authority_address)
427                .or_insert(delegated_now);
428
429            // Record authority as touched for BAL per EIP-7928, even if validation fails later.
430            // This ensures authority appears in BAL with empty change set when:
431            // - Authority was loaded (above)
432            // - But validation fails (checks below)
433            if let Some(recorder) = self.db.bal_recorder.as_mut() {
434                recorder.record_touched_address(authority_address);
435            }
436
437            if !empty_or_delegated {
438                continue;
439            }
440
441            // 6. Verify the nonce of authority is equal to nonce. In case authority does not exist in the trie, verify that nonce is equal to 0.
442            // If it doesn't exist, it means the nonce is zero. The get_account() function will return Account::default()
443            // If it has nonce, the account.info.nonce should equal auth_tuple.nonce
444            if authority_info.nonce != auth_tuple.nonce {
445                continue;
446            }
447
448            if amsterdam {
449                // EELS `set_delegation` charges, in order:
450                // (a) NEW_ACCOUNT (state) when the authority leaf is absent. Uses `exists`
451                //     (EELS `account_exists`), NOT `!is_empty()`; a repeated authority
452                //     that a prior tuple already materialized reads `exists == true`.
453                if !authority_exists && self.increase_state_gas(self.state_gas_new_account).is_err()
454                {
455                    self.fail_prepare_region();
456                    return Ok(());
457                }
458
459                // (b) ACCOUNT_WRITE (regular) on the first write to the authority leaf.
460                if !written_accounts.contains(&authority_address) {
461                    if self
462                        .current_call_frame
463                        .increase_consumed_gas(ACCOUNT_WRITE_AMSTERDAM)
464                        .is_err()
465                    {
466                        self.fail_prepare_region();
467                        return Ok(());
468                    }
469                    written_accounts.insert(authority_address);
470                }
471
472                // (c) AUTH_BASE (state) when a net-new delegation indicator is written:
473                //     setting a non-null delegation, the authority was not delegated
474                //     before the tx, and none was set for it earlier this tx.
475                if auth_tuple.address != Address::zero() {
476                    if !pre_delegated
477                        && !delegation_set_for.contains(&authority_address)
478                        && self.increase_state_gas(self.state_gas_auth_base).is_err()
479                    {
480                        self.fail_prepare_region();
481                        return Ok(());
482                    }
483                    delegation_set_for.insert(authority_address);
484                }
485            } else if authority_exists {
486                // Pre-Amsterdam: existing authority refund (legacy model).
487                refunded_gas = refunded_gas
488                    .checked_add(REFUND_AUTH_PER_EXISTING_ACCOUNT)
489                    .ok_or(InternalError::Overflow)?;
490            }
491
492            // 8. Set the code of authority to be 0xef0100 || address. This is a delegation designation.
493            let delegation_bytes = [
494                &SET_CODE_DELEGATION_BYTES[..],
495                auth_tuple.address.as_bytes(),
496            ]
497            .concat();
498
499            // As a special case, if address is 0x0000000000000000000000000000000000000000 do not write the designation.
500            // Clear the account’s code and reset the account’s code hash to the empty hash.
501            let code = if auth_tuple.address != Address::zero() {
502                delegation_bytes.into()
503            } else {
504                Bytes::new()
505            };
506            self.update_account_bytecode(
507                authority_address,
508                Code::from_bytecode(code, self.crypto),
509            )?;
510
511            // 9. Increase the nonce of authority by one.
512            self.increment_account_nonce(authority_address)
513                .map_err(|_| TxValidationError::NonceIsMax)?;
514        }
515
516        // Pre-Amsterdam legacy refund channel (Amsterdam+ leaves `refunded_gas` at 0).
517        if refunded_gas > 0 {
518            self.substate.refunded_gas = self
519                .substate
520                .refunded_gas
521                .checked_add(refunded_gas)
522                .ok_or(InternalError::Overflow)?;
523        }
524
525        // EELS `auth_state_gas_used` lock-in (`interpreter.py`: after `set_delegation`,
526        // `evm.auth_state_gas_used = frame_state_gas_used(evm)`,
527        // `message.state_gas_reservoir = evm.state_gas_left`, `evm.state_gas_spilled = 0`).
528        // Re-seed the frame's state-gas baseline past the committed auth state gas so a
529        // later *execution* revert's `refill_frame_state_gas` cannot credit auth state
530        // gas back, and zero the frame spill so the auth spill stays consumed. The
531        // subsequent prepare-dispatch (create/value/delegation-resolve) charges sit above
532        // this baseline and stay refillable on an execution revert. The prep-OOG path
533        // instead refills to `prep_baseline_state_gas` (pre-region), so it fully rolls
534        // auth back too. Skipped if the auth loop already OOG'd (early return above).
535        if amsterdam {
536            self.current_call_frame.state_gas_used_at_entry = self.state_gas_used;
537            self.current_call_frame.frame_state_gas_spilled = 0;
538        }
539
540        Ok(())
541    }
542
543    pub fn add_intrinsic_gas(&mut self, intrinsic: &IntrinsicGas) -> Result<(), VMError> {
544        // Intrinsic gas is the gas consumed by the transaction before the execution of the opcodes. Section 6.2 in the Yellow Paper.
545
546        let regular_gas = intrinsic.regular;
547        let state_gas = intrinsic.state;
548
549        let total_gas = regular_gas.checked_add(state_gas).ok_or(OutOfGas)?;
550
551        self.current_call_frame
552            .increase_consumed_gas(total_gas)
553            .map_err(|_| TxValidationError::IntrinsicGasTooLow)?;
554
555        // state_gas_used is i64; intrinsic state gas is bounded by tx gas limit (< i64::MAX).
556        self.state_gas_used = self
557            .state_gas_used
558            .checked_add(i64::try_from(state_gas).map_err(|_| InternalError::Overflow)?)
559            .ok_or(InternalError::Overflow)?;
560        // Remember the intrinsic split so we can leave it in state_gas_used on top-level
561        // error (matches EELS `tx_env.intrinsic_state_gas`, which is kept separate from
562        // `tx_output.state_gas_used` and never refunded).
563        debug_assert_eq!(self.intrinsic_state_gas, 0, "intrinsic_state_gas set twice");
564        self.intrinsic_state_gas = state_gas;
565
566        // EIP-8037 (Amsterdam+): compute state gas reservoir from excess gas_limit.
567        // execution_gas = what remains after all intrinsic gas; regular_gas_budget = how much
568        // regular execution gas is allowed (capped at TX_MAX_GAS_LIMIT_AMSTERDAM); the difference becomes
569        // the reservoir for drawing state gas without consuming regular gas_remaining.
570        if self.env.config.fork >= Fork::Amsterdam {
571            if self.env.is_system_call {
572                // EIP-8037: system
573                // transactions get a dedicated state-gas reservoir of
574                // `state_gas_storage_set * SYSTEM_MAX_SSTORES_PER_CALL` ON TOP of
575                // the full SYS_CALL_GAS_LIMIT regular budget — so SSTORE-heavy
576                // system contracts (EIP-2935, EIP-4788) cannot OOG on state-gas
577                // growth alone. Skip the regular reservoir computation so we don't
578                // pre-consume `gas_remaining`; EELS sets `intrinsic_regular_gas=0`
579                // and `gas=SYSTEM_TRANSACTION_GAS` for the message
580                // (amsterdam/fork.py::process_unchecked_system_transaction).
581                let sys_reservoir = self
582                    .state_gas_storage_set
583                    .saturating_mul(SYSTEM_MAX_SSTORES_PER_CALL);
584                self.state_gas_reservoir = sys_reservoir;
585                self.state_gas_reservoir_initial = sys_reservoir;
586            } else {
587                let gas_limit = self.tx.gas_limit();
588                let execution_gas = gas_limit.saturating_sub(total_gas);
589                let regular_gas_budget = TX_MAX_GAS_LIMIT_AMSTERDAM.saturating_sub(regular_gas);
590                // A simulation that lifted the cap (eth_call, debug_traceCall) spends its
591                // whole gas limit on execution and funds no reservoir, as geth does.
592                let gas_left = if self.env.disable_execution_gas_cap {
593                    execution_gas
594                } else {
595                    regular_gas_budget.min(execution_gas)
596                };
597                let reservoir = execution_gas.saturating_sub(gas_left);
598                if reservoir > 0 {
599                    // Pre-consume reservoir from gas_remaining so GAS opcode returns <= TX_MAX_GAS_LIMIT_AMSTERDAM
600                    let reservoir_i64 =
601                        i64::try_from(reservoir).map_err(|_| InternalError::Overflow)?;
602                    self.current_call_frame.gas_remaining = self
603                        .current_call_frame
604                        .gas_remaining
605                        .checked_sub(reservoir_i64)
606                        .ok_or(InternalError::Overflow)?;
607                    self.state_gas_reservoir = reservoir;
608                }
609                // Capture initial reservoir for block-dimensional regular gas computation.
610                self.state_gas_reservoir_initial = reservoir;
611            }
612
613            // EIP-8037: seed the top frame's state-gas entry baseline to the post-intrinsic
614            // value of `state_gas_used` (the intrinsic state gas was already added above).
615            // A top-level revert/halt refill (`refill_frame_state_gas`) then rolls back only
616            // the execution portion and preserves the intrinsic state gas (which EELS keeps
617            // separate as `tx_env.intrinsic_state_gas` and never refunds).
618            self.current_call_frame.state_gas_used_at_entry = self.state_gas_used;
619        }
620
621        Ok(())
622    }
623
624    // ==================== Gas related functions =======================
625    /// Returns `(regular_gas, state_gas)` intrinsic gas for the transaction.
626    /// For Amsterdam+, state_gas is the EIP-8037 state portion.
627    /// For pre-Amsterdam, state_gas is always 0.
628    pub fn get_intrinsic_gas(&self) -> Result<IntrinsicGas, VMError> {
629        // Intrinsic Gas = Calldata cost + Create cost + Base cost + Access list cost
630        let mut regular_gas: u64 = 0;
631        // Amsterdam+ intrinsic state gas is 0 (CREATE/value NEW_ACCOUNT and all EIP-7702
632        // auth state charges are levied in the atomic prepare region). Pre-Amsterdam has
633        // no state dimension. Kept as a named binding for the `IntrinsicGas` result.
634        let state_gas: u64 = 0;
635        let fork = self.env.config.fork;
636
637        // Calldata Cost
638        // 4 gas for each zero byte in the transaction data 16 gas for each non-zero byte in the transaction.
639        let calldata_cost = self
640            .current_call_frame
641            .calldata
642            .with_slice(gas_cost::tx_calldata)??;
643
644        regular_gas = regular_gas.checked_add(calldata_cost).ok_or(OutOfGas)?;
645
646        let is_create = self.is_create()?;
647
648        if fork >= Fork::Amsterdam {
649            // EIP-2780 (merged EIPs#11645): resource-based intrinsic gas.
650            // The flat 21000 base is decomposed into a sender base + recipient
651            // access charge + value-transfer charge. These tx-level sender/to
652            // charges are ALWAYS the cold rate; access lists do NOT warm
653            // tx-level accounts. Because the intrinsic uses fixed constants
654            // (not substate warmth), the cold rate is applied automatically.
655            let sender = self.env.origin;
656            let to = self.tx.to();
657
658            // Sender base: always TX_BASE_COST_AMSTERDAM (12000).
659            regular_gas = regular_gas
660                .checked_add(tx_base_cost(fork))
661                .ok_or(OutOfGas)?;
662
663            // tx.to + tx.value recipient charge (EELS `calculate_intrinsic_cost`
664            // items 2-3), shared with `intrinsic_gas_dimensions` and the
665            // calldata-floor anchor via `recipient_regular_gas`.
666            regular_gas = regular_gas
667                .checked_add(gas_cost::recipient_regular_gas(
668                    &to,
669                    self.tx.value(),
670                    sender,
671                    fork,
672                ))
673                .ok_or(OutOfGas)?;
674
675            // Contract-creation: NEW_ACCOUNT state gas is charged in-region by
676            // `prepare_execution` (EELS `prepare_dispatch` create branch), not
677            // at intrinsic time. Amsterdam+ create intrinsic state is 0.
678        } else {
679            // Base Cost
680            regular_gas = regular_gas.checked_add(TX_BASE_COST).ok_or(OutOfGas)?;
681
682            // Create Cost
683            if is_create {
684                // https://eips.ethereum.org/EIPS/eip-2#specification
685                regular_gas = regular_gas.checked_add(CREATE_BASE_COST).ok_or(OutOfGas)?;
686            }
687        }
688
689        // EIP-3860 init code words (Shanghai+), unchanged by EIP-2780.
690        if is_create && fork >= Fork::Shanghai {
691            let number_of_words = &self.current_call_frame.calldata.len().div_ceil(WORD_SIZE);
692            let double_number_of_words: u64 = number_of_words
693                .checked_mul(2)
694                .ok_or(OutOfGas)?
695                .try_into()
696                .map_err(|_| InternalError::TypeConversion)?;
697
698            regular_gas = regular_gas
699                .checked_add(double_number_of_words)
700                .ok_or(OutOfGas)?;
701        }
702
703        // Access List Cost
704        let mut access_lists_cost: u64 = 0;
705        for (_, keys) in self.tx.access_list() {
706            access_lists_cost = access_lists_cost
707                .checked_add(gas_cost::access_list_address_cost(fork))
708                .ok_or(OutOfGas)?;
709            for _ in keys {
710                access_lists_cost = access_lists_cost
711                    .checked_add(gas_cost::access_list_storage_key_cost(fork))
712                    .ok_or(OutOfGas)?;
713            }
714        }
715
716        // EIP-7981 (Amsterdam+): access-list data bytes also contribute to the regular arm.
717        // access_list_cost += floor_tokens_in_access_list * total_cost_floor_per_token
718        // = access_list_bytes * STANDARD_TOKEN_COST * total_cost_floor_per_token
719        // Effective: +1280 per address, +2048 per storage key.
720        if fork >= Fork::Amsterdam {
721            let al_floor_tokens = floor_tokens_in_access_list(self.tx.access_list());
722            let al_data_cost = al_floor_tokens
723                .checked_mul(total_cost_floor_per_token(fork))
724                .ok_or(InternalError::Overflow)?;
725            access_lists_cost = access_lists_cost
726                .checked_add(al_data_cost)
727                .ok_or(InternalError::Overflow)?;
728        }
729
730        regular_gas = regular_gas.checked_add(access_lists_cost).ok_or(OutOfGas)?;
731
732        // Authorization List Cost
733        // `unwrap_or_default` will return an empty vec when the `authorization_list` field is None.
734        // If the vec is empty, the len will be 0, thus the authorization_list_cost is 0.
735        let amount_of_auth_tuples: u64 = match self.tx.authorization_list() {
736            None => 0,
737            Some(list) => list
738                .len()
739                .try_into()
740                .map_err(|_| InternalError::TypeConversion)?,
741        };
742
743        if fork >= Fork::Amsterdam {
744            // EIP-8038 (EELS `calculate_intrinsic_cost`): the per-auth intrinsic regular
745            // charge is only `REGULAR_PER_AUTH_BASE_COST` (`PER_AUTH_BASE_COST_AMSTERDAM`,
746            // 7816). The ACCOUNT_WRITE (regular) and NEW_ACCOUNT / AUTH_BASE (state)
747            // charges are state-dependent and levied in-region by
748            // `eip7702_set_access_code` (EELS `set_delegation`), not at intrinsic time.
749            // Amsterdam auth intrinsic state is 0.
750            let regular_auth_cost = PER_AUTH_BASE_COST_AMSTERDAM
751                .checked_mul(amount_of_auth_tuples)
752                .ok_or(InternalError::Overflow)?;
753            regular_gas = regular_gas.checked_add(regular_auth_cost).ok_or(OutOfGas)?;
754        } else {
755            let authorization_list_cost = PER_EMPTY_ACCOUNT_COST
756                .checked_mul(amount_of_auth_tuples)
757                .ok_or(InternalError::Overflow)?;
758            regular_gas = regular_gas
759                .checked_add(authorization_list_cost)
760                .ok_or(OutOfGas)?;
761        }
762
763        Ok(IntrinsicGas {
764            regular: regular_gas,
765            state: state_gas,
766            calldata_cost,
767        })
768    }
769
770    /// Calculates the minimum gas to be consumed in the transaction.
771    pub fn get_min_gas_used(&self) -> Result<u64, VMError> {
772        let fork = self.env.config.fork;
773
774        // If the transaction is a CREATE transaction, the calldata is emptied and the bytecode is assigned.
775        let tx_calldata;
776        let calldata = if self.is_create()? {
777            self.current_call_frame.bytecode.code()
778        } else {
779            // A transaction's own data is owned, so this shares it rather than copying.
780            tx_calldata = self.current_call_frame.calldata.to_bytes()?;
781            tx_calldata.as_ref()
782        };
783
784        // EIP-7976 floor tokens: for the floor arm, all calldata bytes count unweighted.
785        // floor_tokens_in_calldata = (zero_bytes + nonzero_bytes) * STANDARD_TOKEN_COST
786        // Pre-Amsterdam uses the weighted EIP-7623 formula: (nonzero * 16 + zero * 4) / 4
787        let mut tokens_in_calldata: u64 = if fork >= Fork::Amsterdam {
788            // EIP-7976: floor tokens = total_bytes * STANDARD_TOKEN_COST (unweighted).
789            let total_bytes: u64 = calldata
790                .len()
791                .try_into()
792                .map_err(|_| InternalError::TypeConversion)?;
793            total_bytes
794                .checked_mul(STANDARD_TOKEN_COST)
795                .ok_or(InternalError::Overflow)?
796        } else {
797            // Pre-Amsterdam: weighted EIP-7623 token count.
798            gas_cost::tx_calldata(calldata)? / STANDARD_TOKEN_COST
799        };
800
801        // EIP-7981 (Amsterdam+): access-list data bytes fold into the floor-token count.
802        // floor_tokens_in_access_list = access_list_bytes * STANDARD_TOKEN_COST
803        // where access_list_bytes = 20 * address_count + 32 * storage_key_count.
804        if fork >= Fork::Amsterdam {
805            let al_floor_tokens = floor_tokens_in_access_list(self.tx.access_list());
806            tokens_in_calldata = tokens_in_calldata
807                .checked_add(al_floor_tokens)
808                .ok_or(InternalError::Overflow)?;
809        }
810
811        // EELS `data_floor_gas_cost = total_floor_tokens * TX_DATA_TOKEN_FLOOR + base_regular_gas`
812        // where `base_regular_gas = TX_BASE + recipient_regular_gas`. Pre-Amsterdam the floor
813        // base stays anchored on bare `tx_base_cost(fork)` (21000); Amsterdam+ (EIP-2780) folds
814        // in the recipient/value regular-gas contribution via `recipient_regular_gas`.
815        let mut min_gas_used: u64 = tokens_in_calldata
816            .checked_mul(total_cost_floor_per_token(fork))
817            .ok_or(InternalError::Overflow)?;
818
819        let floor_base = if fork >= Fork::Amsterdam {
820            tx_base_cost(fork)
821                .checked_add(gas_cost::recipient_regular_gas(
822                    &self.tx.to(),
823                    self.tx.value(),
824                    self.env.origin,
825                    fork,
826                ))
827                .ok_or(InternalError::Overflow)?
828        } else {
829            tx_base_cost(fork)
830        };
831
832        min_gas_used = min_gas_used
833            .checked_add(floor_base)
834            .ok_or(InternalError::Overflow)?;
835
836        Ok(min_gas_used)
837    }
838
839    /// Gets transaction callee, calculating create address if it's a "Create" transaction.
840    /// Bool indicates whether it is a `create` transaction or not.
841    pub fn get_tx_callee(
842        tx: &Transaction,
843        db: &mut GeneralizedDatabase,
844        env: &Environment,
845        substate: &mut Substate,
846    ) -> Result<(Address, bool), VMError> {
847        match tx.to() {
848            TxKind::Call(address_to) => {
849                substate.add_accessed_address(address_to);
850
851                Ok((address_to, false))
852            }
853
854            TxKind::Create => {
855                let sender_nonce = db.get_account(env.origin)?.info.nonce;
856
857                let created_address = calculate_create_address(env.origin, sender_nonce);
858
859                substate.add_accessed_address(created_address);
860                substate.add_created_account(created_address);
861
862                Ok((created_address, true))
863            }
864        }
865    }
866}
867
868/// Compute `(regular, state)` intrinsic gas for a transaction without needing
869/// a full VM instance. Mirrors `VM::get_intrinsic_gas` but operates on the raw
870/// transaction and fork. Amsterdam+ intrinsic state gas is 0 — CREATE/value
871/// `NEW_ACCOUNT` and all EIP-7702 auth state charges are levied in the atomic
872/// prepare region, not at intrinsic time — so this returns `(regular, 0)` for
873/// every fork.
874///
875/// Used by the block executor to perform the EIP-8037 (PR #2703) per-tx 2D
876/// inclusion check before the tx runs.
877///
878/// `sender` is the transaction's recovered sender; it is required for the
879/// EIP-2780 (Amsterdam+) self-transfer rule, which zeroes the recipient and
880/// value charges when `sender == tx.to`. The parameter is taken
881/// unconditionally so this function stays byte-identical with
882/// `VM::get_intrinsic_gas` across every tx shape (guarded by
883/// `test_intrinsic_parity_*`). A type-3/type-4 tx can never carry `to == sender`
884/// in practice, but the parameter is still threaded through for parity.
885pub fn intrinsic_gas_dimensions(
886    tx: &Transaction,
887    sender: Address,
888    fork: Fork,
889    _block_gas_limit: u64,
890) -> Result<(u64, u64), VMError> {
891    let mut regular_gas: u64 = 0;
892    let state_gas: u64 = 0;
893
894    // Calldata cost (EIP-2028 weighted)
895    let calldata_cost = gas_cost::tx_calldata(tx.data())?;
896    regular_gas = regular_gas.checked_add(calldata_cost).ok_or(OutOfGas)?;
897
898    let to = tx.to();
899    let is_create = matches!(to, TxKind::Create);
900
901    if fork >= Fork::Amsterdam {
902        // EIP-2780 (merged EIPs#11645): resource-based intrinsic gas.
903        // Mirror of `VM::get_intrinsic_gas`. These tx-level sender/to charges
904        // are ALWAYS the cold rate; access lists do NOT warm tx-level accounts.
905
906        // Sender base: always TX_BASE_COST_AMSTERDAM (12000).
907        regular_gas = regular_gas
908            .checked_add(tx_base_cost(fork))
909            .ok_or(OutOfGas)?;
910
911        // tx.to + tx.value recipient charge (EELS `calculate_intrinsic_cost`
912        // items 2-3), shared with `VM::get_intrinsic_gas` and the
913        // calldata-floor anchor via `recipient_regular_gas`.
914        regular_gas = regular_gas
915            .checked_add(gas_cost::recipient_regular_gas(
916                &to,
917                tx.value(),
918                sender,
919                fork,
920            ))
921            .ok_or(OutOfGas)?;
922
923        // Contract-creation: NEW_ACCOUNT state gas is charged in-region by
924        // `prepare_execution` (EELS `prepare_dispatch` create branch), not
925        // at intrinsic time. Amsterdam+ create intrinsic state is 0.
926    } else {
927        // Base cost
928        regular_gas = regular_gas.checked_add(TX_BASE_COST).ok_or(OutOfGas)?;
929
930        if is_create {
931            regular_gas = regular_gas.checked_add(CREATE_BASE_COST).ok_or(OutOfGas)?;
932        }
933    }
934
935    // EIP-3860 init code words (Shanghai+), unchanged by EIP-2780.
936    if is_create && fork >= Fork::Shanghai {
937        let words = tx.data().len().div_ceil(WORD_SIZE);
938        let double_words: u64 = words
939            .checked_mul(2)
940            .ok_or(OutOfGas)?
941            .try_into()
942            .map_err(|_| InternalError::TypeConversion)?;
943        regular_gas = regular_gas.checked_add(double_words).ok_or(OutOfGas)?;
944    }
945
946    // Access list cost
947    let mut access_lists_cost: u64 = 0;
948    for (_, keys) in tx.access_list() {
949        access_lists_cost = access_lists_cost
950            .checked_add(gas_cost::access_list_address_cost(fork))
951            .ok_or(OutOfGas)?;
952        for _ in keys {
953            access_lists_cost = access_lists_cost
954                .checked_add(gas_cost::access_list_storage_key_cost(fork))
955                .ok_or(OutOfGas)?;
956        }
957    }
958
959    // EIP-7981 (Amsterdam+): access-list data bytes fold into regular gas
960    if fork >= Fork::Amsterdam {
961        let al_floor_tokens = floor_tokens_in_access_list(tx.access_list());
962        let al_data_cost = al_floor_tokens
963            .checked_mul(total_cost_floor_per_token(fork))
964            .ok_or(InternalError::Overflow)?;
965        access_lists_cost = access_lists_cost
966            .checked_add(al_data_cost)
967            .ok_or(InternalError::Overflow)?;
968    }
969    regular_gas = regular_gas.checked_add(access_lists_cost).ok_or(OutOfGas)?;
970
971    // Authorization list cost
972    let amount_of_auth_tuples: u64 = match tx.authorization_list() {
973        None => 0,
974        Some(list) => list
975            .len()
976            .try_into()
977            .map_err(|_| InternalError::TypeConversion)?,
978    };
979
980    if fork >= Fork::Amsterdam {
981        // EIP-8038 (EELS `calculate_intrinsic_cost`): per-auth intrinsic regular is only
982        // `REGULAR_PER_AUTH_BASE_COST` (`PER_AUTH_BASE_COST_AMSTERDAM`, 7816). The
983        // ACCOUNT_WRITE / NEW_ACCOUNT / AUTH_BASE charges move to `set_delegation`
984        // (in-region). Amsterdam auth intrinsic state is 0. Mirrors `VM::get_intrinsic_gas`.
985        let regular_auth_cost = PER_AUTH_BASE_COST_AMSTERDAM
986            .checked_mul(amount_of_auth_tuples)
987            .ok_or(InternalError::Overflow)?;
988        regular_gas = regular_gas.checked_add(regular_auth_cost).ok_or(OutOfGas)?;
989    } else {
990        let auth_cost = PER_EMPTY_ACCOUNT_COST
991            .checked_mul(amount_of_auth_tuples)
992            .ok_or(InternalError::Overflow)?;
993        regular_gas = regular_gas.checked_add(auth_cost).ok_or(OutOfGas)?;
994    }
995
996    Ok((regular_gas, state_gas))
997}
998
999/// Standalone EIP-7623/7976/7981 floor gas for a transaction. Mirrors
1000/// [`VM::get_min_gas_used`] but operates on the raw transaction + fork, so it
1001/// can be called by mempool admission / the payload builder without needing a
1002/// VM instance. Returns `TX_BASE_COST + floor_rate * total_floor_tokens`.
1003///
1004/// Amsterdam+ uses the unweighted EIP-7976 floor (16 gas/token = 64 gas/byte)
1005/// and folds EIP-7981 access-list data bytes into the token count. Pre-
1006/// Amsterdam uses the weighted EIP-7623 formula.
1007///
1008/// `sender` is the transaction's recovered sender; it feeds the Amsterdam+
1009/// floor-base anchor (`tx_base_cost(fork) + recipient_regular_gas(...)`, see
1010/// EIP-2780), which needs the sender for the self-transfer zero-rule. Unused
1011/// pre-Amsterdam.
1012///
1013/// A mismatch between this and `VM::get_min_gas_used` would cause mempool
1014/// admission to drift from VM rejection; keep the two in sync. The
1015/// `test_intrinsic_parity_*` suite also guards this.
1016pub fn intrinsic_gas_floor(tx: &Transaction, sender: Address, fork: Fork) -> Result<u64, VMError> {
1017    // EIP-7976: floor tokens count ALL calldata bytes unweighted. For CREATE
1018    // txs the calldata is the init code. Mirrors `get_min_gas_used`.
1019    let calldata = tx.data();
1020
1021    let mut tokens_in_calldata: u64 = if fork >= Fork::Amsterdam {
1022        let total_bytes: u64 = calldata
1023            .len()
1024            .try_into()
1025            .map_err(|_| InternalError::TypeConversion)?;
1026        total_bytes
1027            .checked_mul(STANDARD_TOKEN_COST)
1028            .ok_or(InternalError::Overflow)?
1029    } else {
1030        gas_cost::tx_calldata(calldata)? / STANDARD_TOKEN_COST
1031    };
1032
1033    if fork >= Fork::Amsterdam {
1034        let al_floor_tokens = floor_tokens_in_access_list(tx.access_list());
1035        tokens_in_calldata = tokens_in_calldata
1036            .checked_add(al_floor_tokens)
1037            .ok_or(InternalError::Overflow)?;
1038    }
1039
1040    // Floor base: Amsterdam+ anchors on `tx_base_cost(fork) + recipient_regular_gas(...)`
1041    // (EIP-2780); pre-Amsterdam stays anchored on bare `tx_base_cost(fork)` (21000).
1042    // Mirrors `get_min_gas_used`.
1043    let floor_base = if fork >= Fork::Amsterdam {
1044        tx_base_cost(fork)
1045            .checked_add(gas_cost::recipient_regular_gas(
1046                &tx.to(),
1047                tx.value(),
1048                sender,
1049                fork,
1050            ))
1051            .ok_or(InternalError::Overflow)?
1052    } else {
1053        tx_base_cost(fork)
1054    };
1055
1056    tokens_in_calldata
1057        .checked_mul(total_cost_floor_per_token(fork))
1058        .ok_or(InternalError::Overflow)?
1059        .checked_add(floor_base)
1060        .ok_or(InternalError::Overflow.into())
1061}
1062
1063/// Converts Account to LevmAccount
1064/// The problem with this is that we don't have the storage root.
1065pub fn account_to_levm_account(account: Account) -> (LevmAccount, Code) {
1066    (
1067        LevmAccount {
1068            info: account.info,
1069            has_storage: !account.storage.is_empty(), // This is used in scenarios in which the storage is already all in the account. For the Levm Runner
1070            storage: account.storage.into_iter().collect(),
1071            status: AccountStatus::Unmodified,
1072            exists: true,
1073        },
1074        account.code,
1075    )
1076}
1077
1078/// Converts a U256 value into usize, returning an error if the value is over 32 bits
1079/// This is generally used for memory offsets and sizes, 32 bits is more than enough for this purpose.
1080#[expect(clippy::as_conversions)]
1081pub fn u256_to_usize(val: U256) -> Result<usize, VMError> {
1082    // OR the three high limbs into one branch instead of a 4-way `||` chain,
1083    // then a single magnitude check — fewer branches on this hot conversion
1084    // (MLOAD/MSTORE/MCOPY/CALLDATACOPY/RETURN/... offsets all pass through here).
1085    if (val.0[1] | val.0[2] | val.0[3]) != 0 || val.0[0] > u32::MAX as u64 {
1086        return Err(VMError::ExceptionalHalt(ExceptionalHalt::VeryLargeNumber));
1087    }
1088    Ok(val.0[0] as usize)
1089}
1090
1091/// Converts U256 size and offset to usize.
1092/// If the size is zero, the offset will be zero regardless of its original value as it is not relevant
1093pub fn size_offset_to_usize(size: U256, offset: U256) -> Result<(usize, usize), VMError> {
1094    if size.is_zero() {
1095        // Offset is irrelevant
1096        Ok((0, 0))
1097    } else {
1098        Ok((u256_to_usize(size)?, u256_to_usize(offset)?))
1099    }
1100}
1101
1102// ==================== EIP-7708 Helper Functions ====================
1103
1104/// Creates a Transfer log (LOG3) for an ETH transfer, emitted from
1105/// `log_address`: SYSTEM_ADDRESS for consensus EIP-7708 logs (Amsterdam+) or
1106/// TRACE_TRANSFER_ADDRESS for `eth_simulateV1` traceTransfers. Which of the two
1107/// apply is decided in `VM::push_eth_transfer_logs`.
1108#[inline]
1109pub fn create_eth_transfer_log(
1110    log_address: Address,
1111    from: Address,
1112    to: Address,
1113    value: U256,
1114) -> Log {
1115    let mut from_topic = [0u8; 32];
1116    from_topic[12..].copy_from_slice(from.as_bytes());
1117
1118    let mut to_topic = [0u8; 32];
1119    to_topic[12..].copy_from_slice(to.as_bytes());
1120
1121    let data = value.to_big_endian();
1122
1123    Log {
1124        address: log_address,
1125        topics: vec![
1126            TRANSFER_EVENT_TOPIC,
1127            H256::from(from_topic),
1128            H256::from(to_topic),
1129        ],
1130        data: Bytes::from(data.to_vec()),
1131    }
1132}