Skip to content

fix collectFees native - #1642

Merged
alexcos20 merged 1 commit into
mainfrom
bug/fix_collectfess_native_token
Nov 27, 2026
Merged

alexcos20 merged 1 commit into
mainfrom
bug/fix_collectfess_native_token

Conversation

@alexcos20

@alexcos20 alexcos20 commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Fix collectFees native-token crash on non-EIP-1559 chains ("Cannot mix BigInt and other types")

Branch: bug/fix_collectfess_native_token (base: main)
Type: bug fix + hardening + regression tests


Summary

The collectFees admin command crashed with
TypeError: Cannot mix BigInt and other types, use explicit conversions
whenever it swept the native token on a legacy / non-EIP-1559 chain (Ganache /
barge chainId 8996). The node returned HTTP 500 (and the equivalent P2P error),
which also blocked ocean.js CI.

Root cause: Blockchain.calculateGasCost read block.baseFeePerGas, which is null
on non-EIP-1559 chains, then did baseFee + priorityFee. Adding null to a bigint
throws the Cannot mix BigInt and other types TypeError.

This PR defaults a missing base fee to 0n, hardens the same bug class in
getGasOptions, and adds unit tests that reproduce the crash conditions.


Root cause detail

src/utils/blockchain.ts → calculateGasCost:

const block = await provider.getBlock('latest')
const baseFee = block.baseFeePerGas        // null on Ganache / pre-EIP-1559 chains
const priorityFee = parseUnits('2', 'gwei') // bigint
const maxFee = baseFee + priorityFee        // null + bigint  →  TypeError

calculateGasCost is only reached from the native-token branch of the collectFees
handler (src/components/core/admin/collectFeesHandler.ts, tokenAddress === ZeroAddress),
which is why only the native-token path failed and the ERC20 path did not.

Call path: CollectFeesHandler.handle → native branch (tokenAddress === ZeroAddress)
→ blockchain.calculateGasCost(...) → baseFee + priorityFee with baseFee === null.


Changes

1. src/utils/blockchain.ts — calculateGasCost (the fix)

const block = await provider.getBlock('latest')
const baseFee = block?.baseFeePerGas ?? 0n   // was: block.baseFeePerGas
  • Defaults a missing baseFeePerGas to 0n so the gas-cost math stays entirely in
    BigInt on legacy chains.
  • The block?. optional chain also guards the (rarer) case where getBlock('latest')
    returns null.
  • Behavior on real EIP-1559 chains is unchanged — a real bigint base fee passes
    through ?? 0n untouched.

Why 0n is safe here: calculateGasCost is used only as an advisory balance
pre-check
in collectFeesHandler.ts (if (balance < calculateGasCost(...)) reject).
The value actually transferred on-chain is always exactly the requested amount —
never "balance minus gas" — so a looser estimate can only cause an attempt that the
RPC then rejects for insufficient funds (surfaced as an error), never an over-transfer.
The change strictly improves behavior on non-EIP-1559 chains and loosens no real
protection. (On legacy chains the estimate uses the hardcoded 2 gwei priority fee
rather than the chain's gasPrice, so it is approximate but conservative for a
pre-check.)

2. src/utils/blockchain.ts — getGasOptions (same bug class, hardened)

