Quick Start

From zero to your first RPC and AI call in 3 minutes.

Prerequisites

  • An EVM wallet (private key) or Solana wallet
  • A small amount of USDC on a supported payment network (Base Sepolia for testing)
  • Node.js >= 18

Step 1: Install the SDK

npm install @zan_team/x402 viem

For Solana wallet support, also install:

npm install @solana/web3.js @solana/spl-token bs58 tweetnacl

Step 2: Create the client

import { createX402Client } from '@zan_team/x402';

const client = await createX402Client({
  gatewayUrl: 'https://x402.zan.top',
  privateKey: process.env.PRIVATE_KEY as `0x${string}`,
  autoPayment: true,   // automatically handle 402 payment challenges
  preAuth: true,       // authenticate (SIWE) on creation
});

preAuth: true makes the SDK perform SIWE wallet signature authentication immediately and obtain a JWT. All subsequent calls are session-managed automatically.

autoPayment: true makes the SDK automatically sign and submit on-chain USDC payments whenever the gateway returns HTTP 402.

Step 3: Call RPC — Query blockchain data

const block = await client.call('eth', 'mainnet', 'eth_blockNumber');
console.log(block.result); // "0x1234567"

If your credit balance is insufficient, the SDK automatically triggers an x402 payment to purchase credits, then retries the call — all transparent to your code.

Step 4: Call AI model — Run inference

const response = await client.chat('deepseek-v4-flash', {
  messages: [{ role: 'user', content: 'What is the x402 protocol?' }],
  max_tokens: 1024,
});

console.log(response.data.content);
console.log(response.data.usage);
// { prompt_tokens: 12, completion_tokens: 85, total_tokens: 97 }

AI uses rolling settlement: the first call is free (no payment needed). Each subsequent call settles the previous call's actual token cost. The SDK handles payment signatures automatically.

Step 5: Check balance and discover services

// Check credit balance
const balance = await client.getBalance();
console.log(`Credits remaining: ${balance.balance}`);

// List available credit bundles
const { bundles } = await client.listBundles();
console.log(bundles);
// [{ name: 'default', credits: 100000, price: '0.015', ... }]

// Discover available AI models
const { models } = await client.discovery.listAiModels();
models.forEach(m => {
  console.log(`${m.id}: input=$${m.inputPricePerToken}/token`);
});

Complete runnable example

import { createX402Client } from '@zan_team/x402';

async function main() {
  // 1. Create client (authenticates automatically)
  const client = await createX402Client({
    gatewayUrl: 'https://x402.zan.top',
    privateKey: process.env.PRIVATE_KEY as `0x${string}`,
    autoPayment: true,
    preAuth: true,
  });

  // 2. Query Ethereum block number
  const block = await client.call('eth', 'mainnet', 'eth_blockNumber');
  console.log(`Latest block: ${block.result}`);

  // 3. Query Solana slot
  const slot = await client.call('solana', 'mainnet', 'getSlot');
  console.log(`Solana slot: ${slot.result}`);

  // 4. Call AI model
  const ai = await client.chat('deepseek-v4-flash', {
    messages: [{ role: 'user', content: 'Summarize the x402 payment protocol in one paragraph.' }],
    max_tokens: 256,
  });
  console.log(`AI response: ${ai.data.content}`);
  console.log(`Tokens used: ${ai.data.usage.total_tokens}`);

  // 5. Check remaining balance
  const bal = await client.getBalance();
  console.log(`Credits remaining: ${bal.balance}`);
}

main().catch(console.error);

What happened under the hood

When autoPayment: true, the SDK transparently handles all authentication and payment:

1. Client creation (createX402Client)

SDK                                          Gateway
 │                                              │
 │───────── SIWE: sign wallet message ─────────▶│
 │◀───────── JWT token (valid 1 hour) ──────────│

2. RPC call (client.call) — first time, no credits

SDK                                          Gateway                   Facilitator
 │                                              │                            │
 │─────────── POST /rpc/eth/mainnet ───────────▶│                            │
 │◀─────── 402 { insufficient_credits } ────────│                            │
 │                                              │                            │
 │────── POST /credits/purchase/default ───────▶│                            │
 │◀─────── 402 + PAYMENT-REQUIRED (quote) ──────│                            │
 │                                              │                            │
 │        [sign EIP-3009 USDC transfer]         │                            │
 │                                              │                            │
 │─── POST /credits/purchase + PAYMENT-SIG ────▶│───────── verify ──────────▶│
 │                                              │◀────────── valid ──────────│
 │                                              │───── settle on-chain ─────▶│
 │◀───── 200 { creditsPurchased: 100000 } ──────│                            │
 │                                              │                            │
 │─────── POST /rpc/eth/mainnet (retry) ───────▶│                            │
 │◀─────── 200 { result: "0x1234567" } ─────────│                            │

3. AI call (client.chat) — rolling settlement

SDK                                          Gateway
 │                                              │
 │───────── POST /ai/deepseek-v4-flash ────────▶│
 │◀── 200 { content: "..." } (first call free) ─│
 │                                              │
 │  ... later ...                               │
 │                                              │
 │──────── POST /ai/deepseek-v4-flash ─────────▶│
 │◀── 402 (settle previous: 0.000126 USDC) ─────│
 │                                              │
 │  [sign USDC payment for previous tokens]     │
 │                                              │
 │── POST /ai/deepseek-v4-flash + PAYMENT-SIG─ ▶│
 │◀── 200 { content: "...", txHash: "0x..." } ──│

Using curl (protocol reference)

For debugging or understanding the raw protocol, here's the manual flow:

1. Authenticate

curl -X POST https://x402.zan.top/auth \
  -H "Content-Type: application/json" \
  -d '{
    "chainType": "EVM",
    "message": "<SIWE message>",
    "signature": "0x<wallet signature>"
  }'
# Response: { "token": "eyJ...", "wallet": "0x...", "balance": 0 }

2. Purchase credits

# First request → 402 with payment quote
curl -X POST https://x402.zan.top/credits/purchase/default \
  -H "Authorization: Bearer <jwt>"
# Response: 402 + PAYMENT-REQUIRED header (base64 JSON quote)

# Second request with payment signature → 200
curl -X POST https://x402.zan.top/credits/purchase/default \
  -H "Authorization: Bearer <jwt>" \
  -H "PAYMENT-SIGNATURE: <base64 payment payload>"
# Response: { "creditsPurchased": 100000, "balance": 100000 }

3. Call RPC

curl -X POST https://x402.zan.top/rpc/eth/mainnet \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'
# Response: {"jsonrpc":"2.0","id":1,"result":"0x1234567"}

4. Call AI model

curl -X POST https://x402.zan.top/ai/deepseek-v4-flash \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Hello"}]}'
# First call: 200 (free)
# Subsequent calls: 402 → sign → retry → 200

Next steps



Did this page help you?