example_erc20_gas/
main.rs

1//! Example of a custom handler for ERC20 gas calculation.
2//!
3//! Gas is going to be deducted from ERC20 token.
4
5#![cfg_attr(not(test), warn(unused_crate_dependencies))]
6
7use alloy_provider::{network::Ethereum, DynProvider, Provider, ProviderBuilder};
8use alloy_sol_types::SolValue;
9use anyhow::Result;
10use exec::transact_erc20evm_commit;
11use revm::{
12    context_interface::{
13        result::{InvalidHeader, InvalidTransaction},
14        ContextTr, JournalTr,
15    },
16    database::{AlloyDB, BlockId, CacheDB},
17    database_interface::WrapDatabaseAsync,
18    primitives::{address, hardfork::SpecId, keccak256, Address, TxKind, KECCAK_EMPTY, U256},
19    state::AccountInfo,
20    Context, Database, MainBuilder, MainContext,
21};
22
23pub mod exec;
24pub mod handler;
25
26type AlloyCacheDB = CacheDB<WrapDatabaseAsync<AlloyDB<Ethereum, DynProvider>>>;
27
28// Constants
29pub const TOKEN: Address = address!("a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48");
30pub const TREASURY: Address = address!("0000000000000000000000000000000000000001");
31
32#[tokio::main]
33async fn main() -> Result<()> {
34    // Initialize the Alloy provider and database
35    let rpc_url = "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27";
36    let provider = ProviderBuilder::new().connect(rpc_url).await?.erased();
37
38    let alloy_db = WrapDatabaseAsync::new(AlloyDB::new(provider, BlockId::latest())).unwrap();
39    let mut cache_db = CacheDB::new(alloy_db);
40
41    // Random empty account: From
42    let account = address!("18B06aaF27d44B756FCF16Ca20C1f183EB49111f");
43    // Random empty account: To
44    let account_to = address!("21a4B6F62E51e59274b6Be1705c7c68781B87C77");
45
46    // USDC has 6 decimals
47    let hundred_tokens = U256::from(100_000_000_000_000_000u128);
48
49    let balance_slot = erc_address_storage(account);
50    println!("Balance slot: {balance_slot}");
51    cache_db
52        .insert_account_storage(TOKEN, balance_slot, hundred_tokens * U256::from(2))
53        .unwrap();
54    cache_db.insert_account_info(
55        account,
56        AccountInfo {
57            nonce: 0,
58            balance: hundred_tokens * U256::from(2),
59            code_hash: KECCAK_EMPTY,
60            code: None,
61        },
62    );
63
64    let balance_before = balance_of(account, &mut cache_db).unwrap();
65    println!("Balance before: {balance_before}");
66
67    // Transfer 100 tokens from account to account_to
68    // Magic happens here with custom handlers
69    transfer(account, account_to, hundred_tokens, &mut cache_db)?;
70
71    let balance_after = balance_of(account, &mut cache_db)?;
72    println!("Balance after: {balance_after}");
73
74    Ok(())
75}
76
77/// Helpers
78pub fn token_operation<CTX, ERROR>(
79    context: &mut CTX,
80    sender: Address,
81    recipient: Address,
82    amount: U256,
83) -> Result<(), ERROR>
84where
85    CTX: ContextTr,
86    ERROR: From<InvalidTransaction> + From<InvalidHeader> + From<<CTX::Db as Database>::Error>,
87{
88    let sender_balance_slot = erc_address_storage(sender);
89    let sender_balance = context.journal().sload(TOKEN, sender_balance_slot)?.data;
90
91    if sender_balance < amount {
92        return Err(ERROR::from(
93            InvalidTransaction::MaxFeePerBlobGasNotSupported,
94        ));
95    }
96    // Subtract the amount from the sender's balance
97    let sender_new_balance = sender_balance.saturating_sub(amount);
98    context
99        .journal()
100        .sstore(TOKEN, sender_balance_slot, sender_new_balance)?;
101
102    // Add the amount to the recipient's balance
103    let recipient_balance_slot = erc_address_storage(recipient);
104    let recipient_balance = context.journal().sload(TOKEN, recipient_balance_slot)?.data;
105
106    let recipient_new_balance = recipient_balance.saturating_add(amount);
107    context
108        .journal()
109        .sstore(TOKEN, recipient_balance_slot, recipient_new_balance)?;
110
111    Ok(())
112}
113
114fn balance_of(address: Address, alloy_db: &mut AlloyCacheDB) -> Result<U256> {
115    let slot = erc_address_storage(address);
116    alloy_db.storage(TOKEN, slot).map_err(From::from)
117}
118
119fn transfer(from: Address, to: Address, amount: U256, cache_db: &mut AlloyCacheDB) -> Result<()> {
120    let mut ctx = Context::mainnet()
121        .with_db(cache_db)
122        .modify_cfg_chained(|cfg| {
123            cfg.spec = SpecId::CANCUN;
124        })
125        .modify_tx_chained(|tx| {
126            tx.caller = from;
127            tx.kind = TxKind::Call(to);
128            tx.value = amount;
129            tx.gas_price = 2;
130        })
131        .modify_block_chained(|b| {
132            b.basefee = 1;
133        })
134        .build_mainnet();
135
136    transact_erc20evm_commit(&mut ctx).unwrap();
137
138    Ok(())
139}
140
141pub fn erc_address_storage(address: Address) -> U256 {
142    keccak256((address, U256::from(4)).abi_encode()).into()
143}