@ledgerhq/coin-evm 5.4.0 → 7.0.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 (342) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/docs/evm-family-integration-process/README.md +1 -1
  3. package/knip.json +2 -3
  4. package/lib/adapters/blockOperations.js +6 -6
  5. package/lib/adapters/blockOperations.js.map +1 -1
  6. package/lib/adapters/etherscan.js +23 -23
  7. package/lib/adapters/etherscan.js.map +1 -1
  8. package/lib/adapters/ledger.js +17 -17
  9. package/lib/adapters/ledger.js.map +1 -1
  10. package/lib/api/index.js +4 -4
  11. package/lib/api/index.js.map +1 -1
  12. package/lib/config.d.ts +21 -15
  13. package/lib/config.d.ts.map +1 -1
  14. package/lib/config.js +5 -25
  15. package/lib/config.js.map +1 -1
  16. package/lib/errors.d.ts +9 -0
  17. package/lib/errors.d.ts.map +1 -1
  18. package/lib/errors.js +15 -1
  19. package/lib/errors.js.map +1 -1
  20. package/lib/logic/broadcast.js +1 -1
  21. package/lib/logic/broadcast.js.map +1 -1
  22. package/lib/logic/common.d.ts +2 -1
  23. package/lib/logic/common.d.ts.map +1 -1
  24. package/lib/logic/common.js +4 -4
  25. package/lib/logic/common.js.map +1 -1
  26. package/lib/logic/craftTransaction.d.ts.map +1 -1
  27. package/lib/logic/craftTransaction.js +2 -2
  28. package/lib/logic/craftTransaction.js.map +1 -1
  29. package/lib/logic/estimateFees.d.ts.map +1 -1
  30. package/lib/logic/estimateFees.js +9 -9
  31. package/lib/logic/estimateFees.js.map +1 -1
  32. package/lib/logic/getBalance.d.ts.map +1 -1
  33. package/lib/logic/getBalance.js +50 -16
  34. package/lib/logic/getBalance.js.map +1 -1
  35. package/lib/logic/getBlock.d.ts.map +1 -1
  36. package/lib/logic/getBlock.js +19 -11
  37. package/lib/logic/getBlock.js.map +1 -1
  38. package/lib/logic/getBlockInfo.js +1 -1
  39. package/lib/logic/getBlockInfo.js.map +1 -1
  40. package/lib/logic/getNextSequence.d.ts.map +1 -1
  41. package/lib/logic/getNextSequence.js +1 -1
  42. package/lib/logic/getNextSequence.js.map +1 -1
  43. package/lib/logic/index.d.ts +2 -0
  44. package/lib/logic/index.d.ts.map +1 -1
  45. package/lib/logic/index.js +4 -0
  46. package/lib/logic/index.js.map +1 -1
  47. package/lib/logic/lastBlock.js +1 -1
  48. package/lib/logic/lastBlock.js.map +1 -1
  49. package/lib/logic/listOperations.d.ts.map +1 -1
  50. package/lib/logic/listOperations.js +10 -1
  51. package/lib/logic/listOperations.js.map +1 -1
  52. package/lib/logic/validateIntent.d.ts.map +1 -1
  53. package/lib/logic/validateIntent.js +12 -12
  54. package/lib/logic/validateIntent.js.map +1 -1
  55. package/lib/logic-public/index.d.ts +3 -0
  56. package/lib/logic-public/index.d.ts.map +1 -0
  57. package/lib/logic-public/index.js +19 -0
  58. package/lib/logic-public/index.js.map +1 -0
  59. package/lib/{utils.d.ts → logic-public/utils.d.ts} +0 -44
  60. package/lib/logic-public/utils.d.ts.map +1 -0
  61. package/lib/logic-public/utils.js +166 -0
  62. package/lib/logic-public/utils.js.map +1 -0
  63. package/lib/logic.d.ts +2 -1
  64. package/lib/logic.d.ts.map +1 -1
  65. package/lib/logic.js +3 -3
  66. package/lib/logic.js.map +1 -1
  67. package/lib/network/explorer/etherscan.d.ts +16 -3
  68. package/lib/network/explorer/etherscan.d.ts.map +1 -1
  69. package/lib/network/explorer/etherscan.js +61 -6
  70. package/lib/network/explorer/etherscan.js.map +1 -1
  71. package/lib/network/explorer/ledger.d.ts +50 -4
  72. package/lib/network/explorer/ledger.d.ts.map +1 -1
  73. package/lib/network/explorer/ledger.js +286 -37
  74. package/lib/network/explorer/ledger.js.map +1 -1
  75. package/lib/network/explorer/none.d.ts +1 -0
  76. package/lib/network/explorer/none.d.ts.map +1 -1
  77. package/lib/network/explorer/none.js +4 -1
  78. package/lib/network/explorer/none.js.map +1 -1
  79. package/lib/network/explorer/types.d.ts +15 -2
  80. package/lib/network/explorer/types.d.ts.map +1 -1
  81. package/lib/network/explorer/types.js.map +1 -1
  82. package/lib/network/index.d.ts +5 -0
  83. package/lib/network/index.d.ts.map +1 -0
  84. package/lib/network/index.js +23 -0
  85. package/lib/network/index.js.map +1 -0
  86. package/lib/network/node/explorerProxy.d.ts +27 -0
  87. package/lib/network/node/explorerProxy.d.ts.map +1 -0
  88. package/lib/network/node/explorerProxy.js +262 -0
  89. package/lib/network/node/explorerProxy.js.map +1 -0
  90. package/lib/network/node/index.d.ts +2 -1
  91. package/lib/network/node/index.d.ts.map +1 -1
  92. package/lib/network/node/index.js +11 -10
  93. package/lib/network/node/index.js.map +1 -1
  94. package/lib/network/node/ledger.js +7 -7
  95. package/lib/network/node/ledger.js.map +1 -1
  96. package/lib/network/node/rpc.common.d.ts +2 -2
  97. package/lib/network/node/rpc.common.js +19 -19
  98. package/lib/network/node/rpc.common.js.map +1 -1
  99. package/lib/network/node/withNodeSources.d.ts +21 -0
  100. package/lib/network/node/withNodeSources.d.ts.map +1 -0
  101. package/lib/network/node/withNodeSources.js +78 -0
  102. package/lib/network/node/withNodeSources.js.map +1 -0
  103. package/lib/nodeSources.d.ts +15 -0
  104. package/lib/nodeSources.d.ts.map +1 -0
  105. package/lib/nodeSources.js +33 -0
  106. package/lib/nodeSources.js.map +1 -0
  107. package/lib/staking/contracts.js +1 -1
  108. package/lib/staking/contracts.js.map +1 -1
  109. package/lib/staking/fetchers.js +1 -1
  110. package/lib/staking/fetchers.js.map +1 -1
  111. package/lib/staking/operations/sei.js +1 -1
  112. package/lib/staking/operations/sei.js.map +1 -1
  113. package/lib/staking/prepareIntents.js +3 -3
  114. package/lib/staking/prepareIntents.js.map +1 -1
  115. package/lib/staking/rewards.js +1 -1
  116. package/lib/staking/rewards.js.map +1 -1
  117. package/lib/staking/transactionData.js +2 -2
  118. package/lib/staking/transactionData.js.map +1 -1
  119. package/lib/staking/utils.d.ts +45 -0
  120. package/lib/staking/utils.d.ts.map +1 -0
  121. package/lib/{utils.js → staking/utils.js} +5 -164
  122. package/lib/staking/utils.js.map +1 -0
  123. package/lib/staking/validators/sei.js +1 -1
  124. package/lib/staking/validators/sei.js.map +1 -1
  125. package/lib/types/staking.d.ts +2 -2
  126. package/lib-es/adapters/blockOperations.js +1 -1
  127. package/lib-es/adapters/blockOperations.js.map +1 -1
  128. package/lib-es/adapters/etherscan.js +1 -1
  129. package/lib-es/adapters/etherscan.js.map +1 -1
  130. package/lib-es/adapters/ledger.js +1 -1
  131. package/lib-es/adapters/ledger.js.map +1 -1
  132. package/lib-es/api/index.js +2 -2
  133. package/lib-es/api/index.js.map +1 -1
  134. package/lib-es/config.d.ts +21 -15
  135. package/lib-es/config.d.ts.map +1 -1
  136. package/lib-es/config.js +1 -21
  137. package/lib-es/config.js.map +1 -1
  138. package/lib-es/errors.d.ts +9 -0
  139. package/lib-es/errors.d.ts.map +1 -1
  140. package/lib-es/errors.js +13 -0
  141. package/lib-es/errors.js.map +1 -1
  142. package/lib-es/logic/broadcast.js +1 -1
  143. package/lib-es/logic/broadcast.js.map +1 -1
  144. package/lib-es/logic/common.d.ts +2 -1
  145. package/lib-es/logic/common.d.ts.map +1 -1
  146. package/lib-es/logic/common.js +3 -3
  147. package/lib-es/logic/common.js.map +1 -1
  148. package/lib-es/logic/craftTransaction.d.ts.map +1 -1
  149. package/lib-es/logic/craftTransaction.js +2 -2
  150. package/lib-es/logic/craftTransaction.js.map +1 -1
  151. package/lib-es/logic/estimateFees.d.ts.map +1 -1
  152. package/lib-es/logic/estimateFees.js +6 -6
  153. package/lib-es/logic/estimateFees.js.map +1 -1
  154. package/lib-es/logic/getBalance.d.ts.map +1 -1
  155. package/lib-es/logic/getBalance.js +50 -16
  156. package/lib-es/logic/getBalance.js.map +1 -1
  157. package/lib-es/logic/getBlock.d.ts.map +1 -1
  158. package/lib-es/logic/getBlock.js +16 -8
  159. package/lib-es/logic/getBlock.js.map +1 -1
  160. package/lib-es/logic/getBlockInfo.js +1 -1
  161. package/lib-es/logic/getBlockInfo.js.map +1 -1
  162. package/lib-es/logic/getNextSequence.d.ts.map +1 -1
  163. package/lib-es/logic/getNextSequence.js +1 -1
  164. package/lib-es/logic/getNextSequence.js.map +1 -1
  165. package/lib-es/logic/index.d.ts +2 -0
  166. package/lib-es/logic/index.d.ts.map +1 -1
  167. package/lib-es/logic/index.js +4 -0
  168. package/lib-es/logic/index.js.map +1 -1
  169. package/lib-es/logic/lastBlock.js +1 -1
  170. package/lib-es/logic/lastBlock.js.map +1 -1
  171. package/lib-es/logic/listOperations.d.ts.map +1 -1
  172. package/lib-es/logic/listOperations.js +10 -1
  173. package/lib-es/logic/listOperations.js.map +1 -1
  174. package/lib-es/logic/validateIntent.d.ts.map +1 -1
  175. package/lib-es/logic/validateIntent.js +4 -4
  176. package/lib-es/logic/validateIntent.js.map +1 -1
  177. package/lib-es/logic-public/index.d.ts +3 -0
  178. package/lib-es/logic-public/index.d.ts.map +1 -0
  179. package/lib-es/logic-public/index.js +4 -0
  180. package/lib-es/logic-public/index.js.map +1 -0
  181. package/lib-es/{utils.d.ts → logic-public/utils.d.ts} +0 -44
  182. package/lib-es/logic-public/utils.d.ts.map +1 -0
  183. package/lib-es/logic-public/utils.js +150 -0
  184. package/lib-es/logic-public/utils.js.map +1 -0
  185. package/lib-es/logic.d.ts +2 -1
  186. package/lib-es/logic.d.ts.map +1 -1
  187. package/lib-es/logic.js +3 -3
  188. package/lib-es/logic.js.map +1 -1
  189. package/lib-es/network/explorer/etherscan.d.ts +16 -3
  190. package/lib-es/network/explorer/etherscan.d.ts.map +1 -1
  191. package/lib-es/network/explorer/etherscan.js +60 -5
  192. package/lib-es/network/explorer/etherscan.js.map +1 -1
  193. package/lib-es/network/explorer/ledger.d.ts +50 -4
  194. package/lib-es/network/explorer/ledger.d.ts.map +1 -1
  195. package/lib-es/network/explorer/ledger.js +283 -37
  196. package/lib-es/network/explorer/ledger.js.map +1 -1
  197. package/lib-es/network/explorer/none.d.ts +1 -0
  198. package/lib-es/network/explorer/none.d.ts.map +1 -1
  199. package/lib-es/network/explorer/none.js +2 -0
  200. package/lib-es/network/explorer/none.js.map +1 -1
  201. package/lib-es/network/explorer/types.d.ts +15 -2
  202. package/lib-es/network/explorer/types.d.ts.map +1 -1
  203. package/lib-es/network/explorer/types.js.map +1 -1
  204. package/lib-es/network/index.d.ts +5 -0
  205. package/lib-es/network/index.d.ts.map +1 -0
  206. package/lib-es/network/index.js +7 -0
  207. package/lib-es/network/index.js.map +1 -0
  208. package/lib-es/network/node/explorerProxy.d.ts +27 -0
  209. package/lib-es/network/node/explorerProxy.d.ts.map +1 -0
  210. package/lib-es/network/node/explorerProxy.js +254 -0
  211. package/lib-es/network/node/explorerProxy.js.map +1 -0
  212. package/lib-es/network/node/index.d.ts +2 -1
  213. package/lib-es/network/node/index.d.ts.map +1 -1
  214. package/lib-es/network/node/index.js +11 -10
  215. package/lib-es/network/node/index.js.map +1 -1
  216. package/lib-es/network/node/ledger.js +1 -1
  217. package/lib-es/network/node/ledger.js.map +1 -1
  218. package/lib-es/network/node/rpc.common.d.ts +2 -2
  219. package/lib-es/network/node/rpc.common.js +3 -3
  220. package/lib-es/network/node/rpc.common.js.map +1 -1
  221. package/lib-es/network/node/withNodeSources.d.ts +21 -0
  222. package/lib-es/network/node/withNodeSources.d.ts.map +1 -0
  223. package/lib-es/network/node/withNodeSources.js +74 -0
  224. package/lib-es/network/node/withNodeSources.js.map +1 -0
  225. package/lib-es/nodeSources.d.ts +15 -0
  226. package/lib-es/nodeSources.d.ts.map +1 -0
  227. package/lib-es/nodeSources.js +28 -0
  228. package/lib-es/nodeSources.js.map +1 -0
  229. package/lib-es/staking/contracts.js +1 -1
  230. package/lib-es/staking/contracts.js.map +1 -1
  231. package/lib-es/staking/fetchers.js +1 -1
  232. package/lib-es/staking/fetchers.js.map +1 -1
  233. package/lib-es/staking/operations/sei.js +1 -1
  234. package/lib-es/staking/operations/sei.js.map +1 -1
  235. package/lib-es/staking/prepareIntents.js +1 -1
  236. package/lib-es/staking/prepareIntents.js.map +1 -1
  237. package/lib-es/staking/rewards.js +1 -1
  238. package/lib-es/staking/rewards.js.map +1 -1
  239. package/lib-es/staking/transactionData.js +1 -1
  240. package/lib-es/staking/transactionData.js.map +1 -1
  241. package/lib-es/staking/utils.d.ts +45 -0
  242. package/lib-es/staking/utils.d.ts.map +1 -0
  243. package/lib-es/{utils.js → staking/utils.js} +1 -147
  244. package/lib-es/staking/utils.js.map +1 -0
  245. package/lib-es/staking/validators/sei.js +1 -1
  246. package/lib-es/staking/validators/sei.js.map +1 -1
  247. package/lib-es/types/staking.d.ts +2 -2
  248. package/package.json +72 -7
  249. package/src/adapters/blockOperations.ts +1 -1
  250. package/src/adapters/etherscan.ts +1 -1
  251. package/src/adapters/ledger.ts +1 -1
  252. package/src/api/{index.arc_testnet.integ.test.ts → index.arc.integ.test.ts} +15 -12
  253. package/src/api/index.monad_testnet.integ.test.ts +95 -4
  254. package/src/api/index.ts +2 -2
  255. package/src/config.ts +22 -34
  256. package/src/errors.ts +13 -0
  257. package/src/fixtures/context.fixtures.ts +6 -1
  258. package/src/logic/broadcast.ts +1 -1
  259. package/src/logic/common.ts +4 -2
  260. package/src/logic/craftTransaction.ts +2 -1
  261. package/src/logic/estimateFees.ts +20 -6
  262. package/src/logic/getBalance.ts +72 -26
  263. package/src/logic/getBlock.ts +26 -14
  264. package/src/logic/getBlockInfo.ts +1 -1
  265. package/src/logic/getNextSequence.ts +4 -1
  266. package/src/logic/index.ts +4 -0
  267. package/src/logic/lastBlock.ts +1 -1
  268. package/src/logic/listOperations.ts +14 -1
  269. package/src/logic/tests/broadcast.integ.test.ts +53 -0
  270. package/src/logic/{broadcast.test.ts → tests/broadcast.test.ts} +7 -7
  271. package/src/logic/{broadcastSource.test.ts → tests/broadcastSource.test.ts} +6 -6
  272. package/src/logic/{combine.test.ts → tests/combine.test.ts} +1 -1
  273. package/src/logic/{common.test.ts → tests/common.test.ts} +45 -21
  274. package/src/logic/{computeGasLimit.test.ts → tests/computeGasLimit.test.ts} +2 -2
  275. package/src/logic/{craftTransaction.test.ts → tests/craftTransaction.test.ts} +7 -7
  276. package/src/logic/{craftTransactionData.test.ts → tests/craftTransactionData.test.ts} +4 -4
  277. package/src/logic/{estimateFees.test.ts → tests/estimateFees.test.ts} +12 -12
  278. package/src/logic/tests/getBalance.test.ts +602 -0
  279. package/src/logic/{getBlock.test.ts → tests/getBlock.test.ts} +182 -89
  280. package/src/logic/{getBlockInfo.test.ts → tests/getBlockInfo.test.ts} +8 -8
  281. package/src/logic/{getErc20Data.test.ts → tests/getErc20Data.test.ts} +1 -1
  282. package/src/logic/{getNextSequence.test.ts → tests/getNextSequence.test.ts} +7 -7
  283. package/src/logic/{getStakes.test.ts → tests/getStakes.test.ts} +13 -13
  284. package/src/logic/{internalTransactionsFetcher.test.ts → tests/internalTransactionsFetcher.test.ts} +8 -8
  285. package/src/logic/{lastBlock.test.ts → tests/lastBlock.test.ts} +7 -7
  286. package/src/logic/{listOperations.test.ts → tests/listOperations.test.ts} +125 -6
  287. package/src/logic/{validateAddress.test.ts → tests/validateAddress.test.ts} +1 -1
  288. package/src/logic/{validateIntent.test.ts → tests/validateIntent.test.ts} +80 -78
  289. package/src/logic/validateIntent.ts +7 -4
  290. package/src/logic-public/index.ts +18 -0
  291. package/src/{utils.test.ts → logic-public/tests/utils.test.ts} +1 -27
  292. package/src/logic-public/utils.ts +184 -0
  293. package/src/logic.test.ts +5 -59
  294. package/src/logic.ts +5 -3
  295. package/src/network/explorer/etherscan.test.ts +403 -195
  296. package/src/network/explorer/etherscan.ts +99 -10
  297. package/src/network/explorer/index.test.ts +27 -0
  298. package/src/network/explorer/ledger.test.ts +791 -62
  299. package/src/network/explorer/ledger.ts +426 -54
  300. package/src/network/explorer/none.ts +3 -0
  301. package/src/network/explorer/types.ts +29 -5
  302. package/src/network/index.ts +7 -0
  303. package/src/network/node/explorerProxy.test.ts +673 -0
  304. package/src/network/node/explorerProxy.ts +308 -0
  305. package/src/network/node/index.memoization.test.ts +22 -10
  306. package/src/network/node/index.test.ts +6 -3
  307. package/src/network/node/index.ts +11 -7
  308. package/src/network/node/ledger.ts +1 -1
  309. package/src/network/node/rpc.common.ts +3 -3
  310. package/src/network/node/rpc.test.ts +66 -105
  311. package/src/network/node/withNodeSources.test.ts +240 -0
  312. package/src/network/node/withNodeSources.ts +95 -0
  313. package/src/nodeSources.ts +38 -0
  314. package/src/staking/contracts.ts +1 -1
  315. package/src/staking/encoder.test.ts +1 -1
  316. package/src/staking/fetchers.ts +1 -1
  317. package/src/staking/operations/sei.ts +1 -1
  318. package/src/staking/prepareIntents.ts +1 -1
  319. package/src/staking/redelegations.test.ts +1 -1
  320. package/src/staking/rewards.test.ts +1 -1
  321. package/src/staking/rewards.ts +1 -1
  322. package/src/staking/transactionData.ts +1 -1
  323. package/src/staking/unbondings.test.ts +1 -1
  324. package/src/staking/utils.test.ts +25 -0
  325. package/src/{utils.ts → staking/utils.ts} +2 -182
  326. package/src/staking/validators/sei.ts +1 -1
  327. package/src/types/staking.ts +2 -2
  328. package/lib/constants.d.ts +0 -2
  329. package/lib/constants.d.ts.map +0 -1
  330. package/lib/constants.js +0 -11
  331. package/lib/constants.js.map +0 -1
  332. package/lib/utils.d.ts.map +0 -1
  333. package/lib/utils.js.map +0 -1
  334. package/lib-es/constants.d.ts +0 -2
  335. package/lib-es/constants.d.ts.map +0 -1
  336. package/lib-es/constants.js +0 -7
  337. package/lib-es/constants.js.map +0 -1
  338. package/lib-es/utils.d.ts.map +0 -1
  339. package/lib-es/utils.js.map +0 -1
  340. package/src/constants.ts +0 -9
  341. package/src/logic/broadcast.integ.test.ts +0 -46
  342. package/src/logic/getBalance.test.ts +0 -362
@@ -1,15 +1,22 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import type { NftStandard } from '../../config'
4
+ import type { EvmConfigInfo, NftStandard } from '../../config'
5
+ import type { LedgerExplorerOperation } from '../../types'
6
+ import type { AssetInfo } from '@ledgerhq/coin-module-framework/api/types'
7
+ import type { AxiosRequestConfig } from 'axios'
5
8
  import { AssertionError, fail } from 'assert'
6
9
  import { delay } from '@ledgerhq/coin-module-framework/promises'
7
10
  import axios from 'axios'
8
11
  import eip55 from 'eip55'
9
- import { DEFAULT_LEDGER_EXPLORER_URI, getCoinConfig } from '../../config'
10
- import { LedgerExplorerUsedIncorrectly, RateLimitError } from '../../errors'
12
+ import { DEFAULT_LEDGER_EXPLORER_URI } from '../../config'
11
13
  import {
12
- createMockEvmCoinConfig,
14
+ LedgerExplorerUsedIncorrectly,
15
+ RateLimitError,
16
+ UnpageableLedgerExplorerBlock,
17
+ } from '../../errors'
18
+ import {
19
+ createMockEvmConfigInfo,
13
20
  mkExternalNode,
14
21
  mkLedgerNode,
15
22
  } from '../../fixtures/context.fixtures'
