Skip to content

x402 payments

x402 lets you pay for API requests directly with crypto — no API key needed.
Each request is paid individually with a USDC transaction on Base, signed with your wallet's private key.
This is especially useful for AI Agents so they can pay for their own inference.

TIP

x402 is an alternative to API keys. You can still use the Developer console to create a traditional API key if you prefer.

How it works

  1. Your request hits the API without an API key
  2. The server responds with 402 Payment Required and the payment details
  3. Your client signs an EIP-712 message (Permit or TransferWithAuthorization) with your private key
  4. The request is retried with the signed payment in the X-PAYMENT header
  5. The server verifies the signature and processes your request

All of this happens automatically when using the LibertAI x402 packages.

Installation

sh
npm install @libertai/x402

Usage

With OpenAI SDK

The easiest way to use x402 — wrap the OpenAI client with automatic payment handling:

ts
import { wrapFetchWithPayment } from "@libertai/x402";
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.libertai.io/v1",
  apiKey: "x402",
  fetch: wrapFetchWithPayment(process.env.WALLET_PRIVATE_KEY as `0x${string}`),
});

const response = await client.chat.completions.create({
  model: "gemma-4-31b-it",
  messages: [{ role: "user", content: "Hello!" }],
});

console.log(response.choices[0].message.content);

Set the API key to "x402" — the wrapper strips this dummy value before sending requests. If you use a real API key, it will be preserved.

With plain HTTP

You can also use the payment wrapper directly with any HTTP call:

ts
import { wrapFetchWithPayment } from "@libertai/x402";

const fetchWithPayment = wrapFetchWithPayment(process.env.WALLET_PRIVATE_KEY as `0x${string}`);

const response = await fetchWithPayment(
  "https://api.libertai.io/v1/chat/completions",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "gemma-4-31b-it",
      messages: [{ role: "user", content: "Hello!" }],
    }),
  },
);

What it costs

x402 uses the same per-request pricing as API-key access. Every model's USD price is published in the text, image, and search pricing tables, and the gateway quotes the same amount in USDC at request time. There is no minimum and no top-up — each request is settled independently on Base.

If your account has no funded API key on file, the 402 response from the gateway includes the exact maximum price for that specific request; the wrapper signs an authorization for that amount and the request is retried automatically.

Requirements

  • A wallet private key with USDC on Base (chain ID 8453)
  • TypeScript: Node.js 18+ (uses the global fetch API)
  • Python: Python 3.11+

See also