@w3lib/evm-batch-call 0.2.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 (108) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +184 -30
  3. package/contracts/DeploylessMulticall3.sol +5 -0
  4. package/dist/aggregate.d.ts +25 -3
  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 +54 -3
  33. package/dist/fallback.d.ts.map +1 -1
  34. package/dist/fallback.js +273 -21
  35. package/dist/fallback.js.map +1 -1
  36. package/dist/index.d.ts +10 -8
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +7 -5
  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 +145 -0
  48. package/dist/owner.d.ts.map +1 -0
  49. package/dist/owner.js +510 -0
  50. package/dist/owner.js.map +1 -0
  51. package/dist/provider.d.ts +63 -18
  52. package/dist/provider.d.ts.map +1 -1
  53. package/dist/provider.js +166 -100
  54. package/dist/provider.js.map +1 -1
  55. package/dist/scan.d.ts +59 -0
  56. package/dist/scan.d.ts.map +1 -0
  57. package/dist/scan.js +245 -0
  58. package/dist/scan.js.map +1 -0
  59. package/dist/shortcuts.d.ts +34 -35
  60. package/dist/shortcuts.d.ts.map +1 -1
  61. package/dist/shortcuts.js +41 -73
  62. package/dist/shortcuts.js.map +1 -1
  63. package/dist/source.d.ts +6 -2
  64. package/dist/source.d.ts.map +1 -1
  65. package/dist/source.js +49 -6
  66. package/dist/source.js.map +1 -1
  67. package/dist/subpaths/nft.d.ts +46 -0
  68. package/dist/subpaths/nft.d.ts.map +1 -0
  69. package/dist/subpaths/nft.js +55 -0
  70. package/dist/subpaths/nft.js.map +1 -0
  71. package/dist/subpaths/owner.d.ts +33 -0
  72. package/dist/subpaths/owner.d.ts.map +1 -0
  73. package/dist/subpaths/owner.js +34 -0
  74. package/dist/subpaths/owner.js.map +1 -0
  75. package/dist/tron.d.ts +2 -0
  76. package/dist/tron.d.ts.map +1 -1
  77. package/dist/tron.js +5 -0
  78. package/dist/tron.js.map +1 -1
  79. package/dist/util.d.ts +5 -0
  80. package/dist/util.d.ts.map +1 -1
  81. package/dist/util.js +23 -0
  82. package/dist/util.js.map +1 -1
  83. package/dist/watch.d.ts +25 -0
  84. package/dist/watch.d.ts.map +1 -0
  85. package/dist/watch.js +105 -0
  86. package/dist/watch.js.map +1 -0
  87. package/package.json +19 -10
  88. package/src/aggregate.ts +177 -9
  89. package/src/batcher.ts +69 -9
  90. package/src/call.ts +42 -2
  91. package/src/chains.ts +15 -0
  92. package/src/deployless.ts +1 -1
  93. package/src/erc20.ts +171 -8
  94. package/src/events.ts +42 -0
  95. package/src/fallback.ts +306 -22
  96. package/src/index.ts +20 -27
  97. package/src/multicall.ts +34 -2
  98. package/src/nft.ts +5 -0
  99. package/src/owner.ts +660 -0
  100. package/src/provider.ts +255 -112
  101. package/src/scan.ts +293 -0
  102. package/src/shortcuts.ts +76 -88
  103. package/src/source.ts +51 -8
  104. package/src/subpaths/nft.ts +107 -0
  105. package/src/subpaths/owner.ts +69 -0
  106. package/src/tron.ts +7 -0
  107. package/src/util.ts +27 -0
  108. package/src/watch.ts +149 -0
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,17 +85,29 @@ 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>
93
+ /** 上次 getLogs 成功的节点 */
94
+ #logsNode = -1
95
+ /** 上次成功的节点连续被限频的次数 */
96
+ #logsThrottled = 0
97
+ /** getLogs 超时 / 连不上的时间,只影响 getLogs 的节点顺序 */
98
+ readonly #logsFailedAt: number[]
27
99
 
28
- constructor(nodes: EthersLikeProvider[], options: FallbackOptions = {}) {
100
+ constructor(nodes: EthersLikeProvider[], options: FallbackOptions = {}, info?: readonly FallbackNodeInfo[]) {
29
101
  if (!nodes.length) {
30
102
  throw new Error('FallbackRpc requires at least one node')
31
103
  }
32
104
  this.#nodes = nodes
33
105
  this.#timeout = options.timeout ?? 10_000
106
+ this.#stallTimeout = options.stallTimeout ?? 0
34
107
  this.#cooldown = options.cooldown ?? 30_000
35
- 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)
110
+ this.#logsFailedAt = nodes.map(() => 0)
36
111
  }
37
112
 
38
113
  get nodes(): readonly EthersLikeProvider[] {
@@ -40,45 +115,254 @@ export class FallbackRpc implements EthersLikeProvider {
40
115
  }
41
116
 
42
117
  call(tx: TransactionRequest): Promise<string> {
43
- return this.#run((node) => node.call(tx))
118
+ return this.#run('call', (node) => node.call(tx))
44
119
  }
45
120
 
46
121
  getBalance(address: Parameters<EthersLikeProvider['getBalance']>[0], blockTag?: Parameters<EthersLikeProvider['getBalance']>[1]): Promise<bigint> {
47
- return this.#run((node) => node.getBalance(address, blockTag))
122
+ return this.#run('getBalance', (node) => node.getBalance(address, blockTag))
48
123
  }
49
124
 
50
125
  /** 按节点顺序探测 chainId(节点需实现 getChainId,见 detect.ts) */
51
126
  getChainId(): Promise<number> {
52
- return this.#run((node) => detectChainIdOf(node))
127
+ return this.#run('getChainId', (node) => detectChainIdOf(node))
53
128
  }
54
129
 
55
- async #run<T>(fn: (node: EthersLikeProvider) => Promise<T>): Promise<T> {
56
- let lastError: unknown
57
- for (const index of this.#order()) {
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)
146
+ }
147
+
148
+ /**
149
+ * 当前区块号。优先问上次 getLogs 成功的节点(增量扫描时区块号和日志来自同一个节点,不会因节点间的高度差漏扫);
150
+ * 不支持 getBlockNumber 的节点跳过,失败也不让节点进入冷却(不影响 call / getBalance)
151
+ */
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
+ }
160
+ let lastError: unknown = new Error('No node supports getBlockNumber')
161
+ let attempt = 0
162
+ for (const index of this.#preferLogsNode(this.#order())) {
163
+ const node = this.#nodes[index] as EthersLikeProvider
164
+ if (!node.getBlockNumber) {
165
+ continue
166
+ }
58
167
  try {
59
- const result = await withTimeout(fn(this.#nodes[index] as EthersLikeProvider), this.#timeout)
60
- this.#failedAt[index] = 0
61
- return result
168
+ return await this.#attempt('getBlockNumber', index, attempt++, (n) => (n.getBlockNumber as () => Promise<number>)())
62
169
  } catch (err) {
63
- if (isDeterministic(err)) {
64
- throw err
65
- }
66
- this.#failedAt[index] = Date.now()
67
170
  lastError = err
68
171
  }
69
172
  }
70
173
  throw lastError
71
174
  }
72
175
 
176
+ /**
177
+ * 依次尝试支持 getLogs 的节点。与其他请求不同:
178
+ * - getLogs 失败多半是“区块范围超限 / 节点不开放这个方法”,不代表节点故障,所以不影响 call / getBalance 的节点顺序;
179
+ * 超时 / 连不上的节点只在 getLogs 里排到后面(冷却期内),上次成功的节点排在最前
180
+ * - 在用的节点被限频时直接抛出(连续 3 次后才换节点),其他情况全部失败时抛出;GetLogsError 带上每个节点的错误
181
+ */
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
+ }
191
+ const errors: unknown[] = []
192
+ let preferred: unknown
193
+ const sticky = this.#logsNode
194
+ let attempt = 0
195
+ for (const index of this.#preferLogsNode(this.#order(this.#logsFailedAt))) {
196
+ const node = this.#nodes[index] as EthersLikeProvider
197
+ if (!node.getLogs) {
198
+ continue
199
+ }
200
+ try {
201
+ const logs = await this.#attempt('getLogs', index, attempt++, (n) => (n.getLogs as GetLogs)(filter))
202
+ this.#logsNode = index
203
+ this.#logsFailedAt[index] = 0
204
+ this.#logsThrottled = 0
205
+ return logs
206
+ } catch (err) {
207
+ if (isError(err, 'INVALID_ARGUMENT')) {
208
+ throw err
209
+ }
210
+ if (!isAlive(err)) {
211
+ // 超时 / 连不上:排到后面;如果是上次成功的节点,不再优先用它
212
+ this.#logsFailedAt[index] = Date.now()
213
+ if (index === this.#logsNode) {
214
+ this.#logsNode = -1
215
+ }
216
+ } else if (index === sticky) {
217
+ preferred = err
218
+ if (isRateLimited(err)) {
219
+ // 在用的节点只是限频:直接抛出让调用方退避重试(其他节点多半本来就不能用,逐个试只会更慢);
220
+ // 连续 3 次就不再优先用它,试其他节点
221
+ if (++this.#logsThrottled < 3) {
222
+ throw new GetLogsError([err], err)
223
+ }
224
+ this.#logsThrottled = 0
225
+ this.#logsNode = -1
226
+ }
227
+ }
228
+ errors.push(err)
229
+ }
230
+ }
231
+ throw new GetLogsError(errors, preferred)
232
+ }
233
+
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
261
+ }
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
304
+ }
305
+ launch()
306
+ })
307
+ }
308
+
73
309
  /** 健康的节点按原顺序在前,冷却中的按出错时间先后排在后面(全挂时也都会再试一次) */
74
- #order(): number[] {
310
+ #order(failedAt: readonly number[] = this.#healthKeys.map((key) => healthOf(key).failedAt)): number[] {
75
311
  const now = Date.now()
76
312
  const healthy: number[] = []
77
313
  const cooling: number[] = []
78
- this.#failedAt.forEach((at, i) => (at && now - at < this.#cooldown ? cooling : healthy).push(i))
79
- cooling.sort((a, b) => (this.#failedAt[a] as number) - (this.#failedAt[b] as number))
314
+ failedAt.forEach((at, i) => (at && now - at < this.#cooldown ? cooling : healthy).push(i))
315
+ cooling.sort((a, b) => (failedAt[a] as number) - (failedAt[b] as number))
80
316
  return [...healthy, ...cooling]
81
317
  }
318
+
319
+ /** 上次 getLogs 成功的节点(不在 getLogs 冷却中时)排到最前 */
320
+ #preferLogsNode(order: number[]): number[] {
321
+ const index = this.#logsNode
322
+ const at = this.#logsFailedAt[index]
323
+ if (index < 0 || (at && Date.now() - at < this.#cooldown)) {
324
+ return order
325
+ }
326
+ return [index, ...order.filter((i) => i !== index)]
327
+ }
328
+ }
329
+
330
+ /**
331
+ * getLogs 失败时抛出(所有节点都失败,或在用的节点被限频),errors 是各节点的错误;
332
+ * preferred 是上次成功的节点这次返回的错误(它最能说明问题:其他节点可能一直就不能用)
333
+ */
334
+ export class GetLogsError extends Error {
335
+ constructor(
336
+ readonly errors: readonly unknown[],
337
+ readonly preferred?: unknown,
338
+ ) {
339
+ super(errors.length ? `getLogs failed: ${errors.map(errorText).join(' | ')}` : 'No node supports getLogs')
340
+ this.name = 'GetLogsError'
341
+ }
342
+ }
343
+
344
+ /** 取出错误里节点返回的原始信息(ethers 会把它放在 error.message 里,外层是 “could not coalesce error”) */
345
+ export function errorText(err: unknown): string {
346
+ const e = err as { error?: { message?: unknown }; info?: { error?: { message?: unknown } }; shortMessage?: unknown; message?: unknown } | null
347
+ const parts = [e?.error?.message, e?.info?.error?.message, e?.shortMessage ?? e?.message].filter((p) => typeof p === 'string')
348
+ return parts.length ? parts.join('; ') : String(err)
349
+ }
350
+
351
+ /** 节点正常返回了 JSON-RPC 错误(ethers 把它放在 error / info.error 里)或只是限频,说明节点本身可用 */
352
+ function isAlive(err: unknown): boolean {
353
+ const e = err as { error?: { message?: unknown }; info?: { error?: { message?: unknown } } } | null
354
+ return typeof (e?.error?.message ?? e?.info?.error?.message) === 'string' || isRateLimited(err)
355
+ }
356
+
357
+ function isRateLimited(err: unknown): boolean {
358
+ return /too many requests|rate.?limit|\b429\b/i.test(errorText(err))
359
+ }
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))
82
366
  }
83
367
 
84
368
  /** 换节点也不会变的错误:合约执行结果、参数错误、用户拒绝等 */
package/src/index.ts CHANGED
@@ -1,45 +1,33 @@
1
1
  export { Contract, bindCall, type BoundMethod, type ContractAbi, type ContractRunner } from './contract.js'
2
+ export { GetLogsError } from './fallback.js'
2
3
  export {
3
4
  getAllowances,
4
5
  getBalances,
5
- getErc1155Balances,
6
- getNftBalances,
7
- getNftCollections,
8
- getNftOwners,
9
- getNftTokenUris,
6
+ getMultiBalances,
10
7
  getTokens,
8
+ type GetAllowancesOptions,
11
9
  type GetBalancesOptions,
12
- type GetNftCollectionsOptions,
13
- type GetNftTokenUrisOptions,
14
10
  type GetTokensOptions,
15
11
  type ShortcutOptions,
16
12
  type ShortcutProviderOptions,
17
13
  } from './shortcuts.js'
18
- export {
19
- DEFAULT_NFT_COLLECTION_FIELDS,
20
- ERC1155_ABI,
21
- ERC721_ABI,
22
- type DefaultNftCollectionField,
23
- type Erc1155Balance,
24
- type NftBalance,
25
- type NftCollection,
26
- type NftCollectionField,
27
- type NftCollectionsOptions,
28
- type NftItem,
29
- type NftOwner,
30
- type NftStandard,
31
- type NftTokenUri,
32
- type NftTokenUriOptions,
33
- } from './nft.js'
34
- export { NATIVE_CURRENCIES, getNativeCurrency, type NativeCurrency } from './chains.js'
14
+ export { NATIVE_BALANCE_MODES, NATIVE_CURRENCIES, getNativeBalanceMode, getNativeCurrency, type NativeCurrency } from './chains.js'
35
15
  export { clearChainIdCache, detectChainId } from './detect.js'
36
16
  export {
37
17
  DEFAULT_NATIVE_TOKENS,
38
18
  ERC20_ABI,
39
19
  NATIVE_TOKEN,
20
+ exportTokenMetaCache,
40
21
  formatAmount,
22
+ formatUnits,
23
+ importTokenMetaCache,
24
+ persistTokenMetaCache,
25
+ type TokenMetaSnapshot,
26
+ type TokenMetaStore,
41
27
  type BalanceToken,
42
28
  type Erc20Contract,
29
+ type RawTokenAllowance,
30
+ type RawTokenBalance,
43
31
  type TokenBalance,
44
32
  type TokenAllowance,
45
33
  MAX_UINT256,
@@ -51,7 +39,10 @@ export {
51
39
  } from './erc20.js'
52
40
  export {
53
41
  Provider,
42
+ type AllowancesOptions,
54
43
  type BalancesOptions,
44
+ type BalancesQuery,
45
+ type BlockOptions,
55
46
  type CallInput,
56
47
  type CallResults,
57
48
  type ProviderConfig,
@@ -73,10 +64,12 @@ export {
73
64
  type TronWebLike,
74
65
  } from './tron.js'
75
66
  export { CallFailedError, decodeRevertReason, isExecutionError } from './errors.js'
76
- export { FallbackRpc, type FallbackOptions } from './fallback.js'
67
+ export { AllNodesFailedError, FallbackRpc, type FallbackNodeInfo, type FallbackOptions } from './fallback.js'
68
+ export { onRequest, type RequestEvent, type RequestListener } from './events.js'
69
+ export { watchBalances, type WatchBalancesOptions } from './watch.js'
77
70
  export { ChainCheckedProvider, getDefaultRpcUrls, isTronChain, type SourceOptions } from './source.js'
78
71
  export { DEFAULT_RPC_URLS, DEFAULT_TRON_HOSTS } from './rpcNodes.js'
79
72
  export { MULTICALL3_ADDRESS, getMulticall3, type Multicall } from './multicall.js'
80
- export type { BlockTag, CallOverrides, EthersLikeProvider } from './aggregate.js'
73
+ export type { BlockTag, CallOverrides, EthersLikeProvider, NativeBalanceMode } from './aggregate.js'
81
74
  export type { BatchOptions } from './batcher.js'
82
- export type { BoundCall, Call, FailableCall, Params, RawResult } from './call.js'
75
+ export type { BoundCall, Call, FailableCall, FailureReason, Params, RawResult, Settled } from './call.js'
package/src/multicall.ts CHANGED
@@ -47,12 +47,44 @@ const MULTICALL3: Record<number, Multicall> = {
47
47
  43114: { address: CANONICAL, block: 11907934 },
48
48
  80001: { address: CANONICAL, block: 25444704 },
49
49
  421611: { address: CANONICAL, block: 10228837 },
50
- 5000: { address: '0xd77b59d4cb13bea71f3cc093e401720867355d6e', block: 18877383 },
50
+ // Mantle:标准地址上的合约字节码与其他链不同,但 aggregate3 / getBlockNumber / getEthBalance 行为一致(2026-10 实测);
51
+ // ethcall 表里的 0xd77b…5d6e 调 aggregate3 会 revert
52
+ 5000: { address: CANONICAL, block: 304717 },
51
53
  1666600000: { address: CANONICAL, block: 24185753 },
52
54
  73927: { address: '0x138A85647768815078DF1dD85C6121e611381A0b', block: 14080843 },
53
55
  // Tron 主网 TEazPvZwDjDtFeJupyo7QunvnrnUjPH8ED(链上合约名 Multicall3,2026-10 实测)
54
56
  728126428: { address: '0x32a4f47a74a6810bd0bf861cabab99656a75de9e', block: 0 },
55
- 81457: { address: '0x23928c6f823e0d78eadc9d2f69ace652ff3cdcb1', block: 368182 },
57
+ // Blast:ethcall 表里的 0x2392…cdcb1 调 aggregate3 会 revert,标准地址可用(2026-10 实测)
58
+ 81457: { address: CANONICAL, block: 88189 },
59
+
60
+ // ---- 2026-10 实测补充:标准地址上 aggregate3 可用、区块号与节点一致 ----
61
+ // 部署区块查到的按实际填写;节点不提供历史状态(或忽略区块参数)查不到的,保守地填核实时的区块:
62
+ // 更早的历史查询走 deployless,最新状态照常用合约
63
+ 25: { address: CANONICAL, block: 98990812 }, // Cronos,部署区块未查到
64
+ 106: { address: CANONICAL, block: 70377223 }, // Velas,部署区块未查到
65
+ 130: { address: CANONICAL, block: 60854543 }, // Unichain,部署区块未查到
66
+ 143: { address: CANONICAL, block: 9248132 }, // Monad
67
+ 204: { address: CANONICAL, block: 193943883 }, // opBNB,部署区块未查到
68
+ 288: { address: CANONICAL, block: 40299030 }, // Boba,部署区块未查到
69
+ 321: { address: CANONICAL, block: 56352410 }, // KCC,部署区块未查到
70
+ 592: { address: CANONICAL, block: 761794 }, // Astar
71
+ 988: { address: CANONICAL, block: 42479473 }, // Stable,部署区块未查到
72
+ 999: { address: CANONICAL, block: 48135400 }, // HyperEVM,部署区块未查到
73
+ 1116: { address: CANONICAL, block: 6988931 }, // Core
74
+ 2818: { address: CANONICAL, block: 3654913 }, // Morph
75
+ 4663: { address: CANONICAL, block: 84683398 }, // Robinhood Chain,部署区块未查到
76
+ 4689: { address: CANONICAL, block: 53225909 }, // IoTeX,部署区块未查到
77
+ 9745: { address: CANONICAL, block: 0 }, // Plasma,创世预置
78
+ 34443: { address: CANONICAL, block: 2465882 }, // Mode
79
+ 57073: { address: CANONICAL, block: 58104502 }, // Ink,部署区块未查到
80
+ 59144: { address: CANONICAL, block: 42 }, // Linea
81
+ 80094: { address: CANONICAL, block: 0 }, // Berachain,创世预置
82
+ 534352: { address: CANONICAL, block: 14 }, // Scroll
83
+ 86233268: { address: CANONICAL, block: 10854614 }, // Winchain,部署区块未查到
84
+ // 以下两条链不支持 deployless(合约创建式 eth_call 返回空 / 格式不对),只能用 Multicall3;
85
+ // 早于部署区块的历史查询会失败
86
+ 42262: { address: CANONICAL, block: 22380155 }, // Oasis Emerald,部署区块未查到
87
+ 1313161554: { address: CANONICAL, block: 62907816 }, // Aurora
56
88
  }
57
89
 
58
90
  export function getMulticall3(chainId: number): Multicall | null {
package/src/nft.ts CHANGED
@@ -118,6 +118,7 @@ function expandUri(uri: string, tokenId: bigint, gateway?: string): string {
118
118
  return expanded
119
119
  }
120
120
 
121
+ /** 批量查 ERC721 持有人(ownerOf),可混合多个集合:`await nftOwners(multi, [{ contract: BAYC, tokenId: 1 }])` */
121
122
  export async function nftOwners(provider: Provider, items: readonly NftItem[], overrides?: CallOverrides): Promise<NftOwner[]> {
122
123
  // Tron 上返回 T 开头的地址,方便与 tronWeb.defaultAddress.base58 等直接比较
123
124
  const tron = isTronChain(await provider.getChainId())
@@ -132,6 +133,7 @@ export async function nftOwners(provider: Provider, items: readonly NftItem[], o
132
133
  })
133
134
  }
134
135
 
136
+ /** 批量查 ERC721 持有数量(balanceOf):`await nftBalances(multi, user, [BAYC, MAYC])` */
135
137
  export async function nftBalances(
136
138
  provider: Provider,
137
139
  owner: string,
@@ -146,6 +148,7 @@ export async function nftBalances(
146
148
  })
147
149
  }
148
150
 
151
+ /** 批量查 ERC1155 余额:`await erc1155Balances(multi, user, [{ contract, tokenId: 1 }])` */
149
152
  export async function erc1155Balances(
150
153
  provider: Provider,
151
154
  owner: string,
@@ -169,6 +172,7 @@ export async function erc1155Balances(
169
172
  })
170
173
  }
171
174
 
175
+ /** 批量查 NFT 元数据地址:兼容 ERC721 tokenURI 与 ERC1155 uri({id} 按规范替换),可转换 ipfs:// */
172
176
  export async function nftTokenUris(provider: Provider, items: readonly NftItem[], options: NftTokenUriOptions = {}): Promise<NftTokenUri[]> {
173
177
  const { ipfsGateway, ...overrides } = options
174
178
  const chainId = await provider.getChainId()
@@ -227,6 +231,7 @@ export async function nftTokenUris(provider: Provider, items: readonly NftItem[]
227
231
  })
228
232
  }
229
233
 
234
+ /** 批量查 NFT 集合信息(标准 / name / symbol / totalSupply),字段可选 */
230
235
  export async function nftCollections<F extends NftCollectionField = DefaultNftCollectionField>(
231
236
  provider: Provider,
232
237
  collections: readonly string[],