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