Skip to content

x402 Payment Protocol

x402 is an open, internet-native payment protocol that leverages the HTTP 402 "Payment Required" status code for seamless, low-fee digital dollar transactions. Tributary provides a complete implementation of x402 v2 with support for both subscription and pay-as-you-go payment models.

Overview

x402 enables frictionless payments for API resources and content without requiring users to register, provide credit cards, or complete complex authentication. Payments are embedded directly into the HTTP request/response flow, making it ideal for:

  • AI Agents: Autonomous agents that need to pay for services programmatically
  • API Monetization: Pay-per-use access to premium APIs and data sources
  • Content Platforms: Metered access to articles, videos, or digital goods
  • Cloud Services: Usage-based billing for compute, storage, or networking

Key Features

  • No Registration: Users pay without creating accounts or providing personal information
  • Non-Custodial: Funds stay in user wallets until payment is executed
  • Multi-Chain: Support for Solana and EVM-compatible networks via CAIP-2 identifiers
  • Flexible Payment Models: Subscription (deferred) and pay-as-you-go schemes
  • Low Fees: Sub-cent transaction costs on Solana
  • Fast Settlement: Sub-second payment confirmation

Payment Schemes

Deferred (Subscription)

The deferred scheme enables recurring subscriptions where payment is authorized once and executed automatically on a schedule.

{
  "scheme": "deferred",
  "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
  "amount": 100000,
  "currency": "USDC",
  "paymentFrequency": "monthly",
  "autoRenew": true
}

Pay-as-you-go

The x402://payg scheme enables usage-based billing with configurable limits per period.

{
  "scheme": "x402://payg",
  "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
  "amount": 100000,
  "maxAmountPerPeriod": 1000000,
  "periodLengthSeconds": 86400,
  "maxChunkAmount": 100000
}

Quick Start

Server Implementation

import express from "express";
import { X402Server } from "@tributary-so/sdk-x402";

const app = express();
const server = new X402Server({
  rpcUrl: "https://api.devnet.solana.com",
  jwtSecret: process.env.JWT_SECRET!,
});

// Pay-as-you-go middleware
app.use(
  "/api/premium",
  server.middleware({
    scheme: "x402://payg",
    network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
    amount: 100000, // 0.1 USDC
    recipient: "8EVBvLDVhJUw1nkAUp73mPowviVFK9Wza5ba1GRANEw1",
    gateway: "ConTf7Qf3r1QoDDLcLTMVxLrzzvPTPrwzEYJrjqm1U7",
    tokenMint: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
    maxAmountPerPeriod: 1000000, // $1 per day max
    periodLengthSeconds: 86400,
    maxChunkAmount: 100000, // $0.10 per request max
  })
);

app.listen(3000);

Client Implementation

import { X402Client } from "@tributary-so/sdk-x402";

const client = new X402Client({
  rpcUrl: "https://api.devnet.solana.com",
  wallet: yourKeypair,
});

// Create payment and get JWT
const result = await client.createPayment({
  resource: "https://api.example.com/premium",
  scheme: "x402://payg",
  network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
  amount: 100000,
  recipient: "8EVBvLDVhJUw1nkAUp73mPowviVFK9Wza5ba1GRANEw1",
  gateway: "ConTf7Qf3r1QoDDLcLTMVxLrzzvPTPrwzEYJrjqm1U7",
  tokenMint: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
});

// Use JWT for subsequent requests
const response = await fetch("https://api.example.com/premium", {
  headers: {
    Authorization: `Bearer ${result.jwt}`,
  },
});

HTTP Headers

x402 v2 uses standard HTTP headers (no deprecated X-* prefix):

Header Direction Description
Payment Client → Server Base64-encoded payment payload
Payment-Required Server → Client Payment requirements when 402 is returned
Payment-Response Server → Client Payment confirmation details
Authorization Client → Server JWT token for authenticated access

Payment Flow

1. Initial Request

GET /premium HTTP/1.1
Host: api.example.com
Accept: application/json

2. 402 Response with Payment Requirements

HTTP/1.1 402 Payment Required
Payment-Required: scheme="x402://payg", network="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", resource="https://api.example.com/premium", id="payg_1234567890_abc", amount=100000, currency="USDC", recipient="8EVBv...", gateway="ConT...", tokenMint="4zMM..."

{"accepts":[{"scheme":"x402://payg",...}]}

3. Payment Submission

GET /premium HTTP/1.1
Host: api.example.com
Payment: eyJ4MDYyVmVyc2lvbiI6Miwi...

HTTP/1.1 200 OK
Payment-Response: scheme="x402://payg", network="solana:...", id="payg_1234567890_abc", timestamp=1699999999

{"jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","message":"Payment successful"}

4. Subsequent Requests with JWT

GET /premium HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

HTTP/1.1 200 OK

{"data":"Premium content here"}

Middleware Options

X402MiddlewareConfig

Parameter Type Required Description
scheme deferred | x402://payg Yes Payment scheme
network string Yes CAIP-2 chain identifier
amount number Yes Payment amount in smallest units
recipient string Yes Recipient wallet address
gateway string Yes Gateway/facilitator address
tokenMint string Yes Token mint address
paymentFrequency string No Payment frequency (subscriptions)
autoRenew boolean No Auto-renew flag (subscriptions)
maxRenewals number | null No Maximum renewals (subscriptions)
maxAmountPerPeriod number No Max per period (pay-as-you-go)
periodLengthSeconds number No Period length in seconds (pay-as-you-go)
maxChunkAmount number No Max chunk amount (pay-as-you-go)

Usage Metering

The x402 implementation includes built-in usage metering for pay-as-you-go payments:

import { UsageTracker, TokenMeter, ComputeMeter } from "@tributary-so/x402";

// Track AI API usage
const usage = TokenMeter.fromOpenAI(response);
tracker.trackUsage(requestId, usage, { model: "gpt-4" });

// Get period summary
const summary = tracker.getCurrentPeriod();
console.log(`Tokens used: ${summary.totalUsage["tokens.total"]}`);
console.log(`Cost: ${summary.totalCost}`);

Integration with Tributary

x402 builds on Tributary's smart contract infrastructure:

  • Non-Custodial: Funds stay in user wallets
  • Automated Execution: Smart contracts handle recurring payments
  • Token Delegation: One-time approval enables unlimited payments
  • Fee Structure: Protocol fees + gateway fees

See Pay-as-you-go Payments and Smart Contract for more details.