@ledgerhq/coin-evm 5.3.4 → 5.3.9

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 (97) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/lib/adapters/etherscan.d.ts.map +1 -1
  3. package/lib/adapters/etherscan.js +2 -1
  4. package/lib/adapters/etherscan.js.map +1 -1
  5. package/lib/config.d.ts +4 -0
  6. package/lib/config.d.ts.map +1 -1
  7. package/lib/config.js.map +1 -1
  8. package/lib/errors.d.ts +6 -0
  9. package/lib/errors.d.ts.map +1 -1
  10. package/lib/errors.js +12 -1
  11. package/lib/errors.js.map +1 -1
  12. package/lib/logic/getBlock.js +2 -2
  13. package/lib/logic/getBlock.js.map +1 -1
  14. package/lib/network/explorer/etherscan.d.ts.map +1 -1
  15. package/lib/network/explorer/etherscan.js +38 -24
  16. package/lib/network/explorer/etherscan.js.map +1 -1
  17. package/lib/network/explorer/ledger.d.ts.map +1 -1
  18. package/lib/network/explorer/ledger.js +6 -4
  19. package/lib/network/explorer/ledger.js.map +1 -1
  20. package/lib/network/node/rpc.common.d.ts.map +1 -1
  21. package/lib/network/node/rpc.common.js +30 -6
  22. package/lib/network/node/rpc.common.js.map +1 -1
  23. package/lib/network/node/types.d.ts +3 -1
  24. package/lib/network/node/types.d.ts.map +1 -1
  25. package/lib/network/node/types.js.map +1 -1
  26. package/lib/network/withRetries.d.ts.map +1 -1
  27. package/lib/network/withRetries.js +13 -0
  28. package/lib/network/withRetries.js.map +1 -1
  29. package/lib/types/etherscan.d.ts +2 -0
  30. package/lib/types/etherscan.d.ts.map +1 -1
  31. package/lib/utils.d.ts +0 -2
  32. package/lib/utils.d.ts.map +1 -1
  33. package/lib/utils.js +0 -30
  34. package/lib/utils.js.map +1 -1
  35. package/lib-es/adapters/etherscan.d.ts.map +1 -1
  36. package/lib-es/adapters/etherscan.js +2 -1
  37. package/lib-es/adapters/etherscan.js.map +1 -1
  38. package/lib-es/config.d.ts +4 -0
  39. package/lib-es/config.d.ts.map +1 -1
  40. package/lib-es/config.js.map +1 -1
  41. package/lib-es/errors.d.ts +6 -0
  42. package/lib-es/errors.d.ts.map +1 -1
  43. package/lib-es/errors.js +10 -0
  44. package/lib-es/errors.js.map +1 -1
  45. package/lib-es/logic/getBlock.js +2 -2
  46. package/lib-es/logic/getBlock.js.map +1 -1
  47. package/lib-es/network/explorer/etherscan.d.ts.map +1 -1
  48. package/lib-es/network/explorer/etherscan.js +39 -25
  49. package/lib-es/network/explorer/etherscan.js.map +1 -1
  50. package/lib-es/network/explorer/ledger.d.ts.map +1 -1
  51. package/lib-es/network/explorer/ledger.js +7 -5
  52. package/lib-es/network/explorer/ledger.js.map +1 -1
  53. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  54. package/lib-es/network/node/rpc.common.js +30 -6
  55. package/lib-es/network/node/rpc.common.js.map +1 -1
  56. package/lib-es/network/node/types.d.ts +3 -1
  57. package/lib-es/network/node/types.d.ts.map +1 -1
  58. package/lib-es/network/node/types.js.map +1 -1
  59. package/lib-es/network/withRetries.d.ts.map +1 -1
  60. package/lib-es/network/withRetries.js +10 -0
  61. package/lib-es/network/withRetries.js.map +1 -1
  62. package/lib-es/types/etherscan.d.ts +2 -0
  63. package/lib-es/types/etherscan.d.ts.map +1 -1
  64. package/lib-es/utils.d.ts +0 -2
  65. package/lib-es/utils.d.ts.map +1 -1
  66. package/lib-es/utils.js +0 -28
  67. package/lib-es/utils.js.map +1 -1
  68. package/package.json +1 -1
  69. package/src/adapters/etherscan.test.ts +67 -0
  70. package/src/adapters/etherscan.ts +3 -1
  71. package/src/api/getBlock.integ.test.ts +1 -1
  72. package/src/api/index.avalanche_c_chain_fuji.integ.test.ts +1 -1
  73. package/src/api/index.integ.test.ts +7 -12
  74. package/src/api/index.linea.integ.test.ts +1 -1
  75. package/src/api/index.monad_testnet.integ.test.ts +1 -1
  76. package/src/api/index.optimism.integ.test.ts +30 -1
  77. package/src/api/index.rsk.integ.test.ts +1 -1
  78. package/src/api/index.shape.integ.test.ts +1 -1
  79. package/src/api/index.somnia.integ.test.ts +40 -0
  80. package/src/api/index.zksync.integ.test.ts +42 -0
  81. package/src/config.ts +4 -0
  82. package/src/errors.ts +10 -0
  83. package/src/logic/getBlock.test.ts +49 -0
  84. package/src/logic/getBlock.ts +3 -2
  85. package/src/network/explorer/etherscan.test.ts +407 -91
  86. package/src/network/explorer/etherscan.ts +69 -33
  87. package/src/network/explorer/ledger.test.ts +24 -13
  88. package/src/network/explorer/ledger.ts +27 -22
  89. package/src/network/node/rpc.common.ts +35 -6
  90. package/src/network/node/rpc.test.ts +73 -0
  91. package/src/network/node/types.ts +10 -1
  92. package/src/network/withRetries.test.ts +63 -0
  93. package/src/network/withRetries.ts +12 -0
  94. package/src/staking/validators.integ.test.ts +1 -1
  95. package/src/types/etherscan.ts +2 -0
  96. package/src/utils.test.ts +0 -86
  97. package/src/utils.ts +0 -41
