Skip to main content

revm_handler/
frame.rs

1use crate::{
2    evm::FrameTr, item_or_result::FrameInitOrResult, precompile_provider::PrecompileProvider,
3    CallFrame, CreateFrame, FrameData, FrameResult, ItemOrResult,
4};
5use context::result::FromStringError;
6use context_interface::{
7    context::{take_error, ContextError},
8    journaled_state::{account::JournaledAccountTr, JournalCheckpoint, JournalTr},
9    local::{FrameToken, OutFrame},
10    Cfg, ContextTr, Database,
11};
12use core::cmp::min;
13use derive_where::derive_where;
14use interpreter::{
15    interpreter::{EthInterpreter, ExtBytecode},
16    interpreter_action::FrameInit,
17    interpreter_types::ReturnData,
18    CallInput, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, CreateScheme,
19    FrameInput, Gas, GasTracker, InputsImpl, InstructionResult, Interpreter, InterpreterAction,
20    InterpreterResult, InterpreterTypes, SharedMemory,
21};
22use primitives::{
23    constants::CALL_STACK_LIMIT,
24    hardfork::SpecId::{self, HOMESTEAD, LONDON, SPURIOUS_DRAGON},
25    Address, Bytes, U256,
26};
27use state::Bytecode;
28use std::{borrow::ToOwned, boxed::Box, vec::Vec};
29
30/// Frame implementation for Ethereum.
31#[derive_where(Clone, Debug; IW,
32    <IW as InterpreterTypes>::Stack,
33    <IW as InterpreterTypes>::Memory,
34    <IW as InterpreterTypes>::Bytecode,
35    <IW as InterpreterTypes>::ReturnData,
36    <IW as InterpreterTypes>::Input,
37    <IW as InterpreterTypes>::RuntimeFlag,
38    <IW as InterpreterTypes>::Extend,
39)]
40pub struct EthFrame<IW: InterpreterTypes = EthInterpreter> {
41    /// Frame-specific data (Call, Create, or EOFCreate).
42    pub data: FrameData,
43    /// Input data for the frame.
44    pub input: FrameInput,
45    /// Current call depth in the execution stack.
46    pub depth: usize,
47    /// Journal checkpoint for state reversion.
48    pub checkpoint: JournalCheckpoint,
49    /// Interpreter instance for executing bytecode.
50    pub interpreter: Interpreter<IW>,
51    /// Whether the frame has been finished its execution.
52    /// Frame is considered finished if it has been called and returned a result.
53    pub is_finished: bool,
54}
55
56impl<IT: InterpreterTypes> FrameTr for EthFrame<IT> {
57    type FrameResult = FrameResult;
58    type FrameInit = FrameInit;
59}
60
61impl Default for EthFrame<EthInterpreter> {
62    fn default() -> Self {
63        Self::do_default(Interpreter::default())
64    }
65}
66
67impl EthFrame<EthInterpreter> {
68    /// Creates an new invalid [`EthFrame`].
69    pub fn invalid() -> Self {
70        Self::do_default(Interpreter::invalid())
71    }
72
73    fn do_default(interpreter: Interpreter<EthInterpreter>) -> Self {
74        Self {
75            data: FrameData::Call(CallFrame {
76                return_memory_range: 0..0,
77            }),
78            input: FrameInput::Empty,
79            depth: 0,
80            checkpoint: JournalCheckpoint::default(),
81            interpreter,
82            is_finished: false,
83        }
84    }
85
86    /// Returns true if the frame has finished execution.
87    pub const fn is_finished(&self) -> bool {
88        self.is_finished
89    }
90
91    /// Sets the finished state of the frame.
92    pub const fn set_finished(&mut self, finished: bool) {
93        self.is_finished = finished;
94    }
95}
96
97/// Type alias for database errors from a context.
98pub type ContextTrDbError<CTX> = <<CTX as ContextTr>::Db as Database>::Error;
99
100impl EthFrame<EthInterpreter> {
101    /// Clear and initialize a frame.
102    #[expect(clippy::too_many_arguments)]
103    #[inline(always)]
104    pub fn clear(
105        &mut self,
106        data: FrameData,
107        input: FrameInput,
108        depth: usize,
109        memory: SharedMemory,
110        bytecode: ExtBytecode,
111        inputs: InputsImpl,
112        is_static: bool,
113        spec_id: SpecId,
114        gas_limit: u64,
115        reservoir_remaining_gas: u64,
116        checkpoint: JournalCheckpoint,
117    ) {
118        let Self {
119            data: data_ref,
120            input: input_ref,
121            depth: depth_ref,
122            interpreter,
123            checkpoint: checkpoint_ref,
124            is_finished: is_finished_ref,
125        } = self;
126        *data_ref = data;
127        *input_ref = input;
128        *depth_ref = depth;
129        *is_finished_ref = false;
130        interpreter.clear(
131            memory,
132            bytecode,
133            inputs,
134            is_static,
135            spec_id,
136            gas_limit,
137            reservoir_remaining_gas,
138        );
139        *checkpoint_ref = checkpoint;
140    }
141
142    /// Make call frame
143    #[inline]
144    pub fn make_call_frame<
145        CTX: ContextTr,
146        PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
147        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
148    >(
149        mut this: OutFrame<'_, Self>,
150        ctx: &mut CTX,
151        precompiles: &mut PRECOMPILES,
152        depth: usize,
153        memory: SharedMemory,
154        inputs: Box<CallInputs>,
155    ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
156        let reservoir_remaining_gas = inputs.reservoir;
157        let charged_new_account_state_gas = inputs.charged_new_account_state_gas;
158        let gas =
159            Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas);
160
161        let return_result = |instruction_result: InstructionResult| {
162            Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
163                result: InterpreterResult {
164                    result: instruction_result,
165                    gas,
166                    output: Bytes::new(),
167                },
168                memory_offset: inputs.return_memory_offset.clone(),
169                was_precompile_called: false,
170                precompile_call_logs: Vec::new(),
171                charged_new_account_state_gas,
172            })))
173        };
174
175        // Check depth
176        if depth > CALL_STACK_LIMIT as usize {
177            return return_result(InstructionResult::CallTooDeep);
178        }
179
180        // Create subroutine checkpoint
181        let checkpoint = ctx.journal_mut().checkpoint();
182
183        // Touch address. For "EIP-158 State Clear", this will erase empty accounts.
184        if let CallValue::Transfer(value) = inputs.value {
185            // Transfer value from caller to called account
186            // Target will get touched even if balance transferred is zero.
187            if let Some(i) =
188                ctx.journal_mut()
189                    .transfer_loaded(inputs.caller, inputs.target_address, value)
190            {
191                ctx.journal_mut().checkpoint_revert(checkpoint);
192                return return_result(i.into());
193            }
194        }
195
196        let interpreter_input = InputsImpl {
197            target_address: inputs.target_address,
198            caller_address: inputs.caller,
199            bytecode_address: Some(inputs.bytecode_address),
200            input: inputs.input.clone(),
201            call_value: inputs.value.get(),
202        };
203        let is_static = inputs.is_static;
204        let gas_limit = inputs.gas_limit;
205
206        if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? {
207            let mut logs = Vec::new();
208            if result.result.is_ok() {
209                // Preserve the reservoir on the result gas so it can be reimbursed.
210                // Precompiles don't use reservoir gas, but the first frame carries it.
211                ctx.journal_mut().checkpoint_commit();
212            } else {
213                // clone logs that precompile created, only possible with custom precompiles.
214                // checkpoint.log_i will be always correct.
215                logs = ctx.journal_mut().logs()[checkpoint.log_i..].to_vec();
216                ctx.journal_mut().checkpoint_revert(checkpoint);
217            }
218            return Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
219                result,
220                memory_offset: inputs.return_memory_offset.clone(),
221                was_precompile_called: true,
222                precompile_call_logs: logs,
223                charged_new_account_state_gas,
224            })));
225        }
226
227        // Get bytecode and hash - either from known_bytecode or load from account
228        let (bytecode_hash, bytecode) = inputs.known_bytecode.clone();
229
230        // Returns success if bytecode is empty.
231        if bytecode.is_empty() {
232            ctx.journal_mut().checkpoint_commit();
233            return return_result(InstructionResult::Stop);
234        }
235
236        // Create interpreter and executes call and push new CallStackFrame.
237        this.get(EthFrame::invalid).clear(
238            FrameData::Call(CallFrame {
239                return_memory_range: inputs.return_memory_offset.clone(),
240            }),
241            FrameInput::Call(inputs),
242            depth,
243            memory,
244            ExtBytecode::new_with_hash(bytecode, bytecode_hash),
245            interpreter_input,
246            is_static,
247            ctx.cfg().spec().into(),
248            gas_limit,
249            reservoir_remaining_gas,
250            checkpoint,
251        );
252
253        Ok(ItemOrResult::Item(this.consume()))
254    }
255
256    /// Make create frame.
257    #[inline]
258    pub fn make_create_frame<
259        CTX: ContextTr,
260        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
261    >(
262        mut this: OutFrame<'_, Self>,
263        context: &mut CTX,
264        depth: usize,
265        memory: SharedMemory,
266        inputs: Box<CreateInputs>,
267    ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
268        let reservoir_remaining_gas = inputs.reservoir();
269        let spec = context.cfg().spec().into();
270        // EIP-8037 refund for the CREATE opcode's upfront `create_state_gas` is
271        // applied uniformly in `return_result` when the create fails (revert,
272        // halt, or early-fail with `address == None`), so early-fail results
273        // only carry the reservoir they inherited from the parent.
274        let charged_create_state_gas = inputs.charged_create_state_gas();
275        let return_error = |e| {
276            Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome {
277                result: InterpreterResult {
278                    result: e,
279                    gas: Gas::new_with_regular_gas_and_reservoir(
280                        inputs.gas_limit(),
281                        reservoir_remaining_gas,
282                    ),
283                    output: Bytes::new(),
284                },
285                address: None,
286                charged_create_state_gas,
287            })))
288        };
289
290        // Check depth
291        if depth > CALL_STACK_LIMIT as usize {
292            return return_error(InstructionResult::CallTooDeep);
293        }
294
295        // Fetch balance of caller.
296        let journal = context.journal_mut();
297        let mut caller_info = journal.load_account_mut(inputs.caller())?;
298
299        // Check if caller has enough balance to send to the created contract.
300        // decrement of balance is done in the create_account_checkpoint.
301        if *caller_info.balance() < inputs.value() {
302            return return_error(InstructionResult::OutOfFunds);
303        }
304
305        // Increase nonce of caller and check if it overflows
306        let old_nonce = caller_info.nonce();
307        if !caller_info.bump_nonce() {
308            return return_error(InstructionResult::Return);
309        };
310
311        // Create address — uses OnceCell cache so that if an inspector already called
312        // `created_address`, the expensive keccak256 is not recomputed.
313        let created_address = inputs.created_address(old_nonce);
314        let init_code_hash = matches!(inputs.scheme(), CreateScheme::Create2 { .. })
315            .then(|| inputs.init_code_hash());
316
317        drop(caller_info); // Drop caller info to avoid borrow checker issues.
318
319        // warm load account.
320        journal.load_account(created_address)?;
321
322        // Create account, transfer funds and make the journal checkpoint.
323        let checkpoint = match context.journal_mut().create_account_checkpoint(
324            inputs.caller(),
325            created_address,
326            inputs.value(),
327            spec,
328        ) {
329            Ok(checkpoint) => checkpoint,
330            Err(e) => return return_error(e.into()),
331        };
332
333        let bytecode = ExtBytecode::new_with_optional_hash(
334            Bytecode::new_legacy(inputs.init_code().clone()),
335            init_code_hash,
336        );
337
338        let interpreter_input = InputsImpl {
339            target_address: created_address,
340            caller_address: inputs.caller(),
341            bytecode_address: None,
342            input: CallInput::Bytes(Bytes::new()),
343            call_value: inputs.value(),
344        };
345        let gas_limit = inputs.gas_limit();
346
347        this.get(EthFrame::invalid).clear(
348            FrameData::Create(CreateFrame { created_address }),
349            FrameInput::Create(inputs),
350            depth,
351            memory,
352            bytecode,
353            interpreter_input,
354            false,
355            spec,
356            gas_limit,
357            reservoir_remaining_gas,
358            checkpoint,
359        );
360
361        Ok(ItemOrResult::Item(this.consume()))
362    }
363
364    /// Initializes a frame with the given context and precompiles.
365    pub fn init_with_context<
366        CTX: ContextTr,
367        PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
368    >(
369        this: OutFrame<'_, Self>,
370        ctx: &mut CTX,
371        precompiles: &mut PRECOMPILES,
372        frame_init: FrameInit,
373    ) -> Result<
374        ItemOrResult<FrameToken, FrameResult>,
375        ContextError<<<CTX as ContextTr>::Db as Database>::Error>,
376    > {
377        // TODO cleanup inner make functions
378        let FrameInit {
379            depth,
380            memory,
381            frame_input,
382        } = frame_init;
383
384        match frame_input {
385            FrameInput::Call(inputs) => {
386                Self::make_call_frame(this, ctx, precompiles, depth, memory, inputs)
387            }
388            FrameInput::Create(inputs) => Self::make_create_frame(this, ctx, depth, memory, inputs),
389            FrameInput::Empty => unreachable!(),
390        }
391    }
392}
393
394impl EthFrame<EthInterpreter> {
395    /// Processes the next interpreter action, either creating a new frame or returning a result.
396    pub fn process_next_action<
397        CTX: ContextTr,
398        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
399    >(
400        &mut self,
401        context: &mut CTX,
402        next_action: InterpreterAction,
403    ) -> Result<FrameInitOrResult<Self>, ERROR> {
404        // Run interpreter
405
406        let mut interpreter_result = match next_action {
407            InterpreterAction::NewFrame(frame_input) => {
408                let depth = self.depth + 1;
409                return Ok(ItemOrResult::Item(FrameInit {
410                    frame_input,
411                    depth,
412                    memory: self.interpreter.memory.new_child_context(),
413                }));
414            }
415            InterpreterAction::Return(result) => result,
416        };
417
418        // Handle return from frame
419        let result = match &self.data {
420            FrameData::Call(frame) => {
421                // return_call
422                // Revert changes or not.
423                if interpreter_result.result.is_ok() {
424                    context.journal_mut().checkpoint_commit();
425                } else {
426                    context.journal_mut().checkpoint_revert(self.checkpoint);
427                }
428                // Propagate EIP-8037 new-account state-gas flag from the frame
429                // input so the parent can refund the upfront charge if the call
430                // ends in revert/halt.
431                let charged_new_account_state_gas = match &self.input {
432                    FrameInput::Call(inputs) => inputs.charged_new_account_state_gas,
433                    _ => false,
434                };
435                let mut outcome =
436                    CallOutcome::new(interpreter_result, frame.return_memory_range.clone());
437                outcome.charged_new_account_state_gas = charged_new_account_state_gas;
438                ItemOrResult::Result(FrameResult::Call(outcome))
439            }
440            FrameData::Create(frame) => {
441                return_create(
442                    context,
443                    self.checkpoint,
444                    &mut interpreter_result,
445                    frame.created_address,
446                );
447
448                let mut create_outcome =
449                    CreateOutcome::new(interpreter_result, Some(frame.created_address));
450                create_outcome.charged_create_state_gas = match &self.input {
451                    FrameInput::Create(inputs) => inputs.charged_create_state_gas(),
452                    _ => false,
453                };
454                ItemOrResult::Result(FrameResult::Create(create_outcome))
455            }
456        };
457
458        Ok(result)
459    }
460
461    /// Processes a frame result and updates the interpreter state accordingly.
462    pub fn return_result<CTX: ContextTr, ERROR: From<ContextTrDbError<CTX>> + FromStringError>(
463        &mut self,
464        ctx: &mut CTX,
465        result: FrameResult,
466    ) -> Result<(), ERROR> {
467        self.interpreter.memory.free_child_context();
468        take_error::<ERROR, _>(ctx.error())?;
469
470        // EIP-8037: the CALL/CREATE opcode charged the new-account or
471        // create state gas upfront on this (parent) frame's tracker. When the
472        // child does not create the account leaf it paid for, the charge is
473        // refunded below via `refill_reservoir` (matching 0→x→0 storage
474        // restoration) — the child rollback in `handle_reservoir_remaining_gas`
475        // cannot do it, since the charge lives on the parent, not the child.
476        let refund_state_gas = result.refundable_state_gas(ctx.cfg().gas_params());
477
478        // Insert result to the top frame.
479        match result {
480            FrameResult::Call(outcome) => {
481                let mut out_gas = outcome.gas();
482                let ins_result = *outcome.instruction_result();
483                let returned_len = outcome.result.output.len();
484
485                let interpreter = &mut self.interpreter;
486                let mem_length = outcome.memory_length();
487                let mem_start = outcome.memory_start();
488                interpreter.return_data.set_buffer(outcome.result.output);
489
490                let target_len = min(mem_length, returned_len);
491
492                if ins_result == InstructionResult::FatalExternalError {
493                    panic!("Fatal external error in insert_call_outcome");
494                }
495
496                let item = if ins_result.is_ok() {
497                    U256::from(1)
498                } else {
499                    U256::ZERO
500                };
501                // Safe to push without stack limit check
502                let _ = interpreter.stack.push(item);
503
504                // Copy returned data into the parent's memory on success or revert.
505                if ins_result.is_ok_or_revert() {
506                    interpreter
507                        .memory
508                        .set(mem_start, &interpreter.return_data.buffer()[..target_len]);
509                }
510
511                // Settle the child's gas and merge it into the parent (returns
512                // unused regular gas, adopts the reservoir, and propagates state
513                // gas / refunds on success).
514                handle_reservoir_remaining_gas(
515                    ins_result,
516                    interpreter.gas.tracker_mut(),
517                    out_gas.tracker_mut(),
518                );
519            }
520            FrameResult::Create(outcome) => {
521                let instruction_result = *outcome.instruction_result();
522                let interpreter = &mut self.interpreter;
523
524                if instruction_result == InstructionResult::Revert {
525                    // Save data to return data buffer if the create reverted
526                    interpreter
527                        .return_data
528                        .set_buffer(outcome.output().to_owned());
529                } else {
530                    // Otherwise clear it. Note that RETURN opcode should abort.
531                    interpreter.return_data.clear();
532                };
533
534                assert_ne!(
535                    instruction_result,
536                    InstructionResult::FatalExternalError,
537                    "Fatal external error in insert_eofcreate_outcome"
538                );
539
540                let mut create_gas = *outcome.gas();
541
542                // Settle the child's gas and merge it into the parent (returns
543                // unused regular gas, adopts the reservoir, and propagates state
544                // gas / refunds on success).
545                handle_reservoir_remaining_gas(
546                    instruction_result,
547                    interpreter.gas.tracker_mut(),
548                    create_gas.tracker_mut(),
549                );
550
551                let stack_item = if instruction_result.is_ok() {
552                    outcome.address.unwrap_or_default().into_word().into()
553                } else {
554                    U256::ZERO
555                };
556
557                // Safe to push without stack limit check
558                let _ = interpreter.stack.push(stack_item);
559            }
560        }
561
562        // Refund the upfront state charge after the child's gas is settled
563        // (the settle overwrites the reservoir with the child's).
564        if let Some(charge) = refund_state_gas {
565            self.interpreter.gas.refill_reservoir(charge);
566        }
567
568        Ok(())
569    }
570}
571
572/// Settles a returning child frame's gas and merges it into the parent
573/// (EIP-8037 reservoir model).
574///
575/// First the child *settles its own gas*: a failing frame (revert or halt) rolls
576/// its state-gas charges back in last-in-first-out order
577/// ([`GasTracker::rollback_state_gas`]) — crediting the spilled portion back to its
578/// `remaining` and restoring the reservoir to the value it inherited — and drops
579/// its execution refund counter; an exceptional halt additionally consumes the
580/// child's regular gas.
581///
582/// Then the parent *merges* the settled child:
583/// - unused regular gas (`remaining`, including any spill returned on revert)
584///   flows back to the parent on success or revert; a halt consumes it.
585/// - the reservoir, a shared state-gas pool the child inherited at call time, is
586///   always adopted from the child (restored to the inherited value on
587///   revert/halt).
588/// - net state gas, its spilled portion, and the refund counter persist only on
589///   success; on revert/halt the child's state changes roll back and contribute
590///   nothing.
591#[inline]
592pub const fn handle_reservoir_remaining_gas(
593    instruction_result: InstructionResult,
594    parent_gas: &mut GasTracker,
595    child_gas: &mut GasTracker,
596) {
597    // Settle the child's own gas for its stop reason.
598    if !instruction_result.is_ok() {
599        child_gas.rollback_state_gas();
600        child_gas.set_refunded(0);
601    }
602    if instruction_result.is_halt() {
603        // Exceptional halt consumes the child's regular gas (including the spill
604        // just credited back by `rollback_state_gas`); the reservoir is left
605        // restored to the inherited value for the parent.
606        child_gas.spend_all();
607    }
608
609    // Merge the settled child into the parent.
610    if instruction_result.is_ok_or_revert() {
611        parent_gas.erase_cost(child_gas.remaining());
612    }
613    parent_gas.set_reservoir(child_gas.reservoir());
614    if instruction_result.is_ok() {
615        // Parent may have already charged state gas (e.g. new_account + create)
616        // before creating the child frame, so add rather than overwrite. The
617        // child's `state_gas_spent` can be negative (EIP-8037 issue #2) when it
618        // did more 0→x→0 restorations than 0→x creations; the negative
619        // contribution is the parent's matching charge flowing back out.
620        parent_gas.set_state_gas_spent(
621            parent_gas
622                .state_gas_spent()
623                .saturating_add(child_gas.state_gas_spent()),
624        );
625        parent_gas.add_state_gas_spilled(child_gas.state_gas_spilled());
626        parent_gas.record_refund(child_gas.refunded());
627    }
628}
629
630/// Handles the result of a CREATE operation, including validation and state updates.
631///
632/// The EIP-8037 upfront CREATE state gas is charged on the parent's tracker by
633/// the CREATE/CREATE2 opcode. On child failure (revert/halt/early-fail) it is
634/// refunded to the parent in `return_result`. The child frame is NOT allowed to
635/// borrow the upfront charge to pay for code deposit: it must cover code deposit
636/// state gas from its own reservoir and remaining gas.
637pub fn return_create<CTX: ContextTr>(
638    context: &mut CTX,
639    checkpoint: JournalCheckpoint,
640    interpreter_result: &mut InterpreterResult,
641    address: Address,
642) {
643    let (_, _, cfg, journal, _, _) = context.all_mut();
644
645    let max_code_size = cfg.max_code_size();
646    let is_eip3541_disabled = cfg.is_eip3541_disabled();
647    let spec_id = cfg.spec().into();
648    let is_amsterdam_eip8037 = cfg.is_amsterdam_eip8037_enabled();
649    let gas_params = cfg.gas_params();
650
651    // If return is not ok revert and return.
652    if !interpreter_result.result.is_ok() {
653        journal.checkpoint_revert(checkpoint);
654        return;
655    }
656
657    // EIP-170: Contract code size limit to 0x6000 (~25kb)
658    // EIP-7954 increased this limit to 0x10000 (64kb).
659    // This must be checked BEFORE charging state gas for code deposit,
660    // so that oversized code does not incur storage gas costs.
661    if spec_id.is_enabled_in(SPURIOUS_DRAGON) && interpreter_result.output.len() > max_code_size {
662        journal.checkpoint_revert(checkpoint);
663        interpreter_result.result = InstructionResult::CreateContractSizeLimit;
664        return;
665    }
666
667    // Host error if present on execution
668    // If ok, check contract creation limit and calculate gas deduction on output len.
669    //
670    // EIP-3541: Reject new contract code starting with the 0xEF byte
671    if !is_eip3541_disabled
672        && spec_id.is_enabled_in(LONDON)
673        && interpreter_result.output.first() == Some(&0xEF)
674    {
675        journal.checkpoint_revert(checkpoint);
676        interpreter_result.result = InstructionResult::CreateContractStartingWithEF;
677        return;
678    }
679
680    // regular gas for code deposit. It is zero in EIP-8037.
681    let gas_for_code = gas_params.code_deposit_cost(interpreter_result.output.len());
682    if !interpreter_result.gas.record_regular_cost(gas_for_code) {
683        // Record code deposit gas cost and check if we are out of gas.
684        // EIP-2 point 3: If contract creation does not have enough gas to pay for the
685        // final gas fee for adding the contract code to the state, the contract
686        // creation fails (i.e. goes out-of-gas) rather than leaving an empty contract.
687        if spec_id.is_enabled_in(HOMESTEAD) {
688            journal.checkpoint_revert(checkpoint);
689            interpreter_result.result = InstructionResult::OutOfGas;
690            return;
691        } else {
692            interpreter_result.output = Bytes::new();
693        }
694    }
695
696    // EIP-8037: Hash cost for deployed bytecode (keccak256)
697    // HASH_COST(L) = 6 × ceil(L / 32)
698    // Both CREATE and CREATE2 must pay this cost: it covers hashing the deployed code
699    // to compute the code_hash stored in the account. CREATE2's existing keccak256 charge
700    // (in create2_cost) is for hashing the init code during address derivation, which is
701    // a different hash.
702    if is_amsterdam_eip8037 {
703        let hash_cost = gas_params.keccak256_cost(interpreter_result.output.len());
704        if !interpreter_result.gas.record_regular_cost(hash_cost) {
705            journal.checkpoint_revert(checkpoint);
706            interpreter_result.result = InstructionResult::OutOfGas;
707            return;
708        }
709        // State gas for code deposit (EIP-8037).
710        // Charged after size check: only code that passes validation incurs state gas cost.
711        //
712        // Note: This should be last operation before checkpoint commit as spending state before this messes
713        // with refilling of state gas.
714        let state_gas_for_code = gas_params.code_deposit_state_gas(interpreter_result.output.len());
715        if state_gas_for_code > 0 && !interpreter_result.gas.record_state_cost(state_gas_for_code) {
716            journal.checkpoint_revert(checkpoint);
717            interpreter_result.result = InstructionResult::OutOfGas;
718            return;
719        }
720    }
721
722    // If we have enough gas we can commit changes.
723    journal.checkpoint_commit();
724
725    // Do analysis of bytecode straight away.
726    let bytecode = Bytecode::new_legacy(interpreter_result.output.clone());
727
728    // Set code
729    journal.set_code(address, bytecode);
730
731    interpreter_result.result = InstructionResult::Return;
732}