ferrodocs
402 docs · complete guide

Build paid APIs for agents, apps and people.

Ferro is an HTTP 402 gateway and SDK family. Your server answers with a payment challenge, the caller settles in stablecoins on a supported chain, then retries with proof. No accounts, no API keys for buyers, no card fees.

Getting started

Introduction

HTTP has reserved status code 402 Payment Required since 1997. The x402 protocol finally gives it a standard meaning, and Ferro gives you production-ready tooling around it.

With Ferro you can put a price on any HTTP response (an API call, a web page, a dataset row, an MCP tool call or an AI completion) and get paid per request, in seconds, directly to your own wallet.

Who pays?

Anyone who can sign a stablecoin transfer: autonomous AI agents, backend jobs, CLI scripts, browser apps with a connected wallet, or another API. The buyer needs no account with you and no API key. The payment itself is the credential.

What Ferro adds on top of x402

  • Issued nonces and replay protection so a single payment can never unlock two responses.
  • On-chain settlement verification across eight rails, behind one network option.
  • Signed receipts anchored in Merkle roots, so neither side has to trust the other.
  • SDKs for every side: Express, Hono, Fastify, the Vercel AI SDK, and a buyer-side fetch.
  • A hosted facilitator (0.5%), or self-host everything at 0%.
Getting started

Quickstart

Charge $0.001 for an Express endpoint in under five minutes.

i

Prerequisites: Node.js 18+, an existing Express app, and a wallet address that will receive payments. You do not need a private key on the server, only the public address.

Install the SDK

npm install @ferro/express

Set your receiving wallet

.env env
FERRO_WALLET=0xYourReceivingAddress
FERRO_NETWORK=base-mainnet

Gate a route

server.ts ts
import express from "express";
import { paywall } from "@ferro/express";

const app = express();

// Everything under /api/premium now costs $0.001 per request
app.use("/api/premium", paywall({
  amount: 0.001,                       // USDC
  recipient: process.env.FERRO_WALLET,
  network: process.env.FERRO_NETWORK, // "base-mainnet"
}));

app.get("/api/premium/quote", (req, res) => {
  res.json({ quote: "Paid content", receipt: req.ferro.receipt.id });
});

app.listen(3000);

Test it

An unpaid request now returns a 402 challenge:

terminal sh
curl -i http://localhost:3000/api/premium/quote
response http
HTTP/1.1 402 Payment Required
Content-Type: application/json
X-Pay-Version: 2

{
  "x402Version": 2,
  "amount": "0.001",
  "asset": "USDC",
  "network": "base-mainnet",
  "recipient": "0xYourReceivingAddress",
  "nonce": "n_8f3a1c9e0b7d42a6",
  "expiresAt": "2026-11-23T10:15:00Z"
}

Pay it automatically with @ferro/fetch, or follow the manual client guide.

✓

That's it. Your handler only runs after Ferro has verified the on-chain payment. Nothing else in your app changes.

Getting started

Installation

Install only the packages for the side of the payment you are building. All packages are ESM + CJS, fully typed, and have zero runtime dependencies besides @ferro/core.

PackageUse it forRuntimeVersion
@ferro/expressPaywall middleware for Express / ConnectNode 18+1.1.0
@ferro/honoEdge paywall for HonoWorkers, Bun, Deno, Node1.1.0
@ferro/ai-sdkGate Vercel AI SDK routesNode, Edge1.0.0
@ferro/fetchBuyer SDK: pays and retriesNode, Bun, browser1.0.0
@ferro/coreShared verifier, networks, wire formatAny1.1.0
npm install @ferro/express @ferro/fetch

Environment variables

VariableDescriptionDefault
FERRO_WALLETAddress that receives payments. Used when recipient is omitted.—
FERRO_NETWORKDefault rail slug.base-mainnet
FERRO_API_KEYConsole key for hosted features (receipts, webhooks, analytics).—
FERRO_RPC_URLYour own RPC endpoint when self-hosting verification.Public pool
FERRO_FACILITATORFacilitator base URL. Set to off to self-host.https://api.ferro402.xyz
Getting started

Core concepts

