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},
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(TOKEN)?.data.mark_touch();
53
54        // Load caller's account.
55        let caller_account = journal.load_account_code(tx.caller())?.data;
56
57        validate_account_nonce_and_code(
58            &mut caller_account.info,
59            tx.nonce(),
60            cfg.is_eip3607_disabled(),
61            cfg.is_nonce_check_disabled(),
62        )?;
63
64        // make changes to the account. Account balance stays the same
65        caller_account
66            .caller_initial_modification(caller_account.info.balance, tx.kind().is_call());
67
68        let account_balance_slot = erc_address_storage(tx.caller());
69
70        // load account balance
71        let account_balance = journal.sload(TOKEN, account_balance_slot)?.data;
72
73        let new_balance = calculate_caller_fee(account_balance, tx, block, cfg)?;
74
75        // store deducted balance.
76        journal.sstore(TOKEN, account_balance_slot, new_balance)?;
77
78        Ok(())
79    }
80
81    fn reimburse_caller(
82        &self,
83        evm: &mut Self::Evm,
84        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
85    ) -> Result<(), Self::Error> {
86        let context = evm.ctx();
87        let basefee = context.block().basefee() as u128;
88        let caller = context.tx().caller();
89        let effective_gas_price = context.tx().effective_gas_price(basefee);
90        let gas = exec_result.gas();
91
92        let reimbursement =
93            effective_gas_price.saturating_mul((gas.remaining() + gas.refunded() as u64) as u128);
94
95        let account_balance_slot = erc_address_storage(caller);
96
97        // load account balance
98        let account_balance = context
99            .journal_mut()
100            .sload(TOKEN, account_balance_slot)?
101            .data;
102
103        // reimburse caller
104        context.journal_mut().sstore(
105            TOKEN,
106            account_balance_slot,
107            account_balance + U256::from(reimbursement),
108        )?;
109
110        Ok(())
111    }
112
113    fn reward_beneficiary(
114        &self,
115        evm: &mut Self::Evm,
116        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
117    ) -> Result<(), Self::Error> {
118        let context = evm.ctx();
119        let tx = context.tx();
120        let beneficiary = context.block().beneficiary();
121        let basefee = context.block().basefee() as u128;
122        let effective_gas_price = tx.effective_gas_price(basefee);
123        let gas = exec_result.gas();
124
125        let coinbase_gas_price = if context.cfg().spec().into().is_enabled_in(SpecId::LONDON) {
126            effective_gas_price.saturating_sub(basefee)
127        } else {
128            effective_gas_price
129        };
130
131        let reward = coinbase_gas_price.saturating_mul(gas.used() as u128);
132
133        let beneficiary_slot = erc_address_storage(beneficiary);
134        // load account balance
135        let journal = context.journal_mut();
136        let beneficiary_balance = journal.sload(TOKEN, beneficiary_slot)?.data;
137        // reimburse caller
138        journal.sstore(
139            TOKEN,
140            beneficiary_slot,
141            beneficiary_balance + U256::from(reward),
142        )?;
143
144        Ok(())
145    }
146}