@mento-protocol/mento-sdk 1.17.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 (126) 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 -80
  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.44787.d.ts +0 -2
  18. package/dist/cjs/constants/tokens.44787.js +0 -128
  19. package/dist/cjs/constants/tokens.d.ts +0 -50
  20. package/dist/cjs/constants/tokens.js +0 -155
  21. package/dist/cjs/constants/tradablePairs.11142220.d.ts +0 -2
  22. package/dist/cjs/constants/tradablePairs.11142220.js +0 -7391
  23. package/dist/cjs/constants/tradablePairs.42220.d.ts +0 -2
  24. package/dist/cjs/constants/tradablePairs.42220.js +0 -7391
  25. package/dist/cjs/constants/tradablePairs.44787.d.ts +0 -2
  26. package/dist/cjs/constants/tradablePairs.44787.js +0 -7391
  27. package/dist/cjs/constants/tradablePairs.d.ts +0 -16
  28. package/dist/cjs/constants/tradablePairs.js +0 -53
  29. package/dist/cjs/enums/chainId.d.ts +0 -5
  30. package/dist/cjs/enums/chainId.js +0 -9
  31. package/dist/cjs/enums/index.d.ts +0 -3
  32. package/dist/cjs/enums/index.js +0 -19
  33. package/dist/cjs/enums/proposalState.d.ts +0 -10
  34. package/dist/cjs/enums/proposalState.js +0 -14
  35. package/dist/cjs/enums/tradingMode.d.ts +0 -17
  36. package/dist/cjs/enums/tradingMode.js +0 -21
  37. package/dist/cjs/governance.d.ts +0 -62
  38. package/dist/cjs/governance.js +0 -151
  39. package/dist/cjs/index.d.ts +0 -7
  40. package/dist/cjs/index.js +0 -23
  41. package/dist/cjs/interfaces/IChainClient.d.ts +0 -6
  42. package/dist/cjs/interfaces/IChainClient.js +0 -2
  43. package/dist/cjs/interfaces/index.d.ts +0 -4
  44. package/dist/cjs/interfaces/index.js +0 -20
  45. package/dist/cjs/interfaces/tradingLimit.d.ts +0 -7
  46. package/dist/cjs/interfaces/tradingLimit.js +0 -2
  47. package/dist/cjs/interfaces/tradingLimitsConfig.d.ts +0 -10
  48. package/dist/cjs/interfaces/tradingLimitsConfig.js +0 -2
  49. package/dist/cjs/interfaces/tradingLimitsState.d.ts +0 -9
  50. package/dist/cjs/interfaces/tradingLimitsState.js +0 -2
  51. package/dist/cjs/limits.d.ts +0 -33
  52. package/dist/cjs/limits.js +0 -130
  53. package/dist/cjs/mento.d.ts +0 -287
  54. package/dist/cjs/mento.js +0 -699
  55. package/dist/cjs/routeUtils.d.ts +0 -304
  56. package/dist/cjs/routeUtils.js +0 -372
  57. package/dist/cjs/types/contractAddressMap.d.ts +0 -4
  58. package/dist/cjs/types/contractAddressMap.js +0 -2
  59. package/dist/cjs/types/contractAddresses.d.ts +0 -23
  60. package/dist/cjs/types/contractAddresses.js +0 -2
  61. package/dist/cjs/types/index.d.ts +0 -2
  62. package/dist/cjs/types/index.js +0 -18
  63. package/dist/cjs/utils.d.ts +0 -80
  64. package/dist/cjs/utils.js +0 -177
  65. package/dist/esm/ChainClient.d.ts +0 -9
  66. package/dist/esm/ChainClient.js +0 -54
  67. package/dist/esm/TestChainClient.d.ts +0 -7
  68. package/dist/esm/TestChainClient.js +0 -37
  69. package/dist/esm/constants/addresses.d.ts +0 -4
  70. package/dist/esm/constants/addresses.js +0 -76
  71. package/dist/esm/constants/currencies.d.ts +0 -5
  72. package/dist/esm/constants/currencies.js +0 -26
  73. package/dist/esm/constants/index.d.ts +0 -4
  74. package/dist/esm/constants/index.js +0 -4
  75. package/dist/esm/constants/tokens.11142220.d.ts +0 -2
  76. package/dist/esm/constants/tokens.11142220.js +0 -125
  77. package/dist/esm/constants/tokens.42220.d.ts +0 -2
  78. package/dist/esm/constants/tokens.42220.js +0 -125
  79. package/dist/esm/constants/tokens.44787.d.ts +0 -2
  80. package/dist/esm/constants/tokens.44787.js +0 -125
  81. package/dist/esm/constants/tokens.d.ts +0 -50
  82. package/dist/esm/constants/tokens.js +0 -127
  83. package/dist/esm/constants/tradablePairs.11142220.d.ts +0 -2
  84. package/dist/esm/constants/tradablePairs.11142220.js +0 -7388
  85. package/dist/esm/constants/tradablePairs.42220.d.ts +0 -2
  86. package/dist/esm/constants/tradablePairs.42220.js +0 -7388
  87. package/dist/esm/constants/tradablePairs.44787.d.ts +0 -2
  88. package/dist/esm/constants/tradablePairs.44787.js +0 -7388
  89. package/dist/esm/constants/tradablePairs.d.ts +0 -16
  90. package/dist/esm/constants/tradablePairs.js +0 -26
  91. package/dist/esm/enums/chainId.d.ts +0 -5
  92. package/dist/esm/enums/chainId.js +0 -6
  93. package/dist/esm/enums/index.d.ts +0 -3
  94. package/dist/esm/enums/index.js +0 -3
  95. package/dist/esm/enums/proposalState.d.ts +0 -10
  96. package/dist/esm/enums/proposalState.js +0 -11
  97. package/dist/esm/enums/tradingMode.d.ts +0 -17
  98. package/dist/esm/enums/tradingMode.js +0 -18
  99. package/dist/esm/governance.d.ts +0 -62
  100. package/dist/esm/governance.js +0 -147
  101. package/dist/esm/index.d.ts +0 -7
  102. package/dist/esm/index.js +0 -7
  103. package/dist/esm/interfaces/IChainClient.d.ts +0 -6
  104. package/dist/esm/interfaces/IChainClient.js +0 -1
  105. package/dist/esm/interfaces/index.d.ts +0 -4
  106. package/dist/esm/interfaces/index.js +0 -4
  107. package/dist/esm/interfaces/tradingLimit.d.ts +0 -7
  108. package/dist/esm/interfaces/tradingLimit.js +0 -1
  109. package/dist/esm/interfaces/tradingLimitsConfig.d.ts +0 -10
  110. package/dist/esm/interfaces/tradingLimitsConfig.js +0 -1
  111. package/dist/esm/interfaces/tradingLimitsState.d.ts +0 -9
  112. package/dist/esm/interfaces/tradingLimitsState.js +0 -1
  113. package/dist/esm/limits.d.ts +0 -33
  114. package/dist/esm/limits.js +0 -123
  115. package/dist/esm/mento.d.ts +0 -287
  116. package/dist/esm/mento.js +0 -671
  117. package/dist/esm/routeUtils.d.ts +0 -304
  118. package/dist/esm/routeUtils.js +0 -362
  119. package/dist/esm/types/contractAddressMap.d.ts +0 -4
  120. package/dist/esm/types/contractAddressMap.js +0 -1
  121. package/dist/esm/types/contractAddresses.d.ts +0 -23
  122. package/dist/esm/types/contractAddresses.js +0 -1
  123. package/dist/esm/types/index.d.ts +0 -2
  124. package/dist/esm/types/index.js +0 -2
  125. package/dist/esm/utils.d.ts +0 -80
  126. package/dist/esm/utils.js +0 -162
