Skip to content

fix(rpc,revm): fix alt-token eth_estimateGas allowance and MorphTx validate_env - #244

Open
panos-xyz wants to merge 2 commits into
mainfrom
fix/estimate-gas-alt-token-allowance
Open

panos-xyz wants to merge 2 commits into
mainfrom
fix/estimate-gas-alt-token-allowance

Conversation

@panos-xyz

@panos-xyz panos-xyz commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes M-M04 as a standalone PR targeting main:

Changes (crates/rpc/src/eth/call.rs, crates/revm/src/{handler.rs,token_fee.rs}, crates/revm/Cargo.toml)

  • Exact ETH-space inverse in gas_allowance_from_token_limit (crates/rpc/src/eth/call.rs):
    • Computes max_eth = floor(limit_token * price_ratio / scale) in U512 (saturating to U256::MAX via saturating_to::<U256>()) — the exact mathematical inverse of ceil((l2_fee + l1_fee) * scale / price_ratio) <= limit_token — eliminating L1-fee double-rounding that previously caused false InsufficientFundsForL1Fee rejections on tight 6-decimal USDT/USDC limits.
    • Returns InsufficientFundsForL1Fee when max_eth < l1_fee or when a non-zero L1 fee leaves zero ETH for L2 execution gas, while returning Ok(0) (or u64::MAX when gas_price == 0) on l1_fee == 0 && limit == 0.
  • Call-mode balanceOf(caller) resolution & clean error handling (crates/rpc/src/eth/call.rs, crates/revm/src/token_fee.rs):
    • Made TokenRegistryEntry::ensure_usable pub.
    • Switched Call::caller_gas_allowance directly to load_caller_token_gas_allowance: TokenRegistryEntry::load -> ensure_usable -> eth_balance < value check -> entry.load_for_caller (using the block's MorphEvmEnv via EthApiDbAdapter), so call-mode tokens resolve real balanceOf(caller) and cap by effective_fee_limit, matching morph-geth's DoEstimateGas.
    • Inactive or zero-price_ratio / zero-scale tokens fail fast with InvalidFeeToken before invoking call-mode EVM execution.
    • Database errors from registry reads, account reads, or call-mode balanceOf propagate as MorphEthApiError::Eth instead of being swallowed as InvalidFeeToken.
    • Normalized gas_cap == 0 (unlimited) to u64::MAX while retaining the min(effective_gas_cap) bound in call mode.
  • Align MorphTx validate_env with upstream revm (crates/revm/src/handler.rs, crates/revm/Cargo.toml):
    • Updated MorphEvmHandler::validate_env to gate base-fee checks on cfg.is_base_fee_check_disabled() and priority-fee checks on cfg.is_priority_fee_check_disabled(), independent of cfg.is_fee_charge_disabled().
    • Enabled optional_no_base_fee and optional_priority_fee_check in crates/revm/Cargo.toml [dev-dependencies] only for standalone cargo test -p morph-revm.

Verification

  • cargo fmt --all -- --check: passed
  • cargo clippy -p morph-revm -p morph-rpc -p morph-node --all-targets -- -D warnings: passed (0 warnings)
  • cargo clippy -p morph-node --features test-utils --all-targets -- -D warnings: passed (0 warnings)
  • cargo test -p morph-revm --lib: 145 passed
  • cargo test -p morph-rpc --lib: 132 passed
  • cargo test -p morph-node --features test-utils --test it -- rpc --test-threads=4: 27 passed

…lidate_env (M-M04)

- Compute the exact ETH-space budget `floor(limit_token * price_ratio / scale)`
  in `U512` inside `gas_allowance_from_token_limit` (avoiding double-rounding
  the L1 fee in token space on tight 6-decimal token limits) and return `Ok(0)`
  rather than `InsufficientFundsForL1Fee` when `l1_fee == 0 && limit == 0`.
- Switch `caller_gas_allowance_with_token` to `TokenRegistryEntry::load` +
  `ensure_usable` + `load_for_caller` using the block's `MorphEvmEnv` so
  call-mode tokens resolve `balanceOf(caller)` and cap by `min(balance, fee_limit)`,
  reject inactive/zero-config tokens before spinning up an EVM, propagate DB
  errors as `MorphEthApiError::Eth`, and normalize `gas_cap == 0` to `u64::MAX`.
- Align `MorphEvmHandler::validate_env` MorphTx fee-cap validation with upstream
  revm's EIP-1559 branch (`is_base_fee_check_disabled()` and
  `is_priority_fee_check_disabled()`, independent of `is_fee_charge_disabled()`).
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The pull request changes MorphTx fee-cap validation and the token-based gas allowance path used by RPC calls. It separates base-fee and priority-fee checks, resolves token balances for allowances, and updates allowance limits and fee conversion.

Changes: MorphTx fee validation

