@ledgerhq/coin-evm 16.2.2 → 16.2.5

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.
@@ -6,6 +6,7 @@ import { createMockEvmContext } from '../../fixtures/context.fixtures'
6
6
  import { mkJsonRpcProvider, mkResult } from '../../fixtures/ethers.fixtures'
7
7
  import { withApi } from '../../network/node/rpc.common'
8
8
  import { encodeStakingData, decodeStakingResult } from '../../staking/encoder'
9
+ import { fetchRewards } from '../../staking/rewards'
9
10
  import { fetchUnbondings } from '../../staking/unbondings'
10
11
  import { getValidators } from '../../staking/validators'
11
12
  import { getStakes } from '../getStakes'
@@ -28,11 +29,16 @@ jest.mock('../../staking/unbondings', () => ({
28
29
  fetchUnbondings: jest.fn(),
29
30
  }))
30
31
 
32
+ jest.mock('../../staking/rewards', () => ({
33
+ fetchRewards: jest.fn(),
34
+ }))
35
+
31
36
  const mockWithApi = jest.mocked(withApi)
32
37
  const mockEncodeStakingData = jest.mocked(encodeStakingData)
33
38
  const mockDecodeStakingResult = jest.mocked(decodeStakingResult)
34
39
  const mockGetValidators = jest.mocked(getValidators)
35
40
  const mockFetchUnbondings = jest.mocked(fetchUnbondings)
41
+ const mockFetchRewards = jest.mocked(fetchRewards)
36
42
 
37
43
  const externalNodeConfig = { type: 'external' as const, uri: 'https://test' }
