-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket-basic.ts
More file actions
177 lines (158 loc) · 6.54 KB
/
Copy pathwebsocket-basic.ts
File metadata and controls
177 lines (158 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
* Basic WebSocket Example - Stream Pending Transactions in Real-Time
*
* This example demonstrates the fundamental usage of the WebSocket client
* to stream all pending Ethereum transactions with minimal configuration.
*
* DEVELOPER NOTES:
* - WebSocket provides sub-second latency for real-time monitoring
* - Auto-reconnection is enabled by default
* - No filters applied = receives all pending transactions
* - Event-driven architecture for handling incoming transactions
*
* USE CASES:
* - General blockchain monitoring
* - Real-time transaction analytics
* - Network activity dashboard
* - Transaction volume tracking
*
* REQUIREMENTS:
* - API key from ethpending.com
* - Node.js 16+ or modern browser
*
* RUN:
* $ export ETHPENDING_API_KEY=your-key
* $ npx tsx examples/websocket-basic.ts
*/
import { WebSocketClient } from '../src';
// Configuration: API key from environment variable (recommended) or hardcoded
const API_KEY = process.env.ETHPENDING_API_KEY || 'your-api-key-here';
async function main() {
// Initialize WebSocket client with default configuration
// Default config includes:
// - autoReconnect: true (automatic reconnection on disconnect)
// - maxReconnectAttempts: Infinity
// - reconnectDelay: 1000ms (exponential backoff)
// - heartbeatInterval: 30000ms (keep-alive ping)
const client = new WebSocketClient(API_KEY);
// EVENT LISTENERS
// The client uses a type-safe event emitter pattern
// All events are strongly typed for TypeScript users
/**
* 'connected' event - Fired when WebSocket connection is established
* Use this to initialize any state or notify users
*/
client.on('connected', () => {
console.log('✅ Connected to EthPending WebSocket');
// TIP: Good place to set up filters or start other processes
});
/**
* 'disconnected' event - Fired when connection closes
* Provides close code and reason for debugging
* Common codes: 1000 (normal), 1001 (going away), 1006 (abnormal)
*/
client.on('disconnected', (data) => {
console.log(`❌ Disconnected: ${data.code} - ${data.reason}`);
// TIP: Log to monitoring service for production debugging
});
/**
* 'reconnecting' event - Fired during automatic reconnection attempts
* Provides attempt number for tracking reconnection progress
* Uses exponential backoff: 1s, 2s, 4s, 8s, etc.
*/
client.on('reconnecting', (attempt) => {
console.log(`🔄 Reconnecting... (attempt ${attempt})`);
// TIP: Alert ops team if attempts exceed threshold
});
/**
* 'transaction' event - The main event for processing pending transactions
* Fired for each pending transaction received from the mempool
*
* Transaction Object Properties:
* - txHash: Transaction hash (unique identifier)
* - success: Boolean indicating if tx will succeed (simulation result)
* - network: Network name (e.g., "mainnet", "sepolia")
* - timestamp: ISO 8601 timestamp when tx entered mempool
* - logs: Array of event logs emitted by the transaction
* - from: Sender address
* - to: Recipient address (contract or EOA)
* - value: ETH value in wei (string to handle large numbers)
* - gasPrice: Gas price in wei
* - input: Transaction calldata (function call + parameters)
* - error: Error message if success is false
*/
client.on('transaction', (tx) => {
console.log('\n📦 New pending transaction:');
console.log(` Hash: ${tx.txHash}`);
console.log(` Success: ${tx.success}`); // false = will revert
console.log(` Network: ${tx.network}`);
console.log(` Timestamp: ${tx.timestamp}`);
console.log(` Logs: ${tx.logs.length} events`); // Smart contract events
// DEVELOPER TIP: Access additional fields for detailed analysis
// console.log(` From: ${tx.from}`);
// console.log(` To: ${tx.to}`);
// console.log(` Value: ${tx.value} wei`);
// console.log(` Gas Price: ${tx.gasPrice} wei`);
if (tx.error) {
console.log(` Error: ${tx.error}`); // Revert reason from simulation
}
// EXAMPLE: Process transaction based on criteria
// if (tx.logs.length > 0) {
// // Transaction emitted events - likely a contract interaction
// processContractInteraction(tx);
// }
});
/**
* 'error' event - Fired when errors occur
* Types of errors:
* - ConnectionError: Network/connection issues
* - ParseError: Invalid message format
* - ApiError: Server-side errors
*
* IMPORTANT: This does NOT include transaction errors (use tx.error instead)
*/
client.on('error', (error) => {
console.error('❌ Error:', error.message);
// TIP: Send to error tracking service (Sentry, Datadog, etc.)
// Example: Sentry.captureException(error);
});
// ESTABLISH CONNECTION
// connect() returns a Promise that resolves when connection is established
// Throws ConnectionError if connection fails (e.g., invalid API key, network issues)
try {
await client.connect();
// Connection successful - 'connected' event will fire
} catch (error) {
console.error('Failed to connect:', error);
// TIP: Check API key and network connectivity
process.exit(1);
}
// METRICS MONITORING
// Built-in metrics for monitoring connection health and performance
// Useful for dashboards, alerting, and debugging
setInterval(() => {
const metrics = client.getMetrics();
console.log('\n📊 Metrics:');
console.log(` Messages received: ${metrics.messagesReceived}`); // Total transactions received
console.log(` Connection state: ${metrics.connectionState}`); // connected/disconnected/reconnecting
console.log(` Uptime: ${Math.floor(metrics.uptime / 1000)}s`); // Connection uptime in seconds
console.log(` Reconnect attempts: ${metrics.reconnectAttempts}`); // Number of reconnections
console.log(` Errors: ${metrics.errors}`); // Total error count
// DEVELOPER TIP: Export metrics to monitoring systems
// Example with Prometheus:
// prometheusMetrics.set('ethpending_messages', metrics.messagesReceived);
// prometheusMetrics.set('ethpending_uptime', metrics.uptime);
}, 30000);
// GRACEFUL SHUTDOWN
// Always disconnect cleanly to avoid ghost connections
// Important for production deployments and Docker containers
process.on('SIGINT', () => {
console.log('\n👋 Shutting down...');
client.disconnect(); // Closes WebSocket connection gracefully
// TIP: Add cleanup for databases, file handles, etc.
process.exit(0);
});
}
// ENTRY POINT
// main() is async so we handle errors at the top level
main().catch(console.error);