Skip to content

Latest commit

 

History

History
386 lines (300 loc) · 12.1 KB

File metadata and controls

386 lines (300 loc) · 12.1 KB

x402 Pay-Per-Request API

Enable cryptocurrency micropayments for premium API access using the x402 protocol by Coinbase. Pay only for what you use with USDC on Base.

Overview

x402 is an open payment protocol that enables HTTP-native micropayments. Instead of subscriptions, you pay per API request using cryptocurrency.

┌──────────────────────────────────────────────────────────────┐
│  Client Request → x402 Payment Check → API Response         │
│                                                              │
│  1. Request premium endpoint                                 │
│  2. Server returns 402 Payment Required + payment details    │
│  3. Client pays with USDC (Base network)                     │
│  4. Server verifies payment and returns data                 │
│  5. Transaction settles on-chain                             │
└──────────────────────────────────────────────────────────────┘

Quick Start

Using the SDK

import { x402Client } from '@x402/fetch';

const client = x402Client({
  baseURL: 'https://cryptocurrency.cv',
  wallet: yourWalletClient, // viem wallet
});

// Make a premium request - payment handled automatically
const signals = await client.get('/api/premium/ai/signals?coin=bitcoin');

Using cURL with Payment Header

# 1. First request returns 402 with payment details
curl -i https://cryptocurrency.cv/api/premium/ai/signals?coin=bitcoin

# Response:
# HTTP/2 402 Payment Required
# X-Payment-Required: {"price":"0.05","network":"base","asset":"USDC",...}

# 2. Pay and include payment proof in header
curl -H "X-Payment: <payment_proof>" \
  https://cryptocurrency.cv/api/premium/ai/signals?coin=bitcoin

Pricing Tiers

Free Tier (No Payment Required)

The exact free list is FREE_TIER_PATTERNS and EXEMPT_PATTERNS in src/middleware/config.ts. Everything below needs no key, no payment, and no browser User-Agent: curl is a first-class client.

Free tier (120 requests/hour per IP, anonymous):

Endpoint pattern Description
/api/news* Latest crypto news, categories, international, streaming
/api/prices* Market prices
/api/market* Market overview, top coins
/api/coins* Coin list and metadata
/api/sources* The 358-source catalog, plus /api/sources/health
/api/archive* Historical news archive
/api/article*, /api/articles* Individual articles and listings
/api/signals* Market signals
/api/exchanges* Exchange data
/api/rss*, /api/atom* RSS and Atom feeds
/api/fear-greed Fear & Greed Index
/api/trending Trending topics
/api/unlocks Token unlock schedule

Anonymous /api/news responses are capped at 3 articles and say so (limited: true, maxResults: 3). The site feeds at /feed.xml and /feed.json are uncapped at 50 items.

Exempt (no rate limit, no payment at all):

