//! Token Fee Info for Morph L2 ERC20 gas payment. //! //! This module provides the infrastructure for fetching ERC20 token prices //! and calculating gas fees in alternative tokens. //! //! Reference: use alloy_primitives::{Address, Bytes, U256, address, keccak256}; use evm2::{ env::TxEnvExt, evm::{Database, Db}, registry::HandlerError, }; use crate::{ MorphInvalidTransaction, evm::{MorphEvm, MorphEvmEnv, morph_evm}, }; /// L2 Token Registry contract address on Morph L2. /// Reference: pub const L2_TOKEN_REGISTRY_ADDRESS: Address = address!("5300000000000000000000000000000000000021"); /// TokenRegistry storage slot for mapping(uint16 => TokenInfo) - slot 151. const TOKEN_REGISTRY_SLOT: U256 = U256::from_limbs([151u64, 0, 0, 0]); /// PriceRatio storage slot for mapping(uint16 => uint256) - slot 153. const PRICE_RATIO_SLOT: U256 = U256::from_limbs([153u64, 0, 0, 0]); /// Token fee information for ERC20 gas payment. /// /// Contains the token parameters fetched from the L2 Token Registry contract. /// These parameters are used to calculate gas fees in alternative ERC20 tokens. #[derive(Clone, Copy, Debug, Default)] pub struct TokenFeeInfo { /// The fee token address. pub token_address: Address, /// Whether the token is active for gas payment. pub is_active: bool, /// Token decimals. pub decimals: u8, /// The price ratio of the token (relative to ETH). pub price_ratio: U256, /// The scale of the token for price calculation. pub scale: U256, /// The caller address. pub caller: Address, /// The token balance of the caller. pub balance: U256, /// The user's ERC20 balance storage slot (if known). pub balance_slot: Option, } /// Fee-token registry metadata without any caller-specific balance state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TokenRegistryEntry { /// The registered ERC20 contract address. pub token_address: Address, /// Whether the token is active for gas payment. pub is_active: bool, /// Token decimals. pub decimals: u8, /// The price ratio of the token (relative to ETH). pub price_ratio: U256, /// The scale of the token for price calculation. pub scale: U256, /// The user's ERC20 balance storage slot (`None` means call-mode `balanceOf`). pub balance_slot: Option, } impl TokenRegistryEntry { /// The registered ERC20 contract. pub const fn token_address(&self) -> Address { self.token_address } /// The caller's balance storage slot, when the registry declares one. /// /// `None` means call mode: the balance has to be read by calling `balanceOf`. pub const fn balance_slot(&self) -> Option { self.balance_slot } /// Load fee-token metadata without reading a caller's token balance. pub fn load(db: &mut DB, token_id: u16) -> Result, DB::Error> { Self::load_with(|address, slot| db.get_storage(&address, &slot), token_id) } /// Load fee-token metadata through an existing [`MorphEvm`]'s backing database without /// warming or tracking the registry slots in transaction state. pub fn load_from_evm( evm: &mut MorphEvm<'_>, token_id: u16, ) -> Result, HandlerError> { let state = evm.state_mut(); Ok(Self::load_with( |address, slot| state.storage_slot_untracked(&address, &slot), token_id, )?) } /// As [`Self::load`], reading storage through `read`. pub fn load_with( read: impl FnMut(Address, U256) -> Result, token_id: u16, ) -> Result, E> { read_registry_entry(read, token_id) } /// Reject registry entries that cannot produce a valid token-denominated fee. pub fn ensure_usable(self, token_id: u16) -> Result { if !self.is_active { return Err(MorphInvalidTransaction::TokenNotActive(token_id)); } if self.price_ratio.is_zero() || self.scale.is_zero() { return Err(MorphInvalidTransaction::InvalidTokenConfig(token_id)); } Ok(self) } /// Read `caller`'s balance using an existing [`MorphEvm`], leaving its transaction-scoped /// state completely clean so the same EVM instance can be reused across callers and tokens. pub fn read_caller_balance_with_evm( &self, evm: &mut MorphEvm<'_>, caller: Address, ) -> Result { if let Some(slot) = self.balance_slot { let state = evm.state_mut(); return Ok(read_balance_from_storage( |address, slot| state.storage_slot_untracked(&address, &slot), self.token_address, caller, slot, )?); } // Call mode: ORIGIN matches execution (`caller`); GASPRICE stays zero when admission // does not know the next block's effective price. let chain_id = evm.version().chain_id; *evm.tx_env_mut() = TxEnvExt { origin: caller, chain_id: U256::from(chain_id), ..TxEnvExt::default() }; let result = crate::handler::evm_call_balance_of(evm, self.token_address, caller); evm.state_mut().clear_transaction_state(); result } /// Resolve the caller's balance to produce complete fee information. pub fn load_for_caller( self, db: &mut DB, caller: Address, env: &MorphEvmEnv, ) -> Result { let balance = read_token_balance_with_fallback( db, self.token_address, caller, self.balance_slot, env, )?; Ok(self.into_fee_info(caller, balance)) } fn load_storage_only( self, db: &mut DB, caller: Address, ) -> Result { let balance = if let Some(slot) = self.balance_slot { read_balance_from_storage( |address, slot| db.get_storage(&address, &slot), self.token_address, caller, slot, )? } else { U256::ZERO }; Ok(self.into_fee_info(caller, balance)) } /// Combine registry metadata with a resolved caller balance. pub const fn into_fee_info(self, caller: Address, balance: U256) -> TokenFeeInfo { TokenFeeInfo { token_address: self.token_address, is_active: self.is_active, decimals: self.decimals, price_ratio: self.price_ratio, scale: self.scale, caller, balance, balance_slot: self.balance_slot, } } } impl TokenFeeInfo { /// Maximum permitted token debit, bounded by the available balance. /// A zero fee limit means that the whole balance is available. pub fn effective_fee_limit(&self, fee_limit: U256) -> U256 { if fee_limit.is_zero() { self.balance } else { self.balance.min(fee_limit) } } /// Load token fee information with EVM call fallback. /// /// Reads token parameters from L2 Token Registry storage and validates /// usability (`is_active`, non-zero `price_ratio` and `scale`) before /// resolving the caller's balance, so inactive or misconfigured call-mode /// tokens never execute contract bytecode. If the token's balance slot is /// unknown, falls back to an EVM `balanceOf` call. /// Returns `Ok(None)` if the token is not registered. pub fn load_for_caller( db: &mut DB, token_id: u16, caller: Address, env: &MorphEvmEnv, ) -> Result, HandlerError> { let entry = match TokenRegistryEntry::load(db, token_id).map_err(database_error::)? { Some(e) => e.ensure_usable(token_id)?, None => return Ok(None), }; entry.load_for_caller(db, caller, env).map(Some) } /// Storage-only variant of [`Self::load_for_caller`]. /// /// Reads the registry entry and — when the token's `balance_slot` is /// known — the caller's ERC20 balance directly from contract storage. /// Unlike [`Self::load_for_caller`] this never spins up a temporary /// `MorphEvm`, so it is callable from RPC code paths that only have /// a typed [`Database`] and no block environment. /// /// Behaviour: /// - Returns `Ok(None)` if the token is not registered. /// - Returns `Ok(Some(Self))` with `balance = 0` and /// `balance_slot = None` if the token is registered but its balance /// slot is unknown — callers are expected to skip token-balance /// enforcement in that case (the handler re-checks the balance via /// an EVM call during execution). pub fn load_storage_only( db: &mut DB, token_id: u16, caller: Address, ) -> Result, DB::Error> { let entry = match TokenRegistryEntry::load(db, token_id)? { Some(e) => e, None => return Ok(None), }; entry.load_storage_only(db, caller).map(Some) } /// As [`Self::load_storage_only`], reading storage through `read`. pub fn load_storage_only_with( mut read: impl FnMut(Address, U256) -> Result, token_id: u16, caller: Address, ) -> Result, E> { let entry = match TokenRegistryEntry::load_with(&mut read, token_id)? { Some(e) => e, None => return Ok(None), }; let balance = match entry.balance_slot { Some(slot) => read_balance_from_storage(&mut read, entry.token_address, caller, slot)?, None => U256::ZERO, }; Ok(Some(entry.into_fee_info(caller, balance))) } /// Calculate the token amount required for a given ETH amount, rounding up. /// /// Uses the price ratio and scale to convert ETH value to token amount. #[inline] pub fn eth_to_token_amount(&self, eth_amount: U256) -> U256 { self.eth_to_token_amount_with_credit(eth_amount).0 } /// Same as [`Self::eth_to_token_amount`], and also returns the numerator the /// rounding-up overcharged. /// /// The credit is `price_ratio - remainder` (zero when the division is exact): /// the part of one whole token unit the caller paid for but did not use. From /// Celadon on, [`Self::eth_to_token_amount_floor`] hands it back on the refund /// so that the caller is charged `ceil` of the *net* fee rather than /// `ceil(prepaid) - ceil(refund)`, which under-collects. /// /// Mirrors go-ethereum's `types.EthToAlt`. #[inline] pub fn eth_to_token_amount_with_credit(&self, eth_amount: U256) -> (U256, U256) { // If price_ratio or scale is zero (misconfigured token), return MAX to prevent // free-ride transactions. The caller's balance check will reject the tx. if self.price_ratio.is_zero() || self.scale.is_zero() { return (U256::MAX, U256::ZERO); } // token_amount = eth_amount * scale / price_ratio let (token_amount, remainder) = eth_amount .saturating_mul(self.scale) .div_rem(self.price_ratio); // If there's a remainder, round up by adding 1 if remainder.is_zero() { (token_amount, U256::ZERO) } else { ( token_amount.saturating_add(U256::from(1)), self.price_ratio - remainder, ) } } /// Convert an ETH amount plus the prepaid rounding credit into token units, /// rounding down. /// /// `rounding_credit` comes from the matching /// [`Self::eth_to_token_amount_with_credit`] call made when the fee was /// deducted. Mirrors go-ethereum's `types.EthToAltFloor`. /// /// A misconfigured token refunds nothing. That is the conservative direction /// (the ceiling path returns `U256::MAX` for the same input to make the /// deduction fail), and it is unreachable in practice: such a transaction /// never gets past the balance check at deduction time. #[inline] pub fn eth_to_token_amount_floor(&self, eth_amount: U256, rounding_credit: U256) -> U256 { if self.price_ratio.is_zero() || self.scale.is_zero() { return U256::ZERO; } eth_amount .saturating_mul(self.scale) .saturating_add(rounding_credit) / self.price_ratio } } fn read_registry_entry( mut read: impl FnMut(Address, U256) -> Result, token_id: u16, ) -> Result, E> { // Get the base slot for this token_id in tokenRegistry mapping let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); let base = compute_mapping_slot(TOKEN_REGISTRY_SLOT, &token_id_bytes); // TokenInfo struct layout in storage (Solidity packing): // base + 0: tokenAddress (20 bytes) + padding // base + 1: balanceSlot (32 bytes) // base + 2: isActive (1 byte) + decimals (1 byte) + padding // base + 3: scale (32 bytes) let slot_0 = read(L2_TOKEN_REGISTRY_ADDRESS, base)?; let token_address = Address::from_word(slot_0.into()); if token_address == Address::default() { return Ok(None); } let balance_slot_raw = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(1))?; let balance_slot = if !balance_slot_raw.is_zero() { Some(balance_slot_raw.saturating_sub(U256::from(1))) } else { None }; // isActive at byte 31, decimals at byte 30 (big-endian) let slot_2 = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(2))?; let bytes = slot_2.to_be_bytes::<32>(); let is_active = bytes[31] != 0; let decimals = bytes[30]; let scale = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(3))?; // Get price ratio from priceRatio mapping let price_ratio = read_mapping_value( &mut read, L2_TOKEN_REGISTRY_ADDRESS, PRICE_RATIO_SLOT, &token_id_bytes, )?; Ok(Some(TokenRegistryEntry { token_address, is_active, decimals, price_ratio, scale, balance_slot, })) } /// Calculate the storage slot for a Solidity mapping value. /// /// For `mapping(keyType => valueType)` at slot `base_slot`, /// the value for `key` is at `keccak256(key ++ base_slot)`. /// /// Uses a stack-allocated `[u8; 64]` preimage buffer (32-byte key + 32-byte slot) /// to avoid heap allocations on every call. #[inline] pub fn compute_mapping_slot(base_slot: U256, key: &[u8; 32]) -> U256 { let mut preimage = [0u8; 64]; preimage[..32].copy_from_slice(key); preimage[32..].copy_from_slice(&base_slot.to_be_bytes::<32>()); U256::from_be_bytes(keccak256(preimage).0) } /// Calculate mapping slot for an address key (left-padded to 32 bytes). #[inline] pub fn compute_mapping_slot_for_address(base_slot: U256, account: Address) -> U256 { let mut key = [0u8; 32]; key[12..32].copy_from_slice(account.as_slice()); compute_mapping_slot(base_slot, &key) } /// Load a value from a mapping in contract storage. #[inline] fn read_mapping_value( read: &mut impl FnMut(Address, U256) -> Result, contract: Address, base_slot: U256, key: &[u8; 32], ) -> Result { read(contract, compute_mapping_slot(base_slot, key)) } /// Wraps a typed database error the way evm2's database adapter does. fn database_error(error: DB::Error) -> HandlerError { let fatal = DB::is_fatal(&error); evm2::DatabaseError::new(error, fatal).into() } /// Read ERC20 balance with EVM call fallback. /// /// If `balance_slot` is known, reads directly from storage. /// Otherwise, constructs a temporary EVM to call `balanceOf(address)`. fn read_token_balance_with_fallback( db: &mut DB, token: Address, account: Address, balance_slot: Option, env: &MorphEvmEnv, ) -> Result { if let Some(slot) = balance_slot { return read_balance_from_storage( |address, slot| db.get_storage(&address, &slot), token, account, slot, ) .map_err(database_error::); } // Call mode: stand the EVM up in the caller's environment rather than a default one, // and make the same `balanceOf` call the execution layer makes, so both reach the same // answer for a token whose balance depends on block context or `msg.sender`. let mut evm = morph_evm(Db::new(db), env.clone()); // ORIGIN follows this client's own execution layer, which resolves the same // `balanceOf` against the transaction's `caller`. go-ethereum's pool instead builds // its query on an empty `vm.TxContext{}` (core/tx_pool.go:341), leaving ORIGIN at the // zero address and disagreeing with go-ethereum's own execution layer. Admission // exists to predict what the builder will be able to include, so it follows execution // rather than the other client's pool. GASPRICE is the one input this query still // cannot match: it stays at zero because the effective price depends on the next // block's base fee, which admission does not know. go-ethereum's pool has the same gap. let chain_id = evm.version().chain_id; *evm.tx_env_mut() = TxEnvExt { origin: account, chain_id: U256::from(chain_id), ..TxEnvExt::default() }; crate::handler::evm_call_balance_of(&mut evm, token, account) } /// Read ERC20 balance directly from storage slot. #[inline] pub(crate) fn read_balance_from_storage( mut read: impl FnMut(Address, U256) -> Result, token: Address, account: Address, balance_slot: U256, ) -> Result { let mut key = [0u8; 32]; key[12..32].copy_from_slice(account.as_slice()); read_mapping_value(&mut read, token, balance_slot, &key) } /// Encode ERC20 `balanceOf(address)` calldata. /// /// Function selector: `0x70a08231` pub fn encode_balance_of_calldata(account: Address) -> Bytes { const SELECTOR: [u8; 4] = [0x70, 0xa0, 0x82, 0x31]; let mut data = Vec::with_capacity(36); data.extend_from_slice(&SELECTOR); data.extend_from_slice(&[0u8; 12]); // Left-pad address data.extend_from_slice(account.as_slice()); Bytes::from(data) } #[cfg(test)] pub(crate) mod tests { use super::*; use crate::MorphBlockEnv; use alloy_primitives::{B256, address, bytes}; use evm2::{ bytecode::Bytecode, evm::{AccountInfo, CacheDB, DynDatabase, EmptyDB, InMemoryDB}, interpreter::Word, }; use morph_chainspec::hardfork::MorphHardfork; /// The storage read failure injected by [`UnreadableTokenDb`], distinguishable from any /// error a real database would report. Shared with the handler tests. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct TokenReadFailure; impl core::fmt::Display for TokenReadFailure { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("injected token storage read failure") } } impl core::error::Error for TokenReadFailure {} /// Fails every storage read of `token` with [`TokenReadFailure`]; everything else reads /// normally, so a failure a test observes comes from that token's storage. Shared with the /// handler tests. #[derive(Debug)] pub(crate) struct UnreadableTokenDb { pub(crate) inner: InMemoryDB, pub(crate) token: Address, } impl Database for UnreadableTokenDb { type Error = TokenReadFailure; fn get_account(&mut self, address: &Address) -> Result, Self::Error> { Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) } fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) } fn get_storage(&mut self, address: &Address, key: &Word) -> Result { if *address == self.token { return Err(TokenReadFailure); } Ok(DynDatabase::get_storage(&mut self.inner, address, key).unwrap()) } fn get_block_hash(&mut self, number: &Word) -> Result { Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) } } /// Whether `error` carries the failure injected by [`UnreadableTokenDb`]. pub(crate) fn is_token_read_failure(error: &HandlerError) -> bool { matches!(error, HandlerError::Database(db) if db.downcast_ref::().is_some()) } /// Adapts an infallible in-memory database to the typed [`Database`] the public token-fee /// helpers take. #[derive(Debug)] pub(crate) struct Plain(pub(crate) InMemoryDB); impl Database for Plain { type Error = evm2::DatabaseError; fn get_account(&mut self, address: &Address) -> Result, Self::Error> { DynDatabase::get_account(&mut self.0, address) } fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { DynDatabase::get_code_by_hash(&mut self.0, code_hash) } fn get_storage(&mut self, address: &Address, key: &Word) -> Result { DynDatabase::get_storage(&mut self.0, address, key) } fn get_block_hash(&mut self, number: &Word) -> Result { DynDatabase::get_block_hash(&mut self.0, number) } } /// Registry state for a call-mode token (no `balanceSlot`) whose `balanceOf` returns /// storage slot 0, so reading it is a storage read of the token contract. fn call_mode_token_state(token: Address, balance: u64) -> InMemoryDB { call_mode_token_state_with_code(token, balance, bytes!("6000545f5260205ff3")) } /// As [`call_mode_token_state`], with an explicit `balanceOf` implementation. fn call_mode_token_state_with_code(token: Address, balance: u64, code: Bytes) -> InMemoryDB { let mut db = CacheDB::new(EmptyDB::default()); let mut token_id_bytes = [0u8; 32]; token_id_bytes[31] = 1; let base = compute_mapping_slot(TOKEN_REGISTRY_SLOT, &token_id_bytes); let mut packed = [0u8; 32]; packed[30] = 18; // decimals packed[31] = 1; // isActive for (slot, value) in [ (base, U256::from_be_bytes(token.into_word().0)), // Zero means "no known balance slot": the EVM `balanceOf` fallback is used. (base + U256::from(1), U256::ZERO), (base + U256::from(2), U256::from_be_bytes(packed)), (base + U256::from(3), U256::from(1)), // scale ( compute_mapping_slot(PRICE_RATIO_SLOT, &token_id_bytes), U256::from(1), // priceRatio ), ] { db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &slot, &value); } db.insert_account_info( &token, AccountInfo::default().with_code(Bytecode::new_legacy(code)), ); db.insert_account_storage(&token, &U256::ZERO, &U256::from(balance)); db } #[test] fn call_mode_balance_is_read_under_the_supplied_block_environment() { const TIMESTAMP: u64 = 1_767_765_600; let token = address!("5300000000000000000000000000000000000042"); let caller = address!("0000000000000000000000000000000000000001"); // TIMESTAMP PUSH0 MSTORE PUSH1 0x20 PUSH0 RETURN — a `balanceOf` that reports the // block time, so an answer produced under the wrong environment is visible. let db = call_mode_token_state_with_code(token, 0, bytes!("425f5260205ff3")); let env = MorphEvmEnv::new( MorphHardfork::Emerald, MorphBlockEnv { timestamp: U256::from(TIMESTAMP), ..Default::default() }, 1, ); let info = TokenFeeInfo::load_for_caller(&mut Plain(db), 1, caller, &env) .unwrap() .unwrap(); // `BlockEnv::default()` reports timestamp 1, which is what the pool answered with // regardless of the block it was validating against. assert_eq!(info.balance, U256::from(TIMESTAMP)); } #[test] fn balance_of_fallback_reports_a_failed_state_read_instead_of_a_zero_balance() { let token = address!("5300000000000000000000000000000000000042"); let caller = address!("0000000000000000000000000000000000000001"); let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 1); // Readable state: the fallback reaches the token and reads the balance. let mut readable = Plain(call_mode_token_state(token, 10_000_000)); let info = TokenFeeInfo::load_for_caller(&mut readable, 1, caller, &env) .unwrap() .unwrap(); assert_eq!(info.balance, U256::from(10_000_000)); // Same state, but the token's storage cannot be read. Reporting a zero balance here // would be indistinguishable from an account that genuinely cannot pay. let mut unreadable = UnreadableTokenDb { inner: call_mode_token_state(token, 10_000_000), token, }; let error = TokenFeeInfo::load_for_caller(&mut unreadable, 1, caller, &env).unwrap_err(); assert!(is_token_read_failure(&error), "{error:?}"); } #[test] fn load_for_caller_rejects_unusable_call_mode_tokens_before_executing_bytecode() { let token = address!("5300000000000000000000000000000000000042"); let caller = address!("0000000000000000000000000000000000000001"); let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 1); let mut token_id_bytes = [0u8; 32]; token_id_bytes[31] = 1; let base = compute_mapping_slot(TOKEN_REGISTRY_SLOT, &token_id_bytes); // Inactive token: `UnreadableTokenDb` would fail with `TokenReadFailure` if `balanceOf` // were ever invoked, proving usability is checked before entering call-mode bytecode. let mut inactive_inner = call_mode_token_state(token, 10_000_000); let mut inactive_packed = [0u8; 32]; inactive_packed[30] = 18; inactive_packed[31] = 0; inactive_inner.insert_account_storage( &L2_TOKEN_REGISTRY_ADDRESS, &(base + U256::from(2)), &U256::from_be_bytes(inactive_packed), ); let mut unreadable_inactive = UnreadableTokenDb { inner: inactive_inner, token, }; let err = TokenFeeInfo::load_for_caller(&mut unreadable_inactive, 1, caller, &env).unwrap_err(); assert_eq!( err.external_ref::(), Some(&MorphInvalidTransaction::TokenNotActive(1)) ); // Zero scale token: rejected with `InvalidTokenConfig(1)` before `balanceOf`. let mut zero_scale_inner = call_mode_token_state(token, 10_000_000); zero_scale_inner.insert_account_storage( &L2_TOKEN_REGISTRY_ADDRESS, &(base + U256::from(3)), &U256::ZERO, ); let mut unreadable_zero_scale = UnreadableTokenDb { inner: zero_scale_inner, token, }; let err = TokenFeeInfo::load_for_caller(&mut unreadable_zero_scale, 1, caller, &env).unwrap_err(); assert_eq!( err.external_ref::(), Some(&MorphInvalidTransaction::InvalidTokenConfig(1)) ); } #[test] fn reused_evm_recovers_cleanly_after_proxy_delegatecall_db_failure() { use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, }; struct FlakyImplDb { inner: InMemoryDB, fail_impl: Arc, token: Address, } impl Database for FlakyImplDb { type Error = TokenReadFailure; fn get_account( &mut self, address: &Address, ) -> Result, Self::Error> { Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) } fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) } fn get_storage(&mut self, address: &Address, key: &Word) -> Result { if *address == self.token && self.fail_impl.load(Ordering::Relaxed) { return Err(TokenReadFailure); } Ok(DynDatabase::get_storage(&mut self.inner, address, key).unwrap()) } fn get_block_hash(&mut self, number: &Word) -> Result { Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) } } let proxy = address!("5300000000000000000000000000000000000042"); let implementation = address!("5300000000000000000000000000000000000099"); let caller = address!("0000000000000000000000000000000000000001"); // Minimal DELEGATECALL proxy -> implementation reading slot 0. let mut proxy_code = vec![0x36, 0x5f, 0x5f, 0x37, 0x5f, 0x5f, 0x36, 0x5f, 0x73]; proxy_code.extend_from_slice(implementation.as_slice()); proxy_code.extend_from_slice(&[0x5a, 0xf4, 0x3d, 0x5f, 0x5f, 0x3e, 0x50, 0x3d, 0x5f, 0xf3]); let mut inner = call_mode_token_state_with_code(proxy, 777_000, Bytes::from(proxy_code)); inner.insert_account_info( &implementation, AccountInfo::default().with_code(Bytecode::new_legacy(bytes!("6000545f5260205ff3"))), ); let fail_impl = Arc::new(AtomicBool::new(true)); let db = FlakyImplDb { inner, fail_impl: Arc::clone(&fail_impl), token: proxy, }; let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 2818); let mut evm = morph_evm(Db::new(db), env); let entry = TokenRegistryEntry::load_from_evm(&mut evm, 1) .unwrap() .unwrap() .ensure_usable(1) .unwrap(); // First call fails mid-DELEGATECALL with DB read error. let err = entry .read_caller_balance_with_evm(&mut evm, caller) .unwrap_err(); assert!(is_token_read_failure(&err), "{err:?}"); // Flip DB healthy and reuse the exact same `MorphEvm` instance: must succeed cleanly. fail_impl.store(false, Ordering::Relaxed); let balance = entry .read_caller_balance_with_evm(&mut evm, caller) .expect("reused EVM must recover cleanly after nested frame DB error"); assert_eq!(balance, U256::from(777_000u64)); } #[test] fn test_token_fee_info_default() { let info = TokenFeeInfo::default(); assert_eq!(info.token_address, Address::default()); assert!(!info.is_active); assert_eq!(info.decimals, 0); assert_eq!(info.price_ratio, U256::ZERO); assert_eq!(info.scale, U256::ZERO); assert_eq!(info.balance, U256::ZERO); assert!(info.balance_slot.is_none()); } #[test] fn test_mapping_slot() { // Test that mapping slot calculation produces deterministic results let slot = U256::from(151); let key = [0u8; 32]; let result1 = compute_mapping_slot(slot, &key); let result2 = compute_mapping_slot(slot, &key); assert_eq!(result1, result2); } #[test] fn test_mapping_slot_for() { let slot = U256::from(1); let account = address!("1234567890123456789012345678901234567890"); let result = compute_mapping_slot_for_address(slot, account); // Result should be non-zero assert!(!result.is_zero()); } #[test] fn test_eth_to_token_amount() { let info = TokenFeeInfo { price_ratio: U256::from(2_000_000_000_000_000_000u128), // 2 ETH per token scale: U256::from(1_000_000_000_000_000_000u128), // 1e18 ..Default::default() }; // 1 ETH should give 0.5 tokens let eth_amount = U256::from(1_000_000_000_000_000_000u128); // 1 ETH let token_amount = info.eth_to_token_amount(eth_amount); assert_eq!(token_amount, U256::from(500_000_000_000_000_000u128)); // 0.5 tokens } #[test] fn test_eth_to_token_amount_zero_ratio() { let info = TokenFeeInfo { price_ratio: U256::ZERO, scale: U256::from(1_000_000_000_000_000_000u128), ..Default::default() }; let eth_amount = U256::from(1_000_000_000_000_000_000u128); let token_amount = info.eth_to_token_amount(eth_amount); // Misconfigured token returns MAX to prevent free-ride transactions assert_eq!(token_amount, U256::MAX); } /// Rounding up the prepaid fee leaves `price_ratio - remainder` of a token /// unit paid for but unused, which is exactly what the refund gets back. #[test] fn eth_to_token_amount_reports_the_rounding_credit() { let info = TokenFeeInfo { price_ratio: U256::from(3u64), scale: U256::from(1u64), ..Default::default() }; // 10 / 3 = 3 remainder 1 → charge 4, one third of a unit unused → 3 - 1 = 2. let (amount, credit) = info.eth_to_token_amount_with_credit(U256::from(10u64)); assert_eq!(amount, U256::from(4u64)); assert_eq!(credit, U256::from(2u64)); // An exact division overcharges nothing. let (amount, credit) = info.eth_to_token_amount_with_credit(U256::from(9u64)); assert_eq!(amount, U256::from(3u64)); assert_eq!(credit, U256::ZERO); // The plain ceiling accessor stays the first half of the pair. assert_eq!( info.eth_to_token_amount(U256::from(10u64)), U256::from(4u64) ); } /// The credit is what makes deduct-then-refund add up to `ceil(net fee)`. /// Without it, both halves round up independently and the chain /// under-collects — for `remaining = 4` below, by a whole token unit. #[test] fn floor_refund_charges_the_ceiling_of_the_net_fee() { let info = TokenFeeInfo { price_ratio: U256::from(3u64), scale: U256::from(1u64), ..Default::default() }; for prepaid_eth in 0u64..40 { let (charged, credit) = info.eth_to_token_amount_with_credit(U256::from(prepaid_eth)); for remaining_eth in 0..=prepaid_eth { let refunded = info.eth_to_token_amount_floor(U256::from(remaining_eth), credit); let net_eth = U256::from(prepaid_eth - remaining_eth); assert_eq!( charged - refunded, info.eth_to_token_amount(net_eth), "prepaid {prepaid_eth}, remaining {remaining_eth}" ); } } } /// The Celadon change is observable, so the fork gate in the handler is not /// cosmetic: on an exact deduction the credit is zero and the two roundings /// disagree for every inexact refund. #[test] fn floor_and_ceiling_refunds_differ() { let info = TokenFeeInfo { price_ratio: U256::from(3u64), scale: U256::from(1u64), ..Default::default() }; // Exact deduction (9 / 3) → no credit; refunding 4 ceils to 2, floors to 1. let (_, credit) = info.eth_to_token_amount_with_credit(U256::from(9u64)); assert_eq!(credit, U256::ZERO); assert_eq!(info.eth_to_token_amount(U256::from(4u64)), U256::from(2u64)); assert_eq!( info.eth_to_token_amount_floor(U256::from(4u64), credit), U256::from(1u64) ); } /// Flooring can reach zero where the ceiling never does. The handler skips /// the transfer in that case, matching go-ethereum's `TransferAltTokenHybrid`. #[test] fn floor_refund_can_be_zero() { let info = TokenFeeInfo { price_ratio: U256::from(5u64), scale: U256::from(1u64), ..Default::default() }; let (_, credit) = info.eth_to_token_amount_with_credit(U256::from(5u64)); assert_eq!(credit, U256::ZERO); assert_eq!(info.eth_to_token_amount(U256::from(1u64)), U256::from(1u64)); assert_eq!( info.eth_to_token_amount_floor(U256::from(1u64), credit), U256::ZERO ); } /// A misconfigured token refunds nothing rather than the `U256::MAX` the /// ceiling path returns to make the deduction fail. #[test] fn floor_refund_of_a_misconfigured_token_is_zero() { for info in [ TokenFeeInfo { price_ratio: U256::ZERO, scale: U256::from(1u64), ..Default::default() }, TokenFeeInfo { price_ratio: U256::from(1u64), scale: U256::ZERO, ..Default::default() }, ] { assert_eq!( info.eth_to_token_amount_floor(U256::from(10u64), U256::from(3u64)), U256::ZERO ); let (amount, credit) = info.eth_to_token_amount_with_credit(U256::from(10u64)); assert_eq!(amount, U256::MAX); assert_eq!(credit, U256::ZERO); } } #[test] fn test_encode_balance_of() { let account = address!("1234567890123456789012345678901234567890"); let calldata = encode_balance_of_calldata(account); // Should be 4 bytes selector + 32 bytes address = 36 bytes assert_eq!(calldata.len(), 36); // First 4 bytes should be the selector assert_eq!(&calldata[0..4], &[0x70, 0xa0, 0x82, 0x31]); // Last 20 bytes should be the address assert_eq!(&calldata[16..36], account.as_slice()); } #[test] fn test_l2_token_registry_address() { // Verify the constant is set correctly assert_eq!( L2_TOKEN_REGISTRY_ADDRESS, address!("5300000000000000000000000000000000000021") ); } #[test] fn test_eth_to_token_amount_zero_scale() { let info = TokenFeeInfo { price_ratio: U256::from(2_000_000_000_000_000_000u128), scale: U256::ZERO, // Misconfigured ..Default::default() }; let eth_amount = U256::from(1_000_000_000_000_000_000u128); let token_amount = info.eth_to_token_amount(eth_amount); // Misconfigured token returns MAX assert_eq!(token_amount, U256::MAX); } /// Verify rounding up when there's a remainder in the division. #[test] fn test_eth_to_token_amount_rounds_up() { let info = TokenFeeInfo { price_ratio: U256::from(3), scale: U256::from(1), ..Default::default() }; // 10 * 1 / 3 = 3 remainder 1 -> rounds up to 4 let token_amount = info.eth_to_token_amount(U256::from(10)); assert_eq!(token_amount, U256::from(4)); } /// Exact division should not round up. #[test] fn test_eth_to_token_amount_exact_division() { let info = TokenFeeInfo { price_ratio: U256::from(2), scale: U256::from(1), ..Default::default() }; // 10 * 1 / 2 = 5 exact let token_amount = info.eth_to_token_amount(U256::from(10)); assert_eq!(token_amount, U256::from(5)); } #[test] fn test_eth_to_token_amount_zero_eth() { let info = TokenFeeInfo { price_ratio: U256::from(2), scale: U256::from(1), ..Default::default() }; let token_amount = info.eth_to_token_amount(U256::ZERO); assert_eq!(token_amount, U256::ZERO); } #[test] fn test_mapping_slot_different_keys_produce_different_slots() { let slot = U256::from(151); let key1 = { let mut k = [0u8; 32]; k[31] = 1; k }; let key2 = { let mut k = [0u8; 32]; k[31] = 2; k }; let result1 = compute_mapping_slot(slot, &key1); let result2 = compute_mapping_slot(slot, &key2); assert_ne!(result1, result2); } #[test] fn test_mapping_slot_for_address_different_accounts() { let slot = U256::from(1); let addr1 = address!("1111111111111111111111111111111111111111"); let addr2 = address!("2222222222222222222222222222222222222222"); let result1 = compute_mapping_slot_for_address(slot, addr1); let result2 = compute_mapping_slot_for_address(slot, addr2); assert_ne!(result1, result2); } #[test] fn test_encode_balance_of_zero_address() { let account = Address::ZERO; let calldata = encode_balance_of_calldata(account); assert_eq!(calldata.len(), 36); assert_eq!(&calldata[0..4], &[0x70, 0xa0, 0x82, 0x31]); // Address should be all zeros assert!(calldata[4..36].iter().all(|&b| b == 0)); } }