@testingtest001/x402
v1.0.0
Published
TypeScript SDK for CheckPoint x402 payment facilitator
Maintainers
Readme
@checkpoint/x402
TypeScript SDK for the CheckPoint x402 payment facilitator on Base.
Installation
npm install @checkpoint/x402
# or
pnpm add @checkpoint/x402
# or
yarn add @checkpoint/x402Quick Start
import { CheckPointClient } from '@checkpoint/x402';
const checkpoint = new CheckPointClient();
// Check platform health
const health = await checkpoint.health();
console.log('Status:', health.status);Payment Flow
1. Verify Payment
Verify a payment signature before serving content:
const result = await checkpoint.verify({
paymentPayload: {
x402Version: 2,
accepted: {
scheme: 'exact',
network: 'eip155:8453',
asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
payTo: '0xMerchantWallet',
maxTimeoutSeconds: 3600
},
payload: {
signature: '0x...',
authorization: {
from: '0xPayerWallet',
to: '0xMerchantWallet',
value: '10000',
validAfter: '0',
validBefore: '1735000000',
nonce: '0x...'
}
}
},
paymentRequirements: {
scheme: 'exact',
network: 'eip155:8453',
amount: '10000',
asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
payTo: '0xMerchantWallet',
maxTimeoutSeconds: 3600
}
});
if (result.valid) {
console.log('Payment valid from:', result.payer);
}2. Settle Payment
Execute the USDC transfer on-chain:
const settlement = await checkpoint.settle({
paymentPayload: { /* same as verify */ },
paymentRequirements: { /* same as verify */ }
});
if (settlement.success) {
console.log('TX Hash:', settlement.txHash);
console.log('Block:', settlement.blockNumber);
}3. Verify and Settle (Convenience)
const result = await checkpoint.verifyAndSettle({
paymentPayload: { ... },
paymentRequirements: { ... }
});Batch Settlements
Settle multiple payments in one call (60-80% gas savings):
const batch = await checkpoint.batchSettle({
payments: [
{ paymentPayload: payload1, paymentRequirements: req1 },
{ paymentPayload: payload2, paymentRequirements: req2 }
]
});
console.log(`Settled ${batch.summary.succeeded} of ${batch.summary.total}`);
console.log('Total gas:', batch.summary.gasTotal);Error Handling
Error Codes
The SDK provides typed error codes for precise error handling:
import { CheckPointClient, CheckPointError } from '@checkpoint/x402';
try {
const result = await checkpoint.verify({ ... });
} catch (error) {
if (error instanceof CheckPointError) {
switch (error.code) {
// Verification Errors
case 'INVALID_SIGNATURE':
console.log('EIP-712 signature verification failed');
break;
case 'EXPIRED_AUTHORIZATION':
console.log('validBefore timestamp has passed - re-sign');
break;
case 'PREMATURE_AUTHORIZATION':
console.log('validAfter timestamp not yet reached');
break;
case 'INSUFFICIENT_BALANCE':
console.log('Payer needs more USDC');
break;
case 'AMOUNT_MISMATCH':
console.log('Amount doesnt match requirements');
break;
case 'NONCE_ALREADY_USED':
console.log('Replay detected - generate new nonce');
break;
// Settlement Errors
case 'VERIFICATION_REQUIRED':
console.log('Must verify before settling');
break;
case 'ALREADY_SETTLED':
console.log('Payment already processed');
break;
case 'INSUFFICIENT_GAS':
console.log('Facilitator needs ETH for gas');
break;
case 'TRANSACTION_REVERTED':
console.log('On-chain transaction reverted');
break;
}
}
}Automatic Retry
The SDK automatically retries on network errors and 5xx responses:
const checkpoint = new CheckPointClient({
retry: {
maxRetries: 3, // Default: 3
baseDelay: 1000, // Default: 1000ms
maxDelay: 10000 // Default: 10000ms (exponential backoff capped)
}
});Error Properties
catch (error) {
if (error instanceof CheckPointError) {
console.log('HTTP Status:', error.status); // 0 for network errors
console.log('Error Code:', error.code); // Typed error code
console.log('Message:', error.message); // Human-readable message
if (error.isRetryable) {
console.log('Can retry this error');
}
if (error.isClientError) {
console.log('Client-side error (4xx)');
}
}
}Payment Status
Check the status of a payment by nonce:
const status = await checkpoint.status({
nonce: '0x...',
network: 'eip155:8453',
payer: '0x...'
});
switch (status.status) {
case 'pending': console.log('Not yet verified'); break;
case 'verified': console.log('Ready to settle'); break;
case 'settling': console.log('Settlement in progress'); break;
case 'settled': console.log('TX:', status.txHash); break;
case 'failed': console.log('Error:', status.error); break;
}Receipts
Get a signed receipt for a settled payment:
const receipt = await checkpoint.receipt('0x...txHash');
console.log('Payer:', receipt.receipt.payer);
console.log('Amount:', receipt.receipt.amount);
console.log('Block:', receipt.receipt.blockNumber);Service Discovery
// List all x402-enabled services
const { services, count } = await checkpoint.discovery.list();
// Register a service (requires API key)
const checkpoint = new CheckPointClient({
apiKey: 'your-api-key'
});
const service = await checkpoint.discovery.register({
name: 'My AI Service',
description: 'GPT-powered analysis',
url: 'https://api.myservice.com',
paymentEndpoint: '/v1/analyze',
networks: ['eip155:8453'],
assets: [{
network: 'eip155:8453',
address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
symbol: 'USDC'
}],
pricing: {
model: 'per_request',
amount: '10000',
currency: 'USDC'
},
categories: ['AI'],
owner: '0xYourWallet'
});TypeScript Types
All types are exported:
import type {
// Core payment types
PaymentPayload,
PaymentRequirements,
EIP3009Authorization,
// Request/Response types
VerifyRequest,
VerifyResponse,
SettleRequest,
SettleResponse,
BatchSettleRequest,
BatchSettleResponse,
// Error codes
VerificationErrorCode,
SettlementErrorCode,
// Status types
PaymentStatus,
StatusRequest,
StatusResponse,
ReceiptResponse,
// Health & Discovery
HealthResponse,
Service,
// Helpers
SupportedNetwork
} from '@checkpoint/x402';Constants
import { USDC_ADDRESSES, DEFAULT_CHECKPOINT_URL } from '@checkpoint/x402';
console.log(USDC_ADDRESSES['eip155:8453']); // Base Mainnet USDC
console.log(USDC_ADDRESSES['eip155:84532']); // Base Sepolia USDC
console.log(DEFAULT_CHECKPOINT_URL); // https://checkpoint-pied.vercel.appConfiguration
const checkpoint = new CheckPointClient({
baseUrl: 'https://checkpoint-pied.vercel.app', // Default
apiKey: 'your-api-key', // For authenticated endpoints
timeout: 30000, // Request timeout (ms)
retry: {
maxRetries: 3,
baseDelay: 1000,
maxDelay: 10000
}
});Links
License
MIT
