{"_id":"@bober3r/solana-payment-channels-client","name":"@bober3r/solana-payment-channels-client","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@bober3r/solana-payment-channels-client","version":"0.1.0","description":"Client SDK for automatic payment channel management with x402 protocol on Solana","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":"vitest run","test:watch":"vitest","lint":"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix","typecheck":"tsc --noEmit","clean":"rm -rf dist"},"keywords":["solana","x402","payment-channels","client","sdk","micropayments","blockchain","web3"],"author":{"name":"BOBER3r"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/BOBER3r/solana-payment-channel-kit.git","directory":"packages/client"},"bugs":{"url":"https://github.com/BOBER3r/solana-payment-channel-kit/issues"},"homepage":"https://github.com/BOBER3r/solana-payment-channel-kit#readme","dependencies":{"@bober3r/solana-payment-channels-core":"workspace:*","@x402-solana/client":"latest","@solana/web3.js":"^1.95.8","@solana/spl-token":"^0.4.11","@noble/ed25519":"^2.1.0"},"devDependencies":{"@types/node":"^20.19.24","eslint":"^9.17.0","tsup":"^8.3.5","typescript":"^5.9.3","vitest":"^2.1.8"},"engines":{"node":">=18.0.0"},"_id":"@bober3r/solana-payment-channels-client@0.1.0","gitHead":"46bab13f27fd923d3ff1ca80c1d24dbd000ce11d","_nodeVersion":"22.14.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-GamXyshMLtQWyz5lO5ZqwSKqit3fyyPMMMbisSHAzu1b6YRc3PofUx0fkK6LV5qLyYZtSExXZpQg2dD/yAP++w==","shasum":"df838e14b2d2c6a3ed6f8f85805885320bbe71d4","tarball":"https://registry.npmjs.org/@bober3r/solana-payment-channels-client/-/solana-payment-channels-client-0.1.0.tgz","fileCount":8,"unpackedSize":2406392,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIDageVDRgLw9So7bW4UBrCNTqQFUvdm9foSs0UGAdRXLAiACNvMgXJ95fbv+QpvV86nCvei7nuRIxBlPEobYiYTCIw=="}]},"_npmUser":{"name":"bober3r","email":"BOBER3r@proton.me"},"directories":{},"maintainers":[{"name":"bober3r","email":"BOBER3r@proton.me"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/solana-payment-channels-client_0.1.0_1762457219400_0.4600527389824598"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-06T19:26:59.211Z","0.1.0":"2025-11-06T19:26:59.606Z","modified":"2025-11-06T19:27:00.016Z"},"maintainers":[{"name":"bober3r","email":"BOBER3r@proton.me"}],"description":"Client SDK for automatic payment channel management with x402 protocol on Solana","homepage":"https://github.com/BOBER3r/solana-payment-channel-kit#readme","keywords":["solana","x402","payment-channels","client","sdk","micropayments","blockchain","web3"],"repository":{"type":"git","url":"git+https://github.com/BOBER3r/solana-payment-channel-kit.git","directory":"packages/client"},"author":{"name":"BOBER3r"},"bugs":{"url":"https://github.com/BOBER3r/solana-payment-channel-kit/issues"},"license":"MIT","readme":"# @bober3r/solana-payment-channels-client\n\n[![npm version](https://badge.fury.io/js/%40bober3r%2Fsolana-payment-channels-client.svg)](https://www.npmjs.com/package/@bober3r/solana-payment-channels-client)\n[![npm downloads](https://img.shields.io/npm/dm/%40bober3r%2Fsolana-payment-channels-client.svg)](https://www.npmjs.com/package/@bober3r/solana-payment-channels-client)\n[![GitHub issues](https://img.shields.io/github/issues/BOBER3r/solana-payment-channel-kit)](https://github.com/BOBER3r/solana-payment-channel-kit/issues)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org/)\n\n> Drop-in replacement for `fetch()` with automatic payment channel management\n\nA production-ready client SDK that seamlessly handles payment channels and falls back to x402 protocol. Get started in 5 minutes with zero configuration - the client automatically optimizes between instant, free channel payments and on-chain x402 payments based on usage patterns.\n\n## Features\n\n- **🔄 Drop-in Replacement**: Works exactly like `fetch()` but handles payments automatically\n- **🧠 Intelligent Routing**: Automatically chooses between channel and x402 based on usage patterns\n- **⚡️ Zero Configuration**: Works out-of-the-box with sensible defaults\n- **🎛️ Full Control**: Advanced users can manage channels manually\n- **📊 Event System**: Monitor payments, channel lifecycle, and errors\n- **🔒 Type Safety**: Full TypeScript support with comprehensive types\n- **🚨 Error Handling**: Graceful fallbacks and clear error messages\n- **⚡️ High Performance**: Request caching, capability caching, efficient payment routing\n- **🌐 Universal**: Works in Node.js and browsers (with wallet adapter)\n\n## Installation\n\n```bash\nnpm install @bober3r/solana-payment-channels-client @bober3r/solana-payment-channels-core @solana/web3.js\n# or\nyarn add @bober3r/solana-payment-channels-client @bober3r/solana-payment-channels-core @solana/web3.js\n# or\npnpm add @bober3r/solana-payment-channels-client @bober3r/solana-payment-channels-core @solana/web3.js\n```\n\n## Quick Start (5 Minutes)\n\n### 1. Initialize the Client\n\n```typescript\nimport { createClient } from '@bober3r/solana-payment-channels-client';\nimport { Keypair } from '@solana/web3.js';\n\n// Load your wallet (from env, file, or generate)\nconst wallet = Keypair.fromSecretKey(\n  new Uint8Array(JSON.parse(process.env.WALLET_SECRET_KEY))\n);\n\n// Create client with minimal configuration\nconst client = createClient({\n  wallet,\n  rpcUrl: 'https://api.devnet.solana.com',\n  network: 'devnet',\n});\n```\n\n### 2. Use Like Regular `fetch()`\n\n```typescript\n// That's it! Use client.fetch() instead of fetch()\nconst response = await client.fetch('https://api.example.com/premium');\nconst data = await response.json();\n\n// The client automatically:\n// 1. Detects 402 response\n// 2. Checks if server supports channels\n// 3. Opens channel if beneficial (high-frequency use)\n// 4. Uses channel payment (instant, free)\n// 5. Falls back to x402 for single payments\n// 6. Retries request with payment\n```\n\n### 3. That's It!\n\nYour application now supports automatic payment channels with zero additional code. The client tracks usage patterns and optimizes payment routing for you.\n\n## Basic Usage Examples\n\n### Simple API Calls\n\n```typescript\nimport { createClient } from '@bober3r/solana-payment-channels-client';\n\nconst client = createClient({ wallet, rpcUrl, network: 'devnet' });\n\n// Single request\nconst data = await client.fetch('https://api.example.com/data').then(r => r.json());\n\n// Multiple requests (client automatically optimizes)\nfor (let i = 0; i < 100; i++) {\n  const result = await client.fetch('https://api.example.com/query');\n  console.log(await result.json());\n}\n```\n\n### POST Requests with Body\n\n```typescript\nconst response = await client.fetch('https://api.example.com/search', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({ query: 'solana', limit: 10 }),\n});\n\nconst results = await response.json();\n```\n\n### Error Handling\n\n```typescript\ntry {\n  const response = await client.fetch('https://api.example.com/data');\n\n  if (!response.ok) {\n    console.error(`HTTP error: ${response.status}`);\n    return;\n  }\n\n  const data = await response.json();\n  console.log(data);\n} catch (error) {\n  console.error('Request failed:', error);\n}\n```\n\n## Configuration Options\n\n### Basic Configuration\n\n```typescript\nimport { createClient } from '@bober3r/solana-payment-channels-client';\n\nconst client = createClient({\n  // Required\n  wallet: myKeypair,              // Your Solana keypair\n  rpcUrl: 'https://api.devnet.solana.com',\n  network: 'devnet',              // 'devnet' | 'mainnet-beta'\n\n  // Optional - Channel Management\n  channelThreshold: 10,           // Open channel after N req/hour (default: 10)\n  defaultChannelDeposit: BigInt(10_000_000), // 10 USDC (default)\n  autoRefillThreshold: BigInt(1_000_000),    // Refill at 1 USDC (default)\n  autoRefillAmount: BigInt(10_000_000),      // Refill with 10 USDC (default)\n  channelExpiry: 7 * 24 * 60 * 60,          // 7 days (default)\n\n  // Optional - Behavior\n  autoManageChannels: true,       // Enable auto-management (default: true)\n  trackRequests: true,            // Track for optimization (default: true)\n  debug: false,                   // Enable debug logging (default: false)\n\n  // Optional - Performance\n  capabilitiesCacheTTL: 300000,   // Cache TTL 5 min (default)\n  requestTimeout: 30000,          // Request timeout 30s (default)\n});\n```\n\n### Advanced Configuration\n\n```typescript\nimport { createClient } from '@bober3r/solana-payment-channels-client';\nimport { PublicKey } from '@solana/web3.js';\n\nconst client = createClient({\n  wallet: myKeypair,\n  rpcUrl: 'https://api.mainnet-beta.solana.com',\n  network: 'mainnet-beta',\n\n  // Custom program ID (if not using default)\n  programId: new PublicKey('YourProgramId...'),\n\n  // Custom USDC mint (if needed)\n  usdcMint: new PublicKey('CustomUSDCMint...'),\n\n  // Aggressive channel opening (lower threshold)\n  channelThreshold: 5,\n\n  // Larger deposits for high-volume usage\n  defaultChannelDeposit: BigInt(100_000_000), // 100 USDC\n\n  // More aggressive refilling\n  autoRefillThreshold: BigInt(10_000_000),    // 10 USDC\n  autoRefillAmount: BigInt(50_000_000),        // 50 USDC\n\n  // Longer channel lifetime\n  channelExpiry: 30 * 24 * 60 * 60, // 30 days\n\n  // Enable debug mode\n  debug: true,\n});\n```\n\n## Manual Channel Management\n\nFor advanced use cases, you can manage channels manually:\n\n### Opening Channels\n\n```typescript\n// Open a channel for a specific server\nconst channelId = await client.openChannel(\n  'https://api.example.com',\n  BigInt(10_000_000), // 10 USDC deposit\n);\n\nconsole.log(`Channel opened: ${channelId}`);\n\n// Now all requests to this server use the channel\nconst response = await client.fetch('https://api.example.com/data');\n```\n\n### Checking Channel Balance\n\n```typescript\nconst balance = await client.getChannelBalance(channelId);\nconsole.log(`Remaining balance: ${balance}`);\n\nif (balance < BigInt(1_000_000)) {\n  console.log('Balance is low!');\n}\n```\n\n### Refilling Channels\n\n```typescript\n// Manual refill\nawait client.autoRefillChannel(channelId);\nconsole.log('Channel refilled');\n\n// Refill with custom amount\nawait client.autoRefillChannel(channelId, BigInt(20_000_000)); // 20 USDC\n```\n\n### Closing Channels\n\n```typescript\n// Close channel and get refund\nawait client.closeChannel(channelId);\nconsole.log('Channel closed, remaining balance refunded');\n```\n\n### Getting Channel Information\n\n```typescript\nconst info = client.getChannelInfo(channelId);\n\nconsole.log(`Server: ${info.serverUrl}`);\nconsole.log(`Balance: ${info.currentBalance}`);\nconsole.log(`Payments made: ${info.paymentCount}`);\nconsole.log(`Expires: ${info.expiry}`);\n```\n\n### Listing All Channels\n\n```typescript\nconst channels = client.getAllChannels();\n\nconsole.log(`Active channels: ${channels.length}`);\n\nfor (const channel of channels) {\n  console.log(`${channel.serverUrl}: ${channel.currentBalance} remaining`);\n}\n```\n\n## Event Monitoring\n\nMonitor payments, channels, and errors in real-time:\n\n### Channel Lifecycle Events\n\n```typescript\n// Channel opened\nclient.on('channel_opened', ({ channelId, serverUrl, deposit, expiry }) => {\n  console.log(`✅ Opened channel ${channelId}`);\n  console.log(`   Server: ${serverUrl}`);\n  console.log(`   Deposit: ${deposit}`);\n  console.log(`   Expires: ${expiry}`);\n});\n\n// Channel closed\nclient.on('channel_closed', ({ channelId, serverUrl, refundedAmount }) => {\n  console.log(`🔒 Closed channel ${channelId}`);\n  console.log(`   Refunded: ${refundedAmount}`);\n});\n\n// Channel refilled\nclient.on('channel_refilled', ({ channelId, addedAmount, newBalance }) => {\n  console.log(`💰 Refilled channel ${channelId}`);\n  console.log(`   Added: ${addedAmount}`);\n  console.log(`   New balance: ${newBalance}`);\n});\n\n// Channel depleted (low balance)\nclient.on('channel_depleted', ({ channelId, remainingBalance, threshold }) => {\n  console.log(`⚠️  Channel ${channelId} low on funds`);\n  console.log(`   Remaining: ${remainingBalance}`);\n  console.log(`   Threshold: ${threshold}`);\n});\n```\n\n### Payment Events\n\n```typescript\n// Payment required (402 detected)\nclient.on('payment_required', ({ serverUrl, amount, requirement }) => {\n  console.log(`💳 Payment required for ${serverUrl}`);\n  console.log(`   Amount: ${amount} ${requirement.currency}`);\n});\n\n// Payment made\nclient.on('payment_made', ({ method, amount, serverUrl, signature }) => {\n  console.log(`✅ Paid ${amount} to ${serverUrl}`);\n  console.log(`   Method: ${method}`);\n  console.log(`   Signature: ${signature}`);\n});\n\n// Payment failed\nclient.on('payment_failed', ({ method, serverUrl, error, amount }) => {\n  console.error(`❌ Payment failed to ${serverUrl}`);\n  console.error(`   Method: ${method}`);\n  console.error(`   Error: ${error}`);\n});\n```\n\n### Capability Detection Events\n\n```typescript\n// Server capabilities detected\nclient.on('capabilities_detected', ({ serverUrl, capabilities }) => {\n  console.log(`🔍 Detected capabilities for ${serverUrl}`);\n  console.log(`   Supports channels: ${capabilities.supportsChannels}`);\n  console.log(`   Supports x402: ${capabilities.supportsX402}`);\n\n  if (capabilities.supportsChannels) {\n    console.log(`   Min deposit: ${capabilities.minChannelAmount}`);\n  }\n});\n```\n\n### Complete Event Monitoring Example\n\n```typescript\nimport { createClient } from '@bober3r/solana-payment-channels-client';\n\nconst client = createClient({ wallet, rpcUrl, network: 'devnet' });\n\n// Set up all event listeners\nclient.on('channel_opened', (data) => {\n  console.log('Channel opened:', data);\n});\n\nclient.on('payment_made', (data) => {\n  console.log('Payment made:', data);\n});\n\nclient.on('channel_depleted', async (data) => {\n  console.warn('Channel low on funds:', data);\n  // Auto-refill\n  await client.autoRefillChannel(data.channelId);\n});\n\nclient.on('payment_failed', (data) => {\n  console.error('Payment failed:', data);\n  // Handle failure (e.g., retry, notify user)\n});\n\n// Now make requests with full observability\nawait client.fetch('https://api.example.com/data');\n```\n\n## Analytics & Monitoring\n\nTrack usage patterns and costs:\n\n### Basic Analytics\n\n```typescript\nconst analytics = client.getAnalytics();\n\nconsole.log('=== Usage Statistics ===');\nconsole.log(`Total requests: ${analytics.totalRequests}`);\nconsole.log(`Total payments: ${analytics.totalPayments}`);\nconsole.log(`Total spent: ${analytics.totalSpent} lamports`);\nconsole.log(`Active channels: ${analytics.activeChannels}`);\nconsole.log(`Success rate: ${(analytics.successRate * 100).toFixed(2)}%`);\n\nconsole.log('\\n=== Payment Methods ===');\nconsole.log(`Channel payments: ${analytics.channelPayments}`);\nconsole.log(`x402 payments: ${analytics.x402Payments}`);\nconsole.log(`Total savings: ${analytics.totalSavings} lamports`);\n```\n\n### Per-Domain Statistics\n\n```typescript\nconst analytics = client.getAnalytics();\n\nconsole.log('\\n=== Per-Domain Statistics ===');\nfor (const [domain, stats] of analytics.domainStats) {\n  console.log(`\\n${domain}:`);\n  console.log(`  Total requests: ${stats.totalRequests}`);\n  console.log(`  Paid requests: ${stats.paidRequests}`);\n  console.log(`  Total paid: ${stats.totalPaid}`);\n  console.log(`  Requests/hour: ${stats.requestsPerHour.toFixed(2)}`);\n  console.log(`  Has channel: ${stats.hasActiveChannel}`);\n\n  if (stats.channelId) {\n    const channel = client.getChannelInfo(stats.channelId);\n    console.log(`  Channel balance: ${channel?.currentBalance}`);\n  }\n}\n```\n\n### Cost Analysis\n\n```typescript\nimport { AutoPaymentManager } from '@bober3r/solana-payment-channels-client';\n\n// Get the auto-payment manager for advanced analytics\nconst manager = new AutoPaymentManager();\n\n// Track some requests...\nmanager.trackRequest('https://api.example.com/data', {\n  paymentRequired: true,\n  amount: BigInt(100_000),\n  method: 'x402',\n  statusCode: 200,\n  responseTime: 150,\n});\n\n// Analyze costs\nconst analysis = manager.analyzeCosts('https://api.example.com');\n\nconsole.log('=== Cost Analysis ===');\nconsole.log(`Total requests: ${analysis.totalRequests}`);\nconsole.log(`Channel setup cost: ${analysis.channelSetupCost} lamports`);\nconsole.log(`x402 per-payment cost: ${analysis.x402PaymentCost} lamports`);\nconsole.log(`Total x402 cost: ${analysis.totalX402Cost} lamports`);\nconsole.log(`Total channel cost: ${analysis.totalChannelCost} lamports`);\nconsole.log(`Estimated savings: ${analysis.estimatedSavings} lamports`);\nconsole.log(`Break-even at: ${analysis.breakEvenRequests} requests`);\nconsole.log(`Recommendation: ${analysis.recommendation}`);\n```\n\n## Payment Flow Diagrams\n\n### Automatic Payment Flow\n\n```\n1. Request is made\n   ↓\n2. Is 402 response?\n   ↓ Yes\n3. Check server capabilities\n   ↓\n4. Supports channels?\n   ├─ Yes → Check request frequency\n   │         ↓\n   │         High frequency (>10 req/hr)?\n   │         ├─ Yes → Open channel → Use channel payment (free, instant)\n   │         └─ No  → Use x402 (on-chain payment)\n   │\n   └─ No  → Use x402 (on-chain payment)\n   ↓\n5. Retry request with payment\n   ↓\n6. Return successful response\n```\n\n### Channel Payment Flow\n\n```\n1. Create payment authorization\n   ↓\n2. Sign with client wallet (off-chain)\n   ↓\n3. Attach authorization to request headers\n   ↓\n4. Server verifies signature (instant)\n   ↓\n5. Server serves request (no blockchain interaction)\n   ↓\n6. Server claims payment later (batched on-chain)\n```\n\n### x402 Payment Flow\n\n```\n1. Parse payment requirement from 402 response\n   ↓\n2. Create Solana transaction\n   ↓\n3. Sign and send transaction\n   ↓\n4. Wait for confirmation\n   ↓\n5. Attach transaction signature to request\n   ↓\n6. Server verifies on-chain\n   ↓\n7. Server serves request\n```\n\n## Best Practices\n\n### 1. Use Auto-Management for Most Cases\n\n```typescript\n// ✅ Good: Let the client manage everything\nconst client = createClient({\n  wallet,\n  rpcUrl,\n  network: 'devnet',\n  autoManageChannels: true, // Default\n});\n\nawait client.fetch(url); // Automatic optimization\n```\n\n### 2. Pre-Open Channels for Known High-Frequency APIs\n\n```typescript\n// ✅ Good: Open channel upfront for known usage\nconst client = createClient({ wallet, rpcUrl, network: 'devnet' });\n\n// If you know you'll make many requests\nconst channelId = await client.openChannel(\n  'https://api.example.com',\n  BigInt(50_000_000) // 50 USDC for high volume\n);\n\n// Now make requests (all use channel)\nfor (let i = 0; i < 10000; i++) {\n  await client.fetch('https://api.example.com/data');\n}\n```\n\n### 3. Monitor Low Balances\n\n```typescript\n// ✅ Good: Monitor and handle low balances\nclient.on('channel_depleted', async ({ channelId, remainingBalance }) => {\n  console.warn(`Channel ${channelId} low: ${remainingBalance}`);\n\n  // Automatic refill\n  await client.autoRefillChannel(channelId);\n\n  // Or close and open new one\n  // await client.closeChannel(channelId);\n  // await client.openChannel(serverUrl, BigInt(20_000_000));\n});\n```\n\n### 4. Handle Errors Gracefully\n\n```typescript\n// ✅ Good: Comprehensive error handling\ntry {\n  const response = await client.fetch(url);\n\n  if (response.status === 402) {\n    // Payment required but failed\n    console.error('Payment failed or insufficient funds');\n    return;\n  }\n\n  if (!response.ok) {\n    console.error(`HTTP error: ${response.status}`);\n    return;\n  }\n\n  const data = await response.json();\n  return data;\n} catch (error) {\n  if (error.name === 'AbortError') {\n    console.error('Request timed out');\n  } else if (error instanceof TypeError) {\n    console.error('Network error');\n  } else {\n    console.error('Request failed:', error);\n  }\n}\n```\n\n### 5. Clean Up Channels When Done\n\n```typescript\n// ✅ Good: Close channels to recover funds\nconst channels = client.getAllChannels();\n\nfor (const channel of channels) {\n  // Close expired or unused channels\n  if (channel.expiry < new Date() || channel.paymentCount === 0) {\n    await client.closeChannel(channel.channelId);\n    console.log(`Closed channel ${channel.channelId}, refunded ${channel.currentBalance}`);\n  }\n}\n```\n\n### 6. Use Debug Mode During Development\n\n```typescript\n// ✅ Good: Enable debug logging during development\nconst client = createClient({\n  wallet,\n  rpcUrl,\n  network: 'devnet',\n  debug: true, // Shows detailed logs\n});\n\n// Debug logs will show:\n// - Server capability detection\n// - Payment decisions\n// - Channel operations\n// - Request tracking\n```\n\n### 7. Configure Based on Usage Patterns\n\n```typescript\n// ✅ Good: Tune configuration to your use case\n\n// High-frequency API calls (>50 req/hr)\nconst highFrequencyClient = createClient({\n  wallet, rpcUrl, network: 'devnet',\n  channelThreshold: 5,              // Lower threshold\n  defaultChannelDeposit: BigInt(100_000_000), // 100 USDC\n  autoRefillThreshold: BigInt(20_000_000),    // 20 USDC\n  channelExpiry: 30 * 24 * 60 * 60,           // 30 days\n});\n\n// Occasional API calls (<5 req/hr)\nconst lowFrequencyClient = createClient({\n  wallet, rpcUrl, network: 'devnet',\n  channelThreshold: 20,             // Higher threshold\n  defaultChannelDeposit: BigInt(5_000_000),   // 5 USDC\n  autoManageChannels: false,        // Manual management\n});\n```\n\n## Troubleshooting\n\n### Payment Required (402) Not Being Handled\n\n**Problem**: Requests return 402 but payment isn't automatic.\n\n**Solution**:\n```typescript\n// Check if skipAutoPayment is set\nconst response = await client.fetch(url, {\n  skipAutoPayment: false, // Ensure auto-payment is enabled\n});\n\n// Check server capabilities\nconst capabilities = await fetchServerCapabilities(url);\nconsole.log('Supports channels:', capabilities.supportsChannels);\nconsole.log('Supports x402:', capabilities.supportsX402);\n```\n\n### Channel Not Being Opened\n\n**Problem**: High-frequency requests still using x402.\n\n**Solution**:\n```typescript\n// Check request frequency\nconst stats = client.getAnalytics();\nfor (const [domain, domainStats] of stats.domainStats) {\n  console.log(`${domain}: ${domainStats.requestsPerHour} req/hr`);\n}\n\n// Lower threshold if needed\nconst client = createClient({\n  wallet, rpcUrl, network: 'devnet',\n  channelThreshold: 5, // Lower from default 10\n});\n\n// Or open manually\nawait client.openChannel(url, BigInt(10_000_000));\n```\n\n### Insufficient Channel Balance\n\n**Problem**: Channel payments failing due to low balance.\n\n**Solution**:\n```typescript\n// Enable auto-refill\nconst client = createClient({\n  wallet, rpcUrl, network: 'devnet',\n  autoManageChannels: true,\n  autoRefillThreshold: BigInt(2_000_000),  // Refill at 2 USDC\n  autoRefillAmount: BigInt(10_000_000),    // Refill with 10 USDC\n});\n\n// Or monitor and refill manually\nclient.on('channel_depleted', async ({ channelId }) => {\n  await client.autoRefillChannel(channelId);\n});\n```\n\n### Server Doesn't Support Channels\n\n**Problem**: Server returns 402 but doesn't support channels.\n\n**Solution**:\n```typescript\n// Client will automatically fall back to x402\n// Verify by checking capabilities\nconst capabilities = await fetchServerCapabilities(url);\n\nif (!capabilities.supportsChannels) {\n  console.log('Server only supports x402 - will use on-chain payments');\n}\n\n// Ensure x402 client is properly configured\n// (Integration with @x402-solana/client should be set up)\n```\n\n### Request Timeouts\n\n**Problem**: Requests timing out during payment.\n\n**Solution**:\n```typescript\n// Increase timeout\nconst client = createClient({\n  wallet, rpcUrl, network: 'devnet',\n  requestTimeout: 60000, // 60 seconds\n});\n\n// Or use custom timeout per request\nconst response = await client.fetch(url, {\n  signal: AbortSignal.timeout(90000), // 90 seconds\n});\n```\n\n## API Reference\n\nSee [TypeScript definitions](./src/types/index.ts) for complete API documentation.\n\n### Main Classes\n\n- `PaymentChannelClient` - Main client for automatic payment handling\n- `AutoPaymentManager` - Intelligent payment routing and cost analysis\n\n### Key Methods\n\n- `createClient(config)` - Create a new client instance\n- `client.fetch(url, options)` - Drop-in fetch replacement\n- `client.openChannel(serverUrl, deposit)` - Open a payment channel\n- `client.closeChannel(channelId)` - Close a channel\n- `client.getChannelBalance(channelId)` - Check channel balance\n- `client.autoRefillChannel(channelId)` - Refill a channel\n- `client.getAnalytics()` - Get usage analytics\n\n### Utility Functions\n\n- `fetchServerCapabilities(url)` - Fetch server capabilities\n- `parsePaymentRequirements(response)` - Parse 402 response\n- `createChannelPaymentHeaders(...)` - Create channel payment headers\n- `createX402PaymentHeaders(...)` - Create x402 payment headers\n\n## Contributing\n\nContributions are welcome! Please see [CONTRIBUTING.md](../../CONTRIBUTING.md) for details.\n\n## License\n\nMIT License - see [LICENSE](../../LICENSE) for details.\n\n## Support\n\n- 📚 Documentation: [https://docs.x402.dev](https://docs.x402.dev)\n- 💬 Discord: [https://discord.gg/x402](https://discord.gg/x402)\n- 🐛 Issues: [GitHub Issues](https://github.com/x402/solana-x402/issues)\n- 📧 Email: support@x402.dev\n\n## Related Packages\n\n- [@bober3r/solana-payment-channels-core](../core) - Core payment channel management\n- [@bober3r/solana-payment-channels-server](../server) - Server SDK for accepting payments\n- [@x402-solana/client](https://github.com/x402/solana-x402) - x402 protocol client\n\n---\n\nBuilt with ❤️ by the x402 team\n","readmeFilename":"README.md","_rev":"1-d2928bf68aaf2fcf095055943a8b6a9d"}