TermMeaning
SellerThe server that owns a paid resource and returns 402 challenges.
BuyerAnything that calls the resource and pays: an agent, app, script or another server.
ChallengeThe JSON body of a 402 response describing exactly what to pay, to whom, on which rail.
NonceA one-time identifier issued per challenge. Binds a payment to a single request.
ProofThe transaction hash plus nonce the buyer sends back in headers on retry.
FacilitatorThe service that verifies settlement on-chain. Hosted by Ferro or run by you.
RailA chain + asset pair used to settle, e.g. Base + USDC.
ReceiptA signed record of a verified settlement, later anchored in a Merkle root.
Getting started

The x402 request flow

Every paid request is a short, deterministic loop. Nothing is stored in a session and no account is created.

Buyer / agent Your server Chain + facilitator ① GET /api/premium ② 402 + challenge (nonce) ③ transfer 0.001 USDC → recipient ④ retry + X-Pay-Tx, X-Pay-Nonce ⑤ verify tx valid ✓ ⑥ 200 OK + X-Pay-Receipt
  1. Request. The buyer calls a paid route like any other endpoint.
  2. Challenge. The server replies 402 with amount, asset, network, recipient and a fresh nonce (valid for 5 minutes by default).
  3. Settle. The buyer sends the exact transfer on-chain. Including the nonce in the transfer memo is optional but recommended.
  4. Retry with proof. The buyer repeats the original request with X-Pay-Tx and X-Pay-Nonce headers.
  5. Verify. The facilitator confirms amount, asset, recipient and finality, checks the nonce is unused and the hash has never been redeemed.
  6. Unlock. Your handler runs. The response carries X-Pay-Receipt so the buyer can prove what it paid for.

Server SDKs

Express

paywall() is standard Express middleware. Mount it on a path, a router, or a single route.

routes.ts ts
import { paywall } from "@ferro/express";

// 1. Whole path prefix
app.use("/api/v1", paywall({ amount: 0.002 }));

// 2. A single route
app.get("/report/:id", paywall({ amount: 0.05 }), sendReport);

// 3. Dynamic pricing — compute the amount per request
app.post("/render", paywall({
  amount: (req) => req.body.pages * 0.001,
  description: (req) => `Render ${req.body.pages} pages`,
}), render);

Request context

After a successful payment the middleware attaches req.ferro:

types.d.ts ts
interface FerroContext {
  paid: true;
  amount: string;        // "0.001"
  asset: "USDC" | "ETH";
  network: string;       // "base-mainnet"
  payer: string;         // buyer address
  txHash: string;
  receipt: { id: string; url: string; signature: string };
}

Multiple workers

Nonces and redeemed hashes are kept in memory by default. When you run more than one process, pass a shared store so a payment cannot be redeemed on two workers:

store.ts ts
import { paywall, redisStore } from "@ferro/express";
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

app.use("/api", paywall({ amount: 0.001, store: redisStore(redis) }));
!

Production checklist: use a shared store (Redis or Postgres), pin network explicitly, and never accept the price from the client.

Server SDKs

Hono & edge runtimes

@ferro/hono uses only Web standard APIs, so it runs on Cloudflare Workers, Bun, Deno, Vercel Edge and Node.

worker.ts ts
import { Hono } from "hono";
import { x402, kvStore } from "@ferro/hono";

type Env = { WALLET: string; NONCES: KVNamespace };
const app = new Hono<{ Bindings: Env }>();

app.use("/v1/*", (c, next) =>
  x402({
    amount: 0.001,
    recipient: c.env.WALLET,
    network: "base-mainnet",
    store: kvStore(c.env.NONCES),
  })(c, next)
);

app.get("/v1/weather/:city", (c) =>
  c.json({ city: c.req.param("city"), tempC: 21, paidBy: c.get("ferro").payer })
);

export default app;
i

On Workers, use kvStore or durableObjectStore. In-memory stores are reset between isolates.

Server SDKs

Fastify & Next.js

Any framework can use the framework-agnostic verifier in @ferro/core.

import { createPaywall } from "@ferro/core";

const gate = createPaywall({ amount: 0.001 });

fastify.addHook("preHandler", async (req, reply) => {
  const result = await gate.check({ url: req.url, headers: req.headers });
  if (!result.paid) return reply.code(402).headers(result.headers).send(result.challenge);
  req.ferro = result.context;
});
Server SDKs

