Documentation
Everything you need to monetize your API with per-call USDC micropayments on Solana.
Overview
Register
Create your API on the dashboard. Get your API ID & key.
Install
npm install the SDK. Works with Express, Next.js, Fastify.
Earn
Add one line of middleware. USDC flows to your wallet.
Installation
Install the SDK from npm. Zero native deps, any Node.js 18+ environment.
1npm install @agentpaywall/sdk
Prerequisites: Node.js 18+, a Solana wallet, and an API registered on the dashboard.
Quick Start
Choose your framework. One middleware handles everything.
1import express from 'express';2import { agentPaywall } from '@agentpaywall/sdk';34const app = express();56app.get('/api/your-endpoint',7 agentPaywall({8 priceUsdc: 0.001,9 recipientWallet: 'YOUR_SOLANA_WALLET',10 apiId: 'YOUR_API_ID',11 }),12 (req, res) => {13 res.json({ data: 'protected response' });14 }15);1617app.listen(3001);
How It Works
Request arrives without payment
Middleware checks for X-Payment-Proof. If missing → 402 with payment instructions.
Consumer sends USDC on Solana
AI agent or developer sends exact USDC amount via SPL token transfer.
Retry with transaction proof
Consumer retries with tx signature in X-Payment-Proof header.
SDK verifies & passes through
On-chain verification: correct amount, recipient, token, not replayed. Handler executes.
The 402 Response
Structured JSON that both humans and AI agents can parse:
1{2 "status": 402,3 "error": "Payment Required",4 "code": "PAYMENT_REQUIRED",5 "paymentDetails": {6 "network": "solana",7 "currency": "USDC",8 "amount": 0.001,9 "recipient": "oEmhqmu9aHuzDDvbnE4SMHb1nMbWthZMKSMpxANy6Dg",10 "memo": "agentpaywall:your-api-name",11 "usdcMintAddress": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"12 }13}
Why 402? Designed for "Payment Required" since 1999 but never used. AgentPaywall finally puts it to work.
AI-native. Agents parse JSON, extract recipient + amount, pay on Solana, retry — zero human intervention.
Consumer / Agent Flow
1import { Connection, Keypair, PublicKey } from '@solana/web3.js';2import {3 getAssociatedTokenAddress,4 createTransferInstruction,5} from '@solana/spl-token';67const USDC_MINT = new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU');89async function payAndCall(apiUrl: string, recipientWallet: string, amountUsdc: number) {10 const connection = new Connection('https://api.devnet.solana.com');11 const payer = Keypair.fromSecretKey(/* your agent keypair */);1213 const payerATA = await getAssociatedTokenAddress(USDC_MINT, payer.publicKey);14 const recipientATA = await getAssociatedTokenAddress(15 USDC_MINT, new PublicKey(recipientWallet)16 );17 const amount = Math.round(amountUsdc * 1_000_000);1819 const txSignature = await sendTransaction(20 connection, payer, payerATA, recipientATA, amount21 );2223 const response = await fetch(apiUrl, {24 headers: { 'X-Payment-Proof': txSignature },25 });2627 return await response.json();28}
Using cURL
1# Step 1: Try the API (get 402)2curl -i https://your-api.com/api/endpoint34# Step 2: Send USDC on Solana (via wallet or CLI)5# ... send 0.001 USDC to recipient wallet ...67# Step 3: Retry with proof8curl -H "X-Payment-Proof: <tx_signature>" \9 https://your-api.com/api/endpoint
Security Model
On-chain verification
Every payment verified against the Solana blockchain. No trust required.
Replay protection
Each tx signature used once. Recorded in Supabase for persistence.
Exact amount matching
Underpayments and wrong-token transfers are automatically rejected.
Recipient validation
Transaction must send USDC to your specific wallet address.
Transaction freshness
Configurable timeout prevents use of old proofs.
No private keys
Only needs your public address. Private keys stay in your wallet.
Configuration Reference
| Field | Type | Description |
|---|---|---|
| priceUsdc | number | Price in USDC per API call (e.g. 0.001). |
| recipientWallet | string | Solana wallet address (base58) that receives USDC. |
| apiId | string | API ID from the dashboard for tracking. |
| network | 'devnet' | 'mainnet-beta' | Solana cluster to verify against. |
| rpcUrl | string | Custom RPC URL. Recommended for production. |
| verifyTimeout | number | Timeout (ms) for tx verification. |
| allowReplay | boolean | Allow reuse of tx signatures. Defaults to false — each signature is used once. |
| onPaymentVerified | (tx) => void | Callback fired after successful payment verification. |
| platformApiKey | string | API key from the dashboard. Enables cross-restart replay protection and earnings tracking. |
Environment Variables
1# .env or .env.local2NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co3SUPABASE_SERVICE_ROLE_KEY=your-service-role-key4NEXT_PUBLIC_SOLANA_RPC_URL=https://api.devnet.solana.com5NEXT_PUBLIC_USDC_MINT_ADDRESS=4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU
Advanced Patterns
Production Config
1agentPaywall({2 priceUsdc: 0.005,3 recipientWallet: process.env.SOLANA_WALLET!,4 apiId: process.env.AGENTPAYWALL_API_ID!,56 network: 'devnet',7 rpcUrl: process.env.SOLANA_RPC,8 verifyTimeout: 30000,9 allowReplay: false,1011 onPaymentVerified: (tx) => {12 console.log(`Payment ${tx.signature} verified: ${tx.amount} USDC`);13 },14})
Multi-Endpoint Pricing
Free, cheap, and premium tiers on the same server:
1const baseConfig = {2 recipientWallet: process.env.SOLANA_WALLET!,3 network: 'devnet' as const,4};56// Free: no paywall7app.get('/api/v1/status', (req, res) => res.json({ status: 'ok' }));89// Cheap: market data10app.get('/api/v1/prices',11 agentPaywall({ ...baseConfig, priceUsdc: 0.0001, apiId: 'price-api' }),12 priceHandler13);1415// Premium: AI analysis16app.post('/api/v1/analyze',17 agentPaywall({ ...baseConfig, priceUsdc: 0.05, apiId: 'analyze-api' }),18 analyzeHandler19);
Use Cases
AgentPaywall works for any API that delivers value per call:
AI Agent Tool APIs
Expose tools that AI agents discover & pay for autonomously via the 402 protocol.
Market Data & Analytics
Real-time crypto prices, on-chain analytics, DEX volume, or trading signals.
AI Model Inference
LLM completion, image generation, speech-to-text, embeddings behind a paywall.
Premium Data Feeds
Curated datasets, lead lists, research papers — pay per record, not per month.
Blockchain Infrastructure
Premium RPCs, indexer queries, transaction simulation, archive nodes.
Security & Verification
Wallet screening, contract auditing, phishing detection, KYC checks.
Error Handling
1async function callPaidApi(url: string, proofTx: string) {2 const res = await fetch(url, {3 headers: { 'X-Payment-Proof': proofTx },4 });56 switch (res.status) {7 case 200:8 return await res.json();910 case 402: {11 const { paymentDetails } = await res.json();12 const newTx = await sendPayment(paymentDetails);13 return callPaidApi(url, newTx);14 }1516 case 400:17 throw new Error('Invalid or expired transaction');18 case 403:19 throw new Error('Transaction already used (replay)');20 case 408:21 throw new Error('Verification timeout — try again');22 default:23 throw new Error(`Unexpected: ${res.status}`);24 }25}
| Status | Meaning | Agent Action |
|---|---|---|
| 200 | Success | Parse response body |
| 402 | Payment required | Read paymentDetails, pay, retry |
| 400 | Invalid proof | Send new payment |
| 403 | Replay blocked | Send fresh payment |
| 408 | Timeout | Wait & retry |
vs. Alternatives
Where AgentPaywall fits
AgentPaywall is built on the x402 standard from Coinbase’s open-source facilitator. We don’t replace it — we’re the managed product layer on top of it: dashboard, analytics, marketplace, Node.js middleware, and Solana-first developer experience.
If you want to run the raw x402 protocol yourself, use Coinbase CDP. If you want to ship a paywalled API in 2 minutes, use us.
Compared to the real alternatives
| Feature | AgentPaywall | Stripe | API Keys + DIY |
|---|---|---|---|
| Setup time | 5 min | 2–5 days | 1–3 days |
| Dashboard | ✓ Included | ✓ Stripe | Build it |
| Replay protection | ✓ Built-in | N/A | Build it |
| Min charge | $0.000001 | $0.50 | N/A |
| Per-call fee | ~$0.00025 (Solana) | 2.9% + $0.30 | N/A |
| Chargebacks | Impossible | Yes | N/A |
| AI-agent native | ✓ | ✗ | ✗ |
| Payout | Instant | 2–7 days | N/A |
| Infra you run | 1 npm pkg | Dashboard + webhooks | DB + auth + billing |
Stripe is the right answer when you’re charging a human a dollar or more and need fiat rails. AgentPaywall is the right answer when the caller is another piece of software, the charge is fractions of a cent, and you want the money to settle before the response lands.
Frequently Asked Questions
AgentPaywall is an open-source SDK that lets you monetize any API endpoint with per-call USDC payments on Solana. Add one middleware, and unpaid requests receive a 402 response with payment instructions. Consumers pay via Solana, then retry with proof.
Traditional billing requires subscriptions, invoicing, KYC, chargebacks, and 2.9% + $0.30 per charge. AgentPaywall is instant, permissionless, zero chargebacks, ~$0.00025/tx fees, and works for AI agents that can't sign up for Stripe.
Yes. The SDK, dashboard, and demo APIs are all open source. Self-host or use our hosted dashboard.
x402 is an open payment protocol standard (Linux Foundation, Coinbase, Stripe, Google). AgentPaywall is a managed product layer built on top of it. We are not competing with x402 — we are an early builder on the standard. Any consumer that already speaks x402 works with AgentPaywall out of the box. What x402 doesn't include is the dashboard, analytics, replay protection, framework adapters, marketplace, and the India-first developer community. That's what AgentPaywall adds.
Any developer who has an API worth charging for — especially Indian developers and indie builders who want to earn from their endpoints without building billing infrastructure. AI tool builders, data providers, infrastructure operators, and anyone in the Solana ecosystem.
The middleware returns a 400 error with details. The consumer sends a new payment and retries. No data is leaked before confirmation.
No. By default, allowReplay is false. Each signature is used once. Subsequent attempts get 403. Enforced in-memory and via Supabase.
USDC has 6 decimal places: technically $0.000001. Solana tx fees are ~$0.00025, so anything above that is profitable.
A small amount (~0.002 SOL) for the initial USDC token account. After that, payments arrive as USDC at no cost to you.
Currently USDC only. SOL is on the roadmap. USDC is preferred for price stability.
No. Solana transactions are final and irreversible once confirmed. Zero chargebacks.
Use a premium RPC (Helius, QuickNode, Triton) via rpcUrl. The verifyTimeout (default 30s) controls the wait.
Yes. Set network to "mainnet-beta" and use the mainnet USDC mint. Dashboard defaults to devnet for safe testing.
They call your endpoint, receive the 402 JSON with price + wallet details, then pay and retry — all autonomously.
Yes — Vercel, Lambda, Cloudflare Workers, any Node.js runtime. Use withAgentPaywall for Next.js.
Transaction signatures are stored in Supabase on first use. Duplicate signatures get 403, even across server restarts.
AgentPaywall handles payments, not rate limiting. Add your own rate limiter in front of the middleware.
Yes. Each agentPaywall() call is independent. You can charge $0.001 for data and $0.10 for AI inference on the same server.
Yes. Your wallet address is a public key — designed to be shared. Only your private key (which you never share) can spend funds.
The SDK verifies the exact amount. Underpayments are rejected with 400. Overpayments are accepted (you keep the extra).
The SDK connects directly to Solana's blockchain. If the RPC is unreachable, the request returns 408 (timeout), and the consumer retries with the same valid proof.