@krexa/x402
v0.2.0
Published
Express middleware for x402 payment-gated APIs on Solana — 3 lines to monetize any API with USDC
Downloads
21
Maintainers
Readme
@krexa/x402
Express middleware for x402 payment-gated APIs on Solana. Monetize any API with USDC micropayments in 3 lines.
Quick Start
npm install @krexa/x402import express from 'express';
import { paygate } from '@krexa/x402';
const app = express();
app.use(express.json());
// Create a payment gate — YOUR wallet, YOUR price
const pay = paygate({
merchant: 'YOUR_SOLANA_WALLET_ADDRESS',
priceUsdc: 0.01, // $0.01 per call
});
// Free endpoint
app.get('/health', (req, res) => res.json({ status: 'ok' }));
// Paid endpoint — agents pay $0.01 USDC to call this
app.get('/api/data', pay, (req, res) => {
const { payer } = (req as any).x402;
res.json({ data: 'premium content', paidBy: payer });
});
app.listen(3000);That's it. Your API now accepts USDC payments on Solana.
How It Works
Agent Your API Solana
| | |
|--- GET /api/data ------------>| |
| | |
|<-- 402 Payment Required ------| |
| { price: 0.01, | |
| merchant: "...", | |
| payWith: { ... } } | |
| | |
|--- USDC transfer ($0.01) ----------------------------> |
|<-- tx signature --------------------------------------| |
| | |
|--- GET /api/data ------------>| |
| X-PAYMENT: <tx-sig> |--- verify on-chain ---------> |
| |<-- confirmed + amount OK -----|
|<-- 200 OK + response --------| |- Agent calls your API without payment → gets 402 with instructions
- Agent sends USDC to your wallet on Solana (direct SPL transfer)
- Agent retries with
X-PAYMENT: <solana-tx-signature>header - Middleware verifies the tx on-chain (recipient, amount, freshness, replay)
- Your handler runs, agent gets the response
You get paid directly — USDC goes to your wallet. Krexa is not in the middle.
Agent-Side Payment
Agents can pay using any of these methods:
# Krexa CLI
krexa pay YOUR_WALLET 0.01
# Krexa MCP (for AI agents)
krexa_pay({ recipient: "YOUR_WALLET", amount: 0.01 })
# Direct USDC transfer (any Solana wallet)
# Send 0.01 USDC to YOUR_WALLET, use the tx signature as proofConfiguration
const pay = paygate({
// Required
merchant: 'YOUR_SOLANA_WALLET', // receives USDC payments
priceUsdc: 0.01, // price per call
// Optional
rpcUrl: 'https://api.mainnet-beta.solana.com', // Solana RPC
maxAgeSec: 300, // max tx age (default: 5 min)
description: 'Premium data feed', // shown in 402 response
usedSignatures: myRedisSet, // custom replay protection (default: in-memory)
});Different Prices Per Endpoint
const cheapPay = paygate({ merchant: WALLET, priceUsdc: 0.001 });
const expensivePay = paygate({ merchant: WALLET, priceUsdc: 0.10 });
app.get('/api/price/:token', cheapPay, priceHandler); // $0.001
app.post('/api/analyze', expensivePay, analyzeHandler); // $0.10Accessing Payment Info
After verification, payment details are attached to req.x402:
app.get('/api/data', pay, (req, res) => {
const { signature, payer, amountUsdc, merchant } = (req as any).x402;
console.log(`Paid by ${payer}, tx: ${signature}`);
res.json({ data: '...' });
});402 Response Format
When an agent calls without payment, your API returns:
{
"error": "Payment Required",
"x402Version": 1,
"price": 0.01,
"currency": "USDC",
"network": "solana:mainnet-beta",
"merchant": "YOUR_WALLET",
"payWith": {
"transfer": "Send 0.01 USDC to YOUR_WALLET on Solana, then retry with header X-PAYMENT: <tx-signature>",
"mcp": "krexa_pay({ recipient: \"YOUR_WALLET\", amount: 0.01 })",
"cli": "krexa pay YOUR_WALLET 0.01"
}
}Production Tips
Replay Protection with Redis
By default, used signatures are cached in-memory (lost on restart). For production, use Redis:
import { createClient } from 'redis';
const redis = createClient();
await redis.connect();
// Create a Set-like interface backed by Redis
const usedSigs = {
has: async (sig: string) => !!(await redis.get(`x402:${sig}`)),
add: async (sig: string) => { await redis.set(`x402:${sig}`, '1', { EX: 86400 }); },
} as unknown as Set<string>;
const pay = paygate({ merchant: WALLET, priceUsdc: 0.01, usedSignatures: usedSigs });Use a Fast RPC
The public Solana RPC is rate-limited. For production, use Helius, Quicknode, or Triton:
const pay = paygate({
merchant: WALLET,
priceUsdc: 0.01,
rpcUrl: 'https://mainnet.helius-rpc.com/?api-key=YOUR_KEY',
});Revenue Through Krexa Payment Router
If agents pay through Krexa's payment router (via krexa_pay or execute_payment), the payment is automatically split:
- 97% → Your wallet (merchant)
- 2% → Krexa vault (TVL)
- 1% → Insurance fund
This also builds the agent's credit score (Krexit Score), unlocking larger credit lines.
Requirements
- Node.js 18+
- Express 4+ or 5+
- Solana mainnet USDC (
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)
