example_erc20_gas/
handler.rs

1use revm::{
2    context::{journaled_state::account::JournaledAccountTr, 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.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        drop(caller_account); // Drop caller_account to avoid borrow checker issues.
68
69        // load account balance
70        let account_balance = journal.sload(TOKEN, account_balance_slot)?.data;
71
72        let new_balance = calculate_caller_fee(account_balance, tx, block, cfg)?;
73
74        // store deducted balance.
75        journal.sstore(TOKEN, account_balance_slot, new_balance)?;
76
77        Ok(())
78    }
79
80    fn reimburse_caller(
81        &self,
82        evm: &mut Self::Evm,
83        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
84    ) -> Result<(), Self::Error> {
85        let context = evm.ctx();
86        let basefee = context.block().basefee() as u128;
87        let caller = context.tx().caller();
88        let effective_gas_price = context.tx().effective_gas_price(basefee);
89        let gas = exec_result.gas();
90
91        let reimbursement =
92            effective_gas_price.saturating_mul((gas.remaining() + gas.refunded() as u64) as u128);
93
94        let account_balance_slot = erc_address_storage(caller);
95
96        // load account balance
97        let account_balance = context
98            .journal_mut()
99            .sload(TOKEN, account_balance_slot)?
100            .data;
101
102        // reimburse caller
103        context.journal_mut().sstore(
104            TOKEN,
105            account_balance_slot,
106            account_balance + U256::from(reimbursement),
107        )?;
108
109        Ok(())
110    }
111
112    fn reward_beneficiary(
113        &self,
114        evm: &mut Self::Evm,
115        exec_result: &mut <<Self::Evm as EvmTr>::Frame as FrameTr>::FrameResult,
116    ) -> Result<(), Self::Error> {
117        let context = evm.ctx();
118        let tx = context.tx();
119        let beneficiary = context.block().beneficiary();
120        let basefee = context.block().basefee() as u128;
121        let effective_gas_price = tx.effective_gas_price(basefee);
122        let gas = exec_result.gas();
123
124        let coinbase_gas_price = if context.cfg().spec().into().is_enabled_in(SpecId::LONDON) {
125            effective_gas_price.saturating_sub(basefee)
126        } else {
127            effective_gas_price
128        };
129
130        let reward = coinbase_gas_price.saturating_mul(gas.used() as u128);
131
132        let beneficiary_slot = erc_address_storage(beneficiary);
133        // load account balance
134        let journal = context.journal_mut();
135        let beneficiary_balance = journal.sload(TOKEN, beneficiary_slot)?.data;
136        // reimburse caller
137        journal.sstore(
138            TOKEN,
139            beneficiary_slot,
140            beneficiary_balance + U256::from(reward),
141        )?;
142
143        Ok(())
144    }
145}