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