x402 SDK
Overview
x402 payment protocol SDK for AI billing
x402 SDK
The x402 SDK enables direct-to-protocol AI payments using crypto wallets. No API keys required - payments are handled via HTTP 402 status codes and on-chain signatures.
Installation
npm install @merit-systems/ai-x402
pnpm add @merit-systems/ai-x402
yarn add @merit-systems/ai-x402
bun add @merit-systems/ai-x402
Quick Start
import { createX402OpenAI } from '@merit-systems/ai-x402';
import { generateText } from 'ai';
import { CdpClient } from '@coinbase/cdp-sdk';
import { toAccount } from 'viem/accounts';
// Create wallet using Coinbase Developer Platform
const cdp = new CdpClient({
apiKeyId: process.env.CDP_API_KEY_ID,
apiKeySecret: process.env.CDP_API_KEY_SECRET,
walletSecret: process.env.CDP_WALLET_SECRET,
});
const account = await cdp.evm.getOrCreateAccount({
name: process.env.CDP_WALLET_OWNER,
});
const walletClient = toAccount(account);
// Create OpenAI provider with automatic x402 payment handling
const openai = createX402OpenAI(walletClient);
// Use with Vercel AI SDK
const { text } = await generateText({
model: openai('gpt-4o'),
prompt: 'Hello world'
});
How It Works
- First request returns HTTP 402 with payment requirements
- SDK creates payment signature using your wallet
- SDK retries request with
x-payment
header - Request succeeds and payment settles on-chain
API
createX402OpenAI(walletClient, baseRouterUrl?)
Creates an OpenAI provider that handles x402 payments automatically.
Parameters:
walletClient
- x402 wallet signerbaseRouterUrl
- Optional router URL (default:https://echo.router.merit.systems
)
Returns: OpenAI provider compatible with Vercel AI SDK
Custom Router
const openai = createX402OpenAI(
walletClient,
'https://your-router.com'
);