npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@402exchange/sdk

v0.1.0

Published

JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol

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/sdk

or

yarn add @402exchange/sdk

or

pnpm add @402exchange/sdk

Quick 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:

  1. Initial Request: SDK makes a request to your API endpoint
  2. 402 Response: If payment required, server responds with 402 Payment Required and payment instructions
  3. Payment Processing: SDK processes payment through 402exchange backend
  4. Retry with Payment: SDK retries the request with X-PAYMENT header
  5. 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

Resources

License

MIT

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

Support


Built with ❤️ for the future of AI-powered commerce