πŸ“‘Real-time Events

Complete guide for subscribing to real-time blockchain events using WebSocket connections.

Overview

The SDK provides WebSocket utilities for real-time event streaming, allowing your agents to react instantly to blockchain events without polling.

WebSocket Client

Initialize WebSocket Client

import { SomniaAgentKit } from 'somnia-agent-kit';

const kit = new SomniaAgentKit({ /* config */ });
await kit.initialize();

// Get WebSocket client with default config
const ws = kit.getWebSocketClient();

// Or with custom config
const ws = kit.getWebSocketClient({
  wsUrl: 'wss://dream-rpc.somnia.network',
  autoReconnect: true,
  reconnectDelay: 5000,
  maxReconnectAttempts: 10
});

Option 2: Standalone

Connect to WebSocket

Disconnect

Subscribe to Events

Subscribe to New Blocks

Subscribe to Pending Transactions

Subscribe to Contract Events

Subscribe to Logs

Unsubscribe

Complete Example: Real-Time Agent Monitor

Complete Example: Trading Bot with Real-Time Prices

Event Filtering

Filter by Address

Filter by Topics

Filter by Block Range

Best Practices

1. Handle Reconnections

2. Clean Up Subscriptions

3. Handle Errors Gracefully

4. Rate Limit Event Processing

5. Use Event Batching

Comparison: WebSocket vs Polling

WebSocket (Real-Time)

Polling (Traditional)

See Also

Last updated