opacus-sdk
v1.1.1
Published
Opacus - Multi-Chain Decentralized Agent Communication Protocol with H3-DAC Agent Identity
Maintainers
Readme
Opacus SDK
Production-ready Multi-Chain Decentralized Agent Communication Protocol with H3-DAC Agent Identity
Opacus SDK enables secure, authenticated communication between decentralized agents with built-in support for 0G Chain, H3-based geospatial agent discovery, and multi-chain operations.
🚀 Features
Core Protocol
- ✅ Ed25519 + X25519 Cryptography - Signing and encryption keys
- ✅ ECDH Key Exchange - Secure shared secret derivation
- ✅ Nonce-based Anti-Replay - Protection against replay attacks
- ✅ CBOR Binary Framing - Efficient serialization
- ✅ WebSocket & WebTransport - Multiple transport options
H3-DAC Agent Identity (NEW in v1.0.3)
- ✅ H3 Geospatial Indexing - Location-based agent discovery
- ✅ On-Chain Agent Registry - Blockchain-verified identities
- ✅ DID Standard -
did:opacus:h3:<h3Index>:<address> - ✅ Challenge/Response Auth - Mutual agent authentication
- ✅ Reputation System - Trust scoring (0-100)
- ✅ Capability Discovery - Search by agent abilities
- ✅ Key Rotation - Secure key management with cooldown
Blockchain & Payments
- ✅ 0G Chain Integration - Native support for 0G network
- ✅ Multi-Chain Ready - EVM-compatible chain support
- ✅ DAC Management - Data channel creation and subscriptions
- ✅ Micropayment Escrow - Built-in payment support with stake
- ✅ x402-style Payments - USDC micropayments (10,000x cheaper than x402!)
- ✅ HTTP Payment Protocol - Pay-per-request API calls
- ✅ Gasless Transactions - Relayer-sponsored payments
📦 Installation
npm install opacus-sdk🔧 Quick Start
Initialize Client
import { OpacusClient } from '@opacus/sdk';
const config = {
network: 'testnet',
relayUrl: 'wss://relay.opacus.io',
chainRpc: 'https://evmrpc-testnet.0g.ai',
privateKey: process.env.PRIVATE_KEY
};
const client = new OpacusClient(config);
// Initialize identity
const identity = await client.init();
console.log('Agent ID:', identity.id);
console.log('Address:', identity.address);
// Connect to relay
await client.connect();Send Messages
// Listen for messages
client.onMessage('msg', (frame) => {
console.log('From:', frame.from);
console.log('Message:', frame.payload);
});
// Send message to another agent
await client.sendMessage('target-agent-id', {
type: 'greeting',
text: 'Hello from Opacus!'
});Create DAC (Data Channel)
const dacConfig = {
id: 'my-dac-001',
owner: identity.address,
metadata: {
name: 'My Data Stream',
description: 'Real-time data service',
version: '1.0.0',
tags: ['data', 'streaming']
},
permissions: [
{ role: 'owner', address: identity.address }
],
dataChannels: [
{
id: 'main-stream',
type: 'output',
schema: { type: 'object' },
pricing: {
perByte: 1n,
perMessage: 100n
}
}
],
revenueModel: {
type: 'pay-per-use',
fee: 0n,
treasury: identity.address
}
};
const txHash = await client.createDAC(dacConfig);
console.log('DAC created:', txHash);Subscribe to Data Streams
// Subscribe
await client.subscribeToChannel('main-stream');
// Listen for stream data
client.onMessage('stream', (frame) => {
const { channelId, data } = frame.payload;
console.log(`Channel ${channelId}:`, data);
});
// Send stream data
await client.sendStream('main-stream', {
timestamp: Date.now(),
value: Math.random() * 100
});Register On-Chain
// Initialize contracts
await client.initContracts({
dacRegistry: '0x...',
agentRegistry: '0x...',
dataStream: '0x...',
escrow: '0x...'
});
// Register agent on-chain
const txHash = await client.registerOnChain({
name: 'MyAgent',
version: '1.0.0',
capabilities: ['chat', 'data-stream']
});
console.log('Registered:', txHash);🔐 Security Model
Triple-Layer Authentication
- Ed25519 Signatures - Message signing and verification
- HMAC-SHA256 - Message authentication codes
- Nonce Validation - 60-second window, single-use
Key Exchange
// ECDH shared secret
const shared = security.deriveSharedSecret(myPrivateKey, peerPublicKey);
// Session key derivation
const sessionKey = security.deriveSessionKey(shared);
// HMAC generation
const hmac = security.generateHMAC(sessionKey, messageData);🌐 Multi-Chain Support
import { MultiChainManager, EVMChainAdapter } from '@opacus/sdk';
const manager = new MultiChainManager();
// Add Ethereum
const ethAdapter = new EVMChainAdapter(1, 'Ethereum Mainnet');
await ethAdapter.connect('https://eth-rpc.gateway.pokt.network', privateKey);
manager.registerAdapter(ethAdapter);
// Add Polygon
const polyAdapter = new EVMChainAdapter(137, 'Polygon Mainnet');
await polyAdapter.connect('https://polygon-rpc.com', privateKey);
manager.registerAdapter(polyAdapter);
// Register agent on all chains
const results = await manager.registerAgentAllChains(identity, metadata);📡 Transport Options
WebSocket (Recommended)
import { WebSocketTransport } from '@opacus/sdk';
const transport = new WebSocketTransport('wss://relay.opacus.io');
await transport.connect();WebTransport (HTTP/3)
import { WebTransportTransport } from '@opacus/sdk';
const transport = new WebTransportTransport('https://relay.opacus.io');
await transport.connect();🔌 API Reference
OpacusClient
init(existingIdentity?: string): Promise<AgentIdentity>
Initialize with new or existing identity
connect(): Promise<void>
Connect to relay server
sendMessage(to: string, payload: any): Promise<void>
Send message to specific agent
sendStream(channelId: string, data: any): Promise<void>
Send data to stream channel
createDAC(config: DACConfig): Promise<string>
Create new DAC with channels
registerOnChain(metadata: object): Promise<string>
Register agent on blockchain
getBalance(): Promise<bigint>
Get account balance
disconnect(): Promise<void>
Disconnect from relay
KeyManager
generateFullIdentity(chainId?: number): Promise<AgentIdentity>
Generate new identity with Ed25519 and X25519 keys
exportIdentity(identity: AgentIdentity): string
Export identity to JSON string
importIdentity(json: string): AgentIdentity
Import identity from JSON
SecurityManager
generateNonce(): string
Generate anti-replay nonce
createAuthFrame(...): Promise<OpacusFrame>
Create authenticated frame with signature + HMAC + nonce
verifyAuthFrame(...): Promise<{valid: boolean, reason?: string}>
Verify frame authentication
💳 x402-style Micropayments (USDC)
Opacus provides an x402-style payment protocol using USDC, enabling 10,000x smaller minimum payments than x402!
Why Opacus Payments > x402?
| Feature | x402 (Base) | Opacus (USDC) | |---------|------------|---------------| | Minimum Payment | 0.01 USDC (1 cent) | 0.00001 USDC ($0.00001) | | Token | USDC (stable) | USDC (stable) | | Blockchain | Base L2 (Coinbase) | 0G Chain | | Gas Cost | ~$0.00001 (Base L2) | ~$0.00002 (0G) | | Privacy | Public | Encrypted |
Basic Usage
// Initialize client with payments
const client = new OpacusClient({
network: 'testnet',
relayUrl: 'wss://relay-testnet.opacus.network',
chainRpc: 'https://evmrpc-testnet.0g.ai',
privateKey: process.env.PRIVATE_KEY
});
await client.init();
// Initialize USDC payments (testnet USDC address)
await client.initPayments('0x...USDC_ADDRESS');
// Make paid HTTP request
const result = await client.paidRequest('https://api.example.com/ai/chat', {
method: 'POST',
body: {
prompt: 'Hello, AI!',
model: 'gpt-4'
},
payment: {
to: '0x...SERVICE_PROVIDER',
amount: '0.002' // $0.002 in USDC
}
});
console.log('Response:', await result.response.json());
console.log('Payment TX:', result.receipt.txHash);
console.log('Total cost:', result.cost, 'USDC');Server-side: Accept Payments
import express from 'express';
import { X402PaymentManager } from '@opacus/sdk';
const app = express();
const paymentManager = new X402PaymentManager(chainClient, security);
await paymentManager.init('0x...USDC_ADDRESS');
// Add payment middleware
app.use('/api', paymentManager.createMiddleware());
app.post('/api/ai/chat', async (req, res) => {
// Payment already verified by middleware
const receipt = req.paymentReceipt;
// Process request
const result = await processAIRequest(req.body);
res.json({
result,
paymentReceipt: receipt.txHash
});
});Use Cases
AI API Calls ($0.001 - $0.01)
await client.paidRequest('https://ai-api.com/generate', {
payment: { to: aiProvider, amount: '0.002' }
});IoT Sensor Data ($0.000001 per reading)
await client.paidRequest('https://iot.com/sensor/123', {
payment: { to: iotProvider, amount: '0.000001' }
});Content Micropayments ($0.00001 - $0.05)
await client.paidRequest('https://news.com/article/456', {
payment: { to: publisher, amount: '0.01' }
});Advanced: Custom Payment Logic
const paymentManager = client.getPaymentManager();
// Create payment request
const paymentReq = paymentManager.createPaymentRequest(
myAddress,
serviceProvider,
'0.001', // 0.001 USDC
'API call payment',
60000 // 1 minute expiry
);
// Pay
const receipt = await paymentManager.payForRequest(paymentReq);
// Verify (server-side)
const valid = await paymentManager.verifyPayment(receipt);🧪 Examples
See the /examples directory for complete examples:
client-example.ts- Basic client usagerelay-example.ts- Running a relay serverbrowser-example.html- Browser integrationdac-example.ts- Creating and managing DACsmultichain-example.ts- Multi-chain deploymentpayment-example.ts- x402-style USDC micropayments
📝 Smart Contracts
Solidity contracts are available in /contracts:
DACRegistry.sol- DAC registration and managementAgentRegistry.sol- Agent registration and key rotationDataStream.sol- Data channel subscriptions and paymentsEscrow.sol- Micropayment escrow system
🔗 Network Information
0G Mainnet
- Chain ID: 16661
- RPC: https://evmrpc.0g.ai
- Explorer: https://chainscan.0g.ai
0G Testnet (Galileo)
- Chain ID: 16602
- RPC: https://evmrpc-testnet.0g.ai
- Explorer: https://chainscan-galileo.0g.ai
🤝 Contributing
Contributions are welcome! Please read CONTRIBUTING.md for details.
📄 License
MIT License - see LICENSE for details.
Links
- Website: https://opacus.xyz
- Documentation: https://opacus.xyz/docs
- GitHub: https://github.com/Opacus-xyz/Opacus
Built with ❤️ for the decentralized future
