-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlatency-probe.ts
More file actions
157 lines (128 loc) Β· 4.54 KB
/
latency-probe.ts
File metadata and controls
157 lines (128 loc) Β· 4.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
/**
* Phase 4: RPC Latency Probe Script
* Measures RPC latency and ranks them for optimal ordering
*/
import 'dotenv/config'
import { createPublicClient, http, webSocket } from 'viem'
import { beraChain } from '../src/config.js'
interface RpcLatency {
url: string
type: 'HTTP' | 'WS'
blockNumberLatency: number
callLatency: number
avgLatency: number
success: boolean
error?: string
}
async function probeRpcLatency(url: string, type: 'HTTP' | 'WS'): Promise<RpcLatency> {
const transport = type === 'WS'
? webSocket(url)
: http(url, { timeout: 10000 })
const client = createPublicClient({
chain: beraChain,
transport,
})
const result: RpcLatency = {
url,
type,
blockNumberLatency: 0,
callLatency: 0,
avgLatency: 0,
success: false,
}
try {
// Test 1: eth_blockNumber
const blockStart = Date.now()
await client.getBlockNumber()
result.blockNumberLatency = Date.now() - blockStart
// Test 2: eth_call (read contract)
const callStart = Date.now()
await client.readContract({
address: '0x111111111fd1a588bdb8254e3af1fc2fb0d9078a' as const,
abi: [{ name: 'paused', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ name: '', type: 'bool' }] }],
functionName: 'paused',
})
result.callLatency = Date.now() - callStart
result.avgLatency = (result.blockNumberLatency + result.callLatency) / 2
result.success = true
// Close WS connection if needed
if (type === 'WS' && 'transport' in client && typeof (client.transport as any).close === 'function') {
;(client.transport as any).close()
}
} catch (error: any) {
result.error = error.message || String(error)
result.success = false
}
return result
}
async function main() {
console.log('π Phase 4: RPC Latency Probe\n')
console.log('='.repeat(80))
// Get RPCs from env or use defaults
const rpcsHttpEnv = process.env.RPCS_HTTP || ''
const rpcsWsEnv = process.env.RPCS_WS || ''
const rpcsHttp = rpcsHttpEnv.split(',').map(s => s.trim()).filter(Boolean)
const rpcsWs = rpcsWsEnv.split(',').map(s => s.trim()).filter(Boolean)
if (rpcsHttp.length === 0 && rpcsWs.length === 0) {
console.error('β No RPCs configured. Set RPCS_HTTP and/or RPCS_WS in .env')
process.exit(1)
}
console.log(`Testing ${rpcsHttp.length} HTTP RPCs and ${rpcsWs.length} WS RPCs...\n`)
const allResults: RpcLatency[] = []
// Probe HTTP RPCs
for (const rpc of rpcsHttp) {
console.log(`Probing HTTP: ${rpc}...`)
const result = await probeRpcLatency(rpc, 'HTTP')
allResults.push(result)
if (result.success) {
console.log(` β
BlockNumber: ${result.blockNumberLatency}ms, Call: ${result.callLatency}ms, Avg: ${result.avgLatency.toFixed(1)}ms`)
} else {
console.log(` β Failed: ${result.error}`)
}
}
// Probe WS RPCs
for (const rpc of rpcsWs) {
console.log(`Probing WS: ${rpc}...`)
const result = await probeRpcLatency(rpc, 'WS')
allResults.push(result)
if (result.success) {
console.log(` β
BlockNumber: ${result.blockNumberLatency}ms, Call: ${result.callLatency}ms, Avg: ${result.avgLatency.toFixed(1)}ms`)
} else {
console.log(` β Failed: ${result.error}`)
}
}
// Sort by average latency
const successful = allResults.filter(r => r.success).sort((a, b) => a.avgLatency - b.avgLatency)
const failed = allResults.filter(r => !r.success)
console.log('\n' + '='.repeat(80))
console.log('π RPC LATENCY RANKING (fastest first)')
console.log('='.repeat(80))
if (successful.length === 0) {
console.error('β All RPCs failed!')
process.exit(1)
}
console.log('\nβ
Successful RPCs:')
successful.forEach((rpc, idx) => {
console.log(` ${idx + 1}. ${rpc.type.padEnd(4)} ${rpc.url.padEnd(60)} Avg: ${rpc.avgLatency.toFixed(1)}ms`)
})
if (failed.length > 0) {
console.log('\nβ Failed RPCs:')
failed.forEach(rpc => {
console.log(` - ${rpc.type.padEnd(4)} ${rpc.url.padEnd(60)} Error: ${rpc.error}`)
})
}
console.log('\n' + '='.repeat(80))
console.log('π‘ Recommended .env configuration:')
console.log('='.repeat(80))
const httpSorted = successful.filter(r => r.type === 'HTTP').map(r => r.url)
const wsSorted = successful.filter(r => r.type === 'WS').map(r => r.url)
console.log('\nRPCS_HTTP=' + httpSorted.join(','))
if (wsSorted.length > 0) {
console.log('RPCS_WS=' + wsSorted.join(','))
}
console.log('\nβ
Latency probe complete')
}
main().catch((error) => {
console.error('Fatal error:', error)
process.exit(1)
})