38
44
  const context = createMockEvmContext({
@@ -64,6 +70,7 @@ describe('EVM Staking - getStakes', () => {
64
70
  jest.clearAllMocks()
65
71
  jest.spyOn(console, 'error').mockImplementation(() => undefined)
66
72
  mockFetchUnbondings.mockResolvedValue([])
73
+ mockFetchRewards.mockResolvedValue(new Map())
67
74
  })
68
75
 
69
76
  it('should return stake objects with positive amounts for supported currencies', async () => {
@@ -118,11 +118,24 @@ const EMPTY_RESULT: Readonly<EndpointResult> = {
118
118
  isPageFull: false,
119
119
  }
120
120
 
121
+ /**
122
+ * Every endpoint read through this function returns a list. Etherscan-like explorers answer an
123
+ * empty list with `status: "0"` and `result: []`, and an error (rate limit, query timeout, invalid
124
+ * address...) with `status: "0"` and a `null` or string `result`. The shape of `result` tells them
125
+ * apart, so no error message has to be known in advance: an unknown error must not read as an
126
+ * empty history, or every token of the account is reported with a zero balance (LIVE-38797).
127
+ *
128
+ * `messageIsAnError` lists the messages that are errors even with a list `result`.
129
+ *
130
+ * A query timeout is not retried: Etherscan stops the query after its ~18s server-side limit, and
131
+ * the same query times out again on every retry.
132
+ */
121
133
  export async function fetchWithRetries<T>(
122
134
  params: AxiosRequestConfig,
123
135
  retries = DEFAULT_RETRIES_API,
124
- messageIsAnError = ['NOTOK']
136
+ messageIsAnError: string[] = []
125
137
  ): Promise<T> {
138
+ let isQueryTimeout = false
126
139
  try {
127
140
  const { data } = await axios.request<{
128
141
  status: string
@@ -130,7 +143,11 @@ export async function fetchWithRetries<T>(
130
143
  result: T
131
144
  }>(params)
132
145
 
133
- if (!Number(data.status) && messageIsAnError.includes(data.message)) {
146
+ if (
147
+ (data.status === '0' && !Array.isArray(data.result)) ||
148
+ (!Number(data.status) && messageIsAnError.includes(data.message))
149
+ ) {
150
+ isQueryTimeout = data.message?.startsWith('Query Timeout') ?? false
134
151
  throw new EtherscanAPIError('Error while fetching data from Etherscan like API', {
135
152
  params,
136
153
  data,
@@ -142,7 +159,7 @@ export async function fetchWithRetries<T>(
142
159
  if (axios.isAxiosError(e) && e.response?.status === 429) {
143
160
  throw new RateLimitError()
144
161
  }
145
- if (retries) {
162
+ if (retries && !isQueryTimeout) {
146
163
  // wait the API timeout before trying again
147
164
  await delay(ETHERSCAN_TIMEOUT)
148
165
  // decrement with prefix here or it won't work
@@ -560,15 +577,14 @@ export const getInternalOperations = async (
560
577
  return EMPTY_RESULT
561
578
  }
562
579
 
563
- // Some explorers (e.g. Monad Testnet) return null instead of [] for empty results.
564
- const ops = await fetchWithRetries<EtherscanInternalTransaction[] | null>(
580
+ const ops = await fetchWithRetries<EtherscanInternalTransaction[]>(
565
581
  {
566
582
  method: 'GET',
567
583
  url: `${explorer.uri}?module=account&action=txlistinternal&address=${params.address}`,
568
584
  params: paginationParams(params),
569
585
  },
570
586
  explorer.retries ?? DEFAULT_RETRIES_API
571
- ).then((ops) => (ops ?? []).map(fixTxHash))
587
+ ).then((ops) => ops.map(fixTxHash))
572
588
 
573
589
  // Why this thing ?
574
590
  // Multiple internal transactions can be executed from
@@ -627,13 +643,9 @@ export async function getInternalTransactionsByBlock(
627
643
  }),
628
644
  },
629
645
  0, // do not retry on error
630
- [
631
- // blockscout can respond `{"message":"No internal transactions found","result":[],"status":"0"}`
632
- // even though there are internal transactions that could be fetched otherwise !
633
- 'No internal transactions found',
634
- // this is the common error message for all etherscan like explorers
635
- 'NOTOK',
636
- ]
646
+ // blockscout can respond `{"message":"No internal transactions found","result":[],"status":"0"}`
647
+ // even though there are internal transactions that could be fetched otherwise !
648
+ ['No internal transactions found']
637
649
  )
638
650
 
639
651
  const ops = Array.isArray(raw) ? raw : []
@@ -21,8 +21,8 @@ type GasTracker = {
21
21
  // update of the explorer backend to support EIP1559, we should be able to
22
22
  // update this config without having to release a new version of the app?
23
23
  const explorerIdGasTrackerMap = new Map<string, GasTracker>([
24
- ['avax', { compatibilty: { eip1559: false } }],
25
- ['bnb', { compatibilty: { eip1559: false } }],
24
+ ['avax', { compatibilty: { eip1559: true } }],
25
+ ['bnb', { compatibilty: { eip1559: true } }],
26
26
  ['eth', { compatibilty: { eip1559: true } }],
27
27
  ['etc', { compatibilty: { eip1559: false } }],
28
28
  ['matic', { compatibilty: { eip1559: true } }],
@@ -134,9 +134,9 @@ describe('EVM Family', () => {
134
134
  const spy = jest.spyOn(axios, 'request').mockImplementation(async () => {
135
135
  if (retries) {
136
136
  --retries
137
- return { data: { message: 'NOTOK' } }
137
+ return { data: { status: '0', message: 'NOTOK', result: 'Max rate limit reached' } }
138
138
  }
139
- return { data: { result: true } }
139
+ return { data: { status: '1', message: 'OK', result: true } }
140
140
  })
141
141
  const response = await ETHERSCAN_API.fetchWithRetries({}, retries)
142
142
 
@@ -145,6 +145,57 @@ describe('EVM Family', () => {
145
145
  expect(spy).toHaveBeenCalledTimes(3)
146
146
  })
147
147
 
148
+ it('should throw without retrying when the explorer reports a query timeout', async () => {
149
+ const spy = jest.spyOn(axios, 'request').mockResolvedValue({
150
+ data: {
151
+ status: '0',
152
+ message: 'Query Timeout occured. Please select a smaller result dataset',
153
+ result: null,
154
+ },
155
+ })
156
+
157
+ await expect(
158
+ ETHERSCAN_API.fetchWithRetries({}, ETHERSCAN_API.DEFAULT_RETRIES_API)
159
+ ).rejects.toBeInstanceOf(EtherscanAPIError)
160
+ // the same query times out again on every retry
161
+ expect(spy).toHaveBeenCalledTimes(1)
162
+ })
163
+
164
+ it.each([
165
+ ['an unknown error', 'Invalid address format', null],
166
+ ['an error string', 'NOTOK', 'Max rate limit reached'],
167
+ ])(
168
+ 'should retry, then throw, when the explorer reports %s instead of a list',
169
+ async (_, message, result) => {
170
+ const spy = jest.spyOn(axios, 'request').mockResolvedValue({
171
+ data: { status: '0', message, result },
172
+ })
173
+
174
+ await expect(ETHERSCAN_API.fetchWithRetries({}, 1)).rejects.toBeInstanceOf(
175
+ EtherscanAPIError
176
+ )
177
+ expect(spy).toHaveBeenCalledTimes(2)
178
+ }
179
+ )
180
+
181
+ it('should return an empty list as is', async () => {
182
+ jest.spyOn(axios, 'request').mockResolvedValueOnce({
183
+ data: { status: '0', message: 'No transactions found', result: [] },
184
+ })
185
+
186
+ await expect(ETHERSCAN_API.fetchWithRetries({}, 0)).resolves.toEqual([])
187
+ })
188
+
189
+ it('should throw on a caller-supplied error message even with a list result', async () => {
190
+ jest.spyOn(axios, 'request').mockResolvedValueOnce({
191
+ data: { status: '0', message: 'No internal transactions found', result: [] },
192
+ })
193
+
194
+ await expect(
195
+ ETHERSCAN_API.fetchWithRetries({}, 0, ['No internal transactions found'])
196
+ ).rejects.toBeInstanceOf(EtherscanAPIError)
197
+ })
198
+
148
199
  it('should surface a 429 HTTP response as RateLimitError without retrying', async () => {
149
200
  const rateLimitError = Object.assign(new Error('Request failed with status code 429'), {
150
201
  isAxiosError: true,
@@ -178,32 +229,48 @@ describe('EVM Family', () => {
178
229
  ['ERC20', ETHERSCAN_API.getTokenOperations],
179
230
  ['ERC721', ETHERSCAN_API.getERC721Operations],
180
231
  ['ERC1155', ETHERSCAN_API.getERC1155Operations],
181
- ])('%s operations with non-array explorer results', (_, getOperations) => {
232
+ ])('%s operations with status "0" explorer results', (_, getOperations) => {
182
233
  afterEach(() => {
183
234
  jest.clearAllMocks()
184
235
  })
185
236
 
186
- it.each([null, 'No transactions found'])(
187
- 'returns an empty result when the explorer returns %p',
188
- async (result) => {
189
- jest.spyOn(axios, 'request').mockResolvedValueOnce({
190
- data: { status: '0', message: 'No transactions found', result },
191
- })
237
+ it('returns an empty result when the explorer returns an empty list', async () => {
238
+ jest.spyOn(axios, 'request').mockResolvedValueOnce({
239
+ data: { status: '0', message: 'No transactions found', result: [] },
240
+ })
192
241
 
193
- const response = await getOperations({
194
- config,
195
- address,
196
- fromBlock: 0,
197
- sort: 'asc',
198
- logger: testLogger,
199
- })
242
+ const response = await getOperations({
243
+ config,
244
+ address,
245
+ fromBlock: 0,
246
+ sort: 'asc',
247
+ logger: testLogger,
248
+ })
200
249
 
201
- expect(response).toEqual({
202
- operations: [],
203
- isDone: true,
204
- boundBlock: 0,
205
- isPageFull: true,
250
+ expect(response).toEqual({
251
+ operations: [],
252
+ isDone: true,
253
+ boundBlock: 0,
254
+ isPageFull: true,
255
+ })
256
+ })
257
+
258
+ it.each([null, 'Max rate limit reached'])(
259
+ 'throws when the explorer returns %p instead of a list',
260
+ async (result) => {
261
+ jest.spyOn(axios, 'request').mockResolvedValue({
262
+ data: { status: '0', message: 'NOTOK', result },
206
263
  })
264
+
265
+ await expect(
266
+ getOperations({
267
+ config,
268
+ address,
269
+ fromBlock: 0,
270
+ sort: 'asc',
271
+ logger: testLogger,
272
+ })
273
+ ).rejects.toBeInstanceOf(EtherscanAPIError)
207
274
  }
208
275
  )
209
276
  })
@@ -1547,23 +1614,24 @@ describe('EVM Family', () => {
1547
1614
  )
1548
1615
  })
1549
1616
 
1550
- it('should return empty operations when API returns null result (e.g. Monad Testnet explorer)', async () => {
1551
- // Some explorers (e.g. Monad Testnet) return `{"status":"0","message":"No transactions found","result":null}`
1552
- // instead of `{"result":[]}` for empty internal transaction lists.
1553
- jest.spyOn(axios, 'request').mockResolvedValueOnce({
1554
- data: { status: '0', message: 'No transactions found', result: null },
1555
- })
1556
-
1557
- const response = await ETHERSCAN_API.getInternalOperations({
1558
- config,
1559
- address: address,
1560
- fromBlock: 0,
1561
- sort: 'asc',
1562
- logger: testLogger,
1617
+ it('should throw when API returns a null result instead of a list', async () => {
1618
+ jest.spyOn(axios, 'request').mockResolvedValue({
1619
+ data: {
1620
+ status: '0',
1621
+ message: 'Query Timeout occured. Please select a smaller result dataset',
1622
+ result: null,
1623
+ },
1563
1624
  })
1564
1625
 
1565
- expect(response.operations).toEqual([])
1566
- expect(response.isDone).toBe(true)
1626
+ await expect(
1627
+ ETHERSCAN_API.getInternalOperations({
1628
+ config,
1629
+ address: address,
1630
+ fromBlock: 0,
1631
+ sort: 'asc',
1632
+ logger: testLogger,
1633
+ })
1634
+ ).rejects.toBeInstanceOf(EtherscanAPIError)
1567
1635
  })
1568
1636
 
1569
1637
  describe('isPageFull and isDone', () => {
@@ -165,6 +165,58 @@ describe('EVM Family', () => {
165
165
  expect(gasOptions).toEqual(expectedGasOptions)
166
166
  })
167
167
 
168
+ it('should request and return EIP-1559 gas options on Avalanche C-Chain', async () => {
169
+ const gasOptions: GasOptions = await getGasOptions({
170
+ config: createMockEvmConfigInfo({
171
+ chainId: 43114,
172
+ node: mkLedgerNode({ explorerId: 'avax' }),
173
+ gasTracker: mkLedgerGasTracker({ explorerId: 'avax' }),
174
+ eip1559BaseFeeMultiplier: 2,
175
+ }),
176
+ options: { useEIP1559: true },
177
+ })
178
+
179
+ expect(mockedNetwork).toHaveBeenCalledWith(
180
+ expect.objectContaining({
181
+ url: expect.stringMatching(/\/avax\/gastracker\/barometer\?display=eip1559$/),
182
+ })
183
+ )
184
+ expect(gasOptions.medium).toEqual({
185
+ maxFeePerGas: new BigNumber(10),
186
+ maxPriorityFeePerGas: new BigNumber(2),
187
+ gasPrice: null,
188
+ nextBaseFee: new BigNumber(4),
189
+ })
190
+ })
191
+
192
+ it('should request and return EIP-1559 gas options on BSC, whose base fee is zero', async () => {
193
+ mockedNetwork.mockReset()
194
+ mockedNetwork.mockReturnValueOnce(
195
+ makeNetworkResponse({ low: '1', medium: '2', high: '3', next_base: '0' })
196
+ )
197
+
198
+ const gasOptions: GasOptions = await getGasOptions({
199
+ config: createMockEvmConfigInfo({
200
+ chainId: 56,
201
+ node: mkLedgerNode({ explorerId: 'bnb' }),
202
+ gasTracker: mkLedgerGasTracker({ explorerId: 'bnb' }),
203
+ }),
204
+ options: { useEIP1559: true },
205
+ })
206
+
207
+ expect(mockedNetwork).toHaveBeenCalledWith(
208
+ expect.objectContaining({
209
+ url: expect.stringMatching(/\/bnb\/gastracker\/barometer\?display=eip1559$/),
210
+ })
211
+ )
212
+ expect(gasOptions.medium).toEqual({
213
+ maxFeePerGas: new BigNumber(2),
214
+ maxPriorityFeePerGas: new BigNumber(2),
215
+ gasPrice: null,
216
+ nextBaseFee: new BigNumber(0),
217
+ })
218
+ })
219
+
168
220
  it('should return legacy gas options when EIP-1559 not supported by gas tracker', async () => {
169
221
  const gasOptions: GasOptions = await getGasOptions({
170
222
  config: createMockEvmConfigInfo({