Wrapped x402 Logo

Wrapped x402 Documentation

Open-source library for AI-native x402 integrations on Solana — Python & Node.js.

Introduction

Wrapped x402 standardizes AI micropayments using the x402 protocol (HTTP 402: Payment Required) so any API, model endpoint, or agent can gate premium features with verifiable on-chain credits.

Why x402?

Uniform, trustless pay-per-use for AI endpoints. No proprietary gateways; open verification.

What you get

SDKs, verifiers, and FastAPI/Express templates that ship in minutes, not weeks.

Who it’s for

Builders of AI apps/agents, API vendors, and Solana-native dApps needing metering.

Philosophy

Simple API surface, open verification, lightweight runtime, AI-native mindset.

Installation

Python (SDK + FastAPI)

PyPI

pip install wrappedx402-core wrappedx402-fastapi wrappedx402-langchain

Node.js (SDK + Express)

npm

npm install wrappedx402-core wrappedx402-express wrappedx402-langchain

Peer Requirements

Node ≥ 18, Python ≥ 3.10, public Solana RPC (or custom), and server runtime (serverless OK).

Hello World

Both stacks ship with minimal samples so you can unlock an endpoint with 1-2 functions.

SDK Overview

Both SDKs expose a minimal Client to initiate payments and a Verifier for proof checks.

Python — Client

from wrappedx402_core import X402Client
client = X402Client(
  receiver="FCRJ287uSoeF6qKuDcjV8kh54eaNBkDVYCNr3LCoQyu8",
  rpc="https://api.mainnet-beta.solana.com"
)
payment = client.create_payment(amount="0.001 SOL", memo="AI Query #42")
print(payment)

Node — Client

import { X402Client } from "wrappedx402-core";
const client = new X402Client({
  receiver: "FCRJ287uSoeF6qKuDcjV8kh54eaNBkDVYCNr3LCoQyu8",
  rpc: "https://api.mainnet-beta.solana.com"
});
const payment = await client.createPayment({ amount: "0.001 SOL", memo: "AI Query #42" });
console.log(payment);

Python — Verifier

from wrappedx402_core import verify_proof
valid = verify_proof(signature="5rTxQ...xyz", ttl=180, min_amount=0.001)
print("valid:", valid)

Node — Verifier

import { verifyProof } from "wrappedx402-core";
const valid = await verifyProof({ signature:"5rTxQ...xyz", ttl:180, minAmount:0.001 });
console.log("valid:", valid);

Verifier API

The verifier reads a Solana transaction and checks: receiver, amount, recent block time (TTL), and replay-safety (nonce/signature).

ParamTypeDescription
signaturestringSolana transaction signature (hash).
ttlint (sec)Max age allowed for the proof (e.g., 120–300s).
minAmountnumberMinimum SOL/SPL expected by receiver.
noncestring (opt)Optional unique challenge to bind a single request.
Default TTL is short-lived (e.g., 180s). Expired proofs are rejected automatically.

Server Templates

FastAPI (Python)

from fastapi import FastAPI, Request
from wrappedx402_fastapi import x402_middleware
from wrappedx402_core import verify_proof

app = FastAPI()
app.middleware("http")(x402_middleware)

@app.get("/premium")
async def premium(req: Request):
    proof = req.headers.get("x402-proof")
    if not verify_proof(signature=proof, ttl=120, min_amount=0.001):
        return {"error":"invalid or expired"}
    return {"ok": True, "content":"Unlocked via x402"}

Express (Node)

import express from "express";
import { x402Middleware } from "wrappedx402-express";
import { verifyProof } from "wrappedx402-core";

const app = express();
app.use(x402Middleware());

app.get("/premium", async (req, res) => {
  const proof = req.header("x402-proof");
  const valid = await verifyProof({ signature:proof, ttl:120, minAmount:0.001 });
  if(!valid) return res.status(402).json({ error:"invalid or expired" });
  res.json({ ok:true, content:"Unlocked via x402" });
});

CORS & Rate Limit

Allow origins you trust only. Apply small token-bucket limits to 402 endpoints to avoid spam prior to payment.

Serverless

Compatible with serverless (Vercel/Cloudflare/Render). Keep RPC & receiver in env vars.

HTTP 402 — Payment Required

When a client requests a premium endpoint without proof, respond with HTTP 402 and payment instructions.

Response Shape

HTTP/1.1 402 Payment Required
Content-Type: application/json

{
  "x402": {
    "receiver":"FCRJ...Qyu8",
    "amount":"0.001 SOL",
    "memo":"AI Query #42",
    "ttl":180,
    "nonce":"abc123"
  }
}

Authorized Retry

# Client retries after paying
GET /premium
x402-proof: 5rTxQ...xyz
x402-nonce: abc123

Success

HTTP/1.1 200 OK
{
  "ok":true,
  "content":"Unlocked via x402"
}

