Agent x402 Guide
Minimal setup for AI agents to use x402 endpoints — install dependencies, create a wallet, and make your first paid request.
This guide gets an AI agent set up to make x402 payments. Three steps: install, wallet, go.
For how x402 works under the hood, see x402.
1. Install Dependencies
npm install @x402/fetch @x402/evm viem- viem — wallet creation and EIP-712 signing
- @x402/evm — EVM payment scheme for x402
- @x402/fetch — wraps
fetchto handle 402 responses automatically
2. Set Up a Wallet
You need an EVM private key for a wallet with USDC on Base (chain ID 8453). If you already have one, skip to step 3 — set it as WALLET_PRIVATE_KEY in your environment.
To create a new wallet:
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
const privateKey = generatePrivateKey();
const signer = privateKeyToAccount(privateKey);
console.log("Address:", signer.address);
console.log("Private key:", privateKey);Save the private key securely. Store it in your environment or secrets manager. If you lose it, you lose access to the wallet and any funds in it.
Fund this wallet with USDC on Base before proceeding.
Any wallet that can sign EIP-712 typed data works — the raw private key approach above is the simplest. Coinbase Agentic Wallet is an alternative with native x402 support and programmable spending limits.
3. Make a Paid Request
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const signer = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);fetchWithPayment works like a normal fetch. When a server responds with HTTP 402, it automatically signs the USDC authorization, retries with proof, and returns the result. Use it on any x402 endpoint:
const response = await fetchWithPayment("https://api.aixbt.tech/x402/v2/api-keys/1d", {
method: "POST",
});
const { data } = await response.json();