@centurion_project/router-sdk 2.11.10 → 2.11.12

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 (58) hide show
  1. package/dist/cjs/src/entities/mixedRoute/route.js +4 -19
  2. package/dist/cjs/src/entities/mixedRoute/route.js.map +1 -1
  3. package/dist/cjs/src/utils/index.js +19 -7
  4. package/dist/cjs/src/utils/index.js.map +1 -1
  5. package/dist/esm/src/entities/mixedRoute/route.js +5 -20
  6. package/dist/esm/src/entities/mixedRoute/route.js.map +1 -1
  7. package/dist/esm/src/utils/index.js +19 -7
  8. package/dist/esm/src/utils/index.js.map +1 -1
  9. package/dist/types/src/approveAndCall.d.ts +1 -0
  10. package/dist/types/src/approveAndCall.d.ts.map +1 -0
  11. package/dist/types/src/constants.d.ts +1 -0
  12. package/dist/types/src/constants.d.ts.map +1 -0
  13. package/dist/types/src/entities/mixedRoute/route.d.ts +1 -0
  14. package/dist/types/src/entities/mixedRoute/route.d.ts.map +1 -0
  15. package/dist/types/src/entities/mixedRoute/trade.d.ts +1 -0
  16. package/dist/types/src/entities/mixedRoute/trade.d.ts.map +1 -0
  17. package/dist/types/src/entities/protocol.d.ts +1 -0
  18. package/dist/types/src/entities/protocol.d.ts.map +1 -0
  19. package/dist/types/src/entities/route.d.ts +1 -0
  20. package/dist/types/src/entities/route.d.ts.map +1 -0
  21. package/dist/types/src/entities/trade.d.ts +1 -0
  22. package/dist/types/src/entities/trade.d.ts.map +1 -0
  23. package/dist/types/src/index.d.ts +1 -0
  24. package/dist/types/src/index.d.ts.map +1 -0
  25. package/dist/types/src/multicallExtended.d.ts +1 -0
  26. package/dist/types/src/multicallExtended.d.ts.map +1 -0
  27. package/dist/types/src/paymentsExtended.d.ts +1 -0
  28. package/dist/types/src/paymentsExtended.d.ts.map +1 -0
  29. package/dist/types/src/swapRouter.d.ts +1 -0
  30. package/dist/types/src/swapRouter.d.ts.map +1 -0
  31. package/dist/types/src/utils/TPool.d.ts +1 -0
  32. package/dist/types/src/utils/TPool.d.ts.map +1 -0
  33. package/dist/types/src/utils/encodeMixedRouteToPath.d.ts +1 -0
  34. package/dist/types/src/utils/encodeMixedRouteToPath.d.ts.map +1 -0
  35. package/dist/types/src/utils/index.d.ts +1 -0
  36. package/dist/types/src/utils/index.d.ts.map +1 -0
  37. package/dist/types/src/utils/pathCurrency.d.ts +1 -0
  38. package/dist/types/src/utils/pathCurrency.d.ts.map +1 -0
  39. package/package.json +12 -9
  40. package/src/abis/IApproveAndCall.json +213 -0
  41. package/src/abis/IMulticallExtended.json +78 -0
  42. package/src/abis/IPeripheryPaymentsWithFeeExtended.json +233 -0
  43. package/src/abis/ISwapRouter02.json +717 -0
  44. package/src/approveAndCall.ts +129 -0
  45. package/src/constants.ts +24 -0
  46. package/src/entities/mixedRoute/route.ts +121 -0
  47. package/src/entities/mixedRoute/trade.ts +530 -0
  48. package/src/entities/protocol.ts +6 -0
  49. package/src/entities/route.ts +94 -0
  50. package/src/entities/trade.ts +550 -0
  51. package/src/index.ts +14 -0
  52. package/src/multicallExtended.ts +48 -0
  53. package/src/paymentsExtended.ts +75 -0
  54. package/src/swapRouter.ts +700 -0
  55. package/src/utils/TPool.ts +5 -0
  56. package/src/utils/encodeMixedRouteToPath.ts +112 -0
  57. package/src/utils/index.ts +66 -0
  58. package/src/utils/pathCurrency.ts +36 -0