AI SDK middleware NEW

Charge per generation on any Vercel AI SDK route. Payment is verified before a single token is streamed, so unpaid calls never cost you inference.

// app/api/chat/route.ts
import { createX402Gate } from "@ferro/ai-sdk";
import { streamText } from "ai";

const gate = createX402Gate({
  amount: ({ body }) => (body.model === "large" ? 0.01 : 0.002),
  recipient: process.env.FERRO_WALLET,
});

export const POST = gate(async (req) => {
  const { messages } = await req.json();
  return streamText({ model, messages }).toDataStreamResponse();
});
OptionTypeDescription
amountnumber | (ctx) => numberPrice per generation. Can depend on the model or prompt size.
maxAmountPerCallnumberBuyer-side spend cap for wrapWith402.
onPaid(ctx) => voidHook fired after verification, before streaming starts.

Buyers & agents

@ferro/fetch: the buyer SDK

A drop-in replacement for fetch. When a response is 402, it reads the challenge, checks your spending policy, pays, retries, and then hands you the final response.

agent.ts ts
import { createBuyer } from "@ferro/fetch";
import { privateKeyToAccount } from "viem/accounts";

const buyer = createBuyer({
  account: privateKeyToAccount(process.env.AGENT_KEY),
  networks: ["base-mainnet", "arbitrum-mainnet"],
  policy: {
    maxPerRequest: 0.01,          // USDC
    maxPerDay: 5,
    allowHosts: ["api.example.com", "*.trusted.dev"],
  },
});

const res = await buyer.fetch("https://api.example.com/premium/quote");
console.log(res.status);                       // 200
console.log(res.headers.get("x-pay-receipt")); // signed receipt id
!

Keep keys out of source control. Load agent keys from a secret manager and always set maxPerRequest and maxPerDay. A buyer without a policy will refuse to pay.

Events

events.ts ts
buyer.on("challenge", (c) => log("price", c.amount, c.network));
buyer.on("paid", (p) => log("tx", p.txHash));
buyer.on("refused", (r) => log("blocked by policy:", r.reason));
Buyers & agents

Manual client

No SDK required. Any language that can make HTTP calls and send a token transfer can pay a Ferro endpoint.

const url = "https://api.example.com/premium/quote";

// 1. Ask
let res = await fetch(url);
if (res.status !== 402) return res;
const challenge = await res.json();

// 2. Pay (any wallet library)
const txHash = await wallet.transferToken({
  token: challenge.asset,
  to: challenge.recipient,
  amount: challenge.amount,
  network: challenge.network,
  memo: challenge.nonce,
});

// 3. Retry with proof
res = await fetch(url, {
  headers: { "X-Pay-Tx": txHash, "X-Pay-Nonce": challenge.nonce },
});
✓

If the retry returns 402 with error: "tx_pending", wait ~1 second and retry with the same headers. The nonce stays valid until expiresAt.


Guides

Recipes

Copy-paste patterns for the most common things people build with Ferro.

Paywall an LLM proxy

Resell model access with a margin. The price is computed from the prompt before the call, so you never pay upstream for an unpaid request.

llm-proxy.ts ts
import { Hono } from "hono";
import { paywall } from "@ferro/hono";

const app = new Hono();

app.post("/chat", paywall({
  price: async (c) => {
    const { messages } = await c.req.json();
    const chars = messages.reduce((n, m) => n + m.content.length, 0);
    return Math.max(0.002, chars / 4 / 1000 * 0.003);
  },
}), async (c) => {
  const body = await c.req.json();
  return fetch(UPSTREAM_URL, { method: "POST", body: JSON.stringify(body) });
});

Sell file downloads per MB

downloads.ts ts
app.get("/files/:id", paywall({
  price: async (req) => {
    const { sizeBytes } = await files.stat(req.params.id);
    return +(sizeBytes / 1_048_576 * 0.0005).toFixed(6);   // $0.0005 per MB
  },
  description: (req) => `Download ${req.params.id}`,
}), (req, res) => files.stream(req.params.id).pipe(res));

Give an agent a daily budget

Spending policies live in the buyer SDK, so an agent can never overspend even if a server quotes a high price.

agent.ts ts
import { createFetch } from "@ferro/fetch";

