example_erc20_gas/
handler.rs

1use revm::{
2    context::Cfg,
3    context_interface::{result::HaltReason, Block, ContextTr, JournalTr, Transaction},
4    handler::{
5        pre_execution::{calculate_caller_fee, validate_account_nonce_and_code_with_components},
6        EvmTr, EvmTrError, FrameResult, FrameTr, Handler,
7    },
8    interpreter::interpreter_action::FrameInit,
9    primitives::{hardfork::SpecId, U256},
10    state::EvmState,
11};
12
13use crate::{erc_address_storage, TOKEN};
14
15/// Custom handler that implements ERC20 token gas payment.
16/// Instead of paying gas in ETH, transactions pay gas using ERC20 tokens.
17/// The tokens are transferred from the transaction sender to a treasury address.
18#[derive(Debug)]
19pub struct Erc20MainnetHandler<EVM, ERROR, FRAME> {
20    _phantom: core::marker::PhantomData<(EVM, ERROR, FRAME)>,
21}
22
23impl<CTX, ERROR, FRAME> Erc20MainnetHandler<CTX, ERROR, FRAME> {
24    /// Creates a new ERC20 gas payment handler
25    pub fn new() -> Self {
26        Self {
27            _phantom: core::marker::PhantomData,
28        }
29    }
30}
31
32impl<EVM, ERROR, FRAME> Default for Erc20MainnetHandler<EVM, ERROR, FRAME> {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl<EVM, ERROR, FRAME> Handler for Erc20MainnetHandler<EVM, ERROR, FRAME>
39where
40    EVM: EvmTr<Context: ContextTr<Journal: JournalTr<State = EvmState>>, Frame = FRAME>,
41    FRAME: FrameTr<FrameResult = FrameResult, FrameInit = FrameInit>,
42    ERROR: EvmTrError<EVM>,
43{
44    type Evm = EVM;
45    type Error = ERROR;
46    type HaltReason = HaltReason;
47
48    fn validate_against_state_and_deduct_caller(&self, evm: &mut Self::Evm) -> Result<(), ERROR> {
49        let (block, tx, cfg, journal, _, _) = evm.ctx_mut().all_mut();
50
51        // load TOKEN contract
52        journal.load_account_mut(TOKEN)?.touch();
53
54        // Load caller's account.
55        let mut caller_account = journal.load_account_with_code_mut(tx.caller())?;
56
57        validate_account_nonce_and_code_with_components(&caller_account.info, tx, cfg)?;
58
59        // make changes to the account. Account balance stays the same
60        caller_account.touch();
61        if tx.kind().is_call() {
62            caller_account.bump_nonce();
63        }
64
65        let account_balance_slot = erc_address_storage(tx.caller());
66
67        // load account balance
68        let account_balance = journal.sload(TOKEN, account_balance_slot)?.data;
69
70        let new_balance = calculate_caller_fee(account_balance, tx, block, cfg)?;
71
72        // store deducted balance.
73        journal.sstore(TOKEN, account_balance_slot, new_balance)?;
74
75        Ok(())
76    }
77
78    fn reimburse_caller(
79        &self,
80        evm: &mut Self::Evm,
81        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
82    ) -> Result<(), Self::Error> {
83        let context = evm.ctx();
84        let basefee = context.block().basefee() as u128;
85        let caller = context.tx().caller();
86        let effective_gas_price = context.tx().effective_gas_price(basefee);
87        let gas = exec_result.gas();
88
89        let reimbursement =
90            effective_gas_price.saturating_mul((gas.remaining() + gas.refunded() as u64) as u128);
91
92        let account_balance_slot = erc_address_storage(caller);
93
94        // load account balance
95        let account_balance = context
96            .journal_mut()
97            .sload(TOKEN, account_balance_slot)?
98            .data;
99
100        // reimburse caller
101        context.journal_mut().sstore(
102            TOKEN,
103            account_balance_slot,
104            account_balance + U256::from(reimbursement),
105        )?;
106
107        Ok(())
108    }
109
110    fn reward_beneficiary(
111        &self,
112        evm: &mut Self::Evm,
113        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
114    ) -> Result<(), Self::Error> {
115        let context = evm.ctx();
116        let tx = context.tx();
117        let beneficiary = context.block().beneficiary();
118        let basefee = context.block().basefee() as u128;
119        let effective_gas_price = tx.effective_gas_price(basefee);
120        let gas = exec_result.gas();
121
122        let coinbase_gas_price = if context.cfg().spec().into().is_enabled_in(SpecId::LONDON) {
123            effective_gas_price.saturating_sub(basefee)
124        } else {
125            effective_gas_price
126        };
127
128        let reward = coinbase_gas_price.saturating_mul(gas.used() as u128);
129
130        let beneficiary_slot = erc_address_storage(beneficiary);
131        // load account balance
132        let journal = context.journal_mut();
133        let beneficiary_balance = journal.sload(TOKEN, beneficiary_slot)?.data;
134        // reimburse caller
135        journal.sstore(
136            TOKEN,
137            beneficiary_slot,
138            beneficiary_balance + U256::from(reward),
139        )?;
140
141        Ok(())
142    }
143}