v0.2.1

Documentation

Everything you need to monetize your API with per-call USDC micropayments on Solana.

Overview

📋
Step 1

Register

Create your API on the dashboard. Get your API ID & key.

📦
Step 2

Install

npm install the SDK. Works with Express, Next.js, Fastify.

💰
Step 3

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.

Terminal
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.

Express integration
1import express from 'express';
2import { agentPaywall } from '@agentpaywall/sdk';
3
4const app = express();
5
6app.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);
16
17app.listen(3001);

How It Works

01

Request arrives without payment

Middleware checks for X-Payment-Proof. If missing → 402 with payment instructions.

02

Consumer sends USDC on Solana

AI agent or developer sends exact USDC amount via SPL token transfer.

03

Retry with transaction proof

Consumer retries with tx signature in X-Payment-Proof header.

04

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:

HTTP 402 Payment Required
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

agent-consumer.ts
1import { Connection, Keypair, PublicKey } from '@solana/web3.js';
2import {
3 getAssociatedTokenAddress,
4 createTransferInstruction,
5} from '@solana/spl-token';
6
7const USDC_MINT = new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU');
8
9async 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 */);
12
13 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);
18
19 const txSignature = await sendTransaction(
20 connection, payer, payerATA, recipientATA, amount
21 );
22
23 const response = await fetch(apiUrl, {
24 headers: { 'X-Payment-Proof': txSignature },
25 });
26
27 return await response.json();
28}

Using cURL

Terminal
1# Step 1: Try the API (get 402)
2curl -i https://your-api.com/api/endpoint
3
4# Step 2: Send USDC on Solana (via wallet or CLI)
5# ... send 0.001 USDC to recipient wallet ...
6
7# Step 3: Retry with proof
8curl -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

FieldTypeDescription
priceUsdcnumberPrice in USDC per API call (e.g. 0.001).
recipientWalletstringSolana wallet address (base58) that receives USDC.
apiIdstringAPI ID from the dashboard for tracking.
network'devnet' | 'mainnet-beta'Solana cluster to verify against.
rpcUrlstringCustom RPC URL. Recommended for production.
verifyTimeoutnumberTimeout (ms) for tx verification.
allowReplaybooleanAllow reuse of tx signatures. Defaults to false — each signature is used once.
onPaymentVerified(tx) => voidCallback fired after successful payment verification.
platformApiKeystringAPI key from the dashboard. Enables cross-restart replay protection and earnings tracking.

Environment Variables

.env.local
1# .env or .env.local
2NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
3SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
4NEXT_PUBLIC_SOLANA_RPC_URL=https://api.devnet.solana.com
5NEXT_PUBLIC_USDC_MINT_ADDRESS=4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU

Advanced Patterns

Production Config

Full config
1agentPaywall({
2 priceUsdc: 0.005,
3 recipientWallet: process.env.SOLANA_WALLET!,
4 apiId: process.env.AGENTPAYWALL_API_ID!,
5
6 network: 'devnet',
7 rpcUrl: process.env.SOLANA_RPC,
8 verifyTimeout: 30000,
9 allowReplay: false,
10
11 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:

Multi-tier pricing
1const baseConfig = {
2 recipientWallet: process.env.SOLANA_WALLET!,
3 network: 'devnet' as const,
4};
5
6// Free: no paywall
7app.get('/api/v1/status', (req, res) => res.json({ status: 'ok' }));
8
9// Cheap: market data
10app.get('/api/v1/prices',
11 agentPaywall({ ...baseConfig, priceUsdc: 0.0001, apiId: 'price-api' }),
12 priceHandler
13);
14
15// Premium: AI analysis
16app.post('/api/v1/analyze',
17 agentPaywall({ ...baseConfig, priceUsdc: 0.05, apiId: 'analyze-api' }),
18 analyzeHandler
19);

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.

$0.001 – $0.05
📊

Market Data & Analytics

Real-time crypto prices, on-chain analytics, DEX volume, or trading signals.

$0.0001 – $0.01
🧠

AI Model Inference

LLM completion, image generation, speech-to-text, embeddings behind a paywall.

$0.001 – $0.10
� - �️

Premium Data Feeds

Curated datasets, lead lists, research papers — pay per record, not per month.

$0.01 – $1.00
� -

Blockchain Infrastructure

Premium RPCs, indexer queries, transaction simulation, archive nodes.

$0.0001 – $0.005
🛡️

Security & Verification

Wallet screening, contract auditing, phishing detection, KYC checks.

$0.05 – $5.00

Error Handling

Smart retry logic
1async function callPaidApi(url: string, proofTx: string) {
2 const res = await fetch(url, {
3 headers: { 'X-Payment-Proof': proofTx },
4 });
5
6 switch (res.status) {
7 case 200:
8 return await res.json();
9
10 case 402: {
11 const { paymentDetails } = await res.json();
12 const newTx = await sendPayment(paymentDetails);
13 return callPaidApi(url, newTx);
14 }
15
16 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}
StatusMeaningAgent Action
200SuccessParse response body
402Payment requiredRead paymentDetails, pay, retry
400Invalid proofSend new payment
403Replay blockedSend fresh payment
408TimeoutWait & 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

FeatureAgentPaywallStripeAPI Keys + DIY
Setup time5 min2–5 days1–3 days
Dashboard✓ Included✓ StripeBuild it
Replay protection✓ Built-inN/ABuild it
Min charge$0.000001$0.50N/A
Per-call fee~$0.00025 (Solana)2.9% + $0.30N/A
ChargebacksImpossibleYesN/A
AI-agent native
PayoutInstant2–7 daysN/A
Infra you run1 npm pkgDashboard + webhooksDB + 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.

Ready to monetize?

Register an API and start earning USDC in under 5 minutes.