@megalithlabs/x402
v0.1.3
Published
JavaScript SDK for x402 payments - pay and charge for APIs with stablecoins
Downloads
436
Maintainers
Readme
@megalithlabs/x402
JavaScript SDK for x402 payments. Pay for APIs and charge for APIs with stablecoins.
x402 is an open protocol for internet-native payments using HTTP 402 status codes.
Learn more: x402.org | Megalith Labs
Installation
npm install @megalithlabs/x402For viem WalletClient support (hardware wallets, WalletConnect, etc.):
npm install @megalithlabs/x402 viemNote: viem is an optional peer dependency. Only install it if you need WalletClient support for hardware wallets, WalletConnect, or other advanced wallet integrations. The simple approach using private keys works with just ethers (included by default).
Quick Start
Paying for APIs (Payer)
Simple approach (private key):
const { createSigner, x402Fetch } = require('@megalithlabs/x402');
// Create signer with your wallet
const signer = await createSigner('bsc', process.env.PRIVATE_KEY);
// Wrap fetch to auto-handle 402 responses
const fetchWithPay = x402Fetch(fetch, signer, { maxAmount: '0.50' });
// Use it like normal fetch - payments happen automatically
const response = await fetchWithPay('https://api.example.com/premium-data');
const data = await response.json();Advanced approach (viem wallet client):
Requires viem: Run
npm install viemfirst.
const { createSigner, x402Fetch } = require('@megalithlabs/x402');
const { createWalletClient, http } = require('viem');
const { bsc } = require('viem/chains');
const { privateKeyToAccount } = require('viem/accounts');
// Create viem wallet client (supports hardware wallets, WalletConnect, etc.)
const walletClient = createWalletClient({
account: privateKeyToAccount(process.env.PRIVATE_KEY),
chain: bsc,
transport: http()
});
// Pass the wallet client directly
const signer = await createSigner(walletClient);
// Same usage from here
const fetchWithPay = x402Fetch(fetch, signer, { maxAmount: '0.50' });
const response = await fetchWithPay('https://api.example.com/premium-data');Charging for APIs (Payee)
const express = require('express');
const { x402Express } = require('@megalithlabs/x402');
const app = express();
// USDC on bsc
const USDT = '0x55d398326f99059fF775485246999027B3197955';
// Add payment requirement to routes
app.use(x402Express('0xYourWalletAddress', {
'/api/premium': {
amount: '0.01', // 0.01 USDT (human-readable)
asset: USDT, // Token address
network: 'bsc' // Network
}
}));
app.get('/api/premium', (req, res) => {
res.json({ data: 'premium content' });
});
app.listen(3000);API Reference
createSigner(network, privateKey) OR createSigner(walletClient)
Create a signer for x402 payments. Supports two approaches:
Simple approach (private key):
const signer = await createSigner('bsc', '0xabc123...');| Parameter | Type | Description |
|-----------|------|-------------|
| network | string |'bsc', 'bsc-testnet', 'base', 'base-sepolia' |
| privateKey | string | Wallet private key (hex string) |
Advanced approach (viem wallet client):
Requires viem: Run
npm install viemfirst.
const { createWalletClient, http } = require('viem');
const { bsc } = require('viem/chains');
const { privateKeyToAccount } = require('viem/accounts');
// With private key
const walletClient = createWalletClient({
account: privateKeyToAccount('0xabc123...'),
chain: bsc,
transport: http()
});
// With hardware wallet (Ledger)
const walletClient = createWalletClient({
account: await ledger.getAccount(),
chain: bsc,
transport: http()
});
// With WalletConnect
const walletClient = createWalletClient({
account: walletConnectAccount,
chain: bsc,
transport: http()
});
const signer = await createSigner(walletClient);| Parameter | Type | Description |
|-----------|------|-------------|
| walletClient | WalletClient | viem WalletClient with account and chain configured |
The viem approach supports:
- Hardware wallets (Ledger, Trezor)
- WalletConnect
- Smart contract wallets
- MPC wallets
- Browser extension wallets
x402Fetch(fetch, signer, options)
Wrap fetch to automatically handle 402 Payment Required responses.
const fetchWithPay = x402Fetch(fetch, signer, { maxAmount: '0.50' });
const response = await fetchWithPay('https://api.example.com/data');| Option | Type | Required | Description |
|--------|------|----------|-------------|
| maxAmount | string | Yes | Maximum payment per request (e.g., '0.50') |
| facilitator | string | No | Custom facilitator URL (default: Megalith) |
x402Axios(axiosInstance, signer, options)
Wrap axios to automatically handle 402 Payment Required responses.
const axios = require('axios');
const axiosWithPay = x402Axios(axios.create(), signer, { maxAmount: '0.50' });
const response = await axiosWithPay.get('https://api.example.com/data');Same options as x402Fetch.
x402Express(payTo, routes, options)
Express middleware to require payment for routes.
const USDC = '0x55d398326f99059fF775485246999027B3197955';
app.use(x402Express('0xYourAddress', {
'/api/premium': { amount: '0.01', asset: USDT, network: 'bsc' },
'/api/expensive': { amount: '1.00', asset: USDT, network: 'bsc' }
}));| Parameter | Type | Description |
|-----------|------|-------------|
| payTo | string | Address to receive payments |
| routes | object | Route → config mapping |
| options.facilitator | string | Custom facilitator URL |
Route config:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| amount | string | Yes | Amount in tokens (e.g., '0.01') - human-readable |
| asset | string | Yes | Token contract address |
| network | string | Yes | Blockchain network |
| description | string | No | Human-readable description |
The SDK automatically fetches the token's decimals from the blockchain to convert your human-readable amount to atomic units.
x402Hono(payTo, routes, options)
Hono middleware to require payment for routes.
const { Hono } = require('hono');
const { x402Hono } = require('@megalithlabs/x402');
const USDT = '0x55d398326f99059fF775485246999027B3197955';
const app = new Hono();
app.use('*', x402Hono('0xYourAddress', {
'/api/premium': { amount: '0.01', asset: USDT, network: 'bsc' }
}));Same parameters as x402Express.
x402Next(handler, config, options)
Wrap Next.js API route handlers with payment requirement.
// pages/api/premium.js
const { x402Next } = require('@megalithlabs/x402');
const USDT = '0x55d398326f99059fF775485246999027B3197955';
export default x402Next(
async (req, res) => {
res.json({ data: 'premium content' });
},
{
payTo: '0xYourAddress',
amount: '0.01',
asset: USDT,
network: 'bsc'
}
);Supported Networks
| Network | Chain ID | Description |
|---------|----------|-------------|
| bsc | 56 | BNB Chain Mainnet |
| bsc-testnet | 97 | BNB Chain Testnet |
| base | 8453 | Base Mainnet |
| base-sepolia | 84532 | Base Testnet |
How It Works
Payer Flow
- Your code calls
fetchWithPay('https://api.example.com/data') - API returns
402 Payment Requiredwith payment requirements - SDK reads requirements, signs payment with your wallet
- SDK retries request with
X-PAYMENTheader - API verifies payment, returns data
Payee Flow
- Request arrives at your Express/Hono/Next server
- Middleware checks if route requires payment
- No
X-PAYMENTheader? Return 402 with requirements - Has payment? Verify and settle via facilitator
- Payment confirmed? Continue to your route handler
CLI Tools
For manual testing and learning, standalone CLI tools are available in the x402 repository:
git clone https://github.com/MegalithLabs/x402.git
cd x402/tools
# Create payment authorization (interactive)
node signer.js
# Approve Stargate for ERC-20 tokens
node approve.jsSee /tools/README.md in the repository for details.
Debugging
The SDK includes debug logging powered by the debug package. Enable it by setting the DEBUG environment variable:
# Enable all x402 debug output
DEBUG=x402:* node app.js
# Enable only payer debug (client-side)
DEBUG=x402:payer node app.js
# Enable only payee debug (server-side)
DEBUG=x402:payee node app.js
# Enable multiple namespaces
DEBUG=x402:payer,x402:signer node app.js
# Save debug output to a file
DEBUG=x402:* node app.js 2> debug.logExample output:
x402:payer Request to https://api.example.com/premium +0ms
x402:payer Got 402 Payment Required +125ms
x402:payer Payment requirements: { scheme: 'exact', network: 'bsc', ... } +2ms
x402:payer Creating payment... +0ms
x402:payer Payment created, signature: 0x1a2b3c... +340ms
x402:payer Verifying payment with facilitator: https://x402.megalithlabs.ai +0ms
x402:payer Payment verified successfully +89ms
x402:payer Retrying request with X-PAYMENT header +0ms
x402:payer Final response: 200 +201msAvailable namespaces:
x402:payer- Client-side payment flow (fetch/axios wrappers)x402:payee- Server-side middleware (Express/Hono/Next.js)x402:signer- Wallet signer initialization
Support
- Website: https://megalithlabs.ai
- x402 Protocol: https://x402.org
- Issues: https://github.com/MegalithLabs/x402/issues
- Email: [email protected]
License
MIT License
