x402

Pay for each request in USDC on Base with x402, without an account or API key. How the 402 challenge works, exact and upto payments, Permit2, and paying from Node or MCP.

Most integrations use an API key and credits. x402 is the other way in: no account and no key. Your code pays for each request in USDC on Base and gets back the normal API data response.

It suits AI agents and scripts that hold a wallet, and one-off calls where signing up isn't worth it. If you send a valid x-api-key, x402 is skipped and the request bills credits as usual. An invalid key returns 401; it never falls back to a wallet payment.

A few routes always need an API key and aren't available through x402: /v1/whoami, /v1/balance and natural-language Ask (POST /v1/ask). Without a key they return 401.

Paid routes are also listed in the Coinbase x402 Bazaar catalogue, for HTTP and MCP.

What you need

  • A wallet on Base holding some USDC, and its private key available to your code (server-side only).
  • A client that speaks x402. The official @x402/fetch package does it for Node; the buyer quickstart covers other languages.
  • For routes that use the upto scheme, a one-time Permit2 approval from the wallet.

How it works

A four-step diagram. 1: your code calls the API with no x-api-key header. 2: Social Fetch answers 402 Payment Required with a PAYMENT-REQUIRED header giving the amount, network, address and scheme; this card is boxed and labelled The price comes back as a 402. 3: your wallet signs a USDC payment and the same request is sent again with a PAYMENT-SIGNATURE header. 4: Social Fetch returns 200 OK with the usual JSON and a PAYMENT-RESPONSE receipt. Two cards below say @x402/fetch does steps 2 and 3, and that a valid API key skips x402 and bills credits.
The same request goes out twice: once to get the price, once with the payment.
  1. Call a paid route without an x-api-key header.
  2. The API answers 402 Payment Required. The PAYMENT-REQUIRED header holds the price: a Base64-encoded JSON object with the amount, network, receiving address and scheme.
  3. Sign a USDC payment for that amount with your wallet.
  4. Send the same request again with the signed payment in a PAYMENT-SIGNATURE header.
  5. You get the normal response. The PAYMENT-RESPONSE header is the receipt for the payment that settled on Base.

@x402/fetch does steps 2 to 4 for you. If the API operation returns HTTP 400 or higher, payment is cancelled before settlement. An MCP tool error is also cancelled. A successful response can still be billable when it reports that an account is private or nothing was found. Settlement failures are a separate case: see Which 402 is this?.

To make retries safe, you can send a payment identifier to help guard against replay. This does not make a fresh payment for a repeated request free.

Try it without paying

An unpaid request costs nothing and shows you the price:

curl -i "https://api.socialfetch.dev/v1/twitter/profiles/elonmusk"
HTTP/1.1 402 Payment Required
Content-Type: application/json
Payment-Required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIi…

{"error":{"code":"payment_required","message":"Missing API key. Include a valid x-api-key header to bill credits. See https://www.socialfetch.dev/docs/quickstart.","requestId":"req_…"}}

The body is written for people who meant to send an API key and forgot. x402 clients ignore it and read the header. To decode the header yourself:

curl -s -o /dev/null -D - "https://api.socialfetch.dev/v1/twitter/profiles/elonmusk" \
  | grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\r' | base64 --decode

The part that matters is accepts, the ways you can pay (an unpaid capture, shortened here). Always use the amount, network, asset and receiving address from your current challenge:

{
  "x402Version": 2,
  "error": "Payment required",
  "resource": {
    "url": "https://api.socialfetch.dev/v1/twitter/profiles/elonmusk",
    "description": "Get an X (Twitter) profile by handle or numeric user id."
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "14000",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "payTo": "0x02C2fCAfCe36B4AAdB39625866Bc6B1699d83043",
      "maxTimeoutSeconds": 300,
      "extra": { "name": "USD Coin", "version": "2" }
    }
  ]
}

The header also carries extensions: the route's input and output schema for the Bazaar, and the optional payment identifier.

Left: the 402 response, with the payment-required header line boxed and labelled The price is in this header, above the JSON error body with code payment_required. Right: the header decoded into rows. scheme exact, pay this exact amount. network eip155:8453, Base. amount 14000, with $0.014 underlined, in USDC, which has 6 decimal places. asset, USDC on Base. payTo, Social Fetch's receiving address. maxTimeoutSeconds 300, how long a signed payment stays valid.
The amount is in USDC's smallest unit: 14000 is $0.014, the price of one credit.

What it costs

x402 uses the route's credit pricing contract at $0.014 per credit (the Starter pack rate). API-key credit packs and subscriptions can have a lower price per credit. With exact, you pay the quoted amount even if an API-key request would ultimately charge fewer credits; with upto, settlement uses the actual credit charge, up to the authorised maximum. The amount in the challenge is in USDC's smallest unit, which has 6 decimal places, so 14000 is $0.014. Each route's credit cost is in the API reference.

Exact and upto

The challenge names a scheme, which says how you pay:

SchemeUsed forWhat you paySetup
exactRoutes with a fixed price (most of them)The price in the challengeNone. USDC's own signed transfers (EIP-3009) need no approval
uptoRoutes whose price depends on what comes back, such as batches and filesYou authorise a maximum and pay only what was chargedA one-time Permit2 approval
Two cards. exact, for a fixed price: an X profile lookup where the challenge asks for $0.014, you sign $0.014 and you pay $0.014. upto, for a price that depends on the result: an Instagram post with include=files, where the challenge authorises up to $0.854 (61 credits), a labelled calculation assumes one 16 MB block for 11 credits, which would cost $0.154; the Calculated payment row is boxed and labelled Calculated from 11 credits.
With upto, the challenge is a ceiling. This is a pricing calculation, not a completed payment or receipt.

