@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.
- package/README.md +114 -48
- package/dist/abis/bipoolmanager.d.ts +15 -0
- package/dist/abis/bipoolmanager.d.ts.map +1 -0
- package/dist/abis/bipoolmanager.js +26 -0
- package/dist/abis/bipoolmanager.js.map +1 -0
- package/dist/abis/broker.d.ts +2 -0
- package/dist/abis/broker.d.ts.map +1 -0
- package/dist/abis/broker.js +8 -0
- package/dist/abis/broker.js.map +1 -0
- package/dist/abis/erc20.d.ts +2 -0
- package/dist/abis/erc20.d.ts.map +1 -0
- package/dist/abis/erc20.js +11 -0
- package/dist/abis/erc20.js.map +1 -0
- package/dist/abis/index.d.ts +5 -0
- package/dist/abis/index.d.ts.map +1 -0
- package/dist/{cjs/constants → abis}/index.js +5 -2
- package/dist/abis/index.js.map +1 -0
- package/dist/abis/pricingmodule.d.ts +2 -0
- package/dist/abis/pricingmodule.d.ts.map +1 -0
- package/dist/abis/pricingmodule.js +5 -0
- package/dist/abis/pricingmodule.js.map +1 -0
- package/dist/abis/reserve.d.ts +2 -0
- package/dist/abis/reserve.d.ts.map +1 -0
- package/dist/abis/reserve.js +9 -0
- package/dist/abis/reserve.js.map +1 -0
- package/dist/abis/uniswapV3.d.ts +4 -0
- package/dist/abis/uniswapV3.d.ts.map +1 -0
- package/dist/abis/uniswapV3.js +15 -0
- package/dist/abis/uniswapV3.js.map +1 -0
- package/dist/adapters/implementations/ethersAdapter.d.ts +9 -0
- package/dist/adapters/implementations/ethersAdapter.d.ts.map +1 -0
- package/dist/adapters/implementations/ethersAdapter.js +19 -0
- package/dist/adapters/implementations/ethersAdapter.js.map +1 -0
- package/dist/adapters/implementations/ethersV5Adapter.d.ts +9 -0
- package/dist/adapters/implementations/ethersV5Adapter.d.ts.map +1 -0
- package/dist/adapters/implementations/ethersV5Adapter.js +19 -0
- package/dist/adapters/implementations/ethersV5Adapter.js.map +1 -0
- package/dist/adapters/implementations/viemAdapter.d.ts +9 -0
- package/dist/adapters/implementations/viemAdapter.d.ts.map +1 -0
- package/dist/adapters/implementations/viemAdapter.js +26 -0
- package/dist/adapters/implementations/viemAdapter.js.map +1 -0
- package/dist/adapters/index.d.ts +5 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +10 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/proxies/ethersAdapterProxy.d.ts +25 -0
- package/dist/adapters/proxies/ethersAdapterProxy.d.ts.map +1 -0
- package/dist/adapters/proxies/ethersAdapterProxy.js +71 -0
- package/dist/adapters/proxies/ethersAdapterProxy.js.map +1 -0
- package/dist/adapters/proxies/ethersV5AdapterProxy.d.ts +25 -0
- package/dist/adapters/proxies/ethersV5AdapterProxy.d.ts.map +1 -0
- package/dist/adapters/proxies/ethersV5AdapterProxy.js +71 -0
- package/dist/adapters/proxies/ethersV5AdapterProxy.js.map +1 -0
- package/dist/adapters/proxies/viemAdapterProxy.d.ts +25 -0
- package/dist/adapters/proxies/viemAdapterProxy.d.ts.map +1 -0
- package/dist/adapters/proxies/viemAdapterProxy.js +71 -0
- package/dist/adapters/proxies/viemAdapterProxy.js.map +1 -0
- package/dist/constants/aaveConfig.d.ts +7 -0
- package/dist/constants/aaveConfig.d.ts.map +1 -0
- package/dist/constants/aaveConfig.js +22 -0
- package/dist/constants/aaveConfig.js.map +1 -0
- package/dist/constants/addresses.d.ts +14 -0
- package/dist/constants/addresses.d.ts.map +1 -0
- package/dist/{esm/constants → constants}/addresses.js +17 -16
- package/dist/constants/addresses.js.map +1 -0
- package/dist/{cjs/enums → constants}/chainId.d.ts +1 -0
- package/dist/constants/chainId.d.ts.map +1 -0
- package/dist/{cjs/enums → constants}/chainId.js +2 -1
- package/dist/constants/chainId.js.map +1 -0
- package/dist/constants/contractNames.d.ts +21 -0
- package/dist/constants/contractNames.d.ts.map +1 -0
- package/dist/constants/contractNames.js +24 -0
- package/dist/constants/contractNames.js.map +1 -0
- package/dist/constants/index.d.ts +9 -0
- package/dist/constants/index.d.ts.map +1 -0
- package/dist/constants/index.js +25 -0
- package/dist/constants/index.js.map +1 -0
- package/dist/constants/mentoAddresses.d.ts +6 -0
- package/dist/constants/mentoAddresses.d.ts.map +1 -0
- package/dist/constants/mentoAddresses.js +9 -0
- package/dist/constants/mentoAddresses.js.map +1 -0
- package/dist/{cjs/enums → constants}/proposalState.d.ts +1 -0
- package/dist/constants/proposalState.d.ts.map +1 -0
- package/dist/{cjs/enums → constants}/proposalState.js +2 -1
- package/dist/constants/proposalState.js.map +1 -0
- package/dist/constants/protocolAddresses.d.ts +5 -0
- package/dist/constants/protocolAddresses.d.ts.map +1 -0
- package/dist/constants/protocolAddresses.js +8 -0
- package/dist/constants/protocolAddresses.js.map +1 -0
- package/dist/constants/stableTokenMetadata.d.ts +12 -0
- package/dist/constants/stableTokenMetadata.d.ts.map +1 -0
- package/dist/constants/stableTokenMetadata.js +14 -0
- package/dist/constants/stableTokenMetadata.js.map +1 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +122 -0
- package/dist/index.js.map +1 -0
- package/dist/services/collateralAssetService.d.ts +8 -0
- package/dist/services/collateralAssetService.d.ts.map +1 -0
- package/dist/services/collateralAssetService.js +47 -0
- package/dist/services/collateralAssetService.js.map +1 -0
- package/dist/services/index.d.ts +6 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/{cjs/interfaces → services}/index.js +6 -4
- package/dist/services/index.js.map +1 -0
- package/dist/services/stableTokenService.d.ts +9 -0
- package/dist/services/stableTokenService.d.ts.map +1 -0
- package/dist/services/stableTokenService.js +40 -0
- package/dist/services/stableTokenService.js.map +1 -0
- package/dist/services/supply/ISupplyCalculator.d.ts +14 -0
- package/dist/services/supply/ISupplyCalculator.d.ts.map +1 -0
- package/dist/{cjs/interfaces/tradingLimitsState.js → services/supply/ISupplyCalculator.js} +1 -0
- package/dist/services/supply/ISupplyCalculator.js.map +1 -0
- package/dist/services/supply/aaveSupplyCalculator.d.ts +21 -0
- package/dist/services/supply/aaveSupplyCalculator.d.ts.map +1 -0
- package/dist/services/supply/aaveSupplyCalculator.js +46 -0
- package/dist/services/supply/aaveSupplyCalculator.js.map +1 -0
- package/dist/services/supply/calculatorFactory.d.ts +8 -0
- package/dist/services/supply/calculatorFactory.d.ts.map +1 -0
- package/dist/services/supply/calculatorFactory.js +3 -0
- package/dist/services/supply/calculatorFactory.js.map +1 -0
- package/dist/services/supply/defaultCalculatorFactory.d.ts +9 -0
- package/dist/services/supply/defaultCalculatorFactory.d.ts.map +1 -0
- package/dist/services/supply/defaultCalculatorFactory.js +27 -0
- package/dist/services/supply/defaultCalculatorFactory.js.map +1 -0
- package/dist/services/supply/index.d.ts +7 -0
- package/dist/services/supply/index.d.ts.map +1 -0
- package/dist/{cjs → services/supply}/index.js +7 -6
- package/dist/services/supply/index.js.map +1 -0
- package/dist/services/supply/multisigSupplyCalculator.d.ts +9 -0
- package/dist/services/supply/multisigSupplyCalculator.d.ts.map +1 -0
- package/dist/services/supply/multisigSupplyCalculator.js +33 -0
- package/dist/services/supply/multisigSupplyCalculator.js.map +1 -0
- package/dist/services/supply/uniV3SupplyCalculator.d.ts +21 -0
- package/dist/services/supply/uniV3SupplyCalculator.d.ts.map +1 -0
- package/dist/services/supply/uniV3SupplyCalculator.js +233 -0
- package/dist/services/supply/uniV3SupplyCalculator.js.map +1 -0
- package/dist/services/supplyAdjustmentService.d.ts +14 -0
- package/dist/services/supplyAdjustmentService.d.ts.map +1 -0
- package/dist/services/supplyAdjustmentService.js +46 -0
- package/dist/services/supplyAdjustmentService.js.map +1 -0
- package/dist/services/tokenMetadataService.d.ts +8 -0
- package/dist/services/tokenMetadataService.d.ts.map +1 -0
- package/dist/services/tokenMetadataService.js +44 -0
- package/dist/services/tokenMetadataService.js.map +1 -0
- package/dist/{cjs/types → types}/contractAddresses.d.ts +1 -1
- package/dist/types/contractAddresses.d.ts.map +1 -0
- package/dist/{cjs/types → types}/contractAddresses.js +1 -0
- package/dist/types/contractAddresses.js.map +1 -0
- package/dist/types/exchange.d.ts +6 -0
- package/dist/types/exchange.d.ts.map +1 -0
- package/dist/{cjs/interfaces/tradingLimit.js → types/exchange.js} +1 -0
- package/dist/types/exchange.js.map +1 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/{cjs/types → types}/index.js +4 -1
- package/dist/types/index.js.map +1 -0
- package/dist/types/provider.d.ts +11 -0
- package/dist/types/provider.d.ts.map +1 -0
- package/dist/{cjs/interfaces/tradingLimitsConfig.js → types/provider.js} +1 -0
- package/dist/types/provider.js.map +1 -0
- package/dist/types/token.d.ts +25 -0
- package/dist/types/token.d.ts.map +1 -0
- package/dist/{cjs/interfaces/IChainClient.js → types/token.js} +1 -0
- package/dist/types/token.js.map +1 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/{cjs/enums → utils}/index.js +2 -2
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/retry.d.ts +12 -0
- package/dist/utils/retry.d.ts.map +1 -0
- package/dist/utils/retry.js +28 -0
- package/dist/utils/retry.js.map +1 -0
- package/package.json +33 -61
- package/dist/cjs/ChainClient.d.ts +0 -9
- package/dist/cjs/ChainClient.js +0 -58
- package/dist/cjs/TestChainClient.d.ts +0 -7
- package/dist/cjs/TestChainClient.js +0 -41
- package/dist/cjs/constants/addresses.d.ts +0 -4
- package/dist/cjs/constants/addresses.js +0 -64
- package/dist/cjs/constants/index.d.ts +0 -2
- package/dist/cjs/constants/tradablePairs.42220.d.ts +0 -2
- package/dist/cjs/constants/tradablePairs.42220.js +0 -6407
- package/dist/cjs/constants/tradablePairs.44787.d.ts +0 -2
- package/dist/cjs/constants/tradablePairs.44787.js +0 -7391
- package/dist/cjs/constants/tradablePairs.d.ts +0 -16
- package/dist/cjs/constants/tradablePairs.js +0 -53
- package/dist/cjs/enums/index.d.ts +0 -2
- package/dist/cjs/governance.d.ts +0 -62
- package/dist/cjs/governance.js +0 -151
- package/dist/cjs/index.d.ts +0 -6
- package/dist/cjs/interfaces/IChainClient.d.ts +0 -6
- package/dist/cjs/interfaces/index.d.ts +0 -4
- package/dist/cjs/interfaces/tradingLimit.d.ts +0 -7
- package/dist/cjs/interfaces/tradingLimitsConfig.d.ts +0 -10
- package/dist/cjs/interfaces/tradingLimitsState.d.ts +0 -9
- package/dist/cjs/limits.d.ts +0 -33
- package/dist/cjs/limits.js +0 -130
- package/dist/cjs/mento.d.ts +0 -238
- package/dist/cjs/mento.js +0 -559
- package/dist/cjs/routeUtils.d.ts +0 -304
- package/dist/cjs/routeUtils.js +0 -372
- package/dist/cjs/types/contractAddressMap.d.ts +0 -4
- package/dist/cjs/types/contractAddressMap.js +0 -2
- package/dist/cjs/types/index.d.ts +0 -2
- package/dist/cjs/utils.d.ts +0 -50
- package/dist/cjs/utils.js +0 -129
- package/dist/esm/ChainClient.d.ts +0 -9
- package/dist/esm/ChainClient.js +0 -54
- package/dist/esm/TestChainClient.d.ts +0 -7
- package/dist/esm/TestChainClient.js +0 -37
- package/dist/esm/constants/addresses.d.ts +0 -4
- package/dist/esm/constants/index.d.ts +0 -2
- package/dist/esm/constants/index.js +0 -2
- package/dist/esm/constants/tradablePairs.42220.d.ts +0 -2
- package/dist/esm/constants/tradablePairs.42220.js +0 -6404
- package/dist/esm/constants/tradablePairs.44787.d.ts +0 -2
- package/dist/esm/constants/tradablePairs.44787.js +0 -7388
- package/dist/esm/constants/tradablePairs.d.ts +0 -16
- package/dist/esm/constants/tradablePairs.js +0 -26
- package/dist/esm/enums/chainId.d.ts +0 -4
- package/dist/esm/enums/chainId.js +0 -5
- package/dist/esm/enums/index.d.ts +0 -2
- package/dist/esm/enums/index.js +0 -2
- package/dist/esm/enums/proposalState.d.ts +0 -10
- package/dist/esm/enums/proposalState.js +0 -11
- package/dist/esm/governance.d.ts +0 -62
- package/dist/esm/governance.js +0 -147
- package/dist/esm/index.d.ts +0 -6
- package/dist/esm/index.js +0 -6
- package/dist/esm/interfaces/IChainClient.d.ts +0 -6
- package/dist/esm/interfaces/IChainClient.js +0 -1
- package/dist/esm/interfaces/index.d.ts +0 -4
- package/dist/esm/interfaces/index.js +0 -4
- package/dist/esm/interfaces/tradingLimit.d.ts +0 -7
- package/dist/esm/interfaces/tradingLimit.js +0 -1
- package/dist/esm/interfaces/tradingLimitsConfig.d.ts +0 -10
- package/dist/esm/interfaces/tradingLimitsConfig.js +0 -1
- package/dist/esm/interfaces/tradingLimitsState.d.ts +0 -9
- package/dist/esm/interfaces/tradingLimitsState.js +0 -1
- package/dist/esm/limits.d.ts +0 -33
- package/dist/esm/limits.js +0 -123
- package/dist/esm/mento.d.ts +0 -238
- package/dist/esm/mento.js +0 -555
- package/dist/esm/routeUtils.d.ts +0 -304
- package/dist/esm/routeUtils.js +0 -362
- package/dist/esm/types/contractAddressMap.d.ts +0 -4
- package/dist/esm/types/contractAddressMap.js +0 -1
- package/dist/esm/types/contractAddresses.d.ts +0 -23
- package/dist/esm/types/contractAddresses.js +0 -1
- package/dist/esm/types/index.d.ts +0 -2
- package/dist/esm/types/index.js +0 -2
- package/dist/esm/utils.d.ts +0 -50
- package/dist/esm/utils.js +0 -119
package/dist/cjs/routeUtils.d.ts
DELETED
|
@@ -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 {};
|
package/dist/cjs/routeUtils.js
DELETED
|
@@ -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;
|