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.
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
networkoption. - 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%.
Quickstart
Charge $0.001 for an Express endpoint in under five minutes.
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
pnpm add @ferro/express
yarn add @ferro/express
bun add @ferro/express
Set your receiving wallet
FERRO_WALLET=0xYourReceivingAddress FERRO_NETWORK=base-mainnet
Gate a route
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:
curl -i http://localhost:3000/api/premium/quote
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.
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.
| Package | Use it for | Runtime | Version |
|---|---|---|---|
@ferro/express | Paywall middleware for Express / Connect | Node 18+ | 1.1.0 |
@ferro/hono | Edge paywall for Hono | Workers, Bun, Deno, Node | 1.1.0 |
@ferro/ai-sdk | Gate Vercel AI SDK routes | Node, Edge | 1.0.0 |
@ferro/fetch | Buyer SDK: pays and retries | Node, Bun, browser | 1.0.0 |
@ferro/core | Shared verifier, networks, wire format | Any | 1.1.0 |
npm install @ferro/express @ferro/fetch
pnpm add @ferro/express @ferro/fetch
yarn add @ferro/express @ferro/fetch
bun add @ferro/express @ferro/fetch
Environment variables
| Variable | Description | Default |
|---|---|---|
FERRO_WALLET | Address that receives payments. Used when recipient is omitted. | — |
FERRO_NETWORK | Default rail slug. | base-mainnet |
FERRO_API_KEY | Console key for hosted features (receipts, webhooks, analytics). | — |
FERRO_RPC_URL | Your own RPC endpoint when self-hosting verification. | Public pool |
FERRO_FACILITATOR | Facilitator base URL. Set to off to self-host. | https://api.ferro402.xyz |
Core concepts
| Term | Meaning |
|---|---|
Seller | The server that owns a paid resource and returns 402 challenges. |
Buyer | Anything that calls the resource and pays: an agent, app, script or another server. |
Challenge | The JSON body of a 402 response describing exactly what to pay, to whom, on which rail. |
Nonce | A one-time identifier issued per challenge. Binds a payment to a single request. |
Proof | The transaction hash plus nonce the buyer sends back in headers on retry. |
Facilitator | The service that verifies settlement on-chain. Hosted by Ferro or run by you. |
Rail | A chain + asset pair used to settle, e.g. Base + USDC. |
Receipt | A signed record of a verified settlement, later anchored in a Merkle root. |
The x402 request flow
Every paid request is a short, deterministic loop. Nothing is stored in a session and no account is created.
- Request. The buyer calls a paid route like any other endpoint.
- Challenge. The server replies
402with amount, asset, network, recipient and a fresh nonce (valid for 5 minutes by default). - Settle. The buyer sends the exact transfer on-chain. Including the nonce in the transfer memo is optional but recommended.
- Retry with proof. The buyer repeats the original request with
X-Pay-TxandX-Pay-Nonceheaders. - Verify. The facilitator confirms amount, asset, recipient and finality, checks the nonce is unused and the hash has never been redeemed.
- Unlock. Your handler runs. The response carries
X-Pay-Receiptso the buyer can prove what it paid for.
Express
paywall() is standard Express middleware. Mount it on a path, a router, or a single route.
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:
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:
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.
Hono & edge runtimes
@ferro/hono uses only Web standard APIs, so it runs on Cloudflare Workers, Bun, Deno, Vercel Edge and Node.
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;On Workers, use kvStore or durableObjectStore. In-memory stores are reset between isolates.
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;
});// app/api/premium/route.ts
import { createPaywall } from "@ferro/core";
const gate = createPaywall({ amount: 0.001 });
export async function GET(req: Request) {
const result = await gate.check(req);
if (!result.paid) return result.response; // ready-made 402 Response
return Response.json({ data: "premium", receipt: result.context.receipt.id });
}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();
});import { wrapWith402 } from "@ferro/ai-sdk";
import { generateText } from "ai";
// Wrap a model so the agent pays paid endpoints automatically
const paidModel = wrapWith402(model, { wallet, maxAmountPerCall: 0.02 });
const { text } = await generateText({
model: paidModel,
prompt: "Summarise today's market report",
});| Option | Type | Description |
|---|---|---|
amount | number | (ctx) => number | Price per generation. Can depend on the model or prompt size. |
maxAmountPerCall | number | Buyer-side spend cap for wrapWith402. |
onPaid | (ctx) => void | Hook fired after verification, before streaming starts. |
@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.
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 idKeep 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
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));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 },
});import requests
url = "https://api.example.com/premium/quote"
res = requests.get(url)
if res.status_code == 402:
c = res.json()
tx_hash = wallet.transfer_token(
token=c["asset"], to=c["recipient"],
amount=c["amount"], network=c["network"], memo=c["nonce"],
)
res = requests.get(url, headers={"X-Pay-Tx": tx_hash, "X-Pay-Nonce": c["nonce"]})
print(res.json())# 1. Get the challenge curl -s https://api.example.com/premium/quote | jq # 2. Pay with your wallet, then retry with the proof curl https://api.example.com/premium/quote \ -H "X-Pay-Tx: 0x9c2e…41ab" \ -H "X-Pay-Nonce: n_8f3a1c9e0b7d42a6"
If the retry returns 402 with error: "tx_pending", wait ~1 second and retry with the same headers. The nonce stays valid until expiresAt.
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.
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
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.
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.
paywall({
price: 0.001,
skip: (req) => Boolean(req.session?.user), // logged-in humans pay nothing
});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.
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 + invoices | x402 with Ferro | |
|---|---|---|
| Sign-up needed | Yes | No |
| Smallest practical charge | ~$5 / month | $0.0001 / request |
| Chargebacks | Possible | None. On-chain settlement is final |
| Time to get paid | 30–60 days | Seconds |
| Works for AI agents | Only with a human-issued key | Natively |
Networks & rails
Switching chains is one option, not a different integration. Every SDK accepts the same slugs.
| Slug | Chain | VM · Chain ID | Assets | Typical finality |
|---|---|---|---|---|
base-mainnet | Base DEFAULT | EVM · 8453 | USDC, ETH | ~2 s |
robinhood-mainnet | Robinhood Chain $FERRO | EVM · L2 | USDC | ~1 s |
ethereum-mainnet | Ethereum | EVM · 1 | USDC, ETH | ~12 s |
arbitrum-mainnet | Arbitrum One | EVM · 42161 | USDC | ~1 s |
optimism-mainnet | Optimism | EVM · 10 | USDC | ~2 s |
polygon-mainnet | Polygon | EVM · 137 | USDC | ~2 s |
solana-mainnet | Solana | SVM | USDC | ~0.4 s |
sui-mainnet | Sui | Move | USDC | ~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.
paywall({
amount: 0.001,
accepts: [
{ network: "base-mainnet", recipient: EVM_WALLET },
{ network: "solana-mainnet", recipient: SOLANA_WALLET },
],
});Instant vs batched settlement
| Mode | Settlement | Fee | Best for |
|---|---|---|---|
instant | Per request, < 2 s | 0.5% | Real-time agents, interactive apps |
batched | Aggregated every 15 min or $10 | 0% | 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.
paywall({ amount: 0.0002, mode: "batched", recipient: WALLET });Only instant payments earn per-transaction cashback. Cashback is paid in USDC to the receiving wallet and decays as total network volume grows.
Revenue splits
Distribute every payment between several wallets atomically, in basis points (1 bp = 0.01%). Shares must add up to 10,000.
paywall({
amount: 0.01,
splits: [
{ recipient: "0xFounderA…", bps: 4500 },
{ recipient: "0xFounderB…", bps: 4500 },
{ recipient: "0xTreasury…", bps: 1000 },
],
});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.
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.
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;
},
});| Pattern | Good for | Mode |
|---|---|---|
| Flat price per call | Data lookups, quotes, simple APIs | Instant |
| Per unit (tokens, MB, rows) | LLM proxies, file downloads, exports | Instant or batched |
| Volume tiers | High-frequency agents | Batched |
| Time-boxed pass | Dashboards, streaming feeds | Instant (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.
app.get("/dashboard/live", paywall({ price: 0.05, pass: "15m" }), liveHandler);MCP server
Ferro exposes a Model Context Protocol server so AI clients can browse paid endpoints, create invoices and check payer reputation.
{
"mcpServers": {
"ferro": {
"url": "https://api.ferro402.xyz/mcp",
"headers": { "Authorization": "Bearer ${FERRO_API_KEY}" }
}
}
}| Tool | Description |
|---|---|
list_endpoints | Search the public marketplace by keyword, price or network. |
get_endpoint | Price, schema, latency and uptime for a single endpoint. |
create_invoice | Create a one-off payment request with a shareable link. |
check_reputation | Payment history score for a payer or seller address. |
get_receipt | Fetch and verify a signed receipt. |
Charging for your own MCP tools
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) }] };
}));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.
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"]
}'Searching the catalog
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"
{
"data": [
{
"id": "ep_7Hk2…",
"name": "Realtime FX quote",
"url": "https://api.yoursite.com/v1/quote",
"price": "0.001",
"networks": ["base-mainnet", "solana-mainnet"],
"calls30d": 48210,
"successRate": 0.998
}
],
"next": null
}Listing stats (calls30d, successRate) come from settled receipts, so they cannot be inflated without real payments.
Webhooks & live feed
Receive a signed POST for every settlement, or subscribe to the public Server-Sent Events stream.
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);
});| Event | When |
|---|---|
payment.settled | A payment was verified and the handler unlocked. |
payment.failed | Proof was rejected (wrong amount, expired nonce, reused hash). |
batch.anchored | A Merkle root containing your receipts was committed on-chain. |
cashback.paid | A cashback payout was sent to your wallet. |
curl -N https://api.ferro402.xyz/v1/feed
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.
| Scope | Allows |
|---|---|
endpoints:read | List your endpoints and pricing. |
endpoints:write | Create, update and unpublish endpoints. |
receipts:read | Read receipts and settlement history. |
webhooks:manage | Create 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.
Custom domains
Serve hosted endpoints from your own domain. Add a CNAME, then verify it in the console.
api.yoursite.com. CNAME tunnel.ferro402.xyz.
TLS certificates are issued automatically within a few minutes of verification.
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.
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.
| Threat | Mitigation |
|---|---|
| Replay of a valid proof | Redeemed-hash store + single-use nonce |
| Underpayment | Exact amount match against the signed challenge |
| Paying the wrong address | Recipient is part of the nonce binding |
| Chain re-org | Per-network confirmation threshold |
| Facilitator dishonesty | Signed receipts + public Merkle anchors |
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.
import { verifyReceipt } from "@ferro/core";
const ok = await verifyReceipt(receipt, {
checkSignature: true,
checkAnchor: true, // recompute the Merkle path against the on-chain root
});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).
paywall({
amount: 0.001,
recipient: WALLET,
network: "base-mainnet",
facilitator: false, // verify locally
rpcUrl: process.env.FERRO_RPC_URL,
confirmations: 2,
store: redisStore(redis),
});Self-hosted mode does not issue Ferro-signed receipts or cashback. You can still publish endpoints to the marketplace.
Testing & testnets
Use a frr_test_ key and a testnet slug during development. No real funds move.
| Testnet slug | Mirrors |
|---|---|
base-sepolia | Base |
ethereum-sepolia | Ethereum |
arbitrum-sepolia | Arbitrum One |
solana-devnet | Solana |
Unit tests without a chain
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);Configuration
Options accepted by paywall(), x402() and createPaywall().
| Option | Type | Default | Description |
|---|---|---|---|
amountrequired | number | fn | — | Price per request in the settlement asset. |
recipient | string | FERRO_WALLET | Address that receives funds. |
network | string | base-mainnet | Rail slug. See networks. |
asset | "USDC" | "ETH" | USDC | Settlement asset. |
accepts | Rail[] | — | Offer multiple rails in one challenge. |
mode | "instant" | "batched" | instant | Settlement mode. |
description | string | fn | — | Human-readable memo shown to buyers. |
nonceTtl | number (s) | 300 | How long a challenge stays valid. |
confirmations | number | per network | Blocks required before unlocking. |
store | Store | memory | Nonce and redeemed-hash storage. |
splits | Split[] | — | Revenue split in basis points. |
facilitator | string | false | hosted | Facilitator URL, or false to self-host. |
onPaid | (ctx) => void | — | Called after successful verification. |
HTTP headers
| Header | Direction | Description |
|---|---|---|
X-Pay-Version | Response | Wire format version. Currently 2. |
X-Pay-Tx | Request | Transaction hash (or signature on SVM/Move) proving payment. |
X-Pay-Nonce | Request | Nonce copied from the challenge. |
X-Pay-Network | Request | Rail used, when the challenge offered several. |
X-Pay-Receipt | Response | Receipt id for the unlocked response. |
Ferro-Signature | Webhook | HMAC-SHA256 signature of the webhook body. |
402 response schema
{
"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"
}Facilitator REST API
Base URL https://api.ferro402.xyz. Authenticate with Authorization: Bearer frr_live_…. All responses are JSON.
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" }'{
"valid": true,
"payer": "0x71c9…a3f2",
"amount": "0.001",
"receipt": { "id": "rcpt_3Kq9…", "url": "https://ferro402.xyz/r/rcpt_3Kq9…" }
}Issue a challenge and nonce for a resource (when you are not using an SDK).
Fetch a signed receipt and its Merkle proof.
List supported rails, assets and confirmation thresholds.
Server-Sent Events stream of public settlements.
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.
Error codes
Errors are returned in the 402 body (for proof problems) or with standard HTTP codes (for API problems).
| Code | HTTP | Meaning & fix |
|---|---|---|
payment_required | 402 | No proof sent. Pay the challenge and retry. |
invalid_nonce | 402 | Nonce unknown or for another route. Request a fresh challenge. |
nonce_expired | 402 | Challenge older than nonceTtl. Request a fresh challenge. |
tx_pending | 402 | Transaction not final yet. Retry with the same headers in ~1 s. |
tx_not_found | 402 | Hash not found on the selected network. Check X-Pay-Network. |
amount_mismatch | 402 | Paid amount differs from the challenge. Send the exact amount. |
wrong_recipient | 402 | Transfer went to another address. |
tx_already_used | 402 | This hash already unlocked a response. Pay again. |
unauthorized | 401 | Missing or invalid API key. |
rate_limited | 429 | Too many requests. Respect Retry-After. |
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.
[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…
Glossary
| Term | Meaning |
|---|---|
| x402 | An open protocol that uses HTTP status 402 Payment Required to ask for, and prove, a payment inside a normal HTTP request. |
| Challenge | The 402 response body that says how much to pay, in which asset, on which network and to whom. |
| Nonce | A single-use value inside the challenge that binds the payment to one specific request. |
| Proof | The X-Payment header a client sends on retry: transaction hash plus nonce. |
| Facilitator | The service that verifies proofs on-chain and signs receipts. Ferro hosts one; you can self-host your own. |
| Rail | A network and asset pair you accept, for example USDC on Base. |
| Receipt | A signed record of a settled payment, anchored on-chain in a Merkle batch. |
| Instant / batched | Settle each request on-chain right away, or aggregate many small payments and settle them together. |
| Spending policy | Buyer-side limits (per request, per day, allowed hosts) enforced by @ferro/fetch. |
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.
Changelog
robinhood-mainnetsupported in@ferro/core,@ferro/expressand@ferro/hono.- No config changes needed for existing routes.
@ferro/ai-sdk:createX402Gate()andwrapWith402().@ferro/fetch1.0 with spending policies and events.
- Added Optimism, Solana and Sui.
acceptsoption for multi-rail challenges.
- Atomic basis-point splits per settlement.
- Signed webhooks with four event types.
- Receipts are batched and anchored on-chain.
verifyReceipt()in@ferro/core.
- Edge-compatible
@ferro/hono. - Redis, Postgres and KV stores.
© 2026 Ferro Labs · MIT Licensed · Privacy · Terms · X (Twitter)