@402exchange/sdk
v0.1.0
Published
JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol
Maintainers
Readme
@402exchange/sdk
JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol.
What is x402?
x402 is an open standard for internet-native payments built on HTTP. It leverages the HTTP 402 Payment Required status code to enable seamless machine-to-machine payments, making it perfect for AI agents accessing paid APIs.
Key Features:
- ⚡ Fast: ~2 second settlement time
- 💰 Cheap: Near-zero transaction costs, payments as low as $0.001
- 🔗 Chain Agnostic: Works with any blockchain
- 🤖 AI-Ready: Designed for autonomous agent payments
Installation
npm install @402exchange/sdkor
yarn add @402exchange/sdkor
pnpm add @402exchange/sdkQuick Start
import { create402API } from '@402exchange/sdk';
// Create an API instance
const myAPI = create402API({
apiKey: 'your-402exchange-api-key',
endpoint: 'https://api.example.com/v1/data',
pricePerCall: 100 // sats or smallest currency unit
});
// Make a call - the SDK handles all x402 protocol logic
const result = await myAPI.call({
query: 'your data request'
});
console.log(result.data);Configuration
SDK402Config
interface SDK402Config {
apiKey: string; // Your 402exchange API key (required)
endpoint: string; // The API endpoint to protect (required)
pricePerCall: number; // Price per call in sats (required)
baseUrl?: string; // 402exchange backend URL (optional)
network?: string; // Blockchain network (default: "base-mainnet")
timeoutSeconds?: number; // Payment timeout (default: 300)
facilitatorUrl?: string; // x402 facilitator URL (optional)
}Example Configuration
const api = create402API({
apiKey: 'sk_live_abc123...',
endpoint: 'https://api.yourservice.com/v1/predict',
pricePerCall: 1000, // 1000 sats per call
network: 'base-mainnet',
timeoutSeconds: 600 // 10 minutes
});Usage Examples
Basic POST Request
const api = create402API({
apiKey: 'your-api-key',
endpoint: 'https://api.example.com/analyze',
pricePerCall: 50
});
const result = await api.post({
text: 'Analyze this content',
options: { detailed: true }
});
console.log(result.data);GET Request with Query Parameters
const api = create402API({
apiKey: 'your-api-key',
endpoint: 'https://api.example.com/data',
pricePerCall: 25
});
const result = await api.get({
id: '12345',
format: 'json'
});
console.log(result.data);Custom HTTP Methods
const result = await api.call(
{ data: 'update' },
{ method: 'PUT' }
);Access Transaction History
const history = await api.getTransactionHistory(50);
history.forEach(tx => {
console.log(`${tx.timestamp}: ${tx.amount} sats - ${tx.txHash}`);
});API Reference
create402API(config: SDK402Config): API402
Factory function that creates a new API instance.
Parameters:
config: SDK configuration object
Returns: API402 instance
Class: API402
Methods
initialize(): Promise<void>
Initializes the SDK and validates the API key. This is called automatically on the first API call.
await api.initialize();call<T>(params?, options?): Promise<CallResult<T>>
Makes a request to the protected API endpoint. Automatically handles the x402 payment protocol.
Parameters:
params: Request body/data (optional)options: Call options including method, headers, etc. (optional)
Returns: Promise resolving to CallResult<T>
const result = await api.call({ query: 'data' });get<T>(params?): Promise<CallResult<T>>
Convenience method for GET requests.
const result = await api.get({ id: '123' });post<T>(body?): Promise<CallResult<T>>
Convenience method for POST requests.
const result = await api.post({ data: 'value' });getTransactionHistory(limit?): Promise<TransactionLog[]>
Fetches transaction history for the API key.
Parameters:
limit: Maximum number of transactions to return (default: 50)
const history = await api.getTransactionHistory(100);getConfig(): Readonly<Required<SDK402Config>>
Returns the current configuration.
const config = api.getConfig();
console.log(config.pricePerCall);Types
CallResult<T>
interface CallResult<T> {
data: T; // Response data
status: number; // HTTP status code
headers: Record<string, string>; // Response headers
paymentReceipt?: string; // Payment receipt (if payment was made)
}CallOptions
interface CallOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers?: Record<string, string>;
body?: unknown;
params?: Record<string, string | number | boolean>;
}Error Handling
The SDK provides specific error types for different failure scenarios:
import {
PaymentRequiredError,
PaymentVerificationError,
PaymentSettlementError
} from '@402exchange/sdk';
try {
const result = await api.call({ data: 'request' });
} catch (error) {
if (error instanceof PaymentRequiredError) {
console.log('Payment required:', error.paymentRequirements);
} else if (error instanceof PaymentVerificationError) {
console.log('Payment verification failed:', error.reason);
} else if (error instanceof PaymentSettlementError) {
console.log('Payment settlement failed:', error.message);
} else {
console.log('API call failed:', error);
}
}Advanced Usage
Direct x402 Protocol Handler
For advanced use cases, you can use the low-level x402 protocol handler directly:
import { executeX402Request } from '@402exchange/sdk';
const result = await executeX402Request(
'https://api.example.com/endpoint',
{ method: 'POST', body: { data: 'value' } },
async (requirements) => {
// Custom payment handler
// Return a PaymentPayload
return myCustomPaymentLogic(requirements);
}
);Custom Backend Client
import { createBackendClient } from '@402exchange/sdk';
const backend = createBackendClient('https://your-backend.com');
// Validate API key
const validation = await backend.validateApiKey('your-key');
// Log API call
const log = await backend.logApiCall('your-key', '/endpoint', 100);
// Process payment
const payment = await backend.processPayment('your-key', {
amount: 100,
network: 'base-mainnet',
endpoint: '/api/data'
});How It Works
The SDK implements the x402 protocol flow:
- Initial Request: SDK makes a request to your API endpoint
- 402 Response: If payment required, server responds with
402 Payment Requiredand payment instructions - Payment Processing: SDK processes payment through 402exchange backend
- Retry with Payment: SDK retries the request with
X-PAYMENTheader - Access Granted: Server verifies payment and returns requested data
All of this happens transparently - you just call api.call() and the SDK handles the rest!
Requirements
- Node.js >= 16.0.0
- A 402exchange API key (sign up at 402exchange.com)
Resources
License
MIT
Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
Support
- Documentation: 402exchange.com/docs
- Email: [email protected]
- GitHub Issues: Report a bug
Built with ❤️ for the future of AI-powered commerce