Layer / File(s) Summary
Fee-cap validation and tests
crates/revm/Cargo.toml, crates/revm/src/handler.rs
MorphEvmHandler::validate_env applies MorphTx fee-cap validation even when fee charging is disabled. Base-fee and priority-fee checks follow their separate configuration flags. Tests cover the flag combinations and fee-cap outcomes.

Token gas allowances

Layer / File(s) Summary
Load and validate token balance
crates/revm/src/token_fee.rs, crates/rpc/src/eth/call.rs
TokenRegistryEntry::ensure_usable is public. The RPC path loads token metadata, checks ETH balance against transaction value, and resolves the caller’s token balance. Database errors map to MorphEthApiError::Eth; integration tests cover balance resolution and error cases.
Calculate token gas allowance
crates/rpc/src/eth/call.rs
Allowance calculation uses the resolved token balance and optional positive fee limit. EVM-call allowances respect the gas cap, with a zero cap treated as unlimited. Token amounts convert to ETH using floor division and a wide intermediate. Tests cover limits, L1 fees, zero balances, and rounding.

Estimated code review effort: 4 (Complex) | ~40 minutes

Change: Bug fix

Possibly related PRs

  • morph-l2/morph-reth#239: Changes the fee-charge-disabled simulation path and the same validation flags used by this pull request.
  • morph-l2/morph-reth#235: Covers overlapping token allowance calculations, call-mode balance lookup, gas-cap behavior, and MorphTx priority-fee validation.

Suggested reviewers: dylancai9, chengwenxi, curryxbo

Merge Risk: Minimal · up to 9f249

This PR fixes alternate-token gas estimation so that tight USDT/USDC fee limits are no longer wrongly rejected. It also makes MorphTx fee-cap validation match upstream revm. The changes are covered by new tests, and no remaining defects were found, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names both areas the changeset touches: the alt-token eth_estimateGas allowance fix in crates/rpc (call.rs) and the MorphTx validate_env fee-cap change in crates/revm (handler.rs). It is spe…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names both areas the changeset touches: the alt-token eth_estimateGas allowance fix in crates/rpc (call.rs) and the MorphTx validate_env fee-cap change in crates/revm (handler.rs). It is specific and follows conventional-commit style. It does not cover every detail, such as the dev-dependency feature flags or the token_fee visibility change, which is acceptable for a title.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 86aa375b-ec3f-4556-bb6e-bf455dda6518
Commits

Reviewing files that changed from the base of the PR and between e01b16a and 9f2494c.

Files selected for processing: 4

  • crates/revm/Cargo.toml
  • crates/revm/src/handler.rs
  • crates/revm/src/token_fee.rs
  • crates/rpc/src/eth/call.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

panos-xyz added a commit that referenced this pull request Nov 28, 2026
…l.rs tests

- Inline the single-caller MorphEthApi::caller_gas_allowance_with_token
  pass-through directly to load_caller_token_gas_allowance.
- Simplify U512 clamping in token_amount_to_eth via saturating_to::<U256>().
- Factor repetitive load_caller_token_gas_allowance test invocations through
  local closures.
panos-xyz added a commit that referenced this pull request Dec 1, 2026
panos-xyz added a commit that referenced this pull request Dec 4, 2026
…dit items

- Sync finalized semantics of PRs #237, #238, #239, #240, #241, #244, #247, #248, and #249 natively on reth v2.11.0 + evm2:
  - Proofs ExEx revert retry state machine, zeroed-slot storage pruning, and Reference Index batch parent linkage & async RPC polling
  - Safe validation exemptions (is_safe + safe_blocks FIFO), tree_headers cache, pre/post-Jade next_l1_msg_index & unhashed header checks, synchronized pool eviction, and no_tx_pool forward skip
  - Delegate eth_simulateV1 to upstream with 65B placeholder-sig Curie L1 fee encoding (validation:true), zero L1 fee (validation:false), and normalize_simulate_call
  - Enforce --rpc.gascap (0 = unlimited) across eth_call/eth_callMany/eth_estimateGas and honor blockOverrides.gasLimit above header gas_limit ([MR-10], [MR-12])
- Close unfixed audit items:
  - [MR-03]: Reload live (token_address, balance_slot) from L2TokenRegistry during post-execution token fee reimbursement while keeping deduction-time rates
  - [MR-14]: Rewind orphaned safe block tag to canonical finalized (or genesis) on engine_newL2BlockV2 reorgs and warm BlockTagTracker on startup
  - TxPool Option A: Enforce U256 price bump uniformly on priority_fee_or_price() across Legacy and dynamic-fee replacements
- Restore SP1 zkVM quanta-free dependency graph on morph-revm and morph-evm
- Bump workspace version to 2.0.0, resolve RUSTSEC advisories, and clear CodeQL test false positives
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant