Opacus - Multi-Chain Decentralized Agent Communication Protocol with H3-DAC Agent Identity
npm install opacus-sdkProduction-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.
did:opacus:h3:: ``bash`
npm install opacus-sdk
`typescript
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();
`
`typescript
// 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!'
});
`
`typescript
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);
`
`typescript
// 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
});
`
`typescript
// 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);
`
1. Ed25519 Signatures - Message signing and verification
2. HMAC-SHA256 - Message authentication codes
3. Nonce Validation - 60-second window, single-use
`typescript
// 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);
`
`typescript
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);
`
`typescript
import { WebSocketTransport } from '@opacus/sdk';
const transport = new WebSocketTransport('wss://relay.opacus.io');
await transport.connect();
`
`typescript
import { WebTransportTransport } from '@opacus/sdk';
const transport = new WebTransportTransport('https://relay.opacus.io');
await transport.connect();
`
#### init(existingIdentity?: string): Promise
Initialize with new or existing identity
#### connect(): Promise
Connect to relay server
#### sendMessage(to: string, payload: any): Promise
Send message to specific agent
#### sendStream(channelId: string, data: any): Promise
Send data to stream channel
#### createDAC(config: DACConfig): Promise
Create new DAC with channels
#### registerOnChain(metadata: object): Promise
Register agent on blockchain
#### getBalance(): Promise
Get account balance
#### disconnect(): Promise
Disconnect from relay
#### generateFullIdentity(chainId?: number): Promise
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
#### generateNonce(): string
Generate anti-replay nonce
#### createAuthFrame(...): Promise
Create authenticated frame with signature + HMAC + nonce
#### verifyAuthFrame(...): Promise<{valid: boolean, reason?: string}>
Verify frame authentication
Opacus provides a robust micropayment protocol using USDC for agent-to-agent transactions.
| Feature | OpacusPay |
|---------|-----------|
| Minimum Payment | 0.00001 USDC |
| Token | USDC (stable) |
| Blockchain | 0G Chain |
| Privacy | Encrypted |
| Escrow | Built-in |
| Verification | ZK-proofs |
`typescript
// 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');
`
`typescript
import express from 'express';
import { OpacusPaymentManager } from '@opacus/sdk';
const app = express();
const paymentManager = new OpacusPaymentManager(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
});
});
`
AI API Calls ($0.001 - $0.01)
`typescript`
await client.paidRequest('https://ai-api.com/generate', {
payment: { to: aiProvider, amount: '0.002' }
});
IoT Sensor Data ($0.000001 per reading)
`typescript`
await client.paidRequest('https://iot.com/sensor/123', {
payment: { to: iotProvider, amount: '0.000001' }
});
Content Micropayments ($0.00001 - $0.05)
`typescript`
await client.paidRequest('https://news.com/article/456', {
payment: { to: publisher, amount: '0.01' }
});
`typescript
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);
`
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
- - OpacusPay USDC micropayments
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
-
Contributions are welcome! Please read CONTRIBUTING.md for details.
MIT License - see LICENSE for details.
- Website: https://opacus.xyz
- Documentation: https://opacus.xyz/docs
- GitHub: https://github.com/Opacus-xyz/Opacus
---
Built with โค๏ธ for the decentralized future