const pay = createFetch({
  wallet,
  policy: {
    maxPerRequest: 0.05,      // USDC
    maxPerDay: 5,
    allowHosts: ["*.ferro402.xyz", "api.yoursite.com"],
    networks: ["base-mainnet"],
  },
  onPayment: (p) => log.info("paid", p.amount, p.url),
  onBlocked: (r) => log.warn("blocked by policy", r.reason),
});

const res = await pay("https://api.yoursite.com/v1/quote?pair=EURUSD");

Free for humans, paid for bots

Use skip to bypass the paywall for signed-in users or low-volume traffic.

server.ts ts
paywall({
  price: 0.001,
  skip: (req) => Boolean(req.session?.user),   // logged-in humans pay nothing
});
Guides

Migrating from API keys

You don't have to switch everyone at once. Run x402 next to your existing key-based billing and move traffic over gradually.

Add the paywall behind your key check

Requests with a valid API key keep working; requests without one get a 402 instead of a 401.

server.ts ts
app.use("/v1", paywall({
  price: 0.001,
  skip: (req) => apiKeys.isValid(req.headers["x-api-key"]),
}));

Tell existing customers

Agents and scripts that pay per call no longer need an account, a card or a monthly invoice. Link them to the @ferro/fetch guide.

Compare revenue

The console shows x402 revenue next to your other income per route. When the numbers make sense, start retiring old keys.

API keys + invoicesx402 with Ferro
Sign-up neededYesNo
Smallest practical charge~$5 / month$0.0001 / request
ChargebacksPossibleNone. On-chain settlement is final
Time to get paid30–60 daysSeconds
Works for AI agentsOnly with a human-issued keyNatively
Platform

Networks & rails

Switching chains is one option, not a different integration. Every SDK accepts the same slugs.

SlugChainVM · Chain IDAssetsTypical finality
base-mainnetBase DEFAULTEVM · 8453USDC, ETH~2 s
robinhood-mainnetRobinhood Chain $FERROEVM · L2USDC~1 s
ethereum-mainnetEthereumEVM · 1USDC, ETH~12 s
arbitrum-mainnetArbitrum OneEVM · 42161USDC~1 s
optimism-mainnetOptimismEVM · 10USDC~2 s
polygon-mainnetPolygonEVM · 137USDC~2 s
solana-mainnetSolanaSVMUSDC~0.4 s
sui-mainnetSuiMoveUSDC~0.5 s

Accept several rails at once

Pass an array and the challenge lists every option. Buyers pick the rail they hold funds on.

server.ts ts
paywall({
  amount: 0.001,
  accepts: [
    { network: "base-mainnet",   recipient: EVM_WALLET },
    { network: "solana-mainnet", recipient: SOLANA_WALLET },
  ],
});
Platform

Instant vs batched settlement

ModeSettlementFeeBest for
instantPer request, < 2 s0.5%Real-time agents, interactive apps
batchedAggregated every 15 min or $100%High-volume scraping, data pipelines

In batched mode the buyer pre-funds a small allowance and signs per-request vouchers; Ferro settles the net amount on-chain in one transaction.

server.ts ts
paywall({ amount: 0.0002, mode: "batched", recipient: WALLET });
i

Only instant payments earn per-transaction cashback. Cashback is paid in USDC to the receiving wallet and decays as total network volume grows.

Platform

Revenue splits

Distribute every payment between several wallets atomically, in basis points (1 bp = 0.01%). Shares must add up to 10,000.

server.ts ts
paywall({
  amount: 0.01,
  splits: [
    { recipient: "0xFounderA…", bps: 4500 },
    { recipient: "0xFounderB…", bps: 4500 },
    { recipient: "0xTreasury…", bps: 1000 },
  ],
});
Platform

Dynamic pricing

A price does not have to be a constant. Pass a function and Ferro calls it for every request before issuing the challenge. The returned amount is signed into the nonce, so the buyer pays exactly what was quoted.

server.ts ts
import { paywall } from "@ferro/express";

app.post("/v1/summarize", paywall({
  // Charge per 1k input tokens, minimum $0.001
  price: (req) => {
    const tokens = Math.ceil(req.body.text.length / 4);
    return Math.max(0.001, (tokens / 1000) * 0.0004);
  },
  description: (req) => `Summarize ${req.body.text.length} chars`,
}), summarizeHandler);

Tiers and discounts

Because the payer address is known after the first payment, you can reward repeat buyers. Read it from req.ferro.payer on a previous call and store it in your own database.

tiers.ts ts
const TIERS = [
  { minCalls: 0,      price: 0.002 },
  { minCalls: 1_000,  price: 0.0015 },
  { minCalls: 10_000, price: 0.001 },
];

paywall({
  price: async (req) => {
    const calls = await usage.count(req.headers["x-payer-hint"]);
    return [...TIERS].reverse().find(t => calls >= t.minCalls).price;
  },
});
PatternGood forMode
Flat price per callData lookups, quotes, simple APIsInstant
Per unit (tokens, MB, rows)LLM proxies, file downloads, exportsInstant or batched
Volume tiersHigh-frequency agentsBatched
Time-boxed passDashboards, streaming feedsInstant (one payment unlocks N minutes)
✓

Keep quoted prices stable for the lifetime of a challenge (default 5 minutes). If your price changes mid-flight, the old nonce stays valid at the old amount.

Time-boxed passes

Set pass to let one payment unlock a route for a period. Ferro returns a short-lived signed token in X-Ferro-Pass; clients send it back instead of paying again.

server.ts ts
app.get("/dashboard/live", paywall({ price: 0.05, pass: "15m" }), liveHandler);
Platform

MCP server

Ferro exposes a Model Context Protocol server so AI clients can browse paid endpoints, create invoices and check payer reputation.

mcp.json json
{
  "mcpServers": {
    "ferro": {
      "url": "https://api.ferro402.xyz/mcp",
      "headers": { "Authorization": "Bearer ${FERRO_API_KEY}" }
    }
  }
}
ToolDescription
list_endpointsSearch the public marketplace by keyword, price or network.
get_endpointPrice, schema, latency and uptime for a single endpoint.
create_invoiceCreate a one-off payment request with a shareable link.
check_reputationPayment history score for a payer or seller address.
get_receiptFetch and verify a signed receipt.
server.ts ts
import { priced } from "@ferro/core/mcp";

server.tool("search_filings", schema, priced(0.002, async (args) => {
  return { content: [{ type: "text", text: await search(args.query) }] };
}));
Platform

Marketplace & catalog

Any endpoint you publish from the console can be listed in the public Ferro catalog. Agents use the catalog to discover paid tools by capability, price and rail, then call them with @ferro/fetch without any sign-up.

Describe the endpoint

Give it a name, a one-line description, tags and an example request. These fields are what agents search on.

Publish

Open Console → Endpoints → Publish, or call the API. Listing is free; only settled payments carry the facilitator fee.

Get discovered

Your endpoint appears in GET /v1/catalog/endpoints and in the MCP server's ferro_search tool within a minute.

publish.sh sh
curl -X POST https://api.ferro402.xyz/v1/endpoints \
  -H "Authorization: Bearer $FERRO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://api.yoursite.com/v1/quote",
    "method": "GET",
    "name": "Realtime FX quote",
    "description": "Mid-market FX rate for any ISO currency pair",
    "tags": ["finance", "fx", "realtime"],
    "price": "0.001",
    "networks": ["base-mainnet", "solana-mainnet"]
  }'

The catalog is public and needs no key. Filter by tag, maximum price or network.

curl "https://api.ferro402.xyz/v1/catalog/endpoints?tag=fx&maxPrice=0.01&network=base-mainnet"
i

Listing stats (calls30d, successRate) come from settled receipts, so they cannot be inflated without real payments.

Platform

Webhooks & live feed

Receive a signed POST for every settlement, or subscribe to the public Server-Sent Events stream.

webhook.ts ts
import { verifyWebhook } from "@ferro/core";

app.post("/hooks/ferro", express.raw({ type: "application/json" }), (req, res) => {
  const event = verifyWebhook(req.body, req.headers["ferro-signature"], process.env.WEBHOOK_SECRET);

  if (event.type === "payment.settled") {
    console.log(event.data.amount, event.data.payer, event.data.txHash);
  }
  res.sendStatus(200);
});
EventWhen
payment.settledA payment was verified and the handler unlocked.
payment.failedProof was rejected (wrong amount, expired nonce, reused hash).
batch.anchoredA Merkle root containing your receipts was committed on-chain.
cashback.paidA cashback payout was sent to your wallet.
live feed sh
curl -N https://api.ferro402.xyz/v1/feed
Platform