@@ -0,0 +1,530 @@
1
+ import {
2
+ Currency,
3
+ Fraction,
4
+ Percent,
5
+ Price,
6
+ sortedInsert,
7
+ CurrencyAmount,
8
+ TradeType,
9
+ Token,
10
+ } from '@centurion_project/sdk-core'
11
+ import { Pair } from '@centurion_project/v2-sdk'
12
+ import { BestTradeOptions, Pool as V3Pool } from '@centurion_project/v3-sdk'
13
+ import { Pool as V4Pool } from '@centurion_project/v4-sdk'
14
+ import JSBI from 'jsbi'
15
+ import invariant from 'tiny-invariant'
16
+ import { ONE, ZERO } from '../../constants'
17
+ import { MixedRouteSDK } from './route'
18
+ import { amountWithPathCurrency } from '../../utils/pathCurrency'
19
+ import { TPool } from '../../utils/TPool'
20
+
21
+ /**
22
+ * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
23
+ * @template TInput The input token, either Ether or an ERC-20
24
+ * @template TOutput The output token, either Ether or an ERC-20
25
+ * @template TTradeType The trade type, either exact input or exact output
26
+ * @param a The first trade to compare
27
+ * @param b The second trade to compare
28
+ * @returns A sorted ordering for two neighboring elements in a trade array
29
+ */
30
+ export function tradeComparator<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
31
+ a: MixedRouteTrade<TInput, TOutput, TTradeType>,
32
+ b: MixedRouteTrade<TInput, TOutput, TTradeType>
33
+ ) {
34
+ // must have same input and output token for comparison
35
+ invariant(a.inputAmount.currency.equals(b.inputAmount.currency), 'INPUT_CURRENCY')
36
+ invariant(a.outputAmount.currency.equals(b.outputAmount.currency), 'OUTPUT_CURRENCY')
37
+ if (a.outputAmount.equalTo(b.outputAmount)) {
38
+ if (a.inputAmount.equalTo(b.inputAmount)) {
39
+ // consider the number of hops since each hop costs gas
40
+ const aHops = a.swaps.reduce((total, cur) => total + cur.route.path.length, 0)
41
+ const bHops = b.swaps.reduce((total, cur) => total + cur.route.path.length, 0)
42
+ return aHops - bHops
43
+ }
44
+ // trade A requires less input than trade B, so A should come first
45
+ if (a.inputAmount.lessThan(b.inputAmount)) {
46
+ return -1
47
+ } else {
48
+ return 1
49
+ }
50
+ } else {
51
+ // tradeA has less output than trade B, so should come second
52
+ if (a.outputAmount.lessThan(b.outputAmount)) {
53
+ return 1
54
+ } else {
55
+ return -1
56
+ }
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Represents a trade executed against a set of routes where some percentage of the input is
62
+ * split across each route.
63
+ *
64
+ * Each route has its own set of pools. Pools can not be re-used across routes.
65
+ *
66
+ * Does not account for slippage, i.e., changes in price environment that can occur between
67
+ * the time the trade is submitted and when it is executed.
68
+ * @notice This class is functionally the same as the `Trade` class in the `@centurion_project/v3-sdk` package, aside from typing and some input validation.
69
+ * @template TInput The input token, either Ether or an ERC-20
70
+ * @template TOutput The output token, either Ether or an ERC-20
71
+ * @template TTradeType The trade type, either exact input or exact output
72
+ */
73
+ export class MixedRouteTrade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
74
+ /**
75
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
76
+ * this will return an error.
77
+ *
78
+ * When the trade consists of just a single route, this returns the route of the trade,
79
+ * i.e. which pools the trade goes through.
80
+ */
81
+ public get route(): MixedRouteSDK<TInput, TOutput> {
82
+ invariant(this.swaps.length === 1, 'MULTIPLE_ROUTES')
83
+ return this.swaps[0].route
84
+ }
85
+
86
+ /**
87
+ * The swaps of the trade, i.e. which routes and how much is swapped in each that
88
+ * make up the trade.
89
+ */
90
+ public readonly swaps: {
91
+ route: MixedRouteSDK<TInput, TOutput>
92
+ inputAmount: CurrencyAmount<TInput>
93
+ outputAmount: CurrencyAmount<TOutput>
94
+ }[]
95
+
96
+ /**
97
+ * The type of the trade, either exact in or exact out.
98
+ */
99
+ public readonly tradeType: TTradeType
100
+
101
+ /**
102
+ * The cached result of the input amount computation
103
+ * @private
104
+ */
105
+ private _inputAmount: CurrencyAmount<TInput> | undefined
106
+
107
+ /**
108
+ * The input amount for the trade assuming no slippage.
109
+ */
110
+ public get inputAmount(): CurrencyAmount<TInput> {
111
+ if (this._inputAmount) {
112
+ return this._inputAmount
113
+ }
114
+
115
+ const inputCurrency = this.swaps[0].inputAmount.currency
116
+ const totalInputFromRoutes = this.swaps
117
+ .map(({ inputAmount }) => inputAmount)
118
+ .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(inputCurrency, 0))
119
+
120
+ this._inputAmount = totalInputFromRoutes
121
+ return this._inputAmount
122
+ }
123
+
124
+ /**
125
+ * The cached result of the output amount computation
126
+ * @private
127
+ */
128
+ private _outputAmount: CurrencyAmount<TOutput> | undefined
129
+
130
+ /**
131
+ * The output amount for the trade assuming no slippage.
132
+ */
133
+ public get outputAmount(): CurrencyAmount<TOutput> {
134
+ if (this._outputAmount) {
135
+ return this._outputAmount
136
+ }
137
+
138
+ const outputCurrency = this.swaps[0].outputAmount.currency
139
+ const totalOutputFromRoutes = this.swaps
140
+ .map(({ outputAmount }) => outputAmount)
141
+ .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(outputCurrency, 0))
142
+
143
+ this._outputAmount = totalOutputFromRoutes
144
+ return this._outputAmount
145
+ }
146
+
147
+ /**
148
+ * The cached result of the computed execution price
149
+ * @private
150
+ */
151
+ private _executionPrice: Price<TInput, TOutput> | undefined
152
+
153
+ /**
154
+ * The price expressed in terms of output amount/input amount.
155
+ */
156
+ public get executionPrice(): Price<TInput, TOutput> {
157
+ return (
158
+ this._executionPrice ??
159
+ (this._executionPrice = new Price(
160
+ this.inputAmount.currency,
161
+ this.outputAmount.currency,
162
+ this.inputAmount.quotient,
163
+ this.outputAmount.quotient
164
+ ))
165
+ )
166
+ }
167
+
168
+ /**
169
+ * The cached result of the price impact computation
170
+ * @private
171
+ */
172
+ private _priceImpact: Percent | undefined
173
+
174
+ /**
175
+ * Returns the percent difference between the route's mid price and the price impact
176
+ */
177
+ public get priceImpact(): Percent {
178
+ if (this._priceImpact) {
179
+ return this._priceImpact
180
+ }
181
+
182
+ let spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0)
183
+ for (const { route, inputAmount } of this.swaps) {
184
+ const midPrice = route.midPrice
185
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount))
186
+ }
187
+
188
+ const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount)
189
+ this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator)
190
+
191
+ return this._priceImpact
192
+ }
193
+
194
+ /**
195
+ * Constructs a trade by simulating swaps through the given route
196
+ * @template TInput The input token, either Ether or an ERC-20.
197
+ * @template TOutput The output token, either Ether or an ERC-20.
198
+ * @template TTradeType The type of the trade, either exact in or exact out.
199
+ * @param route route to swap through
200
+ * @param amount the amount specified, either input or output, depending on tradeType
201
+ * @param tradeType whether the trade is an exact input or exact output swap
202
+ * @returns The route
203
+ */
204
+ public static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
205
+ route: MixedRouteSDK<TInput, TOutput>,
206
+ amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,
207
+ tradeType: TTradeType
208
+ ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {
209
+ const amounts: CurrencyAmount<Currency>[] = new Array(route.path.length)
210
+ let inputAmount: CurrencyAmount<TInput>
211
+ let outputAmount: CurrencyAmount<TOutput>
212
+
213
+ invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')
214
+ invariant(amount.currency.equals(route.input), 'INPUT')
215
+
216
+ amounts[0] = amountWithPathCurrency(amount, route.pools[0])
217
+ for (let i = 0; i < route.path.length - 1; i++) {
218
+ const pool = route.pools[i]
219
+ const [outputAmount] = await pool.getOutputAmount(
220
+ amountWithPathCurrency(amounts[i], pool) as CurrencyAmount<Token>
221
+ )
222
+ amounts[i + 1] = outputAmount
223
+ }
224
+
225
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)
226
+ outputAmount = CurrencyAmount.fromFractionalAmount(
227
+ route.output,
228
+ amounts[amounts.length - 1].numerator,
229
+ amounts[amounts.length - 1].denominator
230
+ )
231
+
232
+ return new MixedRouteTrade({
233
+ routes: [{ inputAmount, outputAmount, route }],
234
+ tradeType,
235
+ })
236
+ }
237
+
238
+ /**
239
+ * Constructs a trade from routes by simulating swaps
240
+ *
241
+ * @template TInput The input token, either Ether or an ERC-20.
242
+ * @template TOutput The output token, either Ether or an ERC-20.
243
+ * @template TTradeType The type of the trade, either exact in or exact out.
244
+ * @param routes the routes to swap through and how much of the amount should be routed through each
245
+ * @param tradeType whether the trade is an exact input or exact output swap
246
+ * @returns The trade
247
+ */
248
+ public static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
249
+ routes: {
250
+ amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>
251
+ route: MixedRouteSDK<TInput, TOutput>
252
+ }[],
253
+ tradeType: TTradeType
254
+ ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {
255
+ const populatedRoutes: {
256
+ route: MixedRouteSDK<TInput, TOutput>
257
+ inputAmount: CurrencyAmount<TInput>
258
+ outputAmount: CurrencyAmount<TOutput>
259
+ }[] = []
260
+
261
+ invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')
262
+
263
+ for (const { route, amount } of routes) {
264
+ const amounts: CurrencyAmount<Currency>[] = new Array(route.path.length)
265
+ let inputAmount: CurrencyAmount<TInput>
266
+ let outputAmount: CurrencyAmount<TOutput>
267
+
268
+ invariant(amount.currency.equals(route.input), 'INPUT')
269
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)
270
+ amounts[0] = CurrencyAmount.fromFractionalAmount(route.pathInput, amount.numerator, amount.denominator)
271
+
272
+ for (let i = 0; i < route.path.length - 1; i++) {
273
+ const pool = route.pools[i]
274
+ const [outputAmount] = await pool.getOutputAmount(
275
+ amountWithPathCurrency(amounts[i], pool) as CurrencyAmount<Token>
276
+ )
277
+ amounts[i + 1] = outputAmount
278
+ }
279
+
280
+ outputAmount = CurrencyAmount.fromFractionalAmount(
281
+ route.output,
282
+ amounts[amounts.length - 1].numerator,
283
+ amounts[amounts.length - 1].denominator
284
+ )
285
+
286
+ populatedRoutes.push({ route, inputAmount, outputAmount })
287
+ }
288
+
289
+ return new MixedRouteTrade({
290
+ routes: populatedRoutes,
291
+ tradeType,
292
+ })
293
+ }
294
+
295
+ /**
296
+ * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
297
+ * elsewhere and do not have any tick data
298
+ * @template TInput The input token, either Ether or an ERC-20
299
+ * @template TOutput The output token, either Ether or an ERC-20
300
+ * @template TTradeType The type of the trade, either exact in or exact out
301
+ * @param constructorArguments The arguments passed to the trade constructor
302
+ * @returns The unchecked trade
303
+ */
304
+ public static createUncheckedTrade<
305
+ TInput extends Currency,
306
+ TOutput extends Currency,
307
+ TTradeType extends TradeType
308
+ >(constructorArguments: {
309
+ route: MixedRouteSDK<TInput, TOutput>
310
+ inputAmount: CurrencyAmount<TInput>
311
+ outputAmount: CurrencyAmount<TOutput>
312
+ tradeType: TTradeType
313
+ }): MixedRouteTrade<TInput, TOutput, TTradeType> {
314
+ return new MixedRouteTrade({
315
+ ...constructorArguments,
316
+ routes: [
317
+ {
318
+ inputAmount: constructorArguments.inputAmount,
319
+ outputAmount: constructorArguments.outputAmount,
320
+ route: constructorArguments.route,
321
+ },
322
+ ],
323
+ })
324
+ }
325
+
326
+ /**
327
+ * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
328
+ * elsewhere and do not have any tick data
329
+ * @template TInput The input token, either Ether or an ERC-20
330
+ * @template TOutput The output token, either Ether or an ERC-20
331
+ * @template TTradeType The type of the trade, either exact in or exact out
332
+ * @param constructorArguments The arguments passed to the trade constructor
333
+ * @returns The unchecked trade
334
+ */
335
+ public static createUncheckedTradeWithMultipleRoutes<
336
+ TInput extends Currency,
337
+ TOutput extends Currency,
338
+ TTradeType extends TradeType
339
+ >(constructorArguments: {
340
+ routes: {
341
+ route: MixedRouteSDK<TInput, TOutput>
342
+ inputAmount: CurrencyAmount<TInput>
343
+ outputAmount: CurrencyAmount<TOutput>
344
+ }[]
345
+ tradeType: TTradeType
346
+ }): MixedRouteTrade<TInput, TOutput, TTradeType> {
347
+ return new MixedRouteTrade(constructorArguments)
348
+ }
349
+
350
+ /**
351
+ * Construct a trade by passing in the pre-computed property values
352
+ * @param routes The routes through which the trade occurs
353
+ * @param tradeType The type of trade, exact input or exact output
354
+ */
355
+ private constructor({
356
+ routes,
357
+ tradeType,
358
+ }: {
359
+ routes: {
360
+ route: MixedRouteSDK<TInput, TOutput>
361
+ inputAmount: CurrencyAmount<TInput>
362
+ outputAmount: CurrencyAmount<TOutput>
363
+ }[]
364
+ tradeType: TTradeType
365
+ }) {
366
+ const inputCurrency = routes[0].inputAmount.currency
367
+ const outputCurrency = routes[0].outputAmount.currency
368
+ invariant(
369
+ routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),
370
+ 'INPUT_CURRENCY_MATCH'
371
+ )
372
+ invariant(
373
+ routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),
374
+ 'OUTPUT_CURRENCY_MATCH'
375
+ )
376
+
377
+ const numPools = routes.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0)
378
+ const poolIdentifierSet = new Set<string>()
379
+ for (const { route } of routes) {
380
+ for (const pool of route.pools) {
381
+ if (pool instanceof V4Pool) {
382
+ poolIdentifierSet.add(pool.poolId)
383
+ } else if (pool instanceof V3Pool) {
384
+ poolIdentifierSet.add(V3Pool.getAddress(pool.token0, pool.token1, pool.fee))
385
+ } else if (pool instanceof Pair) {
386
+ const pair = pool
387
+ poolIdentifierSet.add(Pair.getAddress(pair.token0, pair.token1))
388
+ } else {
389
+ throw new Error('Unexpected pool type in route when constructing trade object')
390
+ }
391
+ }
392
+ }
393
+
394
+ invariant(numPools === poolIdentifierSet.size, 'POOLS_DUPLICATED')
395
+
396
+ invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')
397
+
398
+ this.swaps = routes
399
+ this.tradeType = tradeType
400
+ }
401
+
402
+ /**
403
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
404
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
405
+ * @returns The amount out
406
+ */
407
+ public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<TOutput> {
408
+ invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')
409
+ /// does not support exactOutput, as enforced in the constructor
410
+ const slippageAdjustedAmountOut = new Fraction(ONE)
411
+ .subtract(slippageTolerance)
412
+ .multiply(amountOut.quotient).quotient
413
+ const clampedAmount = JSBI.greaterThan(slippageAdjustedAmountOut, JSBI.BigInt(0))
414
+ ? slippageAdjustedAmountOut
415
+ : JSBI.BigInt(0)
416
+ return CurrencyAmount.fromRawAmount(amountOut.currency, clampedAmount)
417
+ }
418
+
419
+ /**
420
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
421
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
422
+ * @returns The amount in
423
+ */
424
+ public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<TInput> {
425
+ invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')
426
+ return amountIn
427
+ /// does not support exactOutput
428
+ }
429
+
430
+ /**
431
+ * Return the execution price after accounting for slippage tolerance
432
+ * @param slippageTolerance the allowed tolerated slippage
433
+ * @returns The execution price
434
+ */
435
+ public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {
436
+ return new Price(
437
+ this.inputAmount.currency,
438
+ this.outputAmount.currency,
439
+ this.maximumAmountIn(slippageTolerance).quotient,
440
+ this.minimumAmountOut(slippageTolerance).quotient
441
+ )
442
+ }
443
+
444
+ /**
445
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
446
+ * amount to an output token, making at most `maxHops` hops.
447
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
448
+ * the amount in among multiple routes.
449
+ * @param pools the pools to consider in finding the best trade
450
+ * @param nextAmountIn exact amount of input currency to spend
451
+ * @param currencyOut the desired currency out
452
+ * @param maxNumResults maximum number of results to return
453
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
454
+ * @param currentPools used in recursion; the current list of pools
455
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
456
+ * @param bestTrades used in recursion; the current list of best trades
457
+ * @returns The exact in trade
458
+ */
459
+ public static async bestTradeExactIn<TInput extends Currency, TOutput extends Currency>(
460
+ pools: TPool[],
461
+ currencyAmountIn: CurrencyAmount<TInput>,
462
+ currencyOut: TOutput,
463
+ { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {},
464
+ // used in recursion.
465
+ currentPools: TPool[] = [],
466
+ nextAmountIn: CurrencyAmount<Currency> = currencyAmountIn,
467
+ bestTrades: MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[] = []
468
+ ): Promise<MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[]> {
469
+ invariant(pools.length > 0, 'POOLS')
470
+ invariant(maxHops > 0, 'MAX_HOPS')
471
+ invariant(currencyAmountIn === nextAmountIn || currentPools.length > 0, 'INVALID_RECURSION')
472
+
473
+ const amountIn = nextAmountIn
474
+ for (let i = 0; i < pools.length; i++) {
475
+ const pool = pools[i]
476
+ const amountInAdjusted = pool instanceof V4Pool ? amountIn : amountIn.wrapped
477
+ // pool irrelevant
478
+ if (!pool.token0.equals(amountInAdjusted.currency) && !pool.token1.equals(amountInAdjusted.currency)) continue
479
+ if (pool instanceof Pair) {
480
+ if ((pool as Pair).reserve0.equalTo(ZERO) || (pool as Pair).reserve1.equalTo(ZERO)) continue
481
+ }
482
+
483
+ let amountOut: CurrencyAmount<Currency>
484
+ try {
485
+ ;[amountOut] =
486
+ pool instanceof V4Pool
487
+ ? await pool.getOutputAmount(amountInAdjusted)
488
+ : await pool.getOutputAmount(amountInAdjusted.wrapped)
489
+ } catch (error) {
490
+ // input too low
491
+ // @ts-ignore[2571] error is unknown
492
+ if (error.isInsufficientInputAmountError) {
493
+ continue
494
+ }
495
+ throw error
496
+ }
497
+ // we have arrived at the output token, so this is the final trade of one of the paths
498
+ if (amountOut.currency.wrapped.equals(currencyOut.wrapped)) {
499
+ sortedInsert(
500
+ bestTrades,
501
+ await MixedRouteTrade.fromRoute(
502
+ new MixedRouteSDK([...currentPools, pool], currencyAmountIn.currency, currencyOut),
503
+ currencyAmountIn,
504
+ TradeType.EXACT_INPUT
505
+ ),
506
+ maxNumResults,
507
+ tradeComparator
508
+ )
509
+ } else if (maxHops > 1 && pools.length > 1) {
510
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length))
511
+
512
+ // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
513
+ await MixedRouteTrade.bestTradeExactIn(
514
+ poolsExcludingThisPool,
515
+ currencyAmountIn,
516
+ currencyOut,
517
+ {
518
+ maxNumResults,
519
+ maxHops: maxHops - 1,
520
+ },
521
+ [...currentPools, pool],
522
+ amountOut,
523
+ bestTrades
524
+ )
525
+ }
526
+ }
527
+
528
+ return bestTrades
529
+ }
530
+ }
@@ -0,0 +1,6 @@
1
+ export enum Protocol {
2
+ V2 = 'V2',
3
+ V3 = 'V3',
4
+ V4 = 'V4',
5
+ MIXED = 'MIXED',
6
+ }
@@ -0,0 +1,94 @@
1
+ // entities/route.ts
2
+
3
+ import { Route as V2RouteSDK, Pair } from '@centurion_project/v2-sdk'
4
+ import { Route as V3RouteSDK, Pool as V3Pool } from '@centurion_project/v3-sdk'
5
+ import { Route as V4RouteSDK, Pool as V4Pool } from '@centurion_project/v4-sdk'
6
+ import { Protocol } from './protocol'
7
+ import { Currency, Price, Token } from '@centurion_project/sdk-core'
8
+ import { MixedRouteSDK } from './mixedRoute/route'
9
+
10
+ // Helper function to get the pathInput and pathOutput for a V2 / V3 route
11
+ // currency could be native so we check against the wrapped version as they don't support native ETH in path
12
+ export function getPathToken(currency: Currency, pool: Pair | V3Pool): Token {
13
+ if (pool.token0.wrapped.equals(currency.wrapped)) {
14
+ return pool.token0
15
+ } else if (pool.token1.wrapped.equals(currency.wrapped)) {
16
+ return pool.token1
17
+ } else {
18
+ throw new Error(`Expected token ${currency.symbol} to be either ${pool.token0.symbol} or ${pool.token1.symbol}`)
19
+ }
20
+ }
21
+
22
+ export interface IRoute<TInput extends Currency, TOutput extends Currency, TPool extends Pair | V3Pool | V4Pool> {
23
+ protocol: Protocol
24
+ // array of pools if v3 or pairs if v2
25
+ pools: TPool[]
26
+ path: Currency[]
27
+ midPrice: Price<TInput, TOutput>
28
+ input: TInput
29
+ output: TOutput
30
+ pathInput: Currency
31
+ pathOutput: Currency
32
+ }
33
+
34
+ // V2 route wrapper
35
+ export class RouteV2<TInput extends Currency, TOutput extends Currency>
36
+ extends V2RouteSDK<TInput, TOutput>
37
+ implements IRoute<TInput, TOutput, Pair>
38
+ {
39
+ public readonly protocol: Protocol = Protocol.V2
40
+ public readonly pools: Pair[]
41
+ public pathInput: Currency
42
+ public pathOutput: Currency
43
+
44
+ constructor(v2Route: V2RouteSDK<TInput, TOutput>) {
45
+ super(v2Route.pairs, v2Route.input, v2Route.output)
46
+ this.pools = this.pairs
47
+ this.pathInput = getPathToken(v2Route.input, this.pairs[0])
48
+ this.pathOutput = getPathToken(v2Route.output, this.pairs[this.pairs.length - 1])
49
+ }
50
+ }
51
+
52
+ // V3 route wrapper
53
+ export class RouteV3<TInput extends Currency, TOutput extends Currency>
54
+ extends V3RouteSDK<TInput, TOutput>
55
+ implements IRoute<TInput, TOutput, V3Pool>
56
+ {
57
+ public readonly protocol: Protocol = Protocol.V3
58
+ public readonly path: Token[]
59
+ public pathInput: Currency
60
+ public pathOutput: Currency
61
+
62
+ constructor(v3Route: V3RouteSDK<TInput, TOutput>) {
63
+ super(v3Route.pools, v3Route.input, v3Route.output)
64
+ this.path = v3Route.tokenPath
65
+ this.pathInput = getPathToken(v3Route.input, this.pools[0])
66
+ this.pathOutput = getPathToken(v3Route.output, this.pools[this.pools.length - 1])
67
+ }
68
+ }
69
+
70
+ // V4 route wrapper
71
+ export class RouteV4<TInput extends Currency, TOutput extends Currency>
72
+ extends V4RouteSDK<TInput, TOutput>
73
+ implements IRoute<TInput, TOutput, V4Pool>
74
+ {
75
+ public readonly protocol: Protocol = Protocol.V4
76
+ public readonly path: Currency[]
77
+
78
+ constructor(v4Route: V4RouteSDK<TInput, TOutput>) {
79
+ super(v4Route.pools, v4Route.input, v4Route.output)
80
+ this.path = v4Route.currencyPath
81
+ }
82
+ }
83
+
84
+ // Mixed route wrapper
85
+ export class MixedRoute<TInput extends Currency, TOutput extends Currency>
86
+ extends MixedRouteSDK<TInput, TOutput>
87
+ implements IRoute<TInput, TOutput, Pair | V3Pool | V4Pool>
88
+ {
89
+ public readonly protocol: Protocol = Protocol.MIXED
90
+
91
+ constructor(mixedRoute: MixedRouteSDK<TInput, TOutput>) {
92
+ super(mixedRoute.pools, mixedRoute.input, mixedRoute.output)
93
+ }
94
+ }