UNPKG

opacus-sdk

Version:

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

199 lines (167 loc) • 5.91 kB
/** * Example: Express.js API with OpacusPay Payment Middleware * Automatically verify and process payments for API endpoints */ import express from 'express'; import { ethers } from 'ethers'; import { AutoPaymentClient, PaymentMiddleware } from '../src/payment/auto-payment-client'; const app = express(); app.use(express.json()); // Configuration const ESCROW_ADDRESS = "0x19F39f1e4C800DDC1725D906D910a9c78902Ff15"; const USDC_ADDRESS = "0x96f7c32232E60C89F1aef5bF1fC0a1695F67c483"; const OG_RPC = "https://evmrpc-testnet.0g.ai"; // Setup payment client const provider = new ethers.JsonRpcProvider(OG_RPC); const privateKey = process.env.PRIVATE_KEY || ""; const signer = new ethers.Wallet(privateKey, provider); const paymentClient = new AutoPaymentClient({ provider, signer, escrowAddress: ESCROW_ADDRESS, usdcAddress: USDC_ADDRESS }); const paymentMiddleware = new PaymentMiddleware(paymentClient); // Free endpoints (no payment required) app.get('/api/v1/health', (req, res) => { res.json({ status: 'healthy', timestamp: Date.now() }); }); app.get('/api/v1/pricing', (req, res) => { res.json({ services: [ { endpoint: '/api/v1/chat', cost: '0.002 USDC', description: 'AI Chat API' }, { endpoint: '/api/v1/image', cost: '0.05 USDC', description: 'Image Generation' }, { endpoint: '/api/v1/data', cost: '0.001 USDC', description: 'Real-time Data Stream' }, { endpoint: '/api/v1/iot', cost: '0.000001 USDC', description: 'IoT Sensor Reading' } ] }); }); // Paid endpoints (payment required) app.post('/api/v1/chat', paymentMiddleware.verify(), async (req, res) => { const { messages } = req.body; // Simulate AI processing const response = { id: `chat-${Date.now()}`, model: 'gpt-4', choices: [{ message: { role: 'assistant', content: 'This is a simulated AI response. Payment verified!' } }], usage: { prompt_tokens: 10, completion_tokens: 15, total_tokens: 25 }, payment: { escrowId: req.payment?.escrowId, amount: '0.002 USDC', status: 'locked' } }; res.json(response); }); app.post('/api/v1/image', paymentMiddleware.verify(), async (req, res) => { const { prompt } = req.body; // Simulate image generation await new Promise(resolve => setTimeout(resolve, 1000)); res.json({ id: `img-${Date.now()}`, prompt: prompt, url: 'https://example.com/generated-image.png', payment: { escrowId: req.payment?.escrowId, amount: '0.05 USDC', status: 'locked' } }); }); app.get('/api/v1/data', paymentMiddleware.verify(), async (req, res) => { // Real-time market data const data = { timestamp: Date.now(), markets: [ { symbol: 'BTC/USD', price: 65000, change24h: 2.5 }, { symbol: 'ETH/USD', price: 3200, change24h: 1.8 }, { symbol: 'A0GI/USD', price: 0.15, change24h: 5.2 } ], payment: { escrowId: req.payment?.escrowId, amount: '0.001 USDC' } }; res.json(data); }); app.get('/api/v1/iot', paymentMiddleware.verify(), async (req, res) => { // IoT sensor reading (impossible with x402 - payment too small!) const reading = { sensor_id: 'temp-001', timestamp: Date.now(), temperature: 23.5, humidity: 65, unit: 'celsius', payment: { escrowId: req.payment?.escrowId, amount: '0.000001 USDC', note: 'This payment is 10,000x smaller than x402 minimum!' } }; res.json(reading); }); // Agent-to-agent communication endpoint app.post('/api/v1/agent/message', paymentMiddleware.verify(), async (req, res) => { const { from, to, message, serviceType } = req.body; console.log(`šŸ¤– Agent Message: ${from} → ${to}`); console.log(` Service: ${serviceType}`); console.log(` Payment: ${req.payment?.escrowId}`); // Process agent message const response = { message_id: `msg-${Date.now()}`, from: to, to: from, reply: `Message received and processed. Payment verified.`, payment: { escrowId: req.payment?.escrowId, status: 'completed' } }; res.json(response); }); // Error handler for payment failures app.use((err: any, req: any, res: any, next: any) => { if (err.code === 'PAYMENT_REQUIRED') { return res.status(402).json({ error: 'Payment Required', message: 'This endpoint requires OpacusPay payment', pricing: '/api/v1/pricing' }); } res.status(500).json({ error: err.message }); }); // Start server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(` ╔════════════════════════════════════════════════════════════════╗ ā•‘ OpacusPay API Server ā•‘ ā•‘ Automatic payment verification for all endpoints ā•‘ ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• šŸš€ Server running on http://localhost:${PORT} šŸ“‹ Available Endpoints: GET /api/v1/health - Health check (free) GET /api/v1/pricing - Pricing info (free) POST /api/v1/chat - AI Chat ($0.002) šŸ’³ POST /api/v1/image - Image Gen ($0.05) šŸ’³ GET /api/v1/data - Market Data ($0.001) šŸ’³ GET /api/v1/iot - IoT Sensor ($0.000001) šŸ’³ POST /api/v1/agent/message - Agent Message (variable) šŸ’³ šŸ’” How to use: 1. Include X-Payment header with payment details 2. Include X-Payment-EscrowId header with escrow ID 3. Payment is auto-verified and released after response šŸ”— Contract: ${ESCROW_ADDRESS} šŸŖ™ USDC: ${USDC_ADDRESS} `); }); export default app;