@mento-protocol/mento-sdk 1.10.2 → 2.0.0-beta.10

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 (254) hide show
  1. package/README.md +114 -48
  2. package/dist/abis/bipoolmanager.d.ts +15 -0
  3. package/dist/abis/bipoolmanager.d.ts.map +1 -0
  4. package/dist/abis/bipoolmanager.js +26 -0
  5. package/dist/abis/bipoolmanager.js.map +1 -0
  6. package/dist/abis/broker.d.ts +2 -0
  7. package/dist/abis/broker.d.ts.map +1 -0
  8. package/dist/abis/broker.js +8 -0
  9. package/dist/abis/broker.js.map +1 -0
  10. package/dist/abis/erc20.d.ts +2 -0
  11. package/dist/abis/erc20.d.ts.map +1 -0
  12. package/dist/abis/erc20.js +11 -0
  13. package/dist/abis/erc20.js.map +1 -0
  14. package/dist/abis/index.d.ts +5 -0
  15. package/dist/abis/index.d.ts.map +1 -0
  16. package/dist/{cjs/constants → abis}/index.js +5 -2
  17. package/dist/abis/index.js.map +1 -0
  18. package/dist/abis/pricingmodule.d.ts +2 -0
  19. package/dist/abis/pricingmodule.d.ts.map +1 -0
  20. package/dist/abis/pricingmodule.js +5 -0
  21. package/dist/abis/pricingmodule.js.map +1 -0
  22. package/dist/abis/reserve.d.ts +2 -0
  23. package/dist/abis/reserve.d.ts.map +1 -0
  24. package/dist/abis/reserve.js +9 -0
  25. package/dist/abis/reserve.js.map +1 -0
  26. package/dist/abis/uniswapV3.d.ts +4 -0
  27. package/dist/abis/uniswapV3.d.ts.map +1 -0
  28. package/dist/abis/uniswapV3.js +15 -0
  29. package/dist/abis/uniswapV3.js.map +1 -0
  30. package/dist/adapters/implementations/ethersAdapter.d.ts +9 -0
  31. package/dist/adapters/implementations/ethersAdapter.d.ts.map +1 -0
  32. package/dist/adapters/implementations/ethersAdapter.js +19 -0
  33. package/dist/adapters/implementations/ethersAdapter.js.map +1 -0
  34. package/dist/adapters/implementations/ethersV5Adapter.d.ts +9 -0
  35. package/dist/adapters/implementations/ethersV5Adapter.d.ts.map +1 -0
  36. package/dist/adapters/implementations/ethersV5Adapter.js +19 -0
  37. package/dist/adapters/implementations/ethersV5Adapter.js.map +1 -0
  38. package/dist/adapters/implementations/viemAdapter.d.ts +9 -0
  39. package/dist/adapters/implementations/viemAdapter.d.ts.map +1 -0
  40. package/dist/adapters/implementations/viemAdapter.js +26 -0
  41. package/dist/adapters/implementations/viemAdapter.js.map +1 -0
  42. package/dist/adapters/index.d.ts +5 -0
  43. package/dist/adapters/index.d.ts.map +1 -0
  44. package/dist/adapters/index.js +10 -0
  45. package/dist/adapters/index.js.map +1 -0
  46. package/dist/adapters/proxies/ethersAdapterProxy.d.ts +25 -0
  47. package/dist/adapters/proxies/ethersAdapterProxy.d.ts.map +1 -0
  48. package/dist/adapters/proxies/ethersAdapterProxy.js +71 -0
  49. package/dist/adapters/proxies/ethersAdapterProxy.js.map +1 -0
  50. package/dist/adapters/proxies/ethersV5AdapterProxy.d.ts +25 -0
  51. package/dist/adapters/proxies/ethersV5AdapterProxy.d.ts.map +1 -0
  52. package/dist/adapters/proxies/ethersV5AdapterProxy.js +71 -0
  53. package/dist/adapters/proxies/ethersV5AdapterProxy.js.map +1 -0
  54. package/dist/adapters/proxies/viemAdapterProxy.d.ts +25 -0
  55. package/dist/adapters/proxies/viemAdapterProxy.d.ts.map +1 -0
  56. package/dist/adapters/proxies/viemAdapterProxy.js +71 -0
  57. package/dist/adapters/proxies/viemAdapterProxy.js.map +1 -0
  58. package/dist/constants/aaveConfig.d.ts +7 -0
  59. package/dist/constants/aaveConfig.d.ts.map +1 -0
  60. package/dist/constants/aaveConfig.js +22 -0
  61. package/dist/constants/aaveConfig.js.map +1 -0
  62. package/dist/constants/addresses.d.ts +14 -0
  63. package/dist/constants/addresses.d.ts.map +1 -0
  64. package/dist/{esm/constants → constants}/addresses.js +17 -16
  65. package/dist/constants/addresses.js.map +1 -0
  66. package/dist/{cjs/enums → constants}/chainId.d.ts +1 -0
  67. package/dist/constants/chainId.d.ts.map +1 -0
  68. package/dist/{cjs/enums → constants}/chainId.js +2 -1
  69. package/dist/constants/chainId.js.map +1 -0
  70. package/dist/constants/contractNames.d.ts +21 -0
  71. package/dist/constants/contractNames.d.ts.map +1 -0
  72. package/dist/constants/contractNames.js +24 -0
  73. package/dist/constants/contractNames.js.map +1 -0
  74. package/dist/constants/index.d.ts +9 -0
  75. package/dist/constants/index.d.ts.map +1 -0
  76. package/dist/constants/index.js +25 -0
  77. package/dist/constants/index.js.map +1 -0
  78. package/dist/constants/mentoAddresses.d.ts +6 -0
  79. package/dist/constants/mentoAddresses.d.ts.map +1 -0
  80. package/dist/constants/mentoAddresses.js +9 -0
  81. package/dist/constants/mentoAddresses.js.map +1 -0
  82. package/dist/{cjs/enums → constants}/proposalState.d.ts +1 -0
  83. package/dist/constants/proposalState.d.ts.map +1 -0
  84. package/dist/{cjs/enums → constants}/proposalState.js +2 -1
  85. package/dist/constants/proposalState.js.map +1 -0
  86. package/dist/constants/protocolAddresses.d.ts +5 -0
  87. package/dist/constants/protocolAddresses.d.ts.map +1 -0
  88. package/dist/constants/protocolAddresses.js +8 -0
  89. package/dist/constants/protocolAddresses.js.map +1 -0
  90. package/dist/constants/stableTokenMetadata.d.ts +12 -0
  91. package/dist/constants/stableTokenMetadata.d.ts.map +1 -0
  92. package/dist/constants/stableTokenMetadata.js +14 -0
  93. package/dist/constants/stableTokenMetadata.js.map +1 -0
  94. package/dist/index.d.ts +67 -0
  95. package/dist/index.d.ts.map +1 -0
  96. package/dist/index.js +122 -0
  97. package/dist/index.js.map +1 -0
  98. package/dist/services/collateralAssetService.d.ts +8 -0
  99. package/dist/services/collateralAssetService.d.ts.map +1 -0
  100. package/dist/services/collateralAssetService.js +47 -0
  101. package/dist/services/collateralAssetService.js.map +1 -0
  102. package/dist/services/index.d.ts +6 -0
  103. package/dist/services/index.d.ts.map +1 -0
  104. package/dist/{cjs/interfaces → services}/index.js +6 -4
  105. package/dist/services/index.js.map +1 -0
  106. package/dist/services/stableTokenService.d.ts +9 -0
  107. package/dist/services/stableTokenService.d.ts.map +1 -0
  108. package/dist/services/stableTokenService.js +40 -0
  109. package/dist/services/stableTokenService.js.map +1 -0
  110. package/dist/services/supply/ISupplyCalculator.d.ts +14 -0
  111. package/dist/services/supply/ISupplyCalculator.d.ts.map +1 -0
  112. package/dist/{cjs/interfaces/tradingLimitsState.js → services/supply/ISupplyCalculator.js} +1 -0
  113. package/dist/services/supply/ISupplyCalculator.js.map +1 -0
  114. package/dist/services/supply/aaveSupplyCalculator.d.ts +21 -0
  115. package/dist/services/supply/aaveSupplyCalculator.d.ts.map +1 -0
  116. package/dist/services/supply/aaveSupplyCalculator.js +46 -0
  117. package/dist/services/supply/aaveSupplyCalculator.js.map +1 -0
  118. package/dist/services/supply/calculatorFactory.d.ts +8 -0
  119. package/dist/services/supply/calculatorFactory.d.ts.map +1 -0
  120. package/dist/services/supply/calculatorFactory.js +3 -0
  121. package/dist/services/supply/calculatorFactory.js.map +1 -0
  122. package/dist/services/supply/defaultCalculatorFactory.d.ts +9 -0
  123. package/dist/services/supply/defaultCalculatorFactory.d.ts.map +1 -0
  124. package/dist/services/supply/defaultCalculatorFactory.js +27 -0
  125. package/dist/services/supply/defaultCalculatorFactory.js.map +1 -0
  126. package/dist/services/supply/index.d.ts +7 -0
  127. package/dist/services/supply/index.d.ts.map +1 -0
  128. package/dist/{cjs → services/supply}/index.js +7 -6
  129. package/dist/services/supply/index.js.map +1 -0
  130. package/dist/services/supply/multisigSupplyCalculator.d.ts +9 -0
  131. package/dist/services/supply/multisigSupplyCalculator.d.ts.map +1 -0
  132. package/dist/services/supply/multisigSupplyCalculator.js +33 -0
  133. package/dist/services/supply/multisigSupplyCalculator.js.map +1 -0
  134. package/dist/services/supply/uniV3SupplyCalculator.d.ts +21 -0
  135. package/dist/services/supply/uniV3SupplyCalculator.d.ts.map +1 -0
  136. package/dist/services/supply/uniV3SupplyCalculator.js +233 -0
  137. package/dist/services/supply/uniV3SupplyCalculator.js.map +1 -0
  138. package/dist/services/supplyAdjustmentService.d.ts +14 -0
  139. package/dist/services/supplyAdjustmentService.d.ts.map +1 -0
  140. package/dist/services/supplyAdjustmentService.js +46 -0
  141. package/dist/services/supplyAdjustmentService.js.map +1 -0
  142. package/dist/services/tokenMetadataService.d.ts +8 -0
  143. package/dist/services/tokenMetadataService.d.ts.map +1 -0
  144. package/dist/services/tokenMetadataService.js +44 -0
  145. package/dist/services/tokenMetadataService.js.map +1 -0
  146. package/dist/{cjs/types → types}/contractAddresses.d.ts +1 -1
  147. package/dist/types/contractAddresses.d.ts.map +1 -0
  148. package/dist/{cjs/types → types}/contractAddresses.js +1 -0
  149. package/dist/types/contractAddresses.js.map +1 -0
  150. package/dist/types/exchange.d.ts +6 -0
  151. package/dist/types/exchange.d.ts.map +1 -0
  152. package/dist/{cjs/interfaces/tradingLimit.js → types/exchange.js} +1 -0
  153. package/dist/types/exchange.js.map +1 -0
  154. package/dist/types/index.d.ts +5 -0
  155. package/dist/types/index.d.ts.map +1 -0
  156. package/dist/{cjs/types → types}/index.js +4 -1
  157. package/dist/types/index.js.map +1 -0
  158. package/dist/types/provider.d.ts +11 -0
  159. package/dist/types/provider.d.ts.map +1 -0
  160. package/dist/{cjs/interfaces/tradingLimitsConfig.js → types/provider.js} +1 -0
  161. package/dist/types/provider.js.map +1 -0
  162. package/dist/types/token.d.ts +25 -0
  163. package/dist/types/token.d.ts.map +1 -0
  164. package/dist/{cjs/interfaces/IChainClient.js → types/token.js} +1 -0
  165. package/dist/types/token.js.map +1 -0
  166. package/dist/utils/index.d.ts +2 -0
  167. package/dist/utils/index.d.ts.map +1 -0
  168. package/dist/{cjs/enums → utils}/index.js +2 -2
  169. package/dist/utils/index.js.map +1 -0
  170. package/dist/utils/retry.d.ts +12 -0
  171. package/dist/utils/retry.d.ts.map +1 -0
  172. package/dist/utils/retry.js +28 -0
  173. package/dist/utils/retry.js.map +1 -0
  174. package/package.json +33 -61
  175. package/dist/cjs/ChainClient.d.ts +0 -9
  176. package/dist/cjs/ChainClient.js +0 -58
  177. package/dist/cjs/TestChainClient.d.ts +0 -7
  178. package/dist/cjs/TestChainClient.js +0 -41
  179. package/dist/cjs/constants/addresses.d.ts +0 -4
  180. package/dist/cjs/constants/addresses.js +0 -64
  181. package/dist/cjs/constants/index.d.ts +0 -2
  182. package/dist/cjs/constants/tradablePairs.42220.d.ts +0 -2
  183. package/dist/cjs/constants/tradablePairs.42220.js +0 -6407
  184. package/dist/cjs/constants/tradablePairs.44787.d.ts +0 -2
  185. package/dist/cjs/constants/tradablePairs.44787.js +0 -7391
  186. package/dist/cjs/constants/tradablePairs.d.ts +0 -16
  187. package/dist/cjs/constants/tradablePairs.js +0 -53
  188. package/dist/cjs/enums/index.d.ts +0 -2
  189. package/dist/cjs/governance.d.ts +0 -62
  190. package/dist/cjs/governance.js +0 -151
  191. package/dist/cjs/index.d.ts +0 -6
  192. package/dist/cjs/interfaces/IChainClient.d.ts +0 -6
  193. package/dist/cjs/interfaces/index.d.ts +0 -4
  194. package/dist/cjs/interfaces/tradingLimit.d.ts +0 -7
  195. package/dist/cjs/interfaces/tradingLimitsConfig.d.ts +0 -10
  196. package/dist/cjs/interfaces/tradingLimitsState.d.ts +0 -9
  197. package/dist/cjs/limits.d.ts +0 -33
  198. package/dist/cjs/limits.js +0 -130
  199. package/dist/cjs/mento.d.ts +0 -238
  200. package/dist/cjs/mento.js +0 -559
  201. package/dist/cjs/routeUtils.d.ts +0 -304
  202. package/dist/cjs/routeUtils.js +0 -372
  203. package/dist/cjs/types/contractAddressMap.d.ts +0 -4
  204. package/dist/cjs/types/contractAddressMap.js +0 -2
  205. package/dist/cjs/types/index.d.ts +0 -2
  206. package/dist/cjs/utils.d.ts +0 -50
  207. package/dist/cjs/utils.js +0 -129
  208. package/dist/esm/ChainClient.d.ts +0 -9
  209. package/dist/esm/ChainClient.js +0 -54
  210. package/dist/esm/TestChainClient.d.ts +0 -7
  211. package/dist/esm/TestChainClient.js +0 -37
  212. package/dist/esm/constants/addresses.d.ts +0 -4
  213. package/dist/esm/constants/index.d.ts +0 -2
  214. package/dist/esm/constants/index.js +0 -2
  215. package/dist/esm/constants/tradablePairs.42220.d.ts +0 -2
  216. package/dist/esm/constants/tradablePairs.42220.js +0 -6404
  217. package/dist/esm/constants/tradablePairs.44787.d.ts +0 -2
  218. package/dist/esm/constants/tradablePairs.44787.js +0 -7388
  219. package/dist/esm/constants/tradablePairs.d.ts +0 -16
  220. package/dist/esm/constants/tradablePairs.js +0 -26
  221. package/dist/esm/enums/chainId.d.ts +0 -4
  222. package/dist/esm/enums/chainId.js +0 -5
  223. package/dist/esm/enums/index.d.ts +0 -2
  224. package/dist/esm/enums/index.js +0 -2
  225. package/dist/esm/enums/proposalState.d.ts +0 -10
  226. package/dist/esm/enums/proposalState.js +0 -11
  227. package/dist/esm/governance.d.ts +0 -62
  228. package/dist/esm/governance.js +0 -147
  229. package/dist/esm/index.d.ts +0 -6
  230. package/dist/esm/index.js +0 -6
  231. package/dist/esm/interfaces/IChainClient.d.ts +0 -6
  232. package/dist/esm/interfaces/IChainClient.js +0 -1
  233. package/dist/esm/interfaces/index.d.ts +0 -4
  234. package/dist/esm/interfaces/index.js +0 -4
  235. package/dist/esm/interfaces/tradingLimit.d.ts +0 -7
  236. package/dist/esm/interfaces/tradingLimit.js +0 -1
  237. package/dist/esm/interfaces/tradingLimitsConfig.d.ts +0 -10
  238. package/dist/esm/interfaces/tradingLimitsConfig.js +0 -1
  239. package/dist/esm/interfaces/tradingLimitsState.d.ts +0 -9
  240. package/dist/esm/interfaces/tradingLimitsState.js +0 -1
  241. package/dist/esm/limits.d.ts +0 -33
  242. package/dist/esm/limits.js +0 -123
  243. package/dist/esm/mento.d.ts +0 -238
  244. package/dist/esm/mento.js +0 -555
  245. package/dist/esm/routeUtils.d.ts +0 -304
  246. package/dist/esm/routeUtils.js +0 -362
  247. package/dist/esm/types/contractAddressMap.d.ts +0 -4
  248. package/dist/esm/types/contractAddressMap.js +0 -1
  249. package/dist/esm/types/contractAddresses.d.ts +0 -23
  250. package/dist/esm/types/contractAddresses.js +0 -1
  251. package/dist/esm/types/index.d.ts +0 -2
  252. package/dist/esm/types/index.js +0 -2
  253. package/dist/esm/utils.d.ts +0 -50
  254. package/dist/esm/utils.js +0 -119
