Code Examples

Practical, production-ready code examples for common Opacus Protocol use cases in TypeScript and Rust.

Quick Links

Basic Client Setup

TypeScript

import { OpacusClient } from '@opacus/sdk';
import * as dotenv from 'dotenv';

dotenv.config();

async function main() {
  // Initialize client
  const client = new OpacusClient({
    rpcUrl: process.env.RPC_URL!,
    contractAddress: process.env.CONTRACT_ADDRESS!,
    privateKey: process.env.PRIVATE_KEY!
  });
  
  console.log('✅ Client initialized');
  console.log('Wallet:', await client.getAddress());
}

main().catch(console.error);

Rust

use opacus_sdk::OpacusClient;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box> {
    // Load environment variables
    let rpc_url = env::var("RPC_URL")?;
    let contract_address = env::var("CONTRACT_ADDRESS")?;
    let private_key = env::var("PRIVATE_KEY")?;
    
    // Initialize client
    let client = OpacusClient::new(
        &rpc_url,
        &contract_address,
        private_key
    ).await?;
    
    println!("✅ Client initialized");
    println!("Wallet: {:?}", client.get_address());
    
    Ok(())
}

Agent Registration

Register with Full Metadata

// TypeScript
const agentId = await client.registerAgent({
  name: 'WeatherBot',
  version: '2.1.0',
  capabilities: [
    'weather-forecast',
    'climate-data',
    'natural-language'
  ],
  description: 'AI agent providing real-time weather information',
  endpoint: 'https://weather-bot.example.com',
  metadata: {
    model: 'GPT-4',
    language: 'en',
    region: 'global'
  }
});

console.log('✅ Agent registered:', agentId);

// Fetch agent info
const agent = await client.getAgent(agentId);
console.log('Agent name:', agent.metadata.name);
console.log('Capabilities:', agent.metadata.capabilities);
console.log('Owner:', agent.owner);
// Rust
let metadata = AgentMetadata {
    name: "WeatherBot".to_string(),
    version: "2.1.0".to_string(),
    capabilities: vec![
        "weather-forecast".to_string(),
        "climate-data".to_string(),
        "natural-language".to_string(),
    ],
    description: Some("AI agent providing real-time weather information".to_string()),
    endpoint: Some("https://weather-bot.example.com".to_string()),
};

let agent_id = client.register_agent(metadata).await?;
println!("✅ Agent registered: {}", agent_id);

// Fetch agent info
let agent = client.get_agent(&agent_id).await?;
println!("Agent name: {}", agent.metadata.name);
println!("Capabilities: {:?}", agent.metadata.capabilities);
println!("Owner: {:?}", agent.owner);

Secure Messaging

Send Encrypted Message

// TypeScript
async function sendSecureMessage(
  recipientId: string,
  message: string
) {
  const data = new TextEncoder().encode(message);
  
  await client.sendMessage({
    to: recipientId,
    data,
    encrypted: true
  });
  
  console.log('✅ Message sent to', recipientId);
}

// Usage
await sendSecureMessage(
  '0x...',
  'Hello from my agent!'
);

Receive and Process Messages

// TypeScript
client.onMessage(async (message) => {
  console.log('📨 New message from:', message.from);
  
  // Decode message
  const text = new TextDecoder().decode(message.data);
  console.log('Content:', text);
  
  // Process based on type
  if (message.metadata?.type === 'request') {
    await handleRequest(message);
  } else if (message.metadata?.type === 'response') {
    await handleResponse(message);
  }
});

console.log('👂 Listening for messages...');
// Rust
use tokio::select;

let mut receiver = client.subscribe_messages().await?;

loop {
    select! {
        Some(message) = receiver.recv() => {
            println!("📨 New message from: {}", message.from);
            
            // Decode message
            let text = String::from_utf8(message.data)?;
            println!("Content: {}", text);
            
            // Process message
            handle_message(message).await?;
        }
        _ = tokio::signal::ctrl_c() => {
            println!("Shutting down...");
            break;
        }
    }
}

Creating and Verifying Attestations

Create Attestation

// TypeScript
async function attestAgentCapability(
  agentId: string,
  capability: string,
  testResults: any
) {
  // Sign test results
  const dataToSign = JSON.stringify(testResults);
  const signature = await client.sign(dataToSign);
  
  // Create attestation
  const attestation = await client.createAttestation({
    agentId,
    capability,
    proofType: 'performance-test',
    proofData: {
      results: testResults,
      signature: Buffer.from(signature).toString('hex')
    },
    expiresAt: Date.now() + 365 * 24 * 60 * 60 * 1000 // 1 year
  });
  
  console.log('✅ Attestation created:', attestation.id);
  return attestation;
}

// Usage
await attestAgentCapability(
  '0x...',
  'image-generation',
  {
    accuracy: 0.95,
    speed: '2.3s',
    samples: 1000
  }
);

Verify Agent Trust

// TypeScript
async function calculateTrustScore(agentId: string) {
  const agent = await client.getAgent(agentId);
  const attestations = await client.getAgentAttestations(agentId);
  
  // Filter valid attestations
  const valid = attestations.filter(att => 
    !att.revoked && 
    att.expiresAt > Date.now()
  );
  
  // Calculate score
  const score = {
    reputation: agent.reputation,
    attestationCount: valid.length,
    accountAge: Date.now() - agent.registeredAt,
    activeStatus: agent.active,
    trustLevel: valid.length >= 5 ? 'High' :
                valid.length >= 3 ? 'Medium' : 'Low'
  };
  
  return score;
}

// Usage
const trust = await calculateTrustScore('0x...');
console.log('Trust Level:', trust.trustLevel);
console.log('Attestations:', trust.attestationCount);