@@ -27,20 +34,62 @@ jest.mocked(delay).mockImplementation(
27
34
  () => new Promise((resolve) => setTimeout(resolve, 1)) // mocking the delay supposed to happen after each try
28
35
  )
29
36
 
30
- jest.mock('../../config')
31
- const mockGetConfig = jest.mocked(getCoinConfig)
37
+ let config: EvmConfigInfo
38
+
39
+ // Minimal record for `discoverTokenAssets`, which only ever reads `transfer_events`.
40
+ const discoveryRecord = (
41
+ transferEvents: Array<{ contract: string; from: string; to: string }>
42
+ ): LedgerExplorerOperation => ({
43
+ hash: '0xhash',
44
+ transaction_type: 2,
45
+ nonce: '0x0',
46
+ nonce_value: 0,
47
+ from: '',
48
+ to: '',
49
+ value: '0',
50
+ gas: '0',
51
+ gas_price: '0',
52
+ max_fee_per_gas: null,
53
+ max_priority_fee_per_gas: null,
54
+ gas_used: '0',
55
+ cumulative_gas_used: '0',
56
+ status: 1,
57
+ confirmations: 1,
58
+ input: null,
59
+ received_at: '2023-01-01T00:00:00Z',
60
+ transfer_events: transferEvents.map((e) => ({ ...e, count: '1' })),
61
+ erc721_transfer_events: [],
62
+ erc1155_transfer_events: [],
63
+ approval_events: [],
64
+ actions: [],
65
+ block: { hash: '0xblock', height: 1, time: '2023-01-01T00:00:00Z' },
66
+ })
67
+
68
+ // axios is fully mocked in this file, so `isAxiosError` has to be restored to its real shape
69
+ // check for the rate-limit branch to be reachable at all.
70
+ const mockRateLimitedExplorer = () => {
71
+ jest
72
+ .spyOn(axios, 'isAxiosError')
73
+ .mockImplementation(
74
+ (e: unknown): boolean => typeof e === 'object' && e !== null && 'isAxiosError' in e
75
+ )
76
+ return jest.spyOn(axios, 'request').mockRejectedValue(
77
+ Object.assign(new Error('Request failed with status code 429'), {
78
+ isAxiosError: true,
79
+ response: { status: 429 },
80
+ })
81
+ )
82
+ }
32
83
 
