UNPKG

@brienteth/opacus-sdk

Version:

Opacus - Multi-Chain Decentralized Agent Communication Protocol with H3-DAC Agent Identity

288 lines (231 loc) โ€ข 7.43 kB
# OpacusPay Auto-Payment System Seamless micropayments for API calls and agent-to-agent communication. Built on H3-DAC V2 protocol. ## ๐ŸŒŸ Features - **Automatic API Payments**: Pay-per-call with transparent pricing - **Agent-to-Agent Payments**: Direct micropayments between AI agents - **Streaming Metered Payments**: Pay-per-byte for real-time data - **Ultra-low Minimums**: $0.000001 payments (10,000x smaller than x402) - **Gas Savings**: 99.5% reduction with batch settlement - **Privacy**: E2E encryption + 0G Data Availability ## ๐Ÿš€ Quick Start ### 1. Browser Usage (Client-Side) ```html <!-- Include Ethers.js --> <script src="https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js"></script> <script> // Connect wallet const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); // Create auto-payment client const client = new AutoPaymentClient({ provider, signer, escrowAddress: "0x19F39f1e4C800DDC1725D906D910a9c78902Ff15", usdcAddress: "0x96f7c32232E60C89F1aef5bF1fC0a1695F67c483", autoApprove: true, maxAutoPayment: "10.0" // Pre-approve 10 USDC }); // Register service await client.registerService({ endpoint: "https://api.example.com/v1/chat", costPerCall: "0.002", payee: "0xServiceProvider" }); // Make API call with automatic payment const response = await client.callAPI( "https://api.example.com/v1/chat", { method: "POST", body: JSON.stringify({ message: "Hello!" }) } ); const data = await response.json(); console.log("AI Response:", data); // Payment automatically locked, verified, and released! </script> ``` ### 2. Node.js/TypeScript Usage ```typescript import { ethers } from 'ethers'; import { AutoPaymentClient } from '@opacus/sdk'; // Setup const provider = new ethers.JsonRpcProvider(OG_RPC); const signer = new ethers.Wallet(PRIVATE_KEY, provider); const client = new AutoPaymentClient({ provider, signer, escrowAddress: "0x19F39f1e4C800DDC1725D906D910a9c78902Ff15", usdcAddress: "0x96f7c32232E60C89F1aef5bF1fC0a1695F67c483", autoApprove: true }); // Register services await client.registerService({ endpoint: "https://api.openai.com/v1/chat/completions", costPerCall: "0.002", payee: "0xAIProvider" }); // Make API call const response = await client.callAPI( "https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: "gpt-4", messages: [{ role: "user", content: "Hello!" }] }) } ); ``` ### 3. Agent-to-Agent Payment ```typescript // Agent A pays Agent B for service const escrowId = await client.payAgent({ fromAgent: "0xAgentA", toAgent: "0xAgentB", serviceType: "data-processing", amount: "0.001", metadata: { task: "analyze-dataset", priority: "high" } }); console.log(`Payment locked: ${escrowId}`); // Agent B completes task and releases payment await client.releasePayment(escrowId, bytesDelivered); ``` ### 4. Express.js API Server ```typescript import express from 'express'; import { AutoPaymentClient, PaymentMiddleware } from '@opacus/sdk'; const app = express(); const paymentMiddleware = new PaymentMiddleware(client); // Free endpoint app.get('/api/health', (req, res) => { res.json({ status: 'healthy' }); }); // Paid endpoint with auto-verification app.post('/api/chat', paymentMiddleware.verify(), (req, res) => { // Payment automatically verified before this handler runs const payment = req.payment; // Payment details attached res.json({ response: "Hello! Your payment was verified.", payment: { escrowId: payment.escrowId, amount: "0.002 USDC" } }); // Payment auto-released after response sent }); app.listen(3000); ``` ## ๐Ÿ“Š Use Cases ### 1. AI API Services ($0.002 per call) ```typescript // ChatGPT-style API await client.registerService({ endpoint: "https://api.example.com/v1/chat", costPerCall: "0.002", payee: "0xAIProvider" }); const response = await client.callAPI(endpoint, { method: "POST", body: JSON.stringify({ prompt: "Explain quantum computing" }) }); ``` ### 2. IoT Sensor Networks ($0.000001 per reading) ```typescript // Impossible with x402 (min $0.01)! await client.registerService({ endpoint: "https://iot.example.com/sensor/temp", costPerCall: "0.000001", // 10,000x smaller! payee: "0xIoTProvider" }); const reading = await client.callAPI(endpoint); console.log("Temperature:", reading.value); ``` ### 3. Real-time Data Streams ($0.0001/second) ```typescript // Start streaming session const sessionId = await client.startStreamingSession( "wss://stream.example.com/market-data", 300 // 5 minutes ); // Add data as it streams for (const chunk of dataStream) { await client.addToStream(sessionId, chunk); } // Close with batch settlement (99.5% gas savings) await client.closeStream(sessionId, true); ``` ### 4. Multi-Agent Systems ```typescript // Agent marketplace const escrowId = await client.payAgent({ fromAgent: "0xDataBuyer", toAgent: "0xDataSeller", serviceType: "dataset-purchase", amount: "5.0", metadata: { dataset: "weather-2025", format: "parquet" } }); ``` ## ๐Ÿ”ง Configuration ```typescript interface PaymentConfig { provider: ethers.Provider; signer: ethers.Signer; escrowAddress: string; // H3DACEscrowV2 contract usdcAddress: string; // USDC token contract autoApprove?: boolean; // Auto-approve USDC (default: false) maxAutoPayment?: string; // Max auto-approval amount } interface ServicePricing { endpoint: string; // API endpoint URL costPerCall?: string; // Fixed cost per request costPerByte?: string; // Variable cost for streaming costPerSecond?: string; // Time-based pricing payee: string; // Service provider address } ``` ## ๐Ÿ“‹ Contract Addresses (0G Newton Testnet) ``` H3DACEscrowV2: 0x19F39f1e4C800DDC1725D906D910a9c78902Ff15 Mock USDC: 0x96f7c32232E60C89F1aef5bF1fC0a1695F67c483 Chain ID: 16602 RPC: https://evmrpc-testnet.0g.ai Explorer: https://chainscan-newton.0g.ai ``` ## ๐ŸŽฏ Key Advantages | Feature | x402 | **OpacusPay** | |---------|------|--------------| | Min Payment | $0.01 | **$0.000001** (10,000x smaller) | | Granularity | Per-request | **Per-datagram** | | Gas Cost | $0.00001 | **$0.00002** (batch: $0.00000002) | | Batch Savings | โŒ | **โœ… 99.5%** | | Reputation | โŒ | **โœ… 20% discount** | | Privacy | TLS only | **โœ… E2E + 0G DA** | ## ๐Ÿงช Live Demos 1. **Auto-Payment Demo**: http://localhost:8000/auto-payment-demo.html 2. **OpacusPay Demo**: http://localhost:8000/opacuspay-demo.html ## ๐Ÿ“š Examples See `/examples` directory: - `auto-payment-example.ts` - Full client usage - `express-payment-middleware.ts` - API server with payment verification - `agent-communication.ts` - Agent-to-agent payments ## ๐Ÿ” Security - โœ… Payment locked before API call - โœ… Escrow ensures atomicity - โœ… Nonce protection against replay attacks - โœ… Byte metering for accurate billing - โœ… ZK proofs for privacy (optional) ## ๐Ÿ“– Documentation Full documentation: https://docs.opacus.xyz/auto-payment ## ๐Ÿค Support - Discord: https://discord.gg/opacus - Twitter: @OpacusProtocol - GitHub: https://github.com/Opacus-xyz/Opacus ## ๐Ÿ“„ License MIT License - see LICENSE file for details