Console & API keys

The console is readable without signing in. Connect a wallet only for private tools: publishing endpoints, receipts, analytics and API keys.

  • Dashboard: revenue, request volume, top endpoints and network health.
  • Transactions: every payment with filters and CSV/JSON export.
  • Marketplace: list endpoints publicly so agents can discover them.
  • API keys: scoped keys for CI, webhooks and the MCP server.
ScopeAllows
endpoints:readList your endpoints and pricing.
endpoints:writeCreate, update and unpublish endpoints.
receipts:readRead receipts and settlement history.
webhooks:manageCreate and rotate webhook endpoints.
!

Keys start with frr_live_ or frr_test_. A leaked key can read your data but can never move funds, because Ferro is non-custodial.

Platform

Custom domains

Serve hosted endpoints from your own domain. Add a CNAME, then verify it in the console.

DNS txt
api.yoursite.com.   CNAME   tunnel.ferro402.xyz.

TLS certificates are issued automatically within a few minutes of verification.


Security

Security model

Ferro is designed so that a buyer can never get a response without paying, and a seller can never claim a payment that did not happen.

Issued nonces

Every challenge carries a server-issued nonce bound to the method, path, amount and network. Proofs with an unknown, expired or mismatched nonce are rejected with invalid_nonce.

Replay-safe transaction hashes

Once a transaction hash unlocks a response it is recorded as redeemed. Any second use returns tx_already_used, across all workers when a shared store is configured.

Settlement verification

The facilitator reads the transfer from the chain and checks token contract, recipient, exact amount, confirmations and that the block is newer than the challenge.

Non-custodial

Funds move directly from buyer to seller on-chain. Ferro never holds keys or balances, and the hosted facilitator only reads chain data.

Stateless option

If you cannot run a shared store (for example on a single edge function), set stateless: true. Nonces become signed, self-contained tokens and redeemed hashes are checked against the facilitator instead of your own database.

server.ts ts
paywall({
  price: 0.001,
  stateless: true,                 // no Redis / KV needed
  secret: process.env.FERRO_SECRET // signs nonces, rotate any time
});
!

Stateless mode requires the hosted facilitator for replay protection. When self-hosting, always configure a shared store.

ThreatMitigation
Replay of a valid proofRedeemed-hash store + single-use nonce
UnderpaymentExact amount match against the signed challenge
Paying the wrong addressRecipient is part of the nonce binding
Chain re-orgPer-network confirmation threshold
Facilitator dishonestySigned receipts + public Merkle anchors
Security

Receipts & proofs

Each verified payment produces a receipt signed by the facilitator. Receipts are batched and their Merkle root is committed on-chain, so history cannot be rewritten.

verify.ts ts
import { verifyReceipt } from "@ferro/core";

const ok = await verifyReceipt(receipt, {
  checkSignature: true,
  checkAnchor: true, // recompute the Merkle path against the on-chain root
});
Security

Self-hosting

Run verification yourself and pay no facilitator fee. You bring an RPC endpoint and a shared store; everything else is in the open-source SDK (MIT).

server.ts ts
paywall({
  amount: 0.001,
  recipient: WALLET,
  network: "base-mainnet",
  facilitator: false,                 // verify locally
  rpcUrl: process.env.FERRO_RPC_URL,
  confirmations: 2,
  store: redisStore(redis),
});
i

Self-hosted mode does not issue Ferro-signed receipts or cashback. You can still publish endpoints to the marketplace.

Security

Testing & testnets

Use a frr_test_ key and a testnet slug during development. No real funds move.

Testnet slugMirrors
base-sepoliaBase
ethereum-sepoliaEthereum
arbitrum-sepoliaArbitrum One
solana-devnetSolana

Unit tests without a chain

paywall.test.ts ts
import { mockFacilitator } from "@ferro/core/testing";

const facilitator = mockFacilitator({ autoApprove: true });
app.use("/api", paywall({ amount: 0.001, facilitator }));

