Documentation
Everything you need to integrate paid APIs on Starknet.
Install
npm install starknet-x402
starknet and axios are included as dependencies. next is a peer dependency (server middleware only).
Server Setup
Add the payment middleware to your Next.js app. Any request to a matched route without a valid payment signature gets a 402 Payment Required response.
// middleware.ts
import { paymentMiddleware, TOKENS } from 'starknet-x402';
export const middleware = paymentMiddleware(
process.env.RECIPIENT_ADDRESS!,
{
'/api/weather': {
price: '10000', // 0.01 USDC
tokenAddress: TOKENS.USDC_SEPOLIA,
network: 'sepolia',
},
'/api/analytics': {
price: '100000', // 0.10 USDC
tokenAddress: TOKENS.USDC_SEPOLIA,
network: 'sepolia',
config: {
description: 'Premium analytics data',
maxTimeoutSeconds: 600,
},
},
},
{ url: process.env.FACILITATOR_URL! }
);
export const config = {
matcher: '/api/:path*',
};// app/api/weather/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({
city: 'Cairo',
temp: '34°C',
conditions: 'Sunny',
});
}Route config options
| Option | Type | Description |
|---|---|---|
| price | string | Amount in token smallest unit |
| tokenAddress | string | ERC-20 contract address |
| network | string | 'sepolia' | 'mainnet' (default: 'sepolia') |
| config.description | string? | Resource description |
| config.mimeType | string? | Response MIME type |
| config.maxTimeoutSeconds | number? | Settlement timeout (default: 300) |
Client Usage
The client handles the full 402 flow automatically — makes the request, receives payment requirements, signs an OutsideExecution via AVNU paymaster, and retries.
x402axios (recommended)
import { x402axios } from 'starknet-x402';
import { Account, RpcProvider } from 'starknet';
const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL });
const account = new Account(provider, address, privateKey);
// Automatic 402 handling — request, sign, pay, done
const result = await x402axios.get('https://api.example.com/api/weather', {
account,
network: 'starknet-sepolia',
});
console.log(result.data); // { city, temp, conditions }
console.log(result.settlement?.transaction); // tx hash on StarknetAll HTTP methods
// All HTTP methods supported
await x402axios.post(url, { account, network: 'starknet-sepolia', data: { query: '...' } });
await x402axios.put(url, { account, network: 'starknet-sepolia' });
await x402axios.patch(url, { account, network: 'starknet-sepolia' });
await x402axios.delete(url, { account, network: 'starknet-sepolia' });payAndRequest (native fetch)
import { payAndRequest } from 'starknet-x402';
import { Account, RpcProvider } from 'starknet';
const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL });
const account = new Account(provider, address, privateKey);
const response = await payAndRequest(
'https://api.example.com/api/weather',
account,
{ network: 'starknet-sepolia' },
);
const data = await response.json();Client options
| Option | Type | Description |
|---|---|---|
| account | Account | Starknet.js Account (used for signing) |
| network | string | 'starknet-sepolia' | 'starknet-mainnet' |
| paymasterUrl | string? | Custom paymaster URL (default: AVNU) |
| paymasterApiKey | string? | Paymaster API key |
Tokens & Pricing
import { TOKENS } from 'starknet-x402';
TOKENS.USDC_SEPOLIA // 0x0512fe...D8343
TOKENS.USDC_MAINNET // 0x03306...e93fb
TOKENS.STRK_SEPOLIA // 0x04718...c938d
TOKENS.ETH // 0x049d3...04dc7USDC pricing reference (6 decimals)
| USDC | price value |
|---|---|
| 0.001 | '1000' |
| 0.01 | '10000' |
| 0.10 | '100000' |
| 1.00 | '1000000' |
Paymaster
The SDK uses AVNU paymaster by default. Gas is sponsored — neither the user nor the server pays gas.
Custom paymaster
const result = await x402axios.get(url, {
account,
network: 'starknet-sepolia',
paymasterUrl: 'https://custom-paymaster.com',
paymasterApiKey: 'your-api-key',
});Environment Variables
# .env STARKNET_RPC_URL=https://starknet-sepolia.g.alchemy.com/starknet/version/rpc/v0_8/... RECIPIENT_ADDRESS=0x... # your address that receives payments FACILITATOR_URL=https://... # facilitator service URL
Protocol Flow
Client Server Facilitator
| | |
|-- GET /api/data ------------->| |
|<-- 402 + PAYMENT-REQUIRED | |
| | |
|-- sign OutsideExecution | |
| (SNIP-9, AVNU paymaster) | |
| | |
|-- GET /api/data ------------->| |
| + PAYMENT-SIGNATURE | |
| |-- POST /verify ------------->|
| |<-- { isValid: true } --------|
| |-- POST /settle ------------->|
| |<-- { success, txHash } ------|
| | |
|<-- 200 + data ----------------| |
| + PAYMENT-RESPONSE | |- Client requests a protected endpoint
- Server returns
402with payment requirements in thePAYMENT-REQUIREDheader - Client signs an OutsideExecution (SNIP-9) containing
token.transfer(), built via AVNU paymaster - Client retries with the
PAYMENT-SIGNATUREheader - Server forwards to facilitator for verification and on-chain settlement
- Client receives
200+ data +PAYMENT-RESPONSEheader with tx hash
Headers
| Header | Direction | Description |
|---|---|---|
| PAYMENT-REQUIRED | Server → Client | Base64 payment requirements (on 402) |
| PAYMENT-SIGNATURE | Client → Server | Base64 signed payment payload |
| PAYMENT-RESPONSE | Server → Client | Base64 settlement result (tx hash) |
Facilitator API
| Endpoint | Method | Description |
|---|---|---|
| /verify | POST | Validate payment signature against requirements |
| /settle | POST | Execute payment on-chain via AVNU paymaster |
| /supported | GET | Returns supported schemes and networks |
AI Agent Prompt
Copy this file into your project or feed it to an AI agent to let it integrate starknet-x402 into any app. Available at /llms.txt.
The prompt contains the full SDK API surface, code examples for both server and client, token addresses, and integration steps. AI agents can use it to add paid API endpoints to any Next.js app without reading the full docs.