@w3lib/evm-batch-call 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -35
  3. package/contracts/DeploylessMulticall3.sol +5 -0
  4. package/dist/aggregate.d.ts +20 -1
  5. package/dist/aggregate.d.ts.map +1 -1
  6. package/dist/aggregate.js +143 -5
  7. package/dist/aggregate.js.map +1 -1
  8. package/dist/batcher.d.ts +6 -1
  9. package/dist/batcher.d.ts.map +1 -1
  10. package/dist/batcher.js +59 -9
  11. package/dist/batcher.js.map +1 -1
  12. package/dist/call.d.ts +27 -2
  13. package/dist/call.d.ts.map +1 -1
  14. package/dist/call.js +22 -0
  15. package/dist/call.js.map +1 -1
  16. package/dist/chains.d.ts +7 -0
  17. package/dist/chains.d.ts.map +1 -1
  18. package/dist/chains.js +11 -0
  19. package/dist/chains.js.map +1 -1
  20. package/dist/deployless.d.ts +1 -1
  21. package/dist/deployless.d.ts.map +1 -1
  22. package/dist/deployless.js +1 -1
  23. package/dist/deployless.js.map +1 -1
  24. package/dist/erc20.d.ts +70 -4
  25. package/dist/erc20.d.ts.map +1 -1
  26. package/dist/erc20.js +121 -5
  27. package/dist/erc20.js.map +1 -1
  28. package/dist/events.d.ts +25 -0
  29. package/dist/events.d.ts.map +1 -0
  30. package/dist/events.js +25 -0
  31. package/dist/events.js.map +1 -0
  32. package/dist/fallback.d.ts +31 -3
  33. package/dist/fallback.d.ts.map +1 -1
  34. package/dist/fallback.js +165 -27
  35. package/dist/fallback.js.map +1 -1
  36. package/dist/index.d.ts +9 -10
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +6 -7
  39. package/dist/index.js.map +1 -1
  40. package/dist/multicall.d.ts.map +1 -1
  41. package/dist/multicall.js +33 -2
  42. package/dist/multicall.js.map +1 -1
  43. package/dist/nft.d.ts +5 -0
  44. package/dist/nft.d.ts.map +1 -1
  45. package/dist/nft.js +5 -0
  46. package/dist/nft.js.map +1 -1
  47. package/dist/owner.d.ts +9 -0
  48. package/dist/owner.d.ts.map +1 -1
  49. package/dist/owner.js +11 -2
  50. package/dist/owner.js.map +1 -1
  51. package/dist/provider.d.ts +55 -29
  52. package/dist/provider.d.ts.map +1 -1
  53. package/dist/provider.js +140 -111
  54. package/dist/provider.js.map +1 -1
  55. package/dist/shortcuts.d.ts +34 -53
  56. package/dist/shortcuts.d.ts.map +1 -1
  57. package/dist/shortcuts.js +41 -91
  58. package/dist/shortcuts.js.map +1 -1
  59. package/dist/source.d.ts +4 -2
  60. package/dist/source.d.ts.map +1 -1
  61. package/dist/source.js +35 -6
  62. package/dist/source.js.map +1 -1
  63. package/dist/subpaths/nft.d.ts +46 -0
  64. package/dist/subpaths/nft.d.ts.map +1 -0
  65. package/dist/subpaths/nft.js +55 -0
  66. package/dist/subpaths/nft.js.map +1 -0
  67. package/dist/subpaths/owner.d.ts +33 -0
  68. package/dist/subpaths/owner.d.ts.map +1 -0
  69. package/dist/subpaths/owner.js +34 -0
  70. package/dist/subpaths/owner.js.map +1 -0
  71. package/dist/tron.d.ts +2 -0
  72. package/dist/tron.d.ts.map +1 -1
  73. package/dist/tron.js +5 -0
  74. package/dist/tron.js.map +1 -1
  75. package/dist/util.d.ts +5 -0
  76. package/dist/util.d.ts.map +1 -1
  77. package/dist/util.js +23 -0
  78. package/dist/util.js.map +1 -1
  79. package/dist/watch.d.ts +25 -0
  80. package/dist/watch.d.ts.map +1 -0
  81. package/dist/watch.js +105 -0
  82. package/dist/watch.js.map +1 -0
  83. package/package.json +19 -10
  84. package/src/aggregate.ts +172 -7
  85. package/src/batcher.ts +69 -9
  86. package/src/call.ts +42 -2
  87. package/src/chains.ts +15 -0
  88. package/src/deployless.ts +1 -1
  89. package/src/erc20.ts +171 -8
  90. package/src/events.ts +42 -0
  91. package/src/fallback.ts +193 -26
  92. package/src/index.ts +19 -61
  93. package/src/multicall.ts +34 -2
  94. package/src/nft.ts +5 -0
  95. package/src/owner.ts +11 -2
  96. package/src/provider.ts +225 -124
  97. package/src/shortcuts.ts +76 -110
  98. package/src/source.ts +35 -8
  99. package/src/subpaths/nft.ts +107 -0
  100. package/src/subpaths/owner.ts +69 -0
  101. package/src/tron.ts +7 -0
  102. package/src/util.ts +27 -0
  103. package/src/watch.ts +149 -0
package/src/erc20.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { BoundCall } from './call.js'
1
+ import type { BoundCall, FailureReason } from './call.js'
2
2
  import type { BoundMethod, Contract } from './contract.js'
3
3
 
4
4
  export const ERC20_ABI = [
@@ -41,9 +41,18 @@ export interface TokenAllowance {
41
41
  formatted: string
42
42
  /** 额度 ≥ uint96 最大值时为 true(覆盖 MaxUint256,以及 UNI / COMP 等把额度截断为 uint96 的代币) */
43
43
  unlimited: boolean
44
+ /** 仅在 withBlock / minBlock 时返回:读取时的区块号(读取失败为 null) */
45
+ blockNumber?: number | null
44
46
  success: boolean
47
+ /** 仅在 success 为 false 时返回:失败原因 */
48
+ error?: FailureReason
49
+ /** 仅在 success 为 false 时返回:哪一项没读到 */
50
+ errorField?: 'allowance' | 'decimals'
45
51
  }
46
52
 
53
+ /** allowances(..., { decimals: false }) 的单项结果:不查 decimals,不带 decimals / formatted */
54
+ export type RawTokenAllowance = Omit<TokenAllowance, 'decimals' | 'formatted'>
55
+
47
56
  /** unlimited 的判定阈值:uint96 最大值 */
48
57
  export const UNLIMITED_ALLOWANCE_THRESHOLD = 2n ** 96n - 1n
49
58
 
@@ -75,8 +84,14 @@ export type TokenDetails<F extends TokenField = DefaultTokenField> = {
75
84
  address: string
76
85
  /** 是否是主币占位地址(信息来自内置链信息表 / nativeSymbol 等配置) */
77
86
  native: boolean
87
+ /** 仅在 withBlock / minBlock 时返回:读取时的区块号(读取失败为 null) */
88
+ blockNumber?: number | null
78
89
  /** 请求的字段都读到时为 true(主币没有 totalSupply,不计入) */
79
90
  success: boolean
91
+ /** 仅在 success 为 false 时返回:第一个没读到的字段的失败原因 */
92
+ error?: FailureReason
93
+ /** 仅在 success 为 false 时返回:第一个没读到的字段 */
94
+ errorField?: TokenField
80
95
  } & { [K in F]: TokenFieldTypes[K] } & ('totalSupply' extends F ? { totalSupplyFormatted: string | null } : unknown)
81
96
 
82
97
  /** 主币占位地址(多数聚合器、钱包的约定),传给 balances() 时按主币处理 */
@@ -100,15 +115,27 @@ export interface TokenBalance {
100
115
  formatted: string
101
116
  /** 仅在 symbol: true 时返回;读取失败或主币 symbol 未知时为 null */
102
117
  symbol?: string | null
118
+ /** 仅在 withBlock / minBlock 时返回:读取时的区块号(与余额在同一次 eth_call 里读出;读取失败为 null) */
119
+ blockNumber?: number | null
103
120
  /** 余额和 decimals 都查到时为 true;失败时 balance、formatted 都为 "0" */
104
121
  success: boolean
122
+ /**
123
+ * 仅在 success 为 false 时返回:失败原因(invalid-address 地址非法、no-contract 地址上没有合约、
124
+ * reverted 执行 revert、decode-failed 返回值无法解码)。symbol 读不到不算失败(symbol 为 null)
125
+ */
126
+ error?: FailureReason
127
+ /** 仅在 success 为 false 时返回:哪一项没读到(两项都失败时为 balance) */
128
+ errorField?: 'balance' | 'decimals'
105
129
  }
106
130
 
131
+ /** balances(..., { decimals: false }) 的单项结果:不查 decimals,不带 decimals / formatted */
132
+ export type RawTokenBalance = Omit<TokenBalance, 'decimals' | 'formatted' | 'errorField'> & { errorField?: 'balance' }
133
+
107
134
  /**
108
- * 按精度格式化:formatAmount(1234500000n, 6) === '1234.5',formatAmount(10n ** 18n, 18) === '1'。
109
- * 不做四舍五入,保留全部有效小数位。
135
+ * 按精度格式化(与 ethers 的 formatUnits 同名同义):formatUnits(1234500000n, 6) === '1234.5',formatUnits(10n ** 18n, 18) === '1'。
136
+ * 不做四舍五入,保留全部有效小数位,整数不带小数点(与 ethers 不同:ethers 会返回 '1.0')。
110
137
  */
111
- export function formatAmount(value: bigint, decimals: number): string {
138
+ export function formatUnits(value: bigint, decimals: number): string {
112
139
  const negative = value < 0n
113
140
  const digits = (negative ? -value : value).toString().padStart(decimals + 1, '0')
114
141
  const whole = digits.slice(0, digits.length - decimals)
@@ -116,7 +143,11 @@ export function formatAmount(value: bigint, decimals: number): string {
116
143
  return `${negative ? '-' : ''}${whole}${fraction ? `.${fraction}` : ''}`
117
144
  }
118
145
 
119
- // decimals / symbol / name 不会变,按 chainId + 地址缓存,轮询余额时只需要查 balanceOf
146
+ /** @deprecated 改用 formatUnits(同一个函数;formatAmount 容易与项目里的数字展示函数撞名) */
147
+ export const formatAmount = formatUnits
148
+
149
+ // 代币信息缓存(按 chainId + 地址):decimals / NFT 标准不会变,永久缓存;name / symbol 在可升级合约上可能改,缓存 1 小时。
150
+ // 条目数有上限,超出时淘汰最早写入的(与 solana-batch-call 一致)。轮询余额时只需要查 balanceOf
120
151
  interface TokenMeta {
121
152
  decimals?: number
122
153
  symbol?: string
@@ -125,21 +156,153 @@ interface TokenMeta {
125
156
  standard?: 'ERC721' | 'ERC1155' | null
126
157
  }
127
158
 
128
- const tokenMetaCache = new Map<string, TokenMeta>()
159
+ interface CachedMeta extends TokenMeta {
160
+ /** name / symbol 各自的写入时间(分开计:只刷新其中一个时,另一个照常过期) */
161
+ nameAt?: number
162
+ symbolAt?: number
163
+ }
164
+
165
+ const NAME_TTL = 60 * 60 * 1000
166
+ const MAX_CACHED_TOKENS = 50_000
167
+ const tokenMetaCache = new Map<string, CachedMeta>()
168
+ const cacheListeners = new Set<() => void>()
129
169
 
130
170
  export function getCachedTokenMeta(chainId: number, token: string): TokenMeta {
131
- return tokenMetaCache.get(`${chainId}:${token.toLowerCase()}`) ?? {}
171
+ const cached = tokenMetaCache.get(`${chainId}:${token.toLowerCase()}`)
172
+ if (!cached) {
173
+ return {}
174
+ }
175
+ const { nameAt, symbolAt, ...meta } = cached
176
+ const now = Date.now()
177
+ if (nameAt === undefined || now - nameAt > NAME_TTL) {
178
+ delete meta.name
179
+ }
180
+ if (symbolAt === undefined || now - symbolAt > NAME_TTL) {
181
+ delete meta.symbol
182
+ }
183
+ return meta
132
184
  }
133
185
 
134
186
  export function setCachedTokenMeta(chainId: number, token: string, meta: TokenMeta): void {
135
187
  if (Object.keys(meta).length === 0) {
136
188
  return // 没有新数据(如查询失败)时不写入空条目
137
189
  }
190
+ const defined: CachedMeta = { ...meta }
191
+ if ('name' in meta) {
192
+ defined.nameAt = Date.now()
193
+ }
194
+ if ('symbol' in meta) {
195
+ defined.symbolAt = Date.now()
196
+ }
138
197
  const key = `${chainId}:${token.toLowerCase()}`
139
- tokenMetaCache.set(key, { ...tokenMetaCache.get(key), ...meta })
198
+ const merged = { ...tokenMetaCache.get(key), ...defined }
199
+ tokenMetaCache.delete(key) // 重新插入,保持“最近写入在后”的顺序
200
+ tokenMetaCache.set(key, merged)
201
+ if (tokenMetaCache.size > MAX_CACHED_TOKENS) {
202
+ tokenMetaCache.delete(tokenMetaCache.keys().next().value as string)
203
+ }
204
+ cacheListeners.forEach((listener) => listener())
140
205
  }
141
206
 
142
207
  /** 测试用:清空 decimals / symbol 缓存 */
143
208
  export function resetDecimalsCache(): void {
144
209
  tokenMetaCache.clear()
145
210
  }
211
+
212
+ /** exportTokenMetaCache() 的结果,可以 JSON.stringify */
213
+ export interface TokenMetaSnapshot {
214
+ version: 1
215
+ /** [chainId:小写地址, 信息],按写入时间先后 */
216
+ entries: Array<[string, CachedMeta]>
217
+ }
218
+
219
+ /**
220
+ * 导出代币信息缓存(decimals / symbol / name / NFT 标准),可存到任意地方,下次用 importTokenMetaCache 导入,
221
+ * 页面刷新后不必重查精度。name / symbol 带写入时间,导入后仍按 1 小时过期。
222
+ *
223
+ * @param maxEntries 最多导出多少条(最近写入的优先),默认全部
224
+ */
225
+ export function exportTokenMetaCache(maxEntries = Number.POSITIVE_INFINITY): TokenMetaSnapshot {
226
+ const entries = [...tokenMetaCache]
227
+ return { version: 1, entries: entries.slice(Math.max(0, entries.length - maxEntries)) }
228
+ }
229
+
230
+ /** 导入 exportTokenMetaCache 的结果;格式不对的数据忽略。已有的条目以缓存里的为准(更新) */
231
+ export function importTokenMetaCache(snapshot: unknown): void {
232
+ const entries = (snapshot as Partial<TokenMetaSnapshot> | null)?.entries
233
+ if ((snapshot as Partial<TokenMetaSnapshot> | null)?.version !== 1 || !Array.isArray(entries)) {
234
+ return
235
+ }
236
+ for (const entry of entries) {
237
+ if (!Array.isArray(entry) || typeof entry[0] !== 'string' || !/^\d+:\S+$/.test(entry[0]) || !entry[1] || typeof entry[1] !== 'object') {
238
+ continue
239
+ }
240
+ const [rawKey, value] = entry as [string, CachedMeta]
241
+ // 与 getCachedTokenMeta 的 key 一致:地址部分小写
242
+ const separator = rawKey.indexOf(':')
243
+ const key = `${rawKey.slice(0, separator)}:${rawKey.slice(separator + 1).toLowerCase()}`
244
+ const meta: CachedMeta = {}
245
+ if (Number.isInteger(value.decimals) && (value.decimals as number) >= 0 && (value.decimals as number) <= 255) meta.decimals = value.decimals
246
+ if (typeof value.name === 'string' && typeof value.nameAt === 'number') {
247
+ meta.name = value.name
248
+ meta.nameAt = value.nameAt
249
+ }
250
+ if (typeof value.symbol === 'string' && typeof value.symbolAt === 'number') {
251
+ meta.symbol = value.symbol
252
+ meta.symbolAt = value.symbolAt
253
+ }
254
+ if (value.standard === 'ERC721' || value.standard === 'ERC1155' || value.standard === null) meta.standard = value.standard
255
+ if (Object.keys(meta).length && !tokenMetaCache.has(key)) {
256
+ tokenMetaCache.set(key, meta)
257
+ }
258
+ }
259
+ while (tokenMetaCache.size > MAX_CACHED_TOKENS) {
260
+ tokenMetaCache.delete(tokenMetaCache.keys().next().value as string)
261
+ }
262
+ }
263
+
264
+ /** persistTokenMetaCache 的存储:localStorage / sessionStorage 可以直接传,也可以自己实现 */
265
+ export interface TokenMetaStore {
266
+ getItem(key: string): string | null
267
+ setItem(key: string, value: string): void
268
+ }
269
+
270
+ /**
271
+ * 把代币信息缓存持久化到同步的键值存储(如 localStorage):调用时先读入,之后缓存有更新就防抖(1 秒)整体写回。
272
+ * 返回停止持久化的函数。存储读写出错(如超出配额)时忽略。
273
+ *
274
+ * ```ts
275
+ * persistTokenMetaCache(localStorage) // 刷新页面后不必重查 decimals
276
+ * ```
277
+ */
278
+ export function persistTokenMetaCache(store: TokenMetaStore, options: { key?: string; maxEntries?: number } = {}): () => void {
279
+ const { key = 'w3lib:evm-token-meta', maxEntries = 5000 } = options
280
+ try {
281
+ const raw = store.getItem(key)
282
+ if (raw) {
283
+ importTokenMetaCache(JSON.parse(raw))
284
+ }
285
+ } catch {
286
+ // 数据损坏:忽略,之后会被覆盖
287
+ }
288
+ let timer: ReturnType<typeof setTimeout> | undefined
289
+ const save = () => {
290
+ timer = undefined
291
+ try {
292
+ store.setItem(key, JSON.stringify(exportTokenMetaCache(maxEntries)))
293
+ } catch {
294
+ // 超出配额等:忽略
295
+ }
296
+ }
297
+ const listener = () => {
298
+ timer ??= setTimeout(save, 1000)
299
+ }
300
+ cacheListeners.add(listener)
301
+ return () => {
302
+ cacheListeners.delete(listener)
303
+ if (timer !== undefined) {
304
+ clearTimeout(timer)
305
+ save()
306
+ }
307
+ }
308
+ }
package/src/events.ts ADDED
@@ -0,0 +1,42 @@
1
+ /** 一次对某个节点的请求(onRequest 的事件) */
2
+ export interface RequestEvent {
3
+ /** 节点标识:URL 节点只取 host(不含 path / query,避免泄露 API Key);钱包为 'wallet',tronWeb 为 'tronWeb',其他对象为 'provider' */
4
+ node: string
5
+ /** 'call' | 'getBalance' | 'getChainId' | 'getBlockNumber' | 'getLogs' */
6
+ method: string
7
+ /** 耗时(毫秒) */
8
+ ms: number
9
+ ok: boolean
10
+ /** 失败时的错误 */
11
+ error?: unknown
12
+ /** 本次请求按故障切换顺序的第几个节点(0 起);大于 0 表示换过节点 */
13
+ attempt: number
14
+ }
15
+
16
+ export type RequestListener = (event: RequestEvent) => void
17
+
18
+ const listeners = new Set<RequestListener>()
19
+
20
+ /**
21
+ * 订阅所有节点请求(全局,对所有 Provider 生效),用于观察哪个节点返回、换过几次节点、每次耗时。返回取消订阅的函数。
22
+ *
23
+ * ```ts
24
+ * const off = onRequest((e) => console.log(e.node, e.method, e.ms, e.ok, e.attempt))
25
+ * ```
26
+ */
27
+ export function onRequest(listener: RequestListener): () => void {
28
+ listeners.add(listener)
29
+ return () => {
30
+ listeners.delete(listener)
31
+ }
32
+ }
33
+
34
+ export function emitRequest(event: RequestEvent): void {
35
+ for (const listener of listeners) {
36
+ try {
37
+ listener(event)
38
+ } catch {
39
+ // 监听函数出错不影响请求
40
+ }
41
+ }
42
+ }
package/src/fallback.ts CHANGED
@@ -3,17 +3,80 @@ import { isError, type TransactionRequest } from 'ethers'
3
3
  import type { EthersLikeProvider } from './aggregate.js'
4
4
  import { detectChainIdOf } from './detect.js'
5
5
  import { isExecutionError } from './errors.js'
6
- import { withTimeout } from './util.js'
6
+ import { emitRequest } from './events.js'
7
+ import { TimeoutError, withTimeout } from './util.js'
7
8
 
8
9
  export interface FallbackOptions {
9
10
  /** 单个节点单次请求超时(毫秒),超时视为该节点故障并换下一个。默认 10000;<= 0 表示不限制 */
10
11
  timeout?: number
11
- /** 节点出错后跳过它的时长(毫秒),期间优先用其他节点。默认 30000 */
12
+ /**
13
+ * 节点迟迟不返回时,过多久(毫秒)同时请求下一个节点:原来的请求不取消,谁先成功用谁(与 ethers FallbackProvider 的 stallTimeout 相同)。
14
+ * 适合正常但偶尔较慢的节点:不必把 timeout 设得很短(正常的慢请求会被判成超时)。
15
+ * 默认 0(不提前请求,只在出错 / 超时后换节点);只影响 call / getBalance,不影响 getLogs / getBlockNumber
16
+ */
17
+ stallTimeout?: number
18
+ /** 节点出错后跳过它的时长(毫秒),期间优先用其他节点。默认 30000。超时不算出错,同一节点连续 3 次超时才冷却 */
12
19
  cooldown?: number
13
20
  }
14
21
 
22
+ /** FallbackRpc 每个节点的标识(resolveSource 传入;直接 new FallbackRpc 时可省略) */
23
+ export interface FallbackNodeInfo {
24
+ /** 用于错误信息和 onRequest 事件的节点标识 */
25
+ label: string
26
+ /** 健康状态的 key:URL 字符串或节点对象。相同 key 的节点在所有 FallbackRpc 之间共享冷却状态 */
27
+ key: string | object
28
+ }
29
+
30
+ /** 节点健康状态,按节点(URL / 对象)全局共享:Provider 重建后刚失败过的节点仍排在后面 */
31
+ interface Health {
32
+ failedAt: number
33
+ /** 连续超时次数 */
34
+ timeouts: number
35
+ }
36
+
37
+ /** 连续超时多少次后才冷却(偶尔慢不算坏节点) */
38
+ const TIMEOUTS_BEFORE_COOLDOWN = 3
39
+ const MAX_TRACKED_URLS = 1000
40
+ const healthByUrl = new Map<string, Health>()
41
+ const healthByObject = new WeakMap<object, Health>()
42
+
43
+ function healthOf(key: string | object): Health {
44
+ if (typeof key === 'string') {
45
+ let health = healthByUrl.get(key)
46
+ if (!health) {
47
+ health = { failedAt: 0, timeouts: 0 }
48
+ healthByUrl.set(key, health)
49
+ if (healthByUrl.size > MAX_TRACKED_URLS) {
50
+ healthByUrl.delete(healthByUrl.keys().next().value as string)
51
+ }
52
+ }
53
+ return health
54
+ }
55
+ let health = healthByObject.get(key)
56
+ if (!health) {
57
+ health = { failedAt: 0, timeouts: 0 }
58
+ healthByObject.set(key, health)
59
+ }
60
+ return health
61
+ }
62
+
63
+ /** 测试用:清空全局的节点健康状态 */
64
+ export function resetNodeHealth(): void {
65
+ healthByUrl.clear()
66
+ }
67
+
68
+ /** 所有节点都失败(多节点时):errors 是每个节点的标识和失败原因,按尝试顺序 */
69
+ export class AllNodesFailedError extends Error {
70
+ constructor(readonly errors: ReadonlyArray<{ node: string; error: unknown }>) {
71
+ super(`All RPC nodes failed: ${errors.map((e) => `${e.node}: ${errorText(e.error)}`).join(' | ')}`, { cause: errors[errors.length - 1]?.error })
72
+ this.name = 'AllNodesFailedError'
73
+ }
74
+ }
75
+
15
76
  /**
16
- * 多节点故障切换:按顺序使用节点,出错或超时换下一个;出错的节点在 cooldown 内排到最后。
77
+ * 多节点故障切换:按顺序使用节点,出错或超时换下一个;出错的节点在 cooldown 内排到最后(超时只换节点,连续 3 次才冷却)。
78
+ * 设置了 stallTimeout 时,节点迟迟不返回就同时请求下一个,谁先成功用谁。所有节点都失败时抛 AllNodesFailedError(单节点时抛原始错误)。
79
+ * 冷却状态按节点全局共享,每次请求都会触发 onRequest 事件。
17
80
  *
18
81
  * 与 ethers FallbackProvider 相比:
19
82
  * - 没有首次请求前对所有节点的 getBlockNumber 同步,一个卡住的节点不会拖住第一次查询
@@ -22,8 +85,11 @@ export interface FallbackOptions {
22
85
  export class FallbackRpc implements EthersLikeProvider {
23
86
  readonly #nodes: EthersLikeProvider[]
24
87
  readonly #timeout: number
88
+ readonly #stallTimeout: number
25
89
  readonly #cooldown: number
26
- readonly #failedAt: number[]
90
+ readonly #labels: string[]
91
+ /** 健康状态的 key;每次用时再从全局表里取(表淘汰条目后,各实例仍取到同一个对象) */
92
+ readonly #healthKeys: Array<string | object>
27
93
  /** 上次 getLogs 成功的节点 */
28
94
  #logsNode = -1
29
95
  /** 上次成功的节点连续被限频的次数 */
@@ -31,14 +97,16 @@ export class FallbackRpc implements EthersLikeProvider {
31
97
  /** getLogs 超时 / 连不上的时间,只影响 getLogs 的节点顺序 */
32
98
  readonly #logsFailedAt: number[]
33
99
 
34
- constructor(nodes: EthersLikeProvider[], options: FallbackOptions = {}) {
100
+ constructor(nodes: EthersLikeProvider[], options: FallbackOptions = {}, info?: readonly FallbackNodeInfo[]) {
35
101
  if (!nodes.length) {
36
102
  throw new Error('FallbackRpc requires at least one node')
37
103
  }
38
104
  this.#nodes = nodes
39
105
  this.#timeout = options.timeout ?? 10_000
106
+ this.#stallTimeout = options.stallTimeout ?? 0
40
107
  this.#cooldown = options.cooldown ?? 30_000
41
- this.#failedAt = nodes.map(() => 0)
108
+ this.#labels = nodes.map((_, i) => info?.[i]?.label ?? `node${i}`)
109
+ this.#healthKeys = nodes.map((node, i) => info?.[i]?.key ?? node)
42
110
  this.#logsFailedAt = nodes.map(() => 0)
43
111
  }
44
112
 
@@ -47,16 +115,34 @@ export class FallbackRpc implements EthersLikeProvider {
47
115
  }
48
116
 
49
117
  call(tx: TransactionRequest): Promise<string> {
50
- return this.#run((node) => node.call(tx))
118
+ return this.#run('call', (node) => node.call(tx))
51
119
  }
52
120
 
53
121
  getBalance(address: Parameters<EthersLikeProvider['getBalance']>[0], blockTag?: Parameters<EthersLikeProvider['getBalance']>[1]): Promise<bigint> {
54
- return this.#run((node) => node.getBalance(address, blockTag))
122
+ return this.#run('getBalance', (node) => node.getBalance(address, blockTag))
55
123
  }
56
124
 
57
125
  /** 按节点顺序探测 chainId(节点需实现 getChainId,见 detect.ts) */
58
126
  getChainId(): Promise<number> {
59
- return this.#run((node) => detectChainIdOf(node))
127
+ return this.#run('getChainId', (node) => detectChainIdOf(node))
128
+ }
129
+
130
+ /** 对第 index 个节点发一次请求(带超时),并触发 onRequest 事件 */
131
+ async #attempt<T>(method: string, index: number, attempt: number, fn: (node: EthersLikeProvider) => Promise<T>, timeout = this.#timeout): Promise<T> {
132
+ const started = Date.now()
133
+ try {
134
+ const result = await withTimeout(Promise.resolve().then(() => fn(this.#nodes[index] as EthersLikeProvider)), timeout)
135
+ emitRequest({ node: this.#labels[index] as string, method, ms: Date.now() - started, ok: true, attempt })
136
+ return result
137
+ } catch (err) {
138
+ emitRequest({ node: this.#labels[index] as string, method, ms: Date.now() - started, ok: false, error: err, attempt })
139
+ throw err
140
+ }
141
+ }
142
+
143
+ /** 单节点:直接请求(getLogs / getBlockNumber 不走多节点的特殊逻辑),抛原始错误 */
144
+ #single<T>(method: string, fn: (node: EthersLikeProvider) => Promise<T>): Promise<T> {
145
+ return this.#attempt(method, 0, 0, fn)
60
146
  }
61
147
 
62
148
  /**
@@ -64,14 +150,22 @@ export class FallbackRpc implements EthersLikeProvider {
64
150
  * 不支持 getBlockNumber 的节点跳过,失败也不让节点进入冷却(不影响 call / getBalance)
65
151
  */
66
152
  async getBlockNumber(): Promise<number> {
153
+ if (this.#nodes.length === 1) {
154
+ const node = this.#nodes[0] as EthersLikeProvider
155
+ if (!node.getBlockNumber) {
156
+ throw new Error('getBlockNumber is not supported by this provider')
157
+ }
158
+ return this.#single('getBlockNumber', (n) => (n.getBlockNumber as () => Promise<number>)())
159
+ }
67
160
  let lastError: unknown = new Error('No node supports getBlockNumber')
161
+ let attempt = 0
68
162
  for (const index of this.#preferLogsNode(this.#order())) {
69
163
  const node = this.#nodes[index] as EthersLikeProvider
70
164
  if (!node.getBlockNumber) {
71
165
  continue
72
166
  }
73
167
  try {
74
- return await withTimeout(node.getBlockNumber(), this.#timeout)
168
+ return await this.#attempt('getBlockNumber', index, attempt++, (n) => (n.getBlockNumber as () => Promise<number>)())
75
169
  } catch (err) {
76
170
  lastError = err
77
171
  }
@@ -86,16 +180,25 @@ export class FallbackRpc implements EthersLikeProvider {
86
180
  * - 在用的节点被限频时直接抛出(连续 3 次后才换节点),其他情况全部失败时抛出;GetLogsError 带上每个节点的错误
87
181
  */
88
182
  async getLogs(filter: Parameters<NonNullable<EthersLikeProvider['getLogs']>>[0]): Promise<Awaited<ReturnType<NonNullable<EthersLikeProvider['getLogs']>>>> {
183
+ type GetLogs = NonNullable<EthersLikeProvider['getLogs']>
184
+ if (this.#nodes.length === 1) {
185
+ // 单节点:原样请求、抛原始错误(与不经过 FallbackRpc 时一致)
186
+ if (!this.#nodes[0]?.getLogs) {
187
+ throw new Error('getLogs is not supported by this provider')
188
+ }
189
+ return this.#single('getLogs', (n) => (n.getLogs as GetLogs)(filter))
190
+ }
89
191
  const errors: unknown[] = []
90
192
  let preferred: unknown
91
193
  const sticky = this.#logsNode
194
+ let attempt = 0
92
195
  for (const index of this.#preferLogsNode(this.#order(this.#logsFailedAt))) {
93
196
  const node = this.#nodes[index] as EthersLikeProvider
94
197
  if (!node.getLogs) {
95
198
  continue
96
199
  }
97
200
  try {
98
- const logs = await withTimeout(node.getLogs(filter), this.#timeout)
201
+ const logs = await this.#attempt('getLogs', index, attempt++, (n) => (n.getLogs as GetLogs)(filter))
99
202
  this.#logsNode = index
100
203
  this.#logsFailedAt[index] = 0
101
204
  this.#logsThrottled = 0
@@ -128,26 +231,83 @@ export class FallbackRpc implements EthersLikeProvider {
128
231
  throw new GetLogsError(errors, preferred)
129
232
  }
130
233
 
131
- async #run<T>(fn: (node: EthersLikeProvider) => Promise<T>): Promise<T> {
132
- let lastError: unknown
133
- for (const index of this.#order()) {
134
- try {
135
- const result = await withTimeout(fn(this.#nodes[index] as EthersLikeProvider), this.#timeout)
136
- this.#failedAt[index] = 0
137
- return result
138
- } catch (err) {
139
- if (isDeterministic(err)) {
140
- throw err
234
+ /**
235
+ * 按顺序请求节点:出错(非确定性错误)或超时立即换下一个;设置了 stallTimeout 时,
236
+ * 当前节点超过 stallTimeout 还没返回也会同时请求下一个(已发出的请求不取消),第一个成功的结果胜出。
237
+ * 出错的节点进入冷却;超时只换节点,同一节点连续 3 次超时才冷却(冷启动的大批量查询偶尔慢,不应把健康的节点踢到后面);
238
+ * 节点还没有请求的区块(minBlock 重查时落后的节点)也只换节点、不冷却。
239
+ * 确定性错误(revert、参数错误等)直接抛出;所有节点都失败时抛 AllNodesFailedError(单节点时抛原始错误)。
240
+ */
241
+ #run<T>(method: string, fn: (node: EthersLikeProvider) => Promise<T>): Promise<T> {
242
+ const order = this.#order()
243
+ return new Promise<T>((resolve, reject) => {
244
+ let next = 0
245
+ let running = 0
246
+ let settled = false
247
+ const errors: Array<{ node: string; error: unknown }> = []
248
+ let stallTimer: ReturnType<typeof setTimeout> | undefined
249
+ const finish = (done: () => void) => {
250
+ settled = true
251
+ clearTimeout(stallTimer)
252
+ done()
253
+ }
254
+ const fail = () => {
255
+ const only = errors.length === 1 && this.#nodes.length === 1
256
+ finish(() => reject(only ? errors[0]?.error : new AllNodesFailedError(errors)))
257
+ }
258
+ const launch = (): boolean => {
259
+ if (settled || next >= order.length) {
260
+ return false
141
261
  }
142
- this.#failedAt[index] = Date.now()
143
- lastError = err
262
+ const attempt = next++
263
+ const index = order[attempt] as number
264
+ const health = healthOf(this.#healthKeys[index] as string | object)
265
+ running++
266
+ clearTimeout(stallTimer)
267
+ if (this.#stallTimeout > 0 && next < order.length) {
268
+ stallTimer = setTimeout(launch, this.#stallTimeout)
269
+ }
270
+ this.#attempt(method, index, attempt, fn).then(
271
+ (result) => {
272
+ running--
273
+ health.failedAt = 0
274
+ health.timeouts = 0
275
+ if (!settled) {
276
+ finish(() => resolve(result))
277
+ }
278
+ },
279
+ (err: unknown) => {
280
+ running--
281
+ const deterministic = isDeterministic(err)
282
+ if (err instanceof TimeoutError) {
283
+ if (++health.timeouts >= TIMEOUTS_BEFORE_COOLDOWN) {
284
+ health.failedAt = Date.now()
285
+ health.timeouts = 0
286
+ }
287
+ } else if (!deterministic && !isBehind(err)) {
288
+ health.failedAt = Date.now()
289
+ }
290
+ if (settled) {
291
+ return
292
+ }
293
+ if (deterministic) {
294
+ finish(() => reject(err))
295
+ return
296
+ }
297
+ errors.push({ node: this.#labels[index] as string, error: err })
298
+ if (!launch() && running === 0) {
299
+ fail()
300
+ }
301
+ },
302
+ )
303
+ return true
144
304
  }
145
- }
146
- throw lastError
305
+ launch()
306
+ })
147
307
  }
148
308
 
149
309
  /** 健康的节点按原顺序在前,冷却中的按出错时间先后排在后面(全挂时也都会再试一次) */
150
- #order(failedAt: readonly number[] = this.#failedAt): number[] {
310
+ #order(failedAt: readonly number[] = this.#healthKeys.map((key) => healthOf(key).failedAt)): number[] {
151
311
  const now = Date.now()
152
312
  const healthy: number[] = []
153
313
  const cooling: number[] = []
@@ -198,6 +358,13 @@ function isRateLimited(err: unknown): boolean {
198
358
  return /too many requests|rate.?limit|\b429\b/i.test(errorText(err))
199
359
  }
200
360
 
361
+ /**
362
+ * 节点还没有请求的区块(minBlock 按指定区块重查时,落后的节点会这样报错):只换节点、不冷却——节点本身是健康的,只是慢一两个块
363
+ */
364
+ function isBehind(err: unknown): boolean {
365
+ return /header not found|unknown block|block not found|block .*not (yet )?(available|found)|requested block .*(ahead|future)|after last accepted block/i.test(errorText(err))
366
+ }
367
+
201
368
  /** 换节点也不会变的错误:合约执行结果、参数错误、用户拒绝等 */
202
369
  function isDeterministic(err: unknown): boolean {
203
370
  return (