
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
@402exchange/sdk
Advanced tools
JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol
JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol.
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:
npm install @402exchange/sdk
or
yarn add @402exchange/sdk
or
pnpm add @402exchange/sdk
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);
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)
}
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
});
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);
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);
const result = await api.call(
{ data: 'update' },
{ method: 'PUT' }
);
const history = await api.getTransactionHistory(50);
history.forEach(tx => {
console.log(`${tx.timestamp}: ${tx.amount} sats - ${tx.txHash}`);
});
create402API(config: SDK402Config): API402Factory function that creates a new API instance.
Parameters:
config: SDK configuration objectReturns: API402 instance
API402initialize(): 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);
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)
}
CallOptionsinterface CallOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers?: Record<string, string>;
body?: unknown;
params?: Record<string, string | number | boolean>;
}
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);
}
}
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);
}
);
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'
});
The SDK implements the x402 protocol flow:
402 Payment Required and payment instructionsX-PAYMENT headerAll of this happens transparently - you just call api.call() and the SDK handles the rest!
MIT
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
Built with ❤️ for the future of AI-powered commerce
FAQs
JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol
We found that @402exchange/sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.