Get the FREE Ultimate OpenClaw Setup Guide →

x402

npx machina-cli add skill tenequm/claude-plugins/x402 --openclaw
Files (1)
SKILL.md
10.8 KB

x402 Protocol Development

x402 is an open standard (Apache-2.0, by Coinbase) that activates the HTTP 402 Payment Required status code for programmatic, on-chain payments. No accounts, sessions, or API keys required - clients pay with signed crypto transactions directly over HTTP.

When to Use

  • Building a paid API that accepts crypto micropayments
  • Adding paywall to web content or endpoints
  • Enabling AI agents to autonomously pay for resources
  • Integrating MCP tools that require payment
  • Building agent-to-agent (A2A) payment flows
  • Working with EVM (Base, Ethereum, MegaETH), Solana, or Aptos payment settlement
  • Implementing usage-based billing with the upto scheme (LLM tokens, bandwidth, compute)

Core Architecture

Three roles in every x402 payment:

  1. Resource Server - protects endpoints, returns 402 with payment requirements
  2. Client - signs payment authorization, retries request with payment header
  3. Facilitator - verifies signatures, settles transactions on-chain

Payment flow (HTTP transport):

Client -> GET /resource -> Server returns 402 + PAYMENT-REQUIRED header
Client -> signs payment -> retries with PAYMENT-SIGNATURE header
Server -> POST /verify to Facilitator -> POST /settle to Facilitator
Server -> returns 200 + PAYMENT-RESPONSE header + resource data

Quick Start: Seller (TypeScript + Express)

import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

const app = express();
const payTo = "0xYourWalletAddress";

const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const server = new x402ResourceServer(facilitator)
  .register("eip155:84532", new ExactEvmScheme());

app.use(
  paymentMiddleware(
    {
      "GET /weather": {
        accepts: [
          { scheme: "exact", price: "$0.001", network: "eip155:84532", payTo },
        ],
        description: "Weather data",
        mimeType: "application/json",
      },
    },
    server,
  ),
);

app.get("/weather", (req, res) => {
  res.json({ weather: "sunny", temperature: 70 });
});

app.listen(4021);

Install: npm install @x402/express @x402/core @x402/evm

Quick Start: Buyer (TypeScript + Axios)

import { x402Client, wrapAxiosWithPayment } from "@x402/axios";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import axios from "axios";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });

const api = wrapAxiosWithPayment(axios.create(), client);
const response = await api.get("http://localhost:4021/weather");
// Payment handled automatically on 402 response

Install: npm install @x402/axios @x402/evm viem

Quick Start: Seller (Python + FastAPI)

from fastapi import FastAPI
from x402.http import FacilitatorConfig, HTTPFacilitatorClient, PaymentOption
from x402.http.middleware.fastapi import PaymentMiddlewareASGI
from x402.http.types import RouteConfig
from x402.mechanisms.evm.exact import ExactEvmServerScheme
from x402.server import x402ResourceServer

app = FastAPI()

facilitator = HTTPFacilitatorClient(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServer(facilitator)
server.register("eip155:84532", ExactEvmServerScheme())

routes = {
    "GET /weather": RouteConfig(
        accepts=[PaymentOption(scheme="exact", pay_to="0xYourAddress", price="$0.001", network="eip155:84532")],
        mime_type="application/json",
        description="Weather data",
    ),
}
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)

@app.get("/weather")
async def get_weather():
    return {"weather": "sunny", "temperature": 70}

Install: pip install "x402[fastapi,evm]"

Quick Start: Seller (Go + Gin)

import (
    x402http "github.com/coinbase/x402/go/http"
    ginmw "github.com/coinbase/x402/go/http/gin"
    evm "github.com/coinbase/x402/go/mechanisms/evm/exact/server"
)

facilitator := x402http.NewHTTPFacilitatorClient(&x402http.FacilitatorConfig{URL: facilitatorURL})

routes := x402http.RoutesConfig{
    "GET /weather": {
        Accepts: x402http.PaymentOptions{
            {Scheme: "exact", Price: "$0.001", Network: "eip155:84532", PayTo: evmAddress},
        },
        Description: "Weather data",
        MimeType:    "application/json",
    },
}

