{"_id":"@402exchange/sdk","name":"@402exchange/sdk","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@402exchange/sdk","version":"0.1.0","description":"JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"scripts":{"build":"tsup src/index.ts --format cjs,esm --dts --clean","dev":"tsup src/index.ts --format cjs,esm --dts --watch","test":"jest","test:watch":"jest --watch","prepublishOnly":"npm run build"},"keywords":["x402","402exchange","payment","api","ai-agents","micropayments","blockchain","http-402","paywall"],"author":{"name":"402exchange"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/yourusername/402exchange-sdk.git"},"bugs":{"url":"https://github.com/yourusername/402exchange-sdk/issues"},"homepage":"https://github.com/yourusername/402exchange-sdk#readme","devDependencies":{"@types/jest":"^29.5.12","@types/node":"^20.11.19","jest":"^29.7.0","ts-jest":"^29.1.2","tsup":"^8.0.2","typescript":"^5.3.3"},"dependencies":{},"engines":{"node":">=16.0.0"},"gitHead":"0e3f7d5e2b5bb3419d9c4ff5d9890bdc0f3d2f7f","_id":"@402exchange/sdk@0.1.0","_nodeVersion":"22.14.0","_npmVersion":"11.6.2","dist":{"integrity":"sha512-/ZFyJnFuQ9t5sizW87A3oAs8aoaK0P6sTRnrBxS9FArwmVE2SWyFxCuxONMuuGM/T9mba/1xCM3m4dvpMTk/UA==","shasum":"1f7262fdd56437552fee352c7761a2b9624a3108","tarball":"https://registry.npmjs.org/@402exchange/sdk/-/sdk-0.1.0.tgz","fileCount":7,"unpackedSize":61991,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDL0xwYyyXPQmTZXzjLttjFlu/w6kypLta5G+3iSkasDQIgMunZk/GPGfDt1DH4h65DI9KivyS3VVud5jP12Ks/YAY="}]},"_npmUser":{"name":"lance2","email":"lancelot.salavert@gmail.com"},"directories":{},"maintainers":[{"name":"lance2","email":"lancelot.salavert@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk_0.1.0_1761220398622_0.6141764617518575"},"_hasShrinkwrap":false}},"time":{"created":"2025-10-23T11:53:18.558Z","0.1.0":"2025-10-23T11:53:18.826Z","modified":"2025-10-23T11:53:19.096Z"},"maintainers":[{"name":"lance2","email":"lancelot.salavert@gmail.com"}],"description":"JavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the x402 protocol","homepage":"https://github.com/yourusername/402exchange-sdk#readme","keywords":["x402","402exchange","payment","api","ai-agents","micropayments","blockchain","http-402","paywall"],"repository":{"type":"git","url":"git+https://github.com/yourusername/402exchange-sdk.git"},"author":{"name":"402exchange"},"bugs":{"url":"https://github.com/yourusername/402exchange-sdk/issues"},"license":"MIT","readme":"# @402exchange/sdk\n\nJavaScript/TypeScript SDK for 402exchange - Enable AI agents to access your paid APIs using the [x402 protocol](https://x402.gitbook.io/x402).\n\n## What is x402?\n\nx402 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.\n\n**Key Features:**\n- ⚡ **Fast**: ~2 second settlement time\n- 💰 **Cheap**: Near-zero transaction costs, payments as low as $0.001\n- 🔗 **Chain Agnostic**: Works with any blockchain\n- 🤖 **AI-Ready**: Designed for autonomous agent payments\n\n## Installation\n\n```bash\nnpm install @402exchange/sdk\n```\n\nor\n\n```bash\nyarn add @402exchange/sdk\n```\n\nor\n\n```bash\npnpm add @402exchange/sdk\n```\n\n## Quick Start\n\n```typescript\nimport { create402API } from '@402exchange/sdk';\n\n// Create an API instance\nconst myAPI = create402API({\n  apiKey: 'your-402exchange-api-key',\n  endpoint: 'https://api.example.com/v1/data',\n  pricePerCall: 100 // sats or smallest currency unit\n});\n\n// Make a call - the SDK handles all x402 protocol logic\nconst result = await myAPI.call({\n  query: 'your data request'\n});\n\nconsole.log(result.data);\n```\n\n## Configuration\n\n### SDK402Config\n\n```typescript\ninterface SDK402Config {\n  apiKey: string;           // Your 402exchange API key (required)\n  endpoint: string;         // The API endpoint to protect (required)\n  pricePerCall: number;     // Price per call in sats (required)\n  baseUrl?: string;         // 402exchange backend URL (optional)\n  network?: string;         // Blockchain network (default: \"base-mainnet\")\n  timeoutSeconds?: number;  // Payment timeout (default: 300)\n  facilitatorUrl?: string;  // x402 facilitator URL (optional)\n}\n```\n\n### Example Configuration\n\n```typescript\nconst api = create402API({\n  apiKey: 'sk_live_abc123...',\n  endpoint: 'https://api.yourservice.com/v1/predict',\n  pricePerCall: 1000, // 1000 sats per call\n  network: 'base-mainnet',\n  timeoutSeconds: 600 // 10 minutes\n});\n```\n\n## Usage Examples\n\n### Basic POST Request\n\n```typescript\nconst api = create402API({\n  apiKey: 'your-api-key',\n  endpoint: 'https://api.example.com/analyze',\n  pricePerCall: 50\n});\n\nconst result = await api.post({\n  text: 'Analyze this content',\n  options: { detailed: true }\n});\n\nconsole.log(result.data);\n```\n\n### GET Request with Query Parameters\n\n```typescript\nconst api = create402API({\n  apiKey: 'your-api-key',\n  endpoint: 'https://api.example.com/data',\n  pricePerCall: 25\n});\n\nconst result = await api.get({\n  id: '12345',\n  format: 'json'\n});\n\nconsole.log(result.data);\n```\n\n### Custom HTTP Methods\n\n```typescript\nconst result = await api.call(\n  { data: 'update' },\n  { method: 'PUT' }\n);\n```\n\n### Access Transaction History\n\n```typescript\nconst history = await api.getTransactionHistory(50);\n\nhistory.forEach(tx => {\n  console.log(`${tx.timestamp}: ${tx.amount} sats - ${tx.txHash}`);\n});\n```\n\n## API Reference\n\n### `create402API(config: SDK402Config): API402`\n\nFactory function that creates a new API instance.\n\n**Parameters:**\n- `config`: SDK configuration object\n\n**Returns:** `API402` instance\n\n### Class: `API402`\n\n#### Methods\n\n##### `initialize(): Promise<void>`\n\nInitializes the SDK and validates the API key. This is called automatically on the first API call.\n\n```typescript\nawait api.initialize();\n```\n\n##### `call<T>(params?, options?): Promise<CallResult<T>>`\n\nMakes a request to the protected API endpoint. Automatically handles the x402 payment protocol.\n\n**Parameters:**\n- `params`: Request body/data (optional)\n- `options`: Call options including method, headers, etc. (optional)\n\n**Returns:** Promise resolving to `CallResult<T>`\n\n```typescript\nconst result = await api.call({ query: 'data' });\n```\n\n##### `get<T>(params?): Promise<CallResult<T>>`\n\nConvenience method for GET requests.\n\n```typescript\nconst result = await api.get({ id: '123' });\n```\n\n##### `post<T>(body?): Promise<CallResult<T>>`\n\nConvenience method for POST requests.\n\n```typescript\nconst result = await api.post({ data: 'value' });\n```\n\n##### `getTransactionHistory(limit?): Promise<TransactionLog[]>`\n\nFetches transaction history for the API key.\n\n**Parameters:**\n- `limit`: Maximum number of transactions to return (default: 50)\n\n```typescript\nconst history = await api.getTransactionHistory(100);\n```\n\n##### `getConfig(): Readonly<Required<SDK402Config>>`\n\nReturns the current configuration.\n\n```typescript\nconst config = api.getConfig();\nconsole.log(config.pricePerCall);\n```\n\n## Types\n\n### `CallResult<T>`\n\n```typescript\ninterface CallResult<T> {\n  data: T;                              // Response data\n  status: number;                       // HTTP status code\n  headers: Record<string, string>;      // Response headers\n  paymentReceipt?: string;              // Payment receipt (if payment was made)\n}\n```\n\n### `CallOptions`\n\n```typescript\ninterface CallOptions {\n  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n  headers?: Record<string, string>;\n  body?: unknown;\n  params?: Record<string, string | number | boolean>;\n}\n```\n\n## Error Handling\n\nThe SDK provides specific error types for different failure scenarios:\n\n```typescript\nimport {\n  PaymentRequiredError,\n  PaymentVerificationError,\n  PaymentSettlementError\n} from '@402exchange/sdk';\n\ntry {\n  const result = await api.call({ data: 'request' });\n} catch (error) {\n  if (error instanceof PaymentRequiredError) {\n    console.log('Payment required:', error.paymentRequirements);\n  } else if (error instanceof PaymentVerificationError) {\n    console.log('Payment verification failed:', error.reason);\n  } else if (error instanceof PaymentSettlementError) {\n    console.log('Payment settlement failed:', error.message);\n  } else {\n    console.log('API call failed:', error);\n  }\n}\n```\n\n## Advanced Usage\n\n### Direct x402 Protocol Handler\n\nFor advanced use cases, you can use the low-level x402 protocol handler directly:\n\n```typescript\nimport { executeX402Request } from '@402exchange/sdk';\n\nconst result = await executeX402Request(\n  'https://api.example.com/endpoint',\n  { method: 'POST', body: { data: 'value' } },\n  async (requirements) => {\n    // Custom payment handler\n    // Return a PaymentPayload\n    return myCustomPaymentLogic(requirements);\n  }\n);\n```\n\n### Custom Backend Client\n\n```typescript\nimport { createBackendClient } from '@402exchange/sdk';\n\nconst backend = createBackendClient('https://your-backend.com');\n\n// Validate API key\nconst validation = await backend.validateApiKey('your-key');\n\n// Log API call\nconst log = await backend.logApiCall('your-key', '/endpoint', 100);\n\n// Process payment\nconst payment = await backend.processPayment('your-key', {\n  amount: 100,\n  network: 'base-mainnet',\n  endpoint: '/api/data'\n});\n```\n\n## How It Works\n\nThe SDK implements the x402 protocol flow:\n\n1. **Initial Request**: SDK makes a request to your API endpoint\n2. **402 Response**: If payment required, server responds with `402 Payment Required` and payment instructions\n3. **Payment Processing**: SDK processes payment through 402exchange backend\n4. **Retry with Payment**: SDK retries the request with `X-PAYMENT` header\n5. **Access Granted**: Server verifies payment and returns requested data\n\nAll of this happens transparently - you just call `api.call()` and the SDK handles the rest!\n\n## Requirements\n\n- Node.js >= 16.0.0\n- A 402exchange API key (sign up at [402exchange.com](https://402exchange.com))\n\n## Resources\n\n- [x402 Protocol Documentation](https://x402.gitbook.io/x402)\n- [402exchange Platform](https://402exchange.com)\n- [GitHub Repository](https://github.com/yourusername/402exchange-sdk)\n- [Report Issues](https://github.com/yourusername/402exchange-sdk/issues)\n\n## License\n\nMIT\n\n## Contributing\n\nContributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.\n\n## Support\n\n- Documentation: [402exchange.com/docs](https://402exchange.com/docs)\n- Email: support@402exchange.com\n- GitHub Issues: [Report a bug](https://github.com/yourusername/402exchange-sdk/issues)\n\n---\n\nBuilt with ❤️ for the future of AI-powered commerce\n","readmeFilename":"README.md","_rev":"1-bb9b3258803a79ee0f5a578e71efb9e2"}