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
// 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 — your API route (unchanged)
// 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

OptionTypeDescription
pricestringAmount in token smallest unit
tokenAddressstringERC-20 contract address
networkstring'sepolia' | 'mainnet' (default: 'sepolia')
config.descriptionstring?Resource description
config.mimeTypestring?Response MIME type
config.maxTimeoutSecondsnumber?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 Starknet

All 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

OptionTypeDescription
accountAccountStarknet.js Account (used for signing)
networkstring'starknet-sepolia' | 'starknet-mainnet'
paymasterUrlstring?Custom paymaster URL (default: AVNU)
paymasterApiKeystring?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...04dc7

USDC pricing reference (6 decimals)

USDCprice 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.

Sepolia: https://sepolia.paymaster.avnu.fi
Mainnet: https://starknet.paymaster.avnu.fi

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         |                              |
  1. Client requests a protected endpoint
  2. Server returns 402 with payment requirements in the PAYMENT-REQUIRED header
  3. Client signs an OutsideExecution (SNIP-9) containing token.transfer(), built via AVNU paymaster
  4. Client retries with the PAYMENT-SIGNATURE header
  5. Server forwards to facilitator for verification and on-chain settlement
  6. Client receives 200 + data + PAYMENT-RESPONSE header with tx hash

Headers

HeaderDirectionDescription
PAYMENT-REQUIREDServer → ClientBase64 payment requirements (on 402)
PAYMENT-SIGNATUREClient → ServerBase64 signed payment payload
PAYMENT-RESPONSEServer → ClientBase64 settlement result (tx hash)

Facilitator API

EndpointMethodDescription
/verifyPOSTValidate payment signature against requirements
/settlePOSTExecute payment on-chain via AVNU paymaster
/supportedGETReturns 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.