Skip to content

0xShak/x402-kit

Repository files navigation

x402-kit

Make x402 payments on Base trivial on both sides of the wire — plus the parts nobody else ships: built-in observability and an MCP server so AI agents can pay autonomously.

// app/api/premium/route.ts  — monetize any Next.js route in 3 lines
import { withX402 } from "@x402-kit/next";

export const GET = withX402(
  { price: "$0.01", payTo: process.env.PAYOUT_ADDRESS, network: "base" },
  async () => Response.json({ data: "the paid thing" }),
);

That's it. Unpaid requests get a 402 with payment requirements; paid requests are verified, settled on-chain (gasless USDC via EIP-3009), and your handler runs — with a settlement receipt attached and a telemetry event emitted.

Status: testnet-first (Base Sepolia). MIT. Built on the verified v1 exact EVM wire format — see NOTES.md for the protocol facts and the drift we corrected.


Why this exists

The base middleware is commoditized; the DX + agent + telemetry layer is not. x402-kit is the plumbing:

  • 🟢 3-line seller setupwithX402() for Next 16 route handlers (or a central proxy.ts gate).
  • 🔵 Drop-in buyerx402Fetch transparently pays a 402 and retries, under hard spend caps.
  • 🤖 Agent-native — an MCP server exposing x402_quote / fetch / budget / history so Claude (or any MCP client) can pay per-call within a budget.
  • 📊 Observability built in — earnings (seller) and spend (buyer): revenue, payers, settlement p50/p95, facilitator mix, failure rate.
  • 🔁 Resilience — a Facilitator interface with CDP / community / Flashblocks impls and a failover() wrapper.

Architecture

                 ┌──────────────────── @x402-kit/core ────────────────────┐
                 │  types · 402/X-PAYMENT encode-decode · price parsing    │
                 │  EIP-3009 typed data · Facilitator + failover()         │
                 └───────▲──────────────────▲───────────────────▲─────────┘
                         │                  │                   │
        ┌────────────────┴───┐   ┌──────────┴────────┐   ┌──────┴──────────┐
        │  @x402-kit/next    │   │ @x402-kit/client  │   │  @x402-kit/mcp  │
        │  withX402() seller │   │ x402Fetch() buyer │   │  agent wallet   │
        └────────┬───────────┘   └─────────┬─────────┘   └────────┬────────┘
                 │ emits                    │ emits                │ emits
                 └──────────────► @x402-kit/telemetry ◄────────────┘
                                  event bus · JSON/SQLite sink · aggregation
                                          │
                                   apps/demo dashboard

core is shared by all three sides so the wire format, signing, and facilitator logic live in one well-typed place.

Packages

Package What it does
@x402-kit/core Protocol primitives: types, encode/decode, price parsing, EIP-3009 typed data, facilitator client + failover.
@x402-kit/next withX402() route wrapper + withX402Matcher() proxy gate for Next 16.
@x402-kit/client x402Fetch buyer wrapper, Signer interface, privateKeySigner (testnet).
@x402-kit/mcp MCP server: x402_quote / fetch / budget / history, server-side spend cap.
@x402-kit/telemetry Event bus, JSON/SQLite sinks, dashboard aggregation.
apps/demo A paid API + an agent that pays for it + a live dashboard. The hero.

Quickstart

pnpm install
pnpm build
cp .env.example .env.local   # fill in X402_PRIVATE_KEY (Base Sepolia) to let the agent pay
pnpm --filter @x402-kit/demo dev

Open http://localhost:3000, click Run the agent, and watch a real $0.01 Base Sepolia settlement appear on the dashboard. Get test USDC at faucet.circle.com.

Buyer

import { privateKeySigner, x402Fetch } from "@x402-kit/client";

const fetch402 = x402Fetch({ signer: privateKeySigner(KEY), maxPerCall: "$0.05" });
const res = await fetch402("https://api.example.com/premium"); // auto-pays a 402, retries once

Agent (MCP)

// .mcp.json — see docs/mcp.json for the full snippet
{
  "mcpServers": {
    "x402": {
      "command": "npx",
      "args": ["-y", "@x402-kit/mcp"],
      "env": { "X402_PRIVATE_KEY": "0xTESTNET_KEY", "X402_MAX_TOTAL_USDC": "2" }
    }
  }
}

Then: “Quote https://api.example.com/premium, and if it’s under 2 cents, fetch it.”

Recipes

Each is a worked example in docs/recipes.md:

  1. Monetize a data API in 3 lines.
  2. Give an AI agent a wallet (MCP) and a $5 budget.
  3. Paywall a Next.js page/route via proxy.ts.
  4. Metered SaaS with no signup.
  5. Two agents transacting M2M, watched on the dashboard.

Safety

  • Testnet-first. Never commit a funded mainnet key — .env* is gitignored from commit 1.
  • A raw env private key is testnet only. For mainnet, implement the Signer interface over CDP Server Wallets / a KMS; @x402-kit/client warns loudly about env keys in serverless prod.
  • Spend caps are hard: a buyer throws SpendCapError rather than silently overpaying.
  • Mainnet hardening (KYT/OFAC, custody, replay/idempotency, failover under real outages) is a tracked later pass — see NOTES.md.

Development

pnpm build      # turbo, dependency-ordered
pnpm test       # vitest, mocked facilitator (24 unit tests)
pnpm typecheck

The Base Sepolia e2e (@x402-kit/client test:e2e) runs in CI only when a funded test wallet secret is present.

License

MIT © 0xShak

About

Make x402 payments on Base trivial on both sides of the wire — seller middleware, buyer fetch, an MCP server for agents, and built-in observability. TypeScript, MIT.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors