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 (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 package.

Installation

sh
npm install @libertai/x402

Usage

With OpenAI SDK

The easiest way to use x402 — wrap the OpenAI client's fetch 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.PRIVATE_KEY as `0x${string}`),
});

const response = await client.chat.completions.create({
  model: "qwen3-coder-next",
  messages: [{ role: "user", content: "Hello!" }],
});

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

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

With plain fetch

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

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

const fetchWithPayment = wrapFetchWithPayment(process.env.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: "qwen3-coder-next",
      messages: [{ role: "user", content: "Hello!" }],
    }),
  },
);

Requirements

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