Skip to main content

@faremeter/fetch

@faremeter/fetch wraps the native fetch API so your application can negotiate Coinbase x402 payments automatically. It understands 402 Payment Required responses, consults local payment handlers, signs payloads, and retries with an X-PAYMENT header.
Source: GitHub › packages/fetch
The package is framework agnostic—use it in browsers, Workers, Node.js, or anywhere fetch is available.

Quick start

import { wrap } from "@faremeter/fetch";
import { createPaymentHandler as solanaHandler } from "@faremeter/payment-solana/exact";
import { Connection, PublicKey } from "@solana/web3.js";

const handlers = [
  await solanaHandler(
    {
      network: "mainnet-beta",
      publicKey: userKeypair.publicKey,
      sendTransaction: userSendTransaction,
    },
    new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), // USDC mint
    new Connection("https://api.mainnet-beta.solana.com"),
  ),
];

const paywalledFetch = wrap(fetch, {
  handlers,
  payerChooser: async (execers) => execers[0], // optional custom chooser
});

const response = await paywalledFetch("https://merchant.example/api/resource");
When the upstream service replies with a 402, wrap will:
  1. Parse the x402 payment requirements (@faremeter/types/x402).
  2. Ask each handler for compatible PaymentExecers.
  3. Pick one (default: first available) and execute it to produce a payload.
  4. Base64-encode the payload into the X-PAYMENT header.
  5. Retry the request with the header and return the new response.
If all retries still return 402 and returnPaymentFailure is false, a WrappedFetchError is thrown.

API surface

wrap(phase2Fetch, options)

Wraps a fetch implementation. Returns a function with the same signature.
  • phase2Fetch: fetch used for the retry that carries the payment header. Pass fetch directly for most cases; override when you need different runtimes for the retry.
  • options.handlers: required array of PaymentHandlers. See @faremeter/types/client.
  • options.payerChooser: async function that selects a PaymentExecer when multiple handlers return candidates. Defaults to chooseFirstAvailable.
  • options.phase1Fetch: alternative fetch for the first attempt (before payment). Useful when hitting a public edge that must see the original request.
  • options.retryCount: number of additional attempts if the second phase keeps returning 402 (default 2).
  • options.initialRetryDelay: backoff starting delay in milliseconds (default 100). Doubles on each retry.
  • options.returnPaymentFailure: when true, returns the final 402 response instead of throwing.
  • Additional properties from ProcessPaymentRequiredResponseOpts (e.g., payerChooser) are forwarded to the underlying processor.

WrappedFetchError

Subclass of Error thrown when retries are exhausted and returnPaymentFailure is false. The original Response is attached as .response.

internal.processPaymentRequiredResponse(context, responseBody, options)

Low-level helper that powers wrap. It:
  • Validates the merchant’s JSON using @faremeter/types/x402.
  • Invokes each PaymentHandler, collecting possible PaymentExecers.
  • Lets you supply a payerChooser to decide which payer executes.
  • Executes the chosen payer, returning { payer, payerResult, paymentPayload, paymentHeader }.
Use this directly if you need bespoke retry logic but still want the x402 parsing utilities.

internal.chooseFirstAvailable(execers)

Default chooser: throws if the array is empty or contains undefined, otherwise returns execers[0].

mock.responseFeeder(responses)

Testing helper that returns a mock fetch function. Provide a queue of Response objects or functions returning Response; each invocation consumes the next item.

Usage patterns

  • Multiple networks: Combine Solana/EVM handlers in the handlers array. The payer chooser can inspect requirements.scheme or requirements.network to prefer a specific chain.
  • UX retries: Set returnPaymentFailure: true to bubble the failing response back to UI layers instead of throwing. Great for showing “Payment still pending…” states.
  • Custom telemetry: Wrap the returned fetch to capture metrics (e.g., time spent negotiating payments).
  • @faremeter/types: definitions for x402 payloads, PaymentHandler, and PaymentExecer.
  • @faremeter/payment-solana, @faremeter/payment-evm: ready-made handlers for blockchain settlements.
  • @faremeter/middleware: server-side companion that issues the 402 Payment Required responses.