diff --git a/crates/revm/Cargo.toml b/crates/revm/Cargo.toml index 735efc44..2c0855cd 100644 --- a/crates/revm/Cargo.toml +++ b/crates/revm/Cargo.toml @@ -35,6 +35,7 @@ thiserror.workspace = true [dev-dependencies] eyre.workspace = true alloy-primitives = { workspace = true, features = ["rand"] } +revm = { workspace = true, features = ["optional_no_base_fee", "optional_priority_fee_check"] } [features] reth = ["dep:reth-storage-api"] diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 4a701649..967d47d1 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -278,10 +278,15 @@ where validation::validate_env::<_, Self::Error>(evm.ctx())?; // MorphTx maps to `TransactionType::Custom`, so revm's standard path - // does not enforce EIP-1559 fee-cap rules. Those rules are independent - // of which asset ultimately pays the fee, matching Morph geth's preCheck. - if evm.ctx_ref().tx().is_morph_tx() && !evm.ctx_ref().cfg().is_fee_charge_disabled() { - let base_fee = Some(evm.ctx_ref().block().basefee() as u128); + // does not enforce EIP-1559 fee-cap rules. Match upstream revm's + // `Eip1559` branch: gate base-fee checks on `is_base_fee_check_disabled()` + // and priority-fee checks on `is_priority_fee_check_disabled()`, + // independent of `is_fee_charge_disabled()`. + if evm.ctx_ref().tx().is_morph_tx() { + let cfg = evm.ctx_ref().cfg(); + let base_fee = (!cfg.is_base_fee_check_disabled()) + .then(|| evm.ctx_ref().block().basefee() as u128); + let disable_priority_fee_check = cfg.is_priority_fee_check_disabled(); validation::validate_priority_fee_tx( evm.ctx_ref().tx().max_fee_per_gas(), evm.ctx_ref() @@ -289,7 +294,7 @@ where .max_priority_fee_per_gas() .unwrap_or_default(), base_fee, - evm.ctx_ref().cfg().is_priority_fee_check_disabled(), + disable_priority_fee_check, )?; } @@ -1685,6 +1690,93 @@ mod tests { )); } + #[test] + fn validate_env_morph_tx_honors_base_fee_and_priority_fee_flags() { + let make_evm = |disable_fee_charge: bool, + disable_base_fee: bool, + disable_priority_fee_check: bool, + max_fee: u128, + max_tip: u128| { + let mut evm = MorphEvm::new( + MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), + NoOpInspector, + ); + evm.cfg.disable_fee_charge = disable_fee_charge; + evm.cfg.disable_base_fee = disable_base_fee; + evm.cfg.disable_priority_fee_check = disable_priority_fee_check; + evm.block = MorphBlockEnv { + inner: BlockEnv { + basefee: 100, + ..Default::default() + }, + }; + evm.tx = MorphTxEnv { + inner: TxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 21_000, + gas_price: max_fee, + gas_priority_fee: Some(max_tip), + kind: TxKind::Call(Address::ZERO), + ..Default::default() + }, + fee_token_id: Some(1), + ..Default::default() + }; + evm + }; + + // 1. `disable_fee_charge = true` must NOT disable priority-fee or base-fee checks. + let mut evm = make_evm(true, false, false, 100, 200); + assert!(matches!( + validate_env_of(&mut evm), + Err(EVMError::Transaction( + MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::PriorityFeeGreaterThanMaxFee + ) + )) + )); + + let mut evm = make_evm(true, false, false, 50, 10); + assert!(matches!( + validate_env_of(&mut evm), + Err(EVMError::Transaction( + MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::GasPriceLessThanBasefee + ) + )) + )); + + let mut evm = make_evm(true, false, false, 100, 50); + assert!(validate_env_of(&mut evm).is_ok()); + + // 2. `disable_base_fee = true` skips base-fee check independently of `disable_fee_charge`, + // while still enforcing `max_priority_fee <= max_fee`. + for disable_fee_charge in [false, true] { + let mut evm = make_evm(disable_fee_charge, true, false, 0, 0); + assert!( + validate_env_of(&mut evm).is_ok(), + "disable_fee_charge={disable_fee_charge}: base fee check must be skipped" + ); + + let mut evm = make_evm(disable_fee_charge, true, false, 100, 200); + assert!( + matches!( + validate_env_of(&mut evm), + Err(EVMError::Transaction( + MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::PriorityFeeGreaterThanMaxFee + ) + )) + ), + "disable_fee_charge={disable_fee_charge}: priority fee > max fee must still reject" + ); + } + + // 3. `disable_priority_fee_check = true` allows `max_priority_fee > max_fee`. + let mut evm = make_evm(true, true, true, 100, 200); + assert!(validate_env_of(&mut evm).is_ok()); + } + // ========================================================================= // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= diff --git a/crates/revm/src/token_fee.rs b/crates/revm/src/token_fee.rs index 43b17022..08aab52b 100644 --- a/crates/revm/src/token_fee.rs +++ b/crates/revm/src/token_fee.rs @@ -84,7 +84,7 @@ impl TokenRegistryEntry { } /// Reject registry entries that cannot produce a valid token-denominated fee. - pub(crate) fn ensure_usable(self, token_id: u16) -> Result { + pub fn ensure_usable(self, token_id: u16) -> Result { if !self.is_active { return Err(MorphInvalidTransaction::TokenNotActive(token_id)); } diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index b1141e31..c3491cc6 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -10,9 +10,9 @@ use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; use alloy_evm::call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}; -use alloy_primitives::U256; +use alloy_primitives::{Address, B256, U256, U512}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; -use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; +use morph_revm::{L1BlockInfo, MorphEvmEnv, MorphTxExt, TokenFeeInfo, TokenRegistryEntry}; use reth_evm::{EvmEnvFor, TxEnvFor}; use reth_provider::ChainSpecProvider; use reth_rpc_eth_api::{ @@ -20,7 +20,62 @@ use reth_rpc_eth_api::{ helpers::{Call, EthCall, estimate::EstimateCall}, }; use reth_rpc_eth_types::EthApiError; -use revm::{Database, context::Transaction as RevmTransaction}; +use revm::{ + Database, + bytecode::Bytecode, + context::{Transaction as RevmTransaction, result::EVMError}, + database_interface::DBErrorMarker, + state::AccountInfo, +}; + +/// Wrapper turning any [`EthApiError`] produced by an RPC database into a +/// `revm::database_interface::DBErrorMarker` error for `alloy_evm::Database`. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +struct EthApiDbError(EthApiError); + +impl DBErrorMarker for EthApiDbError {} + +/// Bridges `revm::Database>` (which lacks `Debug` and +/// `DBErrorMarker`) to `alloy_evm::Database` so `TokenRegistryEntry::load_for_caller` +/// can execute call-mode `balanceOf` directly against the RPC state DB. +struct EthApiDbAdapter<'a, DB>(&'a mut DB); + +impl core::fmt::Debug for EthApiDbAdapter<'_, DB> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("EthApiDbAdapter").finish_non_exhaustive() + } +} + +impl Database for EthApiDbAdapter<'_, DB> +where + DB: Database, + DB::Error: Into, +{ + type Error = EthApiDbError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + self.0.basic(address).map_err(|e| EthApiDbError(e.into())) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + self.0 + .code_by_hash(code_hash) + .map_err(|e| EthApiDbError(e.into())) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + self.0 + .storage(address, index) + .map_err(|e| EthApiDbError(e.into())) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.0 + .block_hash(number) + .map_err(|e| EthApiDbError(e.into())) + } +} impl EthCall for MorphEthApi where @@ -89,14 +144,16 @@ where let l1_fee = self.estimate_l1_fee(&mut db, evm_env, tx_env)?; if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { - return self.caller_gas_allowance_with_token( + return load_caller_token_gas_allowance( &mut db, + evm_env, tx_env.caller(), tx_env.value(), l1_fee, fee_token_id, tx_env.fee_limit, tx_env.gas_price(), + self.eth_api().gas_cap(), ); } @@ -162,57 +219,82 @@ where Ok(l1_info.calculate_tx_l1_cost(rlp_bytes, hardfork)) } +} - /// Allowance for MorphTx ERC20 fee-token callers: cap by token - /// balance, not by ETH balance. - #[allow(clippy::too_many_arguments)] - fn caller_gas_allowance_with_token( - &self, - db: &mut DB, - caller: alloy_primitives::Address, - value: U256, - l1_fee: U256, - fee_token_id: u16, - fee_limit: Option, - gas_price: u128, - ) -> Result - where - DB: revm::Database, - DB::Error: Into, - { - let token_fee_info = TokenFeeInfo::load_storage_only(db, fee_token_id, caller) - .map_err(|_| MorphEthApiError::InvalidFeeToken)? - .ok_or(MorphEthApiError::InvalidFeeToken)?; +/// Loads token registry metadata, validates token usability before executing any +/// call-mode `balanceOf`, resolves the caller's token balance via +/// [`TokenRegistryEntry::load_for_caller`], and computes the caller's gas allowance. +/// +/// Database errors from registry reads, account reads, or call-mode `balanceOf` +/// execution are propagated as [`MorphEthApiError::Eth`] rather than being masked +/// as [`MorphEthApiError::InvalidFeeToken`]. +#[allow(clippy::too_many_arguments)] +fn load_caller_token_gas_allowance( + db: &mut DB, + evm_env: &MorphEvmEnv, + caller: Address, + value: U256, + l1_fee: U256, + fee_token_id: u16, + fee_limit: Option, + gas_price: u128, + gas_cap: u64, +) -> Result +where + DB: revm::Database, + DB::Error: Into, +{ + let mut adapter = EthApiDbAdapter(db); + let entry = TokenRegistryEntry::load(&mut adapter, fee_token_id) + .map_err(|EthApiDbError(eth_err)| MorphEthApiError::Eth(eth_err))? + .ok_or(MorphEthApiError::InvalidFeeToken)?; + // Reject inactive or misconfigured (`price_ratio == 0` / `scale == 0`) tokens + // before invoking call-mode `balanceOf`, avoiding an unnecessary EVM execution. + let entry = entry + .ensure_usable(fee_token_id) + .map_err(|_| MorphEthApiError::InvalidFeeToken)?; + + // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. + // Checking `value` before call-mode `balanceOf` avoids spinning up an EVM + // when the caller cannot even cover `tx.value`. + let eth_balance = adapter + .basic(caller) + .map_err(|EthApiDbError(eth_err)| MorphEthApiError::Eth(eth_err))? + .map(|acc| acc.balance) + .unwrap_or_default(); + if eth_balance < value { + return Err(MorphEthApiError::InsufficientFundsForTransfer); + } - // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. - let eth_balance = db - .basic(caller) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|acc| acc.balance) - .unwrap_or_default(); + let token_fee_info = entry + .load_for_caller(&mut adapter, caller, evm_env) + .map_err(|err| match err { + EVMError::Database(EthApiDbError(eth_err)) => MorphEthApiError::Eth(eth_err), + _ => MorphEthApiError::InvalidFeeToken, + })?; - token_gas_allowance( - eth_balance, - value, - &token_fee_info, - l1_fee, - fee_limit, - gas_price, - self.eth_api().gas_cap(), - ) - } + token_gas_allowance( + eth_balance, + value, + &token_fee_info, + l1_fee, + fee_limit, + gas_price, + gas_cap, + ) } /// Compute the gas allowance for a MorphTx fee-token caller. /// -/// Pure function over the inputs `caller_gas_allowance_with_token` would -/// load from the database, factored out so the affordability and bounding -/// logic can be unit-tested without an EVM/DB stack. +/// Pure function over the inputs `load_caller_token_gas_allowance` loads from +/// the database, factored out so the affordability and bounding logic can be +/// unit-tested without an EVM/DB stack. /// /// The `gas_cap` argument is the per-call RPC ceiling (`EthApiNodeBackend::gas_cap()`), -/// only consumed in EVM-call mode: as the no-`fee_limit` fallback (instead of `u64::MAX`) -/// and as the clamp on a user-supplied `fee_limit`. See the in-body comment for the security -/// rationale. +/// normalized so `0` means unlimited (`u64::MAX`) to match upstream reth. In call mode +/// (`balance_slot.is_none()`), the resulting gas allowance is additionally clamped by +/// `effective_gas_cap` so a call-mode token reporting a huge `balanceOf` cannot bypass +/// an operator-configured `--rpc.gascap`. fn token_gas_allowance( eth_balance: U256, value: U256, @@ -233,53 +315,42 @@ fn token_gas_allowance( return Err(MorphEthApiError::InsufficientFundsForTransfer); } - // Determine the token-denominated affordability cap. - // - // - Slot mode (`balance_slot.is_some()`): RPC reads balance directly - // from token storage; cap by `min(balance, fee_limit)`. The - // trusted balance is the natural ceiling. - // - EVM-call mode (`balance_slot.is_none()`): RPC cannot resolve the - // balance without spinning up an EVM (the handler does that at real - // execution via `load_token_fee_info`). On the estimateGas path - // `disable_fee_charge=true` short-circuits the handler's check, so - // there is no natural balance ceiling — we MUST enforce `gas_cap` - // here, matching `eth_call`'s effective ceiling. Trusting a - // user-supplied `fee_limit` alone would let `fee_limit = U256::MAX` - // bypass the operator-configured `--rpc.gascap`. - let (limit, clamp_to_gas_cap) = match (token_fee_info.balance_slot, fee_limit) { - (Some(_), Some(limit)) if !limit.is_zero() => (token_fee_info.balance.min(limit), false), - (Some(_), _) => (token_fee_info.balance, false), - (None, Some(limit)) if !limit.is_zero() => (limit, true), - (None, _) => return Ok(gas_cap), - }; - + // Both slot-mode and call-mode carry the caller's resolved token balance + // (`load_for_caller`), so both use `effective_fee_limit`: `min(balance, fee_limit)` + // when `fee_limit > 0`, or `balance` when `fee_limit` is omitted / zero. + let limit = token_fee_info.effective_fee_limit(fee_limit.unwrap_or_default()); let allowance = gas_allowance_from_token_limit(limit, l1_fee, token_fee_info, gas_price)?; - Ok(if clamp_to_gas_cap { - allowance.min(gas_cap) + + if token_fee_info.balance_slot.is_none() { + let effective_gas_cap = if gas_cap == 0 { u64::MAX } else { gas_cap }; + Ok(allowance.min(effective_gas_cap)) } else { - allowance - }) + Ok(allowance) + } } /// Convert a token-denominated affordability cap into a gas allowance. /// -/// Subtracts the L1 fee (converted to tokens) from `limit_token`, then -/// converts the remaining token budget back to ETH and divides by -/// `gas_price`. Returns `InsufficientFundsForL1Fee` if the L1 fee swallows -/// the entire limit, matching the semantics surfaced for the ETH path. +/// Computes the exact ETH-space budget `max_eth = floor(limit_token * price_ratio / scale)` +/// (the exact inverse of `ceil((l2_fee + l1_fee) * scale / price_ratio) <= limit_token`), +/// avoiding double-rounding the L1 fee in token space. Returns +/// `InsufficientFundsForL1Fee` when `max_eth < l1_fee` or when a non-zero L1 fee leaves +/// zero ETH for L2 execution gas; when `l1_fee == 0 && max_eth == 0`, returns `Ok(0)` +/// (or `u64::MAX` when `gas_price == 0`) rather than falsely reporting an L1 fee shortfall. fn gas_allowance_from_token_limit( limit_token: U256, l1_fee: U256, token_info: &TokenFeeInfo, gas_price: u128, ) -> Result { - let l1_fee_in_token = token_info.eth_to_token_amount(l1_fee); - if l1_fee_in_token >= limit_token { + let max_eth = + token_amount_to_eth(limit_token, token_info).ok_or(MorphEthApiError::InvalidFeeToken)?; + let Some(available_eth) = max_eth.checked_sub(l1_fee) else { + return Err(MorphEthApiError::InsufficientFundsForL1Fee); + }; + if available_eth.is_zero() && !l1_fee.is_zero() { return Err(MorphEthApiError::InsufficientFundsForL1Fee); } - let available_token = limit_token - l1_fee_in_token; - let available_eth = token_amount_to_eth(available_token, token_info) - .ok_or(MorphEthApiError::InvalidFeeToken)?; Ok(gas_allowance_from_balance(available_eth, gas_price)) } @@ -318,7 +389,9 @@ fn token_amount_to_eth(token_amount: U256, info: &TokenFeeInfo) -> Option if info.price_ratio.is_zero() || info.scale.is_zero() { return None; } - Some(token_amount.saturating_mul(info.price_ratio) / info.scale) + let numerator = U512::from(token_amount) * U512::from(info.price_ratio); + let quotient = numerator / U512::from(info.scale); + Some(quotient.saturating_to::()) } #[cfg(test)] @@ -411,11 +484,11 @@ mod tests { } } - /// EVM-call mode with a user-supplied `fee_limit` that covers the L1 fee + /// EVM-call mode with a user-supplied `fee_limit` bounded by `balanceOf(caller)` /// must return the remaining-budget gas, never `u64::MAX`. #[test] fn token_evm_call_mode_with_fee_limit_uses_user_budget() { - let token = token_1to1(None, U256::ZERO); + let token = token_1to1(None, U256::from(1_000u64)); let allowance = token_gas_allowance( /* eth_balance */ U256::from(1u64), /* value */ U256::ZERO, @@ -425,16 +498,34 @@ mod tests { /* gas_price */ 1, /* gas_cap */ 50_000_000, ) - .expect("fee_limit covers L1 fee with 100 wei to spare"); - // (110 - 10) / 1 = 100 gas + .expect("fee_limit and balance cover L1 fee with 100 wei to spare"); + // (min(1000, 110) - 10) / 1 = 100 gas assert_eq!(allowance, 100); } + /// EVM-call mode with zero caller balance cannot bypass affordability by + /// specifying a large `fee_limit`. + #[test] + fn token_evm_call_mode_zero_balance_rejects_even_with_large_fee_limit() { + let token = token_1to1(None, U256::ZERO); + let err = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + /* l1_fee */ U256::from(10u64), + /* fee_limit */ Some(U256::from(10_000u64)), + 1, + 50_000_000, + ) + .expect_err("zero balance cannot cover non-zero L1 fee"); + assert!(matches!(err, MorphEthApiError::InsufficientFundsForL1Fee)); + } + /// EVM-call mode + `fee_limit` ≤ L1 fee: surface `InsufficientFundsForL1Fee` /// rather than silently capping at zero. #[test] fn token_evm_call_mode_l1_fee_swallows_limit_returns_clear_error() { - let token = token_1to1(None, U256::ZERO); + let token = token_1to1(None, U256::from(1_000u64)); let err = token_gas_allowance( U256::ZERO, U256::ZERO, @@ -448,38 +539,52 @@ mod tests { assert!(matches!(err, MorphEthApiError::InsufficientFundsForL1Fee)); } - /// EVM-call mode without a `fee_limit` must cap at the per-call `gas_cap`, - /// never `u64::MAX` (which lets estimateGas binary-search 25× the - /// block_gas_limit of free EVM work). + /// EVM-call mode without a `fee_limit` uses the resolved token balance and + /// still clamps to the per-call `gas_cap` (never `u64::MAX`). #[test] - fn token_evm_call_mode_without_fee_limit_falls_back_to_gas_cap() { - let token = token_1to1(None, U256::ZERO); + fn token_evm_call_mode_without_fee_limit_uses_balance_and_clamps_to_gas_cap() { let cap = 5_000_000u64; + + // Large resolved balance with no fee_limit clamps to `gas_cap`. + let rich_token = token_1to1(None, U256::from(100_000_000u64)); let allowance = token_gas_allowance( U256::ZERO, U256::ZERO, - &token, + &rich_token, /* l1_fee */ U256::from(123u64), /* fee_limit */ None, 1, cap, ) - .expect("no fee_limit must fall back to gas_cap, not u64::MAX"); + .expect("large balance without fee_limit must clamp to gas_cap"); assert_eq!(allowance, cap, "must equal gas_cap, not u64::MAX"); - // Same with explicit Some(0), which the production code treats as - // "no usable cap" via the `if !limit.is_zero()` guard. + // Explicit Some(0) behaves identically to None (whole balance, clamped to gas_cap). let allowance = token_gas_allowance( U256::ZERO, U256::ZERO, - &token, + &rich_token, U256::from(123u64), Some(U256::ZERO), 1, cap, ) - .expect("Some(0) fee_limit must fall back to gas_cap"); + .expect("Some(0) fee_limit must use whole balance clamped to gas_cap"); assert_eq!(allowance, cap); + + // Smaller resolved balance caps below `gas_cap`. + let small_token = token_1to1(None, U256::from(500u64)); + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &small_token, + U256::from(123u64), + None, + 1, + cap, + ) + .expect("balance of 500 covers L1 fee 123"); + assert_eq!(allowance, 377); } /// Slot-mode regression: `min(balance, fee_limit)` budget; gas_cap unused. @@ -566,11 +671,11 @@ mod tests { } /// EVM-call mode with an absurd user-supplied `fee_limit` (e.g. - /// `U256::MAX`) must clamp to `gas_cap`, never bypass the - /// operator-configured `--rpc.gascap < block_gas_limit`. + /// `U256::MAX`) and huge resolved balance must clamp to `gas_cap`, + /// never bypass the operator-configured `--rpc.gascap < block_gas_limit`. #[test] fn token_evm_call_mode_huge_fee_limit_clamps_to_gas_cap() { - let token = token_1to1(None, U256::ZERO); + let token = token_1to1(None, U256::MAX); let cap = 5_000_000u64; let allowance = token_gas_allowance( U256::ZERO, @@ -585,6 +690,287 @@ mod tests { assert_eq!(allowance, cap, "must clamp to gas_cap, not u64::MAX"); } + /// `gas_cap == 0` means unlimited in upstream reth and must normalize to `u64::MAX` + /// rather than clamping call-mode token allowance to `0`. + #[test] + fn token_evm_call_mode_gas_cap_zero_means_unlimited() { + let token = token_1to1(None, U256::from(1_000u64)); + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + /* l1_fee */ U256::from(50u64), + /* fee_limit */ None, + /* gas_price */ 1, + /* gas_cap == 0 (unlimited) */ 0, + ) + .expect("gas_cap == 0 must not clamp to 0"); + assert_eq!(allowance, 950); + + let huge_token = token_1to1(None, U256::MAX); + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &huge_token, + U256::ZERO, + Some(U256::MAX), + 1, + 0, + ) + .expect("gas_cap == 0 with huge balance must saturate to u64::MAX"); + assert_eq!(allowance, u64::MAX); + } + + /// When `l1_fee == 0` and `limit == 0`, return `Ok(0)` instead of falsely + /// surfacing `InsufficientFundsForL1Fee`. + #[test] + fn token_zero_limit_with_zero_l1_fee_returns_zero_allowance() { + let token = token_1to1(None, U256::ZERO); + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + /* l1_fee */ U256::ZERO, + /* fee_limit */ None, + /* gas_price */ 1, + 50_000_000, + ) + .expect("zero l1_fee with zero balance must return Ok(0), not InsufficientFundsForL1Fee"); + assert_eq!(allowance, 0); + + // With gas_price == 0 and l1_fee == 0, zero tokens still allow gas up to gas_cap. + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + U256::ZERO, + None, + 0, + 50_000_000, + ) + .expect("zero gas_price and zero l1_fee must succeed"); + assert_eq!(allowance, 50_000_000); + } + + /// Tight `feeLimit` on a 6-decimal USDT/USDC-like token must avoid + /// double-rounding the L1 fee in token space. + /// + /// With `scale = 10^6` and `price_ratio = 333_333_333_333_333` (~1 ETH = 3000 USDT), + /// 1 raw token unit covers `floor(1 * price_ratio / scale) = 333_333_333` wei. + /// A 100_000_000 wei L1 fee rounds up to 1 token on its own, so the old + /// `limit - ceil(l1_fee)` path falsely rejected `limit = 1` with + /// `InsufficientFundsForL1Fee` even though 233_333_333 wei of L2 gas budget remain. + #[test] + fn token_tight_fee_limit_avoids_l1_fee_double_rounding() { + let usdt = TokenFeeInfo { + decimals: 6, + price_ratio: U256::from(333_333_333_333_333u64), + scale: U256::from(1_000_000u64), + balance: U256::from(1u64), + ..token_1to1(None, U256::from(1u64)) + }; + let l1_fee = U256::from(100_000_000u64); + let gas_price = 1_000u128; + + // Sanity check: the old code would have rejected because ceil(l1_fee) == 1 == limit. + assert_eq!(usdt.eth_to_token_amount(l1_fee), U256::from(1u64)); + + let allowance = gas_allowance_from_token_limit(U256::from(1u64), l1_fee, &usdt, gas_price) + .expect("1 raw USDT covers 100M wei L1 fee + 233_333 gas at 1000 wei/gas"); + assert_eq!(allowance, 233_333); + + // Exact roundtrip verification: `allowance` gas settles within 1 token, + // while `allowance + 1` gas requires 2 tokens. + assert_eq!( + usdt.eth_to_token_amount(l1_fee + U256::from(allowance) * U256::from(gas_price)), + U256::from(1u64) + ); + assert_eq!( + usdt.eth_to_token_amount(l1_fee + U256::from(allowance + 1) * U256::from(gas_price)), + U256::from(2u64) + ); + + // Exact boundary: `max_eth == l1_fee` with non-zero L1 fee leaves 0 wei for L2 gas -> Err. + let exact_max_eth = U256::from(333_333_333u64); + assert!(matches!( + gas_allowance_from_token_limit(U256::from(1u64), exact_max_eth, &usdt, gas_price), + Err(MorphEthApiError::InsufficientFundsForL1Fee) + )); + // `max_eth < l1_fee` -> Err. + assert!(matches!( + gas_allowance_from_token_limit( + U256::from(1u64), + exact_max_eth + U256::from(1u64), + &usdt, + gas_price + ), + Err(MorphEthApiError::InsufficientFundsForL1Fee) + )); + + // U512 intermediate avoids premature U256 overflow when `limit * price_ratio > U256::MAX`. + let unit_scaled = TokenFeeInfo { + price_ratio: U256::from(1_000_000_000_000_000_000u64), + scale: U256::from(1_000_000_000_000_000_000u64), + ..token_1to1(None, U256::ZERO) + }; + let half_max = U256::MAX >> 1; + assert_eq!(token_amount_to_eth(half_max, &unit_scaled), Some(half_max)); + } + + /// Full `load_caller_token_gas_allowance` integration against an in-memory DB: + /// verifies call-mode `balanceOf(caller)` resolution with and without `fee_limit`, + /// fail-fast usability checks before EVM execution (`is_active`, `price_ratio`, `scale`), + /// and DB error propagation as `MorphEthApiError::Eth` instead of `InvalidFeeToken`. + #[test] + fn load_caller_token_gas_allowance_call_mode_balance_usability_and_db_errors() { + use alloy_primitives::{Bytes, address, keccak256}; + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{L2_TOKEN_REGISTRY_ADDRESS, MorphBlockEnv, compute_mapping_slot}; + use revm::{ + context::CfgEnv, + database::{CacheDB, EmptyDB}, + }; + + let caller = address!("1000000000000000000000000000000000000001"); + let token = address!("5300000000000000000000000000000000000042"); + let evm_env = MorphEvmEnv::new( + CfgEnv::new_with_spec(MorphHardfork::Emerald), + MorphBlockEnv::default(), + ); + + let build_call_mode_db = |balance: u64, is_active: bool, price_ratio: u64, scale: u64| { + let mut db = CacheDB::new(EmptyDB::default()); + let mut key = [0u8; 32]; + key[30..].copy_from_slice(&1u16.to_be_bytes()); + let base = compute_mapping_slot(U256::from(151), &key); + let mut packed = [0u8; 32]; + packed[30] = 18; + packed[31] = u8::from(is_active); + for (slot, val) in [ + (base, U256::from_be_bytes(token.into_word().0)), + // balanceSlot == 0 selects call mode. + (base + U256::from(1), U256::ZERO), + (base + U256::from(2), U256::from_be_bytes(packed)), + (base + U256::from(3), U256::from(scale)), + ( + compute_mapping_slot(U256::from(153), &key), + U256::from(price_ratio), + ), + ] { + db.insert_account_storage(L2_TOKEN_REGISTRY_ADDRESS, slot, val) + .unwrap(); + } + // Minimal `balanceOf(address)` returning storage[0]. + let code = Bytes::from_static(&[0x60, 0x00, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]); + db.insert_account_info( + token, + AccountInfo { + code_hash: keccak256(code.as_ref()), + code: Some(Bytecode::new_raw(code)), + ..Default::default() + }, + ); + db.insert_account_storage(token, U256::ZERO, U256::from(balance)) + .unwrap(); + db + }; + + let eval = |balance: u64, fee_limit: Option| { + let mut db = build_call_mode_db(balance, true, 1, 1); + load_caller_token_gas_allowance( + &mut db, + &evm_env, + caller, + U256::ZERO, + U256::from(50u64), + 1, + fee_limit, + 1, + 50_000_000, + ) + }; + + // 1-4. Call-mode `balanceOf` resolution, `fee_limit` capping, and L1 fee shortfall. + assert_eq!(eval(500, None).unwrap(), 450); + assert_eq!(eval(500, Some(U256::from(200u64))).unwrap(), 150); + assert_eq!(eval(500, Some(U256::from(1_000u64))).unwrap(), 450); + assert!(matches!( + eval(20, Some(U256::from(1_000u64))), + Err(MorphEthApiError::InsufficientFundsForL1Fee) + )); + + struct FailingAddrDb { + inner: CacheDB, + fail_addr: Address, + } + impl Database for FailingAddrDb { + type Error = reth_errors::ProviderError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + if address == self.fail_addr { + return Err(reth_errors::ProviderError::BestBlockNotFound); + } + Ok(self.inner.basic(address).unwrap()) + } + fn code_by_hash(&mut self, code_hash: B256) -> Result { + Ok(self.inner.code_by_hash(code_hash).unwrap()) + } + fn storage(&mut self, address: Address, index: U256) -> Result { + if address == self.fail_addr { + return Err(reth_errors::ProviderError::BestBlockNotFound); + } + Ok(self.inner.storage(address, index).unwrap()) + } + fn block_hash(&mut self, number: u64) -> Result { + Ok(self.inner.block_hash(number).unwrap()) + } + } + let run_failing = |db: &mut FailingAddrDb| { + load_caller_token_gas_allowance( + db, + &evm_env, + caller, + U256::ZERO, + U256::from(50u64), + 1, + None, + 1, + 50_000_000, + ) + }; + + // 5. Inactive / zero price_ratio / zero scale tokens fail fast as `InvalidFeeToken` + // WITHOUT touching `token` (if `balanceOf` ran, `FailingAddrDb` would return `Eth`). + for (label, is_active, price_ratio, scale) in [ + ("inactive", false, 1, 1), + ("zero price_ratio", true, 0, 1), + ("zero scale", true, 1, 0), + ] { + let mut db = FailingAddrDb { + inner: build_call_mode_db(500, is_active, price_ratio, scale), + fail_addr: token, + }; + let err = run_failing(&mut db).expect_err(label); + assert!( + matches!(err, MorphEthApiError::InvalidFeeToken), + "{label}: {err:?}" + ); + } + + // 6-7. DB failures during call-mode `balanceOf` or registry read propagate as `Eth`. + for fail_addr in [token, L2_TOKEN_REGISTRY_ADDRESS] { + let mut db = FailingAddrDb { + inner: build_call_mode_db(500, true, 1, 1), + fail_addr, + }; + let err = run_failing(&mut db).expect_err("DB failure must propagate"); + assert!( + matches!(err, MorphEthApiError::Eth(_)), + "{fail_addr}: {err:?}" + ); + } + } + /// `token_amount_to_eth` must floor, not ceil. Inverse of /// `eth_to_token_amount` (which ceils for protocol safety): an /// affordability budget must round toward the user so the returned