Endpoint Description
/api/health Health status and per-subsystem checks
/api/version Running commit, build time, Cloud Run revision
/api/openapi.json OpenAPI 3.1 spec
/api/docs Swagger UI
/api/mcp Hosted MCP endpoint (Streamable HTTP)
/api/llms.txt, /api/llms-full.txt LLM-oriented reference
/api/.well-known/*, /api/well-known/* Agent and payment discovery
/api/sample Tiny preview payload
/api/sse, /api/ws Real-time streams
/api/register, /api/keys/* Key registration and management

Endpoints not in either list (/api/search, /api/bitcoin, /api/defi, /api/breaking, the AI surface, premium routes) need an X-API-Key or an x402 payment.

Pay-Per-Request (v1 API)

Basic premium endpoints with micro-pricing:

Endpoint Price Description
/api/v1/coins $0.001 Extended coin list
/api/v1/coin $0.002 Detailed coin data
/api/v1/defi $0.002 DeFi protocol data
/api/v1/defi/yields $0.003 DeFi yield rates
/api/v1/ohlcv $0.003 OHLCV candle data
/api/v1/historical $0.005 Historical prices
/api/v1/correlation $0.005 Asset correlations
/api/v1/whale-alerts $0.005 Whale transactions
/api/v1/export $0.01 Data exports

Premium API Endpoints

High-value AI and analytics endpoints:

AI-Powered Analysis

Endpoint Price Description
/api/premium/ai/summary $0.01 AI market summary
/api/premium/ai/explain $0.01 AI explanations
/api/premium/ai/sentiment $0.02 Sentiment analysis
/api/premium/ai/compare $0.03 AI coin comparison
/api/premium/ai/signals $0.05 Buy/sell signals
/api/premium/ai/analyze $0.05 Deep market analysis

Whale & Smart Money

Endpoint Price Description
/api/premium/smart-money $0.05 Institutional flows
/api/premium/whales/transactions $0.05 Whale movements
/api/premium/whales/alerts $0.05 Real-time alerts
/api/premium/wallets/analyze $0.10 Wallet deep dive

Screener & Signals

Endpoint Price Description
/api/premium/screener/advanced $0.02 Advanced screener
/api/premium/momentum $0.02 Momentum analysis
/api/premium/breakouts $0.03 Breakout detection
/api/premium/undervalued $0.03 Undervalued coins

Data & Exports

Endpoint Price Description
/api/premium/market/coins $0.001 500+ coins data
/api/premium/market/history $0.005 5-year history
/api/premium/correlations $0.03 Correlation matrix
/api/premium/history/full $0.05 Complete history
/api/premium/backtest $0.10 Strategy backtest
/api/premium/export/portfolio $0.10 Portfolio export
/api/premium/export/full $0.15 Full database

Payment Networks

Payments are accepted on:

Network Asset Status
Base USDC ✅ Live
Ethereum USDC ✅ Live
Solana USDC 🔜 Coming

Integration Guide

JavaScript/TypeScript

import { createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
import { x402Client } from '@x402/fetch';

// Setup wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const wallet = createWalletClient({
  account,
  chain: base,
  transport: http(),
});

// Create x402 client
const api = x402Client({
  baseURL: 'https://cryptocurrency.cv',
  wallet,
});

// Make premium requests
async function getAISignals(coin: string) {
  const response = await api.get(`/api/premium/ai/signals?coin=${coin}`);
  return response.data;
}

// Signals cost $0.05 per request
const btcSignals = await getAISignals('bitcoin');
console.log(btcSignals);
// { signal: 'BUY', confidence: 0.85, indicators: [...] }

Python

from x402 import X402Client
from eth_account import Account

# Setup wallet
account = Account.from_key(os.environ['PRIVATE_KEY'])

# Create client
client = X402Client(
    base_url='https://cryptocurrency.cv',
    wallet=account,
    network='base'
)

# Make premium request
signals = client.get('/api/premium/ai/signals', params={'coin': 'bitcoin'})
print(signals)

Alternative: API Keys

Don't want to deal with crypto payments? Use traditional API keys:

# Get an API key from the dashboard
curl -H "X-API-Key: your_api_key" \
  https://cryptocurrency.cv/api/premium/ai/signals?coin=bitcoin

API keys are available through monthly subscriptions. See Premium Plans for pricing.

How It Works

Payment Flow

sequenceDiagram
    participant C as Client
    participant S as API Server
    participant F as x402 Facilitator
    participant B as Base Network
    
    C->>S: GET /api/premium/ai/signals
    S->>C: 402 Payment Required + Price
    C->>F: Create Payment Intent
    F->>B: Submit Transaction
    B->>F: Confirm Payment
    F->>C: Payment Proof
    C->>S: GET /api/premium/ai/signals + Payment Header
    S->>F: Verify Payment
    F->>S: Valid
    S->>C: 200 OK + Data
Loading

Payment Verification

The server verifies payments using the x402 facilitator:

  1. Signature Check - Validates payment proof signature
  2. Amount Check - Confirms correct amount paid
  3. Expiry Check - Ensures payment hasn't expired
  4. Replay Prevention - Prevents double-spending

Discovery

Agents find these endpoints through the OpenAPI document, which is the canonical machine-readable contract:

curl https://cryptocurrency.cv/openapi.json

Every operation in it declares its price, its input parameters, its response schema, and a 402 response:

"/api/premium/ai/signals": {
  "get": {
    "summary": "AI-generated trading signals",
    "x-payment-info": {
      "price": { "mode": "fixed", "currency": "USD", "amount": "0.050000" },
      "protocols": [{ "x402": {} }]
    },
    "responses": {
      "200": { "content": { "application/json": { "schema": { /* ... */ } } } },
      "402": { "description": "Payment Required" }
    }
  }
}

Two supporting surfaces exist alongside it:

curl https://cryptocurrency.cv/.well-known/x402   # per-resource accepts + schemas
curl https://cryptocurrency.cv/llms.txt           # prose summary for LLMs

How the document is generated, what the runtime 402 must match, and how to audit both before registering on x402scan: x402scan-discovery.md.

Error Handling

402 Payment Required

Returned when payment is needed. The body is an x402 v2 challenge: accepts carries what to pay and where, in token atomic units, and outputSchema carries what the endpoint takes and returns.

{
  "x402Version": 2,
  "error": "Payment Required",
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:42161",
    "amount": "50000",             // $0.05 of 6-decimal USDC
    "asset": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
    "payTo": "0x...",
    "maxTimeoutSeconds": 60,
    "extra": { "name": "USD Coin", "version": "2" },
    "outputSchema": { "input": { /* ... */ }, "output": { /* ... */ } }
  }],
  "resource": { "url": "...", "description": "...", "mimeType": "application/json" },
  "extensions": { "bazaar": { /* ... */ } }
}

A WWW-Authenticate: Payment ... header accompanies it for MPP clients. Any x402 SDK reads accepts and handles the rest; see x402scan-discovery.md for the full shape.

Payment Errors

Code Description
INSUFFICIENT_FUNDS Wallet balance too low
PAYMENT_EXPIRED Payment proof expired
INVALID_SIGNATURE Invalid payment signature
ALREADY_USED Payment proof already used

Rate Limits

Even with payment, rate limits apply to prevent abuse:

Category Limit
AI Endpoints 30-60/min
Whale Data 30-60/min
Screener 60/min
Market Data 100/min
Exports 5-20/min

Security

  • All payments use cryptographic signatures
  • No credit cards or personal data stored
  • Payments are non-custodial (your wallet → our wallet)
  • On-chain verification ensures transparency

Resources


Related Documentation