33
84
  describe('EVM Family', () => {
34
85
  describe('network/explorer/ledger.ts', () => {
35
86
  beforeEach(() => {
36
- mockGetConfig.mockImplementation(() =>
37
- createMockEvmCoinConfig({
38
- chainId: 1,
39
- node: mkLedgerNode({ explorerId: 'eth' }),
40
- explorer: { type: 'ledger', explorerId: 'eth' },
41
- supportedTokens: ['erc721', 'erc1155'],
42
- })
43
- )
87
+ config = createMockEvmConfigInfo({
88
+ chainId: 1,
89
+ node: mkLedgerNode({ explorerId: 'eth' }),
90
+ explorer: { type: 'ledger', explorerId: 'eth' },
91
+ supportedTokens: ['erc721', 'erc1155'],
92
+ })
44
93
  })
45
94
 
46
95
  afterEach(() => {
@@ -200,13 +249,11 @@ describe('EVM Family', () => {
200
249
 
201
250
  describe('getOperations', () => {
202
251
  it('should throw if the explorer is misconfigured', async () => {
203
- mockGetConfig.mockImplementationOnce(() =>
204
- createMockEvmCoinConfig({ chainId: 1, node: mkExternalNode({ uri: 'anything' }) })
205
- )
252
+ config = createMockEvmConfigInfo({ chainId: 1, node: mkExternalNode({ uri: 'anything' }) })
206
253
 
207
254
  try {
208
255
  await LEDGER_API.getOperations(
209
- getCoinConfig('ethereum').info,
256
+ config,
210
257
  'ethereum',
211
258
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
212
259
  0
@@ -224,20 +271,18 @@ describe('EVM Family', () => {
224
271
  ['configured', 10, 10],
225
272
  ['default', undefined, 10_000],
226
273
  ])('uses the %s batch size', async (_s, configuredBatchSize, expectedBatchSize) => {
227
- mockGetConfig.mockImplementationOnce(() => ({
228
- info: {
229
- chainId: 1,
230
- name: 'Ethereum',
231
- status: { type: 'active' },
232
- node: { type: 'ledger', explorerId: 'matic' },
233
- explorer: { type: 'ledger', explorerId: 'matic', batchSize: configuredBatchSize },
234
- supportedTokens: ['erc721', 'erc1155'],
235
- },
236
- }))
274
+ config = {
275
+ chainId: 1,
276
+ name: 'Ethereum',
277
+ status: { type: 'active' },
278
+ node: { type: 'ledger', explorerId: 'matic' },
279
+ explorer: { type: 'ledger', explorerId: 'matic', batchSize: configuredBatchSize },
280
+ supportedTokens: ['erc721', 'erc1155'],
281
+ }
237
282
  const request = jest.spyOn(axios, 'request').mockResolvedValue({ data: { data: [] } })
238
283
 
239
284
  await LEDGER_API.getOperations(
240
- getCoinConfig('ethereum').info,
285
+ config,
241
286
  'ethereum',
242
287
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
243
288
  0
@@ -256,7 +301,7 @@ describe('EVM Family', () => {
256
301
  }))
257
302
 
258
303
  const response = await LEDGER_API.getOperations(
259
- getCoinConfig('ethereum').info,
304
+ config,
260
305
  'ethereum',
261
306
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
262
307
  0
@@ -460,13 +505,11 @@ describe('EVM Family', () => {
460
505
 
461
506
  describe('getOperations without nft', () => {
462
507
  beforeEach(() => {
463
- mockGetConfig.mockImplementation(() =>
464
- createMockEvmCoinConfig({
465
- chainId: 1,
466
- node: mkLedgerNode({ explorerId: 'eth' }),
467
- explorer: { type: 'ledger', explorerId: 'eth' },
468
- })
469
- )
508
+ config = createMockEvmConfigInfo({
509
+ chainId: 1,
510
+ node: mkLedgerNode({ explorerId: 'eth' }),
511
+ explorer: { type: 'ledger', explorerId: 'eth' },
512
+ })
470
513
  })
471
514
 
472
515
  it('should not return NFT opperation', async () => {
@@ -475,7 +518,7 @@ describe('EVM Family', () => {
475
518
  }))
476
519
 
477
520
  const response = await LEDGER_API.getOperations(
478
- getCoinConfig('ethereum').info,
521
+ config,
479
522
  'ethereum',
480
523
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
481
524
  0
@@ -493,19 +536,18 @@ describe('EVM Family', () => {
493
536
  }))
494
537
  })
495
538
 
496
- const mockConfigWithTokens = (supportedTokens: NftStandard[]) =>
497
- mockGetConfig.mockImplementation(() =>
498
- createMockEvmCoinConfig({
499
- chainId: 1,
500
- node: mkLedgerNode({ explorerId: 'eth' }),
501
- explorer: { type: 'ledger', explorerId: 'eth' },
502
- supportedTokens,
503
- })
504
- )
539
+ const mockConfigWithTokens = (supportedTokens: NftStandard[]) => {
540
+ config = createMockEvmConfigInfo({
541
+ chainId: 1,
542
+ node: mkLedgerNode({ explorerId: 'eth' }),
543
+ explorer: { type: 'ledger', explorerId: 'eth' },
544
+ supportedTokens,
545
+ })
546
+ }
505
547
 
506
548
  const fetchNftAssetTypes = async () => {
507
549
  const response = await LEDGER_API.getOperations(
508
- getCoinConfig('ethereum').info,
550
+ config,
509
551
  'ethereum',
510
552
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
511
553
  0
@@ -541,16 +583,15 @@ describe('EVM Family', () => {
541
583
  // coinOperation1.transfer_events[0].contract — the only ERC20 event in the fixtures.
542
584
  const FIXTURE_CONTRACT = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'
543
585
 
544
- const withConfig = (info: { nativeContracts?: string[] }) =>
545
- mockGetConfig.mockImplementation(() =>
546
- createMockEvmCoinConfig({
547
- chainId: 1,
548
- node: mkLedgerNode({ explorerId: 'eth' }),
549
- explorer: { type: 'ledger', explorerId: 'eth' },
550
- supportedTokens: ['erc721', 'erc1155'],
551
- ...info,
552
- })
553
- )
586
+ const withConfig = (info: { nativeContracts?: string[] }) => {
587
+ config = createMockEvmConfigInfo({
588
+ chainId: 1,
589
+ node: mkLedgerNode({ explorerId: 'eth' }),
590
+ explorer: { type: 'ledger', explorerId: 'eth' },
591
+ supportedTokens: ['erc721', 'erc1155'],
592
+ ...info,
593
+ })
594
+ }
554
595
 
555
596
  it('drops ERC20 transfer events whose contract is listed in nativeContracts', async () => {
556
597
  withConfig({ nativeContracts: [FIXTURE_CONTRACT] })
@@ -559,7 +600,7 @@ describe('EVM Family', () => {
559
600
  }))
560
601
 
561
602
  const response = await LEDGER_API.getOperations(
562
- getCoinConfig('ethereum').info,
603
+ config,
563
604
  'ethereum',
564
605
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
565
606
  0
@@ -575,7 +616,7 @@ describe('EVM Family', () => {
575
616
  }))
576
617
 
577
618
  const response = await LEDGER_API.getOperations(
578
- getCoinConfig('ethereum').info,
619
+ config,
579
620
  'ethereum',
580
621
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
581
622
  0
@@ -591,7 +632,7 @@ describe('EVM Family', () => {
591
632
  }))
592
633
 
593
634
  const response = await LEDGER_API.getOperations(
594
- getCoinConfig('ethereum').info,
635
+ config,
595
636
  'ethereum',
596
637
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
597
638
  0
@@ -607,7 +648,7 @@ describe('EVM Family', () => {
607
648
  }))
608
649
 
609
650
  const response = await LEDGER_API.getOperations(
610
- getCoinConfig('ethereum').info,
651
+ config,
611
652
  'ethereum',
612
653
  '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d',
613
654
  0
@@ -617,5 +658,693 @@ describe('EVM Family', () => {
617
658
  })
618
659
  })
619
660
  })
661
+
662
+ describe('serializeLedgerCursor / parseLedgerCursor', () => {
663
+ it('round-trips a cursor', () => {
664
+ const serialized = LEDGER_API.serializeLedgerCursor({ height: 42, hash: '0xabc' })
665
+
666
+ expect(serialized).toBe('42:0xabc')
667
+ expect(LEDGER_API.parseLedgerCursor(serialized)).toEqual({ height: 42, hash: '0xabc' })
668
+ })
669
+
670
+ it('serializes to NO_TOKEN when there is no record to resume from', () => {
671
+ expect(LEDGER_API.serializeLedgerCursor(undefined)).toBe('')
672
+ })
673
+
674
+ it('parses NO_TOKEN and an absent cursor as undefined', () => {
675
+ expect(LEDGER_API.parseLedgerCursor('')).toBeUndefined()
676
+ expect(LEDGER_API.parseLedgerCursor(undefined)).toBeUndefined()
677
+ })
678
+
679
+ it.each([['garbage'], [':nohash'], ['42:'], ['abc:hash']])(
680
+ 'throws on the malformed cursor %s rather than silently restarting from the tip',
681
+ (malformed) => {
682
+ expect(() => LEDGER_API.parseLedgerCursor(malformed)).toThrow(
683
+ 'Invalid ledger explorer cursor'
684
+ )
685
+ }
686
+ )
687
+ })
688
+
689
+ describe('getOperations with limit (paginated)', () => {
690
+ const ADDR = '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d'
691
+
692
+ // Minimal record for the paginated path: `from` is the requested address so each record
693
+ // maps to exactly one FEES operation, keeping the assertions about record order simple.
694
+ const pagedRecord = (height: number, hash: string): LedgerExplorerOperation => ({
695
+ hash,
696
+ transaction_type: 2,
697
+ nonce: '0x0',
698
+ nonce_value: 0,
699
+ value: '0',
700
+ gas: '0',
701
+ gas_price: '0',
702
+ max_fee_per_gas: null,
703
+ max_priority_fee_per_gas: null,
704
+ from: ADDR,
705
+ to: '0x0000000000000000000000000000000000000009',
706
+ transfer_events: [],
707
+ erc721_transfer_events: [],
708
+ erc1155_transfer_events: [],
709
+ approval_events: [],
710
+ actions: [],
711
+ confirmations: 1,
712
+ input: null,
713
+ gas_used: '0',
714
+ cumulative_gas_used: '0',
715
+ status: 1,
716
+ received_at: '2023-01-01T00:00:00Z',
717
+ block: { hash: `0xblock${height}`, height, time: '2023-01-01T00:00:00Z' },
718
+ })
719
+
720
+ const hashesOf = (response: {
721
+ lastCoinOperations: Array<{ tx: { hash: string } }>
722
+ }): string[] => response.lastCoinOperations.map((op) => op.tx.hash)
723
+
724
+ it('surfaces a 429 as a RateLimitError without retrying', async () => {
725
+ const request = mockRateLimitedExplorer()
726
+
727
+ await expect(
728
+ LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, undefined, undefined, 2, 'desc')
729
+ ).rejects.toBeInstanceOf(RateLimitError)
730
+ // Same rule the exhaustive walk follows: a rate limit is not transient, so it must not
731
+ // consume the retry budget.
732
+ expect(request).toHaveBeenCalledTimes(1)
733
+ })
734
+
735
+ it('honours the explorer-configured retry budget rather than the default', async () => {
736
+ const request = jest.spyOn(axios, 'request').mockRejectedValue(new Error('explorer down'))
737
+ const noRetries = createMockEvmConfigInfo({
738
+ chainId: 1,
739
+ node: mkLedgerNode({ explorerId: 'eth' }),
740
+ explorer: { type: 'ledger', explorerId: 'eth', retries: 0 },
741
+ })
742
+
743
+ await expect(
744
+ LEDGER_API.getOperations(noRetries, 'ethereum', ADDR, 0, undefined, undefined, 2, 'desc')
745
+ ).rejects.toThrow('explorer down')
746
+ expect(request).toHaveBeenCalledTimes(1)
747
+ })
748
+
749
+ it('issues exactly one request carrying batch_size, the mapped order, from_height, and no token parameter', async () => {
750
+ const request = jest.spyOn(axios, 'request').mockResolvedValue({
751
+ data: { data: [pagedRecord(100, 'h100'), pagedRecord(99, 'h99')], token: 'ignored' },
752
+ })
753
+
754
+ const response = await LEDGER_API.getOperations(
755
+ config,
756
+ 'ethereum',
757
+ ADDR,
758
+ 0,
759
+ undefined,
760
+ undefined,
761
+ 2,
762
+ 'desc'
763
+ )
764
+
765
+ expect(request).toHaveBeenCalledTimes(1)
766
+ expect(request).toHaveBeenCalledWith(
767
+ expect.objectContaining({
768
+ params: expect.objectContaining({
769
+ batch_size: 2,
770
+ order: 'descending',
771
+ from_height: 0,
772
+ }),
773
+ })
774
+ )
775
+ expect(request.mock.calls[0][0].params).not.toHaveProperty('token')
776
+ // Descending, no ceiling: the first page is the tip, in the explorer's own order.
777
+ expect(hashesOf(response)).toEqual(['h100', 'h99'])
778
+ })
779
+
780
+ it('resumes from the returned cursor with no gap and no duplicate, and signals end of stream', async () => {
781
+ const records = [
782
+ pagedRecord(105, 'h105'),
783
+ pagedRecord(104, 'h104'),
784
+ pagedRecord(103, 'h103'),
785
+ pagedRecord(102, 'h102'),
786
+ pagedRecord(101, 'h101'),
787
+ ]
788
+ jest.spyOn(axios, 'request').mockImplementation(async ({ params }: AxiosRequestConfig) => {
789
+ const ceiling: number | undefined = params.to_height
790
+ const startIndex =
791
+ ceiling === undefined ? 0 : records.findIndex((r) => r.block.height <= ceiling)
792
+ return {
793
+ data: { data: records.slice(startIndex, startIndex + params.batch_size), token: '' },
794
+ }
795
+ })
796
+
797
+ const page1 = await LEDGER_API.getOperations(
798
+ config,
799
+ 'ethereum',
800
+ ADDR,
801
+ 0,
802
+ undefined,
803
+ undefined,
804
+ 3,
805
+ 'desc'
806
+ )
807
+ expect(hashesOf(page1)).toEqual(['h105', 'h104', 'h103'])
808
+ expect(page1.nextPagingToken).toBe('103:h103')
809
+
810
+ const page2 = await LEDGER_API.getOperations(
811
+ config,
812
+ 'ethereum',
813
+ ADDR,
814
+ 0,
815
+ undefined,
816
+ page1.nextPagingToken,
817
+ 3,
818
+ 'desc'
819
+ )
820
+ expect(hashesOf(page2)).toEqual(['h102', 'h101'])
821
+ expect(page2.nextPagingToken).toBe('101:h101')
822
+
823
+ // The concatenation of the two pages equals the mock's full sequence: no gap, no duplicate.
824
+ expect([...hashesOf(page1), ...hashesOf(page2)]).toEqual([
825
+ 'h105',
826
+ 'h104',
827
+ 'h103',
828
+ 'h102',
829
+ 'h101',
830
+ ])
831
+
832
+ const page3 = await LEDGER_API.getOperations(
833
+ config,
834
+ 'ethereum',
835
+ ADDR,
836
+ 0,
837
+ undefined,
838
+ page2.nextPagingToken,
839
+ 3,
840
+ 'desc'
841
+ )
842
+ expect(hashesOf(page3)).toEqual([])
843
+ expect(page3.nextPagingToken).toBe('')
844
+ })
845
+
846
+ it('caps a resumed descending page at to_height = cursor height, and floors a resumed ascending page at from_height = cursor height', async () => {
847
+ const request = jest
848
+ .spyOn(axios, 'request')
849
+ .mockResolvedValue({ data: { data: [pagedRecord(50, 'h50')], token: '' } })
850
+
851
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, undefined, '60:h60', 5, 'desc')
852
+ expect(request).toHaveBeenLastCalledWith(
853
+ expect.objectContaining({ params: expect.objectContaining({ to_height: 60 }) })
854
+ )
855
+
856
+ request.mockClear()
857
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, undefined, '60:h60', 5, 'asc')
858
+ expect(request).toHaveBeenLastCalledWith(
859
+ expect.objectContaining({ params: expect.objectContaining({ from_height: 60 }) })
860
+ )
861
+ })
862
+
863
+ it('forwards toBlock and combines it with the cursor as the more restrictive of the two (descending)', async () => {
864
+ const request = jest
865
+ .spyOn(axios, 'request')
866
+ .mockResolvedValue({ data: { data: [], token: '' } })
867
+
868
+ // No cursor: toBlock alone is the ceiling.
869
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, 77, undefined, 5, 'desc')
870
+ expect(request).toHaveBeenLastCalledWith(
871
+ expect.objectContaining({ params: expect.objectContaining({ to_height: 77 }) })
872
+ )
873
+
874
+ // Cursor height (40) is more restrictive than toBlock (100).
875
+ request.mockClear()
876
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, 100, '40:hx', 5, 'desc')
877
+ expect(request).toHaveBeenLastCalledWith(
878
+ expect.objectContaining({ params: expect.objectContaining({ to_height: 40 }) })
879
+ )
880
+
881
+ // toBlock (30) is more restrictive than the cursor height (40).
882
+ request.mockClear()
883
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, 30, '40:hx', 5, 'desc')
884
+ expect(request).toHaveBeenLastCalledWith(
885
+ expect.objectContaining({ params: expect.objectContaining({ to_height: 30 }) })
886
+ )
887
+ })
888
+
889
+ it('skips through the cursor by hash, not merely by height, within a boundary block', async () => {
890
+ const sameHeightRecords = [
891
+ pagedRecord(10, 'hA'),
892
+ pagedRecord(10, 'hB'),
893
+ pagedRecord(10, 'hC'),
894
+ ]
895
+ const request = jest
896
+ .spyOn(axios, 'request')
897
+ .mockResolvedValue({ data: { data: sameHeightRecords, token: '' } })
898
+
899
+ const response = await LEDGER_API.getOperations(
900
+ config,
901
+ 'ethereum',
902
+ ADDR,
903
+ 0,
904
+ undefined,
905
+ '10:hA',
906
+ 3,
907
+ 'desc'
908
+ )
909
+
910
+ expect(hashesOf(response)).toEqual(['hB', 'hC'])
911
+ expect(request).toHaveBeenCalledTimes(1)
912
+ })
913
+
914
+ it('enlarges the page and keeps requesting the same window when a block holds more records than the page size (boundary exhaustion)', async () => {
915
+ const boundary = [
916
+ pagedRecord(20, 'b1'),
917
+ pagedRecord(20, 'b2'),
918
+ pagedRecord(20, 'b3'),
919
+ pagedRecord(20, 'b4'),
920
+ pagedRecord(20, 'b5'),
921
+ ]
922
+ const request = jest
923
+ .spyOn(axios, 'request')
924
+ .mockImplementation(async ({ params }: AxiosRequestConfig) => ({
925
+ data: {
926
+ data: boundary.slice(0, Math.min(params.batch_size, boundary.length)),
927
+ token: '',
928
+ },
929
+ }))
930
+
931
+ const response = await LEDGER_API.getOperations(
932
+ config,
933
+ 'ethereum',
934
+ ADDR,
935
+ 0,
936
+ undefined,
937
+ '20:b2',
938
+ 2,
939
+ 'desc'
940
+ )
941
+
942
+ expect(hashesOf(response)).toEqual(['b3', 'b4'])
943
+ expect(request).toHaveBeenCalledTimes(2)
944
+ expect(request).toHaveBeenNthCalledWith(
945
+ 1,
946
+ expect.objectContaining({ params: expect.objectContaining({ batch_size: 2 }) })
947
+ )
948
+ expect(request).toHaveBeenNthCalledWith(
949
+ 2,
950
+ expect.objectContaining({ params: expect.objectContaining({ batch_size: 4 }) })
951
+ )
952
+ })
953
+
954
+ it("returns a real cursor, not NO_TOKEN, when doubling crosses the explorer's own page-size ceiling while history remains, and the follow-up call yields the rest with no gap", async () => {
955
+ const CAP = LEDGER_API.EXPLORER_MAX_PAGE_SIZE
956
+ // A block of 450 records at height 20, followed by 60 more at height 19 — each height is
957
+ // comfortably under the explorer's page-size ceiling, but the combined window (510) is
958
+ // not, so a doubled request that reaches into both heights is served capped at CAP,
959
+ // regardless of how large a batch_size was actually asked for.
960
+ const heightTwentyRecords = Array.from({ length: 450 }, (_, i) => pagedRecord(20, `b${i}`))
961
+ const heightNineteenRecords = Array.from({ length: 60 }, (_, i) => pagedRecord(19, `c${i}`))
962
+ const allRecords = [...heightTwentyRecords, ...heightNineteenRecords]
963
+
964
+ const request = jest
965
+ .spyOn(axios, 'request')
966
+ .mockImplementation(async ({ params }: AxiosRequestConfig) => {
967
+ const ceiling: number | undefined = params.to_height
968
+ const eligible =
969
+ ceiling === undefined
970
+ ? allRecords
971
+ : allRecords.filter((r) => r.block.height <= ceiling)
972
+ return {
973
+ data: { data: eligible.slice(0, Math.min(params.batch_size, CAP)), token: '' },
974
+ }
975
+ })
976
+
977
+ // 400 records already delivered by a hypothetical previous page.
978
+ const page1 = await LEDGER_API.getOperations(
979
+ config,
980
+ 'ethereum',
981
+ ADDR,
982
+ 0,
983
+ undefined,
984
+ '20:b399',
985
+ 100,
986
+ 'desc'
987
+ )
988
+
989
+ // Doubling walked 100 -> 200 -> 400 -> 800, and the explorer capped the last attempt at
990
+ // CAP records regardless of the 800 asked for.
991
+ expect(request).toHaveBeenCalledTimes(4)
992
+ expect(request).toHaveBeenLastCalledWith(
993
+ expect.objectContaining({ params: expect.objectContaining({ batch_size: 800 }) })
994
+ )
995
+ // The remainder of the height-20 block plus the start of height 19 — genuinely new
996
+ // records, not re-served ones.
997
+ expect(hashesOf(page1)).toEqual([
998
+ ...heightTwentyRecords.slice(400).map((r) => r.hash),
999
+ ...heightNineteenRecords.slice(0, 50).map((r) => r.hash),
1000
+ ])
1001
+ // The fix: a real cursor, not NO_TOKEN — the explorer's own cap served exactly CAP
1002
+ // records, which is never proof the window ended, whatever `batch_size` was asked for.
1003
+ expect(page1.nextPagingToken).toBe('19:c49')
1004
+
1005
+ request.mockClear()
1006
+ const page2 = await LEDGER_API.getOperations(
1007
+ config,
1008
+ 'ethereum',
1009
+ ADDR,
1010
+ 0,
1011
+ undefined,
1012
+ page1.nextPagingToken,
1013
+ 100,
1014
+ 'desc'
1015
+ )
1016
+
1017
+ // No gap, no duplicate: the tail of height 19 that page1 could not reach.
1018
+ expect(hashesOf(page2)).toEqual(heightNineteenRecords.slice(50).map((r) => r.hash))
1019
+ // Genuinely exhausted this time: the raw page (60 records) fell short of both what was
1020
+ // asked (100) and the explorer's ceiling (CAP), so end of stream is now correctly signalled.
1021
+ expect(page2.nextPagingToken).toBe('')
1022
+ })
1023
+
1024
+ it('raises rather than reporting end-of-stream when a single block holds more records than the explorer will ever serve in one page', async () => {
1025
+ const CAP = LEDGER_API.EXPLORER_MAX_PAGE_SIZE
1026
+ // A single block (one height) with more records than the explorer's page-size ceiling:
1027
+ // no `to_height`/`from_height` refinement can subdivide within one height, so once the
1028
+ // cursor sits at the ceiling, every request — however large — serves the same leading CAP
1029
+ // records and never reaches anything beyond them.
1030
+ const unpageableBlock = Array.from({ length: CAP + 20 }, (_, i) => pagedRecord(20, `u${i}`))
1031
+
1032
+ const request = jest
1033
+ .spyOn(axios, 'request')
1034
+ .mockImplementation(async ({ params }: AxiosRequestConfig) => ({
1035
+ data: { data: unpageableBlock.slice(0, Math.min(params.batch_size, CAP)), token: '' },
1036
+ }))
1037
+
1038
+ // CAP records already delivered by a hypothetical previous page — sitting exactly at the
1039
+ // explorer's own ceiling.
1040
+ await expect(
1041
+ LEDGER_API.getOperations(
1042
+ config,
1043
+ 'ethereum',
1044
+ ADDR,
1045
+ 0,
1046
+ undefined,
1047
+ `20:u${CAP - 1}`,
1048
+ 50,
1049
+ 'desc'
1050
+ )
1051
+ ).rejects.toBeInstanceOf(UnpageableLedgerExplorerBlock)
1052
+
1053
+ // Doubled 50 -> 100 -> 200 -> 400 -> 800 before giving up at/above CAP, never looping
1054
+ // forever.
1055
+ expect(request).toHaveBeenCalledTimes(5)
1056
+ })
1057
+
1058
+ it('throws on a malformed cursor rather than silently restarting from the tip', async () => {
1059
+ await expect(
1060
+ LEDGER_API.getOperations(
1061
+ config,
1062
+ 'ethereum',
1063
+ ADDR,
1064
+ 0,
1065
+ undefined,
1066
+ 'not-a-cursor',
1067
+ 5,
1068
+ 'desc'
1069
+ )
1070
+ ).rejects.toThrow('Invalid ledger explorer cursor')
1071
+ })
1072
+
1073
+ it('propagates after the existing retries on a page that keeps failing, without returning a partial page', async () => {
1074
+ const request = jest.spyOn(axios, 'request').mockRejectedValue(new Error('network error'))
1075
+
1076
+ await expect(
1077
+ LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, undefined, undefined, 5, 'desc')
1078
+ ).rejects.toThrow('network error')
1079
+
1080
+ expect(request).toHaveBeenCalledTimes(LEDGER_API.DEFAULT_RETRIES_API + 1)
1081
+ })
1082
+
1083
+ it.each<['asc' | 'desc', string]>([
1084
+ ['asc', 'ascending'],
1085
+ ['desc', 'descending'],
1086
+ ])(
1087
+ 'maps order %s to the explorer value %s and never re-sorts the returned records',
1088
+ async (order, mappedOrder) => {
1089
+ // Deliberately out of height order: the paged path must preserve explorer order.
1090
+ const records = [pagedRecord(1, 'x1'), pagedRecord(3, 'x3'), pagedRecord(2, 'x2')]
1091
+ const request = jest
1092
+ .spyOn(axios, 'request')
1093
+ .mockResolvedValue({ data: { data: records, token: '' } })
1094
+
1095
+ const response = await LEDGER_API.getOperations(
1096
+ config,
1097
+ 'ethereum',
1098
+ ADDR,
1099
+ 0,
1100
+ undefined,
1101
+ undefined,
1102
+ 3,
1103
+ order
1104
+ )
1105
+
1106
+ expect(request).toHaveBeenCalledWith(
1107
+ expect.objectContaining({ params: expect.objectContaining({ order: mappedOrder }) })
1108
+ )
1109
+ expect(hashesOf(response)).toEqual(['x1', 'x3', 'x2'])
1110
+ }
1111
+ )
1112
+
1113
+ it('defaults to descending when limit is set but order is omitted', async () => {
1114
+ const request = jest
1115
+ .spyOn(axios, 'request')
1116
+ .mockResolvedValue({ data: { data: [pagedRecord(1, 'h1')], token: '' } })
1117
+
1118
+ await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0, undefined, undefined, 5)
1119
+
1120
+ expect(request).toHaveBeenCalledWith(
1121
+ expect.objectContaining({ params: expect.objectContaining({ order: 'descending' }) })
1122
+ )
1123
+ })
1124
+
1125
+ it('keeps the legacy call shape when limit is undefined: ascending request order and no to_height', async () => {
1126
+ const request = jest.spyOn(axios, 'request').mockResolvedValue({ data: { data: [] } })
1127
+
1128
+ const response = await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0)
1129
+
1130
+ expect(response.nextPagingToken).toBe('')
1131
+ expect(request).toHaveBeenCalledWith(
1132
+ expect.objectContaining({ params: expect.objectContaining({ order: 'ascending' }) })
1133
+ )
1134
+ expect(request.mock.calls[0][0].params).not.toHaveProperty('to_height')
1135
+ })
1136
+ })
1137
+
1138
+ describe('discoverTokenAssets', () => {
1139
+ const ADDR = '0x6cBCD73CD8e8a42844662f0A0e76D7F79Afd933d'
1140
+ const THIRD_PARTY_A = '0x0000000000000000000000000000000000000001'
1141
+ const THIRD_PARTY_B = '0x0000000000000000000000000000000000000002'
1142
+ const CONTRACT_1 = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'
1143
+ const CONTRACT_2 = '0x06012c8cf97bead5deae237070f9587f8e7a266d'
1144
+
1145
+ beforeEach(() => {
1146
+ config = createMockEvmConfigInfo({
1147
+ chainId: 1,
1148
+ node: mkLedgerNode({ explorerId: 'eth' }),
1149
+ explorer: { type: 'ledger', explorerId: 'eth' },
1150
+ })
1151
+ })
1152
+
1153
+ it('throws if the explorer is misconfigured', async () => {
1154
+ config = createMockEvmConfigInfo({ chainId: 1, node: mkExternalNode({ uri: 'anything' }) })
1155
+
1156
+ await expect(
1157
+ LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1158
+ ).rejects.toBeInstanceOf(LedgerExplorerUsedIncorrectly)
1159
+ })
1160
+
1161
+ it('surfaces a 429 as a RateLimitError without retrying', async () => {
1162
+ const request = mockRateLimitedExplorer()
1163
+
1164
+ await expect(
1165
+ LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1166
+ ).rejects.toBeInstanceOf(RateLimitError)
1167
+ expect(request).toHaveBeenCalledTimes(1)
1168
+ })
1169
+
1170
+ it('walks every page and returns the deduplicated, EIP-55 encoded union of ERC20 contracts', async () => {
1171
+ jest.spyOn(axios, 'request').mockImplementation(async ({ params }: AxiosRequestConfig) => {
1172
+ if (params.token === null) {
1173
+ return {
1174
+ data: {
1175
+ data: [discoveryRecord([{ contract: CONTRACT_1, from: ADDR, to: THIRD_PARTY_A }])],
1176
+ token: 'page2',
1177
+ },
1178
+ }
1179
+ }
1180
+ if (params.token === 'page2') {
1181
+ return {
1182
+ data: {
1183
+ data: [discoveryRecord([{ contract: CONTRACT_2, from: THIRD_PARTY_A, to: ADDR }])],
1184
+ token: '',
1185
+ },
1186
+ }
1187
+ }
1188
+ throw new Error('should not be called again')
1189
+ })
1190
+
1191
+ const assets = await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1192
+
1193
+ expect(assets).toEqual([
1194
+ { type: 'erc20', assetReference: eip55.encode(CONTRACT_1), assetOwner: ADDR },
1195
+ { type: 'erc20', assetReference: eip55.encode(CONTRACT_2), assetOwner: ADDR },
1196
+ ])
1197
+ })
1198
+
1199
+ it('matches the set derived from the existing getOperations -> lastTokenOperations path over the same pages', async () => {
1200
+ const pages = [
1201
+ discoveryRecord([{ contract: CONTRACT_1, from: ADDR, to: THIRD_PARTY_A }]),
1202
+ discoveryRecord([{ contract: CONTRACT_2, from: THIRD_PARTY_A, to: ADDR }]),
1203
+ ]
1204
+
1205
+ jest.spyOn(axios, 'request').mockImplementation(async () => ({
1206
+ data: { data: pages, token: null },
1207
+ }))
1208
+
1209
+ const discovered = await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1210
+ const opsResult = await LEDGER_API.getOperations(config, 'ethereum', ADDR, 0)
1211
+
1212
+ const referenceOf = (asset: AssetInfo): string | undefined =>
1213
+ 'assetReference' in asset ? asset.assetReference : undefined
1214
+ const isDefined = (value: string | undefined): value is string => value !== undefined
1215
+
1216
+ const expectedReferences = new Set(
1217
+ opsResult.lastTokenOperations.map((op) => referenceOf(op.asset)).filter(isDefined)
1218
+ )
1219
+
1220
+ const discoveredReferences = new Set(discovered.map(referenceOf).filter(isDefined))
1221
+
1222
+ expect(discoveredReferences).toEqual(expectedReferences)
1223
+ })
1224
+
1225
+ it('drops an event whose from and to are both third parties', async () => {
1226
+ jest.spyOn(axios, 'request').mockImplementation(async () => ({
1227
+ data: {
1228
+ data: [
1229
+ discoveryRecord([{ contract: CONTRACT_1, from: THIRD_PARTY_A, to: THIRD_PARTY_B }]),
1230
+ ],
1231
+ token: '',
1232
+ },
1233
+ }))
1234
+
1235
+ const assets = await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1236
+
1237
+ expect(assets).toEqual([])
1238
+ })
1239
+
1240
+ it.each([
1241
+ ['configured', 10, 10],
1242
+ ['default', undefined, LEDGER_API.DISCOVERY_BATCH_SIZE],
1243
+ ['oversized configured', 10_000, LEDGER_API.DISCOVERY_BATCH_SIZE],
1244
+ // A zero would empty every page, end the walk on its first one, and report an account as
1245
+ // holding no token at all — which reads back as a zero balance on every token it holds.
1246
+ ['non-positive configured', 0, LEDGER_API.DISCOVERY_BATCH_SIZE],
1247
+ ])('uses the %s batch size', async (_s, configuredBatchSize, expectedBatchSize) => {
1248
+ config = createMockEvmConfigInfo({
1249
+ chainId: 1,
1250
+ node: mkLedgerNode({ explorerId: 'eth' }),
1251
+ explorer: { type: 'ledger', explorerId: 'eth', batchSize: configuredBatchSize },
1252
+ })
1253
+ const request = jest
1254
+ .spyOn(axios, 'request')
1255
+ .mockResolvedValue({ data: { data: [], token: '' } })
1256
+
1257
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1258
+
1259
+ expect(request).toHaveBeenCalledWith(
1260
+ expect.objectContaining({
1261
+ params: expect.objectContaining({ batch_size: expectedBatchSize }),
1262
+ })
1263
+ )
1264
+ })
1265
+
1266
+ it('requests from_height: 0 by default and the given fromBlock otherwise', async () => {
1267
+ const request = jest
1268
+ .spyOn(axios, 'request')
1269
+ .mockResolvedValue({ data: { data: [], token: '' } })
1270
+
1271
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1272
+ expect(request).toHaveBeenCalledWith(
1273
+ expect.objectContaining({ params: expect.objectContaining({ from_height: 0 }) })
1274
+ )
1275
+
1276
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR, 42)
1277
+ expect(request).toHaveBeenCalledWith(
1278
+ expect.objectContaining({ params: expect.objectContaining({ from_height: 42 }) })
1279
+ )
1280
+ })
1281
+
1282
+ it('issues exactly one request per page and stops on a falsy token', async () => {
1283
+ const request = jest.spyOn(axios, 'request').mockImplementation(async ({ params }) => {
1284
+ if (params.token === null) return { data: { data: [discoveryRecord([])], token: 'p2' } }
1285
+ if (params.token === 'p2') return { data: { data: [discoveryRecord([])], token: '' } }
1286
+ throw new Error('should not be called again')
1287
+ })
1288
+
1289
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1290
+
1291
+ expect(request).toHaveBeenCalledTimes(2)
1292
+ })
1293
+
1294
+ it('stops when an empty page still carries a token', async () => {
1295
+ const request = jest.spyOn(axios, 'request').mockImplementation(async ({ params }) => {
1296
+ if (params.token === null) return { data: { data: [], token: 'p2' } }
1297
+ throw new Error('should not be called again')
1298
+ })
1299
+
1300
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1301
+
1302
+ expect(request).toHaveBeenCalledTimes(1)
1303
+ })
1304
+
1305
+ it('stops when the explorer returns the same token twice (cycling cursor guard)', async () => {
1306
+ const request = jest.spyOn(axios, 'request').mockImplementation(async ({ params }) => {
1307
+ if (params.token === null) return { data: { data: [discoveryRecord([])], token: 'p2' } }
1308
+ if (params.token === 'p2') return { data: { data: [discoveryRecord([])], token: 'p2' } }
1309
+ throw new Error('should not be called again')
1310
+ })
1311
+
1312
+ await LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1313
+
1314
+ expect(request).toHaveBeenCalledTimes(2)
1315
+ })
1316
+
1317
+ it('propagates after DEFAULT_RETRIES_API attempts on a page that keeps failing, without returning a partial list', async () => {
1318
+ const request = jest.spyOn(axios, 'request').mockRejectedValue(new Error('network error'))
1319
+
1320
+ await expect(LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)).rejects.toThrow(
1321
+ 'network error'
1322
+ )
1323
+
1324
+ expect(request).toHaveBeenCalledTimes(LEDGER_API.DEFAULT_RETRIES_API + 1)
1325
+ })
1326
+
1327
+ it('returns a list whose length is the distinct-contract count, independent of the number of pages walked', async () => {
1328
+ const runWith = async (nPages: number): Promise<unknown[]> => {
1329
+ const pages = Array.from({ length: nPages }, () =>
1330
+ discoveryRecord([{ contract: CONTRACT_1, from: ADDR, to: THIRD_PARTY_A }])
1331
+ )
1332
+ let call = 0
1333
+ jest.spyOn(axios, 'request').mockImplementation(async () => {
1334
+ const page = pages[call]
1335
+ call += 1
1336
+ return { data: { data: [page], token: call < pages.length ? `p${call}` : '' } }
1337
+ })
1338
+ return LEDGER_API.discoverTokenAssets(config, 'ethereum', ADDR)
1339
+ }
1340
+
1341
+ const smallWalk = await runWith(2)
1342
+ const largeWalk = await runWith(50)
1343
+
1344
+ expect(smallWalk).toHaveLength(1)
1345
+ expect(largeWalk).toHaveLength(1)
1346
+ expect(smallWalk).toEqual(largeWalk)
1347
+ })
1348
+ })
620
1349
  })
621
1350
  })