-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket-filtered.ts
More file actions
177 lines (153 loc) · 6.02 KB
/
websocket-filtered.ts
File metadata and controls
177 lines (153 loc) · 6.02 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
/**
* Filtered WebSocket Example - Stream Specific Transactions Only
*
* This example demonstrates how to use filters to receive only transactions
* that match specific criteria (contract addresses and/or method signatures).
*
* DEVELOPER NOTES:
* - Filters drastically reduce bandwidth and processing requirements
* - Can filter by contract addresses, method signatures, or both
* - Filters are AND operations (must match ALL criteria)
* - Filters can be updated dynamically without reconnecting
* - Method signatures are the first 4 bytes of the keccak256 hash
*
* USE CASES:
* - Monitor specific DEX routers (Uniswap, SushiSwap, etc.)
* - Track specific token contracts
* - Watch for specific function calls
* - MEV bot development
* - Protocol-specific analytics
*
* PERFORMANCE:
* - Filtering on server-side saves bandwidth
* - Only receive transactions you care about
* - Reduces client-side processing load
*
* RUN:
* $ export ETHPENDING_API_KEY=your-key
* $ npx tsx examples/websocket-filtered.ts
*/
import { WebSocketClient } from '../src';
// Configuration: API key from environment
const API_KEY = process.env.ETHPENDING_API_KEY || 'your-api-key-here';
// FILTER CONFIGURATION
// Example: Monitor Uniswap V3 Router for specific swap methods
// TIP: Find contract addresses on Etherscan
const UNISWAP_V3_ROUTER = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
// Method Signatures (first 4 bytes of function selector)
// Calculate with: web3.eth.abi.encodeFunctionSignature('functionName(type1,type2)')
// Or use: cast sig "functionName(type1,type2)" | cut -c1-10
const SWAP_EXACT_INPUT = '0xc04b8d59'; // exactInput(bytes,address,uint256,uint256)
const SWAP_EXACT_OUTPUT = '0xf28c0498'; // exactOutput(bytes,address,uint256,uint256)
async function main() {
// Initialize WebSocket client
const client = new WebSocketClient(API_KEY);
// EVENT HANDLERS
/**
* Connection established
*/
client.on('connected', () => {
console.log('✅ Connected to EthPending WebSocket');
console.log('🔍 Filtering for Uniswap V3 swaps...\n');
// DEVELOPER TIP: Filters are automatically sent after connection
});
/**
* 'subscribed' event - Confirmation that filters were applied
* This event is fired whenever setFilters() is called
* Use this to verify your filters are correctly configured
*/
client.on('subscribed', (filters) => {
console.log('✅ Subscribed with filters:');
console.log(' Addresses:', filters.addresses);
console.log(' Methods:', filters.methods);
console.log('');
// DEVELOPER TIP: Validate filters match your expectations
// if (!filters.addresses?.includes(EXPECTED_ADDRESS)) {
// console.warn('Warning: Expected address not in filter');
// }
});
/**
* Transaction event - Only receives filtered transactions
* With filters enabled, you'll ONLY receive transactions that:
* 1. Are sent to one of the filtered addresses AND
* 2. Call one of the filtered methods
*/
client.on('transaction', (tx) => {
console.log('🔄 Uniswap V3 Swap detected!');
console.log(` Hash: ${tx.txHash}`);
console.log(` From: ${tx.from}`);
console.log(` To: ${tx.to}`); // Will always be UNISWAP_V3_ROUTER
console.log(` Value: ${tx.value} wei`); // ETH sent with transaction
console.log(` Gas Price: ${tx.gasPrice} wei`);
console.log(` Success: ${tx.success}`); // Simulation result
console.log(` Events: ${tx.logs.length}`); // Event logs emitted
// DEVELOPER TIP: Parse event logs to extract swap details
// Swap events contain: token addresses, amounts, recipient, etc.
tx.logs.forEach((log, i) => {
console.log(` Event ${i + 1}:`);
console.log(` Address: ${log.address}`); // Token/pool contract
console.log(` Topics: ${log.topics.length}`); // Indexed parameters
// EXAMPLE: Detect Swap events
// const SWAP_EVENT = '0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67';
// if (log.topics[0] === SWAP_EVENT) {
// console.log(' Type: Uniswap V3 Swap');
// // Parse amounts, tokens, etc. from log.data and log.topics
// }
});
console.log('');
});
/**
* Error handler
*/
client.on('error', (error) => {
console.error('❌ Error:', error.message);
});
// ESTABLISH CONNECTION
await client.connect();
// SET FILTERS
// Filters are applied server-side for efficiency
// Multiple addresses and methods can be specified
// Empty arrays = no filter for that criteria
client.setFilters({
addresses: [UNISWAP_V3_ROUTER], // Only transactions to this router
methods: [SWAP_EXACT_INPUT, SWAP_EXACT_OUTPUT], // Only these methods
});
// FILTER EXAMPLES:
// Example 1: Monitor all methods on specific contracts
// client.setFilters({
// addresses: ['0x...', '0x...'],
// methods: [] // All methods
// });
// Example 2: Monitor specific method across all contracts
// client.setFilters({
// addresses: [], // All contracts
// methods: ['0xa9059cbb'] // transfer(address,uint256)
// });
// Example 3: Multiple contracts and methods
// client.setFilters({
// addresses: [UNISWAP_V2, UNISWAP_V3, SUSHISWAP],
// methods: [SWAP_METHOD_1, SWAP_METHOD_2]
// });
// DYNAMIC FILTER UPDATE
// Filters can be changed at runtime without reconnecting
// This is useful for:
// - Adjusting monitoring based on market conditions
// - Rotating through different contracts
// - A/B testing different filter strategies
setTimeout(() => {
console.log('\n🔄 Updating filters to monitor all methods...\n');
client.setFilters({
addresses: [UNISWAP_V3_ROUTER],
methods: [], // Empty methods array = all methods
// This will now show ALL transactions to the Uniswap V3 router
});
}, 60000);
// GRACEFUL SHUTDOWN
process.on('SIGINT', () => {
console.log('\n👋 Shutting down...');
client.disconnect();
process.exit(0);
});
}
// ENTRY POINT
main().catch(console.error);