Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use custom handlers to pay for gas with erc-20 #1901

Merged
merged 20 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ members = [
"examples/database_components",
"examples/uniswap_get_reserves",
"examples/uniswap_v2_usdc_swap",
"examples/erc20_gas",
#"examples/custom_opcodes",
]
resolver = "2"
Expand Down
45 changes: 45 additions & 0 deletions examples/erc20_gas/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
[package]
name = "example-erc20-gas"
version = "0.0.0"
publish = false
authors.workspace = true
edition.workspace = true
keywords.workspace = true
license.workspace = true
repository.workspace = true
readme.workspace = true


[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[lints.rust]
unreachable_pub = "warn"
unused_must_use = "deny"
rust_2018_idioms = "deny"

[lints.rustdoc]
all = "warn"

[dependencies]
revm.workspace = true
database = { workspace = true, features = ["std", "alloydb"] }
specification.workspace = true


# tokio
tokio = { version = "1.40", features = ["rt-multi-thread", "macros"] }

# alloy
alloy-sol-types = { version = "0.8.2", default-features = false, features = [
"std",
] }
alloy-eips = "0.6"
alloy-transport-http = "0.6"
alloy-provider = "0.6"
reqwest = { version = "0.12" }
anyhow = "1.0.89"



6 changes: 6 additions & 0 deletions examples/erc20_gas/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use revm::{
context_interface::{result::{EVMError, InvalidTransaction}, JournalStateGetterDBError},
Context,
};

pub type Erc20Error = EVMError<JournalStateGetterDBError<Context>, InvalidTransaction>;
7 changes: 7 additions & 0 deletions examples/erc20_gas/src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pub mod pre_execution;
pub mod post_execution;
pub mod validation;

pub use pre_execution::Erc20PreExecution;
pub use post_execution::Erc20PostExecution;
pub use validation::Erc20Validation;
94 changes: 94 additions & 0 deletions examples/erc20_gas/src/handlers/post_execution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use crate::error::Erc20Error;
use crate::{token_operation, TREASURY};
use revm::{
context::Cfg,
context_interface::{
result::{HaltReason, ResultAndState},
Block, Transaction, TransactionGetter,
},
handler::{EthPostExecution, FrameResult},
handler_interface::PostExecutionHandler,
primitives::U256,
specification::hardfork::SpecId,
Context,
};

pub struct Erc20PostExecution {
inner: EthPostExecution<Context, Erc20Error, HaltReason>,
}

impl Erc20PostExecution {
pub fn new() -> Self {
Self {
inner: EthPostExecution::new(),
}
}
}

impl PostExecutionHandler for Erc20PostExecution {
type Context = Context;
type Error = Erc20Error;
type ExecResult = FrameResult;
type Output = ResultAndState<HaltReason>;

fn refund(
&self,
context: &mut Self::Context,
exec_result: &mut Self::ExecResult,
eip7702_refund: i64,
) {
self.inner.refund(context, exec_result, eip7702_refund)
}

fn reimburse_caller(
&self,
context: &mut Self::Context,
exec_result: &mut Self::ExecResult,
) -> Result<(), Self::Error> {
let basefee = context.block.basefee();
let caller = context.tx().common_fields().caller();
let effective_gas_price = context.tx().effective_gas_price(*basefee);
let gas = exec_result.gas();

let reimbursement =
effective_gas_price * U256::from(gas.remaining() + gas.refunded() as u64);
token_operation(context, TREASURY, caller, reimbursement).unwrap();

Ok(())
}

fn reward_beneficiary(
&self,
context: &mut Self::Context,
exec_result: &mut Self::ExecResult,
) -> Result<(), Self::Error> {
let tx = context.tx();
let beneficiary = context.block.beneficiary();
let basefee = context.block.basefee();
let effective_gas_price = tx.effective_gas_price(*basefee);
let gas = exec_result.gas();

let coinbase_gas_price = if context.cfg.spec().is_enabled_in(SpecId::LONDON) {
effective_gas_price.saturating_sub(*basefee)
} else {
effective_gas_price
};

let reward = coinbase_gas_price * U256::from(gas.spent() - gas.refunded() as u64);
token_operation(context, TREASURY, *beneficiary, reward).unwrap();

Ok(())
}

fn output(
&self,
context: &mut Self::Context,
result: Self::ExecResult,
) -> Result<Self::Output, Self::Error> {
self.inner.output(context, result)
}

fn clear(&self, context: &mut Self::Context) {
self.inner.clear(context)
}
}
52 changes: 52 additions & 0 deletions examples/erc20_gas/src/handlers/pre_execution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use crate::error::Erc20Error;
use crate::{token_operation, TREASURY};
use revm::context_interface::transaction::Eip4844Tx;
use revm::context_interface::{Block, Transaction, TransactionGetter};
use revm::{
context_interface::TransactionType, handler::EthPreExecution,
handler_interface::PreExecutionHandler, primitives::U256, Context,
};

pub struct Erc20PreExecution {
inner: EthPreExecution<Context, Erc20Error>,
}

impl Erc20PreExecution {
pub fn new() -> Self {
Self {
inner: EthPreExecution::new(),
}
}
}

impl PreExecutionHandler for Erc20PreExecution {
type Context = Context;
type Error = Erc20Error;

fn load_accounts(&self, context: &mut Self::Context) -> Result<(), Self::Error> {
self.inner.load_accounts(context)
}

fn apply_eip7702_auth_list(&self, context: &mut Self::Context) -> Result<u64, Self::Error> {
self.inner.apply_eip7702_auth_list(context)
}

fn deduct_caller(&self, context: &mut Self::Context) -> Result<(), Self::Error> {
let basefee = context.block.basefee();
let blob_price = U256::from(context.block.blob_gasprice().unwrap_or_default());
let effective_gas_price = context.tx().effective_gas_price(*basefee);

let mut gas_cost = U256::from(context.tx().common_fields().gas_limit())
.saturating_mul(effective_gas_price);

if context.tx().tx_type() == TransactionType::Eip4844 {
let blob_gas = U256::from(context.tx().eip4844().total_blob_gas());
gas_cost = gas_cost.saturating_add(blob_price.saturating_mul(blob_gas));
}

let caller = context.tx().common_fields().caller();
token_operation(context, caller, TREASURY, gas_cost)?;

Ok(())
}
}
105 changes: 105 additions & 0 deletions examples/erc20_gas/src/handlers/validation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use crate::error::Erc20Error;
use crate::keccak256;
use crate::TOKEN;
use alloy_sol_types::SolValue;
use revm::context_interface::{Transaction, TransactionGetter};
use revm::{
context::Cfg,
context_interface::{
result::{EVMError, InvalidTransaction},
transaction::Eip4844Tx,
JournalStateGetter, TransactionType,
},
handler::EthValidation,
handler_interface::ValidationHandler,
primitives::U256,
Context,
};
use std::cmp::Ordering;

pub struct Erc20Validation {
inner: EthValidation<Context, Erc20Error>,
}

impl Erc20Validation {
pub fn new() -> Self {
Self {
inner: EthValidation::new(),
}
}
}

impl ValidationHandler for Erc20Validation {
type Context = Context;
type Error = Erc20Error;

fn validate_env(&self, context: &Self::Context) -> Result<(), Self::Error> {
self.inner.validate_env(context)
}

fn validate_tx_against_state(&self, context: &mut Self::Context) -> Result<(), Self::Error> {
let caller = context.tx().common_fields().caller();
let caller_nonce = context.journal().load_account(caller)?.data.info.nonce;
let token_account = context.journal().load_account(TOKEN)?.data.clone();

if !context.cfg.is_nonce_check_disabled() {
let tx_nonce = context.tx().common_fields().nonce();
let state_nonce = caller_nonce;
match tx_nonce.cmp(&state_nonce) {
Ordering::Less => {
return Err(EVMError::Transaction(
InvalidTransaction::NonceTooLow {
tx: tx_nonce,
state: state_nonce,
}
.into(),
))
}
Ordering::Greater => {
return Err(EVMError::Transaction(
InvalidTransaction::NonceTooHigh {
tx: tx_nonce,
state: state_nonce,
}
.into(),
))
}
_ => (),
}
}

let mut balance_check = U256::from(context.tx().common_fields().gas_limit())
.checked_mul(U256::from(context.tx().max_fee()))
.and_then(|gas_cost| gas_cost.checked_add(context.tx().common_fields().value()))
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)?;

if context.tx().tx_type() == TransactionType::Eip4844 {
let tx = context.tx().eip4844();
let data_fee = tx.calc_max_data_fee();
balance_check = balance_check
.checked_add(data_fee)
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)?;
}

let account_balance_slot: U256 = keccak256((caller, U256::from(3)).abi_encode()).into();
let account_balance = token_account
.storage
.get(&account_balance_slot)
.expect("Balance slot not found")
.present_value();

if account_balance < balance_check && !context.cfg.is_balance_check_disabled() {
return Err(InvalidTransaction::LackOfFundForMaxFee {
fee: Box::new(balance_check),
balance: Box::new(account_balance),
}
.into());
};

Ok(())
}

fn validate_initial_tx_gas(&self, context: &Self::Context) -> Result<u64, Self::Error> {
self.inner.validate_initial_tx_gas(context)
}
}
Loading
Loading