// before:
if (feeData.maxPriorityFeePerGas) {
  ...
  const maxFee = (feeData.maxFeePerGas * multiplier) / 100n   // throws if maxFeePerGas is null

// after:
if (feeData.maxPriorityFeePerGas != null && feeData.maxFeePerGas != null) {
  ...
}
// else → existing legacy `gasPrice` branch

getGasOptions had the same latent assumption: on a chain reporting a priority fee but
a null maxFeePerGas, feeData.maxFeePerGas * multiplier would throw the same
TypeError. Instead of defaulting the missing field to 0n (which would floor
maxFeePerGas to 1 wei — below the priority fee, producing an invalid,
unsubmittable fee pair), the EIP-1559 branch now requires both fields to be present
and otherwise falls through to the existing gasPrice branch — the correct legacy
behavior. Normal EIP-1559 chains are unaffected. (getGasOptions is used by the escrow
flow, not by collectFees, so this is defensive hardening of the same bug class.)

3. src/test/unit/blockchain.test.ts — regression tests

Two new describe blocks, provider/signer stubbed (no live chain needed), each
restoring the stub in afterEach:

  • calculateGasCost gas-fee math
    • returns a bigint when baseFeePerGas is null (the reproduced crash)
    • returns a bigint when getBlock('latest') returns null
    • still includes the base fee on EIP-1559 chains (exact-value assertion)
  • getGasOptions fee-field handling
    • applies the multiplier on complete EIP-1559 data
    • falls back to gasPrice when maxFeePerGas is null (partial data)
    • falls back to gasPrice when maxPriorityFeePerGas is null (legacy chain)

All 6 pass:

npm run build-tests
npx mocha --node-env=test --config .mocharc.json \
  "./dist/test/unit/blockchain.test.js" --grep "gas-fee math|fee-field handling"
# 6 passing

Reproduce (before the fix)

  1. Start barge (Ganache chainId 8996 + ocean-node): ./start_ocean.sh.
  2. Call collectFees for the native token:
    { "command": "collectFees", "chainId": 8996,
      "tokenAddress": "0x0000000000000000000000000000000000000000",
      "tokenAmount": "0.0001", "destinationAddress": "0x..." }
    → HTTP 500 TypeError: Cannot mix BigInt and other types before the fix; returns a
    tx hash after it.

The added unit tests reproduce the same condition without barge.


Review summary

Reviewed by three focused agents (code quality, QA/test coverage, security):

  • Security: security-neutral for fund safety — the transferred amount is always the
    requested value, so a looser gas pre-check can only cause a self-reverting tx reported
    as an error (fail-safe). Admin-only command, auth/validation path unchanged, no key
    handling touched.
  • Code review + QA: both independently flagged that the first-draft getGasOptions
    hardening (defaulting fields to 0n) produced an invalid maxFee < priority pair and
    contained dead code; the fix was revised to fall through to the gasPrice branch
    (addressed in this PR). Test stubs are now restored in afterEach.

Out of scope (pre-existing, not addressed here)

  • Native full-balance sweep (no tokenAmount given): the guard compares balance
    against balance + gasCost, which is always true → always rejects with "Amount too
    high". Pre-dates this change and fails safe. If native full-sweep is intended to work,
    the guard should compare against balance - gasCost and send balance - gasCost.
  • Native-branch parseUnits is not wrapped in try/catch (unlike the ERC20 branch), so
    a malformed tokenAmount surfaces as a generic 500 rather than a clean 400. Cosmetic,
    admin-only input.

Scope / files

  • src/utils/blockchain.ts — calculateGasCost null-guard (the fix) + getGasOptions
    hardening.
  • src/test/unit/blockchain.test.ts — 6 regression tests.
  • No ABI, config, or API-contract change. No change needed in ocean.js. Behavior on
    EIP-1559 chains (mainnet / L2s) is unchanged.

Summary by CodeRabbit

  • Bug Fixes
    • Improved gas cost calculations when block or base-fee data is unavailable.
    • Gas options now fall back to gasPrice when EIP-1559 fee values are incomplete.

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change updates blockchain gas cost and gas option handling for missing or incomplete fee data. Regression tests cover null blocks, null base fees, and incomplete EIP-1559 fee values.

Changes: Gas fee handling

Layer / File(s) Summary
Gas cost fallback
src/utils/blockchain.ts, src/test/unit/blockchain.test.ts
calculateGasCost treats a missing block or baseFeePerGas as 0n. Tests cover missing blocks, missing base fees, and a non-null base fee.
Gas options fallback
src/utils/blockchain.ts, src/test/unit/blockchain.test.ts
getGasOptions uses EIP-1559 fee values only when both are non-null. Otherwise, it returns the legacy gasPrice option. Tests cover complete and incomplete fee values.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: mariacarmina

Merge Risk: Minimal · up to bffef

This change stops collectFees from crashing on legacy chains that report no base fee, and makes gas options fall back to gasPrice when fee data is incomplete. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix collectFees native" names the main change: a fix for the collectFees native-token crash on legacy chains. The objectives say the crash came from adding a null baseFeePerGas to a bigint …
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.
Full details: Title check

Explanation

The title "fix collectFees native" names the main change: a fix for the collectFees native-token crash on legacy chains. The objectives say the crash came from adding a null baseFeePerGas to a bigint in calculateGasCost, and the change defaults missing values to 0n. The title is short but has no filler, and it is specific to the changeset, though it does not name the gas-cost root cause or the getGasOptions hardening.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • 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: ae0ec631-e77a-4c2e-9068-e5b9b00cd6d1
Commits

Reviewing files that changed from the base of the PR and between 9f7b371 and bffefc3.

Files selected for processing: 2

  • src/test/unit/blockchain.test.ts
  • src/utils/blockchain.ts

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

@alexcos20

Copy link
Copy Markdown
Member Author

/run-security-scan

@alexcos20 alexcos20 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI automated code review (Gemini 3).

Overall risk: low

Summary:
The PR successfully resolves crashes related to BigInt math on non-EIP-1559 chains by properly handling null values for baseFeePerGas and maxFeePerGas. The implementation correctly defaults missing base fees to 0n and falls back to legacy gas price calculation if EIP-1559 fee data is incomplete. Excellent test coverage has been added to ensure these edge cases are locked down. LGTM!

Comments:
• [INFO][bug] Excellent fix for the BigInt type collision. Using the nullish coalescing operator ?? 0n safely bridges the gap between EIP-1559 and legacy chains, ensuring type safety in all subsequent math operations.
• [INFO][style] Good edge-case handling here. Using != null correctly checks for both null and undefined. Safely falling back to the legacy branch prevents exception-throwing operations and ensures transaction compatibility on chains with incomplete EIP-1559 support.
• [INFO][style] Comprehensive coverage for the different EIP-1559 and legacy combinations. Minor architectural note: While using any for originalGetProvider and temporarily overwriting methods works fine here, consider using a mocking library like sinon.stub() or jest.spyOn() for cleaner and type-safe mock management and restoration in future iterations.

@alexcos20
alexcos20 merged commit 5d94d5b into main Nov 27, 2026
16 of 17 checks passed
@alexcos20
alexcos20 deleted the bug/fix_collectfess_native_token branch November 27, 2026 14:42
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.

2 participants