@centurion_project/v2-sdk 4.20.0-ctn.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -0
  3. package/dist/cjs/src/constants.d.ts +19 -0
  4. package/dist/cjs/src/constants.js +23 -0
  5. package/dist/cjs/src/constants.js.map +1 -0
  6. package/dist/cjs/src/entities/index.d.ts +3 -0
  7. package/dist/cjs/src/entities/index.js +7 -0
  8. package/dist/cjs/src/entities/index.js.map +1 -0
  9. package/dist/cjs/src/entities/pair.d.ts +147 -0
  10. package/dist/cjs/src/entities/pair.js +318 -0
  11. package/dist/cjs/src/entities/pair.js.map +1 -0
  12. package/dist/cjs/src/entities/route.d.ts +12 -0
  13. package/dist/cjs/src/entities/route.js +45 -0
  14. package/dist/cjs/src/entities/route.js.map +1 -0
  15. package/dist/cjs/src/entities/trade.d.ts +103 -0
  16. package/dist/cjs/src/entities/trade.js +260 -0
  17. package/dist/cjs/src/entities/trade.js.map +1 -0
  18. package/dist/cjs/src/errors.d.ts +16 -0
  19. package/dist/cjs/src/errors.js +34 -0
  20. package/dist/cjs/src/errors.js.map +1 -0
  21. package/dist/cjs/src/index.d.ts +4 -0
  22. package/dist/cjs/src/index.js +12 -0
  23. package/dist/cjs/src/index.js.map +1 -0
  24. package/dist/cjs/src/router.d.ts +64 -0
  25. package/dist/cjs/src/router.js +94 -0
  26. package/dist/cjs/src/router.js.map +1 -0
  27. package/dist/esm/src/constants.d.ts +19 -0
  28. package/dist/esm/src/constants.js +19 -0
  29. package/dist/esm/src/constants.js.map +1 -0
  30. package/dist/esm/src/entities/index.d.ts +3 -0
  31. package/dist/esm/src/entities/index.js +4 -0
  32. package/dist/esm/src/entities/index.js.map +1 -0
  33. package/dist/esm/src/entities/pair.d.ts +147 -0
  34. package/dist/esm/src/entities/pair.js +312 -0
  35. package/dist/esm/src/entities/pair.js.map +1 -0
  36. package/dist/esm/src/entities/route.d.ts +12 -0
  37. package/dist/esm/src/entities/route.js +40 -0
  38. package/dist/esm/src/entities/route.js.map +1 -0
  39. package/dist/esm/src/entities/trade.d.ts +103 -0
  40. package/dist/esm/src/entities/trade.js +253 -0
  41. package/dist/esm/src/entities/trade.js.map +1 -0
  42. package/dist/esm/src/errors.d.ts +16 -0
  43. package/dist/esm/src/errors.js +29 -0
  44. package/dist/esm/src/errors.js.map +1 -0
  45. package/dist/esm/src/index.d.ts +4 -0
  46. package/dist/esm/src/index.js +5 -0
  47. package/dist/esm/src/index.js.map +1 -0
  48. package/dist/esm/src/router.d.ts +64 -0
  49. package/dist/esm/src/router.js +89 -0
  50. package/dist/esm/src/router.js.map +1 -0
  51. package/dist/types/src/constants.d.ts +19 -0
  52. package/dist/types/src/entities/index.d.ts +3 -0
  53. package/dist/types/src/entities/pair.d.ts +147 -0
  54. package/dist/types/src/entities/route.d.ts +12 -0
  55. package/dist/types/src/entities/trade.d.ts +103 -0
  56. package/dist/types/src/errors.d.ts +16 -0
  57. package/dist/types/src/index.d.ts +4 -0
  58. package/dist/types/src/router.d.ts +64 -0
  59. package/package.json +68 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../src/entities/route.ts"],"names":[],"mappings":";;;;AAAA,4EAAsC;AACtC,0DAAoE;AAIpE,MAAa,KAAK;IAMhB,YAAmB,KAAa,EAAE,KAAa,EAAE,MAAe;QA0BxD,cAAS,GAAkC,IAAI,CAAA;QAzBrD,IAAA,wBAAS,EAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,OAAO,CAAC,CAAA;QACpC,MAAM,OAAO,GAAW,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAA;QACxC,IAAA,wBAAS,EACP,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,KAAK,OAAO,CAAC,EAC/C,WAAW,CACZ,CAAA;QAED,MAAM,YAAY,GA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K,CAAC,OAAO,EAAE,EAAE;YAC5C,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;gBAC9B,CAAC,CAAC,IAAI,gBAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBAC3G,CAAC,CAAC,IAAI,gBAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAC9G,CAAA;SACF;QACD,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,YAAY,EAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;QACpH,OAAO,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,gBAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAA;IACtG,CAAC;IAED,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAA;IAC9B,CAAC;CACF;AAnDD,sBAmDC"}
