Skip to Content
Getting StartedAuthentication & Payment

Authentication & Payment

X-Router uses a unique authentication model based on cryptographic payments rather than traditional API keys.

Requirements

1. USDC Balance

You need USDC on Base Mainnet in your wallet. See the Quick Start guide for detailed instructions on purchasing, bridging, or getting test USDC.

2. Ethereum Wallet

Any Ethereum wallet with a private key will work. You can:

  • Use an existing wallet
  • Generate a new wallet specifically for API usage
  • Use environment variables to manage keys securely

Important: No ETH is needed! Payments are gasless.

3. x402 Client Library

Install the x402-fetch library:

npm install x402-fetch viem

Setup

Basic Setup

import { wrapFetchWithPayment } from 'x402-fetch'; import { privateKeyToAccount } from 'viem/accounts'; // Create account from private key const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); // Wrap fetch with payment handling const fetchWithPayment = wrapFetchWithPayment(fetch, account); // Use it like normal fetch - payments handled automatically! const response = await fetchWithPayment('https://api.x-router.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: [{ role: 'user', content: 'Hello!' }], model: 'anthropic/claude-3.5-sonnet', max_tokens: 100 }) }); const data = await response.json(); console.log(data.content);

Spending Limits

By default, x402-fetch has a safety limit on how much it will pay per request (~$0.10). For higher-cost operations like premium models or high-resolution images, increase the limit:

const fetchWithPayment = wrapFetchWithPayment(fetch, account, { maxAmountPerRequest: 5.0, // Allow up to $5 per request });

Recommended limits by use case:

Use CaseRecommended Limit
Chat completions (default models)0.50
Premium chat models (GPT-4, Claude Opus)2.0
Image generation (high-res/premium)5.0

If you see the error "Payment amount exceeds maximum allowed", increase your maxAmountPerRequest value.

Environment Variables

Create a .env file:

PRIVATE_KEY=0x1234567890abcdef...

Load it in your application:

import 'dotenv/config'; import { privateKeyToAccount } from 'viem/accounts'; const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);

Security Best Practices

Never Expose Private Keys

  • Never commit private keys to version control
  • Never expose keys in client-side code
  • Store keys in environment variables
  • Use server-side proxy for production applications

Wallet Management

  • Use dedicated wallets for API usage
  • Keep minimal USDC balance (refill as needed)
  • Rotate keys regularly
  • Monitor wallet activity

Production Deployment

For production applications:

  1. Server-side proxy: Create a backend service that handles x402 payments
  2. API key layer: Add your own API key system on top
  3. Rate limiting: Implement rate limiting to prevent abuse
  4. Monitoring: Track usage and costs

Example server-side proxy:

// server.ts import express from 'express'; import { wrapFetchWithPayment } from 'x402-fetch'; import { privateKeyToAccount } from 'viem/accounts'; const app = express(); const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const fetchWithPayment = wrapFetchWithPayment(fetch, account); app.post('/api/chat', async (req, res) => { // Verify API key, rate limit, etc. const response = await fetchWithPayment('https://api.x-router.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(req.body) }); const data = await response.json(); res.json(data); }); app.listen(3000);

How Payments Work

X-Router uses the x402 protocol for gasless micropayments:

  • Currency: USDC on Base Mainnet
  • Network: Base (Ethereum L2)
  • Gas: Paid by facilitator (you pay zero gas)
  • Speed: Instant (no blockchain confirmation needed)

The x402-fetch library handles the entire payment flow automatically. For a detailed explanation of how payments work, see Overview: How x402 Payment Works.

Cost Transparency

Pricing is dynamic and based on:

  • Input token count (all messages)
  • Requested output tokens (max_tokens)
  • Model-specific rates

Use the /v1/estimate endpoint to get exact costs before making paid requests.

Last updated on