From 6822a93002a92b339d0bd3bbf19d515a63e946d9 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Thu, 26 Nov 2026 10:52:52 +0800 Subject: [PATCH 1/6] fix(rpc,revm): fix eth_simulateV1 L1 fee handling and skip beneficiary reward when fees disabled - M-M02 (`crates/revm/src/handler.rs`): - Return early in `MorphEvmHandler::reward_beneficiary` when `cfg.is_fee_charge_disabled()` (matching upstream `revm-handler`), preventing phantom ETH (`execution_fee + l1_data_fee`) from being credited to FeeVault during `eth_call`, `eth_estimateGas`, `eth_simulateV1` (`validation: false`), and `debug_traceCall`. - Skip L1 oracle fetch in `validate_and_deduct_eth_fee` when `cfg.is_fee_charge_disabled()`, leaving `cached_l1_data_fee = U256::ZERO`. - M-H03 (`crates/rpc/src/eth/call.rs`): - Override `EthCall::simulate_v1` for `MorphEthApi`, preserving upstream reth `simulate_v1` semantics (`block_state_calls`, `trace_transfers`, `return_full_transactions`, `block_overrides`, `state_overrides`, `max_simulate_blocks`, `call_gas_limit`, `compute_state_root`). - When `!validation`, set `evm_env.cfg_env.disable_fee_charge = true` alongside `disable_nonce_check`, `disable_base_fee`, and `basefee = 0`, so zero-balance / omitted-`from` callers succeed, funded caller and FeeVault balances are not mutated by L1/L2 fees, and call-mode token-fee MorphTxs neither deduct tokens nor emit fee `Transfer` logs. - When `validation == true`, wrap resolved simulated transactions with their real EIP-2718 encoding (`WithEncoded::new(tx.encoded_2718().into(), tx)`) instead of empty bytes so post-Curie `commit + blob` (and pre-Curie calldata) L1 fees are accurately charged and validated. - Add unit tests in `crates/revm/src/handler.rs` and end-to-end `eth_simulateV1` integration tests in `crates/node/tests/it/rpc.rs`. --- Cargo.lock | 1 + Cargo.toml | 1 + crates/node/src/test_utils.rs | 32 ++ crates/node/tests/it/rpc.rs | 568 ++++++++++++++++++++++++++++++++++ crates/revm/src/handler.rs | 214 +++++++++++-- crates/rpc/Cargo.toml | 3 +- crates/rpc/src/eth/call.rs | 403 +++++++++++++++++++++++- 7 files changed, 1189 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4937c224..8b3e89fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5475,6 +5475,7 @@ dependencies = [ "reth-transaction-pool", "reth-trie-common", "revm", + "revm-inspectors", "serde", "serde_json", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index 773ed379..1e9c7487 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -213,6 +213,7 @@ alloy-sol-types = { version = "1.6.1", default-features = false } alloy-transport = "2.3.0" alloy-chains = { version = "0.2.33", default-features = false } crossbeam-channel = "0.5.13" +revm-inspectors = "0.42.0" revm-primitives = { version = "42.0.0", default-features = false } revm-statetest-types = { version = "42.0.0", default-features = false } arbitrary = { version = "1.3", features = ["derive"] } diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 8874e847..1b9af469 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -282,6 +282,38 @@ impl TestNodeBuilder { self } + /// Override a storage slot for an account in the test genesis. + pub fn with_account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { + let alloc = self + .genesis_json + .get_mut("alloc") + .and_then(serde_json::Value::as_object_mut) + .expect("test genesis alloc must be an object"); + let address_lower = address.to_string().to_ascii_lowercase(); + let key = alloc + .keys() + .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) + .cloned() + .unwrap_or(address_lower); + let entry = alloc + .entry(key) + .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); + let entry = entry + .as_object_mut() + .expect("test genesis account entry must be an object"); + let storage = entry + .entry("storage") + .or_insert_with(|| serde_json::json!({})); + let storage = storage + .as_object_mut() + .expect("test genesis account storage must be an object"); + storage.insert( + format!("{slot:#066x}"), + serde_json::json!(format!("{value:#066x}")), + ); + self + } + /// Set the number of nodes to start. /// /// When `num_nodes > 1`, all nodes are interconnected via a simulated P2P network. diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 2e49b44a..85c95ad8 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1310,3 +1310,571 @@ async fn native_get_proof_and_get_multi_proof_succeed_on_latest() -> eyre::Resul Ok(()) } + +/// Decodes a 32-byte hex string (with `0x` prefix) returned by EVM calls into a [`U256`]. +fn decode_u256_word(hex: &str) -> U256 { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 32, "expected 32-byte ABI word, got {hex}"); + U256::from_be_slice(&bytes) +} + +/// Decodes two concatenated 32-byte hex words returned by the 2-address balance reader. +fn decode_two_u256_words(hex: &str) -> (U256, U256) { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 64, "expected 64-byte ABI output, got {hex}"); + ( + U256::from_be_slice(&bytes[..32]), + U256::from_be_slice(&bytes[32..]), + ) +} + +/// ABI-encodes a single address as a 32-byte calldata word. +fn encode_address_word(addr: Address) -> String { + let mut buf = [0u8; 32]; + buf[12..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes two addresses as 64 bytes of calldata. +fn encode_two_address_words(a: Address, b: Address) -> String { + let mut buf = [0u8; 64]; + buf[12..32].copy_from_slice(a.as_slice()); + buf[44..64].copy_from_slice(b.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes ERC-20 `balanceOf(address)`. +fn encode_balance_of(addr: Address) -> String { + let mut buf = [0u8; 36]; + buf[..4].copy_from_slice(&[0x70, 0xa0, 0x82, 0x31]); + buf[16..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// `eth_simulateV1` with `validation: false` must disable L1 and L2 fee charging +/// for both ETH and token-fee MorphTxs post-Curie with non-zero L1 oracle fees: +/// - Omitted-`from` and zero-balance callers succeed. +/// - Funded caller balances and FeeVault balance are unchanged by L1/L2 fees +/// (and `value > 0` transfers move only `value`). +/// - Call-mode token-fee MorphTxs neither deduct tokens nor emit fee `Transfer` logs. +#[tokio::test(flavor = "multi_thread")] +async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const FEE_VAULT: Address = + alloy_primitives::address!("530000000000000000000000000000000000000a"); + const TEST_TOKEN: Address = + alloy_primitives::address!("5300000000000000000000000000000000000022"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie commit fee) + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie blob fee) + // Runtime bytecode: return `BALANCE(calldataload(0))` (32 bytes). + const BALANCE_READER_CODE: &str = "0x6000353160005260206000f3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let funded = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let latest_state = node.inner.provider.latest()?; + let funded_account = latest_state + .basic_account(&funded)? + .expect("funded wallet exists"); + let initial_funded_balance = funded_account.balance; + let initial_funded_nonce = funded_account.nonce; + let initial_vault_balance = latest_state + .basic_account(&FEE_VAULT)? + .map(|a| a.balance) + .unwrap_or_default(); + + // Read funded wallet's initial call-mode fee token balance via eth_call. + let initial_token_hex: String = client + .request( + "eth_call", + ( + serde_json::json!({ + "to": TEST_TOKEN, + "input": encode_balance_of(funded), + }), + "latest", + ), + ) + .await?; + let initial_token_balance = decode_u256_word(&initial_token_hex); + assert!( + initial_token_balance > U256::ZERO, + "funded wallet must hold genesis test fee tokens" + ); + + let reader_addr = Address::random(); + let unfunded_caller = Address::random(); + let recipient = Address::random(); + let value_recipient = Address::random(); + let transfer_value = U256::from(1_000_000_000_000_000_000u128); // 1 ETH + let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); + + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { + "code": BALANCE_READER_CODE, + }, + }, + "calls": [ + // 0: omitted `from` (spec default 0x0000...0000, zero ETH) + { + "to": recipient, + "input": calldata, + }, + // 1: explicit zero-balance caller with non-zero gasPrice + { + "from": unfunded_caller, + "to": recipient, + "gasPrice": "0x3b9aca00", + "input": calldata, + }, + // 2: funded caller, value = 0, non-zero EIP-1559 fee caps + calldata + { + "from": funded, + "to": recipient, + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + "input": calldata, + }, + // 3: check funded caller ETH balance unchanged + { + "to": reader_addr, + "input": encode_address_word(funded), + }, + // 4: check FeeVault ETH balance unchanged (no phantom reward) + { + "to": reader_addr, + "input": encode_address_word(FEE_VAULT), + }, + // 5: funded caller, value = 1 ETH transfer + { + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + }, + // 6: check funded caller ETH balance decreased by exact transfer_value + { + "to": reader_addr, + "input": encode_address_word(funded), + }, + // 7: check value_recipient received exact transfer_value + { + "to": reader_addr, + "input": encode_address_word(value_recipient), + }, + // 8: check FeeVault ETH balance still unchanged + { + "to": reader_addr, + "input": encode_address_word(FEE_VAULT), + }, + // 9: call-mode token-fee MorphTx from unfunded caller (0 ETH, 0 tokens) + { + "from": unfunded_caller, + "to": recipient, + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0x0", + "input": calldata, + }, + // 10: call-mode token-fee MorphTx from funded wallet (must emit 0 logs & deduct 0 tokens) + { + "from": funded, + "to": recipient, + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0xde0b6b3a7640000", + "input": calldata, + }, + // 11: check funded wallet token balance unchanged + { + "to": TEST_TOKEN, + "input": encode_balance_of(funded), + }, + // 12: check FeeVault token balance unchanged (0) + { + "to": TEST_TOKEN, + "input": encode_balance_of(FEE_VAULT), + }, + ], + }], + "validation": false, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls.len(), 13); + + for (idx, call) in calls.iter().enumerate() { + assert_eq!( + call["status"].as_str(), + Some("0x1"), + "call {idx} must succeed under validation=false: {call}" + ); + } + + // Funded caller ETH balance unchanged after value=0 call. + assert_eq!( + decode_u256_word(calls[3]["returnData"].as_str().unwrap()), + initial_funded_balance, + "validation=false must not deduct L1/L2 fees from funded caller" + ); + // FeeVault ETH balance unchanged after value=0 call. + assert_eq!( + decode_u256_word(calls[4]["returnData"].as_str().unwrap()), + initial_vault_balance, + "validation=false must not credit phantom fees to FeeVault" + ); + // Funded caller ETH balance reduced by exact transfer_value after value>0 call. + assert_eq!( + decode_u256_word(calls[6]["returnData"].as_str().unwrap()), + initial_funded_balance - transfer_value, + "value transfer under validation=false must debit only tx.value" + ); + assert_eq!( + decode_u256_word(calls[7]["returnData"].as_str().unwrap()), + transfer_value, + "recipient must receive exact transfer_value" + ); + assert_eq!( + decode_u256_word(calls[8]["returnData"].as_str().unwrap()), + initial_vault_balance, + "FeeVault balance must remain unchanged after value transfer" + ); + + // Call-mode token-fee MorphTxs must emit zero fee Transfer logs and move zero tokens. + assert!( + calls[9]["logs"].as_array().unwrap().is_empty(), + "unfunded token-fee MorphTx must emit no logs under validation=false" + ); + assert!( + calls[10]["logs"].as_array().unwrap().is_empty(), + "funded call-mode token-fee MorphTx must emit no fee Transfer logs under validation=false" + ); + assert_eq!( + decode_u256_word(calls[11]["returnData"].as_str().unwrap()), + initial_token_balance, + "funded caller token balance must be unchanged under validation=false" + ); + assert_eq!( + decode_u256_word(calls[12]["returnData"].as_str().unwrap()), + U256::ZERO, + "FeeVault token balance must remain zero under validation=false" + ); + + // Verify caller nonce bumped across funded ETH and MorphTx calls (indices 2, 5, 10). + let txs = block["transactions"] + .as_array() + .expect("transactions array"); + assert_eq!( + txs[2]["nonce"].as_str(), + Some(format!("{initial_funded_nonce:#x}").as_str()) + ); + assert_eq!( + txs[5]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) + ); + assert_eq!( + txs[10]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) + ); + + // Also exercise the `traceTransfers: true` (`TransferInspector`) branch under + // `validation: false`: a 1 ETH transfer emits exactly 1 synthetic ETH transfer + // log (to `value_recipient`) and zero FeeVault transfer logs. + let trace_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + }], + }], + "traceTransfers": true, + "validation": false, + }); + let trace_blocks: Value = client + .request("eth_simulateV1", (trace_payload, "latest")) + .await?; + let trace_call = &trace_blocks[0]["calls"][0]; + assert_eq!(trace_call["status"].as_str(), Some("0x1")); + let trace_logs = trace_call["logs"].as_array().expect("trace logs array"); + assert_eq!( + trace_logs.len(), + 1, + "traceTransfers with validation=false must record only the value transfer, not fee transfers: {trace_logs:?}" + ); + + Ok(()) +} + +/// `eth_simulateV1` with `validation: true` must wrap simulated transactions with +/// their real EIP-2718 encoding so post-Curie `commit + blob` L1 fees are charged +/// and validated accurately (for both standard ETH txs and token-fee MorphTxs). +#[tokio::test(flavor = "multi_thread")] +async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const FEE_VAULT: Address = + alloy_primitives::address!("530000000000000000000000000000000000000a"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + // Matches `tests/assets/test-genesis.json` slots 7 & 8. + const COMMIT_SCALAR: u128 = 0x35ba5d7b55; + const BLOB_SCALAR: u128 = 0x18e38a4c; + const L1_FEE_PRECISION: u128 = 1_000_000_000; + // Runtime bytecode: return `(BALANCE(calldataload(0)), BALANCE(calldataload(32)))` (64 bytes). + const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; + let funded_wallet = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let initial_vault_balance = node + .inner + .provider + .latest()? + .basic_account(&FEE_VAULT)? + .map(|a| a.balance) + .unwrap_or_default(); + + let sender = Address::random(); + let recipient = Address::random(); + let reader_addr = Address::random(); + let calldata = Bytes::from(vec![0xab; 1024]); + let gas_limit = 50_000u64; + let max_fee_per_gas = 2_000_000_000u128; // 2 gwei + let max_priority_fee_per_gas = 1_000_000_000u128; // 1 gwei + + // Build the exact simulated EIP-1559 envelope (`Signature(0, 0, false)`) that + // `resolve_transaction` / `TryIntoSimTx` produces so we know its exact EIP-2718 length. + let sim_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let expected_eth_envelope = MorphTxEnvelope::Eip1559( + alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + } + .into_signed(sim_sig), + ); + let encoded_len = expected_eth_envelope.encoded_2718().len() as u128; + let commit_only_l1_fee = + U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let full_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + assert!( + full_l1_fee > commit_only_l1_fee * U256::from(2u64), + "calldata blob fee must significantly exceed commit-only fee" + ); + + let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); + let tx_call = serde_json::json!({ + "from": sender, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": calldata.to_string(), + }); + + // (1) Balance covers L2 + commit-only L1 fee (+ half the blob fee), NOT full Curie L1 fee: + // must fail with insufficient funds (-38014). Under the old empty-RLP bug this passed! + let insufficient_balance = + l2_max_fee + commit_only_l1_fee + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + let fail_payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { + "balance": format!("{insufficient_balance:#x}"), + }, + }, + "calls": [tx_call], + }], + "validation": true, + }); + let err = client + .request::("eth_simulateV1", (fail_payload, "latest")) + .await + .expect_err("validation=true must reject when balance omits Curie blob L1 fee"); + let err_str = err.to_string(); + assert!( + err_str.contains("insufficient funds") || err_str.contains("-38014"), + "expected insufficient funds error, got: {err_str}" + ); + + // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed and deduct exact + // `l2_used_fee + full_l1_fee` from sender and credit the same amount to FeeVault. + let exact_budget = l2_max_fee + full_l1_fee; + let pass_payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { + "balance": format!("{exact_budget:#x}"), + }, + reader_addr.to_string(): { + "code": DUAL_BALANCE_READER_CODE, + }, + }, + "calls": [ + tx_call, + // Executed immediately after Call 0 commits and BEFORE Call 1's own + // `reward_beneficiary` runs, so it observes exact post-Call-0 balances + // of both `sender` and `FEE_VAULT`. + { + "from": funded_wallet, + "to": reader_addr, + "gas": "0x186a0", + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": encode_two_address_words(sender, FEE_VAULT), + }, + ], + }], + "validation": true, + }); + let blocks: Value = client + .request("eth_simulateV1", (pass_payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let block_base_fee = u128::from_str_radix( + block["baseFeePerGas"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); + let expected_total_fee = U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; + + let (sender_balance_after, vault_balance_after) = + decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); + assert_eq!( + sender_balance_after, + exact_budget - expected_total_fee, + "sender must be charged exact L2 execution fee + full Curie (commit + blob) L1 fee" + ); + assert_eq!( + vault_balance_after, + initial_vault_balance + expected_total_fee, + "FeeVault must receive exact L2 execution fee + full Curie (commit + blob) L1 fee" + ); + + // (3) Token-fee MorphTx under `validation: true`: a `feeLimit` that only covers + // L2 (`gas_limit * effective_gas_price`) + commit-only L1 fee (+ half the blob fee) + // must fail, while covering full Curie L1 + L2 succeeds and emits the call-mode + // ERC-20 `Transfer` fee log(s). (Genesis token ID 1 has 1:1 price_ratio == scale == 1e18.) + let l2_effective_max_fee = U256::from(gas_limit) * U256::from(effective_gas_price); + let token_tight_limit = l2_effective_max_fee + + commit_only_l1_fee + + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + let morph_fail_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded_wallet, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_tight_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }); + client + .request::("eth_simulateV1", (morph_fail_payload, "latest")) + .await + .expect_err("token-fee MorphTx must fail under validation=true when feeLimit omits Curie blob L1 fee"); + + let token_generous_limit = l2_max_fee + full_l1_fee * U256::from(2u64); + let morph_pass_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded_wallet, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_generous_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }); + let morph_blocks: Value = client + .request("eth_simulateV1", (morph_pass_payload, "latest")) + .await?; + let morph_call = &morph_blocks[0]["calls"][0]; + assert_eq!(morph_call["status"].as_str(), Some("0x1")); + let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + let logs = morph_call["logs"].as_array().expect("logs array"); + assert!( + logs.iter().any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(transfer_topic) + }), + "validated call-mode token-fee MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" + ); + + Ok(()) +} diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 4a701649..daac1f32 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -234,6 +234,15 @@ where evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult, ) -> Result<(), Self::Error> { + // Mirror upstream `revm_handler::post_execution::reward_beneficiary`: + // when fee charging is disabled (e.g. `eth_call`, `eth_estimateGas`, + // `eth_simulateV1` with `validation: false`, `debug_traceCall`), the + // caller was never charged for gas or L1 data fees so no reward may be + // credited to the beneficiary / FeeVault. + if evm.ctx_ref().cfg().is_fee_charge_disabled() { + return Ok(()); + } + // Reuse the L1 data fee cached during validate_and_deduct_eth_fee / // validate_and_deduct_token_fee, avoiding a redundant calculate_tx_l1_cost call. // Read before ctx().all_mut() borrows evm. @@ -443,24 +452,29 @@ where &self, evm: &mut MorphEvm, ) -> Result<(), EVMError> { - let hardfork = *evm.ctx_ref().cfg().spec(); - - // Fetch L1 block info from the L1 Gas Price Oracle contract per-tx. - // Must NOT use a per-block cache because the oracle can be updated by a - // regular transaction (from the external gas-oracle service) within the - // same block. Subsequent user txs must see the updated fee parameters, - // matching go-ethereum's per-tx L1BlockInfo read. - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().db_mut(), hardfork)?; - - let rlp_bytes = evm - .ctx_ref() - .tx() - .rlp_bytes - .as_ref() - .map(|b| b.as_ref()) - .unwrap_or_default(); - - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork); + let is_fee_charge_disabled = evm.ctx_ref().cfg().is_fee_charge_disabled(); + let l1_data_fee = if is_fee_charge_disabled { + U256::ZERO + } else { + let hardfork = *evm.ctx_ref().cfg().spec(); + + // Fetch L1 block info from the L1 Gas Price Oracle contract per-tx. + // Must NOT use a per-block cache because the oracle can be updated by a + // regular transaction (from the external gas-oracle service) within the + // same block. Subsequent user txs must see the updated fee parameters, + // matching go-ethereum's per-tx L1BlockInfo read. + let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().db_mut(), hardfork)?; + + let rlp_bytes = evm + .ctx_ref() + .tx() + .rlp_bytes + .as_ref() + .map(|b| b.as_ref()) + .unwrap_or_default(); + + l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork) + }; evm.cached_l1_data_fee = l1_data_fee; let (block, tx, cfg, journal, _, _) = evm.ctx().all_mut(); @@ -2483,6 +2497,170 @@ mod tests { assert_eq!(new_balance, balance); } + /// Post-Curie simulation (`disable_fee_charge = true`) must credit 0 ETH to + /// the beneficiary / FeeVault even when L1 oracle fees and gas price are + /// non-zero, and must not touch the beneficiary account in the state diff. + #[test] + fn disable_fee_charge_credits_zero_eth_to_beneficiary_post_curie() { + use crate::l1block::{ + GPO_BLOB_SCALAR_SLOT, GPO_COMMIT_SCALAR_SLOT, GPO_IS_CURIE_SLOT, GPO_L1_BASE_FEE_SLOT, + GPO_L1_BLOB_BASE_FEE_SLOT, L1_GAS_PRICE_ORACLE_ADDRESS, + }; + + let caller = address!("1000000000000000000000000000000000000011"); + let recipient = address!("2000000000000000000000000000000000000022"); + let fee_vault = address!("530000000000000000000000000000000000000a"); + let initial_caller_balance = U256::from(10_000_000_000_000_000u128); + let initial_vault_balance = U256::from(1_000u64); + let transfer_value = U256::from(123_456u64); + let gas_price = 2_000_000_000u128; // 2 gwei + let rlp_bytes = Bytes::from(vec![0xab; 256]); + + let build_db = || { + let mut db = CacheDB::new(EmptyDB::default()); + db.insert_account_info( + caller, + AccountInfo { + balance: initial_caller_balance, + ..Default::default() + }, + ); + db.insert_account_info( + fee_vault, + AccountInfo { + balance: initial_vault_balance, + ..Default::default() + }, + ); + db.insert_account_info(L1_GAS_PRICE_ORACLE_ADDRESS, AccountInfo::default()); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_L1_BASE_FEE_SLOT, + U256::from(10_000_000_000u64), // 10 gwei + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_L1_BLOB_BASE_FEE_SLOT, + U256::from(5_000_000_000u64), // 5 gwei + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_COMMIT_SCALAR_SLOT, + U256::from(230_760_020_821u64), + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_BLOB_SCALAR_SLOT, + U256::from(417_565_260u64), + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_IS_CURIE_SLOT, + U256::from(1u64), + ) + .unwrap(); + db + }; + + let make_tx = |value: U256| MorphTxEnv { + inner: TxEnv { + caller, + kind: TxKind::Call(recipient), + gas_limit: 50_000, + gas_price, + gas_priority_fee: Some(gas_price), + value, + data: Bytes::from(vec![0xaa; 64]), + ..Default::default() + }, + rlp_bytes: Some(rlp_bytes.clone()), + ..Default::default() + }; + + // 1. With `disable_fee_charge = true`: beneficiary receives 0 ETH (and is not even + // touched in the returned state diff), caller only pays `value`, and cached L1 fee is 0. + let mut sim_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + sim_evm.block.inner.beneficiary = fee_vault; + sim_evm.block.inner.basefee = 1_000_000; + sim_evm.cfg.disable_fee_charge = true; + + let sim_res = sim_evm.transact(make_tx(transfer_value)).unwrap(); + assert!(sim_res.result.is_success()); + assert_eq!(sim_evm.cached_l1_data_fee(), U256::ZERO); + assert!( + !sim_res.state.contains_key(&fee_vault), + "FeeVault must not be credited or touched when disable_fee_charge is true" + ); + assert_eq!( + sim_res.state.get(&caller).unwrap().info.balance, + initial_caller_balance - transfer_value, + "caller must only pay tx.value, not L1 or L2 fees" + ); + assert_eq!( + sim_res.state.get(&recipient).unwrap().info.balance, + transfer_value + ); + + // 2. Direct `reward_beneficiary` guard: even if `cached_l1_data_fee` were populated + // directly, `reward_beneficiary` must still skip crediting FeeVault when + // `disable_fee_charge = true`. + let mut direct_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + direct_evm.block.inner.beneficiary = fee_vault; + direct_evm.block.inner.basefee = 1_000_000; + direct_evm.cfg.disable_fee_charge = true; + direct_evm.tx = make_tx(U256::ZERO); + direct_evm.cached_l1_data_fee = U256::from(999_999u64); + let mut frame_result = revm::handler::FrameResult::Call(revm::interpreter::CallOutcome { + result: revm::interpreter::InterpreterResult::new( + revm::interpreter::InstructionResult::Stop, + Bytes::new(), + Gas::new(21_000), + ), + memory_offset: 0..0, + was_precompile_called: false, + precompile_call_logs: Vec::new(), + charged_new_account_state_gas: false, + }); + as Handler>::reward_beneficiary( + &MorphEvmHandler::default(), + &mut direct_evm, + &mut frame_result, + ) + .unwrap(); + assert!( + !direct_evm.ctx.journal_mut().state.contains_key(&fee_vault), + "reward_beneficiary must return early without crediting beneficiary when fee charge is disabled" + ); + + // 3. Sanity contrast: with `disable_fee_charge = false`, FeeVault receives exact + // `execution_fee + l1_data_fee`. + let mut real_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + real_evm.block.inner.beneficiary = fee_vault; + real_evm.block.inner.basefee = 1_000_000; + let real_res = real_evm.transact(make_tx(transfer_value)).unwrap(); + assert!(real_res.result.is_success()); + let expected_l1_fee = real_evm.cached_l1_data_fee(); + assert!(expected_l1_fee > U256::ZERO); + let expected_exec_fee = U256::from(gas_price) * U256::from(real_res.result.tx_gas_used()); + assert_eq!( + real_res.state.get(&fee_vault).unwrap().info.balance, + initial_vault_balance + expected_exec_fee + expected_l1_fee + ); + } + #[test] fn validate_and_deduct_token_fee_rejects_unregistered_token_in_simulation() { let caller = address!("1000000000000000000000000000000000000001"); diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 4f880141..d954c6be 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -42,7 +42,7 @@ reth-transaction-pool.workspace = true # Alloy alloy-consensus.workspace = true -alloy-evm.workspace = true +alloy-evm = { workspace = true, features = ["overrides", "call-util"] } alloy-primitives.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-eth.workspace = true @@ -59,6 +59,7 @@ serde.workspace = true derive_more.workspace = true tokio.workspace = true revm.workspace = true +revm-inspectors.workspace = true # Error handling thiserror.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index b1141e31..35508a66 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -1,26 +1,64 @@ -//! Morph `eth_call` / `eth_estimateGas` overrides. +//! Morph `eth_call` / `eth_estimateGas` / `eth_simulateV1` overrides. //! -//! [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps -//! gas by `balance − value − l1_fee` (ETH path) or a token-denominated limit -//! (MorphTx `fee_token_id > 0`, see `token_gas_allowance`). `eth_call` and -//! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall -//! through to the upstream allowance without the L1-fee extension, except -//! that fee-token callers are left uncapped for the handler. +//! - [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps +//! gas by `balance − value − l1_fee` (ETH path) or a token-denominated limit +//! (MorphTx `fee_token_id > 0`, see `token_gas_allowance`). `eth_call` and +//! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall +//! through to the upstream allowance without the L1-fee extension, except +//! that fee-token callers are left uncapped for the handler. +//! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee +//! charging (including Morph's non-zero L1 data fee) when `validation: false` +//! and passes each transaction's real EIP-2718 encoding when `validation: true` +//! so Curie `commit + blob` (and pre-Curie calldata) L1 fees are accurately +//! charged and validated. 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_consensus::BlockHeader; +use alloy_eips::eip2718::{Encodable2718, WithEncoded}; +use alloy_evm::{ + block::TxResult, + call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}, + overrides::{OverrideBlockHashes, apply_block_overrides, apply_state_overrides}, +}; +use alloy_network::TransactionBuilder; +use alloy_primitives::{B256, U256}; +use alloy_rpc_types_eth::{ + BlockId, + simulate::{SimBlock, SimulatePayload, SimulatedBlock}, +}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; -use reth_evm::{EvmEnvFor, TxEnvFor}; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; +use reth_errors::RethError; +use reth_evm::{ + ConfigureEvm, Evm, EvmEnvFor, TxEnvFor, + env::BlockEnvironment, + execute::{BlockBuilder, BlockBuilderOutcome, BlockExecutor}, +}; use reth_provider::ChainSpecProvider; +use reth_revm::{database::StateProviderDatabase, db::State}; +use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - EthApiTypes, RpcNodeCore, - helpers::{Call, EthCall, estimate::EstimateCall}, + EthApiTypes, RpcBlock, RpcNodeCore, + helpers::{ + Call, EthCall, LoadBlock, LoadPendingBlock, SpawnBlocking, call::SimulatedBlocksResult, + estimate::EstimateCall, + }, }; -use reth_rpc_eth_types::EthApiError; -use revm::{Database, context::Transaction as RevmTransaction}; +use reth_rpc_eth_types::{ + EthApiError, + error::{AsEthApiError, FromEthApiError}, + simulate::{self, EthSimulateError}, +}; +use reth_storage_api::{StateProvider, noop::NoopProvider}; +use revm::{ + Database, + context::{Block, Transaction as RevmTransaction}, + context_interface::{Cfg, result::ExecutionResult}, +}; +use revm_inspectors::transfer::TransferInspector; +use std::collections::BTreeMap; impl EthCall for MorphEthApi where @@ -30,6 +68,343 @@ where reth_rpc_convert::RpcConvert, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { + async fn simulate_v1( + &self, + payload: SimulatePayload::Network>>, + block: Option, + ) -> SimulatedBlocksResult { + if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { + return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into()); + } + + let block = block.unwrap_or_default(); + + let SimulatePayload { + block_state_calls, + trace_transfers, + validation, + return_full_transactions, + } = payload; + + if block_state_calls.is_empty() { + return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); + } + + let _permit = self + .acquire_owned_blocking_io() + .await + .map_err(|_| EthApiError::InternalEthError)?; + + let base_block = self + .recovered_block(block) + .await? + .ok_or_else(|| EthApiError::other(EthSimulateError::BlockNotFound { block }))?; + let parent = base_block.sealed_header().clone(); + let max_simulate_blocks = self.max_simulate_blocks(); + + self.spawn_with_state_at_block(block, move |this, db| { + let state_provider = db.database.0.0; + let mut db = State::builder() + .with_database(StateProviderDatabase::new(&state_provider)) + .with_bundle_update() + .build(); + let mut parent = parent; + + let chain_id = this.provider().chain_spec().chain_id(); + + // Validate block ordering and fill gaps with empty blocks so every entry has an + // explicit `number` and `time` override and the chain is contiguous. + let block_state_calls = simulate::sanitize_chain( + block_state_calls, + &parent, + chain_id, + max_simulate_blocks, + )?; + + let mut blocks: Vec>> = + Vec::with_capacity(block_state_calls.len()); + + let call_gas_limit = this.call_gas_limit(); + let mut remaining_call_gas_limit = (call_gas_limit > 0).then_some(call_gas_limit); + + for block in block_state_calls { + let SimBlock { + block_overrides, + state_overrides, + calls, + } = block; + + let attributes = this + .pending_env_builder() + .pending_env_attributes(&parent, block_overrides.as_ref()) + .map_err(Self::Error::from_eth_err)?; + + let mut evm_env = this + .evm_config() + .next_evm_env(&parent, &attributes) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + + // Always disable EIP-3607. + evm_env.cfg_env.disable_eip3607 = true; + + // EIP-7825's transaction gas cap is only active with Amsterdam's + // regular/state-gas accounting. + if !evm_env.cfg_env.is_amsterdam_eip8037_enabled() { + evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX); + } + + if !validation { + // If not explicitly required, disable nonce check + // . + evm_env.cfg_env.disable_nonce_check = true; + evm_env.cfg_env.disable_base_fee = true; + // Unlike OP-Stack, Morph's post-Curie L1 commit fee is non-zero even for + // empty RLP bytes. Disabling fee charging matches `eth_call` semantics so + // `validation: false` does not reject zero-balance / omitted-`from` + // callers or mutate caller / FeeVault balances or emit fee Transfer logs. + evm_env.cfg_env.disable_fee_charge = true; + evm_env.block_env.inner_mut().basefee = 0; + } + + // Set prevrandao to zero for simulated blocks by default, + // matching spec behavior where MixDigest is zero-initialized. + // If user provides an override, it will be applied by apply_block_overrides. + evm_env.block_env.inner_mut().prevrandao = Some(B256::ZERO); + if !this + .provider() + .chain_spec() + .is_paris_active_at_block(evm_env.block_env.number().saturating_to()) + { + evm_env.block_env.inner_mut().difficulty = parent.difficulty(); + } + + if let Some(block_overrides) = block_overrides { + // Ensure we don't allow uncapped gas limit per block. + if let Some(gas_limit_override) = block_overrides.gas_limit + && gas_limit_override > evm_env.block_env.gas_limit() + && gas_limit_override > this.call_gas_limit() + { + return Err(EthApiError::other(EthSimulateError::GasLimitReached).into()); + } + apply_block_overrides(block_overrides, &mut db, evm_env.block_env.inner_mut()); + } + if let Some(ref state_overrides) = state_overrides { + apply_state_overrides(state_overrides.clone(), &mut db) + .map_err(Self::Error::from_eth_err)?; + } + + let chain_id = evm_env.cfg_env.chain_id; + + let ctx = this + .evm_config() + .context_for_next_block(&parent, attributes) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + let map_err = |e: EthApiError| -> Self::Error { + match e.as_simulate_error() { + Some(sim_err) => Self::Error::from_eth_err(EthApiError::other(sim_err)), + None => Self::Error::from_eth_err(e), + } + }; + + let (result, results) = if trace_transfers { + // Prepare inspector to capture transfers inside the EVM so they are + // recorded and included in logs. + let inspector = TransferInspector::new(false).with_logs(true); + let evm = this + .evm_config() + .evm_with_env_and_inspector(&mut db, evm_env, inspector); + let mut builder = this.evm_config().create_block_builder(evm, &parent, ctx); + + if let Some(ref state_overrides) = state_overrides { + simulate::apply_precompile_overrides( + state_overrides, + builder.evm_mut().precompiles_mut(), + ) + .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; + } + + execute_simulated_transactions( + builder, + &state_provider, + calls, + &mut remaining_call_gas_limit, + chain_id, + this.compute_state_root_for_eth_simulate(), + validation, + this.converter(), + ) + .map_err(map_err)? + } else { + let evm = this.evm_config().evm_with_env(&mut db, evm_env); + let mut builder = this.evm_config().create_block_builder(evm, &parent, ctx); + + if let Some(ref state_overrides) = state_overrides { + simulate::apply_precompile_overrides( + state_overrides, + builder.evm_mut().precompiles_mut(), + ) + .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; + } + + execute_simulated_transactions( + builder, + &state_provider, + calls, + &mut remaining_call_gas_limit, + chain_id, + this.compute_state_root_for_eth_simulate(), + validation, + this.converter(), + ) + .map_err(map_err)? + }; + + let simulated_header = result.block.clone_sealed_header(); + db.override_block_hashes(BTreeMap::from([( + simulated_header.number(), + simulated_header.hash(), + )])); + parent = simulated_header; + + let block = simulate::build_simulated_block::( + result.block, + results, + return_full_transactions.into(), + this.converter(), + )?; + + blocks.push(block); + } + + Ok(blocks) + }) + .await + } +} + +/// Morph-aware equivalent of [`simulate::execute_transactions`]. +/// +/// Mirrors upstream `eth_simulateV1` block execution, gas-cap accounting, and +/// state-root handling, while wrapping resolved transactions with their real +/// EIP-2718 encoding when `validation == true` so Morph's L1 data fee charges +/// the full Curie `commit + blob` (or pre-Curie calldata) cost instead of +/// treating transactions as 0-byte envelopes. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] +fn execute_simulated_transactions( + mut builder: S, + state_provider: impl StateProvider, + calls: Vec>, + remaining_call_gas_limit: &mut Option, + chain_id: u64, + compute_state_root: bool, + validation: bool, + converter: &T, +) -> Result< + ( + BlockBuilderOutcome, + Vec::Evm as Evm>::HaltReason>>, + ), + EthApiError, +> +where + S: BlockBuilder>>>>, + T: RpcConvert, +{ + builder.apply_pre_execution_changes()?; + + let mut results = Vec::with_capacity(calls.len()); + let mut cumulative_tx_gas_used: u64 = 0; + let mut block_regular_gas_used: u64 = 0; + let mut block_state_gas_used: u64 = 0; + let block_gas_limit = builder.evm().block().gas_limit(); + let is_amsterdam = builder.evm().cfg_env().enable_amsterdam_eip8037; + let tx_gas_limit_cap = builder.evm().cfg_env().tx_gas_limit_cap.unwrap_or(u64::MAX); + for mut call in calls { + let block_gas_remaining = if is_amsterdam { + block_gas_limit + .saturating_sub(block_regular_gas_used) + .min(block_gas_limit.saturating_sub(block_state_gas_used)) + } else { + block_gas_limit.saturating_sub(cumulative_tx_gas_used) + }; + let mut default_gas_limit = block_gas_remaining; + + if let Some(gas_limit) = call.as_ref().gas_limit() { + let exceeds_gas_limit = if is_amsterdam { + let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used); + let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used); + let regular_tx_gas_limit = gas_limit.min(tx_gas_limit_cap); + + regular_tx_gas_limit > regular_available_gas || gas_limit > state_available_gas + } else { + gas_limit > block_gas_remaining + }; + + if exceeds_gas_limit { + return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded)); + } + } + + if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit { + if let Some(gas_limit) = call.as_ref().gas_limit() { + if gas_limit > remaining_call_gas_limit { + call.as_mut().set_gas_limit(remaining_call_gas_limit); + } + } else { + default_gas_limit = default_gas_limit.min(remaining_call_gas_limit); + } + } + + // Resolve transaction, populate missing fields and enforce calls + // correctness. + let tx = simulate::resolve_transaction( + call, + default_gas_limit, + builder.evm().block().basefee(), + chain_id, + builder.evm().cfg_env().disable_nonce_check, + builder.evm_mut().db_mut(), + converter, + )?; + // When `validation == true`, pass the real EIP-2718 encoding so Morph's L1 + // fee calculation charges the full commit + blob (Curie) or calldata + // (pre-Curie) fee. When `validation == false`, `disable_fee_charge` skips + // L1 fee charging entirely, so an empty envelope avoids wasted encoding. + let encoded = if validation { + tx.encoded_2718().into() + } else { + Default::default() + }; + let tx = WithEncoded::new(encoded, tx); + + let mut tx_regular_gas_used = 0; + let gas_output = builder.execute_transaction_with_result_closure(tx, |result| { + tx_regular_gas_used = result.result().result.gas().block_regular_gas_used(); + results.push(result.result().result.clone()) + })?; + + let gas_used = gas_output.tx_gas_used(); + if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() { + if gas_used > *remaining_call_gas_limit { + return Err(EthApiError::other(EthSimulateError::GasLimitReached)); + } + *remaining_call_gas_limit -= gas_used; + } + + cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used); + block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used); + block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used()); + } + + let result = if compute_state_root { + builder.finish(state_provider, None)? + } else { + builder.finish(NoopProvider::default(), None)? + }; + + Ok((result, results)) } impl EstimateCall for MorphEthApi From b96cab35b0f1f5855061bcdccac317c1260509da Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 27 Nov 2026 00:31:35 +0800 Subject: [PATCH 2/6] fix(rpc): size simulateV1 L1 fees with placeholder sig and preserve MorphTx with legacy gasPrice --- Cargo.lock | 1 + crates/node/tests/it/rpc.rs | 209 +++++++++++++++++--- crates/rpc/Cargo.toml | 1 + crates/rpc/src/eth/call.rs | 319 ++++++++++++++++++++++++++++-- crates/rpc/src/eth/transaction.rs | 299 ++++++++++++++++++++++++---- 5 files changed, 753 insertions(+), 76 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b3e89fe..fdd20910 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5444,6 +5444,7 @@ dependencies = [ "alloy-rpc-types-debug", "alloy-rpc-types-eth", "alloy-serde", + "alloy-signer", "async-trait", "derive_more", "eyre", diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 85c95ad8..16f8b772 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1681,34 +1681,48 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre let max_fee_per_gas = 2_000_000_000u128; // 2 gwei let max_priority_fee_per_gas = 1_000_000_000u128; // 1 gwei - // Build the exact simulated EIP-1559 envelope (`Signature(0, 0, false)`) that - // `resolve_transaction` / `TryIntoSimTx` produces so we know its exact EIP-2718 length. - let sim_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); - let expected_eth_envelope = MorphTxEnvelope::Eip1559( - alloy_consensus::TxEip1559 { - chain_id, - nonce: 0, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to: TxKind::Call(recipient), - value: U256::ZERO, - access_list: Default::default(), - input: calldata.clone(), - } - .into_signed(sim_sig), + // Build the simulated EIP-1559 envelope with both the 3-byte zero signature + // (`TryIntoSimTx`) and the full 64-byte placeholder signature (`U256::MAX, U256::MAX, true`) + // used for L1 fee sizing. + let zero_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = alloy_primitives::Signature::new(U256::MAX, U256::MAX, true); + let tx_inner = alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + }; + let zero_sig_len = MorphTxEnvelope::Eip1559(tx_inner.clone().into_signed(zero_sig)) + .encoded_2718() + .len() as u128; + let encoded_len = MorphTxEnvelope::Eip1559(tx_inner.into_signed(placeholder_sig)) + .encoded_2718() + .len() as u128; + assert_eq!( + encoded_len, + zero_sig_len + 64, + "placeholder signature must add exactly 64 bytes for L1 fee sizing" ); - let encoded_len = expected_eth_envelope.encoded_2718().len() as u128; let commit_only_l1_fee = U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let zero_sig_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * zero_sig_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); let full_l1_fee = U256::from( (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) / L1_FEE_PRECISION, ); assert!( - full_l1_fee > commit_only_l1_fee * U256::from(2u64), - "calldata blob fee must significantly exceed commit-only fee" + full_l1_fee > zero_sig_l1_fee && zero_sig_l1_fee > commit_only_l1_fee * U256::from(2u64), + "placeholder-signature Curie blob fee must strictly exceed zero-signature and commit-only fees" ); let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); @@ -1721,10 +1735,10 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre "input": calldata.to_string(), }); - // (1) Balance covers L2 + commit-only L1 fee (+ half the blob fee), NOT full Curie L1 fee: - // must fail with insufficient funds (-38014). Under the old empty-RLP bug this passed! - let insufficient_balance = - l2_max_fee + commit_only_l1_fee + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + // (1) Balance covers L2 + zero-signature L1 fee (which omits the 64B placeholder + // signature bytes), NOT full placeholder-signature Curie L1 fee: must fail + // with insufficient funds (-38014). + let insufficient_balance = l2_max_fee + zero_sig_l1_fee; let fail_payload = serde_json::json!({ "blockStateCalls": [{ "stateOverrides": { @@ -1739,15 +1753,18 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre let err = client .request::("eth_simulateV1", (fail_payload, "latest")) .await - .expect_err("validation=true must reject when balance omits Curie blob L1 fee"); + .expect_err( + "validation=true must reject when balance omits 64B placeholder signature L1 fee", + ); let err_str = err.to_string(); assert!( err_str.contains("insufficient funds") || err_str.contains("-38014"), "expected insufficient funds error, got: {err_str}" ); - // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed and deduct exact - // `l2_used_fee + full_l1_fee` from sender and credit the same amount to FeeVault. + // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed, charge exact + // `l2_used_fee + full_l1_fee` to sender and FeeVault, AND with + // `returnFullTransactions: true` keep zero `r`/`s`/`v` on the returned tx. let exact_budget = l2_max_fee + full_l1_fee; let pass_payload = serde_json::json!({ "blockStateCalls": [{ @@ -1775,6 +1792,7 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre ], }], "validation": true, + "returnFullTransactions": true, }); let blocks: Value = client .request("eth_simulateV1", (pass_payload, "latest")) @@ -1784,6 +1802,16 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre assert_eq!(calls[0]["status"].as_str(), Some("0x1")); assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + // Returned full transaction must keep zero r/s/v per the eth_simulateV1 spec. + let txs = block["transactions"] + .as_array() + .expect("full transactions array"); + assert_eq!(txs.len(), 2); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + let block_base_fee = u128::from_str_radix( block["baseFeePerGas"] .as_str() @@ -1878,3 +1906,132 @@ async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre Ok(()) } + +/// `eth_simulateV1(validation: true)` with legacy `gasPrice` + `feeTokenID` on a +/// zero-ETH / funded-token caller must execute as a token-fee MorphTx (`0x7f`) +/// rather than silently degrading into a Legacy ETH transaction. +#[tokio::test(flavor = "multi_thread")] +async fn simulate_v1_validation_true_legacy_gas_price_with_fee_token_id_executes_morph_tx() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const TEST_TOKEN: Address = + alloy_primitives::address!("5300000000000000000000000000000000000022"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let token_holder = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let initial_token_hex: String = client + .request( + "eth_call", + ( + serde_json::json!({ + "to": TEST_TOKEN, + "input": encode_balance_of(token_holder), + }), + "latest", + ), + ) + .await?; + let initial_token_balance = decode_u256_word(&initial_token_hex); + assert!( + initial_token_balance > U256::ZERO, + "genesis token holder must have non-zero fee token balance" + ); + + let recipient = Address::random(); + let gas_limit = 50_000u64; + let gas_price = 2_000_000_000u128; // 2 gwei + let calldata = Bytes::from(vec![0xcd; 128]); + + // Zero out `token_holder`'s ETH balance via `stateOverrides` so a Legacy ETH + // fallback would fail immediately with insufficient ETH, while preserving its + // ERC-20 token balance in `TEST_TOKEN`. + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + token_holder.to_string(): { + "balance": "0x0", + }, + }, + "calls": [ + { + "from": token_holder, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "gasPrice": format!("{gas_price:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": calldata.to_string(), + }, + { + "from": token_holder, + "to": TEST_TOKEN, + "gas": "0x186a0", + "gasPrice": format!("{gas_price:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": encode_balance_of(token_holder), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + // Returned full transaction must be a MorphTx (`0x7f`) with `feeTokenID = 1` + // and zero `r`/`s`/`v` signature fields. + let txs = block["transactions"] + .as_array() + .expect("full transactions array"); + assert_eq!(txs[0]["type"].as_str(), Some("0x7f")); + assert_eq!(txs[0]["feeTokenID"].as_str(), Some("0x1")); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + + // ERC-20 `Transfer` fee log emitted on Call 0. + let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + let logs = calls[0]["logs"].as_array().expect("logs array"); + assert!( + logs.iter().any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(transfer_topic) + }), + "gasPrice + feeTokenID MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" + ); + + // Token balance observed during Call 1 must have decreased from Call 0's fee deduction + // (and Call 1's own upfront deduction). + let token_balance_after = decode_u256_word(calls[1]["returnData"].as_str().unwrap()); + assert!( + token_balance_after < initial_token_balance, + "token fees must be deducted from ERC-20 balance: before={initial_token_balance}, after={token_balance_after}" + ); + + Ok(()) +} diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index d954c6be..149bf2f4 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -69,6 +69,7 @@ eyre.workspace = true tracing.workspace = true [dev-dependencies] +alloy-signer.workspace = true serde_json.workspace = true tempfile.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index 35508a66..acd1b907 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -8,13 +8,14 @@ //! that fee-token callers are left uncapped for the handler. //! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee //! charging (including Morph's non-zero L1 data fee) when `validation: false` -//! and passes each transaction's real EIP-2718 encoding when `validation: true` -//! so Curie `commit + blob` (and pre-Curie calldata) L1 fees are accurately -//! charged and validated. +//! and encodes a copy of each simulated transaction with a full-size +//! placeholder signature when `validation: true` so Curie `commit + blob` +//! (and pre-Curie calldata) L1 fees are accurately charged and validated +//! without mutating the zero signature returned to callers. use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_consensus::BlockHeader; +use alloy_consensus::{BlockHeader, Signed}; use alloy_eips::eip2718::{Encodable2718, WithEncoded}; use alloy_evm::{ block::TxResult, @@ -22,12 +23,13 @@ use alloy_evm::{ overrides::{OverrideBlockHashes, apply_block_overrides, apply_state_overrides}, }; use alloy_network::TransactionBuilder; -use alloy_primitives::{B256, U256}; +use alloy_primitives::{B256, Bytes, Signature, U256}; use alloy_rpc_types_eth::{ BlockId, simulate::{SimBlock, SimulatePayload, SimulatedBlock}, }; use morph_chainspec::{MorphChainSpec, MorphHardforks}; +use morph_primitives::{MorphPrimitives, MorphTxEnvelope}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_errors::RethError; @@ -284,13 +286,56 @@ where } } +/// Encodes a simulated transaction with a full-size placeholder signature for L1 +/// data fee sizing, without mutating the transaction itself. +/// +/// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP +/// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero +/// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Encoding that zero signature +/// directly underestimates post-Curie blob fees by 64 bytes (and pre-Curie calldata +/// gas by 64 non-zero bytes). Using the same 64-byte `0xff` + `yParity = 1` +/// placeholder as [`morph_revm::MorphTxEnv::encode_for_l1_fee`] matches real signed +/// transactions and `eth_estimateGas` while keeping `tx`'s zero signature intact. +fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let envelope = match tx { + MorphTxEnvelope::Legacy(signed) => MorphTxEnvelope::Legacy(Signed::new_unchecked( + signed.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip2930(signed) => MorphTxEnvelope::Eip2930(Signed::new_unchecked( + signed.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip1559(signed) => MorphTxEnvelope::Eip1559(Signed::new_unchecked( + signed.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip7702(signed) => MorphTxEnvelope::Eip7702(Signed::new_unchecked( + signed.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Morph(signed) => MorphTxEnvelope::Morph(Signed::new_unchecked( + signed.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::L1Msg(_) => return tx.encoded_2718().into(), + }; + envelope.encoded_2718().into() +} + /// Morph-aware equivalent of [`simulate::execute_transactions`]. /// /// Mirrors upstream `eth_simulateV1` block execution, gas-cap accounting, and -/// state-root handling, while wrapping resolved transactions with their real -/// EIP-2718 encoding when `validation == true` so Morph's L1 data fee charges -/// the full Curie `commit + blob` (or pre-Curie calldata) cost instead of -/// treating transactions as 0-byte envelopes. +/// state-root handling, while wrapping resolved transactions with a full-size +/// placeholder-signature EIP-2718 encoding when `validation == true` so Morph's +/// L1 data fee charges the full Curie `commit + blob` (or pre-Curie calldata) +/// cost without mutating the zero signature stored on `tx`. #[allow(clippy::too_many_arguments, clippy::type_complexity)] fn execute_simulated_transactions( mut builder: S, @@ -309,7 +354,10 @@ fn execute_simulated_transactions( EthApiError, > where - S: BlockBuilder>>>>, + S: BlockBuilder< + Primitives = MorphPrimitives, + Executor: BlockExecutor>>>, + >, T: RpcConvert, { builder.apply_pre_execution_changes()?; @@ -368,12 +416,16 @@ where builder.evm_mut().db_mut(), converter, )?; - // When `validation == true`, pass the real EIP-2718 encoding so Morph's L1 - // fee calculation charges the full commit + blob (Curie) or calldata - // (pre-Curie) fee. When `validation == false`, `disable_fee_charge` skips - // L1 fee charging entirely, so an empty envelope avoids wasted encoding. + // When `validation == true`, encode a copy of `tx` with a full-size + // placeholder signature (`r = s = U256::MAX, yParity = true`, matching + // `MorphTxEnv::encode_for_l1_fee`) so Morph's L1 fee calculation charges + // the full commit + blob (Curie) or calldata (pre-Curie) fee without + // mutating `tx`'s zero signature (`returnFullTransactions: true` keeps + // zero `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec). When + // `validation == false`, `disable_fee_charge` skips L1 fee charging + // entirely, so an empty envelope avoids wasted encoding. let encoded = if validation { - tx.encoded_2718().into() + encode_simulated_tx_for_l1_fee(tx.inner()) } else { Default::default() }; @@ -994,4 +1046,241 @@ mod tests { Some(U256::from(3u64)) ); } + + /// `encode_simulated_tx_for_l1_fee` must re-encode every signed `MorphTxEnvelope` + /// variant with the 64-byte `0xff` + `yParity = 1` placeholder signature (adding + /// 64 bytes vs `TryIntoSimTx`'s zero signature when the outer RLP header width is + /// unchanged), match `MorphTxEnv::encode_for_l1_fee` for EIP-1559 / EIP-7702 / + /// MorphTx, fall back to `encoded_2718` for `L1Msg`, and leave `tx`'s original + /// zero signature untouched. + #[test] + fn encode_simulated_tx_for_l1_fee_uses_full_placeholder_sig_without_mutating_tx() { + use alloy_consensus::{ + Signed, Transaction as _, TxEip1559, TxEip2930, TxEip7702, TxLegacy, + }; + use alloy_eips::{ + eip2718::Decodable2718, + eip7702::{Authorization, SignedAuthorization}, + }; + use alloy_primitives::{Address, Sealed, TxKind, address}; + use morph_primitives::{ + TxL1Msg, TxMorph, + transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, + }; + use morph_revm::MorphTxEnv; + + let chain_id = 2818u64; + let signer = address!("0000000000000000000000000000000000000001"); + let to = address!("0000000000000000000000000000000000000002"); + // 64 bytes of calldata keeps both zero-sig and placeholder-sig RLP payload + // lengths inside `[56, 255]` so the outer RLP list header is 2 bytes for both + // and the length delta is exactly +64 bytes. + let input = Bytes::from(vec![0xab; 64]); + let zero_sig = Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let auth: SignedAuthorization = Authorization { + chain_id: U256::from(chain_id), + address: address!("0000000000000000000000000000000000000042"), + nonce: 1, + } + .into_signed(Signature::new(U256::from(1u64), U256::from(2u64), true)); + + let signed_cases: Vec<(&str, MorphTxEnvelope, bool)> = vec![ + ( + "legacy", + MorphTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(chain_id), + nonce: 7, + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + value: U256::from(1u64), + input: input.clone(), + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip2930", + MorphTxEnvelope::Eip2930(Signed::new_unchecked( + TxEip2930 { + chain_id, + nonce: 7, + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + value: U256::from(1u64), + access_list: Default::default(), + input: input.clone(), + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip1559", + MorphTxEnvelope::Eip1559(Signed::new_unchecked( + TxEip1559 { + chain_id, + nonce: 7, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + value: U256::from(1u64), + access_list: Default::default(), + input: input.clone(), + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "eip7702", + MorphTxEnvelope::Eip7702(Signed::new_unchecked( + TxEip7702 { + chain_id, + nonce: 7, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to, + value: U256::ZERO, + access_list: Default::default(), + authorization_list: vec![auth.clone()], + input: input.clone(), + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "morph_v1", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + nonce: 7, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + value: U256::ZERO, + access_list: Default::default(), + input: input.clone(), + fee_token_id: 1, + fee_limit: U256::from(10_000u64), + version: MORPH_TX_VERSION_1, + reference: Some(B256::repeat_byte(0x11)), + memo: Some(Bytes::from_static(b"sim")), + authorization_list: vec![], + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "morph_v2", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + nonce: 7, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + value: U256::ZERO, + access_list: Default::default(), + input: input.clone(), + fee_token_id: 1, + fee_limit: U256::from(10_000u64), + version: MORPH_TX_VERSION_2, + reference: None, + memo: None, + authorization_list: vec![auth], + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ]; + + for (label, tx, compare_tx_env) in signed_cases { + let zero_encoded = tx.encoded_2718(); + let sized_encoded = encode_simulated_tx_for_l1_fee(&tx); + + // Exactly +64 bytes (r and s expand from 1 byte 0x80 each to 33 bytes each). + assert_eq!( + sized_encoded.len(), + zero_encoded.len() + 64, + "{label}: expected +64 byte delta vs zero signature" + ); + + // Re-decoded envelope carries the exact placeholder signature. + let decoded = MorphTxEnvelope::decode_2718(&mut sized_encoded.as_ref()) + .expect("placeholder encoding must decode cleanly"); + let sig = match &decoded { + MorphTxEnvelope::Legacy(s) => s.signature(), + MorphTxEnvelope::Eip2930(s) => s.signature(), + MorphTxEnvelope::Eip1559(s) => s.signature(), + MorphTxEnvelope::Eip7702(s) => s.signature(), + MorphTxEnvelope::Morph(s) => s.signature(), + MorphTxEnvelope::L1Msg(_) => unreachable!(), + }; + assert_eq!( + *sig, placeholder_sig, + "{label}: decoded signature must match placeholder" + ); + + // Original `tx` must still hold its zero signature untouched. + let orig_sig = match &tx { + MorphTxEnvelope::Legacy(s) => s.signature(), + MorphTxEnvelope::Eip2930(s) => s.signature(), + MorphTxEnvelope::Eip1559(s) => s.signature(), + MorphTxEnvelope::Eip7702(s) => s.signature(), + MorphTxEnvelope::Morph(s) => s.signature(), + MorphTxEnvelope::L1Msg(_) => unreachable!(), + }; + assert_eq!( + *orig_sig, zero_sig, + "{label}: original tx signature must not be mutated" + ); + + // EIP-1559, EIP-7702, and Morph envelopes match `MorphTxEnv::encode_for_l1_fee` + // byte-for-byte (EIP-7702/MorphV2 authorization signatures differ only if recovered, + // and here `from_recovered_tx` keeps the signed auths or replaces with placeholder). + if compare_tx_env && tx.authorization_list().is_none_or(<[_]>::is_empty) { + let env_encoded = + MorphTxEnv::from_recovered_tx(&tx, signer).encode_for_l1_fee(chain_id); + assert_eq!( + sized_encoded, env_encoded, + "{label}: must match MorphTxEnv::encode_for_l1_fee byte-for-byte" + ); + } + } + + // `L1Msg` has no signature and falls back to `encoded_2718`. + let l1_msg = MorphTxEnvelope::L1Msg(Sealed::new_unchecked( + TxL1Msg { + queue_index: 1, + gas_limit: 50_000, + to, + value: U256::ZERO, + input, + sender: Address::ZERO, + }, + B256::ZERO, + )); + assert_eq!( + encode_simulated_tx_for_l1_fee(&l1_msg), + Bytes::from(l1_msg.encoded_2718()) + ); + } } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index d3d0339a..f36c6ac8 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -19,13 +19,16 @@ use reth_evm::EvmEnv; /// [`try_build_morph_tx_from_request`]. impl TryIntoSimTx for MorphTransactionRequest { fn try_into_sim_tx(self) -> Result> { - // Try to build a MorphTx; returns None if this should be a standard Ethereum tx + // Try to build a MorphTx; returns None if this should be a standard Ethereum tx. + // Simulation preserves Morph fields even when legacy `gasPrice` is set, matching + // `TryIntoTxEnv` and geth's `ToMessage`. let morph_tx_result = try_build_morph_tx_from_request( &self.inner, self.fee_token_id.unwrap_or_default(), self.fee_limit.unwrap_or_default(), self.reference, self.memo.clone(), + true, ); match morph_tx_result { @@ -63,13 +66,15 @@ impl SignableTxRequest for MorphTransactionRequest { self, signer: impl TxSigner + Send, ) -> Result { - // Try to build a MorphTx; returns None if this should be a standard Ethereum tx + // Try to build a MorphTx; returns None if this should be a standard Ethereum tx. + // Real transaction signing keeps legacy `gasPrice` as a standard Ethereum tx. let morph_tx_result = try_build_morph_tx_from_request( &self.inner, self.fee_token_id.unwrap_or_default(), self.fee_limit.unwrap_or_default(), self.reference, self.memo, + false, ); match morph_tx_result { @@ -192,8 +197,15 @@ fn morph_envelope_from_ethereum( /// `Ok(None)` if this should be a standard Ethereum transaction, /// or `Err(...)` if there's a validation error. /// -/// Unless the request sets legacy `gasPrice` (always a standard transaction), -/// a MorphTx is constructed when any of these Morph fields is set: +/// When `allow_legacy_gas_price` is `false` (real transaction signing via +/// [`SignableTxRequest`]), setting legacy `gasPrice` forces a standard Ethereum +/// transaction. When `allow_legacy_gas_price` is `true` (simulation via +/// [`TryIntoSimTx`]), Morph fields take precedence and a legacy `gasPrice` maps +/// onto both `max_fee_per_gas` and `max_priority_fee_per_gas` (rejecting +/// requests that specify both `gasPrice` and EIP-1559 fee fields), matching +/// [`TryIntoTxEnv`] and geth's `ToMessage`. +/// +/// A MorphTx is constructed when any of these Morph fields is set: /// - `feeTokenID > 0` (ERC20 gas payment) /// - a non-zero `reference` /// - a non-empty `memo` @@ -210,9 +222,10 @@ fn try_build_morph_tx_from_request( fee_limit: U256, reference: Option, memo: Option, + allow_legacy_gas_price: bool, ) -> Result, &'static str> { let reference = normalize_reference(reference); - if req.gas_price.is_some() { + if !allow_legacy_gas_price && req.gas_price.is_some() { return Ok(None); } @@ -227,6 +240,18 @@ fn try_build_morph_tx_from_request( return Ok(None); } + let (max_fee_per_gas, max_priority_fee_per_gas) = if let Some(gas_price) = req.gas_price { + if req.max_fee_per_gas.is_some() || req.max_priority_fee_per_gas.is_some() { + return Err("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"); + } + (gas_price, gas_price) + } else { + ( + req.max_fee_per_gas.unwrap_or_default(), + req.max_priority_fee_per_gas.unwrap_or_default(), + ) + }; + let authorization_list = req.authorization_list.clone().unwrap_or_default(); let version = TxMorph::inferred_version(!authorization_list.is_empty()); @@ -236,8 +261,6 @@ fn try_build_morph_tx_from_request( .ok_or("missing chain_id for morph transaction")?; let gas_limit = req.gas.unwrap_or_default(); let nonce = req.nonce.unwrap_or_default(); - let max_fee_per_gas = req.max_fee_per_gas.unwrap_or_default(); - let max_priority_fee_per_gas = req.max_priority_fee_per_gas.unwrap_or_default(); let access_list: AccessList = req.access_list.clone().unwrap_or_default(); let input = req .input @@ -846,7 +869,8 @@ mod tests { #[test] fn try_build_morph_tx_returns_none_for_standard_tx() { let req = create_basic_transaction_request(); - let result = try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None); + let result = + try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None, false); assert!(result.is_ok()); assert!(result.unwrap().is_none()); } @@ -854,8 +878,14 @@ mod tests { #[test] fn try_build_morph_tx_with_fee_token_id() { let req = create_morph_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None); + let result = try_build_morph_tx_from_request( + &req, + U64::from(1), + U256::from(1_000_000), + None, + None, + false, + ); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.fee_token_id, 1); @@ -866,8 +896,14 @@ mod tests { #[test] fn try_build_morph_tx_treats_gas_price_with_morph_fields_as_standard_tx() { let req = create_basic_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None); + let result = try_build_morph_tx_from_request( + &req, + U64::from(1), + U256::from(1_000_000), + None, + None, + false, + ); assert!(result.is_ok()); assert!(result.unwrap().is_none()); @@ -877,8 +913,14 @@ mod tests { fn try_build_morph_tx_with_reference_only() { let req = create_morph_transaction_request(); let reference = B256::random(); - let result = - try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, Some(reference), None); + let result = try_build_morph_tx_from_request( + &req, + U64::ZERO, + U256::ZERO, + Some(reference), + None, + false, + ); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.reference, Some(reference)); @@ -888,8 +930,14 @@ mod tests { #[test] fn try_build_morph_tx_treats_zero_reference_as_absent() { let req = create_morph_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::ZERO, Some(B256::ZERO), None); + let result = try_build_morph_tx_from_request( + &req, + U64::from(1), + U256::ZERO, + Some(B256::ZERO), + None, + false, + ); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); @@ -901,8 +949,14 @@ mod tests { fn try_build_morph_tx_with_memo_only() { let req = create_morph_transaction_request(); let memo = Bytes::from("hello world"); - let result = - try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, Some(memo.clone())); + let result = try_build_morph_tx_from_request( + &req, + U64::ZERO, + U256::ZERO, + None, + Some(memo.clone()), + false, + ); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.memo, Some(memo)); @@ -911,8 +965,14 @@ mod tests { #[test] fn try_build_morph_tx_empty_memo_is_not_trigger() { let req = create_morph_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, Some(Bytes::new())); + let result = try_build_morph_tx_from_request( + &req, + U64::ZERO, + U256::ZERO, + None, + Some(Bytes::new()), + false, + ); assert!(result.is_ok()); // Empty memo should NOT trigger MorphTx creation assert!(result.unwrap().is_none()); @@ -941,10 +1001,16 @@ mod tests { #[test] fn try_build_morph_tx_with_authorization_list_selects_v2() { let req = create_v2_transaction_request(); - let tx = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None) - .unwrap() - .expect("fee token + authorization list builds a MorphTx"); + let tx = try_build_morph_tx_from_request( + &req, + U64::from(1), + U256::from(1_000_000), + None, + None, + false, + ) + .unwrap() + .expect("fee token + authorization list builds a MorphTx"); assert_eq!(tx.version, MORPH_TX_VERSION_2); assert_eq!(tx.fee_token_id, 1); @@ -956,7 +1022,8 @@ mod tests { fn try_build_morph_tx_authorization_list_without_morph_fields_is_standard_tx() { // No Morph field → stays a standard (EIP-7702) transaction. let req = create_v2_transaction_request(); - let result = try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None); + let result = + try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None, false); assert!(result.unwrap().is_none()); } @@ -969,6 +1036,7 @@ mod tests { U256::ZERO, None, Some(Bytes::from("memo")), + false, ) .unwrap() .expect("memo + authorization list builds a MorphTx"); @@ -993,6 +1061,7 @@ mod tests { U256::ZERO, None, Some(Bytes::from("memo")), + false, ) .unwrap() .expect("memo builds a MorphTx"); @@ -1009,9 +1078,10 @@ mod tests { req.to = None; req.input = TransactionInput::new(Bytes::from_static(&[0x60, 0x80])); - let tx = try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None) - .unwrap() - .expect("token fee builds a MorphTx"); + let tx = + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false) + .unwrap() + .expect("token fee builds a MorphTx"); assert_eq!(tx.version, MORPH_TX_VERSION_1); assert!(tx.to.is_create()); assert!(tx.validate().is_ok()); @@ -1023,9 +1093,10 @@ mod tests { authorization_list: Some(vec![]), ..create_morph_transaction_request() }; - let tx = try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None) - .unwrap() - .unwrap(); + let tx = + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false) + .unwrap() + .unwrap(); assert_eq!(tx.version, MORPH_TX_VERSION_1); assert!(tx.authorization_list.is_empty()); } @@ -1037,7 +1108,7 @@ mod tests { req.input = TransactionInput::new(Bytes::from_static(&[0x60, 0x80])); let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); assert_eq!( result.unwrap_err(), "MorphTx with an authorization list cannot create a contract" @@ -1290,7 +1361,7 @@ mod tests { let mut req = create_morph_transaction_request(); req.chain_id = None; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); assert!(result.is_err()); assert!(result.unwrap_err().contains("chain_id")); } @@ -1304,7 +1375,7 @@ mod tests { }; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); assert_eq!(result.unwrap_err(), "data and input fields must match"); } @@ -1315,7 +1386,7 @@ mod tests { req.to = None; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); assert_eq!(result.unwrap_err(), "contract creation requires initcode"); } @@ -1329,6 +1400,7 @@ mod tests { U256::from(500_000), Some(B256::random()), Some(Bytes::from("memo")), + false, ); let tx = result.unwrap().unwrap(); assert_eq!(tx.chain_id, 2818); @@ -1338,6 +1410,163 @@ mod tests { assert_eq!(tx.value, U256::from(1000)); } + #[test] + fn try_into_sim_tx_preserves_morph_fields_with_legacy_gas_price() { + // 1. feeTokenID + legacy gasPrice builds a MorphTx with both caps set to gasPrice. + let req = MorphTransactionRequest { + inner: create_basic_transaction_request(), + fee_token_id: Some(U64::from(1)), + fee_limit: Some(U256::from(1_000_000)), + reference: None, + memo: None, + }; + let env = req + .try_into_sim_tx() + .expect("simulation with feeTokenID + gasPrice must build MorphTx"); + let MorphTxEnvelope::Morph(signed) = env else { + panic!("expected MorphTxEnvelope::Morph, got {env:?}"); + }; + assert_eq!(signed.tx().fee_token_id, 1); + assert_eq!(signed.tx().fee_limit, U256::from(1_000_000)); + assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); + assert_eq!( + *signed.signature(), + Signature::new(U256::ZERO, U256::ZERO, false) + ); + + // 2. reference + legacy gasPrice preserves reference as MorphTx. + let reference = B256::repeat_byte(0x42); + let req = MorphTransactionRequest { + inner: create_basic_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: Some(reference), + memo: None, + }; + let env = req + .try_into_sim_tx() + .expect("simulation with reference + gasPrice must build MorphTx"); + let MorphTxEnvelope::Morph(signed) = env else { + panic!("expected MorphTxEnvelope::Morph, got {env:?}"); + }; + assert_eq!(signed.tx().reference, Some(reference)); + assert_eq!(signed.tx().fee_token_id, 0); + assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); + + // 3. memo + legacy gasPrice preserves memo as MorphTx. + let memo = Bytes::from_static(b"hello"); + let req = MorphTransactionRequest { + inner: create_basic_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(memo.clone()), + }; + let env = req + .try_into_sim_tx() + .expect("simulation with memo + gasPrice must build MorphTx"); + let MorphTxEnvelope::Morph(signed) = env else { + panic!("expected MorphTxEnvelope::Morph, got {env:?}"); + }; + assert_eq!(signed.tx().memo, Some(memo)); + assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); + + // 4. Legacy gasPrice with NO Morph fields stays a standard Legacy tx. + let standard = MorphTransactionRequest { + inner: create_basic_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: None, + }; + let env = standard + .try_into_sim_tx() + .expect("plain gasPrice request builds standard Legacy tx"); + assert!( + matches!(env, MorphTxEnvelope::Legacy(_)), + "expected Legacy, got {env:?}" + ); + } + + #[test] + fn try_into_sim_tx_rejects_conflicting_gas_price_and_eip1559_fields_with_morph_fields() { + // gasPrice + maxFeePerGas + feeTokenID + let mut inner = create_basic_transaction_request(); + inner.max_fee_per_gas = Some(2_000_000_000); + let req = MorphTransactionRequest { + inner, + fee_token_id: Some(U64::from(1)), + fee_limit: None, + reference: None, + memo: None, + }; + let err = req + .try_into_sim_tx() + .expect_err("gasPrice + maxFeePerGas must fail"); + assert!( + err.to_string() + .contains("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"), + "unexpected error: {err}" + ); + + // gasPrice + maxPriorityFeePerGas + memo + let mut inner = create_basic_transaction_request(); + inner.max_priority_fee_per_gas = Some(100_000_000); + let req = MorphTransactionRequest { + inner, + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(Bytes::from_static(b"memo")), + }; + let err = req + .try_into_sim_tx() + .expect_err("gasPrice + maxPriorityFeePerGas must fail"); + assert!( + err.to_string() + .contains("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn signable_tx_request_keeps_legacy_gas_price_with_morph_fields_as_standard_tx() { + struct DummySigner; + + #[async_trait::async_trait] + impl TxSigner for DummySigner { + fn address(&self) -> Address { + address!("0000000000000000000000000000000000000001") + } + + async fn sign_transaction( + &self, + _tx: &mut dyn SignableTransaction, + ) -> alloy_signer::Result { + Ok(Signature::new(U256::from(1u64), U256::from(2u64), false)) + } + } + + let req = MorphTransactionRequest { + inner: create_basic_transaction_request(), + fee_token_id: Some(U64::from(1)), + fee_limit: Some(U256::from(1_000_000)), + reference: None, + memo: None, + }; + let signed = req + .try_build_and_sign(DummySigner) + .await + .expect("real signing with legacy gasPrice must stay a standard Legacy tx"); + assert!( + matches!(signed, MorphTxEnvelope::Legacy(_)), + "expected Legacy tx from SignableTxRequest, got {signed:?}" + ); + } + // ========================================================================= // FromConsensusTx tests // ========================================================================= From 22760399fdd827963207e4a49abc9d69badea00a Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Mon, 30 Nov 2026 17:44:52 +0800 Subject: [PATCH 3/6] refactor(rpc,evm): delegate simulateV1 tx execution upstream and simplify tests - Move encode_simulated_tx_for_l1_fee to morph-revm and fill empty simulated WithEncoded envelopes in MorphBlockExecutor::execute_transaction_without_commit when fee charging is enabled (validation: true). - Delete the copied 128-line execute_simulated_transactions loop in crates/rpc/src/eth/call.rs, call upstream simulate::execute_transactions via a shared helper across trace_transfers / non-tracing paths, and drop dead Amsterdam / pre-Paris branches in simulate_v1 while keeping explicit disable_fee_charge = true when validation is false. - Normalize legacy gasPrice + Morph fields in TryIntoSimTx::try_into_sim_tx without changing try_build_morph_tx_from_request's signature, removing 18 unrelated test edits and the alloy-signer dev-dependency. - Consolidate the three read-only eth_simulateV1 integration tests onto one shared post-Curie node in crates/node/tests/it/rpc.rs. --- Cargo.lock | 1 - crates/evm/src/block/mod.rs | 20 +- crates/node/tests/it/rpc.rs | 1032 ++++++++++++----------------- crates/revm/src/lib.rs | 2 +- crates/revm/src/tx.rs | 214 +++++- crates/rpc/Cargo.toml | 1 - crates/rpc/src/eth/call.rs | 528 ++------------- crates/rpc/src/eth/transaction.rs | 384 ++++------- 8 files changed, 816 insertions(+), 1366 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fdd20910..8b3e89fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5444,7 +5444,6 @@ dependencies = [ "alloy-rpc-types-debug", "alloy-rpc-types-eth", "alloy-serde", - "alloy-signer", "async-trait", "derive_more", "eyre", diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 9b66a3f9..9d484303 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -24,10 +24,13 @@ use alloy_evm::{ }; use alloy_primitives::{Address, U256}; use morph_primitives::{MorphReceipt, MorphTxEnvelope}; -use morph_revm::{L1_GAS_PRICE_ORACLE_ADDRESS, MorphHaltReason, TokenFeeInfo, evm::MorphContext}; +use morph_revm::{ + L1_GAS_PRICE_ORACLE_ADDRESS, MorphHaltReason, TokenFeeInfo, encode_simulated_tx_for_l1_fee, + evm::MorphContext, +}; use reth_primitives_traits::Recovered; use reth_revm::{DatabaseCommit, Inspector, context::result::ResultAndState}; -use revm::context::Block; +use revm::context::{Block, Cfg as _}; /// The result of executing a Morph transaction. /// @@ -208,7 +211,7 @@ where &mut self, tx: impl ExecutableTx, ) -> Result { - let (tx_env, recovered) = tx.into_parts(); + let (mut tx_env, recovered) = tx.into_parts(); // Validate gas limit against the geth-compatible block gas pool. Receipt gas cannot be // used here: L1 messages report their actual execution cost in receipts but reserve their @@ -226,6 +229,17 @@ where ))); } + // Upstream `eth_simulateV1` (`simulate::execute_transactions`) wraps resolved + // transactions in an empty `WithEncoded` envelope (`Default::default()`) with a + // zero signature on `recovered`. When fee charging is enabled (`validation: true`), + // encode a copy with a full-size placeholder signature so Morph's L1 data fee + // matches real signed transactions without mutating `recovered`'s zero signature. + if !self.evm.cfg_env().is_fee_charge_disabled() + && tx_env.rlp_bytes.as_ref().is_none_or(|b| b.is_empty()) + { + tx_env.rlp_bytes = Some(encode_simulated_tx_for_l1_fee(recovered.tx())); + } + // Clone the consensus tx and signer BEFORE transact (since we can't move out later). let consensus_tx = recovered.tx().clone(); let signer = *recovered.signer(); diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 16f8b772..42d24f89 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1353,14 +1353,15 @@ fn encode_balance_of(addr: Address) -> String { format!("0x{}", alloy_primitives::hex::encode(buf)) } -/// `eth_simulateV1` with `validation: false` must disable L1 and L2 fee charging -/// for both ETH and token-fee MorphTxs post-Curie with non-zero L1 oracle fees: -/// - Omitted-`from` and zero-balance callers succeed. -/// - Funded caller balances and FeeVault balance are unchanged by L1/L2 fees -/// (and `value > 0` transfers move only `value`). -/// - Call-mode token-fee MorphTxs neither deduct tokens nor emit fee `Transfer` logs. +/// End-to-end `eth_simulateV1` coverage on a single post-Curie node with non-zero L1 oracle fees: +/// 1. `validation: false` skips L1 and L2 fees for ETH & call-mode token MorphTxs (including +/// `traceTransfers: true`), leaves FeeVault/caller balances unchanged, and moves only `value`. +/// 2. `validation: true` charges full placeholder-signature Curie `commit + blob` L1 + L2 fees +/// (for both ETH and token-fee MorphTxs) while keeping zero `r`/`s`/`v`/`yParity` on returned txs. +/// 3. `validation: true` with legacy `gasPrice` + `feeTokenID` on a zero-ETH caller executes as +/// a `0x7f` token-fee MorphTx rather than degrading to Legacy ETH. #[tokio::test(flavor = "multi_thread")] -async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> { +async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> { reth_tracing::init_test_tracing(); const L1_ORACLE: Address = @@ -1369,10 +1370,17 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> alloy_primitives::address!("530000000000000000000000000000000000000a"); const TEST_TOKEN: Address = alloy_primitives::address!("5300000000000000000000000000000000000022"); - const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie commit fee) - const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie blob fee) - // Runtime bytecode: return `BALANCE(calldataload(0))` (32 bytes). + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + // Matches `tests/assets/test-genesis.json` slots 7 & 8. + const COMMIT_SCALAR: u128 = 0x35ba5d7b55; + const BLOB_SCALAR: u128 = 0x18e38a4c; + const L1_FEE_PRECISION: u128 = 1_000_000_000; + const TRANSFER_TOPIC: &str = + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + // Return `BALANCE(calldataload(0))` (32 bytes) / `(BALANCE(0), BALANCE(32))` (64 bytes). const BALANCE_READER_CODE: &str = "0x6000353160005260206000f3"; + const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; let (mut nodes, wallet) = TestNodeBuilder::new() .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) @@ -1380,6 +1388,7 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> .build() .await?; let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; let funded = wallet.inner.address(); advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; @@ -1398,640 +1407,413 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> .map(|a| a.balance) .unwrap_or_default(); - // Read funded wallet's initial call-mode fee token balance via eth_call. let initial_token_hex: String = client .request( "eth_call", ( - serde_json::json!({ - "to": TEST_TOKEN, - "input": encode_balance_of(funded), - }), + serde_json::json!({ "to": TEST_TOKEN, "input": encode_balance_of(funded) }), "latest", ), ) .await?; let initial_token_balance = decode_u256_word(&initial_token_hex); - assert!( - initial_token_balance > U256::ZERO, - "funded wallet must hold genesis test fee tokens" - ); + assert!(initial_token_balance > U256::ZERO); + + let has_transfer_log = |call: &Value| { + call["logs"] + .as_array() + .expect("logs array") + .iter() + .any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(TRANSFER_TOPIC) + }) + }; - let reader_addr = Address::random(); - let unfunded_caller = Address::random(); - let recipient = Address::random(); - let value_recipient = Address::random(); - let transfer_value = U256::from(1_000_000_000_000_000_000u128); // 1 ETH - let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); - - let payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - reader_addr.to_string(): { - "code": BALANCE_READER_CODE, - }, - }, - "calls": [ - // 0: omitted `from` (spec default 0x0000...0000, zero ETH) - { - "to": recipient, - "input": calldata, - }, - // 1: explicit zero-balance caller with non-zero gasPrice - { - "from": unfunded_caller, - "to": recipient, - "gasPrice": "0x3b9aca00", - "input": calldata, - }, - // 2: funded caller, value = 0, non-zero EIP-1559 fee caps + calldata - { - "from": funded, - "to": recipient, - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - "input": calldata, + // ------------------------------------------------------------------------- + // 1. `validation: false` skips L1/L2 fees for ETH & call-mode token MorphTxs + // ------------------------------------------------------------------------- + { + let reader_addr = Address::random(); + let unfunded_caller = Address::random(); + let recipient = Address::random(); + let value_recipient = Address::random(); + let transfer_value = U256::from(1_000_000_000_000_000_000u128); + let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); + + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, }, - // 3: check funded caller ETH balance unchanged - { - "to": reader_addr, - "input": encode_address_word(funded), - }, - // 4: check FeeVault ETH balance unchanged (no phantom reward) - { - "to": reader_addr, - "input": encode_address_word(FEE_VAULT), - }, - // 5: funded caller, value = 1 ETH transfer - { - "from": funded, - "to": value_recipient, - "value": format!("{transfer_value:#x}"), - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - }, - // 6: check funded caller ETH balance decreased by exact transfer_value - { - "to": reader_addr, - "input": encode_address_word(funded), - }, - // 7: check value_recipient received exact transfer_value - { - "to": reader_addr, - "input": encode_address_word(value_recipient), - }, - // 8: check FeeVault ETH balance still unchanged - { - "to": reader_addr, - "input": encode_address_word(FEE_VAULT), - }, - // 9: call-mode token-fee MorphTx from unfunded caller (0 ETH, 0 tokens) - { - "from": unfunded_caller, - "to": recipient, - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": "0x0", - "input": calldata, - }, - // 10: call-mode token-fee MorphTx from funded wallet (must emit 0 logs & deduct 0 tokens) - { - "from": funded, - "to": recipient, - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": "0xde0b6b3a7640000", - "input": calldata, - }, - // 11: check funded wallet token balance unchanged - { - "to": TEST_TOKEN, - "input": encode_balance_of(funded), - }, - // 12: check FeeVault token balance unchanged (0) - { - "to": TEST_TOKEN, - "input": encode_balance_of(FEE_VAULT), - }, - ], - }], - "validation": false, - "returnFullTransactions": true, - }); - - let blocks: Value = client - .request("eth_simulateV1", (payload, "latest")) - .await?; - let block = &blocks[0]; - let calls = block["calls"].as_array().expect("calls array"); - assert_eq!(calls.len(), 13); + "calls": [ + // 0: omitted `from` + { "to": recipient, "input": calldata }, + // 1: zero-balance caller with non-zero gasPrice + { "from": unfunded_caller, "to": recipient, "gasPrice": "0x3b9aca00", "input": calldata }, + // 2: funded caller, value = 0 + { "from": funded, "to": recipient, "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00", "input": calldata }, + // 3-4: check funded caller & FeeVault ETH balances unchanged + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 5: funded caller, value = 1 ETH transfer + { "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}"), "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00" }, + // 6-8: check funded, recipient, and FeeVault balances + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(value_recipient) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 9-10: unfunded & funded call-mode token-fee MorphTxs + { "from": unfunded_caller, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0x0", "input": calldata }, + { "from": funded, "to": recipient, "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00", "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0xde0b6b3a7640000", "input": calldata }, + // 11-12: check funded & FeeVault token balances unchanged + { "to": TEST_TOKEN, "input": encode_balance_of(funded) }, + { "to": TEST_TOKEN, "input": encode_balance_of(FEE_VAULT) }, + ], + }], + "validation": false, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls.len(), 13); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } - for (idx, call) in calls.iter().enumerate() { assert_eq!( - call["status"].as_str(), - Some("0x1"), - "call {idx} must succeed under validation=false: {call}" + decode_u256_word(calls[3]["returnData"].as_str().unwrap()), + initial_funded_balance ); - } - - // Funded caller ETH balance unchanged after value=0 call. - assert_eq!( - decode_u256_word(calls[3]["returnData"].as_str().unwrap()), - initial_funded_balance, - "validation=false must not deduct L1/L2 fees from funded caller" - ); - // FeeVault ETH balance unchanged after value=0 call. - assert_eq!( - decode_u256_word(calls[4]["returnData"].as_str().unwrap()), - initial_vault_balance, - "validation=false must not credit phantom fees to FeeVault" - ); - // Funded caller ETH balance reduced by exact transfer_value after value>0 call. - assert_eq!( - decode_u256_word(calls[6]["returnData"].as_str().unwrap()), - initial_funded_balance - transfer_value, - "value transfer under validation=false must debit only tx.value" - ); - assert_eq!( - decode_u256_word(calls[7]["returnData"].as_str().unwrap()), - transfer_value, - "recipient must receive exact transfer_value" - ); - assert_eq!( - decode_u256_word(calls[8]["returnData"].as_str().unwrap()), - initial_vault_balance, - "FeeVault balance must remain unchanged after value transfer" - ); - - // Call-mode token-fee MorphTxs must emit zero fee Transfer logs and move zero tokens. - assert!( - calls[9]["logs"].as_array().unwrap().is_empty(), - "unfunded token-fee MorphTx must emit no logs under validation=false" - ); - assert!( - calls[10]["logs"].as_array().unwrap().is_empty(), - "funded call-mode token-fee MorphTx must emit no fee Transfer logs under validation=false" - ); - assert_eq!( - decode_u256_word(calls[11]["returnData"].as_str().unwrap()), - initial_token_balance, - "funded caller token balance must be unchanged under validation=false" - ); - assert_eq!( - decode_u256_word(calls[12]["returnData"].as_str().unwrap()), - U256::ZERO, - "FeeVault token balance must remain zero under validation=false" - ); - - // Verify caller nonce bumped across funded ETH and MorphTx calls (indices 2, 5, 10). - let txs = block["transactions"] - .as_array() - .expect("transactions array"); - assert_eq!( - txs[2]["nonce"].as_str(), - Some(format!("{initial_funded_nonce:#x}").as_str()) - ); - assert_eq!( - txs[5]["nonce"].as_str(), - Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) - ); - assert_eq!( - txs[10]["nonce"].as_str(), - Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) - ); - - // Also exercise the `traceTransfers: true` (`TransferInspector`) branch under - // `validation: false`: a 1 ETH transfer emits exactly 1 synthetic ETH transfer - // log (to `value_recipient`) and zero FeeVault transfer logs. - let trace_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded, - "to": value_recipient, - "value": format!("{transfer_value:#x}"), - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - }], - }], - "traceTransfers": true, - "validation": false, - }); - let trace_blocks: Value = client - .request("eth_simulateV1", (trace_payload, "latest")) - .await?; - let trace_call = &trace_blocks[0]["calls"][0]; - assert_eq!(trace_call["status"].as_str(), Some("0x1")); - let trace_logs = trace_call["logs"].as_array().expect("trace logs array"); - assert_eq!( - trace_logs.len(), - 1, - "traceTransfers with validation=false must record only the value transfer, not fee transfers: {trace_logs:?}" - ); - - Ok(()) -} - -/// `eth_simulateV1` with `validation: true` must wrap simulated transactions with -/// their real EIP-2718 encoding so post-Curie `commit + blob` L1 fees are charged -/// and validated accurately (for both standard ETH txs and token-fee MorphTxs). -#[tokio::test(flavor = "multi_thread")] -async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre::Result<()> { - reth_tracing::init_test_tracing(); - - const L1_ORACLE: Address = - alloy_primitives::address!("530000000000000000000000000000000000000f"); - const FEE_VAULT: Address = - alloy_primitives::address!("530000000000000000000000000000000000000a"); - const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - // Matches `tests/assets/test-genesis.json` slots 7 & 8. - const COMMIT_SCALAR: u128 = 0x35ba5d7b55; - const BLOB_SCALAR: u128 = 0x18e38a4c; - const L1_FEE_PRECISION: u128 = 1_000_000_000; - // Runtime bytecode: return `(BALANCE(calldataload(0)), BALANCE(calldataload(32)))` (64 bytes). - const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; - - let (mut nodes, wallet) = TestNodeBuilder::new() - .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) - .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) - .build() - .await?; - let mut node = nodes.pop().unwrap(); - let chain_id = wallet.chain_id; - let funded_wallet = wallet.inner.address(); - advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; - - let client = node - .rpc_client() - .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; - - let initial_vault_balance = node - .inner - .provider - .latest()? - .basic_account(&FEE_VAULT)? - .map(|a| a.balance) - .unwrap_or_default(); - - let sender = Address::random(); - let recipient = Address::random(); - let reader_addr = Address::random(); - let calldata = Bytes::from(vec![0xab; 1024]); - let gas_limit = 50_000u64; - let max_fee_per_gas = 2_000_000_000u128; // 2 gwei - let max_priority_fee_per_gas = 1_000_000_000u128; // 1 gwei - - // Build the simulated EIP-1559 envelope with both the 3-byte zero signature - // (`TryIntoSimTx`) and the full 64-byte placeholder signature (`U256::MAX, U256::MAX, true`) - // used for L1 fee sizing. - let zero_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); - let placeholder_sig = alloy_primitives::Signature::new(U256::MAX, U256::MAX, true); - let tx_inner = alloy_consensus::TxEip1559 { - chain_id, - nonce: 0, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to: TxKind::Call(recipient), - value: U256::ZERO, - access_list: Default::default(), - input: calldata.clone(), - }; - let zero_sig_len = MorphTxEnvelope::Eip1559(tx_inner.clone().into_signed(zero_sig)) - .encoded_2718() - .len() as u128; - let encoded_len = MorphTxEnvelope::Eip1559(tx_inner.into_signed(placeholder_sig)) - .encoded_2718() - .len() as u128; - assert_eq!( - encoded_len, - zero_sig_len + 64, - "placeholder signature must add exactly 64 bytes for L1 fee sizing" - ); - let commit_only_l1_fee = - U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); - let zero_sig_l1_fee = U256::from( - (COMMIT_SCALAR * u128::from(L1_BASE_FEE) - + BLOB_SCALAR * zero_sig_len * u128::from(L1_BLOB_BASE_FEE)) - / L1_FEE_PRECISION, - ); - let full_l1_fee = U256::from( - (COMMIT_SCALAR * u128::from(L1_BASE_FEE) - + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) - / L1_FEE_PRECISION, - ); - assert!( - full_l1_fee > zero_sig_l1_fee && zero_sig_l1_fee > commit_only_l1_fee * U256::from(2u64), - "placeholder-signature Curie blob fee must strictly exceed zero-signature and commit-only fees" - ); - - let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); - let tx_call = serde_json::json!({ - "from": sender, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "input": calldata.to_string(), - }); - - // (1) Balance covers L2 + zero-signature L1 fee (which omits the 64B placeholder - // signature bytes), NOT full placeholder-signature Curie L1 fee: must fail - // with insufficient funds (-38014). - let insufficient_balance = l2_max_fee + zero_sig_l1_fee; - let fail_payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - sender.to_string(): { - "balance": format!("{insufficient_balance:#x}"), - }, - }, - "calls": [tx_call], - }], - "validation": true, - }); - let err = client - .request::("eth_simulateV1", (fail_payload, "latest")) - .await - .expect_err( - "validation=true must reject when balance omits 64B placeholder signature L1 fee", + assert_eq!( + decode_u256_word(calls[4]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert_eq!( + decode_u256_word(calls[6]["returnData"].as_str().unwrap()), + initial_funded_balance - transfer_value + ); + assert_eq!( + decode_u256_word(calls[7]["returnData"].as_str().unwrap()), + transfer_value + ); + assert_eq!( + decode_u256_word(calls[8]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert!(calls[9]["logs"].as_array().unwrap().is_empty()); + assert!(calls[10]["logs"].as_array().unwrap().is_empty()); + assert_eq!( + decode_u256_word(calls[11]["returnData"].as_str().unwrap()), + initial_token_balance + ); + assert_eq!( + decode_u256_word(calls[12]["returnData"].as_str().unwrap()), + U256::ZERO ); - let err_str = err.to_string(); - assert!( - err_str.contains("insufficient funds") || err_str.contains("-38014"), - "expected insufficient funds error, got: {err_str}" - ); - - // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed, charge exact - // `l2_used_fee + full_l1_fee` to sender and FeeVault, AND with - // `returnFullTransactions: true` keep zero `r`/`s`/`v` on the returned tx. - let exact_budget = l2_max_fee + full_l1_fee; - let pass_payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - sender.to_string(): { - "balance": format!("{exact_budget:#x}"), - }, - reader_addr.to_string(): { - "code": DUAL_BALANCE_READER_CODE, - }, - }, - "calls": [ - tx_call, - // Executed immediately after Call 0 commits and BEFORE Call 1's own - // `reward_beneficiary` runs, so it observes exact post-Call-0 balances - // of both `sender` and `FEE_VAULT`. - { - "from": funded_wallet, - "to": reader_addr, - "gas": "0x186a0", - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "input": encode_two_address_words(sender, FEE_VAULT), - }, - ], - }], - "validation": true, - "returnFullTransactions": true, - }); - let blocks: Value = client - .request("eth_simulateV1", (pass_payload, "latest")) - .await?; - let block = &blocks[0]; - let calls = block["calls"].as_array().expect("calls array"); - assert_eq!(calls[0]["status"].as_str(), Some("0x1")); - assert_eq!(calls[1]["status"].as_str(), Some("0x1")); - - // Returned full transaction must keep zero r/s/v per the eth_simulateV1 spec. - let txs = block["transactions"] - .as_array() - .expect("full transactions array"); - assert_eq!(txs.len(), 2); - assert_eq!(txs[0]["r"].as_str(), Some("0x0")); - assert_eq!(txs[0]["s"].as_str(), Some("0x0")); - assert_eq!(txs[0]["v"].as_str(), Some("0x0")); - assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); - - let block_base_fee = u128::from_str_radix( - block["baseFeePerGas"] - .as_str() - .unwrap() - .trim_start_matches("0x"), - 16, - )?; - let gas_used = u64::from_str_radix( - calls[0]["gasUsed"] - .as_str() - .unwrap() - .trim_start_matches("0x"), - 16, - )?; - let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); - let expected_total_fee = U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; - - let (sender_balance_after, vault_balance_after) = - decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); - assert_eq!( - sender_balance_after, - exact_budget - expected_total_fee, - "sender must be charged exact L2 execution fee + full Curie (commit + blob) L1 fee" - ); - assert_eq!( - vault_balance_after, - initial_vault_balance + expected_total_fee, - "FeeVault must receive exact L2 execution fee + full Curie (commit + blob) L1 fee" - ); - - // (3) Token-fee MorphTx under `validation: true`: a `feeLimit` that only covers - // L2 (`gas_limit * effective_gas_price`) + commit-only L1 fee (+ half the blob fee) - // must fail, while covering full Curie L1 + L2 succeeds and emits the call-mode - // ERC-20 `Transfer` fee log(s). (Genesis token ID 1 has 1:1 price_ratio == scale == 1e18.) - let l2_effective_max_fee = U256::from(gas_limit) * U256::from(effective_gas_price); - let token_tight_limit = l2_effective_max_fee - + commit_only_l1_fee - + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); - let morph_fail_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded_wallet, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": format!("{token_tight_limit:#x}"), - "input": calldata.to_string(), - }], - }], - "validation": true, - }); - client - .request::("eth_simulateV1", (morph_fail_payload, "latest")) - .await - .expect_err("token-fee MorphTx must fail under validation=true when feeLimit omits Curie blob L1 fee"); - - let token_generous_limit = l2_max_fee + full_l1_fee * U256::from(2u64); - let morph_pass_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded_wallet, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": format!("{token_generous_limit:#x}"), - "input": calldata.to_string(), - }], - }], - "validation": true, - }); - let morph_blocks: Value = client - .request("eth_simulateV1", (morph_pass_payload, "latest")) - .await?; - let morph_call = &morph_blocks[0]["calls"][0]; - assert_eq!(morph_call["status"].as_str(), Some("0x1")); - let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; - let logs = morph_call["logs"].as_array().expect("logs array"); - assert!( - logs.iter().any(|log| { - log["topics"] - .as_array() - .and_then(|t| t.first()) - .and_then(Value::as_str) - == Some(transfer_topic) - }), - "validated call-mode token-fee MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" - ); - - Ok(()) -} - -/// `eth_simulateV1(validation: true)` with legacy `gasPrice` + `feeTokenID` on a -/// zero-ETH / funded-token caller must execute as a token-fee MorphTx (`0x7f`) -/// rather than silently degrading into a Legacy ETH transaction. -#[tokio::test(flavor = "multi_thread")] -async fn simulate_v1_validation_true_legacy_gas_price_with_fee_token_id_executes_morph_tx() --> eyre::Result<()> { - reth_tracing::init_test_tracing(); - - const L1_ORACLE: Address = - alloy_primitives::address!("530000000000000000000000000000000000000f"); - const TEST_TOKEN: Address = - alloy_primitives::address!("5300000000000000000000000000000000000022"); - const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - - let (mut nodes, wallet) = TestNodeBuilder::new() - .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) - .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) - .build() - .await?; - let mut node = nodes.pop().unwrap(); - let token_holder = wallet.inner.address(); - advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; - - let client = node - .rpc_client() - .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; - let initial_token_hex: String = client - .request( - "eth_call", - ( - serde_json::json!({ - "to": TEST_TOKEN, - "input": encode_balance_of(token_holder), - }), - "latest", - ), - ) - .await?; - let initial_token_balance = decode_u256_word(&initial_token_hex); - assert!( - initial_token_balance > U256::ZERO, - "genesis token holder must have non-zero fee token balance" - ); + let txs = block["transactions"] + .as_array() + .expect("transactions array"); + assert_eq!( + txs[2]["nonce"].as_str(), + Some(format!("{initial_funded_nonce:#x}").as_str()) + ); + assert_eq!( + txs[5]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) + ); + assert_eq!( + txs[10]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) + ); - let recipient = Address::random(); - let gas_limit = 50_000u64; - let gas_price = 2_000_000_000u128; // 2 gwei - let calldata = Bytes::from(vec![0xcd; 128]); - - // Zero out `token_holder`'s ETH balance via `stateOverrides` so a Legacy ETH - // fallback would fail immediately with insufficient ETH, while preserving its - // ERC-20 token balance in `TEST_TOKEN`. - let payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - token_holder.to_string(): { - "balance": "0x0", - }, - }, - "calls": [ - { - "from": token_holder, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "gasPrice": format!("{gas_price:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "input": calldata.to_string(), - }, - { - "from": token_holder, - "to": TEST_TOKEN, - "gas": "0x186a0", - "gasPrice": format!("{gas_price:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "input": encode_balance_of(token_holder), - }, - ], - }], - "validation": true, - "returnFullTransactions": true, - }); + // `traceTransfers: true` with `validation: false` records only the value transfer log. + let trace_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + }], + }], + "traceTransfers": true, + "validation": false, + }), + "latest", + ), + ) + .await?; + let trace_call = &trace_blocks[0]["calls"][0]; + assert_eq!(trace_call["status"].as_str(), Some("0x1")); + assert_eq!(trace_call["logs"].as_array().unwrap().len(), 1); + } - let blocks: Value = client - .request("eth_simulateV1", (payload, "latest")) - .await?; - let block = &blocks[0]; - let calls = block["calls"].as_array().expect("calls array"); - assert_eq!(calls[0]["status"].as_str(), Some("0x1")); - assert_eq!(calls[1]["status"].as_str(), Some("0x1")); - - // Returned full transaction must be a MorphTx (`0x7f`) with `feeTokenID = 1` - // and zero `r`/`s`/`v` signature fields. - let txs = block["transactions"] - .as_array() - .expect("full transactions array"); - assert_eq!(txs[0]["type"].as_str(), Some("0x7f")); - assert_eq!(txs[0]["feeTokenID"].as_str(), Some("0x1")); - assert_eq!(txs[0]["r"].as_str(), Some("0x0")); - assert_eq!(txs[0]["s"].as_str(), Some("0x0")); - assert_eq!(txs[0]["v"].as_str(), Some("0x0")); - assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); - - // ERC-20 `Transfer` fee log emitted on Call 0. - let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; - let logs = calls[0]["logs"].as_array().expect("logs array"); - assert!( - logs.iter().any(|log| { - log["topics"] - .as_array() - .and_then(|t| t.first()) - .and_then(Value::as_str) - == Some(transfer_topic) - }), - "gasPrice + feeTokenID MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" - ); + // ------------------------------------------------------------------------- + // 2. `validation: true` charges full placeholder-sig Curie L1 + L2 fees + // ------------------------------------------------------------------------- + { + let sender = Address::random(); + let recipient = Address::random(); + let reader_addr = Address::random(); + let calldata = Bytes::from(vec![0xab; 1024]); + let gas_limit = 50_000u64; + let max_fee_per_gas = 2_000_000_000u128; + let max_priority_fee_per_gas = 1_000_000_000u128; + + let zero_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = alloy_primitives::Signature::new(U256::MAX, U256::MAX, true); + let tx_inner = alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + }; + let zero_sig_len = MorphTxEnvelope::Eip1559(tx_inner.clone().into_signed(zero_sig)) + .encoded_2718() + .len() as u128; + let encoded_len = MorphTxEnvelope::Eip1559(tx_inner.into_signed(placeholder_sig)) + .encoded_2718() + .len() as u128; + assert_eq!(encoded_len, zero_sig_len + 64); + + let commit_only_l1_fee = + U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let zero_sig_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * zero_sig_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let full_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); + let tx_call = serde_json::json!({ + "from": sender, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": calldata.to_string(), + }); + + // Balance omitting the 64B placeholder signature L1 fee must fail. + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{:#x}", l2_max_fee + zero_sig_l1_fee) }, + }, + "calls": [tx_call], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("balance omitting 64B placeholder signature L1 fee must fail"); + let err_str = err.to_string(); + assert!(err_str.contains("insufficient funds") || err_str.contains("-38014")); + + // Exact `l2_max_fee + full_l1_fee` succeeds, debits exact fees, and keeps zero r/s/v. + let exact_budget = l2_max_fee + full_l1_fee; + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{exact_budget:#x}") }, + reader_addr.to_string(): { "code": DUAL_BALANCE_READER_CODE }, + }, + "calls": [ + tx_call, + { + "from": funded, + "to": reader_addr, + "gas": "0x186a0", + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": encode_two_address_words(sender, FEE_VAULT), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + + let block_base_fee = u128::from_str_radix( + block["baseFeePerGas"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); + let expected_total_fee = + U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; + + let (sender_after, vault_after) = + decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); + assert_eq!(sender_after, exact_budget - expected_total_fee); + assert_eq!(vault_after, initial_vault_balance + expected_total_fee); + + // Token-fee MorphTx under `validation: true`: tight `feeLimit` fails, generous succeeds. + let token_tight_limit = U256::from(gas_limit) * U256::from(effective_gas_price) + + commit_only_l1_fee + + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_tight_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("token-fee MorphTx must fail when feeLimit omits Curie blob L1 fee"); + + let morph_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{:#x}", l2_max_fee + full_l1_fee * U256::from(2u64)), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await?; + let morph_call = &morph_blocks[0]["calls"][0]; + assert_eq!(morph_call["status"].as_str(), Some("0x1")); + assert!(has_transfer_log(morph_call)); + } - // Token balance observed during Call 1 must have decreased from Call 0's fee deduction - // (and Call 1's own upfront deduction). - let token_balance_after = decode_u256_word(calls[1]["returnData"].as_str().unwrap()); - assert!( - token_balance_after < initial_token_balance, - "token fees must be deducted from ERC-20 balance: before={initial_token_balance}, after={token_balance_after}" - ); + // ------------------------------------------------------------------------- + // 3. `validation: true` with legacy `gasPrice` + `feeTokenID` executes MorphTx + // ------------------------------------------------------------------------- + { + let recipient = Address::random(); + let calldata = Bytes::from(vec![0xcd; 128]); + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { funded.to_string(): { "balance": "0x0" } }, + "calls": [ + { + "from": funded, + "to": recipient, + "gas": "0xc350", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": calldata.to_string(), + }, + { + "from": funded, + "to": TEST_TOKEN, + "gas": "0x186a0", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": encode_balance_of(funded), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["type"].as_str(), Some("0x7f")); + assert_eq!(txs[0]["feeTokenID"].as_str(), Some("0x1")); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + assert!(has_transfer_log(&calls[0])); + assert!(decode_u256_word(calls[1]["returnData"].as_str().unwrap()) < initial_token_balance); + } Ok(()) } diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index 5e420dda..f4661fb6 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -76,4 +76,4 @@ pub use token_fee::{ L2_TOKEN_REGISTRY_ADDRESS, MorphEvmEnv, TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; -pub use tx::{MorphTxEnv, MorphTxExt}; +pub use tx::{MorphTxEnv, MorphTxExt, encode_simulated_tx_for_l1_fee}; diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index f5541be0..21f2d83e 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -3,7 +3,7 @@ //! This module defines the Morph-specific transaction environment with token fee support. use alloy_consensus::{ - EthereumTxEnvelope, SignableTransaction, Transaction as AlloyTransaction, TxEip4844, + EthereumTxEnvelope, SignableTransaction, Signed, Transaction as AlloyTransaction, TxEip4844, }; use alloy_eips::eip2718::Encodable2718; use alloy_eips::eip2930::AccessList; @@ -23,6 +23,48 @@ use std::ops::{Deref, DerefMut}; /// Re-export Either for authorization list use alloy_consensus::transaction::Either; +/// Encodes a simulated transaction with a full-size placeholder signature for L1 +/// data fee sizing, without mutating the transaction itself. +/// +/// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP +/// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero +/// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Using the same 64-byte +/// `0xff` + `yParity = 1` placeholder as [`MorphTxEnv::encode_for_l1_fee`] matches +/// real signed transactions and `eth_estimateGas` while keeping `tx`'s zero +/// signature intact. +pub fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let envelope = match tx { + MorphTxEnvelope::Legacy(s) => MorphTxEnvelope::Legacy(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip2930(s) => MorphTxEnvelope::Eip2930(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip1559(s) => MorphTxEnvelope::Eip1559(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip7702(s) => MorphTxEnvelope::Eip7702(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Morph(s) => MorphTxEnvelope::Morph(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::L1Msg(_) => return tx.encoded_2718().into(), + }; + envelope.encoded_2718().into() +} + /// Morph transaction environment with token fee support. /// /// This wraps the standard [`TxEnv`] and adds Morph-specific fields for: @@ -1085,4 +1127,174 @@ mod tests { other => panic!("expected a recovered authorization, got {other:?}"), } } + + #[test] + fn encode_simulated_tx_for_l1_fee_uses_full_placeholder_sig_without_mutating_tx() { + use alloy_consensus::{TxEip1559, TxEip2930, TxEip7702, TxLegacy}; + use alloy_eips::{ + eip2718::Decodable2718, + eip7702::{Authorization, SignedAuthorization}, + }; + use alloy_primitives::{Sealed, address}; + use morph_primitives::TxL1Msg; + + let chain_id = 2818u64; + let signer = address!("0000000000000000000000000000000000000001"); + let to = address!("0000000000000000000000000000000000000002"); + let input = Bytes::from(vec![0xab; 64]); + let zero_sig = Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let auth: SignedAuthorization = Authorization { + chain_id: U256::from(chain_id), + address: address!("0000000000000000000000000000000000000042"), + nonce: 1, + } + .into_signed(Signature::new(U256::from(1u64), U256::from(2u64), true)); + let sig_of = |env: &MorphTxEnvelope| match env { + MorphTxEnvelope::Legacy(s) => Some(*s.signature()), + MorphTxEnvelope::Eip2930(s) => Some(*s.signature()), + MorphTxEnvelope::Eip1559(s) => Some(*s.signature()), + MorphTxEnvelope::Eip7702(s) => Some(*s.signature()), + MorphTxEnvelope::Morph(s) => Some(*s.signature()), + MorphTxEnvelope::L1Msg(_) => None, + }; + + let cases = [ + ( + "legacy", + MorphTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(chain_id), + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip2930", + MorphTxEnvelope::Eip2930(Signed::new_unchecked( + TxEip2930 { + chain_id, + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip1559", + MorphTxEnvelope::Eip1559(Signed::new_unchecked( + TxEip1559 { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "eip7702", + MorphTxEnvelope::Eip7702(Signed::new_unchecked( + TxEip7702 { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to, + authorization_list: vec![auth.clone()], + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "morph_v1", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + fee_limit: U256::from(10_000u64), + version: MORPH_TX_VERSION_1, + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "morph_v2", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + version: MORPH_TX_VERSION_2, + authorization_list: vec![auth], + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ]; + + for (label, tx, compare_tx_env) in cases { + let sized = encode_simulated_tx_for_l1_fee(&tx); + assert_eq!(sized.len(), tx.encoded_2718().len() + 64, "{label}"); + let decoded = MorphTxEnvelope::decode_2718(&mut sized.as_ref()).unwrap(); + assert_eq!(sig_of(&decoded), Some(placeholder_sig), "{label}"); + assert_eq!(sig_of(&tx), Some(zero_sig), "{label}"); + if compare_tx_env { + let env_encoded = + MorphTxEnv::from_recovered_tx(&tx, signer).encode_for_l1_fee(chain_id); + assert_eq!(sized, env_encoded, "{label}"); + } + } + + let l1_msg = MorphTxEnvelope::L1Msg(Sealed::new_unchecked( + TxL1Msg { + queue_index: 1, + gas_limit: 50_000, + to, + input, + ..Default::default() + }, + B256::ZERO, + )); + assert_eq!( + encode_simulated_tx_for_l1_fee(&l1_msg), + Bytes::from(l1_msg.encoded_2718()) + ); + } } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 149bf2f4..d954c6be 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -69,7 +69,6 @@ eyre.workspace = true tracing.workspace = true [dev-dependencies] -alloy-signer.workspace = true serde_json.workspace = true tempfile.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index acd1b907..ad562608 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -7,31 +7,28 @@ //! through to the upstream allowance without the L1-fee extension, except //! that fee-token callers are left uncapped for the handler. //! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee -//! charging (including Morph's non-zero L1 data fee) when `validation: false` -//! and encodes a copy of each simulated transaction with a full-size -//! placeholder signature when `validation: true` so Curie `commit + blob` -//! (and pre-Curie calldata) L1 fees are accurately charged and validated -//! without mutating the zero signature returned to callers. +//! charging (including Morph's non-zero L1 data fee) when `validation: false`, +//! delegating per-block transaction execution to upstream +//! [`simulate::execute_transactions`] (while [`morph_evm::MorphBlockExecutor`] +//! re-encodes empty simulated envelopes with a full-size placeholder signature +//! when `validation: true`). use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_consensus::{BlockHeader, Signed}; -use alloy_eips::eip2718::{Encodable2718, WithEncoded}; +use alloy_consensus::BlockHeader; use alloy_evm::{ - block::TxResult, call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}, overrides::{OverrideBlockHashes, apply_block_overrides, apply_state_overrides}, }; -use alloy_network::TransactionBuilder; -use alloy_primitives::{B256, Bytes, Signature, U256}; +use alloy_primitives::{B256, U256}; use alloy_rpc_types_eth::{ BlockId, simulate::{SimBlock, SimulatePayload, SimulatedBlock}, + state::StateOverride, }; use morph_chainspec::{MorphChainSpec, MorphHardforks}; -use morph_primitives::{MorphPrimitives, MorphTxEnvelope}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; -use reth_chainspec::{EthChainSpec, EthereumHardforks}; +use reth_chainspec::EthChainSpec; use reth_errors::RethError; use reth_evm::{ ConfigureEvm, Evm, EvmEnvFor, TxEnvFor, @@ -53,11 +50,11 @@ use reth_rpc_eth_types::{ error::{AsEthApiError, FromEthApiError}, simulate::{self, EthSimulateError}, }; -use reth_storage_api::{StateProvider, noop::NoopProvider}; +use reth_storage_api::StateProvider; use revm::{ Database, context::{Block, Transaction as RevmTransaction}, - context_interface::{Cfg, result::ExecutionResult}, + context_interface::result::ExecutionResult, }; use revm_inspectors::transfer::TransferInspector; use std::collections::BTreeMap; @@ -114,8 +111,6 @@ where let chain_id = this.provider().chain_spec().chain_id(); - // Validate block ordering and fill gaps with empty blocks so every entry has an - // explicit `number` and `time` override and the chain is contiguous. let block_state_calls = simulate::sanitize_chain( block_state_calls, &parent, @@ -147,42 +142,24 @@ where .map_err(RethError::other) .map_err(Self::Error::from_eth_err)?; - // Always disable EIP-3607. + // Always disable EIP-3607 and relax `tx_gas_limit_cap` for simulated blocks. evm_env.cfg_env.disable_eip3607 = true; - - // EIP-7825's transaction gas cap is only active with Amsterdam's - // regular/state-gas accounting. - if !evm_env.cfg_env.is_amsterdam_eip8037_enabled() { - evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX); - } + evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX); if !validation { - // If not explicitly required, disable nonce check - // . evm_env.cfg_env.disable_nonce_check = true; evm_env.cfg_env.disable_base_fee = true; - // Unlike OP-Stack, Morph's post-Curie L1 commit fee is non-zero even for - // empty RLP bytes. Disabling fee charging matches `eth_call` semantics so - // `validation: false` does not reject zero-balance / omitted-`from` - // callers or mutate caller / FeeVault balances or emit fee Transfer logs. + // Morph's post-Curie L1 commit fee is non-zero even for empty RLP bytes. + // Disabling fee charging matches `eth_call` semantics so `validation: false` + // does not reject zero-balance / omitted-`from` callers or charge L1/L2 fees. evm_env.cfg_env.disable_fee_charge = true; evm_env.block_env.inner_mut().basefee = 0; } - // Set prevrandao to zero for simulated blocks by default, - // matching spec behavior where MixDigest is zero-initialized. - // If user provides an override, it will be applied by apply_block_overrides. + // Spec default MixDigest is zero-initialized unless overridden below. evm_env.block_env.inner_mut().prevrandao = Some(B256::ZERO); - if !this - .provider() - .chain_spec() - .is_paris_active_at_block(evm_env.block_env.number().saturating_to()) - { - evm_env.block_env.inner_mut().difficulty = parent.difficulty(); - } if let Some(block_overrides) = block_overrides { - // Ensure we don't allow uncapped gas limit per block. if let Some(gas_limit_override) = block_overrides.gas_limit && gas_limit_override > evm_env.block_env.gas_limit() && gas_limit_override > this.call_gas_limit() @@ -197,70 +174,40 @@ where } let chain_id = evm_env.cfg_env.chain_id; - let ctx = this .evm_config() .context_for_next_block(&parent, attributes) .map_err(RethError::other) .map_err(Self::Error::from_eth_err)?; - let map_err = |e: EthApiError| -> Self::Error { - match e.as_simulate_error() { - Some(sim_err) => Self::Error::from_eth_err(EthApiError::other(sim_err)), - None => Self::Error::from_eth_err(e), - } - }; + let compute_state_root = this.compute_state_root_for_eth_simulate(); let (result, results) = if trace_transfers { - // Prepare inspector to capture transfers inside the EVM so they are - // recorded and included in logs. let inspector = TransferInspector::new(false).with_logs(true); let evm = this .evm_config() .evm_with_env_and_inspector(&mut db, evm_env, inspector); - let mut builder = this.evm_config().create_block_builder(evm, &parent, ctx); - - if let Some(ref state_overrides) = state_overrides { - simulate::apply_precompile_overrides( - state_overrides, - builder.evm_mut().precompiles_mut(), - ) - .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; - } - - execute_simulated_transactions( - builder, + execute_simulated_block( + this.evm_config().create_block_builder(evm, &parent, ctx), &state_provider, + state_overrides.as_ref(), calls, &mut remaining_call_gas_limit, chain_id, - this.compute_state_root_for_eth_simulate(), - validation, + compute_state_root, this.converter(), - ) - .map_err(map_err)? + )? } else { let evm = this.evm_config().evm_with_env(&mut db, evm_env); - let mut builder = this.evm_config().create_block_builder(evm, &parent, ctx); - - if let Some(ref state_overrides) = state_overrides { - simulate::apply_precompile_overrides( - state_overrides, - builder.evm_mut().precompiles_mut(), - ) - .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; - } - - execute_simulated_transactions( - builder, + execute_simulated_block( + this.evm_config().create_block_builder(evm, &parent, ctx), &state_provider, + state_overrides.as_ref(), calls, &mut remaining_call_gas_limit, chain_id, - this.compute_state_root_for_eth_simulate(), - validation, + compute_state_root, this.converter(), - ) - .map_err(map_err)? + )? }; let simulated_header = result.block.clone_sealed_header(); @@ -286,177 +233,55 @@ where } } -/// Encodes a simulated transaction with a full-size placeholder signature for L1 -/// data fee sizing, without mutating the transaction itself. -/// -/// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP -/// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero -/// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Encoding that zero signature -/// directly underestimates post-Curie blob fees by 64 bytes (and pre-Curie calldata -/// gas by 64 non-zero bytes). Using the same 64-byte `0xff` + `yParity = 1` -/// placeholder as [`morph_revm::MorphTxEnv::encode_for_l1_fee`] matches real signed -/// transactions and `eth_estimateGas` while keeping `tx`'s zero signature intact. -fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { - let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); - let envelope = match tx { - MorphTxEnvelope::Legacy(signed) => MorphTxEnvelope::Legacy(Signed::new_unchecked( - signed.tx().clone(), - placeholder_sig, - B256::ZERO, - )), - MorphTxEnvelope::Eip2930(signed) => MorphTxEnvelope::Eip2930(Signed::new_unchecked( - signed.tx().clone(), - placeholder_sig, - B256::ZERO, - )), - MorphTxEnvelope::Eip1559(signed) => MorphTxEnvelope::Eip1559(Signed::new_unchecked( - signed.tx().clone(), - placeholder_sig, - B256::ZERO, - )), - MorphTxEnvelope::Eip7702(signed) => MorphTxEnvelope::Eip7702(Signed::new_unchecked( - signed.tx().clone(), - placeholder_sig, - B256::ZERO, - )), - MorphTxEnvelope::Morph(signed) => MorphTxEnvelope::Morph(Signed::new_unchecked( - signed.tx().clone(), - placeholder_sig, - B256::ZERO, - )), - MorphTxEnvelope::L1Msg(_) => return tx.encoded_2718().into(), - }; - envelope.encoded_2718().into() -} - -/// Morph-aware equivalent of [`simulate::execute_transactions`]. -/// -/// Mirrors upstream `eth_simulateV1` block execution, gas-cap accounting, and -/// state-root handling, while wrapping resolved transactions with a full-size -/// placeholder-signature EIP-2718 encoding when `validation == true` so Morph's -/// L1 data fee charges the full Curie `commit + blob` (or pre-Curie calldata) -/// cost without mutating the zero signature stored on `tx`. +/// Applies precompile overrides and delegates block transaction execution to upstream +/// [`simulate::execute_transactions`], mapping simulate errors uniformly across both +/// `trace_transfers` and non-tracing EVM builders. #[allow(clippy::too_many_arguments, clippy::type_complexity)] -fn execute_simulated_transactions( +fn execute_simulated_block( mut builder: S, state_provider: impl StateProvider, + state_overrides: Option<&StateOverride>, calls: Vec>, remaining_call_gas_limit: &mut Option, chain_id: u64, compute_state_root: bool, - validation: bool, converter: &T, ) -> Result< ( BlockBuilderOutcome, Vec::Evm as Evm>::HaltReason>>, ), - EthApiError, + MorphEthApiError, > where S: BlockBuilder< - Primitives = MorphPrimitives, - Executor: BlockExecutor>>>, + Executor: BlockExecutor< + Evm: Evm< + DB: Database>, + Precompiles = alloy_evm::precompiles::PrecompilesMap, + >, >, + >, T: RpcConvert, { - builder.apply_pre_execution_changes()?; - - let mut results = Vec::with_capacity(calls.len()); - let mut cumulative_tx_gas_used: u64 = 0; - let mut block_regular_gas_used: u64 = 0; - let mut block_state_gas_used: u64 = 0; - let block_gas_limit = builder.evm().block().gas_limit(); - let is_amsterdam = builder.evm().cfg_env().enable_amsterdam_eip8037; - let tx_gas_limit_cap = builder.evm().cfg_env().tx_gas_limit_cap.unwrap_or(u64::MAX); - for mut call in calls { - let block_gas_remaining = if is_amsterdam { - block_gas_limit - .saturating_sub(block_regular_gas_used) - .min(block_gas_limit.saturating_sub(block_state_gas_used)) - } else { - block_gas_limit.saturating_sub(cumulative_tx_gas_used) - }; - let mut default_gas_limit = block_gas_remaining; - - if let Some(gas_limit) = call.as_ref().gas_limit() { - let exceeds_gas_limit = if is_amsterdam { - let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used); - let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used); - let regular_tx_gas_limit = gas_limit.min(tx_gas_limit_cap); - - regular_tx_gas_limit > regular_available_gas || gas_limit > state_available_gas - } else { - gas_limit > block_gas_remaining - }; - - if exceeds_gas_limit { - return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded)); - } - } - - if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit { - if let Some(gas_limit) = call.as_ref().gas_limit() { - if gas_limit > remaining_call_gas_limit { - call.as_mut().set_gas_limit(remaining_call_gas_limit); - } - } else { - default_gas_limit = default_gas_limit.min(remaining_call_gas_limit); - } - } - - // Resolve transaction, populate missing fields and enforce calls - // correctness. - let tx = simulate::resolve_transaction( - call, - default_gas_limit, - builder.evm().block().basefee(), - chain_id, - builder.evm().cfg_env().disable_nonce_check, - builder.evm_mut().db_mut(), - converter, - )?; - // When `validation == true`, encode a copy of `tx` with a full-size - // placeholder signature (`r = s = U256::MAX, yParity = true`, matching - // `MorphTxEnv::encode_for_l1_fee`) so Morph's L1 fee calculation charges - // the full commit + blob (Curie) or calldata (pre-Curie) fee without - // mutating `tx`'s zero signature (`returnFullTransactions: true` keeps - // zero `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec). When - // `validation == false`, `disable_fee_charge` skips L1 fee charging - // entirely, so an empty envelope avoids wasted encoding. - let encoded = if validation { - encode_simulated_tx_for_l1_fee(tx.inner()) - } else { - Default::default() - }; - let tx = WithEncoded::new(encoded, tx); - - let mut tx_regular_gas_used = 0; - let gas_output = builder.execute_transaction_with_result_closure(tx, |result| { - tx_regular_gas_used = result.result().result.gas().block_regular_gas_used(); - results.push(result.result().result.clone()) - })?; - - let gas_used = gas_output.tx_gas_used(); - if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() { - if gas_used > *remaining_call_gas_limit { - return Err(EthApiError::other(EthSimulateError::GasLimitReached)); - } - *remaining_call_gas_limit -= gas_used; - } - - cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used); - block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used); - block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used()); - } - - let result = if compute_state_root { - builder.finish(state_provider, None)? - } else { - builder.finish(NoopProvider::default(), None)? - }; - - Ok((result, results)) + if let Some(state_overrides) = state_overrides { + simulate::apply_precompile_overrides(state_overrides, builder.evm_mut().precompiles_mut()) + .map_err(|e| MorphEthApiError::from_eth_err(EthApiError::other(e)))?; + } + + simulate::execute_transactions( + builder, + state_provider, + calls, + remaining_call_gas_limit, + chain_id, + compute_state_root, + converter, + ) + .map_err(|e| match e.as_simulate_error() { + Some(sim_err) => MorphEthApiError::from_eth_err(EthApiError::other(sim_err)), + None => MorphEthApiError::from_eth_err(e), + }) } impl EstimateCall for MorphEthApi @@ -1046,241 +871,4 @@ mod tests { Some(U256::from(3u64)) ); } - - /// `encode_simulated_tx_for_l1_fee` must re-encode every signed `MorphTxEnvelope` - /// variant with the 64-byte `0xff` + `yParity = 1` placeholder signature (adding - /// 64 bytes vs `TryIntoSimTx`'s zero signature when the outer RLP header width is - /// unchanged), match `MorphTxEnv::encode_for_l1_fee` for EIP-1559 / EIP-7702 / - /// MorphTx, fall back to `encoded_2718` for `L1Msg`, and leave `tx`'s original - /// zero signature untouched. - #[test] - fn encode_simulated_tx_for_l1_fee_uses_full_placeholder_sig_without_mutating_tx() { - use alloy_consensus::{ - Signed, Transaction as _, TxEip1559, TxEip2930, TxEip7702, TxLegacy, - }; - use alloy_eips::{ - eip2718::Decodable2718, - eip7702::{Authorization, SignedAuthorization}, - }; - use alloy_primitives::{Address, Sealed, TxKind, address}; - use morph_primitives::{ - TxL1Msg, TxMorph, - transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, - }; - use morph_revm::MorphTxEnv; - - let chain_id = 2818u64; - let signer = address!("0000000000000000000000000000000000000001"); - let to = address!("0000000000000000000000000000000000000002"); - // 64 bytes of calldata keeps both zero-sig and placeholder-sig RLP payload - // lengths inside `[56, 255]` so the outer RLP list header is 2 bytes for both - // and the length delta is exactly +64 bytes. - let input = Bytes::from(vec![0xab; 64]); - let zero_sig = Signature::new(U256::ZERO, U256::ZERO, false); - let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); - let auth: SignedAuthorization = Authorization { - chain_id: U256::from(chain_id), - address: address!("0000000000000000000000000000000000000042"), - nonce: 1, - } - .into_signed(Signature::new(U256::from(1u64), U256::from(2u64), true)); - - let signed_cases: Vec<(&str, MorphTxEnvelope, bool)> = vec![ - ( - "legacy", - MorphTxEnvelope::Legacy(Signed::new_unchecked( - TxLegacy { - chain_id: Some(chain_id), - nonce: 7, - gas_price: 2_000_000_000, - gas_limit: 50_000, - to: TxKind::Call(to), - value: U256::from(1u64), - input: input.clone(), - }, - zero_sig, - B256::ZERO, - )), - false, - ), - ( - "eip2930", - MorphTxEnvelope::Eip2930(Signed::new_unchecked( - TxEip2930 { - chain_id, - nonce: 7, - gas_price: 2_000_000_000, - gas_limit: 50_000, - to: TxKind::Call(to), - value: U256::from(1u64), - access_list: Default::default(), - input: input.clone(), - }, - zero_sig, - B256::ZERO, - )), - false, - ), - ( - "eip1559", - MorphTxEnvelope::Eip1559(Signed::new_unchecked( - TxEip1559 { - chain_id, - nonce: 7, - gas_limit: 50_000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Call(to), - value: U256::from(1u64), - access_list: Default::default(), - input: input.clone(), - }, - zero_sig, - B256::ZERO, - )), - true, - ), - ( - "eip7702", - MorphTxEnvelope::Eip7702(Signed::new_unchecked( - TxEip7702 { - chain_id, - nonce: 7, - gas_limit: 80_000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to, - value: U256::ZERO, - access_list: Default::default(), - authorization_list: vec![auth.clone()], - input: input.clone(), - }, - zero_sig, - B256::ZERO, - )), - true, - ), - ( - "morph_v1", - MorphTxEnvelope::Morph(Signed::new_unchecked( - TxMorph { - chain_id, - nonce: 7, - gas_limit: 50_000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Call(to), - value: U256::ZERO, - access_list: Default::default(), - input: input.clone(), - fee_token_id: 1, - fee_limit: U256::from(10_000u64), - version: MORPH_TX_VERSION_1, - reference: Some(B256::repeat_byte(0x11)), - memo: Some(Bytes::from_static(b"sim")), - authorization_list: vec![], - }, - zero_sig, - B256::ZERO, - )), - true, - ), - ( - "morph_v2", - MorphTxEnvelope::Morph(Signed::new_unchecked( - TxMorph { - chain_id, - nonce: 7, - gas_limit: 80_000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Call(to), - value: U256::ZERO, - access_list: Default::default(), - input: input.clone(), - fee_token_id: 1, - fee_limit: U256::from(10_000u64), - version: MORPH_TX_VERSION_2, - reference: None, - memo: None, - authorization_list: vec![auth], - }, - zero_sig, - B256::ZERO, - )), - true, - ), - ]; - - for (label, tx, compare_tx_env) in signed_cases { - let zero_encoded = tx.encoded_2718(); - let sized_encoded = encode_simulated_tx_for_l1_fee(&tx); - - // Exactly +64 bytes (r and s expand from 1 byte 0x80 each to 33 bytes each). - assert_eq!( - sized_encoded.len(), - zero_encoded.len() + 64, - "{label}: expected +64 byte delta vs zero signature" - ); - - // Re-decoded envelope carries the exact placeholder signature. - let decoded = MorphTxEnvelope::decode_2718(&mut sized_encoded.as_ref()) - .expect("placeholder encoding must decode cleanly"); - let sig = match &decoded { - MorphTxEnvelope::Legacy(s) => s.signature(), - MorphTxEnvelope::Eip2930(s) => s.signature(), - MorphTxEnvelope::Eip1559(s) => s.signature(), - MorphTxEnvelope::Eip7702(s) => s.signature(), - MorphTxEnvelope::Morph(s) => s.signature(), - MorphTxEnvelope::L1Msg(_) => unreachable!(), - }; - assert_eq!( - *sig, placeholder_sig, - "{label}: decoded signature must match placeholder" - ); - - // Original `tx` must still hold its zero signature untouched. - let orig_sig = match &tx { - MorphTxEnvelope::Legacy(s) => s.signature(), - MorphTxEnvelope::Eip2930(s) => s.signature(), - MorphTxEnvelope::Eip1559(s) => s.signature(), - MorphTxEnvelope::Eip7702(s) => s.signature(), - MorphTxEnvelope::Morph(s) => s.signature(), - MorphTxEnvelope::L1Msg(_) => unreachable!(), - }; - assert_eq!( - *orig_sig, zero_sig, - "{label}: original tx signature must not be mutated" - ); - - // EIP-1559, EIP-7702, and Morph envelopes match `MorphTxEnv::encode_for_l1_fee` - // byte-for-byte (EIP-7702/MorphV2 authorization signatures differ only if recovered, - // and here `from_recovered_tx` keeps the signed auths or replaces with placeholder). - if compare_tx_env && tx.authorization_list().is_none_or(<[_]>::is_empty) { - let env_encoded = - MorphTxEnv::from_recovered_tx(&tx, signer).encode_for_l1_fee(chain_id); - assert_eq!( - sized_encoded, env_encoded, - "{label}: must match MorphTxEnv::encode_for_l1_fee byte-for-byte" - ); - } - } - - // `L1Msg` has no signature and falls back to `encoded_2718`. - let l1_msg = MorphTxEnvelope::L1Msg(Sealed::new_unchecked( - TxL1Msg { - queue_index: 1, - gas_limit: 50_000, - to, - value: U256::ZERO, - input, - sender: Address::ZERO, - }, - B256::ZERO, - )); - assert_eq!( - encode_simulated_tx_for_l1_fee(&l1_msg), - Bytes::from(l1_msg.encoded_2718()) - ); - } } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index f36c6ac8..2e12b725 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -19,16 +19,35 @@ use reth_evm::EvmEnv; /// [`try_build_morph_tx_from_request`]. impl TryIntoSimTx for MorphTransactionRequest { fn try_into_sim_tx(self) -> Result> { - // Try to build a MorphTx; returns None if this should be a standard Ethereum tx. // Simulation preserves Morph fields even when legacy `gasPrice` is set, matching - // `TryIntoTxEnv` and geth's `ToMessage`. + // `TryIntoTxEnv` and geth's `ToMessage`. Normalize legacy `gasPrice` onto both + // EIP-1559 fee caps before calling `try_build_morph_tx_from_request`. + let mut inner_for_morph = self.inner.clone(); + if let Some(gas_price) = inner_for_morph.gas_price.take() { + let has_morph_fields = self.fee_token_id.is_some_and(|id| id.to::() > 0) + || is_nonzero_reference(normalize_reference(self.reference).as_ref()) + || self.memo.as_ref().is_some_and(|m| !m.is_empty()); + if has_morph_fields { + if inner_for_morph.max_fee_per_gas.is_some() + || inner_for_morph.max_priority_fee_per_gas.is_some() + { + return Err(alloy_consensus::error::ValueError::new( + self, + "both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified", + )); + } + inner_for_morph.max_fee_per_gas = Some(gas_price); + inner_for_morph.max_priority_fee_per_gas = Some(gas_price); + } + } + + // Try to build a MorphTx; returns None if this should be a standard Ethereum tx let morph_tx_result = try_build_morph_tx_from_request( - &self.inner, + &inner_for_morph, self.fee_token_id.unwrap_or_default(), self.fee_limit.unwrap_or_default(), self.reference, self.memo.clone(), - true, ); match morph_tx_result { @@ -66,15 +85,13 @@ impl SignableTxRequest for MorphTransactionRequest { self, signer: impl TxSigner + Send, ) -> Result { - // Try to build a MorphTx; returns None if this should be a standard Ethereum tx. - // Real transaction signing keeps legacy `gasPrice` as a standard Ethereum tx. + // Try to build a MorphTx; returns None if this should be a standard Ethereum tx let morph_tx_result = try_build_morph_tx_from_request( &self.inner, self.fee_token_id.unwrap_or_default(), self.fee_limit.unwrap_or_default(), self.reference, self.memo, - false, ); match morph_tx_result { @@ -197,15 +214,8 @@ fn morph_envelope_from_ethereum( /// `Ok(None)` if this should be a standard Ethereum transaction, /// or `Err(...)` if there's a validation error. /// -/// When `allow_legacy_gas_price` is `false` (real transaction signing via -/// [`SignableTxRequest`]), setting legacy `gasPrice` forces a standard Ethereum -/// transaction. When `allow_legacy_gas_price` is `true` (simulation via -/// [`TryIntoSimTx`]), Morph fields take precedence and a legacy `gasPrice` maps -/// onto both `max_fee_per_gas` and `max_priority_fee_per_gas` (rejecting -/// requests that specify both `gasPrice` and EIP-1559 fee fields), matching -/// [`TryIntoTxEnv`] and geth's `ToMessage`. -/// -/// A MorphTx is constructed when any of these Morph fields is set: +/// Unless the request sets legacy `gasPrice` (always a standard transaction), +/// a MorphTx is constructed when any of these Morph fields is set: /// - `feeTokenID > 0` (ERC20 gas payment) /// - a non-zero `reference` /// - a non-empty `memo` @@ -222,10 +232,9 @@ fn try_build_morph_tx_from_request( fee_limit: U256, reference: Option, memo: Option, - allow_legacy_gas_price: bool, ) -> Result, &'static str> { let reference = normalize_reference(reference); - if !allow_legacy_gas_price && req.gas_price.is_some() { + if req.gas_price.is_some() { return Ok(None); } @@ -240,18 +249,6 @@ fn try_build_morph_tx_from_request( return Ok(None); } - let (max_fee_per_gas, max_priority_fee_per_gas) = if let Some(gas_price) = req.gas_price { - if req.max_fee_per_gas.is_some() || req.max_priority_fee_per_gas.is_some() { - return Err("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"); - } - (gas_price, gas_price) - } else { - ( - req.max_fee_per_gas.unwrap_or_default(), - req.max_priority_fee_per_gas.unwrap_or_default(), - ) - }; - let authorization_list = req.authorization_list.clone().unwrap_or_default(); let version = TxMorph::inferred_version(!authorization_list.is_empty()); @@ -261,6 +258,8 @@ fn try_build_morph_tx_from_request( .ok_or("missing chain_id for morph transaction")?; let gas_limit = req.gas.unwrap_or_default(); let nonce = req.nonce.unwrap_or_default(); + let max_fee_per_gas = req.max_fee_per_gas.unwrap_or_default(); + let max_priority_fee_per_gas = req.max_priority_fee_per_gas.unwrap_or_default(); let access_list: AccessList = req.access_list.clone().unwrap_or_default(); let input = req .input @@ -869,8 +868,7 @@ mod tests { #[test] fn try_build_morph_tx_returns_none_for_standard_tx() { let req = create_basic_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None, false); + let result = try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None); assert!(result.is_ok()); assert!(result.unwrap().is_none()); } @@ -878,14 +876,8 @@ mod tests { #[test] fn try_build_morph_tx_with_fee_token_id() { let req = create_morph_transaction_request(); - let result = try_build_morph_tx_from_request( - &req, - U64::from(1), - U256::from(1_000_000), - None, - None, - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.fee_token_id, 1); @@ -896,14 +888,8 @@ mod tests { #[test] fn try_build_morph_tx_treats_gas_price_with_morph_fields_as_standard_tx() { let req = create_basic_transaction_request(); - let result = try_build_morph_tx_from_request( - &req, - U64::from(1), - U256::from(1_000_000), - None, - None, - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None); assert!(result.is_ok()); assert!(result.unwrap().is_none()); @@ -913,14 +899,8 @@ mod tests { fn try_build_morph_tx_with_reference_only() { let req = create_morph_transaction_request(); let reference = B256::random(); - let result = try_build_morph_tx_from_request( - &req, - U64::ZERO, - U256::ZERO, - Some(reference), - None, - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, Some(reference), None); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.reference, Some(reference)); @@ -930,14 +910,8 @@ mod tests { #[test] fn try_build_morph_tx_treats_zero_reference_as_absent() { let req = create_morph_transaction_request(); - let result = try_build_morph_tx_from_request( - &req, - U64::from(1), - U256::ZERO, - Some(B256::ZERO), - None, - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::from(1), U256::ZERO, Some(B256::ZERO), None); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); @@ -949,14 +923,8 @@ mod tests { fn try_build_morph_tx_with_memo_only() { let req = create_morph_transaction_request(); let memo = Bytes::from("hello world"); - let result = try_build_morph_tx_from_request( - &req, - U64::ZERO, - U256::ZERO, - None, - Some(memo.clone()), - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, Some(memo.clone())); assert!(result.is_ok()); let tx = result.unwrap().unwrap(); assert_eq!(tx.memo, Some(memo)); @@ -965,14 +933,8 @@ mod tests { #[test] fn try_build_morph_tx_empty_memo_is_not_trigger() { let req = create_morph_transaction_request(); - let result = try_build_morph_tx_from_request( - &req, - U64::ZERO, - U256::ZERO, - None, - Some(Bytes::new()), - false, - ); + let result = + try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, Some(Bytes::new())); assert!(result.is_ok()); // Empty memo should NOT trigger MorphTx creation assert!(result.unwrap().is_none()); @@ -1001,16 +963,10 @@ mod tests { #[test] fn try_build_morph_tx_with_authorization_list_selects_v2() { let req = create_v2_transaction_request(); - let tx = try_build_morph_tx_from_request( - &req, - U64::from(1), - U256::from(1_000_000), - None, - None, - false, - ) - .unwrap() - .expect("fee token + authorization list builds a MorphTx"); + let tx = + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(1_000_000), None, None) + .unwrap() + .expect("fee token + authorization list builds a MorphTx"); assert_eq!(tx.version, MORPH_TX_VERSION_2); assert_eq!(tx.fee_token_id, 1); @@ -1022,8 +978,7 @@ mod tests { fn try_build_morph_tx_authorization_list_without_morph_fields_is_standard_tx() { // No Morph field → stays a standard (EIP-7702) transaction. let req = create_v2_transaction_request(); - let result = - try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None, false); + let result = try_build_morph_tx_from_request(&req, U64::ZERO, U256::ZERO, None, None); assert!(result.unwrap().is_none()); } @@ -1036,7 +991,6 @@ mod tests { U256::ZERO, None, Some(Bytes::from("memo")), - false, ) .unwrap() .expect("memo + authorization list builds a MorphTx"); @@ -1061,7 +1015,6 @@ mod tests { U256::ZERO, None, Some(Bytes::from("memo")), - false, ) .unwrap() .expect("memo builds a MorphTx"); @@ -1078,10 +1031,9 @@ mod tests { req.to = None; req.input = TransactionInput::new(Bytes::from_static(&[0x60, 0x80])); - let tx = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false) - .unwrap() - .expect("token fee builds a MorphTx"); + let tx = try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None) + .unwrap() + .expect("token fee builds a MorphTx"); assert_eq!(tx.version, MORPH_TX_VERSION_1); assert!(tx.to.is_create()); assert!(tx.validate().is_ok()); @@ -1093,10 +1045,9 @@ mod tests { authorization_list: Some(vec![]), ..create_morph_transaction_request() }; - let tx = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false) - .unwrap() - .unwrap(); + let tx = try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None) + .unwrap() + .unwrap(); assert_eq!(tx.version, MORPH_TX_VERSION_1); assert!(tx.authorization_list.is_empty()); } @@ -1108,7 +1059,7 @@ mod tests { req.input = TransactionInput::new(Bytes::from_static(&[0x60, 0x80])); let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); assert_eq!( result.unwrap_err(), "MorphTx with an authorization list cannot create a contract" @@ -1361,7 +1312,7 @@ mod tests { let mut req = create_morph_transaction_request(); req.chain_id = None; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); assert!(result.is_err()); assert!(result.unwrap_err().contains("chain_id")); } @@ -1375,7 +1326,7 @@ mod tests { }; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); assert_eq!(result.unwrap_err(), "data and input fields must match"); } @@ -1386,7 +1337,7 @@ mod tests { req.to = None; let result = - try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None, false); + try_build_morph_tx_from_request(&req, U64::from(1), U256::from(100), None, None); assert_eq!(result.unwrap_err(), "contract creation requires initcode"); } @@ -1400,7 +1351,6 @@ mod tests { U256::from(500_000), Some(B256::random()), Some(Bytes::from("memo")), - false, ); let tx = result.unwrap().unwrap(); assert_eq!(tx.chain_id, 2818); @@ -1410,163 +1360,6 @@ mod tests { assert_eq!(tx.value, U256::from(1000)); } - #[test] - fn try_into_sim_tx_preserves_morph_fields_with_legacy_gas_price() { - // 1. feeTokenID + legacy gasPrice builds a MorphTx with both caps set to gasPrice. - let req = MorphTransactionRequest { - inner: create_basic_transaction_request(), - fee_token_id: Some(U64::from(1)), - fee_limit: Some(U256::from(1_000_000)), - reference: None, - memo: None, - }; - let env = req - .try_into_sim_tx() - .expect("simulation with feeTokenID + gasPrice must build MorphTx"); - let MorphTxEnvelope::Morph(signed) = env else { - panic!("expected MorphTxEnvelope::Morph, got {env:?}"); - }; - assert_eq!(signed.tx().fee_token_id, 1); - assert_eq!(signed.tx().fee_limit, U256::from(1_000_000)); - assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); - assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); - assert_eq!( - *signed.signature(), - Signature::new(U256::ZERO, U256::ZERO, false) - ); - - // 2. reference + legacy gasPrice preserves reference as MorphTx. - let reference = B256::repeat_byte(0x42); - let req = MorphTransactionRequest { - inner: create_basic_transaction_request(), - fee_token_id: None, - fee_limit: None, - reference: Some(reference), - memo: None, - }; - let env = req - .try_into_sim_tx() - .expect("simulation with reference + gasPrice must build MorphTx"); - let MorphTxEnvelope::Morph(signed) = env else { - panic!("expected MorphTxEnvelope::Morph, got {env:?}"); - }; - assert_eq!(signed.tx().reference, Some(reference)); - assert_eq!(signed.tx().fee_token_id, 0); - assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); - assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); - - // 3. memo + legacy gasPrice preserves memo as MorphTx. - let memo = Bytes::from_static(b"hello"); - let req = MorphTransactionRequest { - inner: create_basic_transaction_request(), - fee_token_id: None, - fee_limit: None, - reference: None, - memo: Some(memo.clone()), - }; - let env = req - .try_into_sim_tx() - .expect("simulation with memo + gasPrice must build MorphTx"); - let MorphTxEnvelope::Morph(signed) = env else { - panic!("expected MorphTxEnvelope::Morph, got {env:?}"); - }; - assert_eq!(signed.tx().memo, Some(memo)); - assert_eq!(signed.tx().max_fee_per_gas, 1_000_000_000); - assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); - - // 4. Legacy gasPrice with NO Morph fields stays a standard Legacy tx. - let standard = MorphTransactionRequest { - inner: create_basic_transaction_request(), - fee_token_id: None, - fee_limit: None, - reference: None, - memo: None, - }; - let env = standard - .try_into_sim_tx() - .expect("plain gasPrice request builds standard Legacy tx"); - assert!( - matches!(env, MorphTxEnvelope::Legacy(_)), - "expected Legacy, got {env:?}" - ); - } - - #[test] - fn try_into_sim_tx_rejects_conflicting_gas_price_and_eip1559_fields_with_morph_fields() { - // gasPrice + maxFeePerGas + feeTokenID - let mut inner = create_basic_transaction_request(); - inner.max_fee_per_gas = Some(2_000_000_000); - let req = MorphTransactionRequest { - inner, - fee_token_id: Some(U64::from(1)), - fee_limit: None, - reference: None, - memo: None, - }; - let err = req - .try_into_sim_tx() - .expect_err("gasPrice + maxFeePerGas must fail"); - assert!( - err.to_string() - .contains("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"), - "unexpected error: {err}" - ); - - // gasPrice + maxPriorityFeePerGas + memo - let mut inner = create_basic_transaction_request(); - inner.max_priority_fee_per_gas = Some(100_000_000); - let req = MorphTransactionRequest { - inner, - fee_token_id: None, - fee_limit: None, - reference: None, - memo: Some(Bytes::from_static(b"memo")), - }; - let err = req - .try_into_sim_tx() - .expect_err("gasPrice + maxPriorityFeePerGas must fail"); - assert!( - err.to_string() - .contains("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified"), - "unexpected error: {err}" - ); - } - - #[tokio::test] - async fn signable_tx_request_keeps_legacy_gas_price_with_morph_fields_as_standard_tx() { - struct DummySigner; - - #[async_trait::async_trait] - impl TxSigner for DummySigner { - fn address(&self) -> Address { - address!("0000000000000000000000000000000000000001") - } - - async fn sign_transaction( - &self, - _tx: &mut dyn SignableTransaction, - ) -> alloy_signer::Result { - Ok(Signature::new(U256::from(1u64), U256::from(2u64), false)) - } - } - - let req = MorphTransactionRequest { - inner: create_basic_transaction_request(), - fee_token_id: Some(U64::from(1)), - fee_limit: Some(U256::from(1_000_000)), - reference: None, - memo: None, - }; - let signed = req - .try_build_and_sign(DummySigner) - .await - .expect("real signing with legacy gasPrice must stay a standard Legacy tx"); - assert!( - matches!(signed, MorphTxEnvelope::Legacy(_)), - "expected Legacy tx from SignableTxRequest, got {signed:?}" - ); - } - // ========================================================================= // FromConsensusTx tests // ========================================================================= @@ -1789,4 +1582,67 @@ mod tests { // = 500_000_000 + 1_000_000_000 = 1_500_000_000 assert_eq!(rpc_tx.effective_gas_price, Some(1_500_000_000)); } + + #[test] + fn try_into_sim_tx_preserves_morph_fields_with_legacy_gas_price() { + let base_inner = || TransactionRequest { + chain_id: Some(2818), + nonce: Some(3), + gas: Some(50_000), + gas_price: Some(2_000_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + ..Default::default() + }; + + // `feeTokenID`, `reference`, or `memo` with legacy `gasPrice` builds TxMorph with + // `max_fee_per_gas == max_priority_fee_per_gas == gasPrice`. + let morph_req = MorphTransactionRequest { + inner: base_inner(), + fee_token_id: Some(U64::from(1)), + fee_limit: Some(U256::from(1234)), + reference: Some(B256::repeat_byte(0xab)), + memo: Some(Bytes::from_static(b"sim")), + }; + let env = morph_req + .try_into_sim_tx() + .expect("Morph fields with legacy gasPrice must build TxMorph"); + match env { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().fee_token_id, 1); + assert_eq!(signed.tx().fee_limit, U256::from(1234)); + assert_eq!(signed.tx().reference, Some(B256::repeat_byte(0xab))); + assert_eq!(signed.tx().memo, Some(Bytes::from_static(b"sim"))); + assert_eq!(signed.tx().max_fee_per_gas, 2_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 2_000_000_000); + } + other => panic!("expected MorphTx, got {other:?}"), + } + + // Without Morph fields, legacy `gasPrice` still builds a standard Legacy tx. + let legacy_req = MorphTransactionRequest { + inner: base_inner(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: None, + }; + assert!(matches!( + legacy_req.try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // Conflicting `gasPrice` + `maxFeePerGas` with Morph fields must error. + let mut conflicting_inner = base_inner(); + conflicting_inner.max_fee_per_gas = Some(3_000_000_000); + let conflicting = MorphTransactionRequest { + inner: conflicting_inner, + fee_token_id: Some(U64::from(1)), + fee_limit: None, + reference: None, + memo: None, + }; + assert!(conflicting.try_into_sim_tx().is_err()); + } } From d0c82f5fb7bf8af5f0ad850ddf800f4a5484bea3 Mon Sep 17 00:00:00 2001 From: panos Date: Tue, 1 Dec 2026 02:22:39 +0000 Subject: [PATCH 4/6] fix(rpc,evm): keep fee charging in eth_simulateV1 validation:false and scope gasPrice normalization to simulate `validation: false` disabled fee charging entirely to avoid Morph's post-Curie L1 commit fee on the empty envelope upstream simulates. That also skipped revm's balance check, so a `value` the caller cannot cover returned a failed call instead of upstream's -38014, and an explicit gas price was never charged. - Keep fee charging on in both modes, as upstream does. The handler prices an unencoded RPC simulation (EIP-3607 disabled, empty encoding) at zero L1 fee, which is upstream's "empty envelope carries no L1 cost" convention for L2s. Consensus never disables EIP-3607, so a missing encoding there is still priced by the formula. - `MorphBlockExecutor` encodes the placeholder signature only for `validation: true` simulations (EIP-3607 disabled, nonce checks and fee charging on), via `needs_simulated_l1_encoding`. - Normalize legacy `gasPrice` + Morph fields in `simulate_v1` before upstream resolves defaults, and restore `TryIntoSimTx` to main. `eth_fillTransaction` shares `TryIntoSimTx`, so it keeps geth's `toTransaction` rule (legacy `gasPrice` builds a legacy tx), and a 7702-shaped request no longer reports a false gasPrice conflict from the zero fee fields `resolve_transaction` fills in. - Correct the placeholder-encoding doc: legacy/2930 calls keep their own envelope type, unlike `eth_estimateGas`. --- crates/evm/src/block/mod.rs | 12 +-- crates/evm/src/block/simulate.rs | 80 +++++++++++++++++++ crates/node/tests/it/rpc.rs | 117 ++++++++++++++++++++++++--- crates/revm/src/handler.rs | 36 ++++++++- crates/revm/src/tx.rs | 10 ++- crates/rpc/src/eth/call.rs | 36 +++++---- crates/rpc/src/eth/transaction.rs | 126 +++++++++++++++++++++--------- 7 files changed, 340 insertions(+), 77 deletions(-) create mode 100644 crates/evm/src/block/simulate.rs diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 9d484303..37b49922 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -7,6 +7,7 @@ mod factory; mod receipt; +mod simulate; pub(crate) use factory::MorphBlockExecutorFactory; pub(crate) use receipt::{ @@ -30,7 +31,7 @@ use morph_revm::{ }; use reth_primitives_traits::Recovered; use reth_revm::{DatabaseCommit, Inspector, context::result::ResultAndState}; -use revm::context::{Block, Cfg as _}; +use revm::context::Block; /// The result of executing a Morph transaction. /// @@ -229,14 +230,7 @@ where ))); } - // Upstream `eth_simulateV1` (`simulate::execute_transactions`) wraps resolved - // transactions in an empty `WithEncoded` envelope (`Default::default()`) with a - // zero signature on `recovered`. When fee charging is enabled (`validation: true`), - // encode a copy with a full-size placeholder signature so Morph's L1 data fee - // matches real signed transactions without mutating `recovered`'s zero signature. - if !self.evm.cfg_env().is_fee_charge_disabled() - && tx_env.rlp_bytes.as_ref().is_none_or(|b| b.is_empty()) - { + if simulate::needs_simulated_l1_encoding(self.evm.cfg_env(), tx_env.rlp_bytes.as_ref()) { tx_env.rlp_bytes = Some(encode_simulated_tx_for_l1_fee(recovered.tx())); } diff --git a/crates/evm/src/block/simulate.rs b/crates/evm/src/block/simulate.rs new file mode 100644 index 00000000..fa5b1205 --- /dev/null +++ b/crates/evm/src/block/simulate.rs @@ -0,0 +1,80 @@ +//! L1 data fee encoding for `eth_simulateV1` calls executed by [`super::MorphBlockExecutor`]. + +use alloy_primitives::Bytes; +use revm::context::Cfg; + +/// Whether a simulated transaction must be priced with a placeholder-signature encoding. +/// +/// Upstream `eth_simulateV1` (`simulate::execute_transactions`) wraps resolved calls in an empty +/// `WithEncoded` envelope with a zero signature on the recovered transaction. A +/// `validation: true` simulation (EIP-3607 disabled, nonce checks and fee charging on) is +/// priced like a real signed transaction, so the executor encodes a copy with a full-size +/// placeholder signature for Morph's L1 data fee without touching the recovered transaction. +/// A `validation: false` simulation keeps the empty envelope, which the handler prices at zero +/// L1 fee as upstream does for L2s. Consensus execution never disables EIP-3607, so a real +/// transaction is never given a fabricated encoding. +pub(super) fn needs_simulated_l1_encoding(cfg: &impl Cfg, rlp_bytes: Option<&Bytes>) -> bool { + cfg.is_eip3607_disabled() + && !cfg.is_nonce_check_disabled() + && !cfg.is_fee_charge_disabled() + && rlp_bytes.is_none_or(|bytes| bytes.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::needs_simulated_l1_encoding; + use alloy_primitives::Bytes; + use morph_chainspec::MorphHardfork; + use revm::context::CfgEnv; + + fn cfg( + eip3607_disabled: bool, + nonce_check_disabled: bool, + fee_charge_disabled: bool, + ) -> CfgEnv { + let mut cfg = CfgEnv::new_with_spec(MorphHardfork::Celadon); + cfg.disable_eip3607 = eip3607_disabled; + cfg.disable_nonce_check = nonce_check_disabled; + cfg.disable_fee_charge = fee_charge_disabled; + cfg + } + + #[test] + fn consensus_execution_never_gets_a_placeholder_encoding() { + let consensus = cfg(false, false, false); + assert!(!needs_simulated_l1_encoding(&consensus, None)); + assert!(!needs_simulated_l1_encoding( + &consensus, + Some(&Bytes::new()) + )); + } + + #[test] + fn only_validating_simulations_get_a_placeholder_encoding() { + // `eth_simulateV1` with `validation: true`. + assert!(needs_simulated_l1_encoding( + &cfg(true, false, false), + Some(&Bytes::new()) + )); + assert!(needs_simulated_l1_encoding(&cfg(true, false, false), None)); + // `validation: false` keeps the empty envelope, priced at zero L1 fee by the handler. + assert!(!needs_simulated_l1_encoding( + &cfg(true, true, false), + Some(&Bytes::new()) + )); + // Fee charging disabled (`eth_call`-style) never computes an L1 fee. + assert!(!needs_simulated_l1_encoding( + &cfg(true, false, true), + Some(&Bytes::new()) + )); + } + + #[test] + fn real_encoding_is_never_replaced() { + let encoded = Bytes::from_static(&[0x02, 0xc0]); + assert!(!needs_simulated_l1_encoding( + &cfg(true, false, false), + Some(&encoded) + )); + } +} diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 42d24f89..ad1e9e69 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1354,8 +1354,10 @@ fn encode_balance_of(addr: Address) -> String { } /// End-to-end `eth_simulateV1` coverage on a single post-Curie node with non-zero L1 oracle fees: -/// 1. `validation: false` skips L1 and L2 fees for ETH & call-mode token MorphTxs (including -/// `traceTransfers: true`), leaves FeeVault/caller balances unchanged, and moves only `value`. +/// 1. `validation: false` runs calls in an empty envelope with no L1 fee: calls without fee fields +/// (ETH & call-mode token MorphTxs, including `traceTransfers: true`) leave FeeVault/caller +/// balances unchanged and move only `value`; an explicit gas price pays the L2 fee only; and, +/// as upstream, `value` or a gas price the caller cannot cover fails with insufficient funds. /// 2. `validation: true` charges full placeholder-signature Curie `commit + blob` L1 + L2 fees /// (for both ETH and token-fee MorphTxs) while keeping zero `r`/`s`/`v`/`yParity` on returned txs. /// 3. `validation: true` with legacy `gasPrice` + `feeTokenID` on a zero-ETH caller executes as @@ -1434,7 +1436,7 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> }; // ------------------------------------------------------------------------- - // 1. `validation: false` skips L1/L2 fees for ETH & call-mode token MorphTxs + // 1. `validation: false` charges no L1 fee for ETH & call-mode token MorphTxs // ------------------------------------------------------------------------- { let reader_addr = Address::random(); @@ -1452,22 +1454,22 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> "calls": [ // 0: omitted `from` { "to": recipient, "input": calldata }, - // 1: zero-balance caller with non-zero gasPrice - { "from": unfunded_caller, "to": recipient, "gasPrice": "0x3b9aca00", "input": calldata }, + // 1: zero-balance caller; the empty envelope carries no L1 fee + { "from": unfunded_caller, "to": recipient, "input": calldata }, // 2: funded caller, value = 0 - { "from": funded, "to": recipient, "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00", "input": calldata }, + { "from": funded, "to": recipient, "input": calldata }, // 3-4: check funded caller & FeeVault ETH balances unchanged { "to": reader_addr, "input": encode_address_word(funded) }, { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, // 5: funded caller, value = 1 ETH transfer - { "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}"), "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00" }, + { "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}") }, // 6-8: check funded, recipient, and FeeVault balances { "to": reader_addr, "input": encode_address_word(funded) }, { "to": reader_addr, "input": encode_address_word(value_recipient) }, { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, // 9-10: unfunded & funded call-mode token-fee MorphTxs { "from": unfunded_caller, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0x0", "input": calldata }, - { "from": funded, "to": recipient, "maxFeePerGas": "0x77359400", "maxPriorityFeePerGas": "0x3b9aca00", "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0xde0b6b3a7640000", "input": calldata }, + { "from": funded, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0xde0b6b3a7640000", "input": calldata }, // 11-12: check funded & FeeVault token balances unchanged { "to": TEST_TOKEN, "input": encode_balance_of(funded) }, { "to": TEST_TOKEN, "input": encode_balance_of(FEE_VAULT) }, @@ -1545,8 +1547,6 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}"), - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", }], }], "traceTransfers": true, @@ -1559,6 +1559,77 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> let trace_call = &trace_blocks[0]["calls"][0]; assert_eq!(trace_call["status"].as_str(), Some("0x1")); assert_eq!(trace_call["logs"].as_array().unwrap().len(), 1); + + // An explicit gas price still pays the L2 fee (upstream keeps fee charging on with + // `validation: false`), but the empty envelope adds no L1 fee: the caller loses and the + // FeeVault gains exactly `gasUsed * gasPrice`. + let gas_price = 1_000_000_000u128; + let charged: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, + }, + "calls": [ + { "from": funded, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }, + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + ], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; + let calls = charged[0]["calls"].as_array().expect("calls array"); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let l2_fee = U256::from(gas_used) * U256::from(gas_price); + assert_eq!( + decode_u256_word(calls[1]["returnData"].as_str().unwrap()), + initial_funded_balance - l2_fee + ); + assert_eq!( + decode_u256_word(calls[2]["returnData"].as_str().unwrap()), + initial_vault_balance + l2_fee + ); + + // As upstream, a `value` or gas price the caller cannot cover fails the request. + for underfunded in [ + serde_json::json!({ "from": unfunded_caller, "to": recipient, "value": "0x3e8" }), + serde_json::json!({ "from": unfunded_caller, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }), + ] { + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ "calls": [underfunded] }], + "validation": false, + }), + "latest", + ), + ) + .await + .expect_err("an unaffordable value or gas price must fail"); + let err_str = err.to_string(); + assert!( + err_str.contains("insufficient funds") || err_str.contains("-38014"), + "unexpected error: {err_str}" + ); + } } // ------------------------------------------------------------------------- @@ -1815,5 +1886,31 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> assert!(decode_u256_word(calls[1]["returnData"].as_str().unwrap()) < initial_token_balance); } + // ------------------------------------------------------------------------- + // 4. `eth_fillTransaction` keeps geth's `toTransaction` rule: legacy `gasPrice` builds a + // legacy transaction even with `feeTokenID`, so the simulate-only normalization above + // must not reach it. + // ------------------------------------------------------------------------- + { + let filled: Value = client + .request( + "eth_fillTransaction", + (serde_json::json!({ + "from": funded, + "to": Address::random(), + "gas": "0x5208", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + }),), + ) + .await?; + let tx = &filled["tx"]; + assert!( + matches!(tx["type"].as_str(), Some("0x0") | None), + "legacy gasPrice must fill a legacy transaction: {filled}" + ); + assert!(tx.get("feeTokenID").is_none_or(Value::is_null), "{filled}"); + } + Ok(()) } diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index daac1f32..c4ef5eeb 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -453,7 +453,7 @@ where evm: &mut MorphEvm, ) -> Result<(), EVMError> { let is_fee_charge_disabled = evm.ctx_ref().cfg().is_fee_charge_disabled(); - let l1_data_fee = if is_fee_charge_disabled { + let l1_data_fee = if is_fee_charge_disabled || is_unencoded_rpc_simulation(evm) { U256::ZERO } else { let hardfork = *evm.ctx_ref().cfg().spec(); @@ -689,8 +689,13 @@ where // Get RLP-encoded transaction bytes for L1 fee calculation // Fetch L1 block info per-tx (same rationale as validate_and_deduct_eth_fee). - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().journal_mut().db_mut(), hardfork)?; - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes.as_ref(), hardfork); + let l1_data_fee = if is_unencoded_rpc_simulation(evm) { + U256::ZERO + } else { + let l1_block_info = + L1BlockInfo::try_fetch(evm.ctx_mut().journal_mut().db_mut(), hardfork)?; + l1_block_info.calculate_tx_l1_cost(rlp_bytes.as_ref(), hardfork) + }; // Calculate L2 gas fee using effective_gas_price (= min(gasTipCap + baseFee, gasFeeCap)), // matching go-ethereum's buyAltTokenGas() which uses st.gasPrice (effective gas price). @@ -821,6 +826,31 @@ where } } +/// Whether the transaction is an RPC simulation of an unsigned call that carries no encoding. +/// +/// Upstream `eth_simulateV1` executes each call in an empty `WithEncoded` envelope and treats +/// that as carrying no L1 cost on an L2 (`simulate::execute_transactions`). Morph's post-Curie +/// formula still charges a commit fee for zero bytes, so such calls are priced at zero L1 fee +/// here. `MorphBlockExecutor` gives `validation: true` simulations a placeholder-signature +/// encoding, so only `validation: false` simulations reach the handler unencoded. +/// +/// EIP-3607 is never disabled during consensus execution, where every transaction carries its +/// signed encoding, so a missing encoding there is still priced by the formula instead of +/// silently becoming free. +#[inline] +fn is_unencoded_rpc_simulation(evm: &MorphEvm) -> bool +where + DB: alloy_evm::Database, +{ + evm.ctx_ref().cfg().is_eip3607_disabled() + && evm + .ctx_ref() + .tx() + .rlp_bytes + .as_ref() + .is_none_or(|bytes| bytes.is_empty()) +} + /// Execute `f` within a journal checkpoint. Commits on `Ok`, reverts on `Err`. #[inline] fn with_journal_checkpoint( diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index 21f2d83e..222f4947 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -29,9 +29,13 @@ use alloy_consensus::transaction::Either; /// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP /// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero /// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Using the same 64-byte -/// `0xff` + `yParity = 1` placeholder as [`MorphTxEnv::encode_for_l1_fee`] matches -/// real signed transactions and `eth_estimateGas` while keeping `tx`'s zero -/// signature intact. +/// `0xff` + `yParity = 1` placeholder as [`MorphTxEnv::encode_for_l1_fee`] sizes the +/// L1 fee like a real signed transaction while keeping `tx`'s zero signature intact. +/// +/// The envelope type is kept as simulated, so a legacy or EIP-2930 call is priced as +/// that type. `eth_estimateGas` instead always sizes an EIP-1559, EIP-7702 or MorphTx +/// envelope (as geth does once a base fee exists), so for those two types the L1 fees +/// differ by the few bytes between the encodings. pub fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); let envelope = match tx { diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index ad562608..b5baa5ad 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -6,15 +6,16 @@ //! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall //! through to the upstream allowance without the L1-fee extension, except //! that fee-token callers are left uncapped for the handler. -//! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee -//! charging (including Morph's non-zero L1 data fee) when `validation: false`, -//! delegating per-block transaction execution to upstream -//! [`simulate::execute_transactions`] (while [`morph_evm::MorphBlockExecutor`] -//! re-encodes empty simulated envelopes with a full-size placeholder signature -//! when `validation: true`). - -use crate::MorphEthApiError; -use crate::eth::{MorphEthApi, MorphNodeCore}; +//! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` prices Morph's +//! L1 data fee like upstream does for L2s: `validation: false` calls run in an +//! empty envelope that carries no L1 fee, while [`morph_evm::MorphBlockExecutor`] +//! encodes `validation: true` calls with a full-size placeholder signature so +//! they pay the L1 fee of a real transaction. Calls that combine Morph fields +//! with legacy `gasPrice` are normalized first, and per-block execution is +//! delegated to upstream [`simulate::execute_transactions`]. + +use crate::eth::{MorphEthApi, MorphNodeCore, transaction::normalize_simulate_call}; +use crate::{MorphEthApiError, MorphTransactionRequest}; use alloy_consensus::BlockHeader; use alloy_evm::{ call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}, @@ -39,7 +40,7 @@ use reth_provider::ChainSpecProvider; use reth_revm::{database::StateProviderDatabase, db::State}; use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - EthApiTypes, RpcBlock, RpcNodeCore, + EthApiTypes, RpcBlock, RpcNodeCore, RpcTypes, helpers::{ Call, EthCall, LoadBlock, LoadPendingBlock, SpawnBlocking, call::SimulatedBlocksResult, estimate::EstimateCall, @@ -65,6 +66,7 @@ where N::Provider: ChainSpecProvider, Rpc: reth_rpc_convert::RpcConvert, + Rpc::Network: RpcTypes, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { async fn simulate_v1( @@ -130,6 +132,11 @@ where state_overrides, calls, } = block; + let calls = calls + .into_iter() + .map(normalize_simulate_call) + .collect::, _>>() + .map_err(Self::Error::from_eth_err)?; let attributes = this .pending_env_builder() @@ -146,13 +153,14 @@ where evm_env.cfg_env.disable_eip3607 = true; evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX); + // Fee charging stays on in both modes, as upstream: `validation: false` keeps the + // balance check for `value` and charges an explicit gas price. Its calls run in + // the empty envelope upstream uses to mean "no L1 cost", which the Morph handler + // prices at zero L1 data fee; `validation: true` calls get a placeholder-signature + // encoding from `MorphBlockExecutor` and pay the L1 fee of a real transaction. if !validation { evm_env.cfg_env.disable_nonce_check = true; evm_env.cfg_env.disable_base_fee = true; - // Morph's post-Curie L1 commit fee is non-zero even for empty RLP bytes. - // Disabling fee charging matches `eth_call` semantics so `validation: false` - // does not reject zero-balance / omitted-`from` callers or charge L1/L2 fees. - evm_env.cfg_env.disable_fee_charge = true; evm_env.block_env.inner_mut().basefee = 0; } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index 2e12b725..db394af7 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -19,31 +19,9 @@ use reth_evm::EvmEnv; /// [`try_build_morph_tx_from_request`]. impl TryIntoSimTx for MorphTransactionRequest { fn try_into_sim_tx(self) -> Result> { - // Simulation preserves Morph fields even when legacy `gasPrice` is set, matching - // `TryIntoTxEnv` and geth's `ToMessage`. Normalize legacy `gasPrice` onto both - // EIP-1559 fee caps before calling `try_build_morph_tx_from_request`. - let mut inner_for_morph = self.inner.clone(); - if let Some(gas_price) = inner_for_morph.gas_price.take() { - let has_morph_fields = self.fee_token_id.is_some_and(|id| id.to::() > 0) - || is_nonzero_reference(normalize_reference(self.reference).as_ref()) - || self.memo.as_ref().is_some_and(|m| !m.is_empty()); - if has_morph_fields { - if inner_for_morph.max_fee_per_gas.is_some() - || inner_for_morph.max_priority_fee_per_gas.is_some() - { - return Err(alloy_consensus::error::ValueError::new( - self, - "both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified", - )); - } - inner_for_morph.max_fee_per_gas = Some(gas_price); - inner_for_morph.max_priority_fee_per_gas = Some(gas_price); - } - } - // Try to build a MorphTx; returns None if this should be a standard Ethereum tx let morph_tx_result = try_build_morph_tx_from_request( - &inner_for_morph, + &self.inner, self.fee_token_id.unwrap_or_default(), self.fee_limit.unwrap_or_default(), self.reference, @@ -75,6 +53,38 @@ impl TryIntoSimTx for MorphTransactionRequest { } } +/// Normalizes one `eth_simulateV1` call before upstream resolves its defaults. +/// +/// geth's `ToMessage` keeps the Morph fields (`feeTokenID`, `reference`, `memo`) of a request +/// that uses legacy `gasPrice` and maps `gasPrice` onto both EIP-1559 fee caps, so a simulated +/// call is priced as the same MorphTx `eth_call` would execute. `TryIntoSimTx` cannot do this +/// itself: it also builds the transaction returned by `eth_fillTransaction`, which must keep +/// geth's `toTransaction` rule that legacy `gasPrice` produces a legacy transaction. Running +/// before upstream's `resolve_transaction` also means only fee fields the caller actually set +/// count as a conflict, not the zero defaults it fills in. +pub(crate) fn normalize_simulate_call( + mut request: MorphTransactionRequest, +) -> Result { + let Some(gas_price) = request.inner.gas_price else { + return Ok(request); + }; + let has_morph_fields = request.fee_token_id.is_some_and(|id| id.to::() > 0) + || is_nonzero_reference(normalize_reference(request.reference).as_ref()) + || request.memo.as_ref().is_some_and(|memo| !memo.is_empty()); + if !has_morph_fields { + return Ok(request); + } + if request.inner.max_fee_per_gas.is_some() || request.inner.max_priority_fee_per_gas.is_some() { + return Err(EthApiError::InvalidParams( + "both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified".to_string(), + )); + } + request.inner.gas_price = None; + request.inner.max_fee_per_gas = Some(gas_price); + request.inner.max_priority_fee_per_gas = Some(gas_price); + Ok(request) +} + /// Builds and signs a transaction from an RPC request. /// /// Supports both standard Ethereum transactions and Morph fee token transactions. @@ -1584,7 +1594,7 @@ mod tests { } #[test] - fn try_into_sim_tx_preserves_morph_fields_with_legacy_gas_price() { + fn simulate_call_normalization_keeps_morph_fields_with_legacy_gas_price() { let base_inner = || TransactionRequest { chain_id: Some(2818), nonce: Some(3), @@ -1595,20 +1605,22 @@ mod tests { ))), ..Default::default() }; - - // `feeTokenID`, `reference`, or `memo` with legacy `gasPrice` builds TxMorph with - // `max_fee_per_gas == max_priority_fee_per_gas == gasPrice`. - let morph_req = MorphTransactionRequest { + let morph_req = || MorphTransactionRequest { inner: base_inner(), fee_token_id: Some(U64::from(1)), fee_limit: Some(U256::from(1234)), reference: Some(B256::repeat_byte(0xab)), memo: Some(Bytes::from_static(b"sim")), }; - let env = morph_req + + // `eth_simulateV1`: `feeTokenID`, `reference`, or `memo` with legacy `gasPrice` builds + // TxMorph with `max_fee_per_gas == max_priority_fee_per_gas == gasPrice`. + let normalized = normalize_simulate_call(morph_req()).expect("no fee conflict"); + assert_eq!(normalized.inner.gas_price, None); + match normalized .try_into_sim_tx() - .expect("Morph fields with legacy gasPrice must build TxMorph"); - match env { + .expect("normalized call must build TxMorph") + { MorphTxEnvelope::Morph(signed) => { assert_eq!(signed.tx().fee_token_id, 1); assert_eq!(signed.tx().fee_limit, U256::from(1234)); @@ -1620,7 +1632,14 @@ mod tests { other => panic!("expected MorphTx, got {other:?}"), } - // Without Morph fields, legacy `gasPrice` still builds a standard Legacy tx. + // `eth_fillTransaction` converts the raw request: legacy `gasPrice` keeps building a + // legacy transaction, as geth's `toTransaction` does. + assert!(matches!( + morph_req().try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // Without Morph fields, normalization leaves legacy `gasPrice` untouched. let legacy_req = MorphTransactionRequest { inner: base_inner(), fee_token_id: None, @@ -1628,21 +1647,52 @@ mod tests { reference: None, memo: None, }; + let legacy_req = normalize_simulate_call(legacy_req).unwrap(); + assert_eq!(legacy_req.inner.gas_price, Some(2_000_000_000)); assert!(matches!( legacy_req.try_into_sim_tx().unwrap(), MorphTxEnvelope::Legacy(_) )); - // Conflicting `gasPrice` + `maxFeePerGas` with Morph fields must error. - let mut conflicting_inner = base_inner(); - conflicting_inner.max_fee_per_gas = Some(3_000_000_000); - let conflicting = MorphTransactionRequest { - inner: conflicting_inner, + // `gasPrice` plus an explicit EIP-1559 fee field on a MorphTx is a conflict. + let mut conflicting = morph_req(); + conflicting.inner.max_fee_per_gas = Some(3_000_000_000); + assert!(matches!( + normalize_simulate_call(conflicting), + Err(EthApiError::InvalidParams(_)) + )); + } + + #[test] + fn simulate_call_normalization_accepts_legacy_gas_price_with_authorization_list() { + // Upstream `resolve_transaction` later fills unset EIP-1559 fields with zero for a + // 7702-shaped request; normalizing first must not mistake those for caller input. + let request = MorphTransactionRequest { + inner: TransactionRequest { + chain_id: Some(2818), + nonce: Some(0), + gas: Some(100_000), + gas_price: Some(1_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + authorization_list: Some(vec![sample_signed_authorization()]), + ..Default::default() + }, fee_token_id: Some(U64::from(1)), fee_limit: None, reference: None, memo: None, }; - assert!(conflicting.try_into_sim_tx().is_err()); + let normalized = normalize_simulate_call(request).expect("only gasPrice was set"); + assert_eq!(normalized.inner.max_fee_per_gas, Some(1_000_000)); + assert_eq!(normalized.inner.max_priority_fee_per_gas, Some(1_000_000)); + match normalized.try_into_sim_tx().expect("must build a MorphTx") { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().version, MORPH_TX_VERSION_2); + assert_eq!(signed.tx().authorization_list.len(), 1); + } + other => panic!("expected MorphTx, got {other:?}"), + } } } From 029b52a5013b8d25a4ad28905f48113564d401a8 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Tue, 1 Dec 2026 11:11:34 +0800 Subject: [PATCH 5/6] fix(revm,rpc): respect disable_base_fee for MorphTx and delegate simulate_v1 upstream - Honor `cfg.is_base_fee_check_disabled()` in `MorphEvmHandler::validate_env` for MorphTx (matching revm's standard EIP-1559 check) so `eth_simulateV1` with `validation: false` and a non-zero `blockOverrides.baseFeePerGas` does not reject zero-fee MorphTxs, and drop the stale `validation: false` note from `reward_beneficiary`. - Delegate `MorphEthApi::simulate_v1` directly to `self.eth_api().simulate_v1` after normalizing legacy `gasPrice` + Morph-field calls, removing the copied upstream simulation loop along with the now-unused `revm-inspectors` dependency and `alloy-evm` override feature. - Add unit and E2E coverage for MorphTx under `disable_base_fee` / `baseFeePerGas` block overrides. --- Cargo.lock | 1 - Cargo.toml | 1 - crates/node/tests/it/rpc.rs | 29 ++++ crates/revm/src/handler.rs | 50 ++++++- crates/rpc/Cargo.toml | 3 +- crates/rpc/src/eth/call.rs | 278 +++--------------------------------- 6 files changed, 99 insertions(+), 263 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b3e89fe..4937c224 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5475,7 +5475,6 @@ dependencies = [ "reth-transaction-pool", "reth-trie-common", "revm", - "revm-inspectors", "serde", "serde_json", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index 1e9c7487..773ed379 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -213,7 +213,6 @@ alloy-sol-types = { version = "1.6.1", default-features = false } alloy-transport = "2.3.0" alloy-chains = { version = "0.2.33", default-features = false } crossbeam-channel = "0.5.13" -revm-inspectors = "0.42.0" revm-primitives = { version = "42.0.0", default-features = false } revm-statetest-types = { version = "42.0.0", default-features = false } arbitrary = { version = "1.3", features = ["derive"] } diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index ad1e9e69..2976cf90 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1630,6 +1630,35 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> "unexpected error: {err_str}" ); } + + // `validation: false` disables the base-fee check, so a non-zero `baseFeePerGas` block + // override must not reject a zero-fee MorphTx either. + let override_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "blockOverrides": { "baseFeePerGas": "0x3b9aca00" }, + "calls": [{ + "from": unfunded_caller, + "to": recipient, + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0x0", + "input": calldata, + }], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; + assert_eq!( + override_blocks[0]["calls"][0]["status"].as_str(), + Some("0x1"), + "baseFeePerGas override must not reject zero-fee MorphTx under validation:false: {override_blocks}" + ); } // ------------------------------------------------------------------------- diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index c4ef5eeb..7770f638 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -236,9 +236,8 @@ where ) -> Result<(), Self::Error> { // Mirror upstream `revm_handler::post_execution::reward_beneficiary`: // when fee charging is disabled (e.g. `eth_call`, `eth_estimateGas`, - // `eth_simulateV1` with `validation: false`, `debug_traceCall`), the - // caller was never charged for gas or L1 data fees so no reward may be - // credited to the beneficiary / FeeVault. + // `debug_traceCall`), the caller was never charged for gas or L1 data + // fees so no reward may be credited to the beneficiary / FeeVault. if evm.ctx_ref().cfg().is_fee_charge_disabled() { return Ok(()); } @@ -290,7 +289,8 @@ where // 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); + let base_fee = (!evm.ctx_ref().cfg().is_base_fee_check_disabled()) + .then_some(evm.ctx_ref().block().basefee() as u128); validation::validate_priority_fee_tx( evm.ctx_ref().tx().max_fee_per_gas(), evm.ctx_ref() @@ -1729,6 +1729,48 @@ mod tests { )); } + #[test] + fn validate_env_skips_morph_tx_base_fee_check_when_disabled() { + let mut evm = MorphEvm::new( + MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), + NoOpInspector, + ); + evm.cfg.disable_base_fee = true; + 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: 0, + gas_priority_fee: Some(0), + kind: TxKind::Call(Address::ZERO), + ..Default::default() + }, + fee_token_id: Some(1), + ..Default::default() + }; + + as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) + .expect("disable_base_fee must exempt MorphTx from basefee floor"); + + // Priority fee > max fee is still rejected when disable_priority_fee_check is false. + evm.tx.inner.gas_priority_fee = Some(1); + let err = + as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) + .unwrap_err(); + assert!(matches!( + err, + EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::PriorityFeeGreaterThanMaxFee + )) + )); + } + // ========================================================================= // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index d954c6be..4f880141 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -42,7 +42,7 @@ reth-transaction-pool.workspace = true # Alloy alloy-consensus.workspace = true -alloy-evm = { workspace = true, features = ["overrides", "call-util"] } +alloy-evm.workspace = true alloy-primitives.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-eth.workspace = true @@ -59,7 +59,6 @@ serde.workspace = true derive_more.workspace = true tokio.workspace = true revm.workspace = true -revm-inspectors.workspace = true # Error handling thiserror.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index b5baa5ad..36ec5e4a 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -6,59 +6,28 @@ //! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall //! through to the upstream allowance without the L1-fee extension, except //! that fee-token callers are left uncapped for the handler. -//! - [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` prices Morph's -//! L1 data fee like upstream does for L2s: `validation: false` calls run in an -//! empty envelope that carries no L1 fee, while [`morph_evm::MorphBlockExecutor`] -//! encodes `validation: true` calls with a full-size placeholder signature so -//! they pay the L1 fee of a real transaction. Calls that combine Morph fields -//! with legacy `gasPrice` are normalized first, and per-block execution is -//! delegated to upstream [`simulate::execute_transactions`]. +//! - [`EthCall::simulate_v1`] normalizes calls that combine Morph fields with +//! legacy `gasPrice` and delegates execution to the inner upstream +//! [`EthCall::simulate_v1`]; Morph L1 fee pricing is handled in +//! [`morph_evm::MorphBlockExecutor`] (`validation: true` placeholder encoding) +//! and `morph_revm` (`validation: false` empty envelope priced at zero L1 fee). use crate::eth::{MorphEthApi, MorphNodeCore, transaction::normalize_simulate_call}; use crate::{MorphEthApiError, MorphTransactionRequest}; -use alloy_consensus::BlockHeader; -use alloy_evm::{ - call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}, - overrides::{OverrideBlockHashes, apply_block_overrides, apply_state_overrides}, -}; -use alloy_primitives::{B256, U256}; -use alloy_rpc_types_eth::{ - BlockId, - simulate::{SimBlock, SimulatePayload, SimulatedBlock}, - state::StateOverride, -}; +use alloy_evm::call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}; +use alloy_primitives::U256; +use alloy_rpc_types_eth::{BlockId, simulate::SimulatePayload}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; -use reth_chainspec::EthChainSpec; -use reth_errors::RethError; -use reth_evm::{ - ConfigureEvm, Evm, EvmEnvFor, TxEnvFor, - env::BlockEnvironment, - execute::{BlockBuilder, BlockBuilderOutcome, BlockExecutor}, -}; +use reth_evm::{EvmEnvFor, TxEnvFor}; use reth_provider::ChainSpecProvider; -use reth_revm::{database::StateProviderDatabase, db::State}; use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - EthApiTypes, RpcBlock, RpcNodeCore, RpcTypes, - helpers::{ - Call, EthCall, LoadBlock, LoadPendingBlock, SpawnBlocking, call::SimulatedBlocksResult, - estimate::EstimateCall, - }, -}; -use reth_rpc_eth_types::{ - EthApiError, - error::{AsEthApiError, FromEthApiError}, - simulate::{self, EthSimulateError}, -}; -use reth_storage_api::StateProvider; -use revm::{ - Database, - context::{Block, Transaction as RevmTransaction}, - context_interface::result::ExecutionResult, + EthApiTypes, RpcNodeCore, RpcTypes, + helpers::{Call, EthCall, call::SimulatedBlocksResult, estimate::EstimateCall}, }; -use revm_inspectors::transfer::TransferInspector; -use std::collections::BTreeMap; +use reth_rpc_eth_types::{EthApiError, error::FromEthApiError, simulate::EthSimulateError}; +use revm::{Database, context::Transaction as RevmTransaction}; impl EthCall for MorphEthApi where @@ -71,227 +40,26 @@ where { async fn simulate_v1( &self, - payload: SimulatePayload::Network>>, + mut payload: SimulatePayload::Network>>, block: Option, ) -> SimulatedBlocksResult { if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into()); } - - let block = block.unwrap_or_default(); - - let SimulatePayload { - block_state_calls, - trace_transfers, - validation, - return_full_transactions, - } = payload; - - if block_state_calls.is_empty() { - return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); + for sim_block in &mut payload.block_state_calls { + sim_block.calls = std::mem::take(&mut sim_block.calls) + .into_iter() + .map(normalize_simulate_call) + .collect::, _>>() + .map_err(Self::Error::from_eth_err)?; } - - let _permit = self - .acquire_owned_blocking_io() + self.eth_api() + .simulate_v1(payload, block) .await - .map_err(|_| EthApiError::InternalEthError)?; - - let base_block = self - .recovered_block(block) - .await? - .ok_or_else(|| EthApiError::other(EthSimulateError::BlockNotFound { block }))?; - let parent = base_block.sealed_header().clone(); - let max_simulate_blocks = self.max_simulate_blocks(); - - self.spawn_with_state_at_block(block, move |this, db| { - let state_provider = db.database.0.0; - let mut db = State::builder() - .with_database(StateProviderDatabase::new(&state_provider)) - .with_bundle_update() - .build(); - let mut parent = parent; - - let chain_id = this.provider().chain_spec().chain_id(); - - let block_state_calls = simulate::sanitize_chain( - block_state_calls, - &parent, - chain_id, - max_simulate_blocks, - )?; - - let mut blocks: Vec>> = - Vec::with_capacity(block_state_calls.len()); - - let call_gas_limit = this.call_gas_limit(); - let mut remaining_call_gas_limit = (call_gas_limit > 0).then_some(call_gas_limit); - - for block in block_state_calls { - let SimBlock { - block_overrides, - state_overrides, - calls, - } = block; - let calls = calls - .into_iter() - .map(normalize_simulate_call) - .collect::, _>>() - .map_err(Self::Error::from_eth_err)?; - - let attributes = this - .pending_env_builder() - .pending_env_attributes(&parent, block_overrides.as_ref()) - .map_err(Self::Error::from_eth_err)?; - - let mut evm_env = this - .evm_config() - .next_evm_env(&parent, &attributes) - .map_err(RethError::other) - .map_err(Self::Error::from_eth_err)?; - - // Always disable EIP-3607 and relax `tx_gas_limit_cap` for simulated blocks. - evm_env.cfg_env.disable_eip3607 = true; - evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX); - - // Fee charging stays on in both modes, as upstream: `validation: false` keeps the - // balance check for `value` and charges an explicit gas price. Its calls run in - // the empty envelope upstream uses to mean "no L1 cost", which the Morph handler - // prices at zero L1 data fee; `validation: true` calls get a placeholder-signature - // encoding from `MorphBlockExecutor` and pay the L1 fee of a real transaction. - if !validation { - evm_env.cfg_env.disable_nonce_check = true; - evm_env.cfg_env.disable_base_fee = true; - evm_env.block_env.inner_mut().basefee = 0; - } - - // Spec default MixDigest is zero-initialized unless overridden below. - evm_env.block_env.inner_mut().prevrandao = Some(B256::ZERO); - - if let Some(block_overrides) = block_overrides { - if let Some(gas_limit_override) = block_overrides.gas_limit - && gas_limit_override > evm_env.block_env.gas_limit() - && gas_limit_override > this.call_gas_limit() - { - return Err(EthApiError::other(EthSimulateError::GasLimitReached).into()); - } - apply_block_overrides(block_overrides, &mut db, evm_env.block_env.inner_mut()); - } - if let Some(ref state_overrides) = state_overrides { - apply_state_overrides(state_overrides.clone(), &mut db) - .map_err(Self::Error::from_eth_err)?; - } - - let chain_id = evm_env.cfg_env.chain_id; - let ctx = this - .evm_config() - .context_for_next_block(&parent, attributes) - .map_err(RethError::other) - .map_err(Self::Error::from_eth_err)?; - - let compute_state_root = this.compute_state_root_for_eth_simulate(); - let (result, results) = if trace_transfers { - let inspector = TransferInspector::new(false).with_logs(true); - let evm = this - .evm_config() - .evm_with_env_and_inspector(&mut db, evm_env, inspector); - execute_simulated_block( - this.evm_config().create_block_builder(evm, &parent, ctx), - &state_provider, - state_overrides.as_ref(), - calls, - &mut remaining_call_gas_limit, - chain_id, - compute_state_root, - this.converter(), - )? - } else { - let evm = this.evm_config().evm_with_env(&mut db, evm_env); - execute_simulated_block( - this.evm_config().create_block_builder(evm, &parent, ctx), - &state_provider, - state_overrides.as_ref(), - calls, - &mut remaining_call_gas_limit, - chain_id, - compute_state_root, - this.converter(), - )? - }; - - let simulated_header = result.block.clone_sealed_header(); - db.override_block_hashes(BTreeMap::from([( - simulated_header.number(), - simulated_header.hash(), - )])); - parent = simulated_header; - - let block = simulate::build_simulated_block::( - result.block, - results, - return_full_transactions.into(), - this.converter(), - )?; - - blocks.push(block); - } - - Ok(blocks) - }) - .await + .map_err(Into::into) } } -/// Applies precompile overrides and delegates block transaction execution to upstream -/// [`simulate::execute_transactions`], mapping simulate errors uniformly across both -/// `trace_transfers` and non-tracing EVM builders. -#[allow(clippy::too_many_arguments, clippy::type_complexity)] -fn execute_simulated_block( - mut builder: S, - state_provider: impl StateProvider, - state_overrides: Option<&StateOverride>, - calls: Vec>, - remaining_call_gas_limit: &mut Option, - chain_id: u64, - compute_state_root: bool, - converter: &T, -) -> Result< - ( - BlockBuilderOutcome, - Vec::Evm as Evm>::HaltReason>>, - ), - MorphEthApiError, -> -where - S: BlockBuilder< - Executor: BlockExecutor< - Evm: Evm< - DB: Database>, - Precompiles = alloy_evm::precompiles::PrecompilesMap, - >, - >, - >, - T: RpcConvert, -{ - if let Some(state_overrides) = state_overrides { - simulate::apply_precompile_overrides(state_overrides, builder.evm_mut().precompiles_mut()) - .map_err(|e| MorphEthApiError::from_eth_err(EthApiError::other(e)))?; - } - - simulate::execute_transactions( - builder, - state_provider, - calls, - remaining_call_gas_limit, - chain_id, - compute_state_root, - converter, - ) - .map_err(|e| match e.as_simulate_error() { - Some(sim_err) => MorphEthApiError::from_eth_err(EthApiError::other(sim_err)), - None => MorphEthApiError::from_eth_err(e), - }) -} - impl EstimateCall for MorphEthApi where N: MorphNodeCore, From 106cdc60cbd14c95eed8692d4ca172347c295e60 Mon Sep 17 00:00:00 2001 From: panos Date: Tue, 1 Dec 2026 03:27:41 +0000 Subject: [PATCH 6/6] fix(revm,rpc): enable optional_no_base_fee and keep call-util explicit `CfgEnv::disable_base_fee` is gated behind revm's `optional_no_base_fee` feature, which only reached the build through `reth-engine-tree`. A standalone `morph-revm` build therefore had no way to express the flag, and `validate_env_skips_morph_tx_base_fee_check_when_disabled` failed to compile under `cargo test -p morph-revm`. Enable the feature at the workspace level; node builds already had it, so runtime behaviour is unchanged and `is_base_fee_check_disabled()` now reports the real value everywhere. `crates/rpc/src/eth/call.rs` still calls `alloy_evm::call`, which is gated by alloy-evm's `call-util` feature. Keep it explicit instead of relying on feature unification through `reth-rpc-eth-api`. --- Cargo.toml | 4 ++++ crates/rpc/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 773ed379..655df6e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -185,9 +185,13 @@ reth-trie-sparse = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-mor reth-revm = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false, features = [ "optional-checks", ] } +# `optional_no_base_fee` keeps `CfgEnv::disable_base_fee` and +# `is_base_fee_check_disabled()` available to standalone `morph-revm` builds; the +# node build already enables it through `reth-engine-tree`. revm = { version = "42.0.1", features = [ "optional_fee_charge", "optional_eip7623", + "optional_no_base_fee", ], default-features = false } alloy = { version = "2.3.0", default-features = false } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 4f880141..31fab25d 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -42,7 +42,7 @@ reth-transaction-pool.workspace = true # Alloy alloy-consensus.workspace = true -alloy-evm.workspace = true +alloy-evm = { workspace = true, features = ["call-util"] } alloy-primitives.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-eth.workspace = true