const res = await request(app).get("/api/x").set(facilitator.proofHeaders());
expect(res.status).toBe(200);

Reference

Configuration

Options accepted by paywall(), x402() and createPaywall().

OptionTypeDefaultDescription
amountrequirednumber | fn—Price per request in the settlement asset.
recipientstringFERRO_WALLETAddress that receives funds.
networkstringbase-mainnetRail slug. See networks.
asset"USDC" | "ETH"USDCSettlement asset.
acceptsRail[]—Offer multiple rails in one challenge.
mode"instant" | "batched"instantSettlement mode.
descriptionstring | fn—Human-readable memo shown to buyers.
nonceTtlnumber (s)300How long a challenge stays valid.
confirmationsnumberper networkBlocks required before unlocking.
storeStorememoryNonce and redeemed-hash storage.
splitsSplit[]—Revenue split in basis points.
facilitatorstring | falsehostedFacilitator URL, or false to self-host.
onPaid(ctx) => void—Called after successful verification.
Reference

HTTP headers

HeaderDirectionDescription
X-Pay-VersionResponseWire format version. Currently 2.
X-Pay-TxRequestTransaction hash (or signature on SVM/Move) proving payment.
X-Pay-NonceRequestNonce copied from the challenge.
X-Pay-NetworkRequestRail used, when the challenge offered several.
X-Pay-ReceiptResponseReceipt id for the unlocked response.
Ferro-SignatureWebhookHMAC-SHA256 signature of the webhook body.
Reference

402 response schema

challenge.json json
{
  "x402Version": 2,
  "amount": "0.001",
  "asset": "USDC",
  "network": "base-mainnet",
  "recipient": "0x4b1e…c0de",
  "nonce": "n_8f3a1c9e0b7d42a6",
  "expiresAt": "2026-11-23T10:15:00Z",
  "description": "Premium quote API",
  "accepts": [
    { "network": "base-mainnet", "asset": "USDC", "recipient": "0x4b1e…c0de" },
    { "network": "solana-mainnet", "asset": "USDC", "recipient": "7xKX…9fQa" }
  ],
  "facilitator": "https://api.ferro402.xyz"
}
Reference

Facilitator REST API

Base URL https://api.ferro402.xyz. Authenticate with Authorization: Bearer frr_live_…. All responses are JSON.

POST/v1/verify

Verify a proof against a challenge. Used internally by the SDKs; call it directly from other languages.

curl -X POST https://api.ferro402.xyz/v1/verify \
  -H "Authorization: Bearer $FERRO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "nonce": "n_8f3a1c9e0b7d42a6", "txHash": "0x9c2e…41ab", "network": "base-mainnet" }'
POST/v1/challenges

Issue a challenge and nonce for a resource (when you are not using an SDK).

GET/v1/receipts/{id}

Fetch a signed receipt and its Merkle proof.

GET/v1/catalog

List supported rails, assets and confirmation thresholds.

GET/v1/feed

Server-Sent Events stream of public settlements.

DELETE/v1/endpoints/{id}

Unpublish a marketplace endpoint. Requires endpoints:write.

Rate limits

600 requests per minute per key for /v1/verify, 120 for everything else. Limits are returned in RateLimit-* headers.

Reference

Error codes

Errors are returned in the 402 body (for proof problems) or with standard HTTP codes (for API problems).

CodeHTTPMeaning & fix
payment_required402No proof sent. Pay the challenge and retry.
invalid_nonce402Nonce unknown or for another route. Request a fresh challenge.
nonce_expired402Challenge older than nonceTtl. Request a fresh challenge.
tx_pending402Transaction not final yet. Retry with the same headers in ~1 s.
tx_not_found402Hash not found on the selected network. Check X-Pay-Network.
amount_mismatch402Paid amount differs from the challenge. Send the exact amount.
wrong_recipient402Transfer went to another address.
tx_already_used402This hash already unlocked a response. Pay again.
unauthorized401Missing or invalid API key.
rate_limited429Too many requests. Respect Retry-After.
Reference

Troubleshooting

The most common problems and how to fix them. Turn on debug: true in any SDK to log every step of the 402 loop.

Every request returns 402, even after paying

