x402pp-server
Server middleware for API providers to monetize endpoints
Installation
npm install x402pp-server express @solana/web3.jsx402Middleware
Express middleware that handles the complete x402++ protocol automatically.
Basic Setup
import express from 'express';
import { Connection, Keypair } from '@solana/web3.js';
import { x402Middleware } from 'x402pp-server';
const app = express();
const connection = new Connection('https://api.devnet.solana.com');
const wallet = Keypair.generate();
// Apply middleware to protected routes
app.use('/api/*', x402Middleware({
connection: Connection, // Solana connection
wallet: Keypair, // Provider's keypair
endpoint: string, // Your API URL
pricing: {
basePrice: number,
token: 'SOL' | 'USDC' | 'USDT' | 'BONK'
},
sla: {
maxLatencyMs?: number,
minUptimePercent?: number
},
sessionDurationMs?: number, // Default: 10 minutes
offerExpirationMs?: number // Default: 1 minute
}));What the Middleware Does
Request Flow: 1. Request arrives at /api/endpoint 2. Middleware checks for X-402-Session-Id header ┌─ NO SESSION ────────────────────────────┐ │ │ │ • Check for X-402-Intent header │ │ • Generate signed Offer │ │ • Return 402 + X-402-Offer header │ │ │ └──────────────────────────────────────────┘ ┌─ HAS SESSION ───────────────────────────┐ │ │ │ • Validate session exists & active │ │ • Check balance >= pricePerRequest │ │ • Attach session to req.x402Session │ │ • Call your route handler │ │ • Generate signed receipt │ │ • Deduct from session balance │ │ • Return response + X-402-Receipt │ │ │ └──────────────────────────────────────────┘
Using in Your Routes
Protected API Endpoint
app.post('/api/inference', async (req, res) => {
// Session automatically attached by middleware
const session = req.x402Session;
console.log('Session ID:', session.sessionId);
console.log('Balance:', session.remainingBalance);
console.log('Request #:', session.requestCount + 1);
// Your API logic
const result = await runInference(req.body);
// Middleware automatically:
// - Generates receipt
// - Signs with Ed25519
// - Verifies SLA
// - Deducts from balance
// - Sends X-402-Receipt header
return res.x402Receipt?.(result);
});Pricing Strategies
Static Pricing
pricing: {
basePrice: 0.01,
token: 'USDC'
}
// Same price for all requestsLoad-Based Pricing
import { LoadBasedPricingStrategy } from 'x402pp-server';
const pricing = new LoadBasedPricingStrategy(
0.01, // base price
'USDC',
() => {
// Return 0-1 representing load
return getCurrentLoad() / maxLoad;
}
);
// Price scales with server load:
// 0% load → $0.01
// 50% load → $0.015
// 100% load → $0.02Time-Based Pricing
import { TimeBasedPricingStrategy } from 'x402pp-server';
const pricing = new TimeBasedPricingStrategy(
0.02, // peak price
0.01, // off-peak price
{ start: 9, end: 17 }, // 9 AM - 5 PM peak hours
'USDC'
);Complete Provider Example
provider.ts
1import express from 'express';
2import { Connection, Keypair } from '@solana/web3.js';
3import { x402Middleware } from 'x402pp-server';
4
5const app = express();
6app.use(express.json());
7
8const connection = new Connection('https://api.devnet.solana.com');
9const wallet = Keypair.generate();
10
11// Configure x402++ middleware
12app.use('/api/*', x402Middleware({
13 connection,
14 wallet,
15 endpoint: 'https://your-api.com',
16 pricing: { basePrice: 0.01, token: 'USDC' },
17 sla: { maxLatencyMs: 2000, minUptimePercent: 99.5 }
18}));
19
20// Weather API
21app.post('/api/weather', async (req, res) => {
22 const { city } = req.body;
23 const data = await getWeatherData(city);
24 return res.x402Receipt?.(data);
25});
26
27// AI Inference API
28app.post('/api/inference', async (req, res) => {
29 const { prompt } = req.body;
30 const response = await runAI(prompt);
31 return res.x402Receipt?.(response);
32});
33
34app.listen(3000, () => {
35 console.log('✅ API monetized with Corex402!');
36});