@@ -28,10 +28,10 @@ import {
28
28
  import {
29
29
  EtherscanAPIError,
30
30
  EtherscanLikeExplorerUsedIncorrectly,
31
+ RateLimitError,
31
32
  InvalidExplorerResponse,
32
33
  } from '../../errors'
33
34
  import { enrichRewardOperationsValue } from '../../staking/rewardsFromReceipt'
34
- import { nftDisabled } from '../../utils'
35
35
  import { withApi } from '../node/rpc.common'
36
36
  import { isExternalNodeConfig } from '../node/types'
37
37
  import { isEtherscanLikeExplorerConfig } from './types'
@@ -119,6 +119,9 @@ export async function fetchWithRetries<T>(
119
119
 
120
120
  return data.result
121
121
  } catch (e) {
122
+ if (axios.isAxiosError(e) && e.response?.status === 429) {
123
+ throw new RateLimitError()
124
+ }
122
125
  if (retries) {
123
126
  // wait the API timeout before trying again
124
127
  await delay(ETHERSCAN_TIMEOUT)
@@ -277,11 +280,10 @@ export const getCoinOperations = async (params: FetchOperationsParams): Promise<
277
280
  ? `${explorer.uri}/accounts/list_of_txs_by_address/${params.address}`
278
281
  : `${explorer.uri}?module=account&action=txlist&address=${params.address}`
279
282
 
280
- const raw = await fetchWithRetries<EtherscanOperation[] | null | string>({
281
- method: 'GET',
282
- url,
283
- params: paginationParams(params),
284
- })
283
+ const raw = await fetchWithRetries<EtherscanOperation[] | null | string>(
284
+ { method: 'GET', url, params: paginationParams(params) },
285
+ explorer.retries ?? DEFAULT_RETRIES_API
286
+ )
285
287
  const ops = Array.isArray(raw) ? raw : []
286
288
 
287
289
  const operations = ops.flatMap((tx) =>
@@ -306,6 +308,9 @@ export const getCoinOperations = async (params: FetchOperationsParams): Promise<
306
308
  node
307
309
  )
308
310
  } catch (e) {
311
+ // Enrichment is best-effort, but a rate limit must not be downgraded into a successful
312
+ // response reporting 0-value rewards.
313
+ if (e instanceof RateLimitError) throw e
309
314
  log('EVM getOperations', 'reward amount enrichment failed', e)
310
315
  }
311
316
  }
@@ -337,11 +342,10 @@ export const getTokenOperations = async (
337
342
  ? `${explorer.uri}/accounts/list_of_erc20_transfer_events_by_address/${params.address}`
338
343
  : `${explorer.uri}?module=account&action=tokentx&address=${params.address}`
339
344
 
340
- const raw = await fetchWithRetries<EtherscanERC20Event[] | null | string>({
341
- method: 'GET',
342
- url,
343
- params: paginationParams(params),
344
- })
345
+ const raw = await fetchWithRetries<EtherscanERC20Event[] | null | string>(
346
+ { method: 'GET', url, params: paginationParams(params) },
347
+ explorer.retries ?? DEFAULT_RETRIES_API
348
+ )
345
349
  const ops = Array.isArray(raw) ? raw : []
346
350
 
347
351
  // Drop ERC20 Transfer events on contracts that mirror the native asset
@@ -392,11 +396,10 @@ export const getERC721Operations = async (
392
396
  ? `${explorer.uri}/accounts/list_of_erc721_transfer_events_by_address/${params.address}`
393
397
  : `${explorer.uri}?module=account&action=tokennfttx&address=${params.address}`
394
398
 
395
- const raw = await fetchWithRetries<EtherscanERC721Event[] | null | string>({
396
- method: 'GET',
397
- url,
398
- params: paginationParams(params),
399
- })
399
+ const raw = await fetchWithRetries<EtherscanERC721Event[] | null | string>(
400
+ { method: 'GET', url, params: paginationParams(params) },
401
+ explorer.retries ?? DEFAULT_RETRIES_API
402
+ )
400
403
  const ops = Array.isArray(raw) ? raw : []
401
404
 
402
405
  // Why this thing ?
@@ -440,11 +443,14 @@ export const getERC1155Operations = async (
440
443
  return EMPTY_RESULT
441
444
  }
442
445
 
443
- const raw = await fetchWithRetries<EtherscanERC1155Event[] | null | string>({
444
- method: 'GET',
445
- url: `${explorer.uri}?module=account&action=token1155tx&address=${params.address}`,
446
- params: paginationParams(params),
447
- })
446
+ const raw = await fetchWithRetries<EtherscanERC1155Event[] | null | string>(
447
+ {
448
+ method: 'GET',
449
+ url: `${explorer.uri}?module=account&action=token1155tx&address=${params.address}`,
450
+ params: paginationParams(params),
451
+ },
452
+ explorer.retries ?? DEFAULT_RETRIES_API
453
+ )
448
454
  const ops = Array.isArray(raw) ? raw : []
449
455
 
450
456
  // Why this thing ?
@@ -529,11 +535,14 @@ export const getInternalOperations = async (
529
535
  }
530
536
 
531
537
  // Some explorers (e.g. Monad Testnet) return null instead of [] for empty results.
532
- const ops = await fetchWithRetries<EtherscanInternalTransaction[] | null>({
533
- method: 'GET',
534
- url: `${explorer.uri}?module=account&action=txlistinternal&address=${params.address}`,
535
- params: paginationParams(params),
536
- }).then((ops) => (ops ?? []).map(fixTxHash))
538
+ const ops = await fetchWithRetries<EtherscanInternalTransaction[] | null>(
539
+ {
540
+ method: 'GET',
541
+ url: `${explorer.uri}?module=account&action=txlistinternal&address=${params.address}`,
542
+ params: paginationParams(params),
543
+ },
544
+ explorer.retries ?? DEFAULT_RETRIES_API
545
+ ).then((ops) => (ops ?? []).map(fixTxHash))
537
546
 
538
547
  // Why this thing ?
539
548
  // Multiple internal transactions can be executed from
@@ -767,9 +776,20 @@ export const getOperations = makeLRUCache<
767
776
  endpoint: FetchOperations,
768
777
  boundBlock: number | undefined,
769
778
  isDone: boolean | undefined
770
- ): Promise<{ result: EndpointResult; effectiveBoundBlock: number | undefined }> {
779
+ ): Promise<{
780
+ result: EndpointResult
781
+ effectiveBoundBlock: number | undefined
782
+ // True when the endpoint's block range was narrowed by a prior endpoint's bound.
783
+ // An isDone=true result in this case means "no more data in the constrained window",
784
+ // NOT "globally done" — more data may exist beyond the window.
785
+ wasConstrainedByBoundBlock: boolean
786
+ }> {
771
787
  if (isDone) {
772
- return { result: EMPTY_RESULT, effectiveBoundBlock: boundBlock }
788
+ return {
789
+ result: EMPTY_RESULT,
790
+ effectiveBoundBlock: boundBlock,
791
+ wasConstrainedByBoundBlock: false,
792
+ }
773
793
  }
774
794
  // in asc mode, the cursor is the toBlock
775
795
  // in desc mode the cursor is the fromBlock
@@ -790,7 +810,19 @@ export const getOperations = makeLRUCache<
790
810
  result,
791
811
  cmp
792
812
  )
793
- return { result: result, effectiveBoundBlock: effectiveBoundBlock }
813
+ // The endpoint was "additionally constrained" only when boundBlock tightens the range
814
+ // beyond what the user already specified:
815
+ // asc: boundBlock sets effectiveToBlock — tighter when boundBlock < user's toBlock (or toBlock=∞)
816
+ // desc: boundBlock sets effectiveFromBlock — tighter when boundBlock > user's fromBlock
817
+ const wasConstrainedByBoundBlock =
818
+ order === 'asc'
819
+ ? boundBlock !== undefined && (toBlock === undefined || boundBlock < toBlock)
820
+ : boundBlock !== undefined && boundBlock > fromBlock
821
+ return {
822
+ result: result,
823
+ effectiveBoundBlock: effectiveBoundBlock,
824
+ wasConstrainedByBoundBlock,
825
+ }
794
826
  }
795
827
 
796
828
  // endpoint calls are sorted by likelihood of having more operations than the next
@@ -814,7 +846,7 @@ export const getOperations = makeLRUCache<
814
846
  const nfts = await callEndpoint(
815
847
  getNftOperations,
816
848
  tokens.effectiveBoundBlock,
817
- nftUnsupported || nftDisabled(currencyId) || pagingState?.nftIsDone
849
+ nftUnsupported || pagingState?.nftIsDone
818
850
  )
819
851
 
820
852
  const effectiveBoundBlock = nfts.effectiveBoundBlock
@@ -846,12 +878,16 @@ export const getOperations = makeLRUCache<
846
878
  lastInternalOperations: internalsResult.operations,
847
879
  nextPagingToken: serializePagingToken(nextBoundBlock, {
848
880
  coinIsDone: coinsResult.isDone,
849
- internalIsDone: internalsResult.isDone,
850
- tokenIsDone: tokensResult.isDone,
851
- nftIsDone: nftsResult.isDone,
881
+ // An endpoint constrained by a prior endpoint's bound block is only locally done
882
+ // (no more data in the constrained window). It must be re-queried on the next page
883
+ // because more data may exist beyond that window.
884
+ internalIsDone: internalsResult.isDone && !internals.wasConstrainedByBoundBlock,
885
+ tokenIsDone: tokensResult.isDone && !tokens.wasConstrainedByBoundBlock,
886
+ nftIsDone: nftsResult.isDone && !nfts.wasConstrainedByBoundBlock,
852
887
  }),
853
888
  }