package/dist/esm/mento.js DELETED
@@ -1,671 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BiPoolManager__factory, Broker__factory, IBreakerBox__factory, IBroker__factory, IExchangeProvider__factory, } from '@mento-protocol/mento-core-ts';
11
- import { Signer } from 'ethers';
12
- import { getLimits, getLimitsConfig, getLimitsState } from './limits';
13
- import { getChainId, getDecimalsFromTokenAddress, getNameFromTokenAddress, getSymbolFromTokenAddress, increaseAllowance, validateSigner, validateSignerOrProvider, } from './utils';
14
- import { strict as assert } from 'assert';
15
- import { IMentoRouter__factory } from 'mento-router-ts';
16
- import { getAddress } from './constants/addresses';
17
- import { getCachedTradablePairs, } from './constants/tradablePairs';
18
- import { TradingMode } from './enums';
19
- import { buildConnectivityStructures, generateAllRoutes, selectOptimalRoutes, } from './routeUtils';
20
- // Re-export TokenSymbol for use in auto-generated files and consuming packages
21
- export { TokenSymbol } from './constants/tokens';
22
- export class Mento {
23
- /**
24
- * This constructor is private, use the static create or createWithParams methods
25
- * to create a new Mento instance
26
- * @param signerOrProvider an ethers provider or connected signer
27
- * @param brokerAddress the address of the broker contract
28
- * @param exchanges exchange data for the broker
29
- */
30
- constructor(signerOrProvider, brokerAddress, routerAddress, exchanges) {
31
- this.cachedChainId = null;
32
- this.signerOrProvider = signerOrProvider;
33
- this.broker = IBroker__factory.connect(brokerAddress, signerOrProvider);
34
- this.router = IMentoRouter__factory.connect(routerAddress, signerOrProvider);
35
- this.exchanges = exchanges || [];
36
- }
37
- /**
38
- * Creates a new Mento object instance.
39
- * When constructed with only a Provider only read-only operations are supported
40
- * @param signerOrProvider an ethers signer or provider. A signer is required to execute swaps
41
- * @returns a new Mento object instance
42
- */
43
- static create(signerOrProvider) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- validateSignerOrProvider(signerOrProvider);
46
- const chainId = yield getChainId(signerOrProvider);
47
- const instance = new Mento(signerOrProvider, getAddress('Broker', chainId), getAddress('MentoRouter', chainId));
48
- instance.cachedChainId = chainId;
49
- return instance;
50
- });
51
- }
52
- /**
53
- * Create a new Mento object instance given a broker address and optional exchanges data
54
- * When constructed with a Provider, only read-only operations are supported
55
- * @param signerOrProvider an ethers signer or provider. A signer is required to execute swaps
56
- * @param brokerAddr the address of the broker contract
57
- * @param exchanges the exchanges data for the broker
58
- * @returns a new Mento object instance
59
- */
60
- static createWithParams(signerOrProvider, brokerAddr, routerAddr, exchanges) {
61
- validateSignerOrProvider(signerOrProvider);
62
- return new Mento(signerOrProvider, brokerAddr, routerAddr, exchanges);
63
- }
64
- /**
65
- * Returns a new Mento instance connected to the given signer
66
- * @param signer an ethers signer
67
- * @returns new Mento object instance
68
- */
69
- connectSigner(signer) {
70
- validateSigner(signer);
71
- return new Mento(signer, this.broker.address, this.router.address, this.exchanges);
72
- }
73
- /**
74
- * Get tradable pairs for backwards compatibility
75
- * @returns an array of Asset pairs
76
- */
77
- getTradablePairs({ cached = true, } = {}) {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- return (yield this.getTradablePairsWithPath({ cached })).map((pair) => pair.assets);
80
- });
81
- }
82
- /**
83
- * Returns a list of all tradable pairs on Mento via direct exchanges.
84
- * Each pair is represented using the TradablePair interface, with its id
85
- * (a concatenation of the two asset symbols in alphabetical order),
86
- * the two Asset objects, and a path (an array with a single direct exchange hop).
87
- * @returns An array of direct TradablePair objects.
88
- */
89
- getDirectPairs() {
90
- return __awaiter(this, void 0, void 0, function* () {
91
- const exchanges = yield this.getExchanges();
92
- // Map from pair id (symbol-symbol) to its TradablePair
93
- const directPairsMap = new Map();
94
- for (const exchange of exchanges) {
95
- const [token0, token1] = exchange.assets;
96
- const [symbol0, symbol1] = yield Promise.all([
97
- getSymbolFromTokenAddress(token0, this.signerOrProvider),
98
- getSymbolFromTokenAddress(token1, this.signerOrProvider),
99
- ]);
100
- // Determine canonical order by symbol
101
- let assets;
102
- let pairId;
103
- if (symbol0 <= symbol1) {
104
- assets = [
105
- { address: token0, symbol: symbol0 },
106
- { address: token1, symbol: symbol1 },
107
- ];
108
- pairId = `${symbol0}-${symbol1}`;
109
- }
110
- else {
111
- assets = [
112
- { address: token1, symbol: symbol1 },
113
- { address: token0, symbol: symbol0 },
114
- ];
115
- pairId = `${symbol1}-${symbol0}`;
116
- }
117
- const pathEntry = {
118
- providerAddr: exchange.providerAddr,
119
- id: exchange.id,
120
- assets: exchange.assets,
121
- };
122
- if (directPairsMap.has(pairId)) {
123
- directPairsMap.get(pairId).path.push(pathEntry);
124
- }
125
- else {
126
- directPairsMap.set(pairId, { id: pairId, assets, path: [pathEntry] });
127
- }
128
- }
129
- return Array.from(directPairsMap.values());
130
- });
131
- }
132
- /**
133
- * Returns a list of all tradable pairs on Mento, including those achievable
134
- * via two-hop routes. For two-hop pairs, the path will contain two exchange hops.
135
- * Each TradablePair contains an id (the concatenation of the two asset symbols in alphabetical order),
136
- * the two Asset objects, and an array of exchange details for each hop.
137
- * @param options - Optional parameters
138
- * @param options.cached - Whether to use cached data (default: true)
139
- * @param options.returnAllRoutes - Whether to return all possible routes or just the best one per pair (default: false)
140
- * @returns An array of TradablePair objects representing available trade routes.
141
- */
142
- getTradablePairsWithPath({ cached = true, returnAllRoutes = false, } = {}) {
143
- return __awaiter(this, void 0, void 0, function* () {
144
- // Try to get cached data first
145
- if (cached) {
146
- const cachedPairs = yield this.getCachedTradablePairs();
147
- if (cachedPairs)
148
- return cachedPairs;
149
- }
150
- // Generate routes from scratch
151
- const directPairs = yield this.getDirectPairs();
152
- const connectivity = buildConnectivityStructures(directPairs);
153
- const allRoutes = generateAllRoutes(connectivity);
154
- return selectOptimalRoutes(allRoutes, returnAllRoutes, connectivity.addrToSymbol);
155
- });
156
- }
157
- /**
158
- * Attempts to get cached tradable pairs for the current chain
159
- */
160
- getCachedTradablePairs() {
161
- return __awaiter(this, void 0, void 0, function* () {
162
- const chainId = yield getChainId(this.signerOrProvider);
163
- return yield getCachedTradablePairs(chainId);
164
- });
165
- }
166
- /**
167
- * Returns a list of all unique tokens available on the current chain.
168
- * This method is synchronous and uses pre-cached token data.
169
- * For runtime fetching from the blockchain, use getTokensAsync().
170
- *
171
- * @returns An array of unique Token objects from the static cache.
172
- * @throws Error if no cached tokens are available for the current chain or if chainId is not yet initialized
173
- */
174
- getTokens() {
175
- if (!this.cachedChainId) {
176
- throw new Error('Chain ID not yet initialized. Use Mento.create() to initialize the SDK, or use getTokensAsync() instead.');
177
- }
178
- // eslint-disable-next-line @typescript-eslint/no-var-requires
179
- const { getCachedTokensSync } = require('./constants/tokens');
180
- return Array.from(getCachedTokensSync(this.cachedChainId));
181
- }
182
- /**
183
- * Fetches token metadata from the blockchain at runtime.
184
- * This method is async and makes blockchain calls to get fresh token data.
185
- * For synchronous access using cached data, use getTokens().
186
- *
187
- * @param options - Optional parameters
188
- * @param options.cached - Whether to use cached data (default: true).
189
- * If true, attempts to load from static cache first.
190
- * @returns A Promise resolving to an array of unique Token objects.
191
- */
192
- getTokensAsync({ cached = true, } = {}) {
193
- return __awaiter(this, void 0, void 0, function* () {
194
- // If cached is true, try to use the static cache first
195
- if (cached) {
196
- const { getCachedTokens } = yield import('./constants/tokens');
197
- const chainId = yield this.chainId();
198
- const cachedTokens = yield getCachedTokens(chainId);
199
- if (cachedTokens) {
200
- return Array.from(cachedTokens);
201
- }
202
- }
203
- // Fall back to fetching from blockchain
204
- const tradablePairs = yield this.getTradablePairsWithPath({ cached: false });
205
- // Collect unique token addresses
206
- const uniqueAddresses = new Set(tradablePairs.flatMap((pair) => pair.assets.map((asset) => asset.address)));
207
- // Fetch token metadata for each unique address
208
- const tokens = yield Promise.all(Array.from(uniqueAddresses).map((address) => __awaiter(this, void 0, void 0, function* () {
209
- const [symbol, name, decimals] = yield Promise.all([
210
- getSymbolFromTokenAddress(address, this.signerOrProvider),
211
- getNameFromTokenAddress(address, this.signerOrProvider),
212
- getDecimalsFromTokenAddress(address, this.signerOrProvider),
213
- ]);
214
- return {
215
- address,
216
- symbol,
217
- name,
218
- decimals,
219
- };
220
- })));
221
- // Sort by symbol
222
- return tokens.sort((a, b) => a.symbol.localeCompare(b.symbol));
223
- });
224
- }
225
- /**
226
- * Returns the amount of tokenIn to be sold to buy amountOut of tokenOut.
227
- * If the provided tradablePair has a single (direct) pricing path, then direct pricing is used.
228
- * Otherwise, routed pricing via the MentoRouter is applied.
229
- * @param tokenIn the token to be sold
230
- * @param tokenOut the token to be bought
231
- * @param amountOut the desired amount of tokenOut to be obtained
232
- * @param tradablePair the TradablePair object containing the pricing path information
233
- * @returns the amount of tokenIn to be sold
234
- */
235
- getAmountIn(tokenIn, tokenOut, amountOut, tradablePair) {
236
- return __awaiter(this, void 0, void 0, function* () {
237
- if (!tradablePair) {
238
- tradablePair = yield this.findPairForTokens(tokenIn, tokenOut);
239
- }
240
- if (tradablePair.path.length === 1) {
241
- return this.getAmountInDirect(tokenIn, tokenOut, amountOut, tradablePair);
242
- }
243
- else {
244
- return this.getAmountInRouted(tokenIn, tokenOut, amountOut, tradablePair);
245
- }
246
- });
247
- }
248
- /**
249
- * Returns the amount of tokenOut to be bought by selling amountIn of tokenIn.
250
- * If the provided tradablePair has a single (direct) pricing path, then direct pricing is used.
251
- * Otherwise, routed pricing via the MentoRouter is applied.
252
- * @param tokenIn the token to be sold
253
- * @param tokenOut the token to be bought
254
- * @param amountIn the amount of tokenIn to be sold
255
- * @param tradablePair the TradablePair object containing the pricing path information
256
- * @returns the amount of tokenOut to be bought
257
- */
258
- getAmountOut(tokenIn, tokenOut, amountIn, tradablePair) {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- if (!tradablePair) {
261
- tradablePair = yield this.findPairForTokens(tokenIn, tokenOut);
262
- }
263
- if (tradablePair.path.length === 1) {
264
- return this.getAmountOutDirect(tokenIn, tokenOut, amountIn, tradablePair);
265
- }
266
- else {
267
- return this.getAmountOutRouted(tokenIn, tokenOut, amountIn, tradablePair);
268
- }
269
- });
270
- }
271
- /**
272
- * Internal method for direct pricing: retrieves the exchange for the given tokens
273
- * and returns the amountIn using the broker.
274
- */
275
- getAmountInDirect(tokenIn, tokenOut, amountOut, tradablePair) {
276
- return __awaiter(this, void 0, void 0, function* () {
277
- return this.broker.getAmountIn(tradablePair.path[0].providerAddr, tradablePair.path[0].id, tokenIn, tokenOut, amountOut);
278
- });
279
- }
280
- /**
281
- * Internal method for direct pricing: retrieves the exchange for the given tokens
282
- * and returns the amountOut using the broker.
283
- */
284
- getAmountOutDirect(tokenIn, tokenOut, amountIn, tradablePair) {
285
- return __awaiter(this, void 0, void 0, function* () {
286
- return this.broker.getAmountOut(tradablePair.path[0].providerAddr, tradablePair.path[0].id, tokenIn, tokenOut, amountIn);
287
- });
288
- }
289
- /**
290
- * Internal method for routed pricing: uses the MentoRouter to determine the required tokenIn
291
- * for obtaining amountOut through a multi-hop route specified in tradablePair.path.
292
- */
293
- getAmountInRouted(tokenIn, tokenOut, amountOut, tradablePair) {
294
- return __awaiter(this, void 0, void 0, function* () {
295
- const steps = this.buildSteps(tokenIn, tokenOut, tradablePair);
296
- return this.router.getAmountIn(amountOut, steps);
297
- });
298
- }
299
- /**
300
- * Internal method for routed pricing: uses the MentoRouter to determine the amountOut
301
- * obtainable by selling amountIn through a multi-hop route specified in tradablePair.path.
302
- */
303
- getAmountOutRouted(tokenIn, tokenOut, amountIn, tradablePair) {
304
- return __awaiter(this, void 0, void 0, function* () {
305
- const steps = this.buildSteps(tokenIn, tokenOut, tradablePair);
306
- return this.router.getAmountOut(amountIn, steps);
307
- });
308
- }
309
- /**
310
- * Increases the broker's trading allowance for the given token
311
- * @param token the token to increase the allowance for
312
- * @param amount the amount to increase the allowance by
313
- * @returns the populated TransactionRequest object
314
- */
315
- increaseTradingAllowance(tokenIn, amount, tradablePair) {
316
- return __awaiter(this, void 0, void 0, function* () {
317
- const spender = !tradablePair || (tradablePair === null || tradablePair === void 0 ? void 0 : tradablePair.path.length) == 1
318
- ? this.broker.address
319
- : this.router.address;
320
- const tx = yield increaseAllowance(tokenIn, spender, amount, this.signerOrProvider);
321
- if (Signer.isSigner(this.signerOrProvider)) {
322
- // The contract call doesn't populate all of the signer fields, so we need an extra call for the signer
323
- return this.signerOrProvider.populateTransaction(tx);
324
- }
325
- else {
326
- return tx;
327
- }
328
- });
329
- }
330
- /**
331
- * Returns a token swap populated tx object with a fixed amount of tokenIn and a minimum amount of tokenOut.
332
- * If the tradablePair contains a single-hop route, a direct swap is executed using swapExactTokensForTokens on the broker.
333
- * Otherwise, a routed swap is executed via the router.
334
- * @param tokenIn the token to be sold
335
- * @param tokenOut the token to be bought
336
- * @param amountIn the amount of tokenIn to be sold
337
- * @param amountOutMin the minimum amount of tokenOut to be bought
338
- * @param tradablePair the tradable pair details to determine routing
339
- * @returns the populated TransactionRequest object
340
- */
341
- swapIn(tokenIn, tokenOut, amountIn, amountOutMin, tradablePair) {
342
- return __awaiter(this, void 0, void 0, function* () {
343
- if (!tradablePair) {
344
- tradablePair = yield this.findPairForTokens(tokenIn, tokenOut);
345
- }
346
- if (tradablePair.path.length === 1) {
347
- return this.swapInDirect(tokenIn, tokenOut, amountIn, amountOutMin);
348
- }
349
- else {
350
- return this.swapInRouted(tokenIn, tokenOut, amountIn, amountOutMin, tradablePair);
351
- }
352
- });
353
- }
354
- swapInDirect(tokenIn, tokenOut, amountIn, amountOutMin) {
355
- return __awaiter(this, void 0, void 0, function* () {
356
- const exchange = yield this.getExchangeForTokens(tokenIn, tokenOut);
357
- const tx = yield this.broker.populateTransaction.swapIn(exchange.providerAddr, exchange.id, tokenIn, tokenOut, amountIn, amountOutMin);
358
- return Signer.isSigner(this.signerOrProvider)
359
- ? this.signerOrProvider.populateTransaction(tx)
360
- : tx;
361
- });
362
- }
363
- swapInRouted(tokenIn, tokenOut, amountIn, amountOutMin, tradablePair) {
364
- return __awaiter(this, void 0, void 0, function* () {
365
- const steps = this.buildSteps(tokenIn, tokenOut, tradablePair);
366
- const tx = yield this.router.populateTransaction.swapExactTokensForTokens(amountIn, amountOutMin, steps);
367
- return Signer.isSigner(this.signerOrProvider)
368
- ? this.signerOrProvider.populateTransaction(tx)
369
- : tx;
370
- });
371
- }
372
- /**
373
- * Returns a token swap populated tx object with a maximum amount of tokenIn and a fixed amount of tokenOut.
374
- * If the tradablePair contains a single-hop route, a direct swap is executed using swapTokensForExactTokens on the broker.
375
- * Otherwise, a routed swap is executed via the router.
376
- * @param tokenIn the token to be sold
377
- * @param tokenOut the token to be bought
378
- * @param amountOut the amount of tokenOut to be bought
379
- * @param amountInMax the maximum amount of tokenIn to be sold
380
- * @returns the populated TransactionRequest object
381
- */
382
- swapOut(tokenIn, tokenOut, amountOut, amountInMax, tradablePair) {
383
- return __awaiter(this, void 0, void 0, function* () {
384
- if (!tradablePair) {
385
- tradablePair = yield this.findPairForTokens(tokenIn, tokenOut);
386
- }
387
- if (tradablePair.path.length === 1) {
388
- return this.swapOutDirect(tokenIn, tokenOut, amountOut, amountInMax);
389
- }
390
- else {
391
- return this.swapOutRouted(tokenIn, tokenOut, amountOut, amountInMax, tradablePair);
392
- }
393
- });
394
- }
395
- swapOutDirect(tokenIn, tokenOut, amountOut, amountInMax) {
396
- return __awaiter(this, void 0, void 0, function* () {
397
- const exchange = yield this.getExchangeForTokens(tokenIn, tokenOut);
398
- const tx = yield this.broker.populateTransaction.swapOut(exchange.providerAddr, exchange.id, tokenIn, tokenOut, amountOut, amountInMax);
399
- return Signer.isSigner(this.signerOrProvider)
400
- ? this.signerOrProvider.populateTransaction(tx)
401
- : tx;
402
- });
403
- }
404
- swapOutRouted(tokenIn, tokenOut, amountOut, amountInMax, tradablePair) {
405
- return __awaiter(this, void 0, void 0, function* () {
406
- const steps = this.buildSteps(tokenIn, tokenOut, tradablePair);
407
- const tx = yield this.router.populateTransaction.swapTokensForExactTokens(amountOut, amountInMax, steps);
408
- return Signer.isSigner(this.signerOrProvider)
409
- ? this.signerOrProvider.populateTransaction(tx)
410
- : tx;
411
- });
412
- }
413
- /**
414
- * Helper method to build the steps for a routed swap, ensuring proper token ordering
415
- * through the path segments
416
- */
417
- buildSteps(tokenIn, tokenOut, tradablePair) {
418
- let path = [...tradablePair.path];
419
- if (path[0].assets.includes(tokenOut)) {
420
- path = path.reverse();
421
- }
422
- return path.map((step, idx) => {
423
- const isFirstStep = idx === 0;
424
- const isLastStep = idx === tradablePair.path.length - 1;
425
- const prevStep = idx > 0 ? tradablePair.path[idx - 1] : null;
426
- // For first step, ensure assetIn is tokenIn
427
- // For middle steps, ensure assetIn matches previous step's assetOut
428
- // For last step, ensure assetOut is tokenOut
429
- let [assetIn, assetOut] = step.assets;
430
- if (isFirstStep && assetIn !== tokenIn) {
431
- ;
432
- [assetIn, assetOut] = [assetOut, assetIn];
433
- }
434
- else if (!isFirstStep &&
435
- !isLastStep &&
436
- assetIn !== prevStep.assets[1]) {
437
- ;
438
- [assetIn, assetOut] = [assetOut, assetIn];
439
- }
440
- else if (isLastStep && assetOut !== tokenOut) {
441
- ;
442
- [assetIn, assetOut] = [assetOut, assetIn];
443
- }
444
- return {
445
- exchangeProvider: step.providerAddr,
446
- exchangeId: step.id,
447
- assetIn,
448
- assetOut,
449
- };
450
- });
451
- }
452
- /**
453
- * Returns the mento instance's broker contract
454
- * @returns broker contract
455
- */
456
- getBroker() {
457
- return this.broker;
458
- }
459
- /**
460
- * Finds a tradable pair for the given input and output tokens
461
- * @param tokenIn the input token address
462
- * @param tokenOut the output token address
463
- * @returns the tradable pair containing the path between the tokens
464
- * @throws if no path is found between the tokens
465
- */
466
- findPairForTokens(tokenIn, tokenOut) {
467
- return __awaiter(this, void 0, void 0, function* () {
468
- const allPairs = yield this.getTradablePairsWithPath();
469
- // Find the pair for these tokens
470
- const pair = allPairs.find((p) => {
471
- // Check if the pair connects tokenIn to tokenOut
472
- if (p.assets[0].address === tokenIn && p.assets[1].address === tokenOut) {
473
- return true;
474
- }
475
- // Check reverse direction
476
- if (p.assets[0].address === tokenOut && p.assets[1].address === tokenIn) {
477
- return true;
478
- }
479
- return false;
480
- });
481
- if (!pair) {
482
- throw new Error(`No pair found for tokens ${tokenIn} and ${tokenOut}. They may not have a tradable path.`);
483
- }
484
- return pair;
485
- });
486
- }
487
- /**
488
- * Returns the list of exchanges available in Mento (cached)
489
- * @returns the list of exchanges
490
- */
491
- getExchanges() {
492
- return __awaiter(this, void 0, void 0, function* () {
493
- if (this.exchanges.length > 0) {
494
- return this.exchanges;
495
- }
496
- const exchangeProvidersAddresses = yield this.broker.getExchangeProviders();
497
- const exchanges = (yield Promise.all(exchangeProvidersAddresses.map((a) => this.getExchangesForProvider(a)))).flat();
498
- this.exchanges = exchanges;
499
- return exchanges;
500
- });
501
- }
502
- /**
503
- * Returns the list of exchanges for a given exchange provider address
504
- * @returns list of exchanges
505
- */
506
- getExchangesForProvider(exchangeProviderAddr) {
507
- return __awaiter(this, void 0, void 0, function* () {
508
- const exchangeProvider = IExchangeProvider__factory.connect(exchangeProviderAddr, this.signerOrProvider);
509
- const exchangesInProvider = yield exchangeProvider.getExchanges();
510
- return exchangesInProvider.map((e) => {
511
- assert(e.assets.length === 2, 'Exchange must have 2 assets');
512
- return {
513
- providerAddr: exchangeProviderAddr,
514
- id: e.exchangeId,
515
- assets: e.assets,
516
- };
517
- });
518
- });
519
- }
520
- /**
521
- * Returns the Mento exchange (if any) for a given pair of tokens
522
- * @param token0 the address of the first token
523
- * @param token1 the address of the second token
524
- * @returns exchange
525
- */
526
- getExchangeForTokens(token0, token1) {
527
- return __awaiter(this, void 0, void 0, function* () {
528
- const exchanges = (yield this.getExchanges()).filter((e) => e.assets.includes(token0) && e.assets.includes(token1));
529
- if (exchanges.length === 0) {
530
- throw Error(`No exchange found for ${token0} and ${token1}`);
531
- }
532
- assert(exchanges.length === 1, `More than one exchange found for ${token0} and ${token1}`);
533
- return exchanges[0];
534
- });
535
- }
536
- /**
537
- * Returns the Mento exchange for a given exchange id
538
- * @param exchangeId the id of the exchange
539
- * @returns the exchange with the given id
540
- */
541
- getExchangeById(exchangeId) {
542
- return __awaiter(this, void 0, void 0, function* () {
543
- const exchanges = (yield this.getExchanges()).filter((e) => e.id === exchangeId);
544
- if (exchanges.length === 0) {
545
- throw Error(`No exchange found for id ${exchangeId}`);
546
- }
547
- assert(exchanges.length === 1, `More than one exchange found with id ${exchangeId}`);
548
- return exchanges[0];
549
- });
550
- }
551
- /**
552
- * Returns whether trading is enabled in the given mode for a given exchange id
553
- * @param exchangeId the id of the exchange
554
- * @param mode the trading mode
555
- * @returns true if trading is enabled in the given mode, false otherwise
556
- */
557
- isTradingEnabled(exchangeId) {
558
- return __awaiter(this, void 0, void 0, function* () {
559
- const exchange = yield this.getExchangeById(exchangeId);
560
- const biPoolManager = BiPoolManager__factory.connect(exchange.providerAddr, this.signerOrProvider);
561
- const [breakerBoxAddr, exchangeConfig] = yield Promise.all([
562
- biPoolManager.breakerBox(),
563
- biPoolManager.getPoolExchange(exchangeId),
564
- ]);
565
- const breakerBox = IBreakerBox__factory.connect(breakerBoxAddr, this.signerOrProvider);
566
- const currentMode = yield breakerBox.getRateFeedTradingMode(exchangeConfig.config.referenceRateFeedID);
567
- const BI_DIRECTIONAL_TRADING_MODE = 0;
568
- return currentMode == BI_DIRECTIONAL_TRADING_MODE;
569
- });
570
- }
571
- /**
572
- * Returns the current trading mode for a given rate feed
573
- * @param rateFeedId the address of the rate feed
574
- * @returns the current trading mode (BIDIRECTIONAL, HALTED, or DISABLED)
575
- */
576
- getRateFeedTradingMode(rateFeedId) {
577
- return __awaiter(this, void 0, void 0, function* () {
578
- const breakerBoxAddr = yield this.getAddress('BreakerBox');
579
- const breakerBox = IBreakerBox__factory.connect(breakerBoxAddr, this.signerOrProvider);
580
- const currentMode = yield breakerBox.getRateFeedTradingMode(rateFeedId);
581
- return currentMode;
582
- });
583
- }
584
- /**
585
- * Checks if a trading pair is currently tradable (i.e., all rate feeds in the path are in BIDIRECTIONAL mode)
586
- * For multi-hop routes (e.g., CELO → cUSD → USDT), checks that all intermediate rate feeds are tradable
587
- * @param tokenIn the address of the token to sell
588
- * @param tokenOut the address of the token to buy
589
- * @returns true if the pair is tradable (all rate feeds in BIDIRECTIONAL mode), false otherwise
590
- */
591
- isPairTradable(tokenIn, tokenOut) {
592
- return __awaiter(this, void 0, void 0, function* () {
593
- // Find the tradable pair (which includes the routing path)
594
- const pair = yield this.findPairForTokens(tokenIn, tokenOut);
595
- // For each hop in the path, check if the rate feed is tradable
596
- const biPoolManager = BiPoolManager__factory.connect(pair.path[0].providerAddr, this.signerOrProvider);
597
- // Get all rate feed IDs for each hop in the path
598
- const rateFeedChecks = yield Promise.all(pair.path.map((hop) => __awaiter(this, void 0, void 0, function* () {
599
- const exchangeConfig = yield biPoolManager.getPoolExchange(hop.id);
600
- const rateFeedId = exchangeConfig.config.referenceRateFeedID;
601
- const tradingMode = yield this.getRateFeedTradingMode(rateFeedId);
602
- return tradingMode === TradingMode.BIDIRECTIONAL;
603
- })));
604
- // All rate feeds must be in BIDIRECTIONAL mode for the pair to be tradable
605
- return rateFeedChecks.every((isTradable) => isTradable);
606
- });
607
- }
608
- /**
609
- * Return the trading limits for a given exchange id. Each limit is an object with the following fields:
610
- * asset: the address of the asset with the limit
611
- * maxIn: the maximum amount of the asset that can be sold
612
- * maxOut: the maximum amount of the asset that can be bought
613
- * until: the timestamp until which the limit is valid
614
- * @param exchangeId the id of the exchange
615
- * @returns the list of trading limits
616
- */
617
- getTradingLimits(exchangeId) {
618
- return __awaiter(this, void 0, void 0, function* () {
619
- const exchange = yield this.getExchangeById(exchangeId);
620
- const broker = Broker__factory.connect(this.broker.address, this.signerOrProvider);
621
- const asset0Limits = yield getLimits(broker, exchangeId, exchange.assets[0]);
622
- const asset1Limits = yield getLimits(broker, exchangeId, exchange.assets[1]);
623
- return asset0Limits.concat(asset1Limits);
624
- });
625
- }
626
- /**
627
- * Returns the trading limits configurations for a given exchange id
628
- * @param exchangeId the id of the exchange
629
- * @returns the trading limits configuration
630
- */
631
- getTradingLimitConfig(exchangeId) {
632
- return __awaiter(this, void 0, void 0, function* () {
633
- const exchange = yield this.getExchangeById(exchangeId);
634
- const broker = Broker__factory.connect(this.broker.address, this.signerOrProvider);
635
- const cfgs = [];
636
- for (const asset of exchange.assets) {
637
- const limitCfg = yield getLimitsConfig(broker, exchangeId, asset);
638
- const isLimitConfigured = limitCfg.flags > 0;
639
- if (isLimitConfigured) {
640
- cfgs.push(limitCfg);
641
- }
642
- }
643
- return cfgs;
644
- });
645
- }
646
- /**
647
- * Returns the trading limits state for a given exchange id
648
- * @param exchangeId the id of the exchange
649
- * @returns the trading limits state
650
- */
651
- getTradingLimitState(exchangeId) {
652
- return __awaiter(this, void 0, void 0, function* () {
653
- const broker = Broker__factory.connect(this.broker.address, this.signerOrProvider);
654
- const configuredLimitCfgs = yield this.getTradingLimitConfig(exchangeId);
655
- return yield Promise.all(configuredLimitCfgs.map((cfg) => __awaiter(this, void 0, void 0, function* () { return yield getLimitsState(broker, exchangeId, cfg.asset); })));
656
- });
657
- }
658
- getAddress(identifier) {
659
- return __awaiter(this, void 0, void 0, function* () {
660
- return getAddress(identifier, yield this.chainId());
661
- });
662
- }
663
- chainId() {
664
- return __awaiter(this, void 0, void 0, function* () {
665
- if (!this.cachedChainId) {
666
- this.cachedChainId = yield getChainId(this.signerOrProvider);
667
- }
668
- return this.cachedChainId;
669
- });
670
- }
671
- }