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