Skip to main content

ethrex_levm/opcode_handlers/
system.rs

1//! # System operations
2//!
3//! Includes the following opcodes:
4//!   - `CALL`
5//!   - `CALLCODE`
6//!   - `DELEGATECALL`
7//!   - `STATICCALL`
8//!   - `RETURN`
9//!   - `CREATE`
10//!   - `CREATE2`
11//!   - `SELFDESTRUCT`
12//!   - `REVERT`
13
14use crate::{
15    call_frame::CallFrame,
16    constants::{AMSTERDAM_INIT_CODE_MAX_SIZE, FAIL, INIT_CODE_MAX_SIZE, SUCCESS},
17    errors::{ContextResult, ExceptionalHalt, InternalError, OpcodeResult, TxResult, VMError},
18    gas_cost,
19    memory::{self, CallData, calculate_memory_size},
20    opcode_handlers::OpcodeHandler,
21    utils::{address_to_word, word_to_address, *},
22    vm::VM,
23};
24use bytes::Bytes;
25use ethrex_common::{Address, U256, evm::calculate_create_address, types::Fork};
26use ethrex_common::{
27    tracing::CallType,
28    types::{Code, InitcodeBuffer},
29};
30use std::mem;
31
32pub struct OpCallHandler;
33impl OpcodeHandler for OpCallHandler {
34    #[inline(always)]
35    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
36        let [
37            gas,
38            callee,
39            value,
40            args_offset,
41            args_len,
42            return_offset,
43            return_len,
44        ] = *vm.current_call_frame.stack.pop()?;
45        let callee = word_to_address(callee);
46        let (args_len, args_offset) = size_offset_to_usize(args_len, args_offset)?;
47        let (return_len, return_offset) = size_offset_to_usize(return_len, return_offset)?;
48
49        // Validations.
50        if vm.current_call_frame.is_static && !value.is_zero() {
51            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
52        }
53
54        let value_cost = if !value.is_zero() {
55            gas_cost::call_positive_value_cost(vm.env.config.fork)
56        } else {
57            0
58        };
59        let (new_memory_size, address_was_cold, static_cost) = vm.check_call_static_gas(
60            args_offset,
61            args_len,
62            return_offset,
63            return_len,
64            callee,
65            value_cost,
66        )?;
67
68        vm.substate.add_accessed_address(callee);
69        // `address_is_empty` only feeds gates that also require `value != 0`,
70        // so skip the read entirely when value is zero (matches EELS' gating
71        // of `is_account_alive` on `value != 0`).
72        let address_is_empty = if value.is_zero() {
73            false
74        } else {
75            vm.db.get_account(callee)?.is_empty()
76        };
77        // Detect a 7702 delegation without reading the delegate account: per
78        // EELS the delegate access cost is gas-checked first, so an OOG must
79        // not leak the delegate read into execution witnesses (EIP-8025).
80        let (callee_code, delegation) =
81            eip7702_peek_delegation(vm.db, &vm.substate, callee, vm.env.config.fork)?;
82        let is_delegation_7702 = delegation.is_some();
83        let (eip7702_gas_consumed, code_address) = match delegation {
84            Some((auth_address, access_cost)) => (access_cost, auth_address),
85            None => (0, callee),
86        };
87
88        // EIP-8141 mempool validation-trace: the CALL target must be an existing
89        // account or precompile and not EIP-7702-delegated (sender exempt).
90        if vm.validation_observer.active {
91            vm.validation_check_call_target(callee, is_delegation_7702)?;
92        }
93
94        let create_cost = if address_is_empty {
95            gas_cost::CALL_TO_EMPTY_ACCOUNT
96        } else {
97            0
98        };
99
100        // BAL touches the target before the delegation gas check, so a failed
101        // delegate-access check still leaves the target recorded.
102        vm.record_bal_call_touch(
103            callee,
104            code_address,
105            is_delegation_7702,
106            eip7702_gas_consumed,
107            new_memory_size,
108            vm.current_call_frame.memory.len(),
109            address_was_cold,
110            value_cost,
111            create_cost,
112        );
113
114        // `create_cost` is EIP-8037 state gas (charged via `increase_state_gas`
115        // below) and must not appear in the regular-gas check.
116        let bytecode = if let Some((auth_address, access_cost)) = delegation {
117            vm.current_call_frame.check_gas(
118                static_cost
119                    .checked_add(access_cost)
120                    .ok_or(ExceptionalHalt::OutOfGas)?,
121            )?;
122            vm.substate.add_accessed_address(auth_address);
123            Some(vm.db.get_account_code(auth_address)?.clone())
124        } else {
125            callee_code
126        };
127
128        let fork = vm.env.config.fork;
129
130        // Compute gas_left after eip7702 consumption (without modifying gas_remaining yet).
131        #[expect(clippy::as_conversions, reason = "safe")]
132        let gas_left = (vm.current_call_frame.gas_remaining as u64)
133            .checked_sub(eip7702_gas_consumed)
134            .ok_or(ExceptionalHalt::OutOfGas)?;
135
136        // EIP-8037 (Amsterdam+): account for state gas spill in child gas computation,
137        // but charge state gas AFTER regular gas per EIPs#11421.
138        // Regular gas OOG must not consume state gas that would inflate the parent's
139        // reservoir on frame failure.
140        let needs_state_gas = fork >= Fork::Amsterdam && address_is_empty;
141        let gas_left = if needs_state_gas {
142            let state_gas_new_account = vm.state_gas_new_account;
143            let from_reservoir = vm.state_gas_reservoir.min(state_gas_new_account);
144            // Safe: from_reservoir = min(reservoir, state_gas_new_account) <= state_gas_new_account
145            #[expect(
146                clippy::arithmetic_side_effects,
147                reason = "from_reservoir <= state_gas_new_account"
148            )]
149            let spill = state_gas_new_account - from_reservoir;
150            gas_left
151                .checked_sub(spill)
152                .ok_or(ExceptionalHalt::OutOfGas)?
153        } else {
154            gas_left
155        };
156
157        let (gas_cost, gas_limit) = gas_cost::call(
158            new_memory_size,
159            vm.current_call_frame.memory.len(),
160            address_was_cold,
161            address_is_empty,
162            value,
163            gas,
164            gas_left,
165            fork,
166        )?;
167
168        // Charge regular gas first (before state gas, per EIPs#11421).
169        vm.current_call_frame.increase_consumed_gas(
170            gas_cost
171                .checked_add(eip7702_gas_consumed)
172                .ok_or(ExceptionalHalt::OutOfGas)?,
173        )?;
174
175        // Then charge state gas for new account creation.
176        if needs_state_gas {
177            vm.increase_state_gas(vm.state_gas_new_account)?;
178        }
179
180        // Struct-log: record the geth-compatible CALL gasCost.
181        // Geth's gasCost for CALL family = intrinsic_overhead + callGasTemp (forwarded gas
182        // WITHOUT stipend). LEVM's `gas_cost` already equals `call_gas_costs + gas_forwarded`,
183        // i.e. `intrinsic + callGasTemp`. Stipend is added later inside the child frame, after
184        // the tracer fires, so it is NOT part of the reported gasCost.
185        if vm.opcode_tracer.active {
186            let geth_cost = gas_cost.saturating_add(eip7702_gas_consumed);
187            vm.opcode_tracer.last_opcode_gas_cost = Some(geth_cost);
188        }
189
190        // Resize memory: this is necessary for multiple reasons:
191        //   - Make sure the memory is expanded.
192        //   - When there is return data, preallocate it because it won't be possible while the next
193        //     call frame is active.
194        vm.current_call_frame.memory.resize(new_memory_size)?;
195
196        // Trace CALL operation.
197        let data = vm.get_calldata(args_offset, args_len)?;
198        vm.tracer.enter(
199            CallType::CALL,
200            vm.current_call_frame.to,
201            callee,
202            value,
203            gas_limit,
204            &data,
205        )?;
206
207        // Generic call.
208        vm.generic_call(
209            gas_limit,
210            value,
211            vm.current_call_frame.to,
212            callee,
213            code_address,
214            true,
215            vm.current_call_frame.is_static,
216            data,
217            return_offset,
218            return_len,
219            bytecode,
220            is_delegation_7702,
221            needs_state_gas,
222            None,
223        )
224    }
225}
226
227pub struct OpCallCodeHandler;
228impl OpcodeHandler for OpCallCodeHandler {
229    #[inline(always)]
230    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
231        let [
232            gas,
233            address,
234            value,
235            args_offset,
236            args_len,
237            return_offset,
238            return_len,
239        ] = *vm.current_call_frame.stack.pop()?;
240        let address = word_to_address(address);
241        let (args_len, args_offset) = size_offset_to_usize(args_len, args_offset)?;
242        let (return_len, return_offset) = size_offset_to_usize(return_len, return_offset)?;
243
244        let value_cost = if !value.is_zero() {
245            gas_cost::call_positive_value_cost(vm.env.config.fork)
246        } else {
247            0
248        };
249        let (new_memory_size, address_was_cold, static_cost) = vm.check_call_static_gas(
250            args_offset,
251            args_len,
252            return_offset,
253            return_len,
254            address,
255            value_cost,
256        )?;
257
258        vm.substate.add_accessed_address(address);
259        // Detect a 7702 delegation without reading the delegate account: per
260        // EELS the delegate access cost is gas-checked first, so an OOG must
261        // not leak the delegate read into execution witnesses (EIP-8025).
262        let (target_code, delegation) =
263            eip7702_peek_delegation(vm.db, &vm.substate, address, vm.env.config.fork)?;
264        let is_delegation_7702 = delegation.is_some();
265        let (eip7702_gas_consumed, code_address) = match delegation {
266            Some((auth_address, access_cost)) => (access_cost, auth_address),
267            None => (0, address),
268        };
269
270        // EIP-8141 mempool validation-trace: CALLCODE target check (CALLCODE
271        // itself is banned in non-deploy prefix frames; this also guards the
272        // deploy-frame case).
273        if vm.validation_observer.active {
274            vm.validation_check_call_target(address, is_delegation_7702)?;
275        }
276
277        // BAL touches the target before the delegation gas check.
278        vm.record_bal_call_touch(
279            address,
280            code_address,
281            is_delegation_7702,
282            eip7702_gas_consumed,
283            new_memory_size,
284            vm.current_call_frame.memory.len(),
285            address_was_cold,
286            value_cost,
287            0,
288        );
289
290        let bytecode = if let Some((auth_address, access_cost)) = delegation {
291            vm.current_call_frame.check_gas(
292                static_cost
293                    .checked_add(access_cost)
294                    .ok_or(ExceptionalHalt::OutOfGas)?,
295            )?;
296            vm.substate.add_accessed_address(auth_address);
297            Some(vm.db.get_account_code(auth_address)?.clone())
298        } else {
299            target_code
300        };
301
302        #[expect(clippy::as_conversions, reason = "safe")]
303        let gas_left = (vm.current_call_frame.gas_remaining as u64)
304            .checked_sub(eip7702_gas_consumed)
305            .ok_or(ExceptionalHalt::OutOfGas)?;
306        let (gas_cost, gas_limit) = gas_cost::callcode(
307            new_memory_size,
308            vm.current_call_frame.memory.len(),
309            address_was_cold,
310            value,
311            gas,
312            gas_left,
313            vm.env.config.fork,
314        )?;
315        vm.current_call_frame.increase_consumed_gas(
316            gas_cost
317                .checked_add(eip7702_gas_consumed)
318                .ok_or(ExceptionalHalt::OutOfGas)?,
319        )?;
320
321        // Struct-log: geth-compatible CALLCODE gasCost (intrinsic + forwarded, no stipend).
322        if vm.opcode_tracer.active {
323            let geth_cost = gas_cost.saturating_add(eip7702_gas_consumed);
324            vm.opcode_tracer.last_opcode_gas_cost = Some(geth_cost);
325        }
326
327        // Resize memory: this is necessary for multiple reasons:
328        //   - Make sure the memory is expanded.
329        //   - When there is return data, preallocate it because it won't be possible while the next
330        //     call frame is active.
331        vm.current_call_frame.memory.resize(new_memory_size)?;
332
333        // Trace CALL operation.
334        let data = vm.get_calldata(args_offset, args_len)?;
335        vm.tracer.enter(
336            CallType::CALLCODE,
337            vm.current_call_frame.to,
338            code_address,
339            value,
340            gas_limit,
341            &data,
342        )?;
343
344        // Generic call.
345        vm.generic_call(
346            gas_limit,
347            value,
348            vm.current_call_frame.to,
349            vm.current_call_frame.to,
350            code_address,
351            true,
352            vm.current_call_frame.is_static,
353            data,
354            return_offset,
355            return_len,
356            bytecode,
357            is_delegation_7702,
358            false,
359            Some(address),
360        )
361    }
362}
363
364pub struct OpDelegateCallHandler;
365impl OpcodeHandler for OpDelegateCallHandler {
366    #[inline(always)]
367    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
368        let [
369            gas,
370            address,
371            args_offset,
372            args_len,
373            return_offset,
374            return_len,
375        ] = *vm.current_call_frame.stack.pop()?;
376        let address = word_to_address(address);
377        let (args_len, args_offset) = size_offset_to_usize(args_len, args_offset)?;
378        let (return_len, return_offset) = size_offset_to_usize(return_len, return_offset)?;
379
380        let (new_memory_size, address_was_cold, static_cost) =
381            vm.check_call_static_gas(args_offset, args_len, return_offset, return_len, address, 0)?;
382
383        vm.substate.add_accessed_address(address);
384        // Detect a 7702 delegation without reading the delegate account: per
385        // EELS the delegate access cost is gas-checked first, so an OOG must
386        // not leak the delegate read into execution witnesses (EIP-8025).
387        let (target_code, delegation) =
388            eip7702_peek_delegation(vm.db, &vm.substate, address, vm.env.config.fork)?;
389        let is_delegation_7702 = delegation.is_some();
390        let (eip7702_gas_consumed, code_address) = match delegation {
391            Some((auth_address, access_cost)) => (access_cost, auth_address),
392            None => (0, address),
393        };
394
395        // EIP-8141 mempool validation-trace: the call target must be an existing
396        // account or precompile and not EIP-7702-delegated (sender exempt).
397        if vm.validation_observer.active {
398            vm.validation_check_call_target(address, is_delegation_7702)?;
399        }
400
401        // BAL touches the target before the delegation gas check.
402        vm.record_bal_call_touch(
403            address,
404            code_address,
405            is_delegation_7702,
406            eip7702_gas_consumed,
407            new_memory_size,
408            vm.current_call_frame.memory.len(),
409            address_was_cold,
410            0,
411            0,
412        );
413
414        let bytecode = if let Some((auth_address, access_cost)) = delegation {
415            vm.current_call_frame.check_gas(
416                static_cost
417                    .checked_add(access_cost)
418                    .ok_or(ExceptionalHalt::OutOfGas)?,
419            )?;
420            vm.substate.add_accessed_address(auth_address);
421            Some(vm.db.get_account_code(auth_address)?.clone())
422        } else {
423            target_code
424        };
425
426        #[expect(clippy::as_conversions, reason = "safe")]
427        let gas_left = (vm.current_call_frame.gas_remaining as u64)
428            .checked_sub(eip7702_gas_consumed)
429            .ok_or(ExceptionalHalt::OutOfGas)?;
430        let (gas_cost, gas_limit) = gas_cost::delegatecall(
431            new_memory_size,
432            vm.current_call_frame.memory.len(),
433            address_was_cold,
434            gas,
435            gas_left,
436            vm.env.config.fork,
437        )?;
438        vm.current_call_frame.increase_consumed_gas(
439            gas_cost
440                .checked_add(eip7702_gas_consumed)
441                .ok_or(ExceptionalHalt::OutOfGas)?,
442        )?;
443
444        // Struct-log: geth-compatible DELEGATECALL gasCost (intrinsic + forwarded).
445        if vm.opcode_tracer.active {
446            let geth_cost = gas_cost.saturating_add(eip7702_gas_consumed);
447            vm.opcode_tracer.last_opcode_gas_cost = Some(geth_cost);
448        }
449
450        // Resize memory: this is necessary for multiple reasons:
451        //   - Make sure the memory is expanded.
452        //   - When there is return data, preallocate it because it won't be possible while the next
453        //     call frame is available.
454        vm.current_call_frame.memory.resize(new_memory_size)?;
455
456        // Trace CALL operation.
457        let data = vm.get_calldata(args_offset, args_len)?;
458        // In this trace the `from` is the current contract, we don't want the `from` to be,
459        // for example, the EOA that sent the transaction.
460        vm.tracer.enter(
461            CallType::DELEGATECALL,
462            vm.current_call_frame.to,
463            code_address,
464            vm.current_call_frame.msg_value,
465            gas_limit,
466            &data,
467        )?;
468
469        // Generic call.
470        vm.generic_call(
471            gas_limit,
472            vm.current_call_frame.msg_value,
473            vm.current_call_frame.msg_sender,
474            vm.current_call_frame.to,
475            code_address,
476            false,
477            vm.current_call_frame.is_static,
478            data,
479            return_offset,
480            return_len,
481            bytecode,
482            is_delegation_7702,
483            false,
484            None,
485        )
486    }
487}
488
489pub struct OpStaticCallHandler;
490impl OpcodeHandler for OpStaticCallHandler {
491    #[inline(always)]
492    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
493        let [
494            gas,
495            address,
496            args_offset,
497            args_len,
498            return_offset,
499            return_len,
500        ] = *vm.current_call_frame.stack.pop()?;
501        let address = word_to_address(address);
502        let (args_len, args_offset) = size_offset_to_usize(args_len, args_offset)?;
503        let (return_len, return_offset) = size_offset_to_usize(return_len, return_offset)?;
504
505        let (new_memory_size, address_was_cold, static_cost) =
506            vm.check_call_static_gas(args_offset, args_len, return_offset, return_len, address, 0)?;
507
508        vm.substate.add_accessed_address(address);
509        // Detect a 7702 delegation without reading the delegate account: per
510        // EELS the delegate access cost is gas-checked first, so an OOG must
511        // not leak the delegate read into execution witnesses (EIP-8025).
512        let (target_code, delegation) =
513            eip7702_peek_delegation(vm.db, &vm.substate, address, vm.env.config.fork)?;
514        let is_delegation_7702 = delegation.is_some();
515        let (eip7702_gas_consumed, code_address) = match delegation {
516            Some((auth_address, access_cost)) => (access_cost, auth_address),
517            None => (0, address),
518        };
519
520        // EIP-8141 mempool validation-trace: the call target must be an existing
521        // account or precompile and not EIP-7702-delegated (sender exempt).
522        if vm.validation_observer.active {
523            vm.validation_check_call_target(address, is_delegation_7702)?;
524        }
525
526        // BAL touches the target before the delegation gas check.
527        vm.record_bal_call_touch(
528            address,
529            code_address,
530            is_delegation_7702,
531            eip7702_gas_consumed,
532            new_memory_size,
533            vm.current_call_frame.memory.len(),
534            address_was_cold,
535            0,
536            0,
537        );
538
539        let bytecode = if let Some((auth_address, access_cost)) = delegation {
540            vm.current_call_frame.check_gas(
541                static_cost
542                    .checked_add(access_cost)
543                    .ok_or(ExceptionalHalt::OutOfGas)?,
544            )?;
545            vm.substate.add_accessed_address(auth_address);
546            Some(vm.db.get_account_code(auth_address)?.clone())
547        } else {
548            target_code
549        };
550
551        #[expect(clippy::as_conversions, reason = "safe")]
552        let gas_left = (vm.current_call_frame.gas_remaining as u64)
553            .checked_sub(eip7702_gas_consumed)
554            .ok_or(ExceptionalHalt::OutOfGas)?;
555        let (gas_cost, gas_limit) = gas_cost::staticcall(
556            new_memory_size,
557            vm.current_call_frame.memory.len(),
558            address_was_cold,
559            gas,
560            gas_left,
561            vm.env.config.fork,
562        )?;
563        vm.current_call_frame.increase_consumed_gas(
564            gas_cost
565                .checked_add(eip7702_gas_consumed)
566                .ok_or(ExceptionalHalt::OutOfGas)?,
567        )?;
568
569        // Struct-log: geth-compatible STATICCALL gasCost (intrinsic + forwarded).
570        if vm.opcode_tracer.active {
571            let geth_cost = gas_cost.saturating_add(eip7702_gas_consumed);
572            vm.opcode_tracer.last_opcode_gas_cost = Some(geth_cost);
573        }
574
575        // Resize memory: this is necessary for multiple reasons:
576        //   - Make sure the memory is expanded.
577        //   - When there is return data, preallocate it because it won't be possible while the next
578        //     call frame is active.
579        vm.current_call_frame.memory.resize(new_memory_size)?;
580
581        // Trace CALL operation.
582        let data = vm.get_calldata(args_offset, args_len)?;
583        vm.tracer.enter(
584            CallType::STATICCALL,
585            vm.current_call_frame.to,
586            address,
587            U256::zero(),
588            gas_limit,
589            &data,
590        )?;
591
592        // Generic call.
593        vm.generic_call(
594            gas_limit,
595            U256::zero(),
596            vm.current_call_frame.to,
597            address,
598            address,
599            true,
600            true,
601            data,
602            return_offset,
603            return_len,
604            bytecode,
605            is_delegation_7702,
606            false,
607            None,
608        )
609    }
610}
611
612pub struct OpReturnHandler;
613impl OpcodeHandler for OpReturnHandler {
614    #[inline(always)]
615    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
616        let [offset, len] = *vm.current_call_frame.stack.pop()?;
617        let (len, offset) = size_offset_to_usize(len, offset)?;
618
619        vm.current_call_frame
620            .increase_consumed_gas(gas_cost::exit_opcode(
621                calculate_memory_size(offset, len)?,
622                vm.current_call_frame.memory.len(),
623            )?)?;
624
625        if len != 0 {
626            vm.current_call_frame.output = vm.current_call_frame.memory.load_range(offset, len)?;
627        }
628
629        Ok(OpcodeResult::Halt)
630    }
631}
632
633pub struct OpCreateHandler;
634impl OpcodeHandler for OpCreateHandler {
635    #[inline(always)]
636    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
637        // EIP-8037 (Amsterdam+): is_static check before stack pops and gas charging,
638        // consistent with SSTORE, CALL, and SELFDESTRUCT.
639        if vm.env.config.fork >= Fork::Amsterdam && vm.current_call_frame.is_static {
640            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
641        }
642
643        let [value_in_wei, code_offset, code_len] = *vm.current_call_frame.stack.pop()?;
644        let (code_len, code_offset) = size_offset_to_usize(code_len, code_offset)?;
645
646        let create_gas = gas_cost::create(
647            calculate_memory_size(code_offset, code_len)?,
648            vm.current_call_frame.memory.len(),
649            code_len,
650            vm.env.config.fork,
651        )?;
652        vm.current_call_frame.increase_consumed_gas(create_gas)?;
653
654        // Struct-log: record the opcode-level gas before generic_create charges forwarded gas.
655        if vm.opcode_tracer.active {
656            vm.opcode_tracer.last_opcode_gas_cost = Some(create_gas);
657        }
658
659        // EIP-8141 mempool validation-trace: contract creation is a state write
660        // permitted only inside the deploy frame.
661        if vm.validation_observer.active {
662            vm.validation_check_create();
663        }
664
665        vm.generic_create(value_in_wei, code_offset, code_len, None)
666    }
667}
668
669pub struct OpCreate2Handler;
670impl OpcodeHandler for OpCreate2Handler {
671    #[inline(always)]
672    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
673        // EIP-8037 (Amsterdam+): is_static check before stack pops and gas charging,
674        // consistent with SSTORE, CALL, and SELFDESTRUCT.
675        if vm.env.config.fork >= Fork::Amsterdam && vm.current_call_frame.is_static {
676            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
677        }
678
679        let [value_in_wei, code_offset, code_len, salt] = *vm.current_call_frame.stack.pop()?;
680        let (code_len, code_offset) = size_offset_to_usize(code_len, code_offset)?;
681
682        let create2_gas = gas_cost::create_2(
683            calculate_memory_size(code_offset, code_len)?,
684            vm.current_call_frame.memory.len(),
685            code_len,
686            vm.env.config.fork,
687        )?;
688        vm.current_call_frame.increase_consumed_gas(create2_gas)?;
689
690        // Struct-log: record the opcode-level gas before generic_create charges forwarded gas.
691        if vm.opcode_tracer.active {
692            vm.opcode_tracer.last_opcode_gas_cost = Some(create2_gas);
693        }
694
695        // EIP-8141 mempool validation-trace: contract creation is a state write
696        // permitted only inside the deploy frame.
697        if vm.validation_observer.active {
698            vm.validation_check_create();
699        }
700
701        vm.generic_create(value_in_wei, code_offset, code_len, Some(salt))
702    }
703}
704
705pub struct OpSelfDestructHandler;
706impl OpcodeHandler for OpSelfDestructHandler {
707    #[inline(always)]
708    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
709        if vm.current_call_frame.is_static {
710            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
711        }
712
713        let beneficiary = word_to_address(vm.current_call_frame.stack.pop1()?);
714        let to = vm.current_call_frame.to;
715
716        let target_account_is_cold = vm.substate.add_accessed_address(beneficiary);
717
718        // EELS (Amsterdam) checks the base cost (SELFDESTRUCT + cold access)
719        // BEFORE the beneficiary/self state reads: an OOG here must not leak
720        // those reads into execution witnesses (EIP-8025).
721        if vm.env.config.fork >= Fork::Amsterdam {
722            let base_cost =
723                gas_cost::selfdestruct_base(target_account_is_cold, vm.env.config.fork)?;
724            // Phase 1: Check base cost is available (without charging)
725            #[expect(clippy::as_conversions, reason = "base_cost fits in i64")]
726            if vm.current_call_frame.gas_remaining < (base_cost as i64) {
727                return Err(ExceptionalHalt::OutOfGas.into());
728            }
729        }
730
731        let target_account_is_empty = vm.db.get_account(beneficiary)?.is_empty();
732        let balance = vm.db.get_account(to)?.info.balance;
733
734        // EIP-7928 (Amsterdam): Two-phase gas check for SELFDESTRUCT.
735        // Base cost was checked above before state access; now record BAL
736        // tracking, then charge the full cost including NEW_ACCOUNT. This
737        // ensures the beneficiary is recorded in BAL even when the full
738        // selfdestruct cost (with NEW_ACCOUNT) would cause OOG.
739        if vm.env.config.fork >= Fork::Amsterdam {
740            // State access: record BAL tracking between the two gas phases.
741            // Only the touched addresses (and initial balance) are recorded
742            // here; storage slots are NOT. Per EIP-7928 the BAL records a slot
743            // read only on an actual `get_storage` access (spec state_tracker
744            // `get_storage`), which ethrex already captures on SLOAD/SSTORE via
745            // `record_storage_slot_to_bal`. Recording the whole warm access set
746            // here would inject prewarmed-but-unread (EIP-2930) slots as reads,
747            // diverging the block_access_list_hash from conformant clients.
748            if let Some(recorder) = vm.db.bal_recorder.as_mut() {
749                recorder.record_touched_address(beneficiary);
750                recorder.record_touched_address(to);
751                if balance > U256::zero() {
752                    recorder.set_initial_balance(to, balance);
753                }
754            }
755
756            // Phase 2: Charge the full cost (base only for Amsterdam+; NEW_ACCOUNT moved to state gas)
757            vm.current_call_frame
758                .increase_consumed_gas(gas_cost::selfdestruct(
759                    target_account_is_cold,
760                    target_account_is_empty,
761                    balance,
762                    vm.env.config.fork,
763                )?)?;
764
765            // EIP-8037 (Amsterdam+): charge state gas for new account creation via SELFDESTRUCT
766            if target_account_is_empty && balance > U256::zero() {
767                vm.increase_state_gas(vm.state_gas_new_account)?;
768            }
769        } else {
770            vm.current_call_frame
771                .increase_consumed_gas(gas_cost::selfdestruct(
772                    target_account_is_cold,
773                    target_account_is_empty,
774                    balance,
775                    vm.env.config.fork,
776                )?)?;
777
778            // Record beneficiary and destroyed account for BAL per EIP-7928.
779            // Storage slots are intentionally not recorded here (see the
780            // Amsterdam branch above): reads are captured on actual SLOAD/SSTORE
781            // access, never from the warm access-list set.
782            if let Some(recorder) = vm.db.bal_recorder.as_mut() {
783                recorder.record_touched_address(beneficiary);
784                recorder.record_touched_address(to);
785                if balance > U256::zero() {
786                    recorder.set_initial_balance(to, balance);
787                }
788            }
789        }
790
791        // [EIP-6780] - SELFDESTRUCT only in same transaction from CANCUN
792        if vm.env.config.fork >= Fork::Cancun {
793            // [EIP-8246] (Amsterdam+): a selfdestruct-to-self moves no ETH (balance is
794            // preserved at finalization). Skip the self-transfer so it doesn't fire
795            // spurious BAL balance events that overwrite the recorded initial balance.
796            // For `to != beneficiary` the transfer still runs (balance moves out).
797            if !(vm.env.config.fork >= Fork::Amsterdam && to == beneficiary) {
798                vm.transfer(to, beneficiary, balance)?;
799            }
800
801            // Selfdestruct is executed in the same transaction as the contract was created
802            if vm.substate.is_account_created(&to) {
803                // [EIP-8246] (Amsterdam+): balance is NOT burned; nonce/code/storage are cleared
804                // at finalization while balance is preserved. Pre-Amsterdam (EIP-6780): Ether is
805                // burned when to == beneficiary.
806                if vm.env.config.fork < Fork::Amsterdam {
807                    vm.get_account_mut(to)?.info.balance = U256::zero();
808
809                    // Record balance change to zero for destroyed account in BAL
810                    if let Some(recorder) = vm.db.bal_recorder.as_mut() {
811                        recorder.record_balance_change(to, U256::zero());
812                    }
813                }
814
815                vm.substate.add_selfdestruct(to);
816            }
817
818            // EIP-7708 / traceTransfers: emit appropriate log for ETH movement.
819            // EIP-8246 (Amsterdam+): no burn log for same-tx selfdestruct-to-self, since
820            // the balance is preserved rather than burned, and no consensus log for
821            // to == beneficiary (trace mode includes it).
822            vm.add_eth_transfer_logs(to, beneficiary, balance);
823        } else {
824            vm.increase_account_balance(beneficiary, balance)?;
825            vm.get_account_mut(to)?.info.balance = U256::zero();
826
827            // Record balance change to zero for destroyed account in BAL
828            if let Some(recorder) = vm.db.bal_recorder.as_mut() {
829                recorder.record_balance_change(to, U256::zero());
830            }
831
832            vm.substate.add_selfdestruct(to);
833
834            // traceTransfers: pre-Cancun selfdestructs move the balance too.
835            vm.add_eth_transfer_logs(to, beneficiary, balance);
836        }
837
838        vm.tracer.enter(
839            CallType::SELFDESTRUCT,
840            vm.current_call_frame.to,
841            beneficiary,
842            balance,
843            0,
844            &Default::default(),
845        )?;
846        vm.tracer.exit_early(0, None)?;
847
848        Ok(OpcodeResult::Halt)
849    }
850}
851
852pub struct OpRevertHandler;
853impl OpcodeHandler for OpRevertHandler {
854    #[inline(always)]
855    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
856        let [offset, len] = *vm.current_call_frame.stack.pop()?;
857        let (len, offset) = size_offset_to_usize(len, offset)?;
858
859        vm.current_call_frame
860            .increase_consumed_gas(gas_cost::exit_opcode(
861                calculate_memory_size(offset, len)?,
862                vm.current_call_frame.memory.len(),
863            )?)?;
864
865        if len != 0 {
866            vm.current_call_frame.output = vm.current_call_frame.memory.load_range(offset, len)?;
867        }
868
869        Err(VMError::RevertOpcode)
870    }
871}
872
873impl<'a> VM<'a> {
874    /// Common behavior for CREATE and CREATE2 opcodes
875    pub fn generic_create(
876        &mut self,
877        value: U256,
878        code_offset_in_memory: usize,
879        code_size_in_memory: usize,
880        salt: Option<U256>,
881    ) -> Result<OpcodeResult, VMError> {
882        // The initcode is copied into a reused buffer, which moves into the child frame's code
883        // when the CREATE starts one. On every other exit, an error included, it goes back to
884        // the pool here: a buffer dropped instead is never reclaimed by a bump allocator.
885        let mut initcode = self.initcode_pool.pop().unwrap_or_default();
886        let result = self.create_with_initcode_buffer(
887            &mut initcode,
888            value,
889            code_offset_in_memory,
890            code_size_in_memory,
891            salt,
892        );
893        self.pool_initcode(initcode);
894        result
895    }
896
897    /// [`VM::generic_create`] with `initcode`, a buffer to copy the initcode into. It is taken,
898    /// leaving an empty one with no allocation, only when the child frame starts.
899    fn create_with_initcode_buffer(
900        &mut self,
901        initcode: &mut InitcodeBuffer,
902        value: U256,
903        code_offset_in_memory: usize,
904        code_size_in_memory: usize,
905        salt: Option<U256>,
906    ) -> Result<OpcodeResult, VMError> {
907        // [EIP-3860] / [EIP-7954] - Cant exceed init code max size
908        let init_code_max = if self.env.config.fork >= Fork::Amsterdam {
909            AMSTERDAM_INIT_CODE_MAX_SIZE
910        } else {
911            INIT_CODE_MAX_SIZE
912        };
913        if code_size_in_memory > init_code_max && self.env.config.fork >= Fork::Shanghai {
914            return Err(ExceptionalHalt::OutOfGas.into());
915        }
916
917        let current_call_frame = &mut self.current_call_frame;
918
919        // Pre-Amsterdam: is_static check happens here, before gas reservation
920        if self.env.config.fork < Fork::Amsterdam && current_call_frame.is_static {
921            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
922        }
923
924        // Clear callframe subreturn data
925        current_call_frame.sub_return_data = Bytes::new();
926
927        // Copy the initcode out of memory, once, into the reused buffer.
928        self.current_call_frame.memory.with_range(
929            code_offset_in_memory,
930            code_size_in_memory,
931            |code| initcode.set(code),
932        )?;
933
934        // Get account info of deployer
935        let deployer = self.current_call_frame.to;
936        let (deployer_balance, deployer_nonce) = {
937            let deployer_account = self.db.get_account(deployer)?;
938            (deployer_account.info.balance, deployer_account.info.nonce)
939        };
940
941        // Calculate create address
942        let new_address = match salt {
943            Some(salt) => calculate_create2_address(deployer, initcode.initcode(), salt)?,
944            None => calculate_create_address(deployer, deployer_nonce),
945        };
946
947        let call_type = match salt {
948            Some(_) => CallType::CREATE2,
949            None => CallType::CREATE,
950        };
951
952        let new_depth = self
953            .current_call_frame
954            .depth
955            .checked_add(1)
956            .ok_or(InternalError::Overflow)?;
957
958        // Validations that push 0 (FAIL) to the stack. Per EELS `generic_create`
959        // these run BEFORE the target address is accessed
960        // (`accessed_addresses.add` / `is_account_alive`) and BEFORE the
961        // NEW_ACCOUNT state-gas charge, so no account is touched and no gas is
962        // reserved or charged on this early exit (EELS `push(0); return`).
963        // 1. Sender doesn't have enough balance to send value.
964        // 2. Depth limit has been reached
965        // 3. Sender nonce is max.
966        let checks = [
967            (deployer_balance < value, "OutOfFund"),
968            (new_depth > 1024, "MaxDepth"),
969            (deployer_nonce == u64::MAX, "MaxNonce"),
970        ];
971        for (condition, reason) in checks {
972            if condition {
973                // Child gas preview for the tracer only; no gas is reserved on this
974                // path (mirrors EELS `push(0); return`).
975                let preview_gas = gas_cost::max_message_call_gas(&self.current_call_frame)?;
976                if self.tracer.active {
977                    self.tracer.enter(
978                        call_type,
979                        deployer,
980                        new_address,
981                        value,
982                        preview_gas,
983                        &Bytes::copy_from_slice(initcode.initcode()).into(),
984                    )?;
985                }
986                self.current_call_frame.stack.push(FAIL)?;
987                self.tracer.exit_early(0, Some(reason.to_string()))?;
988                return Ok(OpcodeResult::Continue);
989            }
990        }
991
992        // Add new contract to accessed addresses (after early checks pass, per reference)
993        self.substate.add_accessed_address(new_address);
994
995        // Record address touch for BAL (after early checks pass per EIP-7928 reference).
996        // EELS records the target via `is_account_alive(contract_address)` in
997        // `generic_create` BEFORE charging the NEW_ACCOUNT state gas, so the target
998        // stays listed as accessed in the BAL even when the state-gas charge OOGs.
999        if let Some(recorder) = self.db.bal_recorder.as_mut() {
1000            recorder.record_touched_address(new_address);
1001        }
1002
1003        // EIP-8037 (#3002): read the create target BEFORE charging, mirroring EELS
1004        // `generic_create` `new_account_charged = not is_account_alive(contract_address)`
1005        // (evaluated just before `charge_state_gas`). Reading it here also records the
1006        // target access into `accessed_accounts` for the BAL pure-access checklist.
1007        // `is_account_alive` == exists && non-empty; a nonexistent target reads as an
1008        // empty account, so `!is_empty()` is exactly `is_account_alive`.
1009        let target_alive = !self.get_account_mut(new_address)?.is_empty();
1010
1011        // EIP-8037 (Amsterdam+): charge the NEW_ACCOUNT state gas only when the
1012        // target leaf does not yet exist (`new_account_charged = !target_alive`).
1013        // Charging conditionally — rather than the previous charge-then-refund —
1014        // keeps `gas_left` untouched for an alive/colliding target, so the child-gas
1015        // split below matches EELS on a spilling reservoir (EELS never charges, hence
1016        // never spills, for an alive target). The charge follows the target read and
1017        // the BAL record, so an OOG here still leaves the target in the access set,
1018        // and — since it precedes the child-gas reservation below — its spill into
1019        // `gas_left` is reflected by `max_message_call_gas`.
1020        if self.env.config.fork >= Fork::Amsterdam && !target_alive {
1021            self.increase_state_gas(self.state_gas_new_account)?;
1022        }
1023
1024        // Reserve gas for subcall (EELS `max_message_call_gas` after `charge_state_gas`).
1025        let gas_limit = gas_cost::max_message_call_gas(&self.current_call_frame)?;
1026        self.current_call_frame.increase_consumed_gas(gas_limit)?;
1027
1028        // Log CREATE in tracer (success path) with the reserved child gas.
1029        if self.tracer.active {
1030            self.tracer.enter(
1031                call_type,
1032                deployer,
1033                new_address,
1034                value,
1035                gas_limit,
1036                &Bytes::copy_from_slice(initcode.initcode()).into(),
1037            )?;
1038        }
1039
1040        // Increment sender nonce (irreversible change)
1041        self.increment_account_nonce(deployer)?;
1042
1043        // Deployment will fail (consuming all gas) if the contract already exists.
1044        let new_account = self.get_account_mut(new_address)?;
1045        if new_account.create_would_collide() {
1046            // Per EELS: on collision, regular gas stays consumed (not returned).
1047            // The NEW_ACCOUNT state gas is refunded only if it was charged (target
1048            // not alive) — EELS `if new_account_charged: credit_state_gas_refund`.
1049            if self.env.config.fork >= Fork::Amsterdam && !target_alive {
1050                self.credit_state_gas_refund(self.state_gas_new_account)?;
1051            }
1052            self.current_call_frame.stack.push(FAIL)?;
1053            self.tracer
1054                .exit_early(gas_limit, Some("CreateAccExists".to_string()))?;
1055            return Ok(OpcodeResult::Continue);
1056        }
1057
1058        // Create BAL checkpoint before entering create call for potential revert per EIP-7928
1059        let bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1060
1061        let mut stack = self.stack_pool.pop().unwrap_or_default();
1062        stack.clear();
1063
1064        let next_memory = self.current_call_frame.memory.next_memory();
1065
1066        let mut new_call_frame = CallFrame::new(
1067            deployer,
1068            new_address,
1069            new_address,
1070            Code::from_initcode_buffer(mem::take(initcode)),
1071            value,
1072            CallData::default(),
1073            false,
1074            gas_limit,
1075            new_depth,
1076            true,
1077            true,
1078            0,
1079            0,
1080            stack,
1081            next_memory,
1082        );
1083        // Store BAL checkpoint in the call frame's backup for restoration on revert
1084        new_call_frame.call_frame_backup.bal_checkpoint = bal_checkpoint;
1085        // Snapshot AFTER the CREATE account state-gas charge has landed in
1086        // `vm.state_gas_used`, so the revert restore in `handle_return_create`
1087        // keeps the parent's pre-CREATE intrinsic without re-refunding it.
1088        new_call_frame.state_gas_used_at_entry = self.state_gas_used;
1089        // EIP-8037 (#3002): thread the pre-mutation target-alive flag to the
1090        // success arm of `handle_return_create`.
1091        new_call_frame.target_alive = target_alive;
1092
1093        self.add_callframe(new_call_frame);
1094
1095        // Changes that revert in case the Create fails.
1096        self.increment_account_nonce(new_address)?; // 0 -> 1
1097        self.transfer(deployer, new_address, value)?;
1098
1099        self.substate.push_backup();
1100        self.substate.add_created_account(new_address); // Mostly for SELFDESTRUCT during initcode.
1101
1102        // EIP-7708 / traceTransfers: emit transfer log for nonzero-value CREATE/CREATE2
1103        // Must be after push_backup() so the log reverts if the child context reverts
1104        self.add_eth_transfer_logs(deployer, new_address, value);
1105
1106        Ok(OpcodeResult::Continue)
1107    }
1108
1109    /// Static gas prelude for CALL/CALLCODE/DELEGATECALL/STATICCALL: compute
1110    /// `(new_memory_size, address_was_cold, static_cost)` and `check_gas` it
1111    /// before any state read, mirroring EELS' `# check static gas before state
1112    /// access`. `value_cost` is the per-opcode positive-value cost (0 when
1113    /// none).
1114    fn check_call_static_gas(
1115        &mut self,
1116        args_offset: usize,
1117        args_len: usize,
1118        return_offset: usize,
1119        return_len: usize,
1120        address: Address,
1121        value_cost: u64,
1122    ) -> Result<(usize, bool, u64), VMError> {
1123        let new_memory_size = calculate_memory_size(args_offset, args_len)?
1124            .max(calculate_memory_size(return_offset, return_len)?);
1125        let address_was_cold = !self.substate.is_address_accessed(&address);
1126        let memory_expansion_cost =
1127            memory::expansion_cost(new_memory_size, self.current_call_frame.memory.len())?;
1128        let access_gas_cost = if address_was_cold {
1129            gas_cost::cold_account_access_cost(self.env.config.fork)
1130        } else {
1131            gas_cost::WARM_ADDRESS_ACCESS_COST
1132        };
1133        let static_cost = memory_expansion_cost
1134            .checked_add(access_gas_cost)
1135            .ok_or(ExceptionalHalt::OutOfGas)?
1136            .checked_add(value_cost)
1137            .ok_or(ExceptionalHalt::OutOfGas)?;
1138        self.current_call_frame.check_gas(static_cost)?;
1139        Ok((new_memory_size, address_was_cold, static_cost))
1140    }
1141
1142    /// Record BAL touched addresses for CALL-family opcodes per EIP-7928.
1143    /// Gated on intermediate gas checks matching the EELS reference.
1144    #[expect(
1145        clippy::too_many_arguments,
1146        reason = "matches EIP-7928 EELS reference parameters"
1147    )]
1148    fn record_bal_call_touch(
1149        &mut self,
1150        target: Address,
1151        code_address: Address,
1152        is_delegation_7702: bool,
1153        eip7702_gas_consumed: u64,
1154        new_memory_size: usize,
1155        current_memory_size: usize,
1156        address_was_cold: bool,
1157        value_cost: u64,
1158        create_cost: u64,
1159    ) {
1160        let Some(recorder) = self.db.bal_recorder.as_mut() else {
1161            return;
1162        };
1163        // Safe: expansion_cost only fails on usize→u64 overflow, which is infallible
1164        // (usize ≤ 64 bits). If it somehow did, u64::MAX makes the gas check fail
1165        // conservatively, skipping the BAL touch — a non-consensus recording path.
1166        let mem_cost =
1167            memory::expansion_cost(new_memory_size, current_memory_size).unwrap_or(u64::MAX);
1168        let access_cost = if address_was_cold {
1169            gas_cost::cold_account_access_cost(self.env.config.fork)
1170        } else {
1171            gas_cost::WARM_ADDRESS_ACCESS_COST
1172        };
1173        let basic_cost = mem_cost
1174            .saturating_add(access_cost)
1175            .saturating_add(value_cost);
1176        let gas_remaining = self.current_call_frame.gas_remaining;
1177
1178        if gas_remaining >= i64::try_from(basic_cost).unwrap_or(i64::MAX) {
1179            recorder.record_touched_address(target);
1180
1181            if is_delegation_7702 {
1182                let delegation_check = basic_cost
1183                    .saturating_add(create_cost)
1184                    .saturating_add(eip7702_gas_consumed);
1185                if gas_remaining >= i64::try_from(delegation_check).unwrap_or(i64::MAX) {
1186                    recorder.record_touched_address(code_address);
1187                }
1188            }
1189        }
1190    }
1191
1192    /// This (should) be the only function where gas is used as a
1193    /// U256. This is because we have to use the values that are
1194    /// pushed to the stack.
1195    ///
1196    /// `callcode_target` is `Some` only when the caller is [`OpCallCodeHandler`], and
1197    /// carries the raw address CALLCODE was given. The call kind cannot be inferred from
1198    /// the other arguments: `to == msg_sender && code_address != to` also holds for a CALL
1199    /// to a 7702-delegated self, and fails to hold for a CALLCODE whose target delegates.
1200    /// Only the traceTransfers log reads it; see [`VM::add_call_eth_transfer_logs`].
1201    ///
1202    // Force inline, due to lot of arguments, inlining must be forced, and it is actually beneficial
1203    // because passing so much data is costly. Verified with samply.
1204    #[expect(
1205        clippy::too_many_arguments,
1206        reason = "inlined for performance, many args needed"
1207    )]
1208    #[inline(always)]
1209    pub fn generic_call(
1210        &mut self,
1211        gas_limit: u64,
1212        value: U256,
1213        msg_sender: Address,
1214        to: Address,
1215        code_address: Address,
1216        should_transfer_value: bool,
1217        is_static: bool,
1218        calldata: CallData,
1219        ret_offset: usize,
1220        ret_size: usize,
1221        bytecode: Option<Code>,
1222        is_delegation_7702: bool,
1223        new_account_charged: bool,
1224        callcode_target: Option<Address>,
1225    ) -> Result<OpcodeResult, VMError> {
1226        // Clear callframe subreturn data
1227        self.current_call_frame.sub_return_data.clear();
1228
1229        // Validate sender has enough value
1230        if should_transfer_value && !value.is_zero() {
1231            let sender_balance = self.db.get_account(msg_sender)?.info.balance;
1232            if sender_balance < value {
1233                // EIP-8037: no account is created, refund the new-account state gas.
1234                self.refund_new_account_state_gas(new_account_charged)?;
1235                self.early_revert_message_call(gas_limit, "OutOfFund".to_string())?;
1236                return Ok(OpcodeResult::Continue);
1237            }
1238        }
1239
1240        // Validate max depth has not been reached yet.
1241        let new_depth = self
1242            .current_call_frame
1243            .depth
1244            .checked_add(1)
1245            .ok_or(InternalError::Overflow)?;
1246        if new_depth > 1024 {
1247            self.refund_new_account_state_gas(new_account_charged)?;
1248            self.early_revert_message_call(gas_limit, "MaxDepth".to_string())?;
1249            return Ok(OpcodeResult::Continue);
1250        }
1251
1252        if self.address_is_precompile(&code_address) && !is_delegation_7702 {
1253            // Record precompile address touch for BAL per EIP-7928
1254            if let Some(recorder) = self.db.bal_recorder.as_mut() {
1255                recorder.record_touched_address(code_address);
1256            }
1257
1258            let mut gas_remaining = gas_limit;
1259            // The precompile reads the arguments in place in the caller's memory.
1260            let mut ctx_result =
1261                self.execute_precompile(code_address, &calldata, gas_limit, &mut gas_remaining)?;
1262
1263            let call_frame = &mut self.current_call_frame;
1264
1265            // Return gas left from subcontext
1266            #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
1267            if ctx_result.is_success() {
1268                call_frame.gas_remaining = (call_frame.gas_remaining as u64)
1269                    .checked_add(
1270                        gas_limit
1271                            .checked_sub(ctx_result.gas_used)
1272                            .ok_or(InternalError::Underflow)?,
1273                    )
1274                    .ok_or(InternalError::Overflow)?
1275                    as i64;
1276            }
1277
1278            // Store return data of sub-context
1279            call_frame.memory.store_data(
1280                ret_offset,
1281                if ctx_result.output.len() >= ret_size {
1282                    ctx_result
1283                        .output
1284                        .get(..ret_size)
1285                        .ok_or(ExceptionalHalt::OutOfBounds)?
1286                } else {
1287                    &ctx_result.output
1288                },
1289            )?;
1290            // Move the output into the return-data buffer instead of cloning it:
1291            // a `Vec`-backed `Bytes` allocates a shared header on its first clone.
1292            // Only an active call tracer reads the output again, in `exit_context`.
1293            call_frame.sub_return_data = if self.tracer.active {
1294                ctx_result.output.clone()
1295            } else {
1296                std::mem::take(&mut ctx_result.output)
1297            };
1298
1299            // What to do, depending on TxResult
1300            call_frame.stack.push(match &ctx_result.result {
1301                TxResult::Success => SUCCESS,
1302                TxResult::Revert(_) => FAIL,
1303            })?;
1304
1305            // EIP-8037: a failed precompile call transfers no value, so no account is
1306            // created — refund the new-account state gas (EELS `generic_call`
1307            // `credit_state_gas_refund(NEW_ACCOUNT)` on child error).
1308            self.refund_new_account_state_gas(new_account_charged && !ctx_result.is_success())?;
1309
1310            // Transfer value from caller to callee.
1311            if should_transfer_value && ctx_result.is_success() {
1312                self.transfer(msg_sender, to, value)?;
1313
1314                // EIP-7708 / traceTransfers: emit transfer logs for a nonzero-value call.
1315                self.add_call_eth_transfer_logs(msg_sender, to, callcode_target, value);
1316            }
1317
1318            self.tracer.exit_context(&ctx_result, false)?;
1319        } else {
1320            // Create BAL checkpoint before entering nested call for potential revert per EIP-7928
1321            let bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1322
1323            let mut stack = self.stack_pool.pop().unwrap_or_default();
1324            stack.clear();
1325
1326            let next_memory = self.current_call_frame.memory.next_memory();
1327
1328            let mut new_call_frame = CallFrame::new(
1329                msg_sender,
1330                to,
1331                code_address,
1332                bytecode.unwrap_or_default(),
1333                value,
1334                calldata,
1335                is_static,
1336                gas_limit,
1337                new_depth,
1338                should_transfer_value,
1339                false,
1340                ret_offset,
1341                ret_size,
1342                stack,
1343                next_memory,
1344            );
1345            // Store BAL checkpoint in the call frame's backup for restoration on revert
1346            new_call_frame.call_frame_backup.bal_checkpoint = bal_checkpoint;
1347            new_call_frame.state_gas_used_at_entry = self.state_gas_used;
1348            new_call_frame.new_account_state_gas_charged = new_account_charged;
1349
1350            self.add_callframe(new_call_frame);
1351
1352            // Transfer value from caller to callee.
1353            if should_transfer_value {
1354                self.transfer(msg_sender, to, value)?;
1355            }
1356
1357            self.substate.push_backup();
1358
1359            // EIP-7708 / traceTransfers: emit transfer logs for a nonzero-value call.
1360            // Must be after push_backup() so they revert if the child context reverts.
1361            if should_transfer_value {
1362                self.add_call_eth_transfer_logs(msg_sender, to, callcode_target, value);
1363            }
1364        }
1365
1366        Ok(OpcodeResult::Continue)
1367    }
1368
1369    /// Pop backup from stack and restore substate and cache if transaction reverted.
1370    ///
1371    /// `consume_backup` lets the caller move the frame's backup out (no clone) on the
1372    /// revert path when nothing reads it afterward; see [`VM::restore_cache_state_consuming`].
1373    /// The top-level call passes `true` for normal L1 execution and `false` when a
1374    /// `BackupHook` is installed (L2 / stateless), since that hook reads the backup in
1375    /// `finalize_execution` (gated on `VM::preserve_top_level_backup`).
1376    pub fn handle_state_backup(
1377        &mut self,
1378        ctx_result: &ContextResult,
1379        consume_backup: bool,
1380    ) -> Result<(), VMError> {
1381        if ctx_result.is_success() {
1382            self.substate.commit_backup();
1383        } else {
1384            self.substate.revert_backup();
1385            if consume_backup {
1386                self.restore_cache_state_consuming()?;
1387            } else {
1388                self.restore_cache_state()?;
1389            }
1390        }
1391
1392        Ok(())
1393    }
1394
1395    /// Handles case in which callframe was initiated by another callframe (with CALL or CREATE family opcodes)
1396    ///
1397    /// Returns the pc increment.
1398    pub fn handle_return(&mut self, ctx_result: &ContextResult) -> Result<(), VMError> {
1399        // The frame is popped immediately below and its backup is not read again on
1400        // the revert path, so move it out instead of cloning.
1401        self.handle_state_backup(ctx_result, true)?;
1402        let executed_call_frame = self.pop_call_frame()?;
1403
1404        // Here happens the interaction between child (executed) and parent (caller) callframe.
1405        if executed_call_frame.is_create {
1406            self.handle_return_create(executed_call_frame, ctx_result)?;
1407        } else {
1408            self.handle_return_call(executed_call_frame, ctx_result)?;
1409        }
1410
1411        Ok(())
1412    }
1413
1414    #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
1415    pub fn handle_return_call(
1416        &mut self,
1417        executed_call_frame: CallFrame,
1418        ctx_result: &ContextResult,
1419    ) -> Result<(), VMError> {
1420        let CallFrame {
1421            gas_limit,
1422            ret_offset,
1423            ret_size,
1424            memory: old_callframe_memory,
1425            frame_state_gas_spilled: child_frame_state_gas_spilled,
1426            call_frame_backup,
1427            stack,
1428            new_account_state_gas_charged,
1429            ..
1430        } = executed_call_frame;
1431
1432        #[cfg(not(target_arch = "riscv64"))]
1433        old_callframe_memory.clean_from_base();
1434
1435        #[cfg(target_arch = "riscv64")]
1436        old_callframe_memory.truncate_to_base();
1437
1438        let parent_call_frame = &mut self.current_call_frame;
1439
1440        // Return gas left from subcontext
1441        let child_unused_gas = gas_limit
1442            .checked_sub(ctx_result.gas_used)
1443            .ok_or(InternalError::Underflow)?;
1444        parent_call_frame.gas_remaining = parent_call_frame
1445            .gas_remaining
1446            .checked_add(child_unused_gas as i64)
1447            .ok_or(InternalError::Overflow)?;
1448
1449        // Store return data of sub-context
1450        parent_call_frame.memory.store_data(
1451            ret_offset,
1452            if ctx_result.output.len() >= ret_size {
1453                ctx_result
1454                    .output
1455                    .get(..ret_size)
1456                    .ok_or(ExceptionalHalt::OutOfBounds)?
1457            } else {
1458                &ctx_result.output
1459            },
1460        )?;
1461
1462        parent_call_frame.sub_return_data = ctx_result.output.clone();
1463
1464        // What to do, depending on TxResult
1465        match &ctx_result.result {
1466            TxResult::Success => {
1467                self.current_call_frame.stack.push(SUCCESS)?;
1468                self.merge_call_frame_backup_with_parent(&call_frame_backup)?;
1469                // EIP-8037: on success, child's state_gas_used is already
1470                // accumulated into the VM-level field (signed sum handles refunds).
1471                // No pending flush needed — credits were applied inline.
1472                // Propagate the child's per-frame spill to the parent so a later
1473                // parent revert/halt refills it LIFO (EELS `incorporate_child_on_success`).
1474                self.current_call_frame.frame_state_gas_spilled = self
1475                    .current_call_frame
1476                    .frame_state_gas_spilled
1477                    .checked_add(child_frame_state_gas_spilled)
1478                    .ok_or(InternalError::Overflow)?;
1479                // EIP-8037 (execution-specs#3478): with the child's gas merged in, the
1480                // reservoir repays whatever spill is still outstanding in this frame —
1481                // EELS calls `repay_state_gas_spill` here, on the success arm only.
1482                if self.env.config.fork >= Fork::Amsterdam {
1483                    self.repay_state_gas_spill()?;
1484                }
1485            }
1486            TxResult::Revert(_) => {
1487                // EIP-8037: the child already self-refilled its execution state gas via
1488                // `refill_frame_state_gas` in `handle_opcode_error`. The parent-charged
1489                // new-account state gas (value transfer to an empty account) is separate
1490                // and refunded here on child failure, mirroring EELS `generic_call`
1491                // `credit_state_gas_refund(NEW_ACCOUNT)`.
1492                self.refund_new_account_state_gas(new_account_state_gas_charged)?;
1493                self.current_call_frame.stack.push(FAIL)?;
1494            }
1495        };
1496
1497        self.tracer.exit_context(ctx_result, false)?;
1498
1499        let mut stack = stack;
1500        stack.clear();
1501        self.stack_pool.push(stack);
1502
1503        Ok(())
1504    }
1505
1506    #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
1507    pub fn handle_return_create(
1508        &mut self,
1509        executed_call_frame: CallFrame,
1510        ctx_result: &ContextResult,
1511    ) -> Result<(), VMError> {
1512        let CallFrame {
1513            gas_limit,
1514            to,
1515            call_frame_backup,
1516            memory: old_callframe_memory,
1517            frame_state_gas_spilled: child_frame_state_gas_spilled,
1518            target_alive,
1519            stack,
1520            bytecode,
1521            ..
1522        } = executed_call_frame;
1523
1524        #[cfg(not(target_arch = "riscv64"))]
1525        old_callframe_memory.clean_from_base();
1526
1527        #[cfg(target_arch = "riscv64")]
1528        old_callframe_memory.truncate_to_base();
1529
1530        // Return unused gas
1531        let unused_gas = gas_limit
1532            .checked_sub(ctx_result.gas_used)
1533            .ok_or(InternalError::Underflow)?;
1534        self.current_call_frame.gas_remaining = self
1535            .current_call_frame
1536            .gas_remaining
1537            .checked_add(unused_gas as i64)
1538            .ok_or(InternalError::Overflow)?;
1539
1540        // What to do, depending on TxResult
1541        match ctx_result.result.clone() {
1542            TxResult::Success => {
1543                self.current_call_frame.stack.push(address_to_word(to))?;
1544                self.merge_call_frame_backup_with_parent(&call_frame_backup)?;
1545                // EIP-8037: on success, child's state_gas_used is already
1546                // accumulated into the VM-level field (signed sum handles refunds).
1547                // No pending flush needed — credits were applied inline.
1548                // Propagate the child's per-frame spill to the parent so a later
1549                // parent revert/halt refills it LIFO (EELS `incorporate_child_on_success`).
1550                self.current_call_frame.frame_state_gas_spilled = self
1551                    .current_call_frame
1552                    .frame_state_gas_spilled
1553                    .checked_add(child_frame_state_gas_spilled)
1554                    .ok_or(InternalError::Overflow)?;
1555                // EIP-8037 (execution-specs#3478): with the child's gas merged in, the
1556                // reservoir repays whatever spill is still outstanding in this frame —
1557                // EELS calls `repay_state_gas_spill` here, on the success arm only.
1558                if self.env.config.fork >= Fork::Amsterdam {
1559                    self.repay_state_gas_spill()?;
1560                }
1561                // EIP-8037 (#3002): the parent charged the NEW_ACCOUNT state gas only
1562                // when the target was NOT alive (`new_account_charged = !target_alive`),
1563                // exactly as EELS `generic_create`. On child success EELS does not
1564                // refund it (`incorporate_child_on_success` keeps the charge — a new
1565                // account leaf was created), and when the target was alive nothing was
1566                // charged, so there is nothing to refund here in either case.
1567            }
1568            TxResult::Revert(err) => {
1569                // EIP-8037: the child already self-refilled its state gas via
1570                // `refill_frame_state_gas` in `handle_opcode_error`, so no parent-side
1571                // state-gas reabsorption is needed here.
1572
1573                // EIP-8037: CREATE's account state gas was charged in the parent
1574                // before the child frame began ONLY when the target was not alive
1575                // (`new_account_charged = !target_alive`). On child error EELS refunds
1576                // it only in that case: `if new_account_charged: credit_state_gas_refund`.
1577                if self.env.config.fork >= Fork::Amsterdam && !target_alive {
1578                    self.credit_state_gas_refund(self.state_gas_new_account)?;
1579                }
1580
1581                // Return data is only propagated on REVERT opcode, not on ExceptionalHalt.
1582                if err.is_revert_opcode() {
1583                    self.current_call_frame.sub_return_data = ctx_result.output.clone();
1584                }
1585
1586                self.current_call_frame.stack.push(FAIL)?;
1587            }
1588        };
1589
1590        self.tracer.exit_context(ctx_result, false)?;
1591
1592        let mut stack = stack;
1593        stack.clear();
1594        self.stack_pool.push(stack);
1595        self.recycle_initcode(bytecode);
1596
1597        Ok(())
1598    }
1599
1600    /// A call's arguments, read in place in the caller's memory rather than copied.
1601    fn get_calldata(&mut self, offset: usize, size: usize) -> Result<CallData, VMError> {
1602        self.current_call_frame.memory.calldata_view(offset, size)
1603    }
1604
1605    /// Returns a finished CREATE frame's initcode buffers to the pool, except those something
1606    /// still references.
1607    fn recycle_initcode(&mut self, code: Code) {
1608        self.pool_initcode(code.into_initcode_buffer());
1609    }
1610
1611    /// Keeps `buffer` for the next CREATE, emptied, so no CREATE can build another one's
1612    /// initcode from the pool. A buffer holding no allocation is not worth keeping.
1613    fn pool_initcode(&mut self, mut buffer: InitcodeBuffer) {
1614        if buffer.is_allocated() {
1615            buffer.clear();
1616            self.initcode_pool.push(buffer);
1617        }
1618    }
1619
1620    #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
1621    fn early_revert_message_call(&mut self, gas_limit: u64, reason: String) -> Result<(), VMError> {
1622        let callframe = &mut self.current_call_frame;
1623
1624        // Return gas_limit to callframe.
1625        callframe.gas_remaining = callframe
1626            .gas_remaining
1627            .checked_add(gas_limit as i64)
1628            .ok_or(InternalError::Overflow)?;
1629        callframe.stack.push(FAIL)?; // It's the same as revert for CREATE
1630
1631        self.tracer.exit_early(0, Some(reason))?;
1632        Ok(())
1633    }
1634}