@@ -1,304 +0,0 @@
1
- import { TradablePairWithSpread } from './constants';
2
- import { Address } from './interfaces';
3
- import { TradablePair, TradablePairID } from './mento';
4
- type TokenSymbol = string;
5
- interface ExchangeDetails {
6
- providerAddr: Address;
7
- id: string;
8
- assets: [Address, Address];
9
- }
10
- /**
11
- * =============================================================================
12
- * ROUTE GENERATION UTILITIES
13
- * =============================================================================
14
- *
15
- * Utilities for generating optimal trading routes in the Mento protocol.
16
- *
17
- * The main workflow is:
18
- *
19
- * 1. Build connectivity structures from direct trading pairs
20
- * 2. Generate all possible routes (direct + two-hop)
21
- * 3. Select optimal routes using spread data or heuristics
22
- *
23
- * ALGORITHM OVERVIEW:
24
- * - Creates a graph where tokens are nodes and direct exchanges are edges
25
- * - Uses graph traversal to find two-hop routes through intermediate tokens
26
- * - Optimizes route selection based on spread costs when available
27
- * - Falls back to heuristics (prefer direct routes, major stablecoins)
28
- * =============================================================================
29
- */
30
- /**
31
- * Connectivity data structure that represents the token graph connecting all tokens.
32
- * Helps to efficiently answer: "How can I trade from token A to token B?"
33
- *
34
- * CONCRETE EXAMPLE:
35
- * Given these direct trading pairs:
36
- * - cUSD ↔ CELO (direct exchange exists)
37
- * - CELO ↔ cEUR (direct exchange exists)
38
- * - cUSD ↔ cREAL (direct exchange exists)
39
- *
40
- * How route finding works:
41
- * - Direct route: cUSD → cEUR? Check token graph: cUSD connects to [CELO, cREAL], none is cEUR → No direct route
42
- * - Two-hop route: cUSD → ? → cEUR?
43
- * - cUSD connects to CELO, CELO connects to cEUR → Found route: cUSD → CELO → cEUR
44
- * - cUSD connects to cREAL, cREAL connects to [cUSD] → No route via cREAL
45
- *
46
- * The "connectivity" part means we can quickly traverse the network of
47
- * token connections to find all possible trading paths.
48
- */
49
- export interface ConnectivityData {
50
- /** Maps token address to symbol for efficient lookups
51
- *
52
- * ```
53
- * '0x765D...' → 'cUSD'
54
- * '0x471E...' → 'CELO'
55
- * '0xD876...' → 'cEUR'
56
- * ```
57
- */
58
- addrToSymbol: Map<Address, TokenSymbol>;
59
- /** Adjacency list mapping which tokens connect to which
60
- * Used for finding two-hop routes by traversing token → neighbor → neighbor.
61
- *
62
- * Example for a cUSD => cEUR swap: First we find cUSD → [CELO, cKES, ...]
63
- * Then we find CELO → [cUSD, cEUR, ...] = found route via cUSD → CELO → cEUR
64
- *
65
- * ```
66
- * 'cUSD_addr' → Set(['CELO_addr', 'cKES_addr']) // cUSD connects to CELO and cKES
67
- * 'CELO_addr' → Set(['cUSD_addr', 'cEUR_addr']) // CELO connects to cUSD and cEUR
68
- * 'cEUR_addr' → Set(['CELO_addr']) // cEUR connects to CELO
69
- * 'cKES_addr' → Set(['cUSD_addr']) // cKES connects to cUSD
70
- * ```
71
- */
72
- tokenGraph: Map<Address, Set<Address>>;
73
- /** Maps sorted token address pairs to their direct exchange hop details
74
- * ```
75
- * 'CELO_addr-cEUR_addr' → { exchange details for CELO ↔ cEUR }
76
- * 'CELO_addr-cUSD_addr' → { exchange details for CELO ↔ cUSD }
77
- * 'cUSD_addr-cKES_addr' → { exchange details for cUSD ↔ cKES }
78
- * ```
79
- */
80
- directPathMap: Map<TradablePairID, ExchangeDetails>;
81
- /** Original direct trading pairs from mento.getDirectPairs() for reference */
82
- directPairs: TradablePair[];
83
- }
84
- /**
85
- * Builds the connectivity data structures needed for route generation.
86
- *
87
- * Transforms a list of direct trading pairs into our ConnectivityData
88
- * that allow us to quickly find trading routes.
89
- *
90
- * **Construction Process:**
91
- *
92
- * ```
93
- * Input: TradablePairs = [
94
- * { id: 'cUSD-CELO', assets: [cUSD, CELO], path: [exchange1_CELO_cUSD] },
95
- * { id: 'CELO-cEUR', assets: [CELO, cEUR], path: [exchange2_CELO_cEUR] }
96
- * ]
97
- *
98
- * Step 1 - Build addrToSymbol map:
99
- * cUSD.address → 'cUSD'
100
- * CELO.address → 'CELO'
101
- * cEUR.address → 'cEUR'
102
- *
103
- * Step 2 - Build directPathMap (sorted alphabetically for consistency):
104
- * 'CELO_addr-cEUR_addr' → exchange2_CELO_cEUR
105
- * 'CELO_addr-cUSD_addr' → exchange1_CELO_cUSD
106
- *
107
- * Step 3 - Build bidirectional tokenGraph:
108
- * cUSD.address → Set([CELO.address])
109
- * CELO.address → Set([cUSD.address, cEUR.address])
110
- * cEUR.address → Set([CELO.address])
111
- * ```
112
- *
113
- * **Result**: We can now efficiently answer:
114
- * - "What's the symbol for address X?" → addrToSymbol.get(addr)
115
- * - "What exchange connects tokens X and Y?" → directPathMap.get(sortedAddressPairKey)
116
- * - "What tokens can I reach from token X?" → tokenGraph.get(X)
117
- *
118
- * @param directPairs - Array of direct trading pairs
119
- * @returns Connectivity data structure for efficient route generation
120
- *
121
- * @example
122
- * ```typescript
123
- * const directPairs = [
124
- * { id: 'cUSD-CELO', assets: [cUSD, CELO], path: [exchange1] },
125
- * { id: 'CELO-cEUR', assets: [CELO, cEUR], path: [exchange2] }
126
- * ]
127
- *
128
- * const connectivityData = buildConnectivityStructures(directPairs)
129
- *
130
- * // Now we can efficiently find routes:
131
- * // 1. Check if cUSD connects to anything: connectivityData.tokenGraph.get(cUSD.address) → [CELO.address]
132
- * // 2. Check if CELO connects to cEUR: connectivityData.tokenGraph.get(CELO.address) → [cUSD.address, cEUR.address] ✓
133
- * // 3. Get exchange details: connectivityData.directPathMap.get('CELO_addr-cEUR_addr') → exchange2_CELO_cEUR
134
- * // Result: Found route cUSD → CELO → cEUR with exchange details
135
- * ```
136
- */
137
- export declare function buildConnectivityStructures(directPairs: TradablePair[]): ConnectivityData;
138
- /**
139
- * Generates all possible routes (direct + two-hop) using connectivity data.
140
- *
141
- * This function implements a route discovery algorithm that:
142
- *
143
- * 1. **Adds all direct pairs** (single-hop routes)
144
- * 2. **Discovers two-hop routes** using graph traversal:
145
- * - For each token A, find its neighbors (tokens directly connected)
146
- * - For each neighbor B, find B's neighbors
147
- * - If B connects to token C (C ≠ A), then A->B->C is a valid route
148
- *
149
- * **Route Deduplication**: Multiple routes between the same token pair
150
- * are collected in arrays, allowing the selection algorithm to choose
151
- * the best one based on spread data or heuristics.
152
- *
153
- * **Canonical Pair IDs**: All pairs use alphabetically sorted symbols
154
- * (e.g., 'cEUR-cUSD' not 'cUSD-cEUR') for consistent identification.
155
- *
156
- * @param connectivityData - The connectivity data from buildConnectivityStructures()
157
- * @returns Map of pair ID -> array of possible routes for that pair
158
- *
159
- * @example
160
- * ```typescript
161
- * // Given direct pairs: cUSD-CELO, CELO-cEUR, cUSD-USDC
162
- * const allRoutes = generateAllRoutes(connectivityData)
163
- *
164
- * // Results might include:
165
- * // 'cUSD-CELO' -> [{ path: [cUSD->CELO] }] // direct route
166
- * // 'cEUR-cUSD' -> [
167
- * // { path: [cUSD->USDC, USDC->cEUR] } // two-hop via USDC
168
- * // { path: [cUSD->CELO, CELO->cEUR] } // two-hop via CELO
169
- * // ]
170
- * ```
171
- */
172
- export declare function generateAllRoutes(connectivityData: ConnectivityData): Map<TradablePairID, TradablePair[]>;
173
- /**
174
- * Creates a two-hop tradable pair if valid exchange hops exist.
175
- *
176
- * 1. **Validates tokens exist** in the asset map
177
- * 2. **Finds exchange hops** for both segments of the route
178
- * 3. **Creates canonical pair structure** with sorted symbols
179
- *
180
- * **Route Structure**: The resulting pair represents trading from start->end
181
- * via intermediate token, but the assets are ordered alphabetically by symbol
182
- * for consistency (canonical form).
183
- *
184
- * **Path Representation**: The path array contains the actual exchange hops
185
- * needed to execute the trade, preserving the routing information.
186
- *
187
- * @param startToken - Starting token address
188
- * @param intermediate - Intermediate token address for routing
189
- * @param end - Destination token address
190
- * @param assetMap - Map of token address -> Asset details
191
- * @param directPathMap - Map of token pairs -> exchange hop details
192
- * @returns Route if valid route exists, null otherwise
193
- *
194
- * @example
195
- * ```typescript
196
- * // Create route: cUSD -> CELO -> cEUR
197
- * const pair = createTwoHopPair(
198
- * '0x765D...', // cUSD address
199
- * '0x471E...', // CELO address
200
- * '0xD876...', // cEUR address
201
- * addrToSymbol,
202
- * directPathMap
203
- * )
204
- *
205
- * // Result:
206
- * // {
207
- * // id: 'cEUR-cUSD', // alphabetical order
208
- * // assets: [cEUR, cUSD], // alphabetical order
209
- * // path: [ // actual routing path
210
- * // { cUSD->CELO exchange },
211
- * // { CELO->cEUR exchange }
212
- * // ]
213
- * // }
214
- * ```
215
- */
216
- export declare function createTwoHopPair(startToken: Address, intermediateToken: Address, endToken: Address, addrToSymbol: Map<Address, TokenSymbol>, directPathMap: Map<string, {
217
- providerAddr: Address;
218
- id: string;
219
- assets: [Address, Address];
220
- }>): TradablePair | null;
221
- /**
222
- * Selects optimal routes from all candidates based on spread data or heuristics.
223
- *
224
- * This is the route optimization engine that implements the following logic:
225
- *
226
- * **For Single Route**: Use it directly (no optimization needed)
227
- *
228
- * **For Multiple Routes**:
229
- * - If `returnAllRoutes=true`: Return all routes (used for cache generation)
230
- * - If `returnAllRoutes=false`: Apply optimization to select the best route
231
- *
232
- * **Route Selection Strategy**: Delegates to `selectBestRoute()` which uses
233
- * a multi-tier approach prioritizing cost efficiency and reliability.
234
- *
235
- * @param allRoutes - Map of pair ID -> array of possible routes
236
- * @param returnAllRoutes - Whether to return all routes or optimize selection
237
- * @param assetMap - Asset map for token symbol lookups during optimization
238
- * @returns Array of selected optimal routes
239
- *
240
- * @example
241
- * ```typescript
242
- * // Multiple routes for cUSD-cEUR pair
243
- * const candidates = new Map([
244
- * ['cEUR-cUSD', [
245
- * { path: [cUSD->CELO->cEUR], spreadData: { totalSpreadPercent: 0.5 } },
246
- * { path: [cUSD->cREAL->cEUR], spreadData: { totalSpreadPercent: 0.3 } },
247
- * { path: [cUSD->cEUR] } // direct route, no spread data
248
- * ]]
249
- * ])
250
- *
251
- * const optimal = selectOptimalRoutes(candidates, false, assetMap)
252
- * // Returns the cUSD->cREAL->cEUR route (lowest spread: 0.3%)
253
- * ```
254
- */
255
- export declare function selectOptimalRoutes(allRoutes: Map<TradablePairID, TradablePair[]>, returnAllRoutes: boolean, addrToSymbol: Map<Address, TokenSymbol>): (TradablePair | TradablePairWithSpread)[];
256
- /**
257
- * Selects the best route from candidates using spread data or fallback heuristics.
258
- *
259
- * This function implements a sophisticated route selection algorithm with
260
- * multiple optimization tiers:
261
- *
262
- * **Tier 1 - Spread-Based Optimization** (Preferred):
263
- * - Use routes with spread data (actual cost information)
264
- * - Select route with lowest `totalSpreadPercent`
265
- * - This provides the most cost-efficient trading
266
- *
267
- * **Tier 2 - Direct Route Preference** (Fallback):
268
- * - If no spread data available, prefer direct (single-hop) routes
269
- * - Direct routes have lower execution risk and gas costs
270
- *
271
- * **Tier 3 - Major Stablecoin Preference** (Final Fallback):
272
- * - For two-hop routes, prefer those going through major stablecoins
273
- * - Major FX currencies like cUSD and cEUR typically have better liquidity
274
- *
275
- * **Tier 4 - First Available** (Last Resort):
276
- * - If no other heuristics apply, use the first route found
277
- *
278
- * @param candidates - Array of possible routes for the same token pair
279
- * @param assetMap - Asset map for token symbol lookups
280
- * @returns The optimal route selected using the tier system
281
- *
282
- * @example
283
- * ```typescript
284
- * const candidates = [
285
- * { path: [A->B->C], spreadData: { totalSpreadPercent: 0.8 } },
286
- * { path: [A->D->C], spreadData: { totalSpreadPercent: 0.4 } }, // Winner: lowest spread
287
- * { path: [A->C] }, // direct route, no spread data
288
- * ]
289
- *
290
- * const best = selectBestRoute(candidates, assetMap)
291
- * // Returns the A->D->C route (0.4% spread)
292
- * ```
293
- */
294
- export declare function selectBestRoute(candidates: TradablePair[], addrToSymbol: Map<Address, TokenSymbol>): TradablePair | TradablePairWithSpread;
295
- /**
296
- * Extracts the intermediate token address from a two-hop route.
297
- * In a two-hop route A->B->C, this function finds token B (the intermediate).
298
- */
299
- export declare function getIntermediateToken(route: TradablePair): Address | undefined;
300
- /**
301
- * Type guard to check if a Route has spread data.
302
- */
303
- export declare function hasSpreadData(pair: TradablePair | TradablePairWithSpread): pair is TradablePairWithSpread;
304
- export {};
@@ -1,362 +0,0 @@
1
- /**
2
- * Builds the connectivity data structures needed for route generation.
3
- *
4
- * Transforms a list of direct trading pairs into our ConnectivityData
5
- * that allow us to quickly find trading routes.
6
- *
7
- * **Construction Process:**
8
- *
9
- * ```
10
- * Input: TradablePairs = [
11
- * { id: 'cUSD-CELO', assets: [cUSD, CELO], path: [exchange1_CELO_cUSD] },
12
- * { id: 'CELO-cEUR', assets: [CELO, cEUR], path: [exchange2_CELO_cEUR] }
13
- * ]
14
- *
15
- * Step 1 - Build addrToSymbol map:
16
- * cUSD.address → 'cUSD'
17
- * CELO.address → 'CELO'
18
- * cEUR.address → 'cEUR'
19
- *
20
- * Step 2 - Build directPathMap (sorted alphabetically for consistency):
21
- * 'CELO_addr-cEUR_addr' → exchange2_CELO_cEUR
22
- * 'CELO_addr-cUSD_addr' → exchange1_CELO_cUSD
23
- *
24
- * Step 3 - Build bidirectional tokenGraph:
25
- * cUSD.address → Set([CELO.address])
26
- * CELO.address → Set([cUSD.address, cEUR.address])
27
- * cEUR.address → Set([CELO.address])
28
- * ```
29
- *
30
- * **Result**: We can now efficiently answer:
31
- * - "What's the symbol for address X?" → addrToSymbol.get(addr)
32
- * - "What exchange connects tokens X and Y?" → directPathMap.get(sortedAddressPairKey)
33
- * - "What tokens can I reach from token X?" → tokenGraph.get(X)
34
- *
35
- * @param directPairs - Array of direct trading pairs
36
- * @returns Connectivity data structure for efficient route generation
37
- *
38
- * @example
39
- * ```typescript
40
- * const directPairs = [
41
- * { id: 'cUSD-CELO', assets: [cUSD, CELO], path: [exchange1] },
42
- * { id: 'CELO-cEUR', assets: [CELO, cEUR], path: [exchange2] }
43
- * ]
44
- *
45
- * const connectivityData = buildConnectivityStructures(directPairs)
46
- *
47
- * // Now we can efficiently find routes:
48
- * // 1. Check if cUSD connects to anything: connectivityData.tokenGraph.get(cUSD.address) → [CELO.address]
49
- * // 2. Check if CELO connects to cEUR: connectivityData.tokenGraph.get(CELO.address) → [cUSD.address, cEUR.address] ✓
50
- * // 3. Get exchange details: connectivityData.directPathMap.get('CELO_addr-cEUR_addr') → exchange2_CELO_cEUR
51
- * // Result: Found route cUSD → CELO → cEUR with exchange details
52
- * ```
53
- */
54
- export function buildConnectivityStructures(directPairs) {
55
- const addrToSymbol = new Map();
56
- const directPathMap = new Map();
57
- const tokenGraph = new Map();
58
- for (const pair of directPairs) {
59
- const [assetA, assetB] = pair.assets;
60
- // Build address-to-symbol map for quick symbol lookups
61
- addrToSymbol.set(assetA.address, assetA.symbol);
62
- addrToSymbol.set(assetB.address, assetB.symbol);
63
- // Build direct path map (sorted addresses as key for consistency)
64
- // for quick lookup of exchange details for any token pair
65
- const sortedAddresses = [assetA.address, assetB.address]
66
- .sort()
67
- .join('-');
68
- if (!directPathMap.has(sortedAddresses)) {
69
- directPathMap.set(sortedAddresses, pair.path[0]);
70
- }
71
- // Build bidirectional connectivity graph for route traversal
72
- // Each token can reach its directly connected tokens
73
- if (!tokenGraph.has(assetA.address))
74
- tokenGraph.set(assetA.address, new Set());
75
- if (!tokenGraph.has(assetB.address))
76
- tokenGraph.set(assetB.address, new Set());
77
- tokenGraph.get(assetA.address).add(assetB.address);
78
- tokenGraph.get(assetB.address).add(assetA.address);
79
- }
80
- return { addrToSymbol, directPathMap, tokenGraph, directPairs };
81
- }
82
- /**
83
- * Generates all possible routes (direct + two-hop) using connectivity data.
84
- *
85
- * This function implements a route discovery algorithm that:
86
- *
87
- * 1. **Adds all direct pairs** (single-hop routes)
88
- * 2. **Discovers two-hop routes** using graph traversal:
89
- * - For each token A, find its neighbors (tokens directly connected)
90
- * - For each neighbor B, find B's neighbors
91
- * - If B connects to token C (C ≠ A), then A->B->C is a valid route
92
- *
93
- * **Route Deduplication**: Multiple routes between the same token pair
94
- * are collected in arrays, allowing the selection algorithm to choose
95
- * the best one based on spread data or heuristics.
96
- *
97
- * **Canonical Pair IDs**: All pairs use alphabetically sorted symbols
98
- * (e.g., 'cEUR-cUSD' not 'cUSD-cEUR') for consistent identification.
99
- *
100
- * @param connectivityData - The connectivity data from buildConnectivityStructures()
101
- * @returns Map of pair ID -> array of possible routes for that pair
102
- *
103
- * @example
104
- * ```typescript
105
- * // Given direct pairs: cUSD-CELO, CELO-cEUR, cUSD-USDC
106
- * const allRoutes = generateAllRoutes(connectivityData)
107
- *
108
- * // Results might include:
109
- * // 'cUSD-CELO' -> [{ path: [cUSD->CELO] }] // direct route
110
- * // 'cEUR-cUSD' -> [
111
- * // { path: [cUSD->USDC, USDC->cEUR] } // two-hop via USDC
112
- * // { path: [cUSD->CELO, CELO->cEUR] } // two-hop via CELO
113
- * // ]
114
- * ```
115
- */
116
- export function generateAllRoutes(connectivityData) {
117
- const { addrToSymbol, directPathMap, tokenGraph, directPairs } = connectivityData;
118
- const allRoutes = new Map();
119
- // Step 1: Add all direct pairs (single-hop routes)
120
- for (const pair of directPairs) {
121
- if (!allRoutes.has(pair.id)) {
122
- allRoutes.set(pair.id, []);
123
- }
124
- allRoutes.get(pair.id).push(pair);
125
- }
126
- // Step 2: Generate two-hop pairs using graph traversal
127
- // Algorithm: For each token, explore all paths of length 2
128
- // OUTER LOOP: "For each starting token..." (e.g., cUSD, CELO, cEUR, etc.)
129
- for (const [start, neighbors] of tokenGraph.entries()) {
130
- // MIDDLE LOOP: "Where can I go from the starting token?" (first hop)
131
- // Example: If start = cUSD, neighbors might be [CELO, USDC, cKES]
132
- for (const intermediate of neighbors) {
133
- // Get all tokens reachable from this intermediate token (second hop destinations)
134
- const secondHopNeighbors = tokenGraph.get(intermediate);
135
- if (!secondHopNeighbors)
136
- continue;
137
- // INNER LOOP: "From the intermediate token, where can I go?" (second hop)
138
- // Example: If intermediate = CELO, secondHopNeighbors might be [cUSD, cEUR, cBRL]
139
- for (const end of secondHopNeighbors) {
140
- // Skip circular routes like cUSD → CELO → cUSD (pointless)
141
- if (end === start)
142
- continue;
143
- // At this point we have a potential route: start → intermediate → end
144
- // Example: cUSD → CELO → cEUR
145
- // Try to create a valid two-hop trading pair from this route
146
- const twoHopPair = createTwoHopPair(start, intermediate, end, addrToSymbol, directPathMap);
147
- // If we successfully created the pair, add it to our collection
148
- if (twoHopPair) {
149
- if (!allRoutes.has(twoHopPair.id)) {
150
- allRoutes.set(twoHopPair.id, []);
151
- }
152
- allRoutes.get(twoHopPair.id).push(twoHopPair);
153
- }
154
- }
155
- }
156
- }
157
- return allRoutes;
158
- }
159
- /**
160
- * Creates a two-hop tradable pair if valid exchange hops exist.
161
- *
162
- * 1. **Validates tokens exist** in the asset map
163
- * 2. **Finds exchange hops** for both segments of the route
164
- * 3. **Creates canonical pair structure** with sorted symbols
165
- *
166
- * **Route Structure**: The resulting pair represents trading from start->end
167
- * via intermediate token, but the assets are ordered alphabetically by symbol
168
- * for consistency (canonical form).
169
- *
170
- * **Path Representation**: The path array contains the actual exchange hops
171
- * needed to execute the trade, preserving the routing information.
172
- *
173
- * @param startToken - Starting token address
174
- * @param intermediate - Intermediate token address for routing
175
- * @param end - Destination token address
176
- * @param assetMap - Map of token address -> Asset details
177
- * @param directPathMap - Map of token pairs -> exchange hop details
178
- * @returns Route if valid route exists, null otherwise
179
- *
180
- * @example
181
- * ```typescript
182
- * // Create route: cUSD -> CELO -> cEUR
183
- * const pair = createTwoHopPair(
184
- * '0x765D...', // cUSD address
185
- * '0x471E...', // CELO address
186
- * '0xD876...', // cEUR address
187
- * addrToSymbol,
188
- * directPathMap
189
- * )
190
- *
191
- * // Result:
192
- * // {
193
- * // id: 'cEUR-cUSD', // alphabetical order
194
- * // assets: [cEUR, cUSD], // alphabetical order
195
- * // path: [ // actual routing path
196
- * // { cUSD->CELO exchange },
197
- * // { CELO->cEUR exchange }
198
- * // ]
199
- * // }
200
- * ```
201
- */
202
- export function createTwoHopPair(startToken, intermediateToken, endToken, addrToSymbol, directPathMap) {
203
- // Validate that both start and end tokens exist in our address-to-symbol map
204
- const startSymbol = addrToSymbol.get(startToken);
205
- const endSymbol = addrToSymbol.get(endToken);
206
- if (!startSymbol || !endSymbol)
207
- return null;
208
- // Create Asset objects from address and symbol
209
- const startAsset = { address: startToken, symbol: startSymbol };
210
- const endAsset = { address: endToken, symbol: endSymbol };
211
- // Find exchange hops for both segments of the two-hop route
212
- // Keys are sorted token addresses for consistent lookup
213
- const hop1Key = [startToken, intermediateToken].sort().join('-');
214
- const hop2Key = [intermediateToken, endToken].sort().join('-');
215
- const hop1 = directPathMap.get(hop1Key);
216
- const hop2 = directPathMap.get(hop2Key);
217
- // If either hop doesn't exist, this route is invalid
218
- if (!hop1 || !hop2)
219
- return null;
220
- // Create canonical pair structure (alphabetical symbol ordering)
221
- const sortedSymbols = [startSymbol, endSymbol].sort();
222
- const pairId = `${sortedSymbols[0]}-${sortedSymbols[1]}`;
223
- // Assets array follows alphabetical ordering for consistency
224
- const assets = startSymbol <= endSymbol ? [startAsset, endAsset] : [endAsset, startAsset];
225
- return {
226
- id: pairId,
227
- assets,
228
- path: [hop1, hop2], // Preserves actual routing path for execution
229
- };
230
- }
231
- /**
232
- * Selects optimal routes from all candidates based on spread data or heuristics.
233
- *
234
- * This is the route optimization engine that implements the following logic:
235
- *
236
- * **For Single Route**: Use it directly (no optimization needed)
237
- *
238
- * **For Multiple Routes**:
239
- * - If `returnAllRoutes=true`: Return all routes (used for cache generation)
240
- * - If `returnAllRoutes=false`: Apply optimization to select the best route
241
- *
242
- * **Route Selection Strategy**: Delegates to `selectBestRoute()` which uses
243
- * a multi-tier approach prioritizing cost efficiency and reliability.
244
- *
245
- * @param allRoutes - Map of pair ID -> array of possible routes
246
- * @param returnAllRoutes - Whether to return all routes or optimize selection
247
- * @param assetMap - Asset map for token symbol lookups during optimization
248
- * @returns Array of selected optimal routes
249
- *
250
- * @example
251
- * ```typescript
252
- * // Multiple routes for cUSD-cEUR pair
253
- * const candidates = new Map([
254
- * ['cEUR-cUSD', [
255
- * { path: [cUSD->CELO->cEUR], spreadData: { totalSpreadPercent: 0.5 } },
256
- * { path: [cUSD->cREAL->cEUR], spreadData: { totalSpreadPercent: 0.3 } },
257
- * { path: [cUSD->cEUR] } // direct route, no spread data
258
- * ]]
259
- * ])
260
- *
261
- * const optimal = selectOptimalRoutes(candidates, false, assetMap)
262
- * // Returns the cUSD->cREAL->cEUR route (lowest spread: 0.3%)
263
- * ```
264
- */
265
- export function selectOptimalRoutes(allRoutes, returnAllRoutes, addrToSymbol) {
266
- const result = new Map();
267
- for (const [pairId, routes] of allRoutes) {
268
- if (routes.length === 1) {
269
- // Only one route available - use it directly
270
- result.set(pairId, routes[0]);
271
- }
272
- else if (returnAllRoutes) {
273
- // Return all routes with unique keys (used for cache generation)
274
- routes.forEach((route, index) => {
275
- result.set(`${pairId}_${index}`, route);
276
- });
277
- }
278
- else {
279
- // Multiple routes - select the best one using optimization logic
280
- const bestRoute = selectBestRoute(routes, addrToSymbol);
281
- result.set(pairId, bestRoute);
282
- }
283
- }
284
- return Array.from(result.values());
285
- }
286
- /**
287
- * Selects the best route from candidates using spread data or fallback heuristics.
288
- *
289
- * This function implements a sophisticated route selection algorithm with
290
- * multiple optimization tiers:
291
- *
292
- * **Tier 1 - Spread-Based Optimization** (Preferred):
293
- * - Use routes with spread data (actual cost information)
294
- * - Select route with lowest `totalSpreadPercent`
295
- * - This provides the most cost-efficient trading
296
- *
297
- * **Tier 2 - Direct Route Preference** (Fallback):
298
- * - If no spread data available, prefer direct (single-hop) routes
299
- * - Direct routes have lower execution risk and gas costs
300
- *
301
- * **Tier 3 - Major Stablecoin Preference** (Final Fallback):
302
- * - For two-hop routes, prefer those going through major stablecoins
303
- * - Major FX currencies like cUSD and cEUR typically have better liquidity
304
- *
305
- * **Tier 4 - First Available** (Last Resort):
306
- * - If no other heuristics apply, use the first route found
307
- *
308
- * @param candidates - Array of possible routes for the same token pair
309
- * @param assetMap - Asset map for token symbol lookups
310
- * @returns The optimal route selected using the tier system
311
- *
312
- * @example
313
- * ```typescript
314
- * const candidates = [
315
- * { path: [A->B->C], spreadData: { totalSpreadPercent: 0.8 } },
316
- * { path: [A->D->C], spreadData: { totalSpreadPercent: 0.4 } }, // Winner: lowest spread
317
- * { path: [A->C] }, // direct route, no spread data
318
- * ]
319
- *
320
- * const best = selectBestRoute(candidates, assetMap)
321
- * // Returns the A->D->C route (0.4% spread)
322
- * ```
323
- */
324
- export function selectBestRoute(candidates, addrToSymbol) {
325
- // Tier 1: Prefer routes with spread data (lowest spread wins)
326
- const candidatesWithSpread = candidates.filter(hasSpreadData);
327
- if (candidatesWithSpread.length > 0) {
328
- return candidatesWithSpread.reduce((best, current) => current.spreadData.totalSpreadPercent < best.spreadData.totalSpreadPercent
329
- ? current
330
- : best);
331
- }
332
- // Tier 2: Prefer direct routes (single-hop, lower risk)
333
- const directRoute = candidates.find((c) => c.path.length === 1);
334
- if (directRoute)
335
- return directRoute;
336
- // Tier 3: Prefer routes through major stablecoins (better liquidity)
337
- const stablecoins = ['cUSD', 'cEUR', 'USDC', 'USDT'];
338
- const routeWithStablecoin = candidates.find((candidate) => {
339
- const intermediateToken = getIntermediateToken(candidate);
340
- if (!intermediateToken)
341
- return false;
342
- const symbol = addrToSymbol.get(intermediateToken);
343
- return symbol && stablecoins.includes(symbol);
344
- });
345
- // Tier 4: Use first available route as last resort
346
- return routeWithStablecoin || candidates[0];
347
- }
348
- /**
349
- * Extracts the intermediate token address from a two-hop route.
350
- * In a two-hop route A->B->C, this function finds token B (the intermediate).
351
- */
352
- export function getIntermediateToken(route) {
353
- // Find the common token between the two hops
354
- const [hop1, hop2] = route.path;
355
- return hop1.assets.find((addr) => hop2.assets.includes(addr));
356
- }
357
- /**
358
- * Type guard to check if a Route has spread data.
359
- */
360
- export function hasSpreadData(pair) {
361
- return 'spreadData' in pair && pair.spreadData !== undefined;
362
- }
@@ -1,4 +0,0 @@
1
- import { ContractAddresses } from '.';
2
- export type ContractAddressMap = {
3
- [chainId: number]: ContractAddresses;
4
- };
@@ -1 +0,0 @@
1
- export {};