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