@wintyx/x402-sdk

June 2, 2026 · View on GitHub

npm License: MIT TypeScript x402 Protocol

@wintyx/x402-sdk

TypeScript SDK for integrating x402 Bazaar APIs into AI agents.

Handles the full HTTP 402 payment cycle automatically: detect 402 response, pay USDC on-chain (Base, SKALE, or Polygon), retry with transaction proof. Zero configuration required — the SDK auto-generates and encrypts a wallet if no private key is provided.

Installation

npm install @wintyx/x402-sdk

Quick Start

import { createClient } from '@wintyx/x402-sdk';

// Zero-config: auto-generates an encrypted wallet on first use
const client = createClient({ chain: 'skale' });

// Or provide your own private key
// const client = createClient({
//   privateKey: process.env.AGENT_PRIVATE_KEY as `0x${string}`,
//   chain: 'skale',
// });

// List available APIs
const services = await client.listServices();

// Call an API with automatic payment (detects 402, pays USDC, retries)
const result = await client.call('service-id', { text: 'Hello world' });

// Check wallet balance
const balance = await client.getBalance();
console.log(`${balance} USDC available`);

Auto-Wallet

When no privateKey is provided, the SDK automatically:

  1. Generates a new Ethereum private key
  2. Encrypts it with AES-256-GCM (key derived from machine identity: hostname + username + homedir)
  3. Persists it to ~/.x402-bazaar/sdk-wallet.json
  4. Reuses the same wallet on subsequent calls

The wallet file is distinct from the MCP wallet (wallet.json) to avoid collisions. Fund it with USDC to start calling paid APIs.

import { createClient, loadOrCreateWallet } from '@wintyx/x402-sdk';

// Auto-wallet (recommended for agents)
const client = createClient({ chain: 'skale' });
console.log(`Wallet: ${client.walletAddress}`);

// Or manage the wallet directly
const wallet = loadOrCreateWallet();
console.log(`Address: ${wallet.address}, new: ${wallet.isNew}`);

API

createClient(config) — Factory function

The recommended way to create a client.

const client = createClient({
  chain: 'skale',
  budget: { max: 5.0, period: 'daily' },
  timeout: 30000,
});
OptionTypeDefaultDescription
privateKey`0x${string}`auto-generatedAgent wallet private key (optional — auto-generates encrypted wallet if omitted)
chain'base' | 'base-sepolia' | 'skale' | 'polygon''skale'Blockchain network
networksame as chain'skale'Alias for chain
baseUrlstringhttps://x402-api.onrender.comBazaar API URL
budget{ max: number, period: 'daily'|'weekly'|'monthly' }unlimitedSpending cap (local tracking)
timeoutnumber30000HTTP timeout in ms
walletPathstring~/.x402-bazaar/sdk-wallet.jsonCustom path for auto-generated wallet file

client.call(serviceId, params?, options?)

Calls a Bazaar service by its UUID via the proxy endpoint (POST /api/call/:serviceId). If the API returns 402, the SDK pays automatically and retries. The server handles the 95/5 revenue split.

// Simple call
const weather = await client.call('uuid-weather', { city: 'Paris' })

// With options
const image = await client.call('uuid-image', { prompt: 'A sunset' }, {
  timeout: 60000,
  maxRetries: 2,
})

client.listServices()

Returns all services available on the Bazaar.

const services = await client.listServices();
// ServiceInfo[] with id, name, description, url, price_usdc, category, ...

client.searchServices(query)

Searches services by name, description, category, or tags (client-side filtering).

const aiServices = await client.searchServices('image generation');
const weatherApis = await client.searchServices('weather');

client.getService(serviceId)

Returns a single service by its UUID.

const service = await client.getService('uuid-weather');
// { id, name, description, url, price_usdc, category, ... }

client.getBalance()

Returns the USDC balance of the agent wallet on the configured chain.

const balance = await client.getBalance();  // e.g. 4.523

client.getBudgetStatus()

Returns current budget usage (local tracking, resets automatically each period).

const budget = client.getBudgetStatus();
// {
//   spent: 0.15,
//   limit: 1.0,
//   remaining: 0.85,
//   period: 'daily',
//   callCount: 12,
//   resetAt: Date | null
// }

client.health()

Checks the Bazaar backend status.

const health = await client.health();
// { status: 'ok', version: '1.1.0', network: 'SKALE', uptime_seconds: 3600 }

client.fundWallet()

Returns funding instructions to bridge USDC from any chain to SKALE via the Trails SDK. No network call — returns local info instantly.

const funding = await client.fundWallet();
// {
//   bridgeUrl: 'https://x402bazaar.org/fund',
//   walletAddress: '0x...',
//   supportedChains: ['Ethereum', 'Polygon', 'Arbitrum', 'Optimism', 'Base'],
//   bridgeTime: '5-15 minutes (IMA bridge to SKALE)',
//   minimumAmount: '0.10 USDC',
//   howItWorks: 'Trails SDK routes tokens from any chain → USDC on Base → IMA bridge → SKALE on Base.'
// }

client.callDirect(endpoint, params?, options?)

Calls an API endpoint directly (bypasses the proxy). Use call() instead when possible to benefit from the server-side 95/5 revenue split.

const result = await client.callDirect('/api/search', { q: 'AI tools' });

client.discover(endpoint?)

Backward-compatible method. Without argument: returns all services. With an endpoint path: returns the matching service.

const services = await client.discover();           // ServiceInfo[]
const service  = await client.discover('/api/search'); // ServiceInfo

Error Handling

import {
  BudgetExceededError,
  InsufficientBalanceError,
  PaymentError,
  ApiError,
  NetworkError,
  TimeoutError,
} from '@wintyx/x402-sdk';

try {
  const result = await client.call('uuid-image', { prompt: 'A cat' });
} catch (err) {
  if (err instanceof BudgetExceededError) {
    console.error(`Budget ${err.period} depleted: ${err.spent}/${err.limit} USDC`);
  } else if (err instanceof InsufficientBalanceError) {
    console.error(`Wallet needs ${err.required} USDC, only has ${err.available}`);
  } else if (err instanceof PaymentError) {
    console.error('USDC transfer failed:', err.message);
  } else if (err instanceof ApiError) {
    console.error(`API error ${err.statusCode} on ${err.endpoint}`);
  } else if (err instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (err instanceof NetworkError) {
    console.error('Network error:', err.message);
  }
}

Supported Networks

NetworkChain IDUSDC ContractGas
base84530x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913~$0.001
base-sepolia845320x036CbD53842c5426634e7929541eC2318f3dCF7eTestnet
skale11879479330x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20~$0.0007 (CREDITS)
polygon1370x3c499c542cEF5E3811e1192ce70d8cC03d5c3359~$0.001 (MATIC)

SKALE on Base offers ultra-low gas fees via CREDITS token (~$0.0007 per transfer). Each RPC has fallback endpoints configured automatically.

Protocol Flow

1. client.call('uuid-weather', { city: 'Paris' })
   └─> GET https://x402-api.onrender.com/api/call/uuid-weather?city=Paris
       └─> 402 Payment Required
           {
             payment_details: {
               amount: 0.002,
               recipient: '0xfb1c...',
               networks: [{ network: 'base', chainId: 8453, ... }]
             }
           }

2. SDK pays automatically
   └─> USDC.transfer(recipient, 0.002 USDC) on Base
       └─> txHash: 0xabc123...

3. SDK retries with payment proof
   └─> GET /api/call/uuid-weather?city=Paris
       Headers: X-Payment-TxHash: 0xabc123...
                X-Payment-Chain: base
       └─> 200 OK { temperature: 18, condition: 'Sunny', ... }

CommonJS Support

The SDK ships both ESM and CJS builds:

// CommonJS
const { createClient } = require('@wintyx/x402-sdk');
// ESM / TypeScript
import { createClient } from '@wintyx/x402-sdk';

Available APIs (155 services, 101 native endpoints)

EndpointPriceDescription
/api/search0.005 USDCWeb search (DuckDuckGo)
/api/scrape0.005 USDCWeb scraper
/api/image0.05 USDCImage generation (DALL-E 3)
/api/weather0.002 USDCWeather data
/api/translate0.005 USDCText translation
/api/summarize0.01 USDCText summarization (GPT)
/api/sentiment0.005 USDCSentiment analysis
/api/geocoding0.002 USDCGeocoding
/api/crypto0.001 USDCCrypto prices
/api/stocks0.005 USDCStock prices
/api/news0.005 USDCLatest news
...100+ more

Full list: x402bazaar.org/services or client.listServices()

Ecosystem

RepositoryDescription
x402-backendAPI server, 101 native endpoints, payment middleware, MCP server
x402-frontendReact + TypeScript marketplace UI
x402-bazaar-clinpx x402-bazaar — CLI with 7 commands
x402-sdkTypeScript SDK for AI agents (this repo)
x402-langchainPython LangChain tools
n8n-nodes-x402-bazaarn8n community node

Live: x402bazaar.org | API: x402-api.onrender.com

License

MIT