For example, if a post and its files cost 11 credits under the pricing contract, upto would settle $0.154 against a $0.854 ceiling. No payment was made for this illustration. Unused authorisation is not a charge that needs refunding.

Register both schemes in your client and you don't need to know which route uses which. A client with only exact gets a challenge it can't pay on routes that offer only upto.

Routes whose price depends on the options

Some routes cost more when you ask for extras, such as downloading or hosting media (downloadMedia, hostMedia, include=files). The challenge for these depends on the request:

  • No extras asked for: a plain exact payment at the base price.
  • Extras asked for: upto at the most the request can cost, then you pay only for what was delivered. Some of these routes also offer exact at that same maximum, so a client with only exact still works there but always pays the maximum.

@x402/fetch takes the first option your client supports, and upto is listed first, so a client with both schemes pays only what was delivered. The same rules apply to paid MCP tools.

One-time Permit2 approval

To pay with upto on Base, your wallet must allow the standard Permit2 contract to spend its USDC. Approve before the first upto payment, then renew the allowance if it is used up or revoked:

  • USDC on Base: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
  • Permit2: 0x000000000022D473030F116dDEE9F6B43aC78BA3

Use your wallet to approve a USDC allowance for Permit2 that covers your intended payments. Approval allows spending up to that allowance; review the amount before confirming it. It's an ordinary on-chain transaction, so the wallet needs a little ETH on Base for gas that one time. exact payments don't need it. The x402 buyer quickstart has more on the setup.

Wallet approval screen pending an authorised account. Review the allowance before approving.

Pay from Node

Install the official buyer packages, then wrap fetch. Register Base (eip155:8453) with both the exact and upto schemes.

npm install @x402/fetch@2.19.0 @x402/evm@2.19.0 viem
import {
  decodePaymentResponseHeader,
  wrapFetchWithPayment,
  x402Client,
} from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { UptoEvmScheme } from "@x402/evm/upto/client";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(
  process.env.EVM_PRIVATE_KEY as `0x${string}`,
);

const client = new x402Client()
  .register("eip155:8453", new ExactEvmScheme(signer))
  .register("eip155:8453", new UptoEvmScheme(signer));

const fetchWithPayment = wrapFetchWithPayment(fetch, client);

const res = await fetchWithPayment(
  "https://api.socialfetch.dev/v1/twitter/profiles/elonmusk",
);

console.log(res.status, await res.json());

// The receipt for the payment that settled.
const receipt = res.headers.get("PAYMENT-RESPONSE");
if (receipt) console.log(decodePaymentResponseHeader(receipt));

Keep the private key on your server, never in a browser or an app you ship.

MCP

MCP has two addresses:

  • https://api.socialfetch.dev/mcp is the recommended address for an OAuth connection. It accepts OAuth or an x-api-key, and paid tools bill credits on your account. With no credentials it returns 401.
  • https://api.socialfetch.dev/x402/mcp accepts anonymous wallet callers without an account. For those callers, paid tools answer with an x402 price; your client attaches the payment to the tool call and it settles in USDC. The same exact, upto and Permit2 rules apply. The @x402/mcp package's wrapMCPClientWithPayment handles this for an MCP client.

Whoami, balance and Ask require an authenticated account identity. Anonymous wallet callers cannot use them. With valid OAuth or x-api-key credentials, you can use these tools on either address; paid calls bill credits rather than USDC.

An invalid Bearer token or x-api-key returns 401 on both addresses. It never falls back to x402.

Which 402 is this?

Social Fetch uses HTTP 402 for three different things, so don't treat every 402 as "out of credits".

A decision diagram. HTTP 402 leads to the question Is there a PAYMENT-REQUIRED header?, which is boxed and labelled Check this first. Three cards below: header present with error.code payment_required is an x402 price, so pay and send the same request again. No header with insufficient_credits means the workspace balance or key spending limit blocked the call; read the error message. No header with payment_settlement_failed means settlement could not be confirmed and no data was returned. Check payment status before retrying; a timeout can leave the outcome uncertain.
Look for the PAYMENT-REQUIRED header first, then the error code.
What you seeWhat it meansWhat to do
A PAYMENT-REQUIRED header and error.code payment_requiredNo API key was sent, and this is the x402 pricePay and send the same request again
error.code insufficient_credits (you sent an API key)The workspace balance or the key's spending limit blocked the callRead the message: top up credits for a balance refusal, or review the key's limit
error.code payment_settlement_failedSettlement could not be confirmed, so the data was withheldRetry only after a definitive failure. For a timeout, check the transaction or contact support with the request ID before signing a fresh payment

A timeout during settlement may mean the transfer completed even though its confirmation did not arrive. The API keeps its replay protection in that case; do not assume the payment failed or that a refund happened.

If a local or self-hosted API returns 401 unauthorized with Missing API key. and no PAYMENT-REQUIRED header, x402 may be disabled there. Use an API key or ask the operator to check the deployment; it is not a payment challenge.

The full error bodies are in Errors.

Further reading

On this page