Skip to content

feat(transaction): add useGasEstimator hook#2638

Open
lau90eth wants to merge 1 commit into
coinbase:mainfrom
lau90eth:feat/gas-estimator
Open

feat(transaction): add useGasEstimator hook#2638
lau90eth wants to merge 1 commit into
coinbase:mainfrom
lau90eth:feat/gas-estimator

Conversation

@lau90eth
Copy link
Copy Markdown

@lau90eth lau90eth commented May 2, 2026

Summary

Every user on Base has overpaid gas at least once. Gas spikes are invisible
until after signing — wallets show "0.00 ETH" and then charge $50.
OnchainKit has zero gas visibility before the user confirms.

This PR adds useGasEstimator, a hook that shows real-time gas fees with
spike detection — before the user clicks "Confirm".

const { estimatedFee, maxFee, isSpike, isSafe, waitTimeMinutes } = 
  useGasEstimator({ maxAcceptableFee: '0.01' });

// "Fee: $0.12 ✅ — safe to send"
// "Gas spike! $4.50 🔴 — wait ~3 min for better rates"

What changed

  • useGasEstimator hook — estimates real-time gas fees for the current
    Transaction calls. Detects spikes, flags safe windows, and suggests
    wait time when gas is elevated. Auto-refreshes every 15s (configurable).
  • estimateGasFee utility — reads onchain gas price via viem
    getGasPrice + estimateGas, maintains a 20-block median history
    for spike detection, calculates worst-case max fee with 150% buffer.
  • GasEstimate type — standardized shape for gas data including
    spike/safe flags and wait time estimate.
  • Public exports — added to src/transaction/index.ts

Usage

import { useGasEstimator } from '@coinbase/onchainkit/transaction';

const { 
  estimatedFee,     // "0.000012" ETH
  maxFee,           // "0.000018" ETH (150% buffer)
  gasUnits,         // bigint
  gasPrice,         // bigint (wei)
  isSpike,          // true if > 2x median network gas
  isSafe,           // true if < 1.2x median
  waitTimeMinutes,  // estimated wait for safe window
  isLoading,
  error,
} = useGasEstimator({
  maxAcceptableFee: '0.01',  // ETH — optional cap
  refreshInterval: 15000,    // ms — default 15s
});

// Usage in UI
{isSpike && (
  <div>⚠️ Gas spike — estimated wait: {waitTimeMinutes} min</div>
)}
{isSafe && (
  <div>✅ Fee: {estimatedFee} ETH — safe to send</div>
)}

API

type UseGasEstimatorParams = {
  maxAcceptableFee?: string;  // in ETH, e.g. "0.01"
  refreshInterval?: number;   // ms, default 15000
};

type GasEstimate = {
  estimatedFee: string;       // in ETH
  estimatedFeeUsd?: string;   // if price available
  maxFee: string;             // worst case (150% buffer)
  gasUnits: bigint;
  gasPrice: bigint;
  isSpike: boolean;           // gas > 2x median
  isSafe: boolean;            // gas < 1.2x median
  waitTimeMinutes?: number;   // estimated wait for safe window
};

Notes to reviewers

  • Zero external API dependency — reads directly from chain via viem
    getGasPrice and estimateGas. Works on any chain configured in
    OnchainKitProvider.
  • Spike detection — maintains a 20-block in-memory median history
    per chain. isSpike = current gas > 2x median. isSafe = current
    gas < 1.2x median.
  • waitTimeMinutes — heuristic based on historical gas volatility
    in the cached 20-block window. Not guaranteed — presented as an
    estimate to guide user decisions.
  • maxAcceptableFee — optional. When set, isSafe also requires
    estimated fee to be below this threshold.
  • Auto-refreshes every refreshInterval ms. Clears on unmount.
  • Reads calls from useTransactionContext automatically.

Testing

  • useGasEstimator.test.ts — 4 tests
  • estimateGas.test.ts — utility unit tests
  • All 389 test files pass (2697 tests)

Test cases covered:

  • Empty state when no calls present → returns null
  • Normal gas estimate → correct fee calculation
  • Spike detection → isSpike: true when gas > 2x median
  • API/onchain error → graceful fallback, error state exposed

Risk

Low. Read-only hook. Uses getGasPrice and estimateGas
both are standard viem read operations with zero side effects.

Returns null when no calls are present.
Does not modify TransactionProvider, TransactionButton,
or any existing transaction logic.

Adds real-time gas estimation with spike detection and safety indicators.

- useGasEstimator hook: estimates gas fees, detects spikes, suggests wait time
- estimateGasFee utility: reads onchain gas price, calculates median, detects spikes
- Auto-refresh every 15s (configurable)
- Shows: safe ✅, spike 🔴 with estimated wait time
- 4 tests covering: empty state, normal estimate, spike detection, API error

Refs: coinbase#2572
@vercel
Copy link
Copy Markdown

vercel Bot commented May 2, 2026

@lau90eth is attempting to deploy a commit to the Coinbase Team on Vercel.

A member of the Team first needs to authorize it.

@cb-heimdall
Copy link
Copy Markdown

🟡 Heimdall Review Status

Requirement Status More Info
Reviews 🟡 0/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 0
Sum 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants