@ledgerhq/coin-evm 17.1.4 → 17.1.6

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 (48) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/errors.d.ts +13 -0
  3. package/lib/errors.d.ts.map +1 -1
  4. package/lib/errors.js +23 -1
  5. package/lib/errors.js.map +1 -1
  6. package/lib/logic/getBlock.d.ts.map +1 -1
  7. package/lib/logic/getBlock.js +5 -3
  8. package/lib/logic/getBlock.js.map +1 -1
  9. package/lib/logic/internalTransactionsFetcher.d.ts.map +1 -1
  10. package/lib/logic/internalTransactionsFetcher.js +11 -2
  11. package/lib/logic/internalTransactionsFetcher.js.map +1 -1
  12. package/lib/network/blockscoutV2.d.ts +4 -0
  13. package/lib/network/blockscoutV2.d.ts.map +1 -1
  14. package/lib/network/blockscoutV2.js +23 -10
  15. package/lib/network/blockscoutV2.js.map +1 -1
  16. package/lib/network/explorer/etherscan.js +1 -1
  17. package/lib/network/explorer/etherscan.js.map +1 -1
  18. package/lib/network/rewards.d.ts.map +1 -1
  19. package/lib/network/rewards.js +1 -2
  20. package/lib/network/rewards.js.map +1 -1
  21. package/lib-es/errors.d.ts +13 -0
  22. package/lib-es/errors.d.ts.map +1 -1
  23. package/lib-es/errors.js +20 -0
  24. package/lib-es/errors.js.map +1 -1
  25. package/lib-es/logic/getBlock.d.ts.map +1 -1
  26. package/lib-es/logic/getBlock.js +5 -3
  27. package/lib-es/logic/getBlock.js.map +1 -1
  28. package/lib-es/logic/internalTransactionsFetcher.d.ts.map +1 -1
  29. package/lib-es/logic/internalTransactionsFetcher.js +12 -3
  30. package/lib-es/logic/internalTransactionsFetcher.js.map +1 -1
  31. package/lib-es/network/blockscoutV2.d.ts +4 -0
  32. package/lib-es/network/blockscoutV2.d.ts.map +1 -1
  33. package/lib-es/network/blockscoutV2.js +24 -11
  34. package/lib-es/network/blockscoutV2.js.map +1 -1
  35. package/lib-es/network/explorer/etherscan.js +1 -1
  36. package/lib-es/network/explorer/etherscan.js.map +1 -1
  37. package/lib-es/network/rewards.d.ts.map +1 -1
  38. package/lib-es/network/rewards.js +1 -2
  39. package/lib-es/network/rewards.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/errors.ts +23 -0
  42. package/src/logic/getBlock.ts +7 -3
  43. package/src/logic/internalTransactionsFetcher.ts +11 -3
  44. package/src/logic/tests/internalTransactionsFetcher.test.ts +57 -2
  45. package/src/network/blockscoutV2.ts +32 -17
  46. package/src/network/explorer/etherscan.ts +1 -1
  47. package/src/network/rewards.ts +1 -2
  48. package/src/network/tests/blockscoutV2.test.ts +27 -0
@@ -1 +1 @@
1
- {"version":3,"file":"rewards.js","sourceRoot":"","sources":["../../src/network/rewards.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,sCAAsC;AAKtC,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAA;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAA;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAEnD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,MAAqB,EACrB,UAA8C,EAC9C,MAAc;IAEd,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAA;IACxB,IACE,UAAU,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,KAAK,QAAQ,IAAI,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC;QAChE,oBAAoB,CAAC,IAAI,CAAC,EAC1B,CAAC;QACD,IAAI,CAAC;YACH,MAAM,OAAO,CACX,MAAM,EACN,CAAC,GAAG,EAAE,EAAE,CACN,2BAA2B,CACzB,MAAM,CAAC,OAAO,EACd,UAAU,EACV,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,qBA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K,gBAAgB;gBAAE,MAAM,CAAC,CAAA;YAC9D,MAAM,CAAC,mBAAmB,EAAE,iCAAiC,EAAE,CAAC,CAAC,CAAA;QACnE,CAAC;IACH,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ledgerhq/coin-evm",
3
- "version": "17.1.4",
3
+ "version": "17.1.6",
4
4
  "description": "Ledger EVM Coin integration",
5
5
  "keywords": [
6
6
  "Ledger",
package/src/errors.ts CHANGED
@@ -158,6 +158,29 @@ export class SourceUnavailableError extends Error {
158
158
  }
159
159
  }
160
160
 
161
+ /**
162
+ * The explorer has not indexed the block yet: it lags behind the node. Reported as HTTP 503 so
163
+ * that the caller retries later. Not retried here.
164
+ */
165
+ export class BlockNotIndexedError extends Error {
166
+ override name = 'BlockNotIndexedError'
167
+ readonly statusCode = 503
168
+ constructor(height: number, options?: { cause?: unknown }) {
169
+ super(`Block ${height} is not indexed by the explorer yet, please retry later`)
170
+ if (options?.cause !== undefined) Object.assign(this, { cause: options.cause })
171
+ }
172
+ }
173
+
174
+ /** Matches on the error name, which holds across copies of the module (CommonJS and ESM builds). */
175
+ export function isBlockNotIndexedError(error: unknown): error is BlockNotIndexedError {
176
+ return (
177
+ typeof error === 'object' &&
178
+ error !== null &&
179
+ 'name' in error &&
180
+ error.name === 'BlockNotIndexedError'
181
+ )
182
+ }
183
+
161
184
  // GasTracker errors
162
185
  export class LedgerGasTrackerUsedIncorrectly extends Error {
163
186
  override name = 'LedgerGasTrackerUsedIncorrectly'
@@ -21,7 +21,6 @@ import type { Logger } from '@ledgerhq/coin-module-framework/config'
21
21
  import { promiseAllBatched } from '@ledgerhq/coin-module-framework/promises'
22
22
  import { rpcTransactionToBlockOperations } from '../adapters/blockOperations'
23
23
  import { CHAIN_ID, DEFAULT_INTERNAL_TX_SOURCES } from '../config'
24
- import { UnsupportedRpcMethodError } from '../errors'
25
24
  import { buildSmartContractDetails, safeEncodeEIP55 } from '../logic-public'
26
25
  import { getNodeApi } from '../network/node'
27
26
  import { detectEvmStakingOperationType } from '../staking/detectOperationType'
@@ -407,13 +406,18 @@ async function getTransactionsFromPrefetchedData(
407
406
  })
408
407
  )
409
408
  } catch (error) {
410
- if (!(error instanceof UnsupportedRpcMethodError) || error.method !== 'eth_getBlockReceipts')
409
+ if (
410
+ !(error instanceof Error) ||
411
+ error.name !== 'UnsupportedRpcMethodError' ||
412
+ !('method' in error) ||
413
+ error.method !== 'eth_getBlockReceipts'
414
+ )
411
415
  throw error
412
416
 
413
417
  logger('warn', 'EVM getBlock fallback: eth_getBlockReceipts unsupported', {
414
418
  currency: chainName,
415
419
  blockHeight,
416
- error: error.rawError,
420
+ error: 'rawError' in error ? error.rawError : undefined,
417
421
  })
418
422
  return null
419
423
  }
@@ -8,7 +8,7 @@ import type { BlockOperation } from '@ledgerhq/coin-module-framework/api/index'
8
8
  import type { Logger } from '@ledgerhq/coin-module-framework/config'
9
9
  import { traceBlockItemsToOperationsByHash } from '../adapters/blockOperations'
10
10
  import { internalTxsToOperationsByHash } from '../adapters/etherscan'
11
- import { SourceUnavailableError } from '../errors'
11
+ import { isBlockNotIndexedError, SourceUnavailableError } from '../errors'
12
12
  import { getInternalTransactionsByBlock as getBlockscoutV2InternalTransactionsByBlock } from '../network/blockscoutV2'
13
13
  import { getInternalTransactionsByBlock } from '../network/explorer/etherscan'
14
14
  import {
@@ -37,10 +37,16 @@ function throwCollectedFailures(failures: readonly SourceFailure[]): never {
37
37
  if (failures.length === 1 && first !== undefined) {
38
38
  throw first.error
39
39
  }
40
- throw new AggregateError(
40
+ const aggregate = new AggregateError(
41
41
  failures.map(({ error }) => error),
42
42
  `internal tx sources failed: ${describeFailures(failures)}`
43
43
  )
44
+ // The block can be read once the explorer has indexed it: keep the retryable status (503).
45
+ const notIndexed = failures.map(({ error }) => error).find(isBlockNotIndexedError)
46
+ if (notIndexed !== undefined) {
47
+ Object.assign(aggregate, { statusCode: notIndexed.statusCode })
48
+ }
49
+ throw aggregate
44
50
  }
45
51
 
46
52
  /**
@@ -53,7 +59,7 @@ function recordFailure(
53
59
  source: InternalTxSource,
54
60
  error: unknown
55
61
  ): boolean {
56
- if (!(error instanceof SourceUnavailableError)) {
62
+ if (!(error instanceof Error) || error.name !== 'SourceUnavailableError') {
57
63
  failures.push({ source, error })
58
64
  return true
59
65
  }
@@ -166,6 +172,8 @@ export function makeSourceFetchers(
166
172
  return getByBlock(config, height)
167
173
  .then((txs) => internalTxsToOperationsByHash(txs, logger))
168
174
  .catch((error) => {
175
+ // A real error, kept as is: its HTTP status (503) tells the caller to retry later.
176
+ if (isBlockNotIndexedError(error)) throw error
169
177
  logger('coin-evm', 'debug: explorer internal txs failed, falling through', {
170
178
  currency: config.name,
171
179
  blockHeight: height,
@@ -3,8 +3,8 @@
3
3
 
4
4
  import type { SourceFetcher } from '../internalTransactionsFetcher'
5
5
  import type { BlockOperation } from '@ledgerhq/coin-module-framework/api/index'
6
- import { internalTxSourcesFromList } from '../../config'
7
- import { SourceUnavailableError } from '../../errors'
6
+ import { DEFAULT_INTERNAL_TX_SOURCES, internalTxSourcesFromList } from '../../config'
7
+ import { BlockNotIndexedError, SourceUnavailableError } from '../../errors'
8
8
  import {
9
9
  createMockEvmConfigInfo,
10
10
  mkEtherscanExplorer,
@@ -113,6 +113,48 @@ describe('composeInternalTxsFetcher', () => {
113
113
  await expect(fetch(height)).rejects.toThrow(traceError)
114
114
  })
115
115
 
116
+ it('propagates a block not indexed yet as is, with its retryable status', async () => {
117
+ const notIndexed = new BlockNotIndexedError(height)
118
+ const fetch = composeInternalTxsFetcher(
119
+ ['explorer', 'empty'],
120
+ makeFetchers({ explorer: jest.fn().mockRejectedValue(notIndexed) })
121
+ )
122
+
123
+ await expect(fetch(height)).rejects.toBe(notIndexed)
124
+ expect(notIndexed.statusCode).toBe(503)
125
+ })
126
+
127
+ it('keeps the retryable status of a block not indexed yet when later sources also fail', async () => {
128
+ const fetch = composeInternalTxsFetcher(
129
+ DEFAULT_INTERNAL_TX_SOURCES,
130
+ makeFetchers({
131
+ explorer: jest.fn().mockRejectedValue(new BlockNotIndexedError(height)),
132
+ trace_block: jest.fn().mockRejectedValue(new Error('trace down')),
133
+ debug_traceBlockByNumber: jest.fn().mockRejectedValue(new Error('debug down')),
134
+ })
135
+ )
136
+
137
+ await expect(fetch(height)).rejects.toMatchObject({
138
+ name: 'AggregateError',
139
+ statusCode: 503,
140
+ message: expect.stringContaining(`[explorer] Block ${height} is not indexed`),
141
+ })
142
+ })
143
+
144
+ it('reports other collected failures without a status', async () => {
145
+ const fetch = composeInternalTxsFetcher(
146
+ DEFAULT_INTERNAL_TX_SOURCES,
147
+ makeFetchers({
148
+ trace_block: jest.fn().mockRejectedValue(new Error('trace down')),
149
+ debug_traceBlockByNumber: jest.fn().mockRejectedValue(new Error('debug down')),
150
+ })
151
+ )
152
+
153
+ const error: unknown = await fetch(height).catch((e: unknown) => e)
154
+ expect(error).toBeInstanceOf(AggregateError)
155
+ expect(error).not.toHaveProperty('statusCode')
156
+ })
157
+
116
158
  it('propagates collected real errors when empty is not configured', async () => {
117
159
  const explorerError = new Error('explorer down')
118
160
  const traceError = new Error('trace down')
@@ -320,6 +362,19 @@ describe('makeSourceFetchers', () => {
320
362
  })
321
363
  })
322
364
 
365
+ it('passes a block not indexed yet by Blockscout v2 through, so that its status is kept', async () => {
366
+ const config = createMockEvmConfigInfo({
367
+ chainId: 534352,
368
+ node: mkExternalNode(),
369
+ explorer: { type: 'blockscout-v2', uri: 'https://blockscout.example/api/v2' },
370
+ })
371
+ const notIndexed = new BlockNotIndexedError(99)
372
+ jest.mocked(getBlockscoutV2InternalTransactionsByBlock).mockRejectedValueOnce(notIndexed)
373
+
374
+ const fetchers = makeSourceFetchers(config, mockNodeApi(), testLogger)
375
+ await expect(fetchers.explorer(99)).rejects.toBe(notIndexed)
376
+ })
377
+
323
378
  it('empty always resolves to an empty map', async () => {
324
379
  const config = createMockEvmConfigInfo({ chainId: 1, node: mkExternalNode() })
325
380
 
@@ -25,7 +25,7 @@ import {
25
25
  blockscoutV2InternalTransactionsToOperations,
26
26
  blockscoutV2TransactionToOperations,
27
27
  } from '../adapters'
28
- import { InvalidExplorerResponse, RateLimitError } from '../errors'
28
+ import { BlockNotIndexedError, InvalidExplorerResponse, RateLimitError } from '../errors'
29
29
  import { isBlockscoutV2ExplorerConfig, NO_TOKEN } from './explorer/types'
30
30
  import { getNodeApi } from './node'
31
31
  import { enrichRewardOperations } from './rewards'
@@ -194,6 +194,10 @@ const INTERNAL_TRANSACTIONS = (address: string): Stream => ({
194
194
  /**
195
195
  * Get all the internal transactions of a block, for the `explorer` internal transaction source of
196
196
  * `getBlock`. Not retried: `getBlock` falls back to the next source on failure.
197
+ *
198
+ * Blockscout answers 404 for a block that it has not indexed yet (it lags behind the node by up
199
+ * to about a minute), and an empty list for an indexed block without internal transactions. The
200
+ * 404 is reported as a {@link BlockNotIndexedError}, for the caller to retry later.
197
201
  */
198
202
  export async function getInternalTransactionsByBlock(
199
203
  config: EvmConfigInfo,
@@ -203,22 +207,29 @@ export async function getInternalTransactionsByBlock(
203
207
  if (!isBlockscoutV2ExplorerConfig(explorer)) return []
204
208
 
205
209
  const internalTransactions: EtherscanInternalTransaction[] = []
206
- await walkStream<BlockscoutV2InternalTransaction>(
207
- explorer.uri,
208
- {
209
- path: `/blocks/${blockHeight}/internal-transactions`,
210
- params: {},
211
- // Only ever read from the first page
212
- seed: (): PageParams => ({}),
213
- },
214
- blockHeight,
215
- undefined,
216
- 0,
217
- (internalTx) => {
218
- internalTransactions.push(blockscoutV2InternalTransactionToEtherscan(internalTx))
219
- return true
210
+ try {
211
+ await walkStream<BlockscoutV2InternalTransaction>(
212
+ explorer.uri,
213
+ {
214
+ path: `/blocks/${blockHeight}/internal-transactions`,
215
+ params: {},
216
+ // Only ever read from the first page
217
+ seed: (): PageParams => ({}),
218
+ },
219
+ blockHeight,
220
+ undefined,
221
+ 0,
222
+ (internalTx) => {
223
+ internalTransactions.push(blockscoutV2InternalTransactionToEtherscan(internalTx))
224
+ return true
225
+ }
226
+ )
227
+ } catch (e) {
228
+ if (isAxiosError(e) && e.response?.status === 404) {
229
+ throw new BlockNotIndexedError(blockHeight, { cause: e })
220
230
  }
221
- )
231
+ throw e
232
+ }
222
233
  return internalTransactions
223
234
  }
224
235
 
@@ -390,7 +401,11 @@ export const getOperations = makeLRUCache<
390
401
  nextPagingToken,
391
402
  }
392
403
  } catch (err) {
393
- if (err instanceof RateLimitError || err instanceof InvalidParameterError) throw err
404
+ if (
405
+ err instanceof Error &&
406
+ (err.name === 'RateLimitError' || err.name === 'InvalidParameterError')
407
+ )
408
+ throw err
394
409
  logger('EVM getOperations', 'Error while fetching data from Blockscout v2 API', err)
395
410
  const message = err instanceof Error ? `${err.name} - ${err.message}` : String(err)
396
411
  throw new InvalidExplorerResponse(
@@ -919,7 +919,7 @@ export const getOperations = makeLRUCache<
919
919
  }),
920
920
  }
921
921
  } catch (err) {
922
- if (err instanceof RateLimitError) throw err
922
+ if (err instanceof Error && err.name === 'RateLimitError') throw err
923
923
  logger('EVM getOperations', 'Error while fetching data from Etherscan like API', err)
924
924
  const message =
925
925
  typeof err === 'string'
@@ -4,7 +4,6 @@
4
4
  import type { EvmConfigInfo } from '../config'
5
5
  import type { MemoNotSupported, Operation } from '@ledgerhq/coin-module-framework/api/types'
6
6
  import type { Logger } from '@ledgerhq/coin-module-framework/config'
7
- import { RateLimitError } from '../errors'
8
7
  import { enrichRewardOperationsValue } from '../staking/rewardsFromReceipt'
9
8
  import { withApi } from './node/rpc.common'
10
9
  import { isExternalNodeConfig } from './node/types'
@@ -40,7 +39,7 @@ export async function enrichRewardOperations(
40
39
  } catch (e) {
41
40
  // Enrichment is best-effort, but a rate limit must not be downgraded into a successful
42
41
  // response reporting 0-value rewards.
43
- if (e instanceof RateLimitError) throw e
42
+ if (e instanceof Error && e.name === 'RateLimitError') throw e
44
43
  logger('EVM getOperations', 'reward amount enrichment failed', e)
45
44
  }
46
45
  }
@@ -528,6 +528,33 @@ describe('blockscout-v2 explorer', () => {
528
528
  ).rejects.toThrow('upstream error')
529
529
  expect(spy).toHaveBeenCalledTimes(1)
530
530
  })
531
+
532
+ // Blockscout answers 404 for a block it has not indexed yet, and an empty list for an indexed
533
+ // block without internal transactions.
534
+ it('reports a 404 as a block not indexed yet, retryable by the caller, without retrying', async () => {
535
+ const spy = jest.spyOn(axios, 'request').mockRejectedValue(
536
+ Object.assign(new Error('Request failed with status code 404'), {
537
+ isAxiosError: true,
538
+ response: { status: 404, data: { message: 'Not found' } },
539
+ })
540
+ )
541
+
542
+ await expect(
543
+ getInternalTransactionsByBlock(
544
+ { ...config, explorer: { type: 'blockscout-v2', uri, retries: 3 } },
545
+ 99
546
+ )
547
+ ).rejects.toMatchObject({ name: 'BlockNotIndexedError', statusCode: 503 })
548
+ expect(spy).toHaveBeenCalledTimes(1)
549
+ })
550
+
551
+ it('reads an indexed block without internal transactions as an empty list', async () => {
552
+ jest
553
+ .spyOn(axios, 'request')
554
+ .mockResolvedValueOnce({ data: { items: [], next_page_params: null } })
555
+
556
+ await expect(getInternalTransactionsByBlock(config, 99)).resolves.toEqual([])
557
+ })
531
558
  })
532
559
 
533
560
  describe('discoverTokenAssets', () => {