Skip to main content

revm_handler/
post_execution.rs

1use crate::FrameResult;
2use context::journaled_state::account::JournaledAccountTr;
3use context_interface::{
4    journaled_state::JournalTr,
5    result::{ExecutionResult, HaltReason, HaltReasonTr, ResultGas},
6    Block, Cfg, ContextTr, Database, LocalContextTr, Transaction,
7};
8use interpreter::{Gas, InitialAndFloorGas, SuccessOrHalt};
9use primitives::{hardfork::SpecId, U256};
10
11/// Builds a [`ResultGas`] from the execution [`Gas`] struct and [`InitialAndFloorGas`].
12pub fn build_result_gas(gas: &Gas, init_and_floor_gas: InitialAndFloorGas) -> ResultGas {
13    let state_gas = gas
14        .state_gas_spent()
15        .saturating_add(init_and_floor_gas.initial_state_gas)
16        .saturating_sub(init_and_floor_gas.eip7702_reservoir_refund);
17
18    ResultGas::default()
19        .with_total_gas_spent(
20            gas.limit()
21                .saturating_sub(gas.remaining())
22                .saturating_sub(gas.reservoir()),
23        )
24        .with_refunded(gas.refunded() as u64)
25        .with_floor_gas(init_and_floor_gas.floor_gas)
26        .with_state_gas_spent(state_gas)
27}
28
29/// Ensures minimum gas floor is spent according to EIP-7623.
30///
31/// Per EIP-8037, gas used before refund is `tx.gas - gas_left - state_gas_reservoir`.
32/// The floor applies to this combined total, not just regular gas.
33pub fn eip7623_check_gas_floor(gas: &mut Gas, init_and_floor_gas: InitialAndFloorGas) {
34    // EIP-7623: Increase calldata cost
35    // EIP-8037: tx_gas_used_before_refund = tx.gas - gas_left - reservoir
36    // The floor must apply to this combined value, not just (limit - remaining).
37    let gas_used_before_refund = gas.total_gas_spent().saturating_sub(gas.reservoir());
38    let gas_used_after_refund = gas_used_before_refund.saturating_sub(gas.refunded() as u64);
39    if gas_used_after_refund < init_and_floor_gas.floor_gas {
40        // Set spent so that (limit - remaining - reservoir) = floor_gas
41        // i.e. remaining = limit - floor_gas - reservoir
42        gas.set_spent(init_and_floor_gas.floor_gas + gas.reservoir());
43        // clear refund
44        gas.set_refund(0);
45    }
46}
47
48/// Calculates and applies gas refunds based on the specification.
49pub fn refund(spec: SpecId, gas: &mut Gas, eip7702_refund: i64) {
50    gas.record_refund(eip7702_refund);
51    // Calculate gas refund for transaction.
52    // If spec is set to london, it will decrease the maximum refund amount to 5th part of
53    // gas spend. (Before london it was 2th part of gas spend)
54    gas.set_final_refund(spec.is_enabled_in(SpecId::LONDON));
55}
56
57/// Reimburses the caller for unused gas.
58#[inline]
59pub fn reimburse_caller<CTX: ContextTr>(
60    context: &mut CTX,
61    gas: &Gas,
62    additional_refund: U256,
63) -> Result<(), <CTX::Db as Database>::Error> {
64    let basefee = context.block().basefee() as u128;
65    let caller = context.tx().caller();
66    let effective_gas_price = context.tx().effective_gas_price(basefee);
67
68    // Return balance of not spent gas.
69    // Include reservoir gas (EIP-8037) which is also unused and must be reimbursed.
70    let reimbursable = gas.remaining() + gas.reservoir() + gas.refunded() as u64;
71    context
72        .journal_mut()
73        .load_account_mut(caller)?
74        .incr_balance(
75            U256::from(effective_gas_price.saturating_mul(reimbursable as u128))
76                + additional_refund,
77        );
78
79    Ok(())
80}
81
82/// Rewards the beneficiary with transaction fees.
83#[inline]
84pub fn reward_beneficiary<CTX: ContextTr>(
85    context: &mut CTX,
86    gas: &Gas,
87) -> Result<(), <CTX::Db as Database>::Error> {
88    let (block, tx, cfg, journal, _, _) = context.all_mut();
89    let basefee = block.basefee() as u128;
90    let effective_gas_price = tx.effective_gas_price(basefee);
91
92    // Transfer fee to coinbase/beneficiary.
93    // EIP-1559 discard basefee for coinbase transfer. Basefee amount of gas is discarded.
94    let coinbase_gas_price = if cfg.spec().into().is_enabled_in(SpecId::LONDON) {
95        effective_gas_price.saturating_sub(basefee)
96    } else {
97        effective_gas_price
98    };
99
100    // Reward beneficiary.
101    // Exclude reservoir gas (EIP-8037) from the used gas — reservoir is unused and reimbursed.
102    let effective_used = gas.used().saturating_sub(gas.reservoir());
103    journal
104        .load_account_mut(block.beneficiary())?
105        .incr_balance(U256::from(coinbase_gas_price * effective_used as u128));
106
107    Ok(())
108}
109
110/// Calculate last gas spent and transform internal reason to external.
111///
112/// TODO make Journal FinalOutput more generic.
113pub fn output<CTX: ContextTr<Journal: JournalTr>, HALTREASON: HaltReasonTr>(
114    context: &mut CTX,
115    // TODO, make this more generic and nice.
116    // FrameResult should be a generic that returns gas and interpreter result.
117    result: FrameResult,
118    result_gas: ResultGas,
119) -> ExecutionResult<HALTREASON> {
120    let output = result.output();
121    let instruction_result = result.into_interpreter_result();
122
123    // take logs from journal.
124    let logs = context.journal_mut().take_logs();
125
126    match SuccessOrHalt::<HALTREASON>::from(instruction_result.result) {
127        SuccessOrHalt::Success(reason) => ExecutionResult::Success {
128            reason,
129            gas: result_gas,
130            logs,
131            output,
132        },
133        SuccessOrHalt::Revert => ExecutionResult::Revert {
134            gas: result_gas,
135            logs,
136            output: output.into_data(),
137        },
138        SuccessOrHalt::Halt(reason) => {
139            // Bubble up precompile errors from context when available
140            if matches!(
141                instruction_result.result,
142                interpreter::InstructionResult::PrecompileError
143            ) {
144                if let Some(message) = context.local_mut().take_precompile_error_context() {
145                    return ExecutionResult::Halt {
146                        reason: HALTREASON::from(HaltReason::PrecompileErrorWithContext(message)),
147                        gas: result_gas,
148                        logs,
149                    };
150                }
151            }
152            ExecutionResult::Halt {
153                reason,
154                gas: result_gas,
155                logs,
156            }
157        }
158        // Only two internal return flags.
159        flag @ (SuccessOrHalt::FatalExternalError | SuccessOrHalt::Internal(_)) => {
160            panic!(
161                "Encountered unexpected internal return flag: {flag:?} with instruction result: {instruction_result:?}"
162            )
163        }
164    }
165}