Failure

HTTP/1.1 402 Payment Required
{ "error":"invalid or expired" }

Configuration

Receiver

Solana address (wallet/program) that receives payments.

RPC Endpoint

Public RPC or private node URL for signature lookups.

Min Amount

Lower bound per call (e.g., 0.001 SOL). Prevents dust.

TTL Window

Proof expiration (e.g., 120–300s). Shorter = safer.

Environment Variables

KeyExamplePurpose
SOLANA_RPChttps://api.mainnet-beta.solana.comRPC for verifier lookups
SOL_RECEIVERFCRJ...Qyu8Destination for payments
MIN_AMOUNT0.001Minimum required amount
TTL_SECONDS180Max proof age
CORS_ORIGINShttps://example.comAllowed web origins

TTL & Credit Flow

Step 1

Client → GET /premium

Step 2

Server → 402 with receiver/amount/ttl/nonce

Step 3

Client pays on Solana; obtains signature

Step 4

Server verifies signature + TTL + minAmount

Step 5

Client retries with x402-proof

Step 6

Server returns 200 OK + content

Anti-replay uses nonce & binding the proof to a single request context.

Error Codes

StatusCodeMeaning
402X402_REQUIREDPayment required; no/invalid proof
402X402_EXPIREDTTL elapsed
402X402_UNDERPAIDAmount below minimum
400X402_MALFORMEDMalformed headers/body
429RATE_LIMITToo many attempts before payment
500RPC_ERRORUpstream RPC failure

Webhooks & Callbacks

Payment Confirmed

Optional server callback when a signature passes verification, e.g., for analytics or credits ledgering.

Abuse Signals

Emit events on repeated invalid proofs to block IP/keys temporarily.

Ledger Hooks

Mirror successful calls to internal billing for dashboards.

Retry Policy

Idempotent handlers recommended to avoid double-counting on client retries.

Testing & Sandbox

Local RPC

Use a dev RPC or a mock verifier that asserts header shapes and TTL math.

Unit Tests

Mock verify_proof/verifyProof to simulate valid/expired/underpaid flows.

Load Tests

Benchmark 402 → pay → verify → 200 to tune cache & RPC pool.

CI Tips

Inject env via secrets; never commit keys or private RPC URLs.

CLI (Tools)

Check Proof

wrappedx402 check --sig 5rTxQ... --ttl 180 --min 0.001

Gen Nonce

wrappedx402 nonce --len 24

Dump Tx

wrappedx402 tx --sig 5rTxQ...

Config

wrappedx402 config --rpc <URL> --receiver <ADDR>

Examples

Python — Minimal

from fastapi import FastAPI, Request
from wrappedx402_fastapi import x402_middleware
from wrappedx402_core import verify_proof

app = FastAPI()
app.middleware("http")(x402_middleware)

@app.get("/ai/answer")
async def ai_answer(req: Request):
    proof = req.headers.get("x402-proof")
    ok = verify_proof(signature=proof, ttl=180, min_amount=0.001)
    return {"answer":"42"} if ok else {"error":"payment required"}

Node — Minimal

import express from "express";
import { x402Middleware } from "wrappedx402-express";
import { verifyProof } from "wrappedx402-core";

const app = express();
app.use(x402Middleware());

app.get("/ai/answer", async (req, res) => {
  const sig = req.header("x402-proof");
  const ok = await verifyProof({ signature:sig, ttl:180, minAmount:0.001 });
  res.json(ok ? { answer:"42" } : { error:"payment required" });
});

Browser Fetch

const res = await fetch("/premium");
if(res.status === 402){
  const x = await res.json(); // { x402: { receiver, amount, ttl, nonce } }
  // show pay modal → obtain signature → retry
}
const data = await fetch("/premium", { headers:{ "x402-proof":signature } });

LangChain Hook

# pseudocode
if not verify_proof(sig, ttl=120, min_amount=0.001):
    raise PaymentRequired()
llm.invoke(prompt)

Best Practices

Short TTL

120–300s is typical; shorter for high-value endpoints.

Strict Min

Reject underpay to avoid ambiguous pricing.

Nonce Binding

Bind proof to request to kill reuse.

Cache RPC

Pool connections or add small cache for lookups.

CORS Hardened

Only allow your production origins.

Observability

Log proof age, tx latency, reject reasons.

FAQ

Is devnet supported?

Use at your own risk for testing. Production should be mainnet with strict envs.

Can I use SPL tokens?

Yes, as long as the verifier checks mint + amount. Examples focus on SOL for brevity.

How fast is verification?

Typical ~200ms with healthy RPC; add small caches for bursts.

Any vendor lock-in?

No. All logic is open-source with reproducible verification paths.

License & Resources

Wrapped x402 is released under the MIT License. Contributions and PRs are welcome.