Setting Up x402 on Base, Ethereum, and Solana

tutorial blockchain · x402 Guide

Introduction

The x402 protocol revolutionizes how services handle machine-to-machine payments by leveraging the HTTP 402 "Payment Required" status code alongside USDC stablecoin transactions. While x402 was initially optimized for Base L2 due to its low transaction costs and fast settlement times, the protocol's flexibility allows deployment across multiple blockchain networks including Ethereum mainnet and Solana.

This comprehensive guide walks you through setting up x402 services on each supported blockchain, comparing their unique characteristics, costs, and implementation considerations. Whether you're building the next AskClaude.shop-style AI service or exploring micropayment infrastructure for your API, understanding multi-chain deployment strategies is crucial for maximizing reach and minimizing costs.

Why Multi-Chain x402 Deployment Matters

Different blockchain networks offer distinct advantages for x402 services. Base L2 provides ultra-low transaction fees perfect for micropayments, Ethereum offers maximum liquidity and ecosystem maturity, while Solana delivers high throughput and sub-second confirmation times. By supporting multiple chains, your x402 service can:

Understanding the x402 payment flow is essential before diving into chain-specific implementations, as the core protocol remains consistent across networks while only the underlying settlement mechanics change.

Setting Up x402 on Base L2

Why Choose Base for x402

Base, Coinbase's Ethereum Layer 2 solution, represents the optimal network for x402 deployments. With transaction fees typically under $0.01 and 2-second block times, Base enables true micropayment scenarios that would be economically unfeasible on Ethereum mainnet.

Key Base advantages for x402:

Base Implementation Setup

First, install the necessary dependencies for Base x402 integration:

npm install @anthropic-ai/sdk ethers @coinbase/cdp-sdk
npm install express cors helmet

Configure your Base network connection:

import { ethers } from 'ethers';

const BASE_RPC = 'https://mainnet.base.org';
const BASE_CHAIN_ID = 8453;
const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';

const provider = new ethers.JsonRpcProvider(BASE_RPC);
const contract = new ethers.Contract(
  USDC_BASE,
  ['function transferWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32) external'],
  provider
);

Create your Base x402 service endpoint:

import express from 'express';

const app = express();
app.use(express.json());

app.get('/api/query', async (req, res) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader?.startsWith('x402')) {
    return res.status(402).json({
      protocol: 'x402',
      amount: '1000000', // $1 USDC (6 decimals)
      currency: 'USDC',
      network: 'base',
      facilitator: 'https://api.cdp.coinbase.com/x402/facilitator',
      recipient: '0x742d35Cc6634C0532925a3b8D69B1F8b8C4bb8C6',
      memo: 'AI Query Service Payment'
    });
  }

  // Verify payment with facilitator
  const paymentValid = await verifyBasePayment(authHeader);
  if (!paymentValid) {
    return res.status(402).json({ error: 'Payment verification failed' });
  }

  // Deliver service
  res.json({ response: 'Your AI query result...' });
});

Base Network Configuration

When deploying on Base, configure these network-specific parameters:

const BASE_CONFIG = {
  networkId: 8453,
  rpcUrl: 'https://mainnet.base.org',
  usdcAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  blockTime: 2, // seconds
  confirmations: 1, // Base finality is fast
  gasLimit: 21000,
  maxGasPrice: ethers.parseUnits('0.01', 'gwei')
};

Setting Up x402 on Ethereum Mainnet

Ethereum Considerations

Ethereum mainnet offers the highest liquidity and most mature DeFi ecosystem but comes with significantly higher transaction costs. Ethereum x402 services work best for higher-value transactions where the $5-50 gas fees represent a small percentage of the payment amount.

Ethereum advantages:

Ethereum Setup Process

Configure Ethereum mainnet for x402:

const ETHEREUM_CONFIG = {
  networkId: 1,
  rpcUrl: 'https://eth-mainnet.g.alchemy.com/v2/your-api-key',
  usdcAddress: '0xA0b86a33E6e94e5bBb17A2A4f6Eb49dF3c9fB2c0',
  blockTime: 12, // seconds
  confirmations: 3, // Wait for finality
  gasLimit: 50000,
  maxGasPrice: ethers.parseUnits('30', 'gwei')
};

const ethereumProvider = new ethers.JsonRpcProvider(ETHEREUM_CONFIG.rpcUrl);

Handle Ethereum's variable gas costs dynamically:

async function calculateEthereumFees() {
  const gasPrice = await ethereumProvider.getFeeData();
  const estimatedGas = 21000n; // Basic USDC transfer
  
  const totalGasCost = gasPrice.gasPrice * estimatedGas;
  const gasCostUSD = await convertWeiToUSD(totalGasCost);
  
  // Only proceed if gas cost is reasonable relative to payment
  return gasCostUSD < paymentAmount * 0.1; // Max 10% gas overhead
}

Implement Ethereum-specific payment verification:

async function verifyEthereumPayment(authHeader, expectedAmount) {
  try {
    const paymentData = parseX402Header(authHeader);
    
    // Check transaction on Ethereum
    const tx = await ethereumProvider.getTransaction(paymentData.txHash);
    const receipt = await ethereumProvider.getTransactionReceipt(paymentData.txHash);
    
    if (receipt.status !== 1) return false;
    if (receipt.confirmations < ETHEREUM_CONFIG.confirmations) return false;
    
    // Verify USDC transfer amount and recipient
    const transferLog = receipt.logs.find(log => 
      log.address.toLowerCase() === ETHEREUM_CONFIG.usdcAddress.toLowerCase()
    );
    
    return verifyTransferLog(transferLog, expectedAmount);
  } catch (error) {
    console.error('Ethereum payment verification failed:', error);
    return false;
  }
}

Setting Up x402 on Solana

Solana's Unique Advantages

Solana brings exceptional speed and low costs to x402 implementations, with 400ms block times and transaction fees under $0.001. However, Solana requires different technical approaches due to its account-based model and different programming paradigms.

Solana benefits for x402:

Solana Implementation Differences

Solana x402 requires the @solana/web3.js library instead of ethers:

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

Configure Solana connection:

import { Connection, PublicKey } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';

const SOLANA_RPC = 'https://api.mainnet-beta.solana.com';
const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';

const connection = new Connection(SOLANA_RPC, 'confirmed');
const usdcMint = new PublicKey(USDC_SOLANA);

Handle Solana's account-based payment verification:

async function verifySolanaPayment(signature, expectedAmount, recipient) {
  try {
    const tx = await connection.getTransaction(signature, {
      commitment: 'confirmed'
    });
    
    if (!tx || tx.meta.err) return false;
    
    // Find USDC transfer in transaction
    const transferInstruction = tx.transaction.message.instructions.find(ix => 
      tx.transaction.message.accountKeys[ix.programIdIndex].equals(TOKEN_PROGRAM_ID)
    );
    
    if (!transferInstruction) return false;
    
    // Verify transfer details match expected payment
    return verifyTransferAmount(transferInstruction, expectedAmount, recipient);
  } catch (error) {
    console.error('Solana payment verification failed:', error);
    return false;
  }
}

Solana x402 Service Configuration

const SOLANA_CONFIG = {
  cluster: 'mainnet-beta',
  rpcUrl: 'https://api.mainnet-beta.solana.com',
  usdcMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  blockTime: 0.4, // 400ms
  confirmations: 'confirmed', // Solana confirmation level
  fees: 0.000005 // ~$0.001 at current SOL prices
};

Blockchain Comparison: Costs and Performance

Transaction Cost Analysis

Understanding the cost implications of each network helps determine optimal deployment strategies:

Network Avg Gas Cost Settlement Time Best For
Base L2 $0.005 - $0.01 2-4 seconds Micropayments, high frequency
Ethereum $5 - $50 12-60 seconds High-value transactions
Solana $0.0005 400ms - 1.5s Ultra-fast, ultra-cheap

Performance Benchmarks

Based on real-world testing across networks:

Facilitator Support Across Networks

Different facilitators offer varying levels of support across blockchain networks. Understanding these differences is crucial for choosing the right facilitator for your multi-chain strategy:

Coinbase CDP Facilitator

UltravioletaDAO

Multi-Chain Deployment Strategy

Network Selection Logic

Implement intelligent network selection based on payment characteristics:

function selectOptimalNetwork(paymentAmount, urgency, userPreference) {
  // For micropayments under $1
  if (paymentAmount < 1) {
    return userPreference === 'solana' ? 'solana' : 'base';
  }
  
  // For medium payments $1-$100
  if (paymentAmount < 100) {
    if (urgency === 'high') return 'solana';
    return 'base'; // Good balance of cost and reliability
  }
  
  // For high-value payments over $100
  if (paymentAmount >= 100) {
    return 'ethereum'; // Security and liqu
  

Try an x402-Powered Service

AskClaude.shop is a live x402 service — AI agents pay per query with USDC micropayments.

Visit AskClaude.shop