@mento-protocol/mento-sdk 1.0.9 → 1.10.1
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.
- package/README.md +42 -2
- package/dist/cjs/constants/addresses.js +0 -23
- package/dist/cjs/constants/index.d.ts +1 -0
- package/dist/cjs/constants/index.js +1 -0
- package/dist/cjs/constants/tradablePairs.42220.d.ts +2 -0
- package/dist/cjs/constants/tradablePairs.42220.js +6407 -0
- package/dist/cjs/constants/tradablePairs.44787.d.ts +2 -0
- package/dist/cjs/constants/tradablePairs.44787.js +6407 -0
- package/dist/cjs/constants/tradablePairs.d.ts +15 -2
- package/dist/cjs/constants/tradablePairs.js +48 -9093
- package/dist/cjs/enums/chainId.d.ts +1 -2
- package/dist/cjs/enums/chainId.js +0 -1
- package/dist/cjs/index.d.ts +4 -3
- package/dist/cjs/index.js +3 -2
- package/dist/cjs/mento.d.ts +14 -4
- package/dist/cjs/mento.js +36 -90
- package/dist/cjs/routeUtils.d.ts +304 -0
- package/dist/cjs/routeUtils.js +372 -0
- package/dist/cjs/utils.d.ts +8 -0
- package/dist/cjs/utils.js +18 -1
- package/dist/esm/constants/addresses.js +0 -23
- package/dist/esm/constants/index.d.ts +1 -0
- package/dist/esm/constants/index.js +1 -0
- package/dist/esm/constants/tradablePairs.42220.d.ts +2 -0
- package/dist/esm/constants/tradablePairs.42220.js +6404 -0
- package/dist/esm/constants/tradablePairs.44787.d.ts +2 -0
- package/dist/esm/constants/tradablePairs.44787.js +6404 -0
- package/dist/esm/constants/tradablePairs.d.ts +15 -2
- package/dist/esm/constants/tradablePairs.js +23 -9091
- package/dist/esm/enums/chainId.d.ts +1 -2
- package/dist/esm/enums/chainId.js +0 -1
- package/dist/esm/index.d.ts +4 -3
- package/dist/esm/index.js +3 -2
- package/dist/esm/mento.d.ts +14 -4
- package/dist/esm/mento.js +37 -91
- package/dist/esm/routeUtils.d.ts +304 -0
- package/dist/esm/routeUtils.js +362 -0
- package/dist/esm/utils.d.ts +8 -0
- package/dist/esm/utils.js +16 -0
- package/package.json +18 -6
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export * from './mento';
|
|
2
|
-
export * from './governance';
|
|
3
|
-
export * from './utils';
|
|
4
1
|
export * from './constants';
|
|
2
|
+
export * from './governance';
|
|
3
|
+
export * from './mento';
|
|
4
|
+
export * from './routeUtils';
|
|
5
5
|
export { ContractAddresses } from './types';
|
|
6
|
+
export * from './utils';
|
package/dist/cjs/index.js
CHANGED
|
@@ -15,7 +15,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
16
16
|
};
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
__exportStar(require("./
|
|
18
|
+
__exportStar(require("./constants"), exports);
|
|
19
19
|
__exportStar(require("./governance"), exports);
|
|
20
|
+
__exportStar(require("./mento"), exports);
|
|
21
|
+
__exportStar(require("./routeUtils"), exports);
|
|
20
22
|
__exportStar(require("./utils"), exports);
|
|
21
|
-
__exportStar(require("./constants"), exports);
|
package/dist/cjs/mento.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IBroker } from '@mento-protocol/mento-core-ts';
|
|
2
|
-
import { BigNumber, BigNumberish,
|
|
2
|
+
import { BigNumber, BigNumberish, providers, Signer } from 'ethers';
|
|
3
3
|
import { Address, TradingLimit, TradingLimitsConfig, TradingLimitsState } from './interfaces';
|
|
4
|
+
import { TradablePairWithSpread } from './constants/tradablePairs';
|
|
4
5
|
export interface Exchange {
|
|
5
6
|
providerAddr: Address;
|
|
6
7
|
id: string;
|
|
@@ -10,8 +11,9 @@ export interface Asset {
|
|
|
10
11
|
address: Address;
|
|
11
12
|
symbol: string;
|
|
12
13
|
}
|
|
14
|
+
export type TradablePairID = `${Address}-${Address}`;
|
|
13
15
|
export interface TradablePair {
|
|
14
|
-
id:
|
|
16
|
+
id: TradablePairID;
|
|
15
17
|
assets: [Asset, Asset];
|
|
16
18
|
path: Array<{
|
|
17
19
|
providerAddr: Address;
|
|
@@ -74,11 +76,19 @@ export declare class Mento {
|
|
|
74
76
|
* via two-hop routes. For two-hop pairs, the path will contain two exchange hops.
|
|
75
77
|
* Each TradablePair contains an id (the concatenation of the two asset symbols in alphabetical order),
|
|
76
78
|
* the two Asset objects, and an array of exchange details for each hop.
|
|
79
|
+
* @param options - Optional parameters
|
|
80
|
+
* @param options.cached - Whether to use cached data (default: true)
|
|
81
|
+
* @param options.returnAllRoutes - Whether to return all possible routes or just the best one per pair (default: false)
|
|
77
82
|
* @returns An array of TradablePair objects representing available trade routes.
|
|
78
83
|
*/
|
|
79
|
-
getTradablePairsWithPath({ cached, }?: {
|
|
84
|
+
getTradablePairsWithPath({ cached, returnAllRoutes, }?: {
|
|
80
85
|
cached?: boolean;
|
|
81
|
-
|
|
86
|
+
returnAllRoutes?: boolean;
|
|
87
|
+
}): Promise<readonly (TradablePair | TradablePairWithSpread)[]>;
|
|
88
|
+
/**
|
|
89
|
+
* Attempts to get cached tradable pairs for the current chain
|
|
90
|
+
*/
|
|
91
|
+
private getCachedTradablePairs;
|
|
82
92
|
/**
|
|
83
93
|
* Returns the amount of tokenIn to be sold to buy amountOut of tokenOut.
|
|
84
94
|
* If the provided tradablePair has a single (direct) pricing path, then direct pricing is used.
|
package/dist/cjs/mento.js
CHANGED
|
@@ -18,6 +18,7 @@ const assert_1 = require("assert");
|
|
|
18
18
|
const mento_router_ts_1 = require("mento-router-ts");
|
|
19
19
|
const addresses_1 = require("./constants/addresses");
|
|
20
20
|
const tradablePairs_1 = require("./constants/tradablePairs");
|
|
21
|
+
const routeUtils_1 = require("./routeUtils");
|
|
21
22
|
class Mento {
|
|
22
23
|
/**
|
|
23
24
|
* This constructor is private, use the static create or createWithParams methods
|
|
@@ -129,90 +130,33 @@ class Mento {
|
|
|
129
130
|
* via two-hop routes. For two-hop pairs, the path will contain two exchange hops.
|
|
130
131
|
* Each TradablePair contains an id (the concatenation of the two asset symbols in alphabetical order),
|
|
131
132
|
* the two Asset objects, and an array of exchange details for each hop.
|
|
133
|
+
* @param options - Optional parameters
|
|
134
|
+
* @param options.cached - Whether to use cached data (default: true)
|
|
135
|
+
* @param options.returnAllRoutes - Whether to return all possible routes or just the best one per pair (default: false)
|
|
132
136
|
* @returns An array of TradablePair objects representing available trade routes.
|
|
133
137
|
*/
|
|
134
|
-
getTradablePairsWithPath({ cached = true, } = {}) {
|
|
138
|
+
getTradablePairsWithPath({ cached = true, returnAllRoutes = false, } = {}) {
|
|
135
139
|
return __awaiter(this, void 0, void 0, function* () {
|
|
136
|
-
//
|
|
140
|
+
// Try to get cached data first
|
|
137
141
|
if (cached) {
|
|
138
|
-
const
|
|
139
|
-
if (
|
|
140
|
-
return
|
|
141
|
-
}
|
|
142
|
+
const cachedPairs = yield this.getCachedTradablePairs();
|
|
143
|
+
if (cachedPairs)
|
|
144
|
+
return cachedPairs;
|
|
142
145
|
}
|
|
143
|
-
//
|
|
146
|
+
// Generate routes from scratch
|
|
144
147
|
const directPairs = yield this.getDirectPairs();
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (!directPathMap.has(sortedAddresses)) {
|
|
158
|
-
// Use the first available direct hop for the connectivity graph.
|
|
159
|
-
directPathMap.set(sortedAddresses, pair.path[0]);
|
|
160
|
-
}
|
|
161
|
-
if (!graph.has(assetA.address))
|
|
162
|
-
graph.set(assetA.address, new Set());
|
|
163
|
-
if (!graph.has(assetB.address))
|
|
164
|
-
graph.set(assetB.address, new Set());
|
|
165
|
-
graph.get(assetA.address).add(assetB.address);
|
|
166
|
-
graph.get(assetB.address).add(assetA.address);
|
|
167
|
-
}
|
|
168
|
-
// Initialize tradablePairsMap with direct pairs keyed by their id (symbol-symbol).
|
|
169
|
-
const tradablePairsMap = new Map();
|
|
170
|
-
for (const pair of directPairs) {
|
|
171
|
-
tradablePairsMap.set(pair.id, pair);
|
|
172
|
-
}
|
|
173
|
-
// Generate two-hop pairs using the connectivity graph.
|
|
174
|
-
// For each potential route: start -> intermediate -> end, add a two-hop pair
|
|
175
|
-
// only if no direct route (i.e. same symbol pair) exists.
|
|
176
|
-
for (const [start, neighbors] of graph.entries()) {
|
|
177
|
-
for (const intermediate of neighbors) {
|
|
178
|
-
const secondHopNeighbors = graph.get(intermediate);
|
|
179
|
-
if (!secondHopNeighbors)
|
|
180
|
-
continue;
|
|
181
|
-
for (const end of secondHopNeighbors) {
|
|
182
|
-
if (end === start)
|
|
183
|
-
continue; // Avoid self-loop.
|
|
184
|
-
const assetStart = assetMap.get(start);
|
|
185
|
-
const assetEnd = assetMap.get(end);
|
|
186
|
-
if (!assetStart || !assetEnd)
|
|
187
|
-
continue;
|
|
188
|
-
// Determine canonical pair id based on asset symbols.
|
|
189
|
-
const sortedSymbols = [assetStart.symbol, assetEnd.symbol].sort();
|
|
190
|
-
const pairId = `${sortedSymbols[0]}-${sortedSymbols[1]}`;
|
|
191
|
-
if (tradablePairsMap.has(pairId))
|
|
192
|
-
continue; // Skip if a direct pair exists.
|
|
193
|
-
// Retrieve the direct hops for the two segments.
|
|
194
|
-
const hop1Key = [start, intermediate].sort().join('-');
|
|
195
|
-
const hop2Key = [intermediate, end].sort().join('-');
|
|
196
|
-
const hop1 = directPathMap.get(hop1Key);
|
|
197
|
-
const hop2 = directPathMap.get(hop2Key);
|
|
198
|
-
if (!hop1 || !hop2)
|
|
199
|
-
continue;
|
|
200
|
-
let assets;
|
|
201
|
-
if (assetStart.symbol <= assetEnd.symbol) {
|
|
202
|
-
assets = [assetStart, assetEnd];
|
|
203
|
-
}
|
|
204
|
-
else {
|
|
205
|
-
assets = [assetEnd, assetStart];
|
|
206
|
-
}
|
|
207
|
-
tradablePairsMap.set(pairId, {
|
|
208
|
-
id: pairId,
|
|
209
|
-
assets,
|
|
210
|
-
path: [hop1, hop2],
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
return Array.from(tradablePairsMap.values());
|
|
148
|
+
const connectivity = (0, routeUtils_1.buildConnectivityStructures)(directPairs);
|
|
149
|
+
const allRoutes = (0, routeUtils_1.generateAllRoutes)(connectivity);
|
|
150
|
+
return (0, routeUtils_1.selectOptimalRoutes)(allRoutes, returnAllRoutes, connectivity.addrToSymbol);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Attempts to get cached tradable pairs for the current chain
|
|
155
|
+
*/
|
|
156
|
+
getCachedTradablePairs() {
|
|
157
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
158
|
+
const chainId = yield (0, utils_1.getChainId)(this.signerOrProvider);
|
|
159
|
+
return yield (0, tradablePairs_1.getCachedTradablePairs)(chainId);
|
|
216
160
|
});
|
|
217
161
|
}
|
|
218
162
|
/**
|
|
@@ -458,19 +402,21 @@ class Mento {
|
|
|
458
402
|
*/
|
|
459
403
|
findPairForTokens(tokenIn, tokenOut) {
|
|
460
404
|
return __awaiter(this, void 0, void 0, function* () {
|
|
461
|
-
const
|
|
462
|
-
//
|
|
463
|
-
(p
|
|
464
|
-
|
|
465
|
-
p.
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
405
|
+
const allPairs = yield this.getTradablePairsWithPath();
|
|
406
|
+
// Find the pair for these tokens
|
|
407
|
+
const pair = allPairs.find((p) => {
|
|
408
|
+
// Check if the pair connects tokenIn to tokenOut
|
|
409
|
+
if (p.assets[0].address === tokenIn && p.assets[1].address === tokenOut) {
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
// Check reverse direction
|
|
413
|
+
if (p.assets[0].address === tokenOut && p.assets[1].address === tokenIn) {
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
return false;
|
|
417
|
+
});
|
|
472
418
|
if (!pair) {
|
|
473
|
-
throw new Error(`No
|
|
419
|
+
throw new Error(`No pair found for tokens ${tokenIn} and ${tokenOut}. They may not have a tradable path.`);
|
|
474
420
|
}
|
|
475
421
|
return pair;
|
|
476
422
|
});
|
|
@@ -0,0 +1,304 @@
|
|
|
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 {};
|