854
889
  } catch (err) {
890
+ if (err instanceof RateLimitError) throw err
855
891
  log('EVM getOperations', 'Error while fetching data from Etherscan like API', err)
856
892
  const message =
857
893
  typeof err === 'string'
@@ -7,7 +7,7 @@ import { delay } from '@ledgerhq/coin-module-framework/promises'
7
7
  import axios from 'axios'
8
8
  import eip55 from 'eip55'
9
9
  import { DEFAULT_LEDGER_EXPLORER_URI, getCoinConfig } from '../../config'
10
- import { LedgerExplorerUsedIncorrectly } from '../../errors'
10
+ import { LedgerExplorerUsedIncorrectly, RateLimitError } from '../../errors'
11
11
  import {
12
12
  createMockEvmCoinConfig,
13
13
  mkExternalNode,
@@ -94,6 +94,29 @@ describe('EVM Family', () => {
94
94
  }
95
95
  })
96
96
 
97
+ it('should surface a 429 as a RateLimitError without retrying', async () => {
98
+ const rateLimitError = Object.assign(new Error('Request failed with status code 429'), {
99
+ isAxiosError: true,
100
+ response: { status: 429 },
101
+ })
102
+ // axios is fully mocked - restore isAxiosError to its real behaviour for this test
103
+ jest
104
+ .spyOn(axios, 'isAxiosError')
105
+ .mockImplementation(
106
+ (e: unknown): boolean => typeof e === 'object' && e !== null && 'isAxiosError' in e
107
+ )
108
+ const spy = jest.spyOn(axios, 'request').mockRejectedValue(rateLimitError)
109
+
110
+ await expect(
111
+ LEDGER_API.fetchPaginatedOpsWithRetries(
112
+ { explorerId: 'test', address: '0x', fromBlock: 0, batchSize: 10 },
113
+ null
114
+ )
115
+ ).rejects.toBeInstanceOf(RateLimitError)
116
+ // a rate limit is not transient: it must not consume the retry budget
117
+ expect(spy).toHaveBeenCalledTimes(1)
118
+ })
119
+
97
120
  it('should recursively fetch paginated data', async () => {
98
121
  jest.spyOn(axios, 'request').mockImplementation(async ({ params }) => {
99
122
  switch (params.token) {
@@ -176,10 +199,6 @@ describe('EVM Family', () => {
176
199
  })
177
200
 
178
201
  describe('getOperations', () => {
179
- beforeEach(() => {
180
- process.env.NFT_CURRENCIES = JSON.stringify([])
181
- })
182
-
183
202
  it('should throw if the explorer is misconfigured', async () => {
184
203
  mockGetConfig.mockImplementationOnce(() =>
185
204
  createMockEvmCoinConfig({ chainId: 1, node: mkExternalNode({ uri: 'anything' }) })
@@ -232,8 +251,6 @@ describe('EVM Family', () => {
232
251
  })
233
252
 
234
253
  it('should return the different operation types', async () => {
235
- process.env.NFT_CURRENCIES = JSON.stringify(['ethereum'])
236
-
237
254
  jest.spyOn(axios, 'request').mockImplementation(async () => ({
238
255
  data: { data: [coinOperation1, coinOperation2, coinOperation3, coinOperation4] },
239
256
  }))
@@ -474,12 +491,6 @@ describe('EVM Family', () => {
474
491
  jest.spyOn(axios, 'request').mockImplementation(async () => ({
475
492
  data: { data: [coinOperation1, coinOperation2, coinOperation3, coinOperation4] },
476
493
  }))
477
-
478
- process.env.NFT_CURRENCIES = JSON.stringify(['ethereum'])
479
- })
480
-
481
- afterAll(() => {
482
- process.env.NFT_CURRENCIES = JSON.stringify([])
483
494
  })
484
495
 
485
496
  const mockConfigWithTokens = (supportedTokens: NftStandard[]) =>
@@ -14,8 +14,7 @@ import {
14
14
  ledgerOperationToOperations,
15
15
  } from '../../adapters/index'
16
16
  import { DEFAULT_LEDGER_EXPLORER_URI } from '../../config'
17
- import { LedgerExplorerUsedIncorrectly } from '../../errors'
18
- import { nftEnabled } from '../../utils'
17
+ import { LedgerExplorerUsedIncorrectly, RateLimitError } from '../../errors'
19
18
  import { isLedgerExplorerConfig, NO_TOKEN } from './types'
20
19
 
21
20
  export const DEFAULT_BATCH_SIZE = 10_000
@@ -75,6 +74,9 @@ export async function fetchPaginatedOpsWithRetries(
75
74
  (a, b) => new Date(b.block.time).getTime() - new Date(a.block.time).getTime()
76
75
  )
77
76
  } catch (e) {
77
+ if (axios.isAxiosError(e) && e.response?.status === 429) {
78
+ throw new RateLimitError()
79
+ }
78
80
  if (retries) {
79
81
  // wait the API timeout before trying again
80
82
  await delay(LEDGER_TIMEOUT)
@@ -105,14 +107,19 @@ export const getOperations: ExplorerApi['getOperations'] = async (
105
107
  )
106
108
  }
107
109
 
108
- const ledgerExplorerOps = await fetchPaginatedOpsWithRetries({
109
- explorerUri: config.ledgerExplorerUri,
110
- clientVersion: config.ledgerClientVersion,
111
- explorerId: explorer.explorerId,
112
- address,
113
- fromBlock,
114
- batchSize: explorer.batchSize ?? DEFAULT_BATCH_SIZE,
115
- })
110
+ const ledgerExplorerOps = await fetchPaginatedOpsWithRetries(
111
+ {
112
+ explorerUri: config.ledgerExplorerUri,
113
+ clientVersion: config.ledgerClientVersion,
114
+ explorerId: explorer.explorerId,
115
+ address,
116
+ fromBlock,
117
+ batchSize: explorer.batchSize ?? DEFAULT_BATCH_SIZE,
118
+ },
119
+ null,
120
+ [],
121
+ explorer.retries ?? DEFAULT_RETRIES_API
122
+ )
116
123
 
117
124
  const lastCoinOperations: Array<Operation<MemoNotSupported>> = []
118
125
  const lastTokenOperations: Array<Operation<MemoNotSupported>> = []
@@ -135,18 +142,16 @@ export const getOperations: ExplorerApi['getOperations'] = async (
135
142
  const erc20Ops = erc20TransferEvents.flatMap((event, index) =>
136
143
  ledgerERC20EventToOperations(address, coinOps[0], event, index)
137
144
  )
138
- const erc721Ops =
139
- nftEnabled(currencyId) && config.supportedTokens?.includes('erc721')
140
- ? ledgerOp.erc721_transfer_events.flatMap((event, index) =>
141
- ledgerERC721EventToOperations(address, coinOps[0], event, index)
142
- )
143
- : []
144
- const erc1155Ops =
145
- nftEnabled(currencyId) && config.supportedTokens?.includes('erc1155')
146
- ? ledgerOp.erc1155_transfer_events.flatMap((event, index) =>
147
- ledgerERC1155EventToOperations(address, coinOps[0], event, index)
148
- )
149
- : []
145
+ const erc721Ops = config.supportedTokens?.includes('erc721')
146
+ ? ledgerOp.erc721_transfer_events.flatMap((event, index) =>
147
+ ledgerERC721EventToOperations(address, coinOps[0], event, index)
148
+ )
149
+ : []
150
+ const erc1155Ops = config.supportedTokens?.includes('erc1155')
151
+ ? ledgerOp.erc1155_transfer_events.flatMap((event, index) =>
152
+ ledgerERC1155EventToOperations(address, coinOps[0], event, index)
153
+ )
154
+ : []
150
155
  const internalOps = ledgerOp.actions.flatMap((action, index) =>
151
156
  ledgerInternalTransactionToOperations(address, coinOps[0], action, index)
152
157
  )
@@ -223,37 +223,63 @@ export async function withApi<T>(
223
223
  )
224
224
  }
225
225
 
226
+ /**
227
+ * Read the L1 data/security fee from a raw RPC receipt, normalized to a decimal string.
228
+ *
229
+ * Only OP-stack chains (Optimism, Base, Blast, …) report it; it is a non-standard field, so it is read off the raw
230
+ * record rather than the typed receipt.
231
+ *
232
+ * @param raw raw RPC receipt
233
+ */
234
+ function parseReceiptL1Fee(raw: Record<string, unknown>): string | undefined {
235
+ const l1Fee = raw.l1Fee
236
+ return typeof l1Fee === 'string' ? BigInt(l1Fee).toString() : undefined
237
+ }
238
+
226
239
  async function getTransaction(
227
240
  api: JsonRpcProvider,
228
241
  _currencyId: string,
229
242
  txHash: string
230
243
  ): Promise<TransactionInfo> {
244
+ // Note: raw RPC call is used to get transaction receipt, as ethers method drops extra fields. We need optimism's
245
+ // extra fields that contain L1 fees.
246
+ // A pull request for ethers is open to avoid this: https://github.com/ethers-io/ethers.js/pull/5189
231
247
  const [tx, receipt] = await Promise.all([
232
248
  api.getTransaction(txHash),
233
- api.getTransactionReceipt(txHash),
249
+ api.send('eth_getTransactionReceipt', [txHash]) as Promise<TransactionReceipt | null>,
234
250
  ])
235
251
 
236
252
  if (!tx || !receipt) {
237
253
  throw new Error('Transaction or receipt not found')
238
254
  }
239
255
 
256
+ const raw = receipt as TransactionReceipt & Record<string, unknown>
257
+ const contractAddressRaw = raw.contractAddress
258
+ const contractAddress =
259
+ typeof contractAddressRaw === 'string' && contractAddressRaw.startsWith('0x')
260
+ ? contractAddressRaw
261
+ : undefined
262
+
263
+ const l1Fee = parseReceiptL1Fee(raw)
264
+
240
265
  return {
241
266
  hash: tx.hash,
242
267
  blockHeight: tx.blockNumber ?? undefined,
243
268
  blockHash: tx.blockHash ?? undefined,
244
269
  nonce: tx.nonce,
245
- gasUsed: receipt.gasUsed.toString(),
246
- gasPrice: receipt.gasPrice.toString(),
247
- status: receipt.status,
270
+ gasUsed: BigInt(receipt.gasUsed).toString(),
271
+ gasPrice: BigInt(receipt.effectiveGasPrice ?? receipt.gasPrice ?? '0x0').toString(),
272
+ status: receipt.status === null ? null : Number(receipt.status),
248
273
  value: tx.value.toString(),
249
274
  from: tx.from,
250
275
  to: tx.to ?? undefined,
251
- type: receipt.type ?? tx.type ?? undefined,
276
+ type: receipt.type !== undefined ? Number(receipt.type) : (tx.type ?? undefined),
252
277
  ...(tx.data !== null && tx.data !== undefined && isSmartContractInput(tx.data)
253
278
  ? { input: tx.data }
254
279
  : {}),
255
- ...(receipt.contractAddress ? { contractAddress: receipt.contractAddress } : {}),
280
+ ...(contractAddress ? { contractAddress } : {}),
256
281
  erc20Transfers: parseERC20TransfersFromLogs(receipt.logs),
282
+ ...(l1Fee !== undefined ? { l1Fee } : {}),
257
283
  }
258
284
  }
259
285
 
@@ -710,6 +736,8 @@ async function getBlockReceipts(
710
736
  ? contractAddressRaw
711
737
  : undefined
712
738
 
739
+ const l1Fee = parseReceiptL1Fee(raw)
740
+
713
741
  return {
714
742
  hash: receipt.transactionHash,
715
743
  gasUsed: BigInt(receipt.gasUsed).toString(),
@@ -718,6 +746,7 @@ async function getBlockReceipts(
718
746
  erc20Transfers: parseERC20TransfersFromLogs(receipt.logs),
719
747
  ...(contractAddress ? { contractAddress } : {}),
720
748
  ...(receipt.type !== undefined ? { type: Number(receipt.type) } : {}),
749
+ ...(l1Fee !== undefined ? { l1Fee } : {}),
721
750
  }
722
751
  })
723
752
  }
@@ -281,6 +281,50 @@ describe('EVM Family', () => {
281
281
  })
282
282
 
283
283
  describe('getTransaction', () => {
284
+ // Mocks the raw eth_getTransactionReceipt response, as ethers' getTransactionReceipt would
285
+ // drop the non-standard fields (l1Fee) this path reads.
286
+ function mockRawReceipt(overrides: Record<string, unknown> = {}): void {
287
+ jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
288
+ if (method === 'eth_getTransactionReceipt') {
289
+ return {
290
+ transactionHash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
291
+ gasUsed: '0x7a',
292
+ gasPrice: '0x315',
293
+ status: '0x1',
294
+ logs: [],
295
+ type: '0x0',
296
+ contractAddress: null,
297
+ ...overrides,
298
+ }
299
+ }
300
+ return null
301
+ })
302
+ }
303
+
304
+ beforeEach(() => {
305
+ mockRawReceipt()
306
+ })
307
+
308
+ it('should normalize the hex l1Fee of an OP-stack receipt to a decimal string', async () => {
309
+ mockRawReceipt({ l1Fee: '0x56c2d5eea374' }) // 95394812830580
310
+
311
+ const tx = await nodeApi.getTransaction(
312
+ currencyId,
313
+ '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
314
+ )
315
+
316
+ expect(tx.l1Fee).toBe('95394812830580')
317
+ })
318
+
319
+ it('should leave l1Fee undefined when the receipt has none (non OP-stack chains)', async () => {
320
+ const tx = await nodeApi.getTransaction(
321
+ currencyId,
322
+ '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
323
+ )
324
+
325
+ expect(tx.l1Fee).toBeUndefined()
326
+ })
327
+
284
328
  it('should return the expected payload', async () => {
285
329
  expect(
286
330
  await nodeApi.getTransaction(
@@ -1368,6 +1412,35 @@ describe('EVM Family', () => {
1368
1412
  ])
1369
1413
  })
1370
1414
 
1415
+ it('should normalize the hex l1Fee of an OP-stack receipt to a decimal string', async () => {
1416
+ jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementationOnce(async (method) => {
1417
+ if (method === 'eth_getBlockReceipts') {
1418
+ return [
1419
+ {
1420
+ transactionHash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
1421
+ gasUsed: '0x5208', // 21000
1422
+ effectiveGasPrice: '0x3b9aca00', // 1000000000
1423
+ status: '0x1',
1424
+ logs: [],
1425
+ l1Fee: '0x56c2d5eea374', // 95394812830580
1426
+ },
1427
+ ]
1428
+ }
1429
+ throw new Error(`Method not mocked: ${method}`)
1430
+ })
1431
+
1432
+ expect(await nodeApi.getBlockReceipts!(currencyId, 1)).toEqual([
1433
+ {
1434
+ hash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
1435
+ gasUsed: '21000',
1436
+ gasPrice: '1000000000',
1437
+ status: 1,
1438
+ erc20Transfers: [],
1439
+ l1Fee: '95394812830580',
1440
+ },
1441
+ ])
1442
+ })
1443
+
1371
1444
  it('should throw UnsupportedRpcMethodError for RPC -32601', async () => {
1372
1445
  jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
1373
1446
  if (method === 'eth_chainId') {
@@ -146,6 +146,8 @@ export type TransactionInfo = {
146
146
  erc20Transfers: ERC20Transfer[]
147
147
  /** Tx envelope type per EIP-2718 (decimal), e.g. 2 for EIP-1559. */
148
148
  type?: number
149
+ /** L1 data/security fee in wei (OP-stack chains: Optimism, Base, Blast, …). Present only when the receipt includes the field. */
150
+ l1Fee?: string
149
151
  }
150
152
 
151
153
  export type PrefetchedBlockTransaction = Pick<
@@ -155,7 +157,14 @@ export type PrefetchedBlockTransaction = Pick<
155
157
 
156
158
  export type BlockReceiptInfo = Pick<
157
159
  TransactionInfo,
158
- 'hash' | 'gasUsed' | 'gasPrice' | 'status' | 'erc20Transfers' | 'contractAddress' | 'type'
160
+ | 'hash'
161
+ | 'gasUsed'
162
+ | 'gasPrice'
163
+ | 'status'
164
+ | 'erc20Transfers'
165
+ | 'contractAddress'
166
+ | 'type'
167
+ | 'l1Fee'
159
168
  >
160
169
 
161
170
  export type BlockByHeightResult = {
@@ -0,0 +1,63 @@
1
+ // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { delay } from '@ledgerhq/coin-module-framework/promises'
5
+ import { RateLimitError } from '../errors'
6
+ import { withRetries } from './withRetries'
7
+
8
+ jest.mock('@ledgerhq/coin-module-framework/promises')
9
+ jest.mocked(delay).mockResolvedValue(undefined)
10
+
11
+ describe('EVM Family', () => {
12
+ describe('network/withRetries.ts', () => {
13
+ beforeEach(() => {
14
+ jest.clearAllMocks()
15
+ })
16
+
17
+ it('should retry a transient error until it succeeds', async () => {
18
+ const fn = jest.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce('ok')
19
+
20
+ await expect(withRetries(fn, 2, 10)).resolves.toBe('ok')
21
+ expect(fn).toHaveBeenCalledTimes(2)
22
+ })
23
+
24
+ it('should surface an external node 429 as a RateLimitError without retrying', async () => {
25
+ // ethers escalates a 429 into a 599 SERVER_ERROR, keeping the original status in the
26
+ // statusMessage. This is the exact `${statusCode} ${statusMessage}` shape it produces.
27
+ const escalated = Object.assign(new Error('server response 599'), {
28
+ code: 'SERVER_ERROR',
29
+ info: {
30
+ responseStatus:
31
+ '599 CLIENT ESCALATED SERVER ERROR (429 Too Many Requests; exceeded maximum retry limit)',
32
+ },
33
+ })
34
+ const fn = jest.fn().mockRejectedValue(escalated)
35
+
36
+ await expect(withRetries(fn, 5, 10)).rejects.toBeInstanceOf(RateLimitError)
37
+ // a rate limit is not transient: it must not consume the retry budget
38
+ expect(fn).toHaveBeenCalledTimes(1)
39
+ })
40
+
41
+ it('should surface a Ledger node 429 as a RateLimitError without retrying', async () => {
42
+ const rateLimitError = Object.assign(new Error('Request failed with status code 429'), {
43
+ isAxiosError: true,
44
+ response: { status: 429 },
45
+ })
46
+ const fn = jest.fn().mockRejectedValue(rateLimitError)
47
+
48
+ await expect(withRetries(fn, 5, 10)).rejects.toBeInstanceOf(RateLimitError)
49
+ expect(fn).toHaveBeenCalledTimes(1)
50
+ })
51
+
52
+ it('should keep retrying a non-429 SERVER_ERROR', async () => {
53
+ const serverError = Object.assign(new Error('server response 503'), {
54
+ code: 'SERVER_ERROR',
55
+ info: { responseStatus: '503 Service Unavailable' },
56
+ })
57
+ const fn = jest.fn().mockRejectedValue(serverError)
58
+
59
+ await expect(withRetries(fn, 2, 10)).rejects.toBe(serverError)
60
+ expect(fn).toHaveBeenCalledTimes(3)
61
+ })
62
+ })
63
+ })
@@ -2,6 +2,9 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import { delay } from '@ledgerhq/coin-module-framework/promises'
5
+ import axios from 'axios'
6
+ import { isError } from 'ethers'
7
+ import { RateLimitError } from '../errors'
5
8
 
6
9
  /**
7
10
  * Executes an async function and retries on failure.
@@ -18,6 +21,15 @@ export async function withRetries<T>(
18
21
  try {
19
22
  return await fn()
20
23
  } catch (e) {
24
+ // External nodes go through ethers, which escalates a 429 into a 599 SERVER_ERROR whose
25
+ // responseStatus (`${statusCode} ${statusMessage}`) embeds the original status — hence the
26
+ // substring match rather than an equality check. Ledger nodes reject with plain axios errors.
27
+ if (
28
+ (isError(e, 'SERVER_ERROR') && String(e.info?.responseStatus ?? '').includes('429')) ||
29
+ (axios.isAxiosError(e) && e.response?.status === 429)
30
+ ) {
31
+ throw new RateLimitError()
32
+ }
21
33
  if (retries > 0) {
22
34
  await delay(delayMs)
23
35
  return withRetries(fn, retries - 1, delayMs)
@@ -24,7 +24,7 @@ describe('getValidators', () => {
24
24
  'somnia',
25
25
  createMockEvmCoinConfig({
26
26
  chainId: 5031,
27
- node: mkExternalNode({ uri: 'https://somnia-rpc.publicnode.com' }),
27
+ node: mkExternalNode({ uri: 'https://api.infra.mainnet.somnia.network' }),
28
28
  }),
29
29
  ],
30
30
  ])("fetches validators on '%s'", async (currencyId, config) => {
@@ -28,6 +28,8 @@ export type EtherscanOperation = {
28
28
  confirmations: string
29
29
  methodId: string
30
30
  functionName: string
31
+ /** L1 data/security fee in wei, as reported by OP-stack explorers (Optimism, Base, Blast, …). */
32
+ L1FeesPaid?: string
31
33
  }
32
34
 
33
35
  export type EtherscanERC20Event = {