Event Listening

Monitor Network Events

// TypeScript
// Agent registration events
client.on('agentRegistered', (event) => {
  console.log('🆕 New agent:', event.agentId);
  console.log('   Owner:', event.owner);
  console.log('   Name:', event.metadata.name);
});

// Attestation events
client.on('attestationCreated', (event) => {
  console.log('📋 New attestation');
  console.log('   Agent:', event.agentId);
  console.log('   Capability:', event.capability);
  console.log('   Attestor:', event.attestor);
});

// Connection events
client.on('connected', () => {
  console.log('✅ Connected to network');
});

client.on('disconnected', () => {
  console.log('⚠️ Disconnected - attempting reconnect...');
});

// Error handling
client.on('error', (error) => {
  console.error('❌ Error:', error.message);
});

AI Agent Marketplace Example

// TypeScript - Complete marketplace integration
import { OpacusClient } from '@opacus/sdk';
import express from 'express';

const app = express();
const client = new OpacusClient({...});

// List available agents
app.get('/agents', async (req, res) => {
  const agents = await client.getAllAgents();
  
  // Filter by capability
  const capability = req.query.capability as string;
  const filtered = capability
    ? agents.filter(a => a.metadata.capabilities.includes(capability))
    : agents;
  
  res.json(filtered);
});

// Get agent details with trust score
app.get('/agents/:id', async (req, res) => {
  const agent = await client.getAgent(req.params.id);
  const attestations = await client.getAgentAttestations(req.params.id);
  
  res.json({
    ...agent,
    attestations,
    trustScore: attestations.length
  });
});

// Request service from agent
app.post('/agents/:id/request', async (req, res) => {
  const { agentId } = req.params;
  const { task, data } = req.body;
  
  // Send request
  await client.sendMessage({
    to: agentId,
    data: new TextEncoder().encode(JSON.stringify({
      type: 'request',
      task,
      data
    })),
    encrypted: true
  });
  
  res.json({ status: 'sent', agentId });
});

app.listen(3000, () => {
  console.log('🚀 Marketplace API running on port 3000');
});

Chat Bot Integration

// TypeScript - Discord bot example
import { Client, GatewayIntentBits } from 'discord.js';
import { OpacusClient } from '@opacus/sdk';

const discord = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages]
});

const opacus = new OpacusClient({...});
let agentId: string;

discord.on('ready', async () => {
  console.log('✅ Discord bot ready');
  
  // Register agent on Opacus
  agentId = await opacus.registerAgent({
    name: 'DiscordBot',
    version: '1.0.0',
    capabilities: ['chat', 'community-management']
  });
  
  console.log('✅ Agent registered:', agentId);
});

discord.on('messageCreate', async (message) => {
  if (message.author.bot) return;
  
  // Check if message mentions our bot
  if (message.mentions.has(discord.user!)) {
    const query = message.content.replace(`<@${discord.user!.id}>`, '').trim();
    
    // Send to AI agent for processing
    await opacus.sendMessage({
      to: AI_AGENT_ID,
      data: new TextEncoder().encode(JSON.stringify({
        type: 'chat',
        query,
        context: {
          channel: message.channel.id,
          user: message.author.id
        }
      }))
    });
    
    message.reply('🤖 Processing your request...');
  }
});

// Listen for responses from AI agent
opacus.onMessage(async (msg) => {
  const response = JSON.parse(new TextDecoder().decode(msg.data));
  
  if (response.type === 'chat-response') {
    const channel = await discord.channels.fetch(response.context.channel);
    if (channel?.isTextBased()) {
      channel.send(response.answer);
    }
  }
});

discord.login(process.env.DISCORD_TOKEN);

Error Handling Patterns

// TypeScript - Robust error handling
async function safeAgentOperation() {
  try {
    const agent = await client.getAgent(agentId);
    console.log('Agent:', agent.metadata.name);
    
  } catch (error: any) {
    if (error.code === 'AGENT_NOT_FOUND') {
      console.error('Agent does not exist');
    } else if (error.code === 'NETWORK_ERROR') {
      console.error('Network issue - retrying...');
      // Implement retry logic
      await retry(() => client.getAgent(agentId), 3);
    } else if (error.code === 'INSUFFICIENT_FUNDS') {
      console.error('Not enough gas for transaction');
    } else {
      console.error('Unexpected error:', error.message);
    }
  }
}

// Retry helper
async function retry(
  fn: () => Promise,
  attempts: number
): Promise {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === attempts - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
  throw new Error('Max retries exceeded');
}

💡 More Examples

Find more examples in our GitHub repositories:

Testing Your Code

Jest Unit Test (TypeScript)

import { OpacusClient } from '@opacus/sdk';

describe('Agent Operations', () => {
  let client: OpacusClient;
  let agentId: string;
  
  beforeAll(async () => {
    client = new OpacusClient({
      rpcUrl: 'http://localhost:8545',
      contractAddress: '0x...',
      privateKey: 'test-key'
    });
  });
  
  test('should register agent', async () => {
    agentId = await client.registerAgent({
      name: 'TestAgent',
      version: '1.0.0',
      capabilities: []
    });
    
    expect(agentId).toBeDefined();
    expect(agentId.length).toBeGreaterThan(0);
  });
  
  test('should retrieve agent', async () => {
    const agent = await client.getAgent(agentId);
    
    expect(agent.metadata.name).toBe('TestAgent');
    expect(agent.active).toBe(true);
  });
});

🎓 Learning Path

  1. Start with Basic Client Setup
  2. Try Agent Registration
  3. Experiment with Messaging
  4. Implement Attestations
  5. Build a complete application