Future implementation guide for adding x402 payment protocol support to Crypto Data Aggregator.
- Overview
- What is x402?
- Why x402 for Crypto Data Aggregator?
- Protocol Specification
- Architecture
- Implementation Guide
- SDK Options
- Use Cases
- Security Considerations
- Resources
x402 is an open payment protocol built on HTTP 402 (Payment Required) that enables micropayments for API access. It's developed by Coinbase and provides a standardized way to monetize APIs with cryptocurrency payments.
Key Benefits:
- 💵 No fees, 2-second settlement
- 💰 Micropayments from $0.001
- 🔓 No API keys required for clients
- ⚡ Automatic payment handling
- 🌐 Multi-chain support (EVM, Solana)
x402 is a payment protocol that uses the HTTP 402 status code ("Payment Required") to enable direct payments for web resources. It provides:
| Component | Description |
|---|---|
| Resource Server | Your API that requires payment for access |
| Client | Application making paid requests |
| Facilitator | Service that verifies and settles payments on-chain |
┌──────────┐ ┌─────────────────┐ ┌─────────────┐
│ Client │ │ Resource Server │ │ Facilitator │
└────┬─────┘ └────────┬────────┘ └──────┬──────┘
│ │ │
│ 1. GET /api/premium │ │
│────────────────────────>│ │
│ │ │
│ 2. 402 + PAYMENT-REQUIRED header │
│<────────────────────────│ │
│ │ │
│ 3. GET /api/premium + PAYMENT-SIGNATURE header │
│────────────────────────>│ │
│ │ │
│ │ 4. Verify payment │
│ │─────────────────────────>│
│ │ │
│ │ 5. Verification result │
│ │<─────────────────────────│
│ │ │
│ 6. 200 OK + Response │ │
│<────────────────────────│ │
│ │ │
│ │ 7. Settle on-chain │
│ │─────────────────────────>│
│ │ │
| Header | Direction | Purpose |
|---|---|---|
PAYMENT-REQUIRED |
Server → Client | Contains payment requirements (402 response) |
PAYMENT-SIGNATURE |
Client → Server | Contains signed payment authorization |
PAYMENT-RESPONSE |
Server → Client | Contains settlement confirmation |
| Feature | Price Point | Use Case |
|---|---|---|
| Premium API Access | $0.001/request | High-frequency trading bots |
| Real-time WebSocket | $0.01/hour | Live price feeds |
| Historical Data Export | $0.10/export | Bulk data downloads |
| Advanced Analytics | $0.05/query | Custom screener queries |
| Priority Rate Limits | $1.00/day | Higher API limits |
- No Infrastructure - No user accounts, no payment processing
- Crypto-Native - Pay with USDC on Base, Solana, etc.
- Micropayments - Monetize individual API calls
- Open Source - MIT licensed, maintained by Coinbase
- Multi-Chain - Support multiple blockchains
When a protected endpoint is accessed without payment:
// 402 Response with PAYMENT-REQUIRED header
{
"x402Version": 2,
"accepts": [
{
"scheme": "exact",
"network": "eip155:8453", // Base mainnet
"asset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", // USDC
"payTo": "0xYourAddress",
"maxAmountRequired": "1000", // In smallest unit (0.001 USDC)
"resource": "https://api.example.com/premium",
"description": "Premium API access",
"mimeType": "application/json",
"paymentNonce": "unique-nonce-123"
}
]
}Client creates a signed payment authorization:
// PAYMENT-SIGNATURE header
{
"x402Version": 2,
"scheme": "exact",
"network": "eip155:8453",
"payload": {
"signature": "0x...", // Signed authorization
"authorization": {
"from": "0xClientAddress",
"to": "0xPayToAddress",
"asset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
"amount": "1000",
"nonce": "unique-nonce-123",
"validAfter": 1737500000,
"validBefore": 1737510000
}
}
}After successful payment:
// PAYMENT-RESPONSE header
{
"success": true,
"transactionHash": "0x...",
"network": "eip155:8453",
"settledAt": "2026-01-22T12:00:00Z"
}┌─────────────────────────────────────────────────────────────────┐
│ Crypto Data Aggregator │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Free API │ │ Premium API │ │
│ │ /api/market │ │ /api/premium │ │
│ │ /api/trending │ │ /api/export │ │
│ └─────────────────┘ └────────┬────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ x402 Middleware │ │
│ │ (paymentMiddleware) │
│ └────────┬────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ x402ResourceServer │
│ └────────┬────────┘ │
│ │ │
└──────────────────────────────────┼───────────────────────────────┘
│
┌────────▼────────┐
│ Facilitator │
│ (x402.org or │
│ self-hosted) │
└────────┬────────┘
│
┌──────────────┴──────────────┐
│ │
┌─────▼─────┐ ┌──────▼──────┐
│ Base │ │ Solana │
│ (EVM) │ │ (SVM) │
└───────────┘ └─────────────┘
// Premium routes requiring payment
const premiumRoutes = {
'GET /api/premium/coins': {
accepts: {
payTo: process.env.PAYMENT_ADDRESS,
scheme: 'exact',
price: '$0.001',
network: 'eip155:8453', // Base mainnet
},
},
'GET /api/premium/export': {
accepts: {
payTo: process.env.PAYMENT_ADDRESS,
scheme: 'exact',
price: '$0.10',
network: 'eip155:8453',
},
},
'GET /api/premium/analytics/*': {
accepts: {
payTo: process.env.PAYMENT_ADDRESS,
scheme: 'exact',
price: '$0.05',
network: 'eip155:8453',
},
},
};// src/app/api/premium/route.ts
import { paymentMiddleware } from '@x402/express';
import { x402ResourceServer, HTTPFacilitatorClient } from '@x402/core/server';
import { registerExactEvmScheme } from '@x402/evm/exact/server';
const facilitatorClient = new HTTPFacilitatorClient({
url: 'https://x402.org/facilitator',
});
const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);
const routes = {
'GET /api/premium/coins': {
accepts: {
payTo: process.env.PAYMENT_ADDRESS as `0x${string}`,
scheme: 'exact',
price: '$0.001',
network: 'eip155:8453',
},
},
};
// Apply middleware
app.use(paymentMiddleware(routes, server));// middleware.ts
import { paymentProxy } from '@x402/next';
import { x402ResourceServer, HTTPFacilitatorClient } from '@x402/core/server';
import { registerExactEvmScheme } from '@x402/evm/exact/server';
const facilitatorClient = new HTTPFacilitatorClient({
url: 'https://x402.org/facilitator',
});
const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);
export const middleware = paymentProxy(
{
'GET /api/premium/:path*': {
accepts: {
payTo: process.env.PAYMENT_ADDRESS,
scheme: 'exact',
price: '$0.001',
network: 'eip155:8453',
},
},
},
server
);
export const config = {
matcher: '/api/premium/:path*',
};// Automatic payment handling with axios
import axios from 'axios';
import { wrapAxiosWithPayment } from '@x402/axios';
import { x402Client } from '@x402/core/client';
import { registerExactEvmScheme } from '@x402/evm/exact/client';
import { privateKeyToAccount } from 'viem/accounts';
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const client = new x402Client();
registerExactEvmScheme(client, { signer: account });
const axiosClient = wrapAxiosWithPayment(axios.create(), client);
// Payments happen automatically!
const response = await axiosClient.get('https://crypto-aggregator.com/api/premium/coins');// src/app/api/premium/coins/route.ts
export async function GET(request: Request) {
// This only runs after successful payment verification
const coins = await getDetailedCoinData();
return Response.json({
coins,
meta: {
premium: true,
dataPoints: coins.length,
timestamp: new Date().toISOString(),
},
});
}// Support both EVM (Base) and Solana
const routes = {
'GET /api/premium/coins': {
accepts: [
{
payTo: process.env.EVM_ADDRESS,
scheme: 'exact',
price: '$0.001',
network: 'eip155:8453', // Base
},
{
payTo: process.env.SOL_ADDRESS,
scheme: 'exact',
price: '$0.001',
network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', // Solana
},
],
},
};| Package | Purpose | Install |
|---|---|---|
@x402/core |
Core client/server | npm i @x402/core |
@x402/express |
Express middleware | npm i @x402/express |
@x402/next |
Next.js middleware | npm i @x402/next |
@x402/hono |
Hono middleware | npm i @x402/hono |
@x402/axios |
Axios interceptor | npm i @x402/axios |
@x402/fetch |
Fetch wrapper | npm i @x402/fetch |
@x402/evm |
EVM chain support | npm i @x402/evm |
@x402/svm |
Solana support | npm i @x402/svm |
| Package | Purpose | Install |
|---|---|---|
x402 |
Core SDK | pip install x402 |
| Package | Purpose | Import |
|---|---|---|
x402 |
Core SDK | github.com/coinbase/x402/go |
gin |
Gin middleware | github.com/coinbase/x402/go/http/gin |
| Package | Purpose |
|---|---|
x402-java |
Spring Boot integration |
// $0.001 per request for detailed coin data
"GET /api/premium/coins/:id": {
accepts: {
price: "$0.001",
description: "Detailed coin data with social metrics",
outputSchema: {
type: "object",
properties: {
id: { type: "string" },
price: { type: "number" },
socialMetrics: { type: "object" },
developerData: { type: "object" },
},
},
},
}// $0.10 per export (CSV/JSON)
"GET /api/premium/export/portfolio": {
accepts: {
price: "$0.10",
description: "Export portfolio data as CSV or JSON",
},
}// $0.01 per hour of WebSocket access
"POST /api/premium/websocket/subscribe": {
accepts: {
price: "$0.01",
description: "1 hour of real-time price WebSocket access",
},
}// $0.05 per complex query
"POST /api/premium/screener/query": {
accepts: {
price: "$0.05",
description: "Custom screener with unlimited filters",
},
}// $0.02 per year of historical data
"GET /api/premium/history/:coinId": {
accepts: {
price: "$0.02",
description: "Full historical price data",
},
}x402 includes built-in replay attack prevention:
{
"paymentNonce": "unique-per-request",
"validAfter": 1737500000, // Unix timestamp
"validBefore": 1737510000, // 10 minute window
}- Hosted Facilitator (
x402.org): Managed by Coinbase, handles settlement - Self-Hosted: Run your own facilitator for full control
Always verify the payment amount matches requirements:
if (paymentPayload.amount < requirements.maxAmountRequired) {
return { isValid: false, invalidReason: 'Insufficient payment' };
}# .env.local
# Payment receiving address (your wallet)
PAYMENT_ADDRESS=0xYourWalletAddress
EVM_ADDRESS=0xYourEVMAddress
SOL_ADDRESS=YourSolanaAddress
# Facilitator URL (use testnet for development)
FACILITATOR_URL=https://x402.org/facilitator
# For self-hosted facilitator
FACILITATOR_PRIVATE_KEY=0x...// Use Base Sepolia for testing
const testRoutes = {
'GET /api/premium/test': {
accepts: {
payTo: process.env.TEST_ADDRESS,
scheme: 'exact',
price: '$0.001',
network: 'eip155:84532', // Base Sepolia testnet
},
},
};# 1. Make request without payment
curl -i https://localhost:3000/api/premium/coins
# Returns: 402 with PAYMENT-REQUIRED header
# 2. Decode requirements
# Parse the PAYMENT-REQUIRED header (base64)
# 3. Create payment with test wallet
# Use x402 client SDK- x402.org - Official website
- GitHub: coinbase/x402 - Source code
- Specification v2
- Install x402 packages (
@x402/core,@x402/next,@x402/evm) - Configure facilitator client
- Set up payment receiving address
- Create environment variables
- Add x402 middleware to Next.js (
src/lib/x402-middleware.ts) - Configure protected routes (
src/lib/x402-config.ts) - Set pricing for each endpoint (25+ endpoints configured)
- Test with testnet
- Create
/api/premium/routes - Implement AI analysis endpoints (sentiment, signals, summary, compare)
- Implement whale tracking endpoints (transactions, alerts, smart-money)
- Implement advanced screener endpoint
- Implement access pass endpoints (hour, day, week)
- Update API documentation (
docs/API.md) - Add client integration examples
- Document pricing (
/api/premiumendpoint) - Create premium pricing page (
/pricing/premium)
- Switch to mainnet
- Monitor payments
- Track revenue analytics
- Iterate on pricing
| File | Purpose |
|---|---|
src/lib/x402-config.ts |
Centralized pricing & configuration for 25+ premium endpoints |
src/lib/x402-middleware.ts |
Next.js middleware for x402 payment verification |
src/lib/premium-ai.ts |
AI-powered analysis (sentiment, signals, summaries, comparisons) |
src/lib/premium-whales.ts |
Whale tracking & smart money analysis |
src/lib/premium-screener.ts |
Advanced screener with unlimited filters |
src/app/api/premium/route.ts |
Premium API documentation endpoint |
src/app/api/premium/ai/*/route.ts |
AI analysis endpoints |
src/app/api/premium/whales/*/route.ts |
Whale tracking endpoints |
src/app/api/premium/screener/*/route.ts |
Screener endpoints |
src/app/api/premium/smart-money/route.ts |
Smart money endpoint |
src/app/pricing/premium/page.tsx |
Premium pricing UI page |
| Category | Endpoint | Price | Description |
|---|---|---|---|
| AI | /api/premium/ai/sentiment |
$0.02 | News sentiment analysis |
| AI | /api/premium/ai/signals |
$0.05 | Trading signals |
| AI | /api/premium/ai/summary |
$0.01 | Market summary |
| AI | /api/premium/ai/compare |
$0.03 | Coin comparison |
| Whales | /api/premium/whales/transactions |
$0.05 | Whale transactions |
| Whales | /api/premium/whales/alerts |
$0.05 | Webhook alerts |
| Whales | /api/premium/wallets/analyze |
$0.10 | Wallet analysis |
| Whales | /api/premium/smart-money |
$0.05 | Smart money flow |
| Screener | /api/premium/screener/advanced |
$0.02 | Advanced screener |
| Data | /api/premium/history/full |
$0.05 | 5+ years history |
| Data | /api/premium/correlations |
$0.03 | Correlation matrix |
| Data | /api/premium/export/full |
$0.15 | Full database export |
| Pass | /api/premium/pass/hour |
$0.25 | 1 hour unlimited |
| Pass | /api/premium/pass/day |
$2.00 | 24 hour unlimited |
| Pass | /api/premium/pass/week |
$10.00 | 7 day unlimited |
| Provider | Price | x402 Advantage |
|---|---|---|
| CoinGecko Pro | $129/month | Pay only for what you use |
| CoinMarketCap | $99/month | No subscription needed |
| Messari | $249/month | Micropayments possible |
| Project | Stars | Description | What They Do Well |
|---|---|---|---|
| coinbase/x402 | 5,300+ | Reference implementation | Full SDK suite, multi-lang, production-ready |
| google-agentic-commerce/a2a-x402 | 200+ | Agent-to-Agent extension | AI agent monetization |
| daydreamsai/lucid-agents | 150+ | Protocol-agnostic agent SDK | Multi-protocol support |
| daydreamsai/facilitator | 100+ | Multi-chain facilitator | EVM, Solana, Starknet |
| nuwa-protocol/x402-exec | 50+ | Programmable settlement | Custom settlement hooks |
Most x402 examples require payment for ALL access. We offer:
// Free tier with generous limits
"/api/market/coins": { /* No payment required */ },
// Premium tier for advanced features
"/api/premium/market/coins": {
accepts: { price: "$0.001", ... },
// Full metadata, no rate limits
}Advantage: Lower barrier to entry, viral growth potential, gradual upgrade path.
Create a discoverable marketplace for AI agents:
import { declareDiscoveryExtension } from "@x402/extensions/bazaar";
export const GET = withX402(handler, {
accepts: { ... },
extensions: {
...declareDiscoveryExtension({
category: "crypto-market-data",
tags: ["bitcoin", "ethereum", "defi", "real-time"],
popularity: 4.5,
inputSchema: { coinId: "string", days: "number" },
outputSchema: {
example: { price: 50000, change24h: 2.5, volume: 1000000 },
},
}),
},
}, server);Advantage: AI agents can discover and use our API automatically via Bazaar extension.
Support user preference for payment chain:
accepts: [
// Let users choose their preferred chain
{ scheme: "exact", price: "$0.001", network: "eip155:8453", payTo: evmAddr }, // Base
{ scheme: "exact", price: "$0.001", network: "eip155:1", payTo: evmAddr }, // Ethereum
{ scheme: "exact", price: "$0.001", network: "eip155:137", payTo: evmAddr }, // Polygon
{ scheme: "exact", price: "$0.001", network: "solana:mainnet", payTo: solAddr }, // Solana
],Advantage: Users pay with their preferred chain, reducing friction.
Offer time-based access for heavy users:
"/api/premium/pass/hour": {
accepts: { price: "$0.10" },
description: "1 hour unlimited premium access",
// Returns JWT valid for 1 hour
},
"/api/premium/pass/day": {
accepts: { price: "$1.00" },
description: "24 hour unlimited premium access",
},Advantage: Power users get predictable costs; we get committed revenue.
Provide helpful 402 responses:
// Enhanced 402 response
{
"x402Version": 2,
"error": "payment_required",
"message": "This endpoint requires payment to access premium features",
"freeAlternative": "/api/market/coins?limit=100",
"pricing": {
"perRequest": "$0.001",
"hourlyPass": "$0.10",
"dailyPass": "$1.00",
},
"documentation": "https://docs.example.com/premium",
"accepts": [...]
}Advantage: Better developer experience, clear upgrade path, SEO for docs.
Custom paywall with crypto branding:
const paywallConfig = {
appName: 'Crypto Data Aggregator',
appLogo: '/logo.svg',
theme: 'dark',
accentColor: '#3b82f6',
supportedWallets: ['coinbase', 'metamask', 'phantom', 'rainbow'],
showPriceInUSD: true,
showPriceInCrypto: true, // Show USDC amount
customCopy: {
title: 'Unlock Premium Data',
description: 'Access detailed market analytics, historical data, and AI insights',
cta: 'Pay with Crypto',
},
};Advantage: Branded, trustworthy UI increases conversion.
Provide users visibility into their spending:
// GET /api/account/usage (free, requires wallet signature)
{
"wallet": "0x...",
"totalSpent": "$4.52",
"thisMonth": "$1.20",
"requests": 1200,
"endpoints": {
"/api/premium/market/history": { calls: 500, spent: "$2.50" },
"/api/premium/ai/analyze": { calls: 10, spent: "$0.50" },
},
"savedVsSubscription": "$124.48" // vs $129/month CoinGecko Pro
}Advantage: Transparency builds trust, shows value vs subscriptions.
Enable async workflows:
// POST /api/premium/alerts/subscribe
{
accepts: { price: "$0.05" },
description: "Subscribe to price alert webhook (24h)",
inputSchema: {
coinId: "string",
condition: "above|below",
threshold: "number",
webhookUrl: "string",
},
}Advantage: AI agents can subscribe to events, not just poll.
| Feature | Impact | Effort | Priority |
|---|---|---|---|
| Freemium model | High | Low | 🔴 P0 |
| Multi-chain support | High | Medium | 🟠 P1 |
| Bazaar discovery extension | Medium | Low | 🟠 P1 |
| Usage bundles/passes | Medium | Medium | 🟡 P2 |
| Analytics dashboard | Medium | High | 🟡 P2 |
| Custom paywall UI | Low | Medium | 🟢 P3 |
| Webhook support | Medium | High | 🟢 P3 |
This document will be updated as x402 implementation progresses.