A TypeScript SDK for handling X402 payment protocol on Base and other Layer 2 networks. Automatically handles payment flows when accessing paid APIs that return 402 Payment Required responses.
npm install @logiccrafterdz/xpay-sdkimport { createWalletClient, http } from 'viem';
import { baseSepolia } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
import { createX402Client, createXPayWalletClient } from '@logiccrafterdz/xpay-sdk';
// Initialize wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const viemWallet = createWalletClient({
account,
chain: baseSepolia,
transport: http()
});
// Create XPay wallet wrapper
const xpayWallet = createXPayWalletClient({
walletClient: viemWallet,
chain: 'base-sepolia'
});
// Create X402 client
const client = createX402Client({
walletClient: xpayWallet,
chain: 'base-sepolia',
maxRetries: 3,
confirmationTimeout: 30000
});
// Make request to paid API - payment handled automatically
const response = await client.request({
method: 'GET',
url: 'https://api.example.com/premium-endpoint'
});| Chain | Chain ID | Supported Tokens |
|---|---|---|
| Base Mainnet | 8453 | USDC |
| Base Sepolia | 84532 | USDC |
- 🚀 TypeScript Support: Full type definitions and IntelliSense
- 🔗 Multi-Chain: Support for Base mainnet and testnet
- 💰 Automatic Payments: Handles X402 payment flow seamlessly
- 🛡️ Error Handling: Comprehensive error types and retry logic
- ⚡ Viem Integration: Built on top of the modern viem library
- 🧪 Well Tested: Comprehensive unit and integration test coverage
Creates an HTTP client that automatically handles X402 payment flows.
Parameters:
walletClient: XPayWalletClient instancechain: Supported chain ('base' | 'base-sepolia')maxRetries?: Maximum payment retry attempts (default: 1)confirmationTimeout?: Transaction confirmation timeout in ms (default: 60000)
Wraps a viem WalletClient with XPay-specific functionality.
Parameters:
viemWallet: A configured viem WalletClient instance
import { parsePaymentInfo } from '@logiccrafterdz/xpay-sdk';
// Parse payment info from 402 response headers
const paymentInfo = parsePaymentInfo(response.headers);import { getTokenAddress, getChainConfig } from '@logiccrafterdz/xpay-sdk';
// Get USDC token address for a specific chain
const usdcAddress = getTokenAddress('base-sepolia', 'USDC');
// Get viem chain configuration
const chainConfig = getChainConfig('base-sepolia');See examples/pay-for-api.ts for a complete working example.
To run the example:
# Set your private key (testnet only!)
export PRIVATE_KEY="0x..."
# Run the example
npm run example- Never hardcode private keys in production code
- Use environment variables or secure key management systems
- Only use testnet private keys for development and testing
- Ensure your wallet has sufficient USDC balance and ETH for gas fees
- Always validate payment amounts and recipients before confirming transactions
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Run example
npm run exampleThe SDK provides specific error types for different failure scenarios:
import { InsufficientBalanceError, InsufficientAllowanceError } from '@logiccrafterdz/xpay-sdk';
try {
const response = await client.request({ ... });
} catch (error) {
if (error instanceof InsufficientBalanceError) {
console.log('Not enough USDC balance');
} else if (error instanceof InsufficientAllowanceError) {
console.log('Need to approve USDC spending');
}
}- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
MIT
- Developer: LogicCrafterDZ
- Email: logiccrafterdz@gmail.com
- Twitter: @Arana_lib
- Telegram: https://t.me/LogicCrafterDZ
- Farcaster : @esta