@mento-protocol/mento-sdk 3.2.7-beta.0 → 3.2.7

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 (302) hide show
  1. package/package.json +1 -1
  2. package/dist/cache/routes.d.ts +0 -13
  3. package/dist/cache/routes.js +0 -14649
  4. package/dist/cache/tokens.d.ts +0 -68
  5. package/dist/cache/tokens.js +0 -488
  6. package/dist/core/abis/activePool.d.ts +0 -2
  7. package/dist/core/abis/activePool.js +0 -14
  8. package/dist/core/abis/addressesRegistry.d.ts +0 -2
  9. package/dist/core/abis/addressesRegistry.js +0 -26
  10. package/dist/core/abis/bipoolmanager.d.ts +0 -34
  11. package/dist/core/abis/bipoolmanager.js +0 -72
  12. package/dist/core/abis/borrowerOperations.d.ts +0 -9
  13. package/dist/core/abis/borrowerOperations.js +0 -89
  14. package/dist/core/abis/breakerbox.d.ts +0 -13
  15. package/dist/core/abis/breakerbox.js +0 -8
  16. package/dist/core/abis/broker.d.ts +0 -2
  17. package/dist/core/abis/broker.js +0 -9
  18. package/dist/core/abis/erc20.d.ts +0 -9
  19. package/dist/core/abis/erc20.js +0 -21
  20. package/dist/core/abis/fpmm.d.ts +0 -270
  21. package/dist/core/abis/fpmm.js +0 -49
  22. package/dist/core/abis/fpmmFactory.d.ts +0 -85
  23. package/dist/core/abis/fpmmFactory.js +0 -26
  24. package/dist/core/abis/hintHelpers.d.ts +0 -2
  25. package/dist/core/abis/hintHelpers.js +0 -14
  26. package/dist/core/abis/index.d.ts +0 -22
  27. package/dist/core/abis/index.js +0 -38
  28. package/dist/core/abis/liquidityStrategy.d.ts +0 -132
  29. package/dist/core/abis/liquidityStrategy.js +0 -10
  30. package/dist/core/abis/multiTroveGetter.d.ts +0 -8
  31. package/dist/core/abis/multiTroveGetter.js +0 -15
  32. package/dist/core/abis/priceFeed.d.ts +0 -7
  33. package/dist/core/abis/priceFeed.js +0 -16
  34. package/dist/core/abis/pricingmodule.d.ts +0 -2
  35. package/dist/core/abis/pricingmodule.js +0 -6
  36. package/dist/core/abis/reserve.d.ts +0 -3
  37. package/dist/core/abis/reserve.js +0 -18
  38. package/dist/core/abis/router.d.ts +0 -521
  39. package/dist/core/abis/router.js +0 -45
  40. package/dist/core/abis/sortedTroves.d.ts +0 -2
  41. package/dist/core/abis/sortedTroves.js +0 -15
  42. package/dist/core/abis/systemParams.d.ts +0 -2
  43. package/dist/core/abis/systemParams.js +0 -14
  44. package/dist/core/abis/troveManager.d.ts +0 -2
  45. package/dist/core/abis/troveManager.js +0 -27
  46. package/dist/core/abis/troveNFT.d.ts +0 -2
  47. package/dist/core/abis/troveNFT.js +0 -9
  48. package/dist/core/abis/virtualPool.d.ts +0 -50
  49. package/dist/core/abis/virtualPool.js +0 -11
  50. package/dist/core/abis/virtualPoolFactory.d.ts +0 -59
  51. package/dist/core/abis/virtualPoolFactory.js +0 -17
  52. package/dist/core/constants/addresses.d.ts +0 -18
  53. package/dist/core/constants/addresses.js +0 -113
  54. package/dist/core/constants/borrowConstants.d.ts +0 -10
  55. package/dist/core/constants/borrowConstants.js +0 -16
  56. package/dist/core/constants/borrowRegistries.d.ts +0 -7
  57. package/dist/core/constants/borrowRegistries.js +0 -34
  58. package/dist/core/constants/chainId.d.ts +0 -7
  59. package/dist/core/constants/chainId.js +0 -11
  60. package/dist/core/constants/contractNames.d.ts +0 -21
  61. package/dist/core/constants/contractNames.js +0 -24
  62. package/dist/core/constants/index.d.ts +0 -6
  63. package/dist/core/constants/index.js +0 -22
  64. package/dist/core/errors/base.d.ts +0 -8
  65. package/dist/core/errors/base.js +0 -17
  66. package/dist/core/errors/index.d.ts +0 -4
  67. package/dist/core/errors/index.js +0 -20
  68. package/dist/core/errors/oracle.d.ts +0 -9
  69. package/dist/core/errors/oracle.js +0 -15
  70. package/dist/core/errors/router.d.ts +0 -14
  71. package/dist/core/errors/router.js +0 -24
  72. package/dist/core/types/borrow.d.ts +0 -87
  73. package/dist/core/types/borrow.js +0 -3
  74. package/dist/core/types/contractAddresses.d.ts +0 -42
  75. package/dist/core/types/contractAddresses.js +0 -3
  76. package/dist/core/types/index.d.ts +0 -10
  77. package/dist/core/types/index.js +0 -26
  78. package/dist/core/types/liquidity.d.ts +0 -194
  79. package/dist/core/types/liquidity.js +0 -3
  80. package/dist/core/types/pool.d.ts +0 -208
  81. package/dist/core/types/pool.js +0 -14
  82. package/dist/core/types/provider.d.ts +0 -45
  83. package/dist/core/types/provider.js +0 -3
  84. package/dist/core/types/route.d.ts +0 -62
  85. package/dist/core/types/route.js +0 -3
  86. package/dist/core/types/token.d.ts +0 -21
  87. package/dist/core/types/token.js +0 -3
  88. package/dist/core/types/tradingLimits.d.ts +0 -91
  89. package/dist/core/types/tradingLimits.js +0 -3
  90. package/dist/core/types/tradingMode.d.ts +0 -24
  91. package/dist/core/types/tradingMode.js +0 -31
  92. package/dist/core/types/transaction.d.ts +0 -45
  93. package/dist/core/types/transaction.js +0 -3
  94. package/dist/esm/cache/routes.js +0 -14644
  95. package/dist/esm/cache/tokens.js +0 -480
  96. package/dist/esm/core/abis/activePool.js +0 -10
  97. package/dist/esm/core/abis/addressesRegistry.js +0 -22
  98. package/dist/esm/core/abis/bipoolmanager.js +0 -68
  99. package/dist/esm/core/abis/borrowerOperations.js +0 -85
  100. package/dist/esm/core/abis/breakerbox.js +0 -4
  101. package/dist/esm/core/abis/broker.js +0 -5
  102. package/dist/esm/core/abis/erc20.js +0 -17
  103. package/dist/esm/core/abis/fpmm.js +0 -45
  104. package/dist/esm/core/abis/fpmmFactory.js +0 -22
  105. package/dist/esm/core/abis/hintHelpers.js +0 -10
  106. package/dist/esm/core/abis/index.js +0 -21
  107. package/dist/esm/core/abis/liquidityStrategy.js +0 -6
  108. package/dist/esm/core/abis/multiTroveGetter.js +0 -11
  109. package/dist/esm/core/abis/priceFeed.js +0 -12
  110. package/dist/esm/core/abis/pricingmodule.js +0 -2
  111. package/dist/esm/core/abis/reserve.js +0 -14
  112. package/dist/esm/core/abis/router.js +0 -41
  113. package/dist/esm/core/abis/sortedTroves.js +0 -11
  114. package/dist/esm/core/abis/systemParams.js +0 -10
  115. package/dist/esm/core/abis/troveManager.js +0 -23
  116. package/dist/esm/core/abis/troveNFT.js +0 -5
  117. package/dist/esm/core/abis/virtualPool.js +0 -7
  118. package/dist/esm/core/abis/virtualPoolFactory.js +0 -13
  119. package/dist/esm/core/constants/addresses.js +0 -107
  120. package/dist/esm/core/constants/borrowConstants.js +0 -12
  121. package/dist/esm/core/constants/borrowRegistries.js +0 -29
  122. package/dist/esm/core/constants/chainId.js +0 -7
  123. package/dist/esm/core/constants/contractNames.js +0 -20
  124. package/dist/esm/core/constants/index.js +0 -5
  125. package/dist/esm/core/errors/base.js +0 -12
  126. package/dist/esm/core/errors/index.js +0 -3
  127. package/dist/esm/core/errors/oracle.js +0 -10
  128. package/dist/esm/core/errors/router.js +0 -18
  129. package/dist/esm/core/types/borrow.js +0 -1
  130. package/dist/esm/core/types/contractAddresses.js +0 -1
  131. package/dist/esm/core/types/index.js +0 -9
  132. package/dist/esm/core/types/liquidity.js +0 -1
  133. package/dist/esm/core/types/pool.js +0 -10
  134. package/dist/esm/core/types/provider.js +0 -1
  135. package/dist/esm/core/types/route.js +0 -1
  136. package/dist/esm/core/types/token.js +0 -1
  137. package/dist/esm/core/types/tradingLimits.js +0 -1
  138. package/dist/esm/core/types/tradingMode.js +0 -26
  139. package/dist/esm/core/types/transaction.js +0 -1
  140. package/dist/esm/index.js +0 -139
  141. package/dist/esm/package.json +0 -1
  142. package/dist/esm/services/borrow/BorrowService.js +0 -455
  143. package/dist/esm/services/borrow/borrowHelpers.js +0 -3
  144. package/dist/esm/services/borrow/borrowMath.js +0 -127
  145. package/dist/esm/services/borrow/index.js +0 -3
  146. package/dist/esm/services/borrow/internal/borrowApprovalService.js +0 -48
  147. package/dist/esm/services/borrow/internal/borrowContextStore.js +0 -35
  148. package/dist/esm/services/borrow/internal/borrowErc20.js +0 -38
  149. package/dist/esm/services/borrow/internal/borrowHints.js +0 -27
  150. package/dist/esm/services/borrow/internal/borrowPositionParser.js +0 -82
  151. package/dist/esm/services/borrow/internal/borrowReadService.js +0 -271
  152. package/dist/esm/services/borrow/internal/borrowRegistryReader.js +0 -108
  153. package/dist/esm/services/borrow/internal/borrowTransactionService.js +0 -271
  154. package/dist/esm/services/borrow/internal/borrowTypes.js +0 -1
  155. package/dist/esm/services/borrow/internal/borrowValidation.js +0 -89
  156. package/dist/esm/services/index.js +0 -8
  157. package/dist/esm/services/liquidity/LiquidityService.js +0 -163
  158. package/dist/esm/services/liquidity/basicLiquidity.js +0 -162
  159. package/dist/esm/services/liquidity/index.js +0 -1
  160. package/dist/esm/services/liquidity/liquidityHelpers.js +0 -95
  161. package/dist/esm/services/liquidity/rebalance.js +0 -59
  162. package/dist/esm/services/liquidity/zapHelpers.js +0 -181
  163. package/dist/esm/services/liquidity/zapIn.js +0 -131
  164. package/dist/esm/services/liquidity/zapOut.js +0 -248
  165. package/dist/esm/services/pools/PoolService.js +0 -204
  166. package/dist/esm/services/pools/index.js +0 -1
  167. package/dist/esm/services/pools/poolDetails.js +0 -209
  168. package/dist/esm/services/pools/poolDiscovery.js +0 -112
  169. package/dist/esm/services/pools/rebalancePreview.js +0 -181
  170. package/dist/esm/services/quotes/QuoteService.js +0 -85
  171. package/dist/esm/services/quotes/index.js +0 -1
  172. package/dist/esm/services/routes/RouteService.js +0 -268
  173. package/dist/esm/services/routes/index.js +0 -1
  174. package/dist/esm/services/swap/SwapService.js +0 -247
  175. package/dist/esm/services/swap/index.js +0 -1
  176. package/dist/esm/services/tokens/index.js +0 -1
  177. package/dist/esm/services/tokens/tokenService.js +0 -285
  178. package/dist/esm/services/trading/TradingLimitsService.js +0 -154
  179. package/dist/esm/services/trading/TradingService.js +0 -222
  180. package/dist/esm/services/trading/index.js +0 -2
  181. package/dist/esm/utils/chainConfig.js +0 -118
  182. package/dist/esm/utils/costUtils.js +0 -56
  183. package/dist/esm/utils/deadline.js +0 -22
  184. package/dist/esm/utils/index.js +0 -9
  185. package/dist/esm/utils/multicall.js +0 -47
  186. package/dist/esm/utils/pathEncoder.js +0 -69
  187. package/dist/esm/utils/rateFeed.js +0 -23
  188. package/dist/esm/utils/retry.js +0 -24
  189. package/dist/esm/utils/routeUtils.js +0 -361
  190. package/dist/esm/utils/routes.js +0 -2
  191. package/dist/esm/utils/sortUtils.js +0 -33
  192. package/dist/esm/utils/tokens.js +0 -2
  193. package/dist/esm/utils/tradingLimits.js +0 -163
  194. package/dist/esm/utils/validation.js +0 -30
  195. package/dist/index.d.ts +0 -101
  196. package/dist/index.js +0 -158
  197. package/dist/services/borrow/BorrowService.d.ts +0 -381
  198. package/dist/services/borrow/BorrowService.js +0 -460
  199. package/dist/services/borrow/borrowHelpers.d.ts +0 -4
  200. package/dist/services/borrow/borrowHelpers.js +0 -13
  201. package/dist/services/borrow/borrowMath.d.ts +0 -21
  202. package/dist/services/borrow/borrowMath.js +0 -137
  203. package/dist/services/borrow/index.d.ts +0 -4
  204. package/dist/services/borrow/index.js +0 -20
  205. package/dist/services/borrow/internal/borrowApprovalService.d.ts +0 -14
  206. package/dist/services/borrow/internal/borrowApprovalService.js +0 -53
  207. package/dist/services/borrow/internal/borrowContextStore.d.ts +0 -11
  208. package/dist/services/borrow/internal/borrowContextStore.js +0 -40
  209. package/dist/services/borrow/internal/borrowErc20.d.ts +0 -5
  210. package/dist/services/borrow/internal/borrowErc20.js +0 -43
  211. package/dist/services/borrow/internal/borrowHints.d.ts +0 -7
  212. package/dist/services/borrow/internal/borrowHints.js +0 -31
  213. package/dist/services/borrow/internal/borrowPositionParser.d.ts +0 -4
  214. package/dist/services/borrow/internal/borrowPositionParser.js +0 -87
  215. package/dist/services/borrow/internal/borrowReadService.d.ts +0 -31
  216. package/dist/services/borrow/internal/borrowReadService.js +0 -276
  217. package/dist/services/borrow/internal/borrowRegistryReader.d.ts +0 -5
  218. package/dist/services/borrow/internal/borrowRegistryReader.js +0 -113
  219. package/dist/services/borrow/internal/borrowTransactionService.d.ts +0 -23
  220. package/dist/services/borrow/internal/borrowTransactionService.js +0 -276
  221. package/dist/services/borrow/internal/borrowTypes.d.ts +0 -15
  222. package/dist/services/borrow/internal/borrowTypes.js +0 -3
  223. package/dist/services/borrow/internal/borrowValidation.d.ts +0 -14
  224. package/dist/services/borrow/internal/borrowValidation.js +0 -104
  225. package/dist/services/index.d.ts +0 -9
  226. package/dist/services/index.js +0 -25
  227. package/dist/services/liquidity/LiquidityService.d.ts +0 -139
  228. package/dist/services/liquidity/LiquidityService.js +0 -168
  229. package/dist/services/liquidity/basicLiquidity.d.ts +0 -11
  230. package/dist/services/liquidity/basicLiquidity.js +0 -172
  231. package/dist/services/liquidity/index.d.ts +0 -2
  232. package/dist/services/liquidity/index.js +0 -18
  233. package/dist/services/liquidity/liquidityHelpers.d.ts +0 -19
  234. package/dist/services/liquidity/liquidityHelpers.js +0 -104
  235. package/dist/services/liquidity/rebalance.d.ts +0 -6
  236. package/dist/services/liquidity/rebalance.js +0 -64
  237. package/dist/services/liquidity/zapHelpers.d.ts +0 -100
  238. package/dist/services/liquidity/zapHelpers.js +0 -192
  239. package/dist/services/liquidity/zapIn.d.ts +0 -18
  240. package/dist/services/liquidity/zapIn.js +0 -138
  241. package/dist/services/liquidity/zapOut.d.ts +0 -9
  242. package/dist/services/liquidity/zapOut.js +0 -255
  243. package/dist/services/pools/PoolService.d.ts +0 -69
  244. package/dist/services/pools/PoolService.js +0 -209
  245. package/dist/services/pools/index.d.ts +0 -2
  246. package/dist/services/pools/index.js +0 -18
  247. package/dist/services/pools/poolDetails.d.ts +0 -13
  248. package/dist/services/pools/poolDetails.js +0 -216
  249. package/dist/services/pools/poolDiscovery.d.ts +0 -12
  250. package/dist/services/pools/poolDiscovery.js +0 -117
  251. package/dist/services/pools/rebalancePreview.d.ts +0 -5
  252. package/dist/services/pools/rebalancePreview.js +0 -186
  253. package/dist/services/quotes/QuoteService.d.ts +0 -51
  254. package/dist/services/quotes/QuoteService.js +0 -91
  255. package/dist/services/quotes/index.d.ts +0 -2
  256. package/dist/services/quotes/index.js +0 -18
  257. package/dist/services/routes/RouteService.d.ts +0 -117
  258. package/dist/services/routes/RouteService.js +0 -306
  259. package/dist/services/routes/index.d.ts +0 -2
  260. package/dist/services/routes/index.js +0 -18
  261. package/dist/services/swap/SwapService.d.ts +0 -198
  262. package/dist/services/swap/SwapService.js +0 -252
  263. package/dist/services/swap/index.d.ts +0 -2
  264. package/dist/services/swap/index.js +0 -18
  265. package/dist/services/tokens/index.d.ts +0 -2
  266. package/dist/services/tokens/index.js +0 -18
  267. package/dist/services/tokens/tokenService.d.ts +0 -55
  268. package/dist/services/tokens/tokenService.js +0 -290
  269. package/dist/services/trading/TradingLimitsService.d.ts +0 -38
  270. package/dist/services/trading/TradingLimitsService.js +0 -159
  271. package/dist/services/trading/TradingService.d.ts +0 -115
  272. package/dist/services/trading/TradingService.js +0 -227
  273. package/dist/services/trading/index.d.ts +0 -3
  274. package/dist/services/trading/index.js +0 -19
  275. package/dist/utils/chainConfig.d.ts +0 -16
  276. package/dist/utils/chainConfig.js +0 -123
  277. package/dist/utils/costUtils.d.ts +0 -12
  278. package/dist/utils/costUtils.js +0 -60
  279. package/dist/utils/deadline.d.ts +0 -21
  280. package/dist/utils/deadline.js +0 -26
  281. package/dist/utils/index.d.ts +0 -10
  282. package/dist/utils/index.js +0 -26
  283. package/dist/utils/multicall.d.ts +0 -30
  284. package/dist/utils/multicall.js +0 -52
  285. package/dist/utils/pathEncoder.d.ts +0 -34
  286. package/dist/utils/pathEncoder.js +0 -73
  287. package/dist/utils/rateFeed.d.ts +0 -18
  288. package/dist/utils/rateFeed.js +0 -27
  289. package/dist/utils/retry.d.ts +0 -12
  290. package/dist/utils/retry.js +0 -28
  291. package/dist/utils/routeUtils.d.ts +0 -295
  292. package/dist/utils/routeUtils.js +0 -371
  293. package/dist/utils/routes.d.ts +0 -3
  294. package/dist/utils/routes.js +0 -8
  295. package/dist/utils/sortUtils.d.ts +0 -24
  296. package/dist/utils/sortUtils.js +0 -39
  297. package/dist/utils/tokens.d.ts +0 -2
  298. package/dist/utils/tokens.js +0 -13
  299. package/dist/utils/tradingLimits.d.ts +0 -41
  300. package/dist/utils/tradingLimits.js +0 -171
  301. package/dist/utils/validation.d.ts +0 -19
  302. package/dist/utils/validation.js +0 -34
@@ -1,295 +0,0 @@
1
- import type { Route, RouteID, RouteWithCost, Pool } from '../core/types';
2
- type TokenSymbol = string;
3
- type Address = string;
4
- /**
5
- * =============================================================================
6
- * ROUTE GENERATION UTILITIES
7
- * =============================================================================
8
- *
9
- * Utilities for generating optimal trading routes in the Mento protocol.
10
- *
11
- * The main workflow is:
12
- *
13
- * 1. Build connectivity structures from direct trading pairs
14
- * 2. Generate all possible routes (direct + two-hop)
15
- * 3. Select optimal routes using cost data or heuristics
16
- *
17
- * ALGORITHM OVERVIEW:
18
- * - Creates a graph where tokens are nodes and direct exchanges are edges
19
- * - Uses graph traversal to find two-hop routes through intermediate tokens
20
- * - Optimizes route selection based on cost data when available
21
- * - Falls back to heuristics (prefer direct routes, major stablecoins)
22
- * =============================================================================
23
- */
24
- /**
25
- * Connectivity data structure that represents the token graph connecting all tokens.
26
- * Helps to efficiently answer: "How can I trade from token A to token B?"
27
- *
28
- * CONCRETE EXAMPLE:
29
- * Given these direct trading pairs:
30
- * - USDm ↔ CELO (direct exchange exists)
31
- * - CELO ↔ EURm (direct exchange exists)
32
- * - USDm ↔ BRLm (direct exchange exists)
33
- *
34
- * How route finding works:
35
- * - Direct route: USDm → EURm? Check token graph: USDm connects to [CELO, BRLm], none is EURm → No direct route
36
- * - Two-hop route: USDm → ? → EURm?
37
- * - USDm connects to CELO, CELO connects to EURm → Found route: USDm → CELO → EURm
38
- * - USDm connects to BRLm, BRLm connects to [USDm] → No route via BRLm
39
- *
40
- * The "connectivity" part means we can quickly traverse the network of
41
- * token connections to find all possible trading paths.
42
- */
43
- export interface ConnectivityData {
44
- /** Maps token address to symbol for efficient lookups
45
- *
46
- * ```
47
- * '0x765D...' → 'USDm'
48
- * '0x471E...' → 'CELO'
49
- * '0xD876...' → 'EURm'
50
- * ```
51
- */
52
- addrToSymbol: Map<Address, TokenSymbol>;
53
- /** Adjacency list mapping which tokens connect to which
54
- * Used for finding two-hop routes by traversing token → neighbor → neighbor.
55
- *
56
- * Example for a USDm => EURm swap: First we find USDm → [CELO, KESm, ...]
57
- * Then we find CELO → [USDm, EURm, ...] = found route via USDm → CELO → EURm
58
- *
59
- * ```
60
- * 'USDm_addr' → Set(['CELO_addr', 'KESm_addr']) // USDm connects to CELO and KESm
61
- * 'CELO_addr' → Set(['USDm_addr', 'EURm_addr']) // CELO connects to USDm and EURm
62
- * 'EURm_addr' → Set(['CELO_addr']) // EURm connects to CELO
63
- * 'KESm_addr' → Set(['USDm_addr']) // KESm connects to USDm
64
- * ```
65
- */
66
- tokenGraph: Map<Address, Set<Address>>;
67
- /** Maps sorted token address pairs to their direct route details
68
- * ```
69
- * 'CELO_addr-EURm_addr' → { route details for CELO ↔ EURm }
70
- * 'CELO_addr-USDm_addr' → { route details for CELO ↔ USDm }
71
- * 'USDm_addr-KESm_addr' → { route details for USDm ↔ KESm }
72
- * ```
73
- */
74
- directRouteMap: Map<RouteID, Pool>;
75
- /** Original direct routes from mento.getDirectRoutes() for reference */
76
- directRoutes: Route[];
77
- }
78
- /**
79
- * Builds the connectivity data structures needed for route generation.
80
- *
81
- * Transforms a list of direct trading pairs into our ConnectivityData
82
- * that allow us to quickly find trading routes.
83
- *
84
- * **Construction Process:**
85
- *
86
- * ```
87
- * Input: TradablePairs = [
88
- * { id: 'USDm-CELO', assets: [USDm, CELO], path: [exchange1_CELO_USDm] },
89
- * { id: 'CELO-EURm', assets: [CELO, EURm], path: [exchange2_CELO_EURm] }
90
- * ]
91
- *
92
- * Step 1 - Build addrToSymbol map:
93
- * USDm.address → 'USDm'
94
- * CELO.address → 'CELO'
95
- * EURm.address → 'EURm'
96
- *
97
- * Step 2 - Build directPathMap (sorted alphabetically for consistency):
98
- * 'CELO_addr-EURm_addr' → exchange2_CELO_EURm
99
- * 'CELO_addr-USDm_addr' → exchange1_CELO_USDm
100
- *
101
- * Step 3 - Build bidirectional tokenGraph:
102
- * USDm.address → Set([CELO.address])
103
- * CELO.address → Set([USDm.address, EURm.address])
104
- * EURm.address → Set([CELO.address])
105
- * ```
106
- *
107
- * **Result**: We can now efficiently answer:
108
- * - "What's the symbol for address X?" → addrToSymbol.get(addr)
109
- * - "What exchange connects tokens X and Y?" → directPathMap.get(sortedAddressPairKey)
110
- * - "What tokens can I reach from token X?" → tokenGraph.get(X)
111
- *
112
- * @param directRoutes - Array of direct trading pairs
113
- * @returns Connectivity data structure for efficient route generation
114
- *
115
- * @example
116
- * ```typescript
117
- * const directPairs = [
118
- * { id: 'USDm-CELO', assets: [USDm, CELO], path: [exchange1] },
119
- * { id: 'CELO-EURm', assets: [CELO, EURm], path: [exchange2] }
120
- * ]
121
- *
122
- * const connectivityData = buildConnectivityStructures(directPairs)
123
- *
124
- * // Now we can efficiently find routes:
125
- * // 1. Check if USDm connects to anything: connectivityData.tokenGraph.get(USDm.address) → [CELO.address]
126
- * // 2. Check if CELO connects to EURm: connectivityData.tokenGraph.get(CELO.address) → [USDm.address, EURm.address] ✓
127
- * // 3. Get exchange details: connectivityData.directPathMap.get('CELO_addr-EURm_addr') → exchange2_CELO_EURm
128
- * // Result: Found route USDm → CELO → EURm with exchange details
129
- * ```
130
- */
131
- export declare function buildConnectivityStructures(directRoutes: Route[]): ConnectivityData;
132
- /**
133
- * Generates all possible routes (direct + two-hop) using connectivity data.
134
- *
135
- * This function implements a route discovery algorithm that:
136
- *
137
- * 1. **Adds all direct routes** (single-hop routes)
138
- * 2. **Discovers two-hop routes** using graph traversal:
139
- * - For each token A, find its neighbors (tokens directly connected)
140
- * - For each neighbor B, find B's neighbors
141
- * - If B connects to token C (C ≠ A), then A->B->C is a valid route
142
- *
143
- * **Route Deduplication**: Multiple routes between the same token pair
144
- * are collected in arrays, allowing the selection algorithm to choose
145
- * the best one based on cost data or heuristics.
146
- *
147
- * **Canonical Route IDs**: All routes use alphabetically sorted symbols
148
- * (e.g., 'EURm-USDm' not 'USDm-EURm') for consistent identification.
149
- *
150
- * @param connectivityData - The connectivity data from buildConnectivityStructures()
151
- * @returns Map of route ID -> array of possible routes for that token pair
152
- *
153
- * @example
154
- * ```typescript
155
- * // Given direct routes: USDm-CELO, CELO-EURm, USDm-USDC
156
- * const allRoutes = generateAllRoutes(connectivityData)
157
- *
158
- * // Results might include:
159
- * // 'USDm-CELO' -> [{ path: [USDm->CELO] }] // direct route
160
- * // 'EURm-USDm' -> [
161
- * // { path: [USDm->USDC, USDC->EURm] } // two-hop via USDC
162
- * // { path: [USDm->CELO, CELO->EURm] } // two-hop via CELO
163
- * // ]
164
- * ```
165
- */
166
- export declare function generateAllRoutes(connectivityData: ConnectivityData): Map<RouteID, Route[]>;
167
- /**
168
- * Creates a two-hop tradable pair if valid exchange hops exist.
169
- *
170
- * 1. **Validates tokens exist** in the asset map
171
- * 2. **Finds exchange hops** for both segments of the route
172
- * 3. **Creates canonical pair structure** with sorted symbols
173
- *
174
- * **Route Structure**: The resulting pair represents trading from start->end
175
- * via intermediate token, but the assets are ordered alphabetically by symbol
176
- * for consistency (canonical form).
177
- *
178
- * **Path Representation**: The path array contains the actual exchange hops
179
- * needed to execute the trade, preserving the routing information.
180
- *
181
- * @param startToken - Starting token address
182
- * @param intermediate - Intermediate token address for routing
183
- * @param end - Destination token address
184
- * @param assetMap - Map of token address -> Asset details
185
- * @param directPathMap - Map of token pairs -> exchange hop details
186
- * @returns Route if valid route exists, null otherwise
187
- *
188
- * @example
189
- * ```typescript
190
- * // Create route: USDm -> CELO -> EURm
191
- * const pair = createTwoHopPair(
192
- * '0x765D...', // USDm address
193
- * '0x471E...', // CELO address
194
- * '0xD876...', // EURm address
195
- * addrToSymbol,
196
- * directPathMap
197
- * )
198
- *
199
- * // Result:
200
- * // {
201
- * // id: 'EURm-USDm', // alphabetical order
202
- * // assets: [EURm, USDm], // alphabetical order
203
- * // path: [ // actual routing path
204
- * // { USDm->CELO exchange },
205
- * // { CELO->EURm exchange }
206
- * // ]
207
- * // }
208
- * ```
209
- */
210
- export declare function createTwoHopRoute(startAddr: Address, intermediateAddr: Address, endAddr: Address, addrToSymbol: Map<Address, TokenSymbol>, directRouteMap: Map<RouteID, Pool>): Route | null;
211
- /**
212
- * Selects optimal routes from all candidates based on spread data or heuristics.
213
- *
214
- * This is the route optimization engine that implements the following logic:
215
- *
216
- * **For Single Route**: Use it directly (no optimization needed)
217
- *
218
- * **For Multiple Routes**:
219
- * - If `returnAllRoutes=true`: Return all routes (used for cache generation)
220
- * - If `returnAllRoutes=false`: Apply optimization to select the best route
221
- *
222
- * **Route Selection Strategy**: Delegates to `selectBestRoute()` which uses
223
- * a multi-tier approach prioritizing cost efficiency and reliability.
224
- *
225
- * @param allRoutes - Map of pair ID -> array of possible routes
226
- * @param returnAllRoutes - Whether to return all routes or optimize selection
227
- * @param assetMap - Asset map for token symbol lookups during optimization
228
- * @returns Array of selected optimal routes
229
- *
230
- * @example
231
- * ```typescript
232
- * // Multiple routes for USDm-EURm pair
233
- * const candidates = new Map([
234
- * ['EURm-USDm', [
235
- * { path: [USDm->CELO->EURm], costData: { totalCostPercent: 0.5 } },
236
- * { path: [USDm->BRLm->EURm], costData: { totalCostPercent: 0.3 } },
237
- * { path: [USDm->EURm] } // direct route, no cost data
238
- * ]]
239
- * ])
240
- *
241
- * const optimal = selectOptimalRoutes(candidates, false, assetMap)
242
- * // Returns the USDm->BRLm->EURm route (lowest cost: 0.3%)
243
- * ```
244
- */
245
- export declare function selectOptimalRoutes(allRoutes: Map<RouteID, Route[]>, returnAllRoutes: boolean, addrToSymbol: Map<Address, TokenSymbol>): (Route | RouteWithCost)[];
246
- /**
247
- * Selects the best route from candidates using cost data or fallback heuristics.
248
- *
249
- * This function implements a sophisticated route selection algorithm with
250
- * multiple optimization tiers:
251
- *
252
- * **Tier 1 - Cost-Based Optimization** (Preferred):
253
- * - Use routes with cost data (actual cost information)
254
- * - Select route with lowest `totalCostPercent`
255
- * - This provides the most cost-efficient trading
256
- *
257
- * **Tier 2 - Direct Route Preference** (Fallback):
258
- * - If no cost data available, prefer direct (single-hop) routes
259
- * - Direct routes have lower execution risk and gas costs
260
- *
261
- * **Tier 3 - Major Stablecoin Preference** (Final Fallback):
262
- * - For two-hop routes, prefer those going through major stablecoins
263
- * - Major FX currencies like USDm and EURm typically have better liquidity
264
- *
265
- * **Tier 4 - First Available** (Last Resort):
266
- * - If no other heuristics apply, use the first route found
267
- *
268
- * @param candidates - Array of possible routes for the same token pair
269
- * @param assetMap - Asset map for token symbol lookups
270
- * @returns The optimal route selected using the tier system
271
- *
272
- * @example
273
- * ```typescript
274
- * const candidates = [
275
- * { path: [A->B->C], costData: { totalCostPercent: 0.8 } },
276
- * { path: [A->D->C], costData: { totalCostPercent: 0.4 } }, // Winner: lowest cost
277
- * { path: [A->C] }, // direct route, no cost data
278
- * ]
279
- *
280
- * const best = selectBestRoute(candidates, assetMap)
281
- * // Returns the A->D->C route (0.4% cost)
282
- * ```
283
- */
284
- export declare function selectBestRoute(candidates: Route[], addrToSymbol: Map<Address, TokenSymbol>): Route | RouteWithCost;
285
- /**
286
- * Extracts the intermediate token address from a two-hop route.
287
- * In a two-hop route A->B->C, this function finds token B (the intermediate).
288
- */
289
- export declare function getIntermediateToken(route: Route): Address | undefined;
290
- /**
291
- * Type guard to check if a Route has cost data.
292
- */
293
- export declare function hasCostData(pair: Route | RouteWithCost): pair is RouteWithCost;
294
- export {};
295
- //# sourceMappingURL=routeUtils.d.ts.map
@@ -1,371 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildConnectivityStructures = buildConnectivityStructures;
4
- exports.generateAllRoutes = generateAllRoutes;
5
- exports.createTwoHopRoute = createTwoHopRoute;
6
- exports.selectOptimalRoutes = selectOptimalRoutes;
7
- exports.selectBestRoute = selectBestRoute;
8
- exports.getIntermediateToken = getIntermediateToken;
9
- exports.hasCostData = hasCostData;
10
- const sortUtils_1 = require("./sortUtils");
11
- /**
12
- * Builds the connectivity data structures needed for route generation.
13
- *
14
- * Transforms a list of direct trading pairs into our ConnectivityData
15
- * that allow us to quickly find trading routes.
16
- *
17
- * **Construction Process:**
18
- *
19
- * ```
20
- * Input: TradablePairs = [
21
- * { id: 'USDm-CELO', assets: [USDm, CELO], path: [exchange1_CELO_USDm] },
22
- * { id: 'CELO-EURm', assets: [CELO, EURm], path: [exchange2_CELO_EURm] }
23
- * ]
24
- *
25
- * Step 1 - Build addrToSymbol map:
26
- * USDm.address → 'USDm'
27
- * CELO.address → 'CELO'
28
- * EURm.address → 'EURm'
29
- *
30
- * Step 2 - Build directPathMap (sorted alphabetically for consistency):
31
- * 'CELO_addr-EURm_addr' → exchange2_CELO_EURm
32
- * 'CELO_addr-USDm_addr' → exchange1_CELO_USDm
33
- *
34
- * Step 3 - Build bidirectional tokenGraph:
35
- * USDm.address → Set([CELO.address])
36
- * CELO.address → Set([USDm.address, EURm.address])
37
- * EURm.address → Set([CELO.address])
38
- * ```
39
- *
40
- * **Result**: We can now efficiently answer:
41
- * - "What's the symbol for address X?" → addrToSymbol.get(addr)
42
- * - "What exchange connects tokens X and Y?" → directPathMap.get(sortedAddressPairKey)
43
- * - "What tokens can I reach from token X?" → tokenGraph.get(X)
44
- *
45
- * @param directRoutes - Array of direct trading pairs
46
- * @returns Connectivity data structure for efficient route generation
47
- *
48
- * @example
49
- * ```typescript
50
- * const directPairs = [
51
- * { id: 'USDm-CELO', assets: [USDm, CELO], path: [exchange1] },
52
- * { id: 'CELO-EURm', assets: [CELO, EURm], path: [exchange2] }
53
- * ]
54
- *
55
- * const connectivityData = buildConnectivityStructures(directPairs)
56
- *
57
- * // Now we can efficiently find routes:
58
- * // 1. Check if USDm connects to anything: connectivityData.tokenGraph.get(USDm.address) → [CELO.address]
59
- * // 2. Check if CELO connects to EURm: connectivityData.tokenGraph.get(CELO.address) → [USDm.address, EURm.address] ✓
60
- * // 3. Get exchange details: connectivityData.directPathMap.get('CELO_addr-EURm_addr') → exchange2_CELO_EURm
61
- * // Result: Found route USDm → CELO → EURm with exchange details
62
- * ```
63
- */
64
- function buildConnectivityStructures(directRoutes) {
65
- const addrToSymbol = new Map();
66
- const directRouteMap = new Map();
67
- const tokenGraph = new Map();
68
- for (const route of directRoutes) {
69
- const [tokenA, tokenB] = route.tokens;
70
- // Build address-to-symbol map for quick symbol lookups
71
- addrToSymbol.set(tokenA.address, tokenA.symbol);
72
- addrToSymbol.set(tokenB.address, tokenB.symbol);
73
- // Build direct path map (sorted addresses as key for consistency)
74
- // for quick lookup of exchange details for any token pair
75
- const routeId = (0, sortUtils_1.canonicalSymbolKey)(tokenA.symbol, tokenB.symbol);
76
- if (!directRouteMap.has(routeId)) {
77
- directRouteMap.set(routeId, route.path[0]);
78
- }
79
- // Build bidirectional connectivity graph for route traversal
80
- // Each token can reach its directly connected tokens
81
- if (!tokenGraph.has(tokenA.address))
82
- tokenGraph.set(tokenA.address, new Set());
83
- if (!tokenGraph.has(tokenB.address))
84
- tokenGraph.set(tokenB.address, new Set());
85
- tokenGraph.get(tokenA.address).add(tokenB.address);
86
- tokenGraph.get(tokenB.address).add(tokenA.address);
87
- }
88
- return { addrToSymbol, directRouteMap, tokenGraph, directRoutes };
89
- }
90
- /**
91
- * Generates all possible routes (direct + two-hop) using connectivity data.
92
- *
93
- * This function implements a route discovery algorithm that:
94
- *
95
- * 1. **Adds all direct routes** (single-hop routes)
96
- * 2. **Discovers two-hop routes** using graph traversal:
97
- * - For each token A, find its neighbors (tokens directly connected)
98
- * - For each neighbor B, find B's neighbors
99
- * - If B connects to token C (C ≠ A), then A->B->C is a valid route
100
- *
101
- * **Route Deduplication**: Multiple routes between the same token pair
102
- * are collected in arrays, allowing the selection algorithm to choose
103
- * the best one based on cost data or heuristics.
104
- *
105
- * **Canonical Route IDs**: All routes use alphabetically sorted symbols
106
- * (e.g., 'EURm-USDm' not 'USDm-EURm') for consistent identification.
107
- *
108
- * @param connectivityData - The connectivity data from buildConnectivityStructures()
109
- * @returns Map of route ID -> array of possible routes for that token pair
110
- *
111
- * @example
112
- * ```typescript
113
- * // Given direct routes: USDm-CELO, CELO-EURm, USDm-USDC
114
- * const allRoutes = generateAllRoutes(connectivityData)
115
- *
116
- * // Results might include:
117
- * // 'USDm-CELO' -> [{ path: [USDm->CELO] }] // direct route
118
- * // 'EURm-USDm' -> [
119
- * // { path: [USDm->USDC, USDC->EURm] } // two-hop via USDC
120
- * // { path: [USDm->CELO, CELO->EURm] } // two-hop via CELO
121
- * // ]
122
- * ```
123
- */
124
- function generateAllRoutes(connectivityData) {
125
- const { addrToSymbol, directRouteMap, tokenGraph, directRoutes } = connectivityData;
126
- const allRoutes = new Map();
127
- // Step 1: Add all direct pairs (single-hop routes)
128
- for (const route of directRoutes) {
129
- if (!allRoutes.has(route.id)) {
130
- allRoutes.set(route.id, []);
131
- }
132
- allRoutes.get(route.id).push(route);
133
- }
134
- // Step 2: Generate two-hop routes using graph traversal
135
- // Algorithm: For each token, explore all paths of length 2
136
- // OUTER LOOP: "For each starting token..." (e.g., USDm, CELO, EURm, etc.)
137
- for (const [start, neighbors] of tokenGraph.entries()) {
138
- // MIDDLE LOOP: "Where can I go from the starting token?" (first hop)
139
- // Example: If start = USDm, neighbors might be [CELO, USDC, KESm]
140
- for (const intermediate of neighbors) {
141
- // Get all tokens reachable from this intermediate token (second hop destinations)
142
- const secondHopNeighbors = tokenGraph.get(intermediate);
143
- if (!secondHopNeighbors)
144
- continue;
145
- // INNER LOOP: "From the intermediate token, where can I go?" (second hop)
146
- // Example: If intermediate = CELO, secondHopNeighbors might be [USDm, EURm, BRLm]
147
- for (const end of secondHopNeighbors) {
148
- // Skip circular routes like USDm → CELO → USDm (pointless)
149
- if (end === start)
150
- continue;
151
- // At this point we have a potential route: start → intermediate → end
152
- // Example: USDm → CELO → EURm
153
- // Try to create a valid two-hop trading pair from this route
154
- const twoHopRoute = createTwoHopRoute(start, intermediate, end, addrToSymbol, directRouteMap);
155
- // If we successfully created the pair, add it to our collection
156
- if (twoHopRoute) {
157
- if (!allRoutes.has(twoHopRoute.id)) {
158
- allRoutes.set(twoHopRoute.id, []);
159
- }
160
- allRoutes.get(twoHopRoute.id).push(twoHopRoute);
161
- }
162
- }
163
- }
164
- }
165
- return allRoutes;
166
- }
167
- /**
168
- * Creates a two-hop tradable pair if valid exchange hops exist.
169
- *
170
- * 1. **Validates tokens exist** in the asset map
171
- * 2. **Finds exchange hops** for both segments of the route
172
- * 3. **Creates canonical pair structure** with sorted symbols
173
- *
174
- * **Route Structure**: The resulting pair represents trading from start->end
175
- * via intermediate token, but the assets are ordered alphabetically by symbol
176
- * for consistency (canonical form).
177
- *
178
- * **Path Representation**: The path array contains the actual exchange hops
179
- * needed to execute the trade, preserving the routing information.
180
- *
181
- * @param startToken - Starting token address
182
- * @param intermediate - Intermediate token address for routing
183
- * @param end - Destination token address
184
- * @param assetMap - Map of token address -> Asset details
185
- * @param directPathMap - Map of token pairs -> exchange hop details
186
- * @returns Route if valid route exists, null otherwise
187
- *
188
- * @example
189
- * ```typescript
190
- * // Create route: USDm -> CELO -> EURm
191
- * const pair = createTwoHopPair(
192
- * '0x765D...', // USDm address
193
- * '0x471E...', // CELO address
194
- * '0xD876...', // EURm address
195
- * addrToSymbol,
196
- * directPathMap
197
- * )
198
- *
199
- * // Result:
200
- * // {
201
- * // id: 'EURm-USDm', // alphabetical order
202
- * // assets: [EURm, USDm], // alphabetical order
203
- * // path: [ // actual routing path
204
- * // { USDm->CELO exchange },
205
- * // { CELO->EURm exchange }
206
- * // ]
207
- * // }
208
- * ```
209
- */
210
- function createTwoHopRoute(startAddr, intermediateAddr, endAddr, addrToSymbol, directRouteMap) {
211
- // Validate that both all tokens exist in our address-to-symbol map
212
- const startSymbol = addrToSymbol.get(startAddr);
213
- const intermediateSymbol = addrToSymbol.get(intermediateAddr);
214
- const endSymbol = addrToSymbol.get(endAddr);
215
- if (!startSymbol || !intermediateSymbol || !endSymbol)
216
- return null;
217
- // Find exchange hops for both segments of the two-hop route
218
- // Keys are sorted token addresses for consistent lookup
219
- const hop1Key = (0, sortUtils_1.canonicalSymbolKey)(startSymbol, intermediateSymbol);
220
- const hop2Key = (0, sortUtils_1.canonicalSymbolKey)(intermediateSymbol, endSymbol);
221
- const hop1 = directRouteMap.get(hop1Key);
222
- const hop2 = directRouteMap.get(hop2Key);
223
- // If either hop doesn't exist, this route is invalid
224
- if (!hop1 || !hop2)
225
- return null;
226
- // Create canonical pair structure (alphabetical symbol ordering)
227
- const routeId = (0, sortUtils_1.canonicalSymbolKey)(startSymbol, endSymbol);
228
- // Create Token objects from address and symbol
229
- const startToken = { address: startAddr, symbol: startSymbol };
230
- const endToken = { address: endAddr, symbol: endSymbol };
231
- // Token array follows alphabetical ordering for consistency
232
- const tokens = startSymbol <= endSymbol ? [startToken, endToken] : [endToken, startToken];
233
- return {
234
- id: routeId,
235
- tokens,
236
- path: [hop1, hop2], // Preserves actual routing path for execution
237
- };
238
- }
239
- /**
240
- * Selects optimal routes from all candidates based on spread data or heuristics.
241
- *
242
- * This is the route optimization engine that implements the following logic:
243
- *
244
- * **For Single Route**: Use it directly (no optimization needed)
245
- *
246
- * **For Multiple Routes**:
247
- * - If `returnAllRoutes=true`: Return all routes (used for cache generation)
248
- * - If `returnAllRoutes=false`: Apply optimization to select the best route
249
- *
250
- * **Route Selection Strategy**: Delegates to `selectBestRoute()` which uses
251
- * a multi-tier approach prioritizing cost efficiency and reliability.
252
- *
253
- * @param allRoutes - Map of pair ID -> array of possible routes
254
- * @param returnAllRoutes - Whether to return all routes or optimize selection
255
- * @param assetMap - Asset map for token symbol lookups during optimization
256
- * @returns Array of selected optimal routes
257
- *
258
- * @example
259
- * ```typescript
260
- * // Multiple routes for USDm-EURm pair
261
- * const candidates = new Map([
262
- * ['EURm-USDm', [
263
- * { path: [USDm->CELO->EURm], costData: { totalCostPercent: 0.5 } },
264
- * { path: [USDm->BRLm->EURm], costData: { totalCostPercent: 0.3 } },
265
- * { path: [USDm->EURm] } // direct route, no cost data
266
- * ]]
267
- * ])
268
- *
269
- * const optimal = selectOptimalRoutes(candidates, false, assetMap)
270
- * // Returns the USDm->BRLm->EURm route (lowest cost: 0.3%)
271
- * ```
272
- */
273
- function selectOptimalRoutes(allRoutes, returnAllRoutes, addrToSymbol) {
274
- const result = new Map();
275
- for (const [routeId, routes] of allRoutes) {
276
- if (routes.length === 1) {
277
- // Only one route available - use it directly
278
- result.set(routeId, routes[0]);
279
- }
280
- else if (returnAllRoutes) {
281
- // Return all routes with unique keys (used for cache generation)
282
- routes.forEach((route, index) => {
283
- result.set(`${routeId}_${index}`, route);
284
- });
285
- }
286
- else {
287
- // Multiple routes - select the best one using optimization logic
288
- const bestRoute = selectBestRoute(routes, addrToSymbol);
289
- result.set(routeId, bestRoute);
290
- }
291
- }
292
- return Array.from(result.values());
293
- }
294
- /**
295
- * Selects the best route from candidates using cost data or fallback heuristics.
296
- *
297
- * This function implements a sophisticated route selection algorithm with
298
- * multiple optimization tiers:
299
- *
300
- * **Tier 1 - Cost-Based Optimization** (Preferred):
301
- * - Use routes with cost data (actual cost information)
302
- * - Select route with lowest `totalCostPercent`
303
- * - This provides the most cost-efficient trading
304
- *
305
- * **Tier 2 - Direct Route Preference** (Fallback):
306
- * - If no cost data available, prefer direct (single-hop) routes
307
- * - Direct routes have lower execution risk and gas costs
308
- *
309
- * **Tier 3 - Major Stablecoin Preference** (Final Fallback):
310
- * - For two-hop routes, prefer those going through major stablecoins
311
- * - Major FX currencies like USDm and EURm typically have better liquidity
312
- *
313
- * **Tier 4 - First Available** (Last Resort):
314
- * - If no other heuristics apply, use the first route found
315
- *
316
- * @param candidates - Array of possible routes for the same token pair
317
- * @param assetMap - Asset map for token symbol lookups
318
- * @returns The optimal route selected using the tier system
319
- *
320
- * @example
321
- * ```typescript
322
- * const candidates = [
323
- * { path: [A->B->C], costData: { totalCostPercent: 0.8 } },
324
- * { path: [A->D->C], costData: { totalCostPercent: 0.4 } }, // Winner: lowest cost
325
- * { path: [A->C] }, // direct route, no cost data
326
- * ]
327
- *
328
- * const best = selectBestRoute(candidates, assetMap)
329
- * // Returns the A->D->C route (0.4% cost)
330
- * ```
331
- */
332
- function selectBestRoute(candidates, addrToSymbol) {
333
- // Tier 1: Prefer routes with cost data (lowest cost wins)
334
- const candidatesWithCost = candidates.filter(hasCostData);
335
- if (candidatesWithCost.length > 0) {
336
- return candidatesWithCost.reduce((best, current) => current.costData.totalCostPercent < best.costData.totalCostPercent ? current : best);
337
- }
338
- // Tier 2: Prefer direct routes (single-hop, lower risk)
339
- const directRoute = candidates.find((c) => c.path.length === 1);
340
- if (directRoute)
341
- return directRoute;
342
- // Tier 3: Prefer routes through major stablecoins (better liquidity)
343
- const stablecoins = ['USDm', 'EURm', 'USDC', 'USDT'];
344
- const routeWithStablecoin = candidates.find((candidate) => {
345
- const intermediateToken = getIntermediateToken(candidate);
346
- if (!intermediateToken)
347
- return false;
348
- const symbol = addrToSymbol.get(intermediateToken);
349
- return symbol && stablecoins.includes(symbol);
350
- });
351
- // Tier 4: Use first available route as last resort
352
- return routeWithStablecoin || candidates[0];
353
- }
354
- /**
355
- * Extracts the intermediate token address from a two-hop route.
356
- * In a two-hop route A->B->C, this function finds token B (the intermediate).
357
- */
358
- function getIntermediateToken(route) {
359
- // Find the common token between the two hops
360
- const [hop1, hop2] = route.path;
361
- const hop1Tokens = [hop1.token0, hop1.token1];
362
- const hop2Tokens = [hop2.token0, hop2.token1];
363
- return hop1Tokens.find((addr) => hop2Tokens.includes(addr));
364
- }
365
- /**
366
- * Type guard to check if a Route has cost data.
367
- */
368
- function hasCostData(pair) {
369
- return 'costData' in pair && pair.costData !== undefined;
370
- }
371
- //# sourceMappingURL=routeUtils.js.map
@@ -1,3 +0,0 @@
1
- export { getCachedRoutes, cachedRoutes } from '../cache/routes';
2
- export type { RouteWithCost } from '../core/types';
3
- //# sourceMappingURL=routes.d.ts.map
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.cachedRoutes = exports.getCachedRoutes = void 0;
4
- // Re-export from consolidated cache
5
- var routes_1 = require("../cache/routes");
6
- Object.defineProperty(exports, "getCachedRoutes", { enumerable: true, get: function () { return routes_1.getCachedRoutes; } });
7
- Object.defineProperty(exports, "cachedRoutes", { enumerable: true, get: function () { return routes_1.cachedRoutes; } });
8
- //# sourceMappingURL=routes.js.map