The retry is probably missing the X-Payment header, or a proxy strips it. Check that your CDN or load balancer forwards custom headers, and that the header contains the transaction hash and the nonce.

invalid_nonce after a server restart

Nonces are kept in memory by default. Configure a shared store (Redis, Postgres or KV) or switch to stateless mode so nonces survive restarts and work across multiple instances.

amount_mismatch on Solana

USDC on Solana has 6 decimals and amounts are compared in base units. Make sure your client converts 0.001 to 1000, not 1000000. @ferro/fetch handles this for you.

insufficient_confirmations

The transfer was found but not yet final. The SDK retries automatically for up to 30 seconds; increase confirmTimeout on slower networks or use batched mode.

Webhooks are not arriving

Your endpoint must answer with a 2xx within 10 seconds. Failed deliveries retry with backoff for 24 hours. Check Console → Webhooks → Deliveries for response codes, and verify the signature with the secret for that exact endpoint.

CORS errors when paying from a browser

Expose the payment headers: Access-Control-Expose-Headers: X-Payment-Response, X-Ferro-Receipt and allow X-Payment in Access-Control-Allow-Headers. The Express and Hono adapters do this when cors: true.

debug output txt
[ferro] GET /premium → 402 challenge n_8f3a… 0.001 USDC base-mainnet
[ferro] GET /premium ← X-Payment tx=0x9c2e…41ab nonce=n_8f3a…
[ferro] verify ok payer=0x71c9…a3f2 confirmations=1/1 (412ms)
[ferro] GET /premium → 200 receipt=rcpt_3Kq9…
Reference

Glossary

TermMeaning
x402An open protocol that uses HTTP status 402 Payment Required to ask for, and prove, a payment inside a normal HTTP request.
ChallengeThe 402 response body that says how much to pay, in which asset, on which network and to whom.
NonceA single-use value inside the challenge that binds the payment to one specific request.
ProofThe X-Payment header a client sends on retry: transaction hash plus nonce.
FacilitatorThe service that verifies proofs on-chain and signs receipts. Ferro hosts one; you can self-host your own.
RailA network and asset pair you accept, for example USDC on Base.
ReceiptA signed record of a settled payment, anchored on-chain in a Merkle batch.
Instant / batchedSettle each request on-chain right away, or aggregate many small payments and settle them together.
Spending policyBuyer-side limits (per request, per day, allowed hosts) enforced by @ferro/fetch.
Reference

FAQ

Do buyers need an account or API key?

No. The on-chain payment is the credential. Buyers only need a wallet with funds on one of the rails you accept.

What is the smallest price I can charge?

$0.0001 per request. Network fees on the default rail are around $0.0001, so prices from $0.001 upward are practical in instant mode; use batched mode for anything smaller.

Can I offer refunds?

Payments are final on-chain. You can send a refund transfer to the payer address from the receipt, or issue credit in your own app.

Does Ferro ever hold my funds?

Never. Transfers go directly from the buyer's wallet to yours. The facilitator only reads chain data and signs receipts.

Can browsers and humans pay too?

Yes. Any frontend with a connected wallet can use @ferro/fetch in the browser. You can also serve free content to humans and charge only automated clients.

What happens if the facilitator is down?

Configure facilitator: false with your own RPC as a fallback. The SDK switches to local verification automatically when fallbackToLocal: true.

Reference

Changelog

v1.1.02026-11-20Robinhood Chain rail
  • robinhood-mainnet supported in @ferro/core, @ferro/express and @ferro/hono.
  • No config changes needed for existing routes.
v1.0.02026-11-10AI SDK gate & stable buyer SDK
  • @ferro/ai-sdk: createX402Gate() and wrapWith402().
  • @ferro/fetch 1.0 with spending policies and events.
v0.5.02026-10-02Seven rails
  • Added Optimism, Solana and Sui.
  • accepts option for multi-rail challenges.
v0.4.02026-08-21Revenue splits & webhooks
  • Atomic basis-point splits per settlement.
  • Signed webhooks with four event types.
v0.3.02026-07-09Merkle anchoring
  • Receipts are batched and anchored on-chain.
  • verifyReceipt() in @ferro/core.
v0.2.02026-05-30Hono adapter & shared stores
  • Edge-compatible @ferro/hono.
  • Redis, Postgres and KV stores.