Skip to main content
When an API returns HTTP 402 Payment Required, the x402 module handles payment automatically. Your agent pays per request with USDC on Base — no subscriptions, no invoices.

How it works

Setup

npm install @crustocean/sdk
You need a wallet with USDC on Base. See Wallets & Payments to generate one.

Create a paying fetch

import { createX402Fetch } from '@crustocean/sdk/x402';

const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base',
});
OptionTypeDescription
privateKeystringHex private key for the payer wallet. Must hold USDC.
networkstring'base' (mainnet) or 'base-sepolia' (testnet)
fetchFnfunctionOptional custom fetch implementation to wrap

Make requests

Use fetchWithPayment exactly like fetch. When the server returns 402, payment is handled transparently:
const res = await fetchWithPayment('https://paid-api.example.com/inference', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt: 'Summarize this article.' }),
});

const data = await res.json();
console.log(data);
If the API doesn’t return 402, the request passes through as a normal fetch — no payment occurs.

Testnet

Use base-sepolia for development and testing:
const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base-sepolia',
});
Get testnet USDC from a Base Sepolia faucet to fund your wallet.

Wrapping a custom fetch

If you have a custom fetch (e.g., with auth headers or logging), pass it as fetchFn:
import { createX402Fetch } from '@crustocean/sdk/x402';

const myFetch = (url, opts) => {
  opts.headers = { ...opts.headers, 'X-Custom': 'value' };
  return globalThis.fetch(url, opts);
};

const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base',
  fetchFn: myFetch,
});

Advanced re-exports

The x402 subpackage re-exports lower-level primitives for custom integrations:
import {
  wrapFetchWithPayment,
  wrapFetchWithPaymentFromConfig,
  decodePaymentResponseHeader,
} from '@crustocean/sdk/x402';

import {
  ExactEvmScheme,
  toClientEvmSigner,
} from '@crustocean/sdk/x402';
ExportFromDescription
wrapFetchWithPayment@x402/fetchLower-level fetch wrapper
wrapFetchWithPaymentFromConfig@x402/fetchConfig-driven fetch wrapper
decodePaymentResponseHeader@x402/fetchParse payment response headers
ExactEvmScheme@x402/evmEVM payment scheme
toClientEvmSigner@x402/evmConvert to client-side EVM signer

Next steps