TypeScript SDK

Complete documentation for the Opacus TypeScript SDK with WebSocket and WebTransport support for modern web applications.

Installation

npm install @opacus/sdk
# or
yarn add @opacus/sdk
# or
pnpm add @opacus/sdk

Basic Usage

Initialize Client

Create a new Opacus client instance with your configuration:

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

const client = new OpacusClient({
  rpcUrl: 'https://evmrpc-testnet.0g.ai',
  contractAddress: '0x5FbDB2315678afecb367f032d93F642f64180aa3',
  privateKey: process.env.PRIVATE_KEY,
  transport: 'websocket' // or 'webtransport'
});

// Connect to the network
await client.connect();

Configuration Options

Available configuration options for the client:

interface OpacusClientConfig {
  rpcUrl: string;              // 0G Chain RPC endpoint
  contractAddress: string;     // OpacusCore contract address
  privateKey: string;          // Wallet private key
  transport?: 'websocket' | 'webtransport';
  timeout?: number;            // Request timeout in ms
  retryAttempts?: number;      // Number of retry attempts
}

Agent Management

Register an Agent

Register a new AI agent on the Opacus protocol:

const agentId = await client.registerAgent({
  metadata: {
    name: 'MyAIAgent',
    version: '1.0.0',
    capabilities: ['text-generation', 'reasoning', 'analysis'],
    description: 'AI agent for text processing'
  }
});

console.log('Agent ID:', agentId);

Get Agent Information

Retrieve information about a registered agent:

const agent = await client.getAgent(agentId);

console.log('Agent:', {
  id: agent.id,
  name: agent.metadata.name,
  owner: agent.owner,
  registeredAt: agent.timestamp,
  capabilities: agent.metadata.capabilities
});

Update Agent Metadata

Update an existing agent's metadata:

await client.updateAgent(agentId, {
  metadata: {
    name: 'MyAIAgent',
    version: '2.0.0',
    capabilities: ['text-generation', 'reasoning', 'analysis', 'translation']
  }
});

Attestations

Create Attestation

Create a cryptographic attestation to prove agent capabilities:

const attestation = await client.createAttestation({
  agentId: agentId,
  capability: 'text-generation',
  proof: {
    algorithm: 'ed25519',
    signature: signatureData,
    publicKey: publicKeyData
  },
  metadata: {
    model: 'gpt-4',
    accuracy: 0.95
  }
});

console.log('Attestation ID:', attestation.id);

Verify Attestation

Verify the validity of an attestation:

const isValid = await client.verifyAttestation(attestationId);

if (isValid) {
  console.log('Attestation is valid');
} else {
  console.log('Attestation verification failed');
}

Get Attestations for Agent

Retrieve all attestations associated with an agent:

const attestations = await client.getAgentAttestations(agentId);

attestations.forEach(att => {
  console.log(`Capability: ${att.capability}, Valid: ${att.isValid}`);
});

Event Listening

Listen to Events

Subscribe to real-time events from the Opacus protocol:

// Agent registration events
client.on('agentRegistered', (event) => {
  console.log('New agent registered:', {
    agentId: event.agentId,
    owner: event.owner,
    timestamp: event.timestamp
  });
});

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

// Agent update events
client.on('agentUpdated', (event) => {
  console.log('Agent updated:', event.agentId);
});

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

client.on('disconnected', () => {
  console.log('Disconnected from network');
});

Remove Event Listeners

// Remove specific listener
client.off('agentRegistered', listenerFunction);

// Remove all listeners for an event
client.removeAllListeners('agentRegistered');

Data Streams

Create Data Stream

Establish a real-time data stream for agent communication:

const stream = await client.createDataStream({
  agentId: agentId,
  streamType: 'bidirectional',
  encryption: true
});

// Send data through stream
await stream.send({
  type: 'message',
  content: 'Hello from agent'
});

// Receive data from stream
stream.on('data', (data) => {
  console.log('Received:', data);
});

// Close stream
await stream.close();

Error Handling

Handle Errors Gracefully

try {
  await client.registerAgent({
    metadata: { name: 'Agent' }
  });
} catch (error) {
  if (error.code === 'INSUFFICIENT_FUNDS') {
    console.error('Not enough gas for transaction');
  } else if (error.code === 'AGENT_ALREADY_EXISTS') {
    console.error('Agent already registered');
  } else {
    console.error('Unexpected error:', error.message);
  }
}

Error Types

Common error codes you might encounter:

Advanced Features

Batch Operations

Execute multiple operations in a single transaction:

const batch = client.batch();

batch.registerAgent({ metadata: { name: 'Agent1' } });
batch.registerAgent({ metadata: { name: 'Agent2' } });
batch.createAttestation({ agentId: 'id1', capability: 'cap1' });

const results = await batch.execute();
console.log('Batch results:', results);

Custom Gas Settings

Configure gas settings for transactions:

await client.registerAgent(
  { metadata: { name: 'Agent' } },
  {
    gasLimit: 500000,
    gasPrice: '20000000000', // 20 gwei
    maxPriorityFeePerGas: '2000000000' // 2 gwei
  }
);

Transaction Monitoring

Monitor transaction status in real-time:

const tx = await client.registerAgent({
  metadata: { name: 'Agent' }
});

console.log('Transaction hash:', tx.hash);

// Wait for confirmation
const receipt = await tx.wait();
console.log('Confirmed in block:', receipt.blockNumber);

💡 Best Practices

Always implement proper error handling, use environment variables for sensitive data, and test thoroughly on testnet before deploying to mainnet.

API Reference

OpacusClient Class

Methods

Events

Examples

For more examples and integration patterns, check out: