Skip to main content

revm_handler/
handler.rs

1use crate::{
2    evm::FrameTr,
3    execution,
4    post_execution::{self, build_result_gas},
5    pre_execution::{self, apply_eip7702_auth_list},
6    validation, EvmTr, FrameResult, ItemOrResult,
7};
8use context::{
9    result::{ExecutionResult, FromStringError},
10    LocalContextTr,
11};
12use context_interface::{
13    context::{take_error, ContextError},
14    result::{HaltReasonTr, InvalidHeader, InvalidTransaction, ResultGas},
15    Cfg, ContextTr, Database, JournalTr, Transaction,
16};
17use interpreter::{interpreter_action::FrameInit, Gas, InitialAndFloorGas, SharedMemory};
18use primitives::U256;
19
20/// Trait for errors that can occur during EVM execution.
21///
22/// This trait represents the minimal error requirements for EVM execution,
23/// ensuring that all necessary error types can be converted into the handler's error type.
24pub trait EvmTrError<EVM: EvmTr>:
25    From<InvalidTransaction>
26    + From<InvalidHeader>
27    + From<<<EVM::Context as ContextTr>::Db as Database>::Error>
28    + From<ContextError<<<EVM::Context as ContextTr>::Db as Database>::Error>>
29    + FromStringError
30{
31}
32
33impl<
34        EVM: EvmTr,
35        T: From<InvalidTransaction>
36            + From<InvalidHeader>
37            + From<<<EVM::Context as ContextTr>::Db as Database>::Error>
38            + From<ContextError<<<EVM::Context as ContextTr>::Db as Database>::Error>>
39            + FromStringError,
40    > EvmTrError<EVM> for T
41{
42}
43
44/// The main implementation of Ethereum Mainnet transaction execution.
45///
46/// The [`Handler::run`] method serves as the entry point for execution and provides
47/// out-of-the-box support for executing Ethereum mainnet transactions.
48///
49/// This trait allows EVM variants to customize execution logic by implementing
50/// their own method implementations.
51///
52/// The handler logic consists of four phases:
53///   * Validation - Validates tx/block/config fields and loads caller account and validates initial gas requirements and
54///     balance checks.
55///   * Pre-execution - Loads and warms accounts, deducts initial gas
56///   * Execution - Executes the main frame loop, delegating to [`EvmTr`] for creating and running call frames.
57///   * Post-execution - Calculates final refunds, validates gas floor, reimburses caller,
58///     and rewards beneficiary
59///
60///
61/// The [`Handler::catch_error`] method handles cleanup of intermediate state if an error
62/// occurs during execution.
63///
64/// # Returns
65///
66/// Returns execution status, error, gas spend and logs. State change is not returned and it is
67/// contained inside Context Journal. This setup allows multiple transactions to be chain executed.
68///
69/// To finalize the execution and obtain changed state, call [`JournalTr::finalize`] function.
70pub trait Handler {
71    /// The EVM type containing Context, Instruction, and Precompiles implementations.
72    type Evm: EvmTr<
73        Context: ContextTr<Journal: JournalTr, Local: LocalContextTr>,
74        Frame: FrameTr<FrameInit = FrameInit, FrameResult = FrameResult>,
75    >;
76    /// The error type returned by this handler.
77    type Error: EvmTrError<Self::Evm>;
78    /// The halt reason type included in the output
79    type HaltReason: HaltReasonTr;
80
81    /// The main entry point for transaction execution.
82    ///
83    /// This method calls [`Handler::run_without_catch_error`] and if it returns an error,
84    /// calls [`Handler::catch_error`] to handle the error and cleanup.
85    ///
86    /// The [`Handler::catch_error`] method ensures intermediate state is properly cleared.
87    ///
88    /// # Error handling
89    ///
90    /// In case of error, the journal can be in an inconsistent state and should be cleared by calling
91    /// [`JournalTr::discard_tx`] method or dropped.
92    ///
93    /// # Returns
94    ///
95    /// Returns execution result, error, gas spend and logs.
96    #[inline]
97    fn run(
98        &mut self,
99        evm: &mut Self::Evm,
100    ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> {
101        // Run inner handler and catch all errors to handle cleanup.
102        match self.run_without_catch_error(evm) {
103            Ok(output) => Ok(output),
104            Err(e) => self.catch_error(evm, e),
105        }
106    }
107
108    /// Runs the system call.
109    ///
110    /// System call is a special transaction where caller is a [`crate::SYSTEM_ADDRESS`]
111    ///
112    /// It is used to call a system contracts and it skips all the `validation` and `pre-execution` and most of `post-execution` phases.
113    /// For example it will not deduct the caller or reward the beneficiary.
114    ///
115    /// State changs can be obtained by calling [`JournalTr::finalize`] method from the [`EvmTr::Context`].
116    ///
117    /// # Error handling
118    ///
119    /// By design system call should not fail and should always succeed.
120    /// In case of an error (If fetching account/storage on rpc fails), the journal can be in an inconsistent
121    /// state and should be cleared by calling [`JournalTr::discard_tx`] method or dropped.
122    #[inline]
123    fn run_system_call(
124        &mut self,
125        evm: &mut Self::Evm,
126    ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> {
127        // dummy values that are not used.
128        let init_and_floor_gas = InitialAndFloorGas::new(0, 0);
129        // call execution and than output.
130        match self
131            .execution(evm, &init_and_floor_gas)
132            .and_then(|exec_result| {
133                // System calls have no intrinsic gas; build ResultGas from frame result.
134                let gas = exec_result.gas();
135                let result_gas = build_result_gas(gas, init_and_floor_gas);
136                self.execution_result(evm, exec_result, result_gas)
137            }) {
138            out @ Ok(_) => out,
139            Err(e) => self.catch_error(evm, e),
140        }
141    }
142
143    /// Called by [`Handler::run`] to execute the core handler logic.
144    ///
145    /// Executes the four phases in sequence: [Handler::validate],
146    /// [Handler::pre_execution], [Handler::execution], [Handler::post_execution].
147    ///
148    /// Returns any errors without catching them or calling [`Handler::catch_error`].
149    #[inline]
150    fn run_without_catch_error(
151        &mut self,
152        evm: &mut Self::Evm,
153    ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> {
154        let mut init_and_floor_gas = self.validate(evm)?;
155        let eip7702_refund = self.pre_execution(evm, &mut init_and_floor_gas)?;
156        // Regular refund is returned from pre_execution after state gas split is applied
157        let eip7702_regular_refund = eip7702_refund as i64;
158
159        let mut exec_result = self.execution(evm, &init_and_floor_gas)?;
160        let result_gas = self.post_execution(
161            evm,
162            &mut exec_result,
163            init_and_floor_gas,
164            eip7702_regular_refund,
165        )?;
166
167        // Prepare the output
168        self.execution_result(evm, exec_result, result_gas)
169    }
170
171    /// Validates the execution environment and transaction parameters.
172    ///
173    /// Calculates initial and floor gas requirements and verifies they are covered by the gas limit.
174    ///
175    /// Validation against state is done later in pre-execution phase in deduct_caller function.
176    #[inline]
177    fn validate(&self, evm: &mut Self::Evm) -> Result<InitialAndFloorGas, Self::Error> {
178        self.validate_env(evm)?;
179        self.validate_initial_tx_gas(evm)
180    }
181
182    /// Prepares the EVM state for execution.
183    ///
184    /// Loads the beneficiary account (EIP-3651: Warm COINBASE) and all accounts/storage from the access list (EIP-2929).
185    ///
186    /// Deducts the maximum possible fee from the caller's balance.
187    ///
188    /// For EIP-7702 transactions, applies the authorization list and delegates successful authorizations.
189    /// Returns the gas refund amount from EIP-7702. Authorizations are applied before execution begins.
190    #[inline]
191    fn pre_execution(
192        &self,
193        evm: &mut Self::Evm,
194        init_and_floor_gas: &mut InitialAndFloorGas,
195    ) -> Result<u64, Self::Error> {
196        self.validate_against_state_and_deduct_caller(evm, init_and_floor_gas)?;
197        self.load_accounts(evm)?;
198
199        let gas = self.apply_eip7702_auth_list(evm, init_and_floor_gas)?;
200        Ok(gas)
201    }
202
203    /// Creates and executes the initial frame, then processes the execution loop.
204    ///
205    /// Always calls [Handler::last_frame_result] to handle returned gas from the call.
206    #[inline]
207    fn execution(
208        &mut self,
209        evm: &mut Self::Evm,
210        init_and_floor_gas: &InitialAndFloorGas,
211    ) -> Result<FrameResult, Self::Error> {
212        // Compute the regular gas budget and EIP-8037 reservoir for the first frame.
213        let (gas_limit, reservoir) = init_and_floor_gas.initial_gas_and_reservoir(
214            evm.ctx().tx().gas_limit(),
215            evm.ctx().cfg().tx_gas_limit_cap(),
216            evm.ctx().cfg().is_amsterdam_eip8037_enabled(),
217        );
218
219        // Create first frame action
220        // Note: first_frame_input now handles state gas deduction from the reservoir
221        let first_frame_input = self.first_frame_input(evm, gas_limit, reservoir)?;
222
223        // Run execution loop
224        let mut frame_result = self.run_exec_loop(evm, first_frame_input)?;
225
226        // Handle last frame result
227        self.last_frame_result(evm, &mut frame_result)?;
228        Ok(frame_result)
229    }
230
231    /// Handles the final steps of transaction execution.
232    ///
233    /// Calculates final refunds and validates the gas floor (EIP-7623) to ensure minimum gas is spent.
234    /// After EIP-7623, at least floor gas must be consumed.
235    ///
236    /// Reimburses unused gas to the caller and rewards the beneficiary with transaction fees.
237    /// The effective gas price determines rewards, with the base fee being burned.
238    ///
239    /// Finally, finalizes output by returning the journal state and clearing internal state
240    /// for the next execution.
241    #[inline]
242    fn post_execution(
243        &self,
244        evm: &mut Self::Evm,
245        exec_result: &mut FrameResult,
246        init_and_floor_gas: InitialAndFloorGas,
247        eip7702_gas_refund: i64,
248    ) -> Result<ResultGas, Self::Error> {
249        // Calculate final refund and add EIP-7702 refund to gas.
250        self.refund(evm, exec_result, eip7702_gas_refund);
251
252        // Build ResultGas from the final gas state
253        // This includes all necessary fields and gas values.
254        let result_gas = post_execution::build_result_gas(exec_result.gas(), init_and_floor_gas);
255
256        // Ensure gas floor is met and minimum floor gas is spent.
257        // if `cfg.is_eip7623_disabled` is true, floor gas will be set to zero
258        self.eip7623_check_gas_floor(evm, exec_result, init_and_floor_gas);
259        // Return unused gas to caller
260        self.reimburse_caller(evm, exec_result)?;
261        // Pay transaction fees to beneficiary
262        self.reward_beneficiary(evm, exec_result)?;
263        // Build ResultGas from the final gas state
264        Ok(result_gas)
265    }
266
267    /* VALIDATION */
268
269    /// Validates block, transaction and configuration fields.
270    ///
271    /// Performs all validation checks that can be done without loading state.
272    /// For example, verifies transaction gas limit is below block gas limit.
273    #[inline]
274    fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
275        validation::validate_env(evm.ctx())
276    }
277
278    /// Calculates initial gas costs based on transaction type and input data.
279    ///
280    /// Includes additional costs for access list and authorization list.
281    ///
282    /// Verifies the initial cost does not exceed the transaction gas limit.
283    #[inline]
284    fn validate_initial_tx_gas(
285        &self,
286        evm: &mut Self::Evm,
287    ) -> Result<InitialAndFloorGas, Self::Error> {
288        let ctx = evm.ctx_ref();
289        let gas = validation::validate_initial_tx_gas(
290            ctx.tx(),
291            ctx.cfg().spec().into(),
292            ctx.cfg().is_eip7623_disabled(),
293            ctx.cfg().is_amsterdam_eip8037_enabled(),
294            ctx.cfg().tx_gas_limit_cap(),
295        )?;
296
297        Ok(gas)
298    }
299
300    /* PRE EXECUTION */
301
302    /// Loads access list and beneficiary account, marking them as warm in the [`context::Journal`].
303    #[inline]
304    fn load_accounts(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
305        pre_execution::load_accounts(evm)
306    }
307
308    /// Processes the authorization list, validating authority signatures, nonces and chain IDs.
309    /// Applies valid authorizations to accounts.
310    ///
311    /// Returns the gas refund amount specified by EIP-7702.
312    #[inline]
313    fn apply_eip7702_auth_list(
314        &self,
315        evm: &mut Self::Evm,
316        init_and_floor_gas: &mut InitialAndFloorGas,
317    ) -> Result<u64, Self::Error> {
318        apply_eip7702_auth_list(evm.ctx_mut(), init_and_floor_gas)
319    }
320
321    /// Deducts the maximum possible fee from caller's balance.
322    ///
323    /// If cfg.is_balance_check_disabled, this method will add back enough funds to ensure that
324    /// the caller's balance is at least tx.value() before returning. Note that the amount of funds
325    /// added back in this case may exceed the maximum fee.
326    ///
327    /// Unused fees are returned to caller after execution completes.
328    #[inline]
329    fn validate_against_state_and_deduct_caller(
330        &self,
331        evm: &mut Self::Evm,
332        _init_and_floor_gas: &mut InitialAndFloorGas,
333    ) -> Result<(), Self::Error> {
334        pre_execution::validate_against_state_and_deduct_caller(evm.ctx())
335    }
336
337    /* EXECUTION */
338
339    /// Creates initial frame input using transaction parameters, gas limit and configuration.
340    #[inline]
341    fn first_frame_input(
342        &mut self,
343        evm: &mut Self::Evm,
344        gas_limit: u64,
345        reservoir: u64,
346    ) -> Result<FrameInit, Self::Error> {
347        let ctx = evm.ctx_mut();
348        let mut memory = SharedMemory::new_with_buffer(ctx.local().shared_memory_buffer().clone());
349        memory.set_memory_limit(ctx.cfg().memory_limit());
350
351        let frame_input = execution::create_init_frame(ctx, gas_limit, reservoir)?;
352
353        Ok(FrameInit {
354            depth: 0,
355            memory,
356            frame_input,
357        })
358    }
359
360    /// Processes the result of the initial call and handles returned gas.
361    #[inline]
362    fn last_frame_result(
363        &mut self,
364        evm: &mut Self::Evm,
365        frame_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
366    ) -> Result<(), Self::Error> {
367        let instruction_result = frame_result.interpreter_result().result;
368        let gas = frame_result.gas_mut();
369        let remaining = gas.remaining();
370        let refunded = gas.refunded();
371        let reservoir = gas.reservoir();
372        let state_gas_spent = gas.state_gas_spent();
373
374        // Spend the gas limit. Gas is reimbursed when the tx returns successfully.
375        *gas = Gas::new_spent_with_reservoir(evm.ctx().tx().gas_limit(), reservoir);
376
377        if instruction_result.is_ok_or_revert() {
378            // Return unused regular gas. Reservoir is handled separately via state_gas_spent.
379            gas.erase_cost(remaining);
380        }
381
382        if instruction_result.is_ok() {
383            gas.record_refund(refunded);
384        }
385
386        // Reservoir handling at the top-level frame:
387        // - On success: use the frame's final reservoir as-is, state gas was consumed.
388        // - On revert/halt: restore state gas spent back to the reservoir,
389        //   because state changes are rolled back so state gas should be refunded.
390        //
391        // Note: eth devnet3 does NOT do this — it ignores state_gas_spent and
392        // unconditionally sets gas.set_reservoir(reservoir) regardless of the
393        // instruction_result kind. This is a bug in the devnet3 spec.
394        if instruction_result.is_ok() {
395            gas.set_state_gas_spent(state_gas_spent);
396        } else {
397            // State changes rolled back, so no execution state gas was consumed.
398            gas.set_state_gas_spent(0);
399            gas.set_reservoir(reservoir + state_gas_spent);
400        }
401
402        Ok(())
403    }
404
405    /* FRAMES */
406
407    /// Executes the main frame processing loop.
408    ///
409    /// This loop manages the frame stack, processing each frame until execution completes.
410    /// For each iteration:
411    /// 1. Calls the current frame
412    /// 2. Handles the returned frame input or result
413    /// 3. Creates new frames or propagates results as needed
414    #[inline]
415    fn run_exec_loop(
416        &mut self,
417        evm: &mut Self::Evm,
418        first_frame_input: <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameInit,
419    ) -> Result<FrameResult, Self::Error> {
420        let res = evm.frame_init(first_frame_input)?;
421
422        if let ItemOrResult::Result(frame_result) = res {
423            return Ok(frame_result);
424        }
425
426        loop {
427            let call_or_result = evm.frame_run()?;
428
429            let result = match call_or_result {
430                ItemOrResult::Item(init) => {
431                    match evm.frame_init(init)? {
432                        ItemOrResult::Item(_) => {
433                            continue;
434                        }
435                        // Do not pop the frame since no new frame was created
436                        ItemOrResult::Result(result) => result,
437                    }
438                }
439                ItemOrResult::Result(result) => result,
440            };
441
442            if let Some(result) = evm.frame_return_result(result)? {
443                return Ok(result);
444            }
445        }
446    }
447
448    /* POST EXECUTION */
449
450    /// Validates that the minimum gas floor requirements are satisfied.
451    ///
452    /// Ensures that at least the floor gas amount has been consumed during execution.
453    #[inline]
454    fn eip7623_check_gas_floor(
455        &self,
456        _evm: &mut Self::Evm,
457        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
458        init_and_floor_gas: InitialAndFloorGas,
459    ) {
460        post_execution::eip7623_check_gas_floor(exec_result.gas_mut(), init_and_floor_gas)
461    }
462
463    /// Calculates the final gas refund amount, including any EIP-7702 refunds.
464    #[inline]
465    fn refund(
466        &self,
467        evm: &mut Self::Evm,
468        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
469        eip7702_refund: i64,
470    ) {
471        let spec = evm.ctx().cfg().spec().into();
472        post_execution::refund(spec, exec_result.gas_mut(), eip7702_refund)
473    }
474
475    /// Returns unused gas costs to the transaction sender's account.
476    #[inline]
477    fn reimburse_caller(
478        &self,
479        evm: &mut Self::Evm,
480        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
481    ) -> Result<(), Self::Error> {
482        post_execution::reimburse_caller(evm.ctx(), exec_result.gas(), U256::ZERO)
483            .map_err(From::from)
484    }
485
486    /// Transfers transaction fees to the block beneficiary's account.
487    #[inline]
488    fn reward_beneficiary(
489        &self,
490        evm: &mut Self::Evm,
491        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
492    ) -> Result<(), Self::Error> {
493        post_execution::reward_beneficiary(evm.ctx(), exec_result.gas()).map_err(From::from)
494    }
495
496    /// Processes the final execution output.
497    ///
498    /// This method, retrieves the final state from the journal, converts internal results to the external output format.
499    /// Internal state is cleared and EVM is prepared for the next transaction.
500    #[inline]
501    fn execution_result(
502        &mut self,
503        evm: &mut Self::Evm,
504        result: <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
505        result_gas: ResultGas,
506    ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> {
507        take_error::<Self::Error, _>(evm.ctx().error())?;
508
509        let exec_result = post_execution::output(evm.ctx(), result, result_gas);
510
511        // commit transaction
512        evm.ctx().journal_mut().commit_tx();
513        evm.ctx().local_mut().clear();
514        evm.frame_stack().clear();
515
516        Ok(exec_result)
517    }
518
519    /// Handles cleanup when an error occurs during execution.
520    ///
521    /// Ensures the journal state is properly cleared before propagating the error.
522    /// On happy path journal is cleared in [`Handler::execution_result`] method.
523    #[inline]
524    fn catch_error(
525        &self,
526        evm: &mut Self::Evm,
527        error: Self::Error,
528    ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> {
529        // clean up local context. Initcode cache needs to be discarded.
530        evm.ctx().local_mut().clear();
531        evm.ctx().journal_mut().discard_tx();
532        evm.frame_stack().clear();
533        Err(error)
534    }
535}