r.Use(ginmw.X402Payment(ginmw.Config{
    Routes:      routes,
    Facilitator: facilitator,
    Schemes:     []ginmw.SchemeConfig{{Network: "eip155:84532", Server: evm.NewExactEvmScheme()}},
}))

Install: go get github.com/coinbase/x402/go

Multi-Network Support (EVM + Solana)

Servers can accept payment on multiple networks simultaneously:

import { ExactEvmScheme } from "@x402/evm/exact/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";

const server = new x402ResourceServer(facilitator)
  .register("eip155:84532", new ExactEvmScheme())
  .register("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", new ExactSvmScheme());

// Route config with both networks
"GET /weather": {
  accepts: [
    { scheme: "exact", price: "$0.001", network: "eip155:84532", payTo: evmAddress },
    { scheme: "exact", price: "$0.001", network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", payTo: svmAddress },
  ],
}

Clients register both schemes and auto-select based on server requirements:

const client = new x402Client();
registerExactEvmScheme(client, { signer: evmSigner });
registerExactSvmScheme(client, { signer: svmSigner });

Supported Networks

NetworkCAIP-2 IDStatus
Base Mainneteip155:8453Mainnet
Base Sepoliaeip155:84532Testnet
MegaETH Mainneteip155:4326Mainnet (USDM default, 18 decimals)
Solana Mainnetsolana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpMainnet
Solana Devnetsolana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1Testnet
Aptos Mainnetaptos:1Mainnet (TypeScript SDK only)
Aptos Testnetaptos:2Testnet (TypeScript SDK only)
Avalancheeip155:43114Via community facilitators

Default facilitator (https://x402.org/facilitator) supports Base Sepolia and Solana Devnet.

SDK Packages

TypeScript (npm)

PackagePurpose
@x402/coreCore types, client, server, facilitator
@x402/evmEVM scheme (EIP-3009 + Permit2)
@x402/svmSolana scheme (SPL TransferChecked)
@x402/aptosAptos scheme (Fungible Asset transfers)
@x402/expressExpress middleware
@x402/honoHono edge middleware
@x402/nextNext.js middleware
@x402/axiosAxios interceptor
@x402/fetchFetch wrapper
@x402/paywallBrowser paywall UI
@x402/mcpMCP client + server
@x402/extensionsBazaar, payment-identifier, sign-in-with-x

Python (pip)

pip install "x402[httpx]"      # Async HTTP client
pip install "x402[requests]"   # Sync HTTP client
pip install "x402[fastapi]"    # FastAPI server
pip install "x402[flask]"      # Flask server
pip install "x402[svm]"        # Solana support

Go

go get github.com/coinbase/x402/go

Key Concepts

  • Client/Server/Facilitator: The three roles in every payment. Client signs, server enforces, facilitator settles on-chain. See references/core-concepts.md
  • Wallet: Both payment mechanism and identity for buyers/sellers. See references/core-concepts.md
  • Networks & Tokens: CAIP-2 identifiers, EIP-3009 tokens on EVM, SPL on Solana, custom token config. See references/core-concepts.md
  • Scheme: Payment method. exact = transfer exact amount (production-ready); upto = authorize max, settle actual usage (spec finalized, not yet supported by facilitators). See references/evm-scheme.md, references/svm-scheme.md, references/upto-scheme.md, references/aptos-scheme.md
  • Transport: How payment data is transmitted (HTTP headers, MCP _meta, A2A metadata). See references/transports.md
  • Extensions: Optional features (bazaar discovery, payment-identifier idempotency, sign-in-with-x auth, gas sponsoring). See references/extensions.md
  • Hooks: Lifecycle callbacks on client/server/facilitator (TS, Python, Go). See references/lifecycle-hooks.md
  • Protocol types: PaymentRequired, PaymentPayload, SettlementResponse. See references/protocol-spec.md
  • Custom tokens: Use registerMoneyParser for non-USDC tokens, Permit2 for non-EIP-3009 tokens. See references/evm-scheme.md
  • Mainnet deployment: Switch facilitator URL, network IDs, and wallet addresses. See references/core-concepts.md

References

FileContent
references/core-concepts.mdHTTP 402 foundation, client/server/facilitator roles, wallet identity, networks, tokens, custom token config, dynamic registration, self-hosted facilitator, mainnet deployment
references/protocol-spec.mdv2 protocol types, payment flow, facilitator API, error codes
references/typescript-sdk.mdTypeScript SDK patterns for server, client, MCP, paywall, facilitator
references/python-sdk.mdPython SDK patterns for server, client, MCP (server + client), facilitator
references/go-sdk.mdGo SDK patterns for server, client, MCP, facilitator, signers, custom money parser
references/evm-scheme.mdEVM exact scheme: EIP-3009, Permit2, default asset resolution, registerMoneyParser, custom tokens
references/svm-scheme.mdSolana exact scheme: SPL TransferChecked, verification rules
references/upto-scheme.mdUpto (usage-based) scheme: authorize max amount, settle actual usage. EVM via Permit2 only
references/aptos-scheme.mdAptos exact scheme: fungible asset transfers, fee payer sponsorship, TypeScript SDK only
references/transports.mdHTTP, MCP, A2A transport implementations
references/extensions.mdBazaar, payment-identifier, sign-in-with-x, gas sponsoring (eip2612 + erc20) extensions
references/lifecycle-hooks.mdClient/server/facilitator hooks (TypeScript, Python, Go), hook chaining, MCP hooks

Official Resources

Source

git clone https://github.com/tenequm/claude-plugins/blob/main/x402/SKILL.mdView on GitHub

Overview

x402 is an open standard that activates HTTP 402 Payment Required for programmatic, on-chain payments without accounts or API keys. Clients sign crypto transactions and pay over HTTP, enabling paid APIs, paywalls, and autonomous AI agent payments across multiple networks. It provides TypeScript, Python, and Go SDKs for EVM (Base, MegaETH), Solana, and Aptos with HTTP, MCP, and A2A transports, supporting exact and upto (usage-based) pricing.

How This Skill Works

Three roles exist in every x402 payment: Resource Server, Client, and Facilitator. The flow starts when the Client GETs a protected resource; the Server responds with 402 and a PAYMENT-REQUIRED header. The Client signs the payment and retries with a PAYMENT-SIGNATURE header; the Server verifies with the Facilitator and, upon settlement, returns 200 with a PAYMENT-RESPONSE header and the resource data.

When to Use It

  • Building a paid API that accepts crypto micropayments.
  • Adding a paywall to web content or endpoints.
  • Enabling AI agents to autonomously pay for resources.
  • Integrating MCP tools that require on-chain payments or agent-to-agent (A2A) flows.
  • Working with EVM (Base, Ethereum, MegaETH), Solana, or Aptos to settle payments and implement usage-based pricing (upto).

Quick Start

  1. Step 1: Set up a Resource Server with a Facilitator client and register networks (e.g., eip155:84532) and a price scheme.
  2. Step 2: Configure endpoints with a paymentMiddleware that defines resource rules (price, scheme, network) and attach the server.
  3. Step 3: On the Buyer side, initialize the x402 client, register the payment scheme, and use the client to automatically sign and retry payments when a 402 is encountered.

Best Practices

  • Clearly define price and the payment scheme (exact vs upto) per resource.
  • Use the Facilitator to securely verify signatures and settle on-chain.
  • Choose the appropriate transport (HTTP, MCP, A2A) and network (EVM, Solana, Aptos) per use case.
  • Test end-to-end 402 flow in staging before production deployment.
  • Monitor payment failures and implement retry/backoff strategies to avoid leaking data.

Example Use Cases

  • A paid API service where clients fetch data by paying with crypto micropayments via x402.
  • A paywalled article platform where access is granted after successful 402 payment verification.
  • Autonomous AI agents that automatically pay for resource usage (compute, data) during task execution.
  • An MCP-based tool that requires on-chain payments to unlock tool capabilities or data feeds.
  • A2A payment flows across EVM, Solana, and Aptos enabling seamless agent-to-agent settlements.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers