# BoltzPay SDK — Complete Reference > Universal TypeScript SDK for paying APIs. Handles protocol detection, wallet management, budget enforcement, and payment execution across x402, L402, and MPP. ## Installation ```bash npm install @boltzpay/sdk # Optional packages: npm install @boltzpay/cli # CLI tool npm install @boltzpay/mcp # MCP server for AI agents ``` ## Quick Start ```typescript import { BoltzPay } from "@boltzpay/sdk"; const agent = new BoltzPay({ wallets: [{ type: "tempo", name: "main", tempoPrivateKey: process.env.TEMPO_PRIVATE_KEY!, }], budget: { daily: "5.00", perTransaction: "1.00" }, }); // Pay for an API call — protocol detected automatically const response = await agent.fetch("https://api.example.com/data"); console.log(response.status, response.payment); const data = await response.json(); // Discover paid endpoints from the registry const endpoints = await agent.discover({ protocol: "mpp", minScore: 80 }); // Clean up agent.close(); ``` ## Configuration (BoltzPayConfig) All fields are optional. Validated via Zod at construction. ```typescript const agent = new BoltzPay({ // --- Wallet configuration (new multi-wallet API) --- wallets: [ // See "Wallet Types" section below for all 5 types ], // --- Legacy single-wallet (still supported) --- coinbaseApiKeyId: string, // Coinbase CDP API key ID coinbaseApiKeySecret: string, // Coinbase CDP API key secret coinbaseWalletSecret: string, // Coinbase CDP wallet secret nwcConnectionString: string, // "nostr+walletconnect://..." for Lightning // --- Network --- network: "base" | "base-sepolia", // Default: "base" preferredChains: ("evm" | "svm")[], // Chain preference order // --- Budget --- budget: { daily: string | number, // e.g. "10.00" or 10 monthly: string | number, perTransaction: string | number, warningThreshold: number, // 0-1, default 0.8 satToUsdRate: number, // Default: 0.001 }, // --- Storage --- storage: "file" | "memory" | { type: "file", dir: string, // Custom directory maxHistoryRecords: number, // Default: 1000 } | StorageAdapter, // Custom adapter (get/set/delete/keys) // --- Timeouts (ms) --- timeouts: { detect: number, // Default: 10000 quote: number, // Default: 15000 payment: number, // Default: 30000 }, // --- Safety --- maxAmountPerRequest: string | number, // Hard cap per request allowlist: string[], // Only these domains blocklist: string[], // Block these domains // --- Retry --- retry: { maxRetries: number, // Default: 3 backoffMs: number, // Default: 200 }, rateLimit: { strategy: "wait" | "error", // Default: "wait" maxWaitMs: number, // Default: 60000 }, // --- MPP --- mppPreferredMethods: string[], // e.g. ["tempo", "stripe"] registryUrl: string, // Default: "https://status.boltzpay.ai" sessionMaxDeposit: string | number, // Max deposit for openSession() // --- Logging --- logLevel: "debug" | "info" | "warn" | "error" | "silent", // Default: "warn" logFormat: "text" | "json", // Default: "text" }); ``` ## Wallet Types Five wallet types supported. Configure via the `wallets` array. ### coinbase — EVM/SVM on-chain payments (x402) ```typescript { type: "coinbase", name: "main", coinbaseApiKeyId: "...", coinbaseApiKeySecret: "...", coinbaseWalletSecret: "...", networks: ["evm"] } ``` ### nwc — Lightning Network (L402, MPP lightning) ```typescript { type: "nwc", name: "lightning", nwcConnectionString: "nostr+walletconnect://..." } ``` ### tempo — Tempo payments (MPP) ```typescript { type: "tempo", name: "tempo-main", tempoPrivateKey: "0x..." } ``` ### stripe-mpp — Stripe payments (MPP) ```typescript { type: "stripe-mpp", name: "stripe", stripeSecretKey: "sk_..." } ``` ### visa-mpp — Visa payments (MPP) ```typescript { type: "visa-mpp", name: "visa", visaJwe: "..." } ``` All wallet types accept an optional `networks: string[]` to restrict which networks they can pay on. ## Public API — BoltzPay class ### fetch(url, options?) → Promise Fetches a URL, automatically detecting and paying any required protocol. ```typescript const res = await agent.fetch("https://api.example.com/resource", { maxAmount: "2.00", // Override per-request max headers: { "X-Custom": "value" }, method: "POST", body: new Uint8Array(...), chain: "evm", // Force specific chain namespace dryRun: false, }); // BoltzPayResponse properties: res.ok // boolean res.status // number res.headers // Headers res.payment // { protocol, amount, url, timestamp, txHash } res.protocol // "x402" | "l402" | "mpp" await res.json() await res.text() await res.arrayBuffer() ``` ### fetch(url, { dryRun: true }) → Promise Simulates a payment without executing it. ```typescript const dry = await agent.fetch("https://api.example.com/resource", { dryRun: true }); // { wouldPay: boolean, reason?: string, quote?, budgetCheck?, wallet? } ``` ### discover(options?) → Promise Queries the BoltzPay Registry for paid endpoints. ```typescript const entries = await agent.discover({ protocol: "mpp", // "x402" | "l402" | "mpp" minScore: 80, // 0-100 category: "AI", query: "image generation", limit: 20, // Default: 50, max: 200 offset: 0, signal: AbortSignal.timeout(5000), }); // DiscoveredEntry: // { slug, name, url, protocol, score, health, category, isPaid, badge } ``` ### quote(url) → Promise Gets a price quote without paying. ```typescript const q = await agent.quote("https://api.example.com/resource"); // { amount: Money, protocol: string, network?: string, allAccepts?, inputHints? } ``` ### openSession(url, options?) → Promise Opens a streaming payment session (MPP with Tempo wallet required). ```typescript const session = await agent.openSession("https://api.example.com/stream", { maxDeposit: "5.00", // Optional, respects budget signal: AbortSignal.timeout(30000), }); // Stream data with automatic micropayments for await (const event of session.stream()) { if (event.type === "data") console.log(event.payload); if (event.type === "payment") console.log("Voucher:", event.voucher); } // SessionEvent types: // { type: "data", payload: string } // { type: "payment", voucher: { channelId, cumulativeAmount: bigint, index: number } } const receipt = await session.close(); // SessionReceipt: { channelId, totalSpent: bigint, refunded: bigint, voucherCount } ``` ### wrapMcpClient(client) → WrappedMcpClient Wraps a MCP Client with automatic MPP payment handling for -32042 errors. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const mcpClient = new Client({ name: "my-agent", version: "1.0" }); // ... connect mcpClient to server ... const wrapped = agent.wrapMcpClient(mcpClient); const result = await wrapped.callTool({ name: "expensive_tool", arguments: { query: "test" } }); // Automatic payment if server returns -32042 // result: { content, isError?, _meta?, receipt?: { method, status, reference, timestamp } } ``` Requires at least one MPP wallet configured (tempo or stripe-mpp). ### diagnose(url) → Promise Diagnoses an endpoint's payment protocol support. ```typescript const diag = await agent.diagnose("https://api.example.com"); ``` ### getBudget() → BudgetState ```typescript const budget = agent.getBudget(); // { dailySpent, monthlySpent, dailyRemaining?, monthlyRemaining?, dailyLimit?, monthlyLimit? } ``` ### Other methods ```typescript agent.getHistory() // readonly PaymentRecord[] agent.getMetrics() // PaymentMetrics agent.exportHistory("csv") // string (csv or json) agent.getCapabilities() // { network, protocols, canPay, canPayLightning, chains, addresses } agent.getBalances() // { evm?: { address, balance }, svm?: { address, balance } } agent.getWalletStatus() // Full wallet diagnostic agent.resetDailyBudget() // Reset daily spend counter agent.close() // Cleanup (closes NWC connections) ``` ## Events Subscribe via `agent.on(event, listener)`, unsubscribe via `agent.off(event, listener)`. | Event | Payload | Description | |-------|---------|-------------| | `payment` | `PaymentRecord` | Successful payment executed | | `budget:warning` | `{ spent, limit, period, usage }` | Budget approaching threshold | | `budget:exceeded` | `{ requested, limit, period }` | Budget limit hit | | `retry:attempt` | `{ attempt, maxRetries, delay, phase, error }` | Retry in progress | | `retry:exhausted` | `{ maxRetries, phase, error }` | All retries failed | | `payment:uncertain` | `{ url, amount, protocol, error, nonce?, txHash? }` | Payment may have been sent (network error post-signature) | | `protocol:unsupported-scheme` | `{ scheme, maxAmount?, network?, url }` | Non-exact payment scheme detected | | `protocol:unsupported-network` | `{ namespace, url }` | Unsupported chain namespace | | `wallet:selected` | `{ walletName, network, reason }` | Wallet chosen for payment | | `session:open` | `{ channelId, depositAmount, url }` | Session opened | | `session:voucher` | `{ channelId, cumulativeAmount, index }` | Voucher issued during session | | `session:close` | `{ channelId, totalSpent, refunded }` | Session closed | | `session:error` | `{ channelId?, error }` | Session error | | `mcp:payment` | `{ toolName, amount, receipt }` | MCP tool payment executed | | `error` | `Error` | Any error | ## CLI ```bash npx @boltzpay/cli discover --protocol mpp --min-score 80 --category AI npx @boltzpay/cli discover --query "image" --json npx @boltzpay/cli fetch https://api.example.com/data npx @boltzpay/cli diagnose https://api.example.com npx @boltzpay/cli wallet-status npx @boltzpay/cli history --format csv ``` CLI reads config from environment variables or `~/.boltzpay/config.json`. ## MCP Server The `@boltzpay/mcp` package exposes SDK tools to AI agents via the Model Context Protocol. ### Tools exposed | Tool | Parameters | Description | |------|-----------|-------------| | `boltzpay_discover` | `category?, protocol?, minScore?, query?` | Browse paid APIs from registry | | `boltzpay_fetch` | `url, maxAmount?` | Fetch a paid API endpoint | | `boltzpay_quote` | `url` | Get price quote | | `boltzpay_diagnose` | `url` | Diagnose endpoint | | `boltzpay_wallet_status` | — | Get wallet status | | `boltzpay_budget` | — | Get budget state | ## Protocol Detection Priority 1. **MPP** — Checked first via POST probe 2. **x402** — HTTP 402 response with `X-Payment` or `WWW-Authenticate` headers 3. **L402** — HTTP 402 with Lightning macaroon challenge The SDK tries each detected protocol in order. If the first fails (e.g., no matching wallet), it falls back to the next. ## Error Types | Error Class | Codes | Description | |-------------|-------|-------------| | `BudgetExceededError` | `daily_exceeded`, `monthly_exceeded`, `per_transaction_exceeded` | Budget limit hit | | `ProtocolError` | `payment_failed`, `protocol_detection_failed`, `no_compatible_chain`, `x402_payment_failed` | Protocol-level failure | | `NetworkError` | `endpoint_unreachable`, `blockchain_error` | Network/infra failure | | `NoWalletError` | — | No wallet configured for required network | | `PaymentUncertainError` | — | Payment may have been sent (post-signature network error) | | `ConfigurationError` | `invalid_config`, `domain_blocked` | Config validation failure | | `MppSessionBudgetError` | — | Insufficient budget for session deposit | ## Registry Integration The SDK discovers endpoints from the BoltzPay Registry (status.boltzpay.ai) by default. ```typescript // Discover + fetch pattern const endpoints = await agent.discover({ protocol: "x402", minScore: 70, category: "AI" }); for (const ep of endpoints) { const res = await agent.fetch(ep.url); if (res.ok) console.log(await res.json()); } ``` Override registry URL: ```typescript const agent = new BoltzPay({ registryUrl: "https://custom-registry.example.com" }); ``` ## Links - Website: https://boltzpay.ai - Registry: https://status.boltzpay.ai - npm: https://www.npmjs.com/package/@boltzpay/sdk - Docs: https://docs.boltzpay.ai - Registry API docs: https://status.boltzpay.ai/llms-full.txt