ClawRouter icon indicating copy to clipboard operation
ClawRouter copied to clipboard

feat: support fxUSD and multi-decimal EIP-3009 stablecoins

Open huwangtao123 opened this issue 8 months ago • 1 comments

What

Add proper multi-decimal EIP-3009 stablecoin support, fixing bugs that would cause incorrect behavior with non-6-decimal assets like fxUSD (18 decimals).

Why

ClawRouter's payment layer was hardcoded to assume 6 decimals (USDC) in several places. Adding fxUSD (18 decimals, verified on Basescan) exposed these gaps.

Changes

  • /health endpoint now returns paymentAssetDecimals
  • Proxy reuse path preserves decimals from existing proxy (fixes 10^12× balance inflation for 18-decimal assets)
  • transformPaymentError uses asset-native decimals for USD conversion in insufficient_funds errors
  • payment-asset.ts (new) — BasePaymentAsset type, normalizer, fetcher
  • balance.ts — updated USDC-specific comments to generic stablecoin
  • 3 new tests — fxUSD normalization, mixed-decimal assets, real contract address

On-Chain Verification

fxUSD contract (0x55380fe7a1910dff29a47b622057ab4139da42c5) on Base implements full EIP-3009:

  • transferWithAuthorization ✅
  • receiveWithAuthorization ✅
  • cancelAuthorization ✅
  • All typehashes + authorizationState + DOMAIN_SEPARATOR ✅

Testing

  • 363 tests pass, 0 regressions
  • 3 new tests added for fxUSD-specific scenarios

Summary by CodeRabbit

  • New Features
    • Multi-asset Base support with per-request asset selection, runtime asset switching, normalized USD-micros balances, and payment-asset metadata surfaced in health/proxy outputs; default remains USDC on Base.
  • Bug Fixes / UX
    • Balance checks, shortfall messages and funding prompts now show the active asset symbol and use consistent USD formatting.
  • Tests
    • New tests covering payment-asset normalization, fetching, ordering and fallback behavior.

huwangtao123 avatar Mar 21 '26 05:03 huwangtao123

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Balance monitoring was generalized from a USDC-only model to configurable Base-chain EIP-3009 assets; a new payment-asset module and tests were added; proxy, CLI, doctor, index, and Solana monitor code were updated to fetch, advertise, select, and use per-request Base payment assets for balance checks and deductions.

Changes

Cohort / File(s) Summary
Payment Asset Infrastructure
src/payment-asset.ts, src/payment-asset.test.ts
Adds BasePaymentAsset type and DEFAULT_BASE_PAYMENT_ASSET; normalization helpers (normalizeBasePaymentAsset, normalizeBasePaymentAssets), fetchers (fetchBasePaymentAsset(s)), priority/enablement filtering and fallback; includes Vitest coverage for normalization, fetching, fallback, ordering.
Balance Monitor Generalization
src/balance.ts
BalanceMonitor now accepts a BasePaymentAsset (default fallback), reads balances from this.asset.asset, normalizes on-chain amounts to USD micros, adds setAsset()/getAsset()/getAssetSymbol(), per-asset shared monitors cache, updates BalanceInfo to include assetSymbol, and renames USDC format helper to generic formatUSD().
Proxy Server Integration
src/proxy.ts
Introduces paymentAssets/selected asset state, persists/restores active asset selection, exposes asset metadata in /health, selects a sufficient Base asset per request by iterating candidate monitors, threads per-request requestBalanceMonitor for checks/optimistic deductions/invalidation, and surfaces asset metadata in error formatting.
CLI & Doctor output and startup
src/cli.ts, src/doctor.ts
Console messages and startup diagnostics now reference resolved Base payment asset symbol; doctor fetches payment asset (with fallback) and constructs BalanceMonitor(address, paymentAsset); funding/get-buy messages adjusted per asset.
Exports / Public API Surface & Wallet UI
src/index.ts, src/solana-balance.ts
Exports payment-asset utilities/types (DEFAULT_BASE_PAYMENT_ASSET, fetchBasePaymentAsset, normalizeBasePaymentAsset, BasePaymentAsset); Solana monitor now exposes assetSymbol in SolanaBalanceInfo and getAssetSymbol(); /wallet lists supported assets and per-asset balance lines.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Proxy as Proxy Server
    participant Fetcher as Asset Fetcher
    participant Selector as Asset Selector
    participant Monitor as BalanceMonitor
    participant Chain as Blockchain

    Client->>Proxy: incoming request
    Proxy->>Fetcher: fetchBasePaymentAssets()
    Fetcher-->>Proxy: normalized asset list
    Proxy->>Selector: evaluate assets for sufficiency
    loop candidates
        Selector->>Monitor: getSharedMonitorForAsset(candidate)
        Selector->>Monitor: checkSufficient(bufferedCostMicros)
        Monitor->>Chain: balanceOf(candidate.asset)
        Chain-->>Monitor: raw token balance
        Monitor->>Monitor: toUsdMicros(raw, decimals)
        Monitor-->>Selector: sufficiency result
        alt sufficient
            Selector-->>Proxy: select asset & stop
        end
    end
    Proxy->>Monitor: optimistic deduction on selected monitor
    Proxy-->>Client: proceed / respond

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: support fxUSD and multi-decimal EIP-3009 stablecoins' accurately reflects the primary changes in the PR: adding support for multiple EIP-3009 stablecoins with varying decimals, specifically fxUSD.
Docstring Coverage ✅ Passed Docstring coverage is 86.36% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Mar 21 '26 05:03 coderabbitai[bot]

Thanks for this — and to be clear up front, the math is correct. toUsdMicros (rawAmount / 10n ** BigInt(decimals - 6)) is BigInt throughout and truncates conservatively, and I checked that the signed amount still comes from the server's selectedRequirements.amount, so there was never a 10^n mispay risk here. The decimals work only affects balance pre-checks, error text and /health.

Closing for a different reason: it's client-side support for a server capability that doesn't exist. It discovers assets via GET /v1/payment-metadata?chain=base, which returns 404 on the live gateway today. A client can only pay with what the server advertises in its 402, and the gateway advertises USDC only — so fetchBasePaymentAssets always falls through to DEFAULT_BASE_PAYMENT_ASSET. The 1656 lines unconditionally no-op.

This is server-led. If we ship multi-asset 402s, this is worth reopening against that work — but the diff is 4 months old, conflicting, and includes 730 lines of regenerated dist/, so it wouldn't survive the rebase anyway. Sorry it sat this long without that being said.

VickyXAI avatar Jul 15 '26 04:07 VickyXAI