SDK Reference

Complete API documentation for @x402apechain/sdk


Installation

npm install @x402apechain/sdk viem

FacilitatorClient

The main client for interacting with the X402 facilitator API.

Constructor

import { FacilitatorClient } from '@x402apechain/sdk';

const client = new FacilitatorClient({
  baseUrl: string,           // Facilitator API URL
  chainId: number,           // Chain ID (33139 for ApeChain)
  settlementAddress: Address, // Settlement contract address
  defaultToken?: Address      // Optional default payment token
});

Methods

MethodDescriptionReturns
verify(request)Verify a payment permit is validPromise<VerifyResponse>
settle(request)Execute payment settlement on-chainPromise<SettleResponse>
supported()Get supported networks and tokensPromise<SupportedResponse>
stats()Get facilitator statisticsPromise<StatsResponse>
health()Check facilitator health statusPromise<HealthResponse>

AgentPaymentClient

High-level client that handles the full payment flow (sign permit → verify → settle).

Constructor

import { AgentPaymentClient } from '@x402apechain/sdk';

const agent = new AgentPaymentClient({
  facilitator: FacilitatorClient,  // FacilitatorClient instance
  publicClient: PublicClient,      // viem public client
  walletClient: WalletClient,      // viem wallet client
  defaultDeadlineSeconds?: number  // Default: 600 (10 minutes)
});

Methods

MethodDescriptionReturns
pay(options)Execute a complete payment flowPromise<SettleResponse>

Constants

Pre-configured chain definitions and addresses.

import { 
  APECHAIN,                    // ApeChain Mainnet (chainId: 33139)
  APECHAIN_TESTNET,            // ApeChain Curtis Testnet (chainId: 33111)
  APECHAIN_USDC,               // USDC token address
  DEFAULT_FACILITATOR_URL,     // https://x402apes-production.up.railway.app
  DEFAULT_SETTLEMENT_ADDRESS,  // Settlement contract
  DEFAULT_FACILITATOR_ADDRESS  // Facilitator wallet
} from '@x402apechain/sdk';

Utility Functions

import { 
  toTokenUnits,        // Convert human-readable to token units
  fetchTokenMetadata,  // Get token name, decimals, version
  fetchPermitNonce,    // Get current permit nonce
  validateAddress,     // Validate Ethereum address
  isValidAddress       // Check if address is valid
} from '@x402apechain/sdk';

// Examples
toTokenUnits('1.50', 6)  // Returns 1500000n for USDC
await fetchPermitNonce(publicClient, tokenAddress, ownerAddress)

Error Handling

The SDK throws FacilitatorError for API errors with helpful methods.

import { FacilitatorError } from '@x402apechain/sdk';

try {
  await agent.pay({ invoice });
} catch (error) {
  if (error instanceof FacilitatorError) {
    console.error('Message:', error.message);
    console.error('Status:', error.status);
    
    // Helper methods
    if (error.isInsufficientFunds()) {
      console.error('Not enough USDC balance');
    }
    if (error.isInvalidSignature()) {
      console.error('Signature verification failed');
    }
    if (error.isReplayAttack()) {
      console.error('Nonce already used');
    }
  }
}

Types

All TypeScript types are exported for type-safe development.

import type {
  FacilitatorConfig,
  FacilitatorInvoice,
  AgentPaymentOptions,
  PaymentRequest,
  PaymentPayload,
  PaymentRequirements,
  VerifyResponse,
  SettleResponse,
  SupportedResponse,
  StatsResponse,
  HealthResponse
} from '@x402apechain/sdk';

// Invoice structure
interface FacilitatorInvoice {
  id?: string;              // Optional invoice ID
  chainId: number;          // Must match facilitator chain
  tokenAddress: Address;    // ERC-20 token with permit
  recipient: Address;       // Payment recipient
  amount: bigint;           // Amount in smallest units
  metadata?: Record<string, unknown>;
}