@x402apechain/sdk
v0.1.0
Published
TypeScript SDK for interacting with the X402 ApeChain facilitator - gasless EIP-2612 permit payments
Maintainers
Readme
@x402apechain/sdk
TypeScript SDK for interacting with the X402 ApeChain payment facilitator. Enable gasless EIP-2612 permit-based payments for AI agents and services on ApeChain.
Installation
npm install @x402apechain/sdk viemQuick Start
For AI Agents / Backend Services
import { createPublicClient, createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import {
FacilitatorClient,
AgentPaymentClient,
APECHAIN,
APECHAIN_USDC,
toTokenUnits
} from '@x402apechain/sdk';
// 1. Setup clients
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const publicClient = createPublicClient({ chain: APECHAIN, transport: http() });
const walletClient = createWalletClient({ account, chain: APECHAIN, transport: http() });
// 2. Create facilitator client
const facilitator = new FacilitatorClient({
baseUrl: 'https://x402apes-production.up.railway.app',
chainId: APECHAIN.id,
settlementAddress: '0xe24a8dbf205ee116c991f60686f778a2337a844f',
defaultToken: APECHAIN_USDC
});
// 3. Create agent payment client
const agent = new AgentPaymentClient({
facilitator,
publicClient,
walletClient,
defaultDeadlineSeconds: 600 // 10 minutes
});
// 4. Make a payment
const receipt = await agent.pay({
invoice: {
chainId: APECHAIN.id,
tokenAddress: APECHAIN_USDC,
recipient: '0xYourRecipientAddress',
amount: toTokenUnits('0.10', 6) // 0.10 USDC
}
});
console.log('Payment settled:', receipt.txHash);For React/Frontend Apps
import { createPublicClient, createWalletClient, custom, http } from 'viem';
import {
FacilitatorClient,
AgentPaymentClient,
APECHAIN,
APECHAIN_USDC,
toTokenUnits
} from '@x402apechain/sdk';
// With a wallet provider (e.g., from Privy, wagmi, etc.)
const walletClient = createWalletClient({
account: walletAddress,
chain: APECHAIN,
transport: custom(walletProvider)
});
const publicClient = createPublicClient({
chain: APECHAIN,
transport: http()
});
const facilitator = new FacilitatorClient({
baseUrl: 'https://x402apes-production.up.railway.app',
chainId: APECHAIN.id,
settlementAddress: '0xe24a8dbf205ee116c991f60686f778a2337a844f'
});
const agent = new AgentPaymentClient({
facilitator,
publicClient,
walletClient
});
// Pay for a service
const receipt = await agent.pay({
invoice: {
chainId: APECHAIN.id,
tokenAddress: APECHAIN_USDC,
recipient: recipientAddress,
amount: toTokenUnits('1.00', 6) // 1.00 USDC
}
});API Reference
FacilitatorClient
The main client for interacting with the X402 facilitator API.
const facilitator = 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
| Method | Description | Returns |
|--------|-------------|---------|
| verify(request) | Verify a payment permit is valid | Promise<VerifyResponse> |
| settle(request) | Execute payment settlement on-chain | Promise<SettleResponse> |
| supported() | Get supported networks and tokens | Promise<SupportedResponse> |
| stats() | Get facilitator statistics | Promise<StatsResponse> |
| health() | Check facilitator health status | Promise<HealthResponse> |
AgentPaymentClient
High-level client that handles the full payment flow (sign permit → verify → settle).
const agent = new AgentPaymentClient({
facilitator: FacilitatorClient,
publicClient: PublicClient, // viem public client
walletClient: WalletClient, // viem wallet client
defaultDeadlineSeconds?: number // Default: 600 (10 minutes)
});Methods
| Method | Description | Returns |
|--------|-------------|---------|
| pay(options) | Execute a complete payment flow | Promise<SettleResponse> |
Utility Functions
// Convert human-readable amounts to token units
toTokenUnits('1.5', 6) // Returns 1500000n for USDC (6 decimals)
// Fetch token metadata (name, decimals, version)
await fetchTokenMetadata(publicClient, tokenAddress)
// Fetch current permit nonce for an address
await fetchPermitNonce(publicClient, tokenAddress, ownerAddress)Constants
import { APECHAIN, APECHAIN_TESTNET, APECHAIN_USDC } from '@x402apechain/sdk';
// ApeChain Mainnet (chainId: 33139)
APECHAIN.id // 33139
APECHAIN.name // 'ApeChain'
APECHAIN.rpcUrls // RPC endpoints
// ApeChain Curtis Testnet (chainId: 33111)
APECHAIN_TESTNET.id // 33111
// Bridged USDC on ApeChain
APECHAIN_USDC // '0xF1815bd50389c46847f0Bda824eC8da914045D14'Types
interface FacilitatorInvoice {
id?: string; // Optional invoice ID
chainId: number; // Must match facilitator chain
tokenAddress: Address; // ERC-20 token with permit support
recipient: Address; // Payment recipient
amount: bigint; // Amount in smallest units
metadata?: Record<string, unknown>;
}
interface SettleResponse {
success: boolean;
txHash: Hex;
settledAt: string;
}
interface VerifyResponse {
success: boolean;
id: string;
}Error Handling
The SDK throws FacilitatorError for API errors:
import { FacilitatorError } from '@x402apechain/sdk';
try {
await agent.pay({ invoice });
} catch (error) {
if (error instanceof FacilitatorError) {
console.error('Facilitator error:', error.message);
console.error('Status:', error.status);
console.error('Details:', error.details);
}
}How X402 Works
- Agent signs a permit - Off-chain EIP-2612 signature authorizing the settlement contract to transfer tokens
- Facilitator verifies - Checks signature validity, balance, and nonce
- Facilitator settles - Executes the permit + transfer atomically on-chain
- Agent receives service - After successful settlement
The agent never pays gas fees - the facilitator handles all on-chain execution.
Links
License
MIT