@@ -0,0 +1,103 @@
1
+ import { Currency, CurrencyAmount, Percent, Price, TradeType } from '@centurion_project/sdk-core';
2
+ import { Pair } from './pair';
3
+ import { Route } from './route';
4
+ interface InputOutput<TInput extends Currency, TOutput extends Currency> {
5
+ readonly inputAmount: CurrencyAmount<TInput>;
6
+ readonly outputAmount: CurrencyAmount<TOutput>;
7
+ }
8
+ export declare function inputOutputComparator<TInput extends Currency, TOutput extends Currency>(a: InputOutput<TInput, TOutput>, b: InputOutput<TInput, TOutput>): number;
9
+ export declare function tradeComparator<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(a: Trade<TInput, TOutput, TTradeType>, b: Trade<TInput, TOutput, TTradeType>): number;
10
+ export interface BestTradeOptions {
11
+ maxNumResults?: number;
12
+ maxHops?: number;
13
+ }
14
+ /**
15
+ * Represents a trade executed against a list of pairs.
16
+ * Does not account for slippage, i.e. trades that front run this trade and move the price.
17
+ */
18
+ export declare class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
19
+ /**
20
+ * The route of the trade, i.e. which pairs the trade goes through and the input/output currencies.
21
+ */
22
+ readonly route: Route<TInput, TOutput>;
23
+ /**
24
+ * The type of the trade, either exact in or exact out.
25
+ */
26
+ readonly tradeType: TTradeType;
27
+ /**
28
+ * The input amount for the trade assuming no slippage.
29
+ */
30
+ readonly inputAmount: CurrencyAmount<TInput>;
31
+ /**
32
+ * The output amount for the trade assuming no slippage.
33
+ */
34
+ readonly outputAmount: CurrencyAmount<TOutput>;
35
+ /**
36
+ * The price expressed in terms of output amount/input amount.
37
+ */
38
+ readonly executionPrice: Price<TInput, TOutput>;
39
+ /**
40
+ * The percent difference between the mid price before the trade and the trade execution price.
41
+ */
42
+ readonly priceImpact: Percent;
43
+ /**
44
+ * Constructs an exact in trade with the given amount in and route
45
+ * @param route route of the exact in trade
46
+ * @param amountIn the amount being passed in
47
+ */
48
+ static exactIn<TInput extends Currency, TOutput extends Currency>(route: Route<TInput, TOutput>, amountIn: CurrencyAmount<TInput>): Trade<TInput, TOutput, TradeType.EXACT_INPUT>;
49
+ /**
50
+ * Constructs an exact out trade with the given amount out and route
51
+ * @param route route of the exact out trade
52
+ * @param amountOut the amount returned by the trade
53
+ */
54
+ static exactOut<TInput extends Currency, TOutput extends Currency>(route: Route<TInput, TOutput>, amountOut: CurrencyAmount<TOutput>): Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>;
55
+ constructor(route: Route<TInput, TOutput>, amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>, tradeType: TTradeType);
56
+ /**
57
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
58
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
59
+ */
60
+ minimumAmountOut(slippageTolerance: Percent): CurrencyAmount<TOutput>;
61
+ /**
62
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
63
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
64
+ */
65
+ maximumAmountIn(slippageTolerance: Percent): CurrencyAmount<TInput>;
66
+ /**
67
+ * Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
68
+ * amount to an output token, making at most `maxHops` hops.
69
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
70
+ * the amount in among multiple routes.
71
+ * @param pairs the pairs to consider in finding the best trade
72
+ * @param nextAmountIn exact amount of input currency to spend
73
+ * @param currencyOut the desired currency out
74
+ * @param maxNumResults maximum number of results to return
75
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
76
+ * @param currentPairs used in recursion; the current list of pairs
77
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
78
+ * @param bestTrades used in recursion; the current list of best trades
79
+ */
80
+ static bestTradeExactIn<TInput extends Currency, TOutput extends Currency>(pairs: Pair[], currencyAmountIn: CurrencyAmount<TInput>, currencyOut: TOutput, { maxNumResults, maxHops }?: BestTradeOptions, currentPairs?: Pair[], nextAmountIn?: CurrencyAmount<Currency>, bestTrades?: Trade<TInput, TOutput, TradeType.EXACT_INPUT>[]): Trade<TInput, TOutput, TradeType.EXACT_INPUT>[];
81
+ /**
82
+ * Return the execution price after accounting for slippage tolerance
83
+ * @param slippageTolerance the allowed tolerated slippage
84
+ */
85
+ worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput>;
86
+ /**
87
+ * similar to the above method but instead targets a fixed output amount
88
+ * given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
89
+ * to an output token amount, making at most `maxHops` hops
90
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
91
+ * the amount in among multiple routes.
92
+ * @param pairs the pairs to consider in finding the best trade
93
+ * @param currencyIn the currency to spend
94
+ * @param nextAmountOut the exact amount of currency out
95
+ * @param maxNumResults maximum number of results to return
96
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
97
+ * @param currentPairs used in recursion; the current list of pairs
98
+ * @param currencyAmountOut used in recursion; the original value of the currencyAmountOut parameter
99
+ * @param bestTrades used in recursion; the current list of best trades
100
+ */
101
+ static bestTradeExactOut<TInput extends Currency, TOutput extends Currency>(pairs: Pair[], currencyIn: TInput, currencyAmountOut: CurrencyAmount<TOutput>, { maxNumResults, maxHops }?: BestTradeOptions, currentPairs?: Pair[], nextAmountOut?: CurrencyAmount<Currency>, bestTrades?: Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[]): Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[];
102
+ }
103
+ export {};
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Trade = exports.tradeComparator = exports.inputOutputComparator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const sdk_core_1 = require("@centurion_project/sdk-core");
6
+ const constants_1 = require("../constants");
7
+ const tiny_invariant_1 = tslib_1.__importDefault(require("tiny-invariant"));
8
+ const route_1 = require("./route");
9
+ // comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts
10
+ // in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first
11
+ function inputOutputComparator(a, b) {
12
+ // must have same input and output token for comparison
13
+ (0, tiny_invariant_1.default)(a.inputAmount.currency.equals(b.inputAmount.currency), 'INPUT_CURRENCY');
14
+ (0, tiny_invariant_1.default)(a.outputAmount.currency.equals(b.outputAmount.currency), 'OUTPUT_CURRENCY');
15
+ if (a.outputAmount.equalTo(b.outputAmount)) {
16
+ if (a.inputAmount.equalTo(b.inputAmount)) {
17
+ return 0;
18
+ }
19
+ // trade A requires less input than trade B, so A should come first
20
+ if (a.inputAmount.lessThan(b.inputAmount)) {
21
+ return -1;
22
+ }
23
+ else {
24
+ return 1;
25
+ }
26
+ }
27
+ else {
28
+ // tradeA has less output than trade B, so should come second
29
+ if (a.outputAmount.lessThan(b.outputAmount)) {
30
+ return 1;
31
+ }
32
+ else {
33
+ return -1;
34
+ }
35
+ }
36
+ }
37
+ exports.inputOutputComparator = inputOutputComparator;
38
+ // extension of the input output comparator that also considers other dimensions of the trade in ranking them
39
+ function tradeComparator(a, b) {
40
+ const ioComp = inputOutputComparator(a, b);
41
+ if (ioComp !== 0) {
42
+ return ioComp;
43
+ }
44
+ // consider lowest slippage next, since these are less likely to fail
45
+ if (a.priceImpact.lessThan(b.priceImpact)) {
46
+ return -1;
47
+ }
48
+ else if (a.priceImpact.greaterThan(b.priceImpact)) {
49
+ return 1;
50
+ }
51
+ // finally consider the number of hops since each hop costs gas
52
+ return a.route.path.length - b.route.path.length;
53
+ }
54
+ exports.tradeComparator = tradeComparator;
55
+ /**
56
+ * Represents a trade executed against a list of pairs.
57
+ * Does not account for slippage, i.e. trades that front run this trade and move the price.
58
+ */
59
+ class Trade {
60
+ /**
61
+ * Constructs an exact in trade with the given amount in and route
62
+ * @param route route of the exact in trade
63
+ * @param amountIn the amount being passed in
64
+ */
65
+ static exactIn(route, amountIn) {
66
+ return new Trade(route, amountIn, sdk_core_1.TradeType.EXACT_INPUT);
67
+ }
68
+ /**
69
+ * Constructs an exact out trade with the given amount out and route
70
+ * @param route route of the exact out trade
71
+ * @param amountOut the amount returned by the trade
72
+ */
73
+ static exactOut(route, amountOut) {
74
+ return new Trade(route, amountOut, sdk_core_1.TradeType.EXACT_OUTPUT);
75
+ }
76
+ constructor(route, amount, tradeType) {
77
+ this.route = route;
78
+ this.tradeType = tradeType;
79
+ const tokenAmounts = new Array(route.path.length);
80
+ if (tradeType === sdk_core_1.TradeType.EXACT_INPUT) {
81
+ (0, tiny_invariant_1.default)(amount.currency.equals(route.input), 'INPUT');
82
+ tokenAmounts[0] = amount.wrapped;
83
+ for (let i = 0; i < route.path.length - 1; i++) {
84
+ const pair = route.pairs[i];
85
+ const [outputAmount] = pair.getOutputAmount(tokenAmounts[i]);
86
+ tokenAmounts[i + 1] = outputAmount;
87
+ }
88
+ this.inputAmount = sdk_core_1.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
89
+ this.outputAmount = sdk_core_1.CurrencyAmount.fromFractionalAmount(route.output, tokenAmounts[tokenAmounts.length - 1].numerator, tokenAmounts[tokenAmounts.length - 1].denominator);
90
+ }
91
+ else {
92
+ (0, tiny_invariant_1.default)(amount.currency.equals(route.output), 'OUTPUT');
93
+ tokenAmounts[tokenAmounts.length - 1] = amount.wrapped;
94
+ for (let i = route.path.length - 1; i > 0; i--) {
95
+ const pair = route.pairs[i - 1];
96
+ const [inputAmount] = pair.getInputAmount(tokenAmounts[i]);
97
+ tokenAmounts[i - 1] = inputAmount;
98
+ }
99
+ this.inputAmount = sdk_core_1.CurrencyAmount.fromFractionalAmount(route.input, tokenAmounts[0].numerator, tokenAmounts[0].denominator);
100
+ this.outputAmount = sdk_core_1.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
101
+ }
102
+ this.executionPrice = new sdk_core_1.Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
103
+ this.priceImpact = (0, sdk_core_1.computePriceImpact)(route.midPrice, this.inputAmount, this.outputAmount);
104
+ }
105
+ /**
106
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
107
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
108
+ */
109
+ minimumAmountOut(slippageTolerance) {
110
+ (0, tiny_invariant_1.default)(!slippageTolerance.lessThan(constants_1.ZERO), 'SLIPPAGE_TOLERANCE');
111
+ if (this.tradeType === sdk_core_1.TradeType.EXACT_OUTPUT) {
112
+ return this.outputAmount;
113
+ }
114
+ else {
115
+ const slippageAdjustedAmountOut = new sdk_core_1.Fraction(constants_1.ONE)
116
+ .add(slippageTolerance)
117
+ .invert()
118
+ .multiply(this.outputAmount.quotient).quotient;
119
+ return sdk_core_1.CurrencyAmount.fromRawAmount(this.outputAmount.currency, slippageAdjustedAmountOut);
120
+ }
121
+ }
122
+ /**
123
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
124
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
125
+ */
126
+ maximumAmountIn(slippageTolerance) {
127
+ (0, tiny_invariant_1.default)(!slippageTolerance.lessThan(constants_1.ZERO), 'SLIPPAGE_TOLERANCE');
128
+ if (this.tradeType === sdk_core_1.TradeType.EXACT_INPUT) {
129
+ return this.inputAmount;
130
+ }
131
+ else {
132
+ const slippageAdjustedAmountIn = new sdk_core_1.Fraction(constants_1.ONE)
133
+ .add(slippageTolerance)
134
+ .multiply(this.inputAmount.quotient).quotient;
135
+ return sdk_core_1.CurrencyAmount.fromRawAmount(this.inputAmount.currency, slippageAdjustedAmountIn);
136
+ }
137
+ }
138
+ /**
139
+ * Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
140
+ * amount to an output token, making at most `maxHops` hops.
141
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
142
+ * the amount in among multiple routes.
143
+ * @param pairs the pairs to consider in finding the best trade
144
+ * @param nextAmountIn exact amount of input currency to spend
145
+ * @param currencyOut the desired currency out
146
+ * @param maxNumResults maximum number of results to return
147
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
148
+ * @param currentPairs used in recursion; the current list of pairs
149
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
150
+ * @param bestTrades used in recursion; the current list of best trades
151
+ */
152
+ static bestTradeExactIn(pairs, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {},
153
+ // used in recursion.
154
+ currentPairs = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
155
+ (0, tiny_invariant_1.default)(pairs.length > 0, 'PAIRS');
156
+ (0, tiny_invariant_1.default)(maxHops > 0, 'MAX_HOPS');
157
+ (0, tiny_invariant_1.default)(currencyAmountIn === nextAmountIn || currentPairs.length > 0, 'INVALID_RECURSION');
158
+ const amountIn = nextAmountIn.wrapped;
159
+ const tokenOut = currencyOut.wrapped;
160
+ for (let i = 0; i < pairs.length; i++) {
161
+ const pair = pairs[i];
162
+ // pair irrelevant
163
+ if (!pair.token0.equals(amountIn.currency) && !pair.token1.equals(amountIn.currency))
164
+ continue;
165
+ if (pair.reserve0.equalTo(constants_1.ZERO) || pair.reserve1.equalTo(constants_1.ZERO))
166
+ continue;
167
+ let amountOut;
168
+ try {
169
+ ;
170
+ [amountOut] = pair.getOutputAmount(amountIn);
171
+ }
172
+ catch (error) {
173
+ // input too low
174
+ if (error.isInsufficientInputAmountError) {
175
+ continue;
176
+ }
177
+ throw error;
178
+ }
179
+ // we have arrived at the output token, so this is the final trade of one of the paths
180
+ if (amountOut.currency.equals(tokenOut)) {
181
+ (0, sdk_core_1.sortedInsert)(bestTrades, new Trade(new route_1.Route([...currentPairs, pair], currencyAmountIn.currency, currencyOut), currencyAmountIn, sdk_core_1.TradeType.EXACT_INPUT), maxNumResults, tradeComparator);
182
+ }
183
+ else if (maxHops > 1 && pairs.length > 1) {
184
+ const pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
185
+ // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
186
+ Trade.bestTradeExactIn(pairsExcludingThisPair, currencyAmountIn, currencyOut, {
187
+ maxNumResults,
188
+ maxHops: maxHops - 1,
189
+ }, [...currentPairs, pair], amountOut, bestTrades);
190
+ }
191
+ }
192
+ return bestTrades;
193
+ }
194
+ /**
195
+ * Return the execution price after accounting for slippage tolerance
196
+ * @param slippageTolerance the allowed tolerated slippage
197
+ */
198
+ worstExecutionPrice(slippageTolerance) {
199
+ return new sdk_core_1.Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
200
+ }
201
+ /**
202
+ * similar to the above method but instead targets a fixed output amount
203
+ * given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
204
+ * to an output token amount, making at most `maxHops` hops
205
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
206
+ * the amount in among multiple routes.
207
+ * @param pairs the pairs to consider in finding the best trade
208
+ * @param currencyIn the currency to spend
209
+ * @param nextAmountOut the exact amount of currency out
210
+ * @param maxNumResults maximum number of results to return
211
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
212
+ * @param currentPairs used in recursion; the current list of pairs
213
+ * @param currencyAmountOut used in recursion; the original value of the currencyAmountOut parameter
214
+ * @param bestTrades used in recursion; the current list of best trades
215
+ */
216
+ static bestTradeExactOut(pairs, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {},
217
+ // used in recursion.
218
+ currentPairs = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
219
+ (0, tiny_invariant_1.default)(pairs.length > 0, 'PAIRS');
220
+ (0, tiny_invariant_1.default)(maxHops > 0, 'MAX_HOPS');
221
+ (0, tiny_invariant_1.default)(currencyAmountOut === nextAmountOut || currentPairs.length > 0, 'INVALID_RECURSION');
222
+ const amountOut = nextAmountOut.wrapped;
223
+ const tokenIn = currencyIn.wrapped;
224
+ for (let i = 0; i < pairs.length; i++) {
225
+ const pair = pairs[i];
226
+ // pair irrelevant
227
+ if (!pair.token0.equals(amountOut.currency) && !pair.token1.equals(amountOut.currency))
228
+ continue;
229
+ if (pair.reserve0.equalTo(constants_1.ZERO) || pair.reserve1.equalTo(constants_1.ZERO))
230
+ continue;
231
+ let amountIn;
232
+ try {
233
+ ;
234
+ [amountIn] = pair.getInputAmount(amountOut);
235
+ }
236
+ catch (error) {
237
+ // not enough liquidity in this pair
238
+ if (error.isInsufficientReservesError) {
239
+ continue;
240
+ }
241
+ throw error;
242
+ }
243
+ // we have arrived at the input token, so this is the first trade of one of the paths
244
+ if (amountIn.currency.equals(tokenIn)) {
245
+ (0, sdk_core_1.sortedInsert)(bestTrades, new Trade(new route_1.Route([pair, ...currentPairs], currencyIn, currencyAmountOut.currency), currencyAmountOut, sdk_core_1.TradeType.EXACT_OUTPUT), maxNumResults, tradeComparator);
246
+ }
247
+ else if (maxHops > 1 && pairs.length > 1) {
248
+ const pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
249
+ // otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
250
+ Trade.bestTradeExactOut(pairsExcludingThisPair, currencyIn, currencyAmountOut, {
251
+ maxNumResults,
252
+ maxHops: maxHops - 1,
253
+ }, [pair, ...currentPairs], amountIn, bestTrades);
254
+ }
255
+ }
256
+ return bestTrades;
257
+ }
258
+ }
259
+ exports.Trade = Trade;
260
+ //# sourceMappingURL=trade.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trade.js","sourceRoot":"","sources":["../../../../src/entities/trade.ts"],"names":[],"mappings":";;;;AAAA,0DAUoC;AACpC,4CAAwC;AACxC,4EAAsC;AAGtC,mCAA+B;AAQ/B,sHAAsH;AACtH,4GAA4G;AAC5G,SAAgB,qBAAqB,CACnC,CAA+B,EAC/B,CAA+B;IAE/B,uDAAuD;IACvD,IAAA,wBAAS,EAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC,CAAA;IAClF,IAAA,wBAAS,EAAC,CAAC,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,Y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AC,CAAA;aAC7C;YAAC,OAAO,KAAK,EAAE;gBACd,oCAAoC;gBACpC,IAAK,KAAa,CAAC,2BAA2B,EAAE;oBAC9C,SAAQ;iBACT;gBACD,MAAM,KAAK,CAAA;aACZ;YACD,qFAAqF;YACrF,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE;gBACrC,IAAA,uBAAY,EACV,UAAU,EACV,IAAI,KAAK,CACP,IAAI,aAAK,CAAC,CAAC,IAAI,EAAE,GAAG,YAAY,CAAC,EAAE,UAAU,EAAE,iBAAiB,CAAC,QAAQ,CAAC,EAC1E,iBAAiB,EACjB,oBAAS,CAAC,YAAY,CACvB,EACD,aAAa,EACb,eAAe,CAChB,CAAA;aACF;iBAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;gBAC1C,MAAM,sBAAsB,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAA;gBAEzF,4GAA4G;gBAC5G,KAAK,CAAC,iBAAiB,CACrB,sBAAsB,EACtB,UAAU,EACV,iBAAiB,EACjB;oBACE,aAAa;oBACb,OAAO,EAAE,OAAO,GAAG,CAAC;iBACrB,EACD,CAAC,IAAI,EAAE,GAAG,YAAY,CAAC,EACvB,QAAQ,EACR,UAAU,CACX,CAAA;aACF;SACF;QAED,OAAO,UAAU,CAAA;IACnB,CAAC;CACF;AA/SD,sBA+SC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
3
+ * obtained by sending any amount of input.
4
+ */
5
+ export declare class InsufficientReservesError extends Error {
6
+ readonly isInsufficientReservesError: true;
7
+ constructor();
8
+ }
9
+ /**
10
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
11
+ * than the price of a single unit of output after fees.
12
+ */
13
+ export declare class InsufficientInputAmountError extends Error {
14
+ readonly isInsufficientInputAmountError: true;
15
+ constructor();
16
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InsufficientInputAmountError = exports.InsufficientReservesError = void 0;
4
+ // see https://stackoverflow.com/a/41102306
5
+ const CAN_SET_PROTOTYPE = 'setPrototypeOf' in Object;
6
+ /**
7
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
8
+ * obtained by sending any amount of input.
9
+ */
10
+ class InsufficientReservesError extends Error {
11
+ constructor() {
12
+ super();
13
+ this.isInsufficientReservesError = true;
14
+ this.name = this.constructor.name;
15
+ if (CAN_SET_PROTOTYPE)
16
+ Object.setPrototypeOf(this, new.target.prototype);
17
+ }
18
+ }
19
+ exports.InsufficientReservesError = InsufficientReservesError;
20
+ /**
21
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
22
+ * than the price of a single unit of output after fees.
23
+ */
24
+ class InsufficientInputAmountError extends Error {
25
+ constructor() {
26
+ super();
27
+ this.isInsufficientInputAmountError = true;
28
+ this.name = this.constructor.name;
29
+ if (CAN_SET_PROTOTYPE)
30
+ Object.setPrototypeOf(this, new.target.prototype);
31
+ }
32
+ }
33
+ exports.InsufficientInputAmountError = InsufficientInputAmountError;
34
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/errors.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAC3C,MAAM,iBAAiB,GAAG,gBAAgB,IAAI,MAAM,CAAA;AAEpD;;;GAGG;AACH,MAAa,yBAA0B,SAAQ,KAAK;IAGlD;QACE,KAAK,EAAE,CAAA;QAHO,gCAA2B,GAAS,IAAI,CAAA;QAItD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAA;QACjC,IAAI,iBAAiB;YAAE,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IAC1E,CAAC;CACF;AARD,8DAQC;AAED;;;GAGG;AACH,MAAa,4BAA6B,SAAQ,KAAK;IAGrD;QACE,KAAK,EAAE,CAAA;QAHO,mCAA8B,GAAS,IAAI,CAAA;QAIzD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAA;QACjC,IAAI,iBAAiB;YAAE,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IAC1E,CAAC;CACF;AARD,oEAQC"}
@@ -0,0 +1,4 @@
1
+ export { FACTORY_ADDRESS_MAP, INIT_CODE_HASH, MINIMUM_LIQUIDITY } from './constants';
2
+ export * from './errors';
3
+ export * from './entities';
4
+ export * from './router';
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MINIMUM_LIQUIDITY = exports.INIT_CODE_HASH = exports.FACTORY_ADDRESS_MAP = void 0;
4
+ const tslib_1 = require("tslib");
5
+ var constants_1 = require("./constants");
6
+ Object.defineProperty(exports, "FACTORY_ADDRESS_MAP", { enumerable: true, get: function () { return constants_1.FACTORY_ADDRESS_MAP; } });
7
+ Object.defineProperty(exports, "INIT_CODE_HASH", { enumerable: true, get: function () { return constants_1.INIT_CODE_HASH; } });
8
+ Object.defineProperty(exports, "MINIMUM_LIQUIDITY", { enumerable: true, get: function () { return constants_1.MINIMUM_LIQUIDITY; } });
9
+ tslib_1.__exportStar(require("./errors"), exports);
10
+ tslib_1.__exportStar(require("./entities"), exports);
11
+ tslib_1.__exportStar(require("./router"), exports);
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":";;;;AAAA,yCAAoF;AAA3E,gHAAA,mBAAmB,OAAA;AAAE,2GAAA,cAAc,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAE/D,mDAAwB;AACxB,qDAA0B;AAC1B,mDAAwB"}
@@ -0,0 +1,64 @@
1
+ import { Currency, Percent, TradeType } from '@centurion_project/sdk-core';
2
+ import { Trade } from './entities';
3
+ /**
4
+ * Options for producing the arguments to send call to the router.
5
+ */
6
+ export interface TradeOptions {
7
+ /**
8
+ * How much the execution price is allowed to move unfavorably from the trade execution price.
9
+ */
10
+ allowedSlippage: Percent;
11
+ /**
12
+ * How long the swap is valid until it expires, in seconds.
13
+ * This will be used to produce a `deadline` parameter which is computed from when the swap call parameters
14
+ * are generated.
15
+ */
16
+ ttl: number;
17
+ /**
18
+ * The account that should receive the output of the swap.
19
+ */
20
+ recipient: string;
21
+ /**
22
+ * Whether any of the tokens in the path are fee on transfer tokens, which should be handled with special methods
23
+ */
24
+ feeOnTransfer?: boolean;
25
+ }
26
+ export interface TradeOptionsDeadline extends Omit<TradeOptions, 'ttl'> {
27
+ /**
28
+ * When the transaction expires.
29
+ * This is an atlernate to specifying the ttl, for when you do not want to use local time.
30
+ */
31
+ deadline: number;
32
+ }
33
+ /**
34
+ * The parameters to use in the call to the Uniswap V2 Router to execute a trade.
35
+ */
36
+ export interface SwapParameters {
37
+ /**
38
+ * The method to call on the Uniswap V2 Router.
39
+ */
40
+ methodName: string;
41
+ /**
42
+ * The arguments to pass to the method, all hex encoded.
43
+ */
44
+ args: (string | string[])[];
45
+ /**
46
+ * The amount of wei to send in hex.
47
+ */
48
+ value: string;
49
+ }
50
+ /**
51
+ * Represents the Uniswap V2 Router, and has static methods for helping execute trades.
52
+ */
53
+ export declare abstract class Router {
54
+ /**
55
+ * Cannot be constructed.
56
+ */
57
+ private constructor();
58
+ /**
59
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
60
+ * @param trade to produce call parameters for
61
+ * @param options options for the call parameters
62
+ */
63
+ static swapCallParameters(trade: Trade<Currency, Currency, TradeType>, options: TradeOptions | TradeOptionsDeadline): SwapParameters;
64
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Router = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const sdk_core_1 = require("@centurion_project/sdk-core");
6
+ const tiny_invariant_1 = tslib_1.__importDefault(require("tiny-invariant"));
7
+ function toHex(currencyAmount) {
8
+ return `0x${currencyAmount.quotient.toString(16)}`;
9
+ }
10
+ const ZERO_HEX = '0x0';
11
+ /**
12
+ * Represents the Uniswap V2 Router, and has static methods for helping execute trades.
13
+ */
14
+ class Router {
15
+ /**
16
+ * Cannot be constructed.
17
+ */
18
+ constructor() { }
19
+ /**
20
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
21
+ * @param trade to produce call parameters for
22
+ * @param options options for the call parameters
23
+ */
24
+ static swapCallParameters(trade, options) {
25
+ const etherIn = trade.inputAmount.currency.isNative;
26
+ const etherOut = trade.outputAmount.currency.isNative;
27
+ // the router does not support both ether in and out
28
+ (0, tiny_invariant_1.default)(!(etherIn && etherOut), 'ETHER_IN_OUT');
29
+ (0, tiny_invariant_1.default)(!('ttl' in options) || options.ttl > 0, 'TTL');
30
+ const to = (0, sdk_core_1.validateAndParseAddress)(options.recipient);
31
+ const amountIn = toHex(trade.maximumAmountIn(options.allowedSlippage));
32
+ const amountOut = toHex(trade.minimumAmountOut(options.allowedSlippage));
33
+ const path = trade.route.path.map((token) => token.address);
34
+ const deadline = 'ttl' in options
35
+ ? `0x${(Math.floor(new Date().getTime() / 1000) + options.ttl).toString(16)}`
36
+ : `0x${options.deadline.toString(16)}`;
37
+ const useFeeOnTransfer = Boolean(options.feeOnTransfer);
38
+ let methodName;
39
+ let args;
40
+ let value;
41
+ switch (trade.tradeType) {
42
+ case sdk_core_1.TradeType.EXACT_INPUT:
43
+ if (etherIn) {
44
+ methodName = useFeeOnTransfer ? 'swapExactETHForTokensSupportingFeeOnTransferTokens' : 'swapExactETHForTokens';
45
+ // (uint amountOutMin, address[] calldata path, address to, uint deadline)
46
+ args = [amountOut, path, to, deadline];
47
+ value = amountIn;
48
+ }
49
+ else if (etherOut) {
50
+ methodName = useFeeOnTransfer ? 'swapExactTokensForETHSupportingFeeOnTransferTokens' : 'swapExactTokensForETH';
51
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
52
+ args = [amountIn, amountOut, path, to, deadline];
53
+ value = ZERO_HEX;
54
+ }
55
+ else {
56
+ methodName = useFeeOnTransfer
57
+ ? 'swapExactTokensForTokensSupportingFeeOnTransferTokens'
58
+ : 'swapExactTokensForTokens';
59
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
60
+ args = [amountIn, amountOut, path, to, deadline];
61
+ value = ZERO_HEX;
62
+ }
63
+ break;
64
+ case sdk_core_1.TradeType.EXACT_OUTPUT:
65
+ (0, tiny_invariant_1.default)(!useFeeOnTransfer, 'EXACT_OUT_FOT');
66
+ if (etherIn) {
67
+ methodName = 'swapETHForExactTokens';
68
+ // (uint amountOut, address[] calldata path, address to, uint deadline)
69
+ args = [amountOut, path, to, deadline];
70
+ value = amountIn;
71
+ }
72
+ else if (etherOut) {
73
+ methodName = 'swapTokensForExactETH';
74
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
75
+ args = [amountOut, amountIn, path, to, deadline];
76
+ value = ZERO_HEX;
77
+ }
78
+ else {
79
+ methodName = 'swapTokensForExactTokens';
80
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
81
+ args = [amountOut, amountIn, path, to, deadline];
82
+ value = ZERO_HEX;
83
+ }
84
+ break;
85
+ }
86
+ return {
87
+ methodName,
88
+ args,
89
+ value,
90
+ };
91
+ }
92
+ }
93
+ exports.Router = Router;
94
+ //# sourceMappingURL=router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../../../src/router.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