@pioneer-platform/uniswap-client 0.1.0 → 0.2.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 (51) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/package.json +15 -24
  3. package/tsconfig.json +2 -1
  4. package/lib/constants/chainInfo.d.ts +0 -47
  5. package/lib/constants/chainInfo.js +0 -248
  6. package/lib/constants/chains.d.ts +0 -46
  7. package/lib/constants/chains.js +0 -136
  8. package/lib/constants/governance.d.ts +0 -8
  9. package/lib/constants/governance.js +0 -23
  10. package/lib/constants/lists.d.ts +0 -12
  11. package/lib/constants/lists.js +0 -56
  12. package/lib/constants/locales.d.ts +0 -6
  13. package/lib/constants/locales.js +0 -71
  14. package/lib/constants/misc.d.ts +0 -16
  15. package/lib/constants/misc.js +0 -31
  16. package/lib/constants/networks.d.ts +0 -21
  17. package/lib/constants/networks.js +0 -169
  18. package/lib/constants/proposals/index.d.ts +0 -5
  19. package/lib/constants/proposals/index.js +0 -8
  20. package/lib/constants/proposals/polygon_proposal_title.d.ts +0 -1
  21. package/lib/constants/proposals/polygon_proposal_title.js +0 -4
  22. package/lib/constants/proposals/uniswap_grants_proposal_description.d.ts +0 -1
  23. package/lib/constants/proposals/uniswap_grants_proposal_description.js +0 -109
  24. package/lib/constants/providers.d.ts +0 -20
  25. package/lib/constants/providers.js +0 -32
  26. package/lib/constants/routing.d.ts +0 -16
  27. package/lib/constants/routing.js +0 -106
  28. package/lib/constants/supportArticles.d.ts +0 -13
  29. package/lib/constants/supportArticles.js +0 -17
  30. package/lib/constants/tokens.d.ts +0 -70
  31. package/lib/constants/tokens.js +0 -252
  32. package/lib/index.d.ts +0 -1
  33. package/lib/index.js +0 -724
  34. package/lib/routing/clientSideSmartOrderRouter.d.ts +0 -5
  35. package/lib/routing/clientSideSmartOrderRouter.js +0 -102
  36. package/lib/routing/gas.d.ts +0 -5
  37. package/lib/routing/gas.js +0 -71
  38. package/lib/routing/types.d.ts +0 -393
  39. package/lib/routing/types.js +0 -320
  40. package/lib/routing/utils.d.ts +0 -28
  41. package/lib/routing/utils.js +0 -264
  42. package/lib/rpc/AppJsonRpcProvider.d.ts +0 -44
  43. package/lib/rpc/AppJsonRpcProvider.js +0 -92
  44. package/lib/rpc/ConfiguredJsonRpcProvider.d.ts +0 -8
  45. package/lib/rpc/ConfiguredJsonRpcProvider.js +0 -16
  46. package/lib/utils/contracts/getContract.d.ts +0 -3
  47. package/lib/utils/contracts/getContract.js +0 -28
  48. package/lib/utils/transformSwapRouteToGetQuoteResult.d.ts +0 -4
  49. package/lib/utils/transformSwapRouteToGetQuoteResult.js +0 -113
  50. package/lib/utils/uniswapData.d.ts +0 -21
  51. package/lib/utils/uniswapData.js +0 -139
@@ -1,320 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.URAQuoteType = exports.SwapRouterNativeAssets = exports.PoolType = exports.QuoteState = exports.LimitOrderTrade = exports.PreviewTrade = exports.DutchOrderTrade = exports.OFFCHAIN_ORDER_TYPE_TO_SIGNATURE_TYPE = exports.OffchainOrderType = exports.ClassicTrade = exports.TradeFillType = exports.QuoteIntent = exports.RouterPreference = exports.INTERNAL_ROUTER_PREFERENCE_PRICE = exports.QuoteMethod = exports.TradeState = void 0;
4
- exports.isClassicQuoteResponse = isClassicQuoteResponse;
5
- const constants_1 = require("@ethersproject/constants");
6
- const router_sdk_1 = require("@uniswap/router-sdk");
7
- const sdk_core_1 = require("@uniswap/sdk-core");
8
- const uniswapx_sdk_1 = require("@uniswap/uniswapx-sdk");
9
- const misc_1 = require("../constants/misc");
10
- const ethers_1 = require("ethers/lib/ethers");
11
- var SignatureType;
12
- (function (SignatureType) {
13
- SignatureType["SIGN_UNISWAPX_ORDER"] = "signUniswapXOrder";
14
- SignatureType["SIGN_UNISWAPX_V2_ORDER"] = "signUniswapXV2Order";
15
- SignatureType["SIGN_LIMIT"] = "signLimit";
16
- })(SignatureType || (SignatureType = {}));
17
- var TradeState;
18
- (function (TradeState) {
19
- TradeState["LOADING"] = "loading";
20
- TradeState["INVALID"] = "invalid";
21
- TradeState["STALE"] = "stale";
22
- TradeState["NO_ROUTE_FOUND"] = "no_route_found";
23
- TradeState["VALID"] = "valid";
24
- })(TradeState || (exports.TradeState = TradeState = {}));
25
- var QuoteMethod;
26
- (function (QuoteMethod) {
27
- QuoteMethod["ROUTING_API"] = "ROUTING_API";
28
- QuoteMethod["QUICK_ROUTE"] = "QUICK_ROUTE";
29
- QuoteMethod["CLIENT_SIDE_FALLBACK"] = "CLIENT_SIDE_FALLBACK";
30
- })(QuoteMethod || (exports.QuoteMethod = QuoteMethod = {}));
31
- // This is excluded from `RouterPreference` enum because it's only used
32
- // internally for token -> USDC trades to get a USD value.
33
- exports.INTERNAL_ROUTER_PREFERENCE_PRICE = 'price';
34
- var RouterPreference;
35
- (function (RouterPreference) {
36
- RouterPreference["X"] = "uniswapx";
37
- RouterPreference["API"] = "api";
38
- })(RouterPreference || (exports.RouterPreference = RouterPreference = {}));
39
- // TODO(limits): add Limit market price intent
40
- var QuoteIntent;
41
- (function (QuoteIntent) {
42
- QuoteIntent["Pricing"] = "pricing";
43
- QuoteIntent["Quote"] = "quote";
44
- })(QuoteIntent || (exports.QuoteIntent = QuoteIntent = {}));
45
- function isClassicQuoteResponse(data) {
46
- return data.routing === URAQuoteType.CLASSIC;
47
- }
48
- var TradeFillType;
49
- (function (TradeFillType) {
50
- TradeFillType["Classic"] = "classic";
51
- TradeFillType["UniswapX"] = "uniswap_x";
52
- TradeFillType["None"] = "none";
53
- })(TradeFillType || (exports.TradeFillType = TradeFillType = {}));
54
- class ClassicTrade extends router_sdk_1.Trade {
55
- constructor({ gasUseEstimate, gasUseEstimateUSD, blockNumber, requestId, quoteMethod, approveInfo, swapFee, ...routes }) {
56
- super(routes);
57
- this.fillType = TradeFillType.Classic;
58
- this.blockNumber = blockNumber;
59
- this.gasUseEstimateUSD = gasUseEstimateUSD;
60
- this.requestId = requestId;
61
- this.quoteMethod = quoteMethod;
62
- this.approveInfo = approveInfo;
63
- this.swapFee = swapFee;
64
- this.gasUseEstimate = gasUseEstimate;
65
- }
66
- get executionPrice() {
67
- if (this.tradeType === sdk_core_1.TradeType.EXACT_INPUT || !this.swapFee) { // @ts-ignore
68
- return super.executionPrice;
69
- }
70
- // Fix inaccurate price calculation for exact output trades
71
- return new sdk_core_1.Price({ baseAmount: this.inputAmount, quoteAmount: this.postSwapFeeOutputAmount });
72
- }
73
- get postSwapFeeOutputAmount() {
74
- // Routing api already applies the swap fee to the output amount for exact-in
75
- if (this.tradeType === sdk_core_1.TradeType.EXACT_INPUT)
76
- return this.outputAmount;
77
- const swapFeeAmount = sdk_core_1.CurrencyAmount.fromRawAmount(this.outputAmount.currency, this.swapFee?.amount ?? 0);
78
- return this.outputAmount.subtract(swapFeeAmount);
79
- }
80
- // gas estimate for maybe approve + swap
81
- get totalGasUseEstimateUSD() {
82
- if (this.approveInfo.needsApprove && this.gasUseEstimateUSD) {
83
- return this.approveInfo.approveGasEstimateUSD + this.gasUseEstimateUSD;
84
- }
85
- return this.gasUseEstimateUSD;
86
- }
87
- }
88
- exports.ClassicTrade = ClassicTrade;
89
- var OffchainOrderType;
90
- (function (OffchainOrderType) {
91
- OffchainOrderType["DUTCH_AUCTION"] = "Dutch";
92
- OffchainOrderType["DUTCH_V2_AUCTION"] = "Dutch_V2";
93
- OffchainOrderType["LIMIT_ORDER"] = "Limit";
94
- })(OffchainOrderType || (exports.OffchainOrderType = OffchainOrderType = {}));
95
- exports.OFFCHAIN_ORDER_TYPE_TO_SIGNATURE_TYPE = {
96
- [OffchainOrderType.DUTCH_AUCTION]: SignatureType.SIGN_UNISWAPX_ORDER,
97
- [OffchainOrderType.DUTCH_V2_AUCTION]: SignatureType.SIGN_UNISWAPX_V2_ORDER,
98
- [OffchainOrderType.LIMIT_ORDER]: SignatureType.SIGN_LIMIT,
99
- };
100
- class DutchOrderTrade extends uniswapx_sdk_1.DutchOrderTrade {
101
- constructor({ currencyIn, currenciesOut, orderInfo, tradeType, quoteId, requestId, wrapInfo, approveInfo, classicGasUseEstimateUSD, auctionPeriodSecs, startTimeBufferSecs, deadlineBufferSecs, slippageTolerance, swapFee, }) {
102
- super({ currencyIn, currenciesOut, orderInfo, tradeType });
103
- this.fillType = TradeFillType.UniswapX;
104
- this.offchainOrderType = OffchainOrderType.DUTCH_AUCTION;
105
- this.inputTax = misc_1.ZERO_PERCENT;
106
- this.outputTax = misc_1.ZERO_PERCENT;
107
- this.quoteId = quoteId;
108
- this.requestId = requestId;
109
- this.approveInfo = approveInfo;
110
- this.wrapInfo = wrapInfo;
111
- this.classicGasUseEstimateUSD = classicGasUseEstimateUSD;
112
- this.auctionPeriodSecs = auctionPeriodSecs;
113
- this.deadlineBufferSecs = deadlineBufferSecs;
114
- this.slippageTolerance = slippageTolerance;
115
- this.startTimeBufferSecs = startTimeBufferSecs;
116
- this.swapFee = swapFee;
117
- }
118
- get totalGasUseEstimateUSD() {
119
- if (this.wrapInfo.needsWrap && this.approveInfo.needsApprove) {
120
- return this.wrapInfo.wrapGasEstimateUSD + this.approveInfo.approveGasEstimateUSD;
121
- }
122
- if (this.wrapInfo.needsWrap)
123
- return this.wrapInfo.wrapGasEstimateUSD;
124
- if (this.approveInfo.needsApprove)
125
- return this.approveInfo.approveGasEstimateUSD;
126
- return 0;
127
- }
128
- asDutchOrderTrade() {
129
- return this;
130
- }
131
- }
132
- exports.DutchOrderTrade = DutchOrderTrade;
133
- class PreviewTrade {
134
- constructor({ inputAmount, outputAmount, tradeType, }) {
135
- this.fillType = TradeFillType.None;
136
- this.quoteMethod = QuoteMethod.QUICK_ROUTE;
137
- this.inputAmount = inputAmount;
138
- this.outputAmount = outputAmount;
139
- this.tradeType = tradeType;
140
- }
141
- // below methods are copied from router-sdk
142
- // Trade https://github.com/Uniswap/router-sdk/blob/main/src/entities/trade.ts#L10
143
- minimumAmountOut(slippageTolerance, amountOut = this.outputAmount) {
144
- if (this.tradeType === sdk_core_1.TradeType.EXACT_OUTPUT) {
145
- return amountOut;
146
- }
147
- else {
148
- const slippageAdjustedAmountOut = new sdk_core_1.Fraction(router_sdk_1.ONE)
149
- .add(slippageTolerance)
150
- .invert()
151
- .multiply(amountOut.quotient).quotient;
152
- return sdk_core_1.CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
153
- }
154
- }
155
- maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
156
- if (this.tradeType === sdk_core_1.TradeType.EXACT_INPUT) {
157
- return amountIn;
158
- }
159
- else {
160
- const slippageAdjustedAmountIn = new sdk_core_1.Fraction(router_sdk_1.ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
161
- return sdk_core_1.CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
162
- }
163
- }
164
- /**
165
- * Returns the sell tax of the input token
166
- */
167
- get inputTax() {
168
- const inputCurrency = this.inputAmount.currency;
169
- if (inputCurrency.isNative || !inputCurrency.wrapped.sellFeeBps)
170
- return misc_1.ZERO_PERCENT;
171
- return new sdk_core_1.Percent(inputCurrency.wrapped.sellFeeBps.toNumber(), 10000);
172
- }
173
- /**
174
- * Returns the buy tax of the output token
175
- */
176
- get outputTax() {
177
- const outputCurrency = this.outputAmount.currency;
178
- if (outputCurrency.isNative || !outputCurrency.wrapped.buyFeeBps)
179
- return misc_1.ZERO_PERCENT;
180
- return new sdk_core_1.Percent(outputCurrency.wrapped.buyFeeBps.toNumber(), 10000);
181
- }
182
- /**
183
- * The price expressed in terms of output amount/input amount.
184
- */
185
- get executionPrice() {
186
- return (this._executionPrice ??
187
- (this._executionPrice = new sdk_core_1.Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient)));
188
- }
189
- worstExecutionPrice(slippageTolerance) {
190
- return new sdk_core_1.Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
191
- }
192
- }
193
- exports.PreviewTrade = PreviewTrade;
194
- // TODO(limits): get this from uniswapx-sdk
195
- const UNISWAPX_REACTOR = '0x6000da47483062a0d734ba3dc7576ce6a0b645c4';
196
- class LimitOrderTrade {
197
- constructor({ tradeType, amountIn, amountOut, deadlineBufferSecs, swapFee, wrapInfo, approveInfo, swapper, }) {
198
- this.fillType = TradeFillType.UniswapX;
199
- this.offchainOrderType = OffchainOrderType.LIMIT_ORDER;
200
- // Placeholder values that aren't used in a limit trade
201
- this.inputTax = misc_1.ZERO_PERCENT;
202
- this.outputTax = misc_1.ZERO_PERCENT;
203
- this.slippageTolerance = misc_1.ZERO_PERCENT;
204
- this.quoteId = undefined;
205
- this.requestId = undefined;
206
- this.deadlineBufferSecs = deadlineBufferSecs;
207
- this.swapFee = swapFee;
208
- this.wrapInfo = wrapInfo;
209
- this.approveInfo = approveInfo;
210
- this.amountIn = amountIn;
211
- this.amountOut = amountOut;
212
- this.tradeType = tradeType;
213
- this.swapper = swapper;
214
- // deadline is shown in the review modal, but updated on submission
215
- const nowSecs = Math.floor(Date.now() / 1000);
216
- this.deadline = (nowSecs + deadlineBufferSecs) * 1000;
217
- }
218
- asDutchOrderTrade(options) {
219
- const swapperOutput = {
220
- token: this.amountOut.currency.isNative ? constants_1.AddressZero : this.amountOut.currency.address,
221
- recipient: options?.swapper ?? this.swapper,
222
- startAmount: ethers_1.BigNumber.from(this.amountOut.quotient.toString()),
223
- endAmount: ethers_1.BigNumber.from(this.amountOut.quotient.toString()),
224
- };
225
- const swapFee = this.swapFee && {
226
- token: this.amountOut.currency.isNative ? constants_1.AddressZero : this.amountOut.currency.address,
227
- recipient: this.swapFee.recipient,
228
- startAmount: ethers_1.BigNumber.from(this.amountOut.multiply(this.swapFee.percent).quotient.toString()),
229
- endAmount: ethers_1.BigNumber.from(this.amountOut.multiply(this.swapFee.percent).quotient.toString()),
230
- };
231
- const outputs = swapFee ? [swapperOutput, swapFee] : [swapperOutput];
232
- const nowSecs = Math.floor(Date.now() / 1000);
233
- return new uniswapx_sdk_1.DutchOrderTrade({
234
- currencyIn: this.amountIn.currency,
235
- currenciesOut: [this.amountOut.currency],
236
- orderInfo: {
237
- reactor: UNISWAPX_REACTOR,
238
- swapper: options?.swapper ?? this.swapper,
239
- deadline: (nowSecs + this.deadlineBufferSecs) * 1000,
240
- additionalValidationContract: constants_1.AddressZero,
241
- additionalValidationData: '0x',
242
- nonce: options?.nonce ?? ethers_1.BigNumber.from(0),
243
- // decay timings dont matter at all
244
- decayStartTime: nowSecs,
245
- decayEndTime: nowSecs,
246
- exclusiveFiller: constants_1.AddressZero,
247
- exclusivityOverrideBps: ethers_1.BigNumber.from(0),
248
- input: {
249
- token: this.amountIn.currency.isNative ? constants_1.AddressZero : this.amountIn.currency.address,
250
- startAmount: ethers_1.BigNumber.from(this.amountIn.quotient.toString()),
251
- endAmount: ethers_1.BigNumber.from(this.amountIn.quotient.toString()),
252
- },
253
- outputs,
254
- },
255
- tradeType: this.tradeType,
256
- });
257
- }
258
- get inputAmount() {
259
- return this.amountIn;
260
- }
261
- get outputAmount() {
262
- return this.amountOut;
263
- }
264
- /** For UniswapX, handling token taxes in the output amount is outsourced to quoters */
265
- get postTaxOutputAmount() {
266
- return this.outputAmount;
267
- }
268
- get totalGasUseEstimateUSD() {
269
- return this.wrapInfo.needsWrap ? this.wrapInfo.wrapGasEstimateUSD : 0;
270
- }
271
- get classicGasUseEstimateUSD() {
272
- return 0;
273
- }
274
- // no decay for limit orders
275
- get startTimeBufferSecs() {
276
- return 0;
277
- }
278
- // no decay auction for limit orders
279
- get auctionPeriodSecs() {
280
- return 0;
281
- }
282
- get executionPrice() {
283
- return new sdk_core_1.Price(this.amountIn.currency, this.amountOut.currency, this.amountIn.quotient, this.amountOut.quotient);
284
- }
285
- worstExecutionPrice() {
286
- return this.executionPrice;
287
- }
288
- maximumAmountIn() {
289
- return this.inputAmount;
290
- }
291
- minimumAmountOut() {
292
- return this.outputAmount;
293
- }
294
- }
295
- exports.LimitOrderTrade = LimitOrderTrade;
296
- var QuoteState;
297
- (function (QuoteState) {
298
- QuoteState["SUCCESS"] = "Success";
299
- QuoteState["NOT_FOUND"] = "Not found";
300
- })(QuoteState || (exports.QuoteState = QuoteState = {}));
301
- var PoolType;
302
- (function (PoolType) {
303
- PoolType["V2Pool"] = "v2-pool";
304
- PoolType["V3Pool"] = "v3-pool";
305
- })(PoolType || (exports.PoolType = PoolType = {}));
306
- // swap router API special cases these strings to represent native currencies
307
- // all chains except for bnb chain and polygon
308
- // have "ETH" as native currency symbol
309
- var SwapRouterNativeAssets;
310
- (function (SwapRouterNativeAssets) {
311
- SwapRouterNativeAssets["MATIC"] = "MATIC";
312
- SwapRouterNativeAssets["BNB"] = "BNB";
313
- SwapRouterNativeAssets["AVAX"] = "AVAX";
314
- SwapRouterNativeAssets["ETH"] = "ETH";
315
- })(SwapRouterNativeAssets || (exports.SwapRouterNativeAssets = SwapRouterNativeAssets = {}));
316
- var URAQuoteType;
317
- (function (URAQuoteType) {
318
- URAQuoteType["CLASSIC"] = "CLASSIC";
319
- URAQuoteType["DUTCH_LIMIT"] = "DUTCH_LIMIT";
320
- })(URAQuoteType || (exports.URAQuoteType = URAQuoteType = {}));
@@ -1,28 +0,0 @@
1
- import { MixedRouteSDK } from '@uniswap/router-sdk';
2
- import { Currency, CurrencyAmount, TradeType } from '@uniswap/sdk-core';
3
- import { Route as V2Route } from '@uniswap/v2-sdk';
4
- import { Route as V3Route } from '@uniswap/v3-sdk';
5
- import { ClassicQuoteData, ClassicTrade, DutchOrderTrade, GetQuickQuoteArgs, GetQuoteArgs, InterfaceTrade, LimitOrderTrade, PreviewTrade, QuickRouteResponse, QuoteMethod, SubmittableTrade, TradeResult, URAQuoteResponse } from './types';
6
- interface RouteResult {
7
- routev3: V3Route<Currency, Currency> | null;
8
- routev2: V2Route<Currency, Currency> | null;
9
- mixedRoute: MixedRouteSDK<Currency, Currency> | null;
10
- inputAmount: CurrencyAmount<Currency>;
11
- outputAmount: CurrencyAmount<Currency>;
12
- }
13
- /**
14
- * Transforms a Routing API quote into an array of routes that can be used to
15
- * create a `Trade`.
16
- */
17
- export declare function computeRoutes(args: GetQuoteArgs, routes: ClassicQuoteData['route']): RouteResult[] | undefined;
18
- export declare function transformQuickRouteToTrade(args: GetQuickQuoteArgs, data: QuickRouteResponse): PreviewTrade;
19
- export declare function getUSDCostPerGas(gasUseEstimateUSD?: number, gasUseEstimate?: number): number | undefined;
20
- export declare function transformQuoteToTrade(args: GetQuoteArgs, data: URAQuoteResponse, quoteMethod: QuoteMethod): Promise<TradeResult>;
21
- export declare function isExactInput(tradeType: TradeType): boolean;
22
- export declare function currencyAddressForSwapQuote(currency: Currency): string;
23
- export declare function isClassicTrade(trade?: InterfaceTrade): trade is ClassicTrade;
24
- export declare function isPreviewTrade(trade?: InterfaceTrade): trade is PreviewTrade;
25
- export declare function isSubmittableTrade(trade?: InterfaceTrade): trade is SubmittableTrade;
26
- export declare function isUniswapXTrade(trade?: InterfaceTrade): trade is DutchOrderTrade | LimitOrderTrade;
27
- export declare function isLimitTrade(trade?: InterfaceTrade): trade is LimitOrderTrade;
28
- export {};
@@ -1,264 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeRoutes = computeRoutes;
4
- exports.transformQuickRouteToTrade = transformQuickRouteToTrade;
5
- exports.getUSDCostPerGas = getUSDCostPerGas;
6
- exports.transformQuoteToTrade = transformQuoteToTrade;
7
- exports.isExactInput = isExactInput;
8
- exports.currencyAddressForSwapQuote = currencyAddressForSwapQuote;
9
- exports.isClassicTrade = isClassicTrade;
10
- exports.isPreviewTrade = isPreviewTrade;
11
- exports.isSubmittableTrade = isSubmittableTrade;
12
- exports.isUniswapXTrade = isUniswapXTrade;
13
- exports.isLimitTrade = isLimitTrade;
14
- const bignumber_1 = require("@ethersproject/bignumber");
15
- const router_sdk_1 = require("@uniswap/router-sdk");
16
- const sdk_core_1 = require("@uniswap/sdk-core");
17
- const v2_sdk_1 = require("@uniswap/v2-sdk");
18
- const v3_sdk_1 = require("@uniswap/v3-sdk");
19
- const misc_1 = require("../constants/misc");
20
- const tokens_1 = require("../constants/tokens");
21
- const PRECISION = 10000;
22
- const DENOMINATOR = PRECISION * 100;
23
- function toSlippagePercent(slippage) {
24
- const numerator = Number(slippage) * PRECISION;
25
- return new sdk_core_1.Percent(numerator, DENOMINATOR);
26
- }
27
- const gas_1 = require("./gas");
28
- const types_1 = require("./types");
29
- /**
30
- * Transforms a Routing API quote into an array of routes that can be used to
31
- * create a `Trade`.
32
- */
33
- function computeRoutes(args, routes) {
34
- if (routes.length === 0)
35
- return [];
36
- const [currencyIn, currencyOut] = getTradeCurrencies(args, false, routes);
37
- try {
38
- return routes.map((route) => {
39
- if (route.length === 0) {
40
- throw new Error('Expected route to have at least one pair or pool');
41
- }
42
- const rawAmountIn = route[0].amountIn;
43
- const rawAmountOut = route[route.length - 1].amountOut;
44
- if (!rawAmountIn || !rawAmountOut) {
45
- throw new Error('Expected both amountIn and amountOut to be present');
46
- }
47
- const isOnlyV2 = isVersionedRoute(types_1.PoolType.V2Pool, route);
48
- const isOnlyV3 = isVersionedRoute(types_1.PoolType.V3Pool, route);
49
- return {
50
- routev3: isOnlyV3 ? new v3_sdk_1.Route(route.map(parsePool), currencyIn, currencyOut) : null,
51
- routev2: isOnlyV2 ? new v2_sdk_1.Route(route.map(parsePair), currencyIn, currencyOut) : null,
52
- mixedRoute: !isOnlyV3 && !isOnlyV2 ? new router_sdk_1.MixedRouteSDK(route.map(parsePoolOrPair), currencyIn, currencyOut) : null,
53
- inputAmount: sdk_core_1.CurrencyAmount.fromRawAmount(currencyIn, rawAmountIn),
54
- outputAmount: sdk_core_1.CurrencyAmount.fromRawAmount(currencyOut, rawAmountOut),
55
- };
56
- });
57
- }
58
- catch (e) {
59
- console.error('Error computing routes', e);
60
- return;
61
- }
62
- }
63
- const parsePoolOrPair = (pool) => {
64
- return pool.type === types_1.PoolType.V3Pool ? parsePool(pool) : parsePair(pool);
65
- };
66
- function isVersionedRoute(type, route) {
67
- return route.every((pool) => pool.type === type);
68
- }
69
- function toDutchOrderInfo(orderInfoJSON) {
70
- const { nonce, input, outputs, exclusivityOverrideBps } = orderInfoJSON;
71
- return {
72
- ...orderInfoJSON,
73
- nonce: bignumber_1.BigNumber.from(nonce),
74
- exclusivityOverrideBps: bignumber_1.BigNumber.from(exclusivityOverrideBps),
75
- input: {
76
- ...input,
77
- startAmount: bignumber_1.BigNumber.from(input.startAmount),
78
- endAmount: bignumber_1.BigNumber.from(input.endAmount),
79
- },
80
- outputs: outputs.map((output) => ({
81
- ...output,
82
- startAmount: bignumber_1.BigNumber.from(output.startAmount),
83
- endAmount: bignumber_1.BigNumber.from(output.endAmount),
84
- })),
85
- };
86
- }
87
- // Prepares the currencies used for the actual Swap (either UniswapX or Universal Router)
88
- // May not match `currencyIn` that the user selected because for ETH inputs in UniswapX, the actual
89
- // swap will use WETH.
90
- function getTradeCurrencies(args, isUniswapXTrade, routes) {
91
- const { tokenInAddress, tokenInChainId, tokenInDecimals, tokenInSymbol, tokenOutAddress, tokenOutChainId, tokenOutDecimals, tokenOutSymbol, } = args;
92
- const tokenInIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenInAddress);
93
- const tokenOutIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenOutAddress);
94
- const serializedTokenIn = routes?.[0]?.[0]?.tokenIn;
95
- const serializedTokenOut = routes?.[0]?.[routes[0]?.length - 1]?.tokenOut;
96
- const currencyIn = tokenInIsNative
97
- ? (0, tokens_1.nativeOnChain)(tokenInChainId)
98
- : parseToken({
99
- address: tokenInAddress,
100
- chainId: tokenInChainId,
101
- decimals: tokenInDecimals,
102
- symbol: tokenInSymbol,
103
- buyFeeBps: serializedTokenIn?.buyFeeBps,
104
- sellFeeBps: serializedTokenIn?.sellFeeBps,
105
- });
106
- const currencyOut = tokenOutIsNative
107
- ? (0, tokens_1.nativeOnChain)(tokenOutChainId)
108
- : parseToken({
109
- address: tokenOutAddress,
110
- chainId: tokenOutChainId,
111
- decimals: tokenOutDecimals,
112
- symbol: tokenOutSymbol,
113
- buyFeeBps: serializedTokenOut?.buyFeeBps,
114
- sellFeeBps: serializedTokenOut?.sellFeeBps,
115
- });
116
- if (!isUniswapXTrade) {
117
- return [currencyIn, currencyOut];
118
- }
119
- return [currencyIn.isNative ? currencyIn.wrapped : currencyIn, currencyOut];
120
- }
121
- function getSwapFee(data) {
122
- const { portionAmount, portionBips, portionRecipient } = data;
123
- if (!portionAmount || !portionBips || !portionRecipient)
124
- return undefined;
125
- return {
126
- recipient: portionRecipient,
127
- percent: new sdk_core_1.Percent(portionBips, misc_1.BIPS_BASE),
128
- amount: portionAmount,
129
- };
130
- }
131
- function getClassicTradeDetails(args, data) {
132
- const classicQuote = data.routing === types_1.URAQuoteType.CLASSIC ? data.quote : data.allQuotes.find(types_1.isClassicQuoteResponse)?.quote;
133
- if (!classicQuote) {
134
- return {};
135
- }
136
- return {
137
- gasUseEstimate: classicQuote.gasUseEstimate ? parseFloat(classicQuote.gasUseEstimate) : undefined,
138
- gasUseEstimateUSD: classicQuote.gasUseEstimateUSD ? parseFloat(classicQuote.gasUseEstimateUSD) : undefined,
139
- blockNumber: classicQuote.blockNumber,
140
- routes: computeRoutes(args, classicQuote.route),
141
- swapFee: getSwapFee(classicQuote),
142
- };
143
- }
144
- function transformQuickRouteToTrade(args, data) {
145
- const { amount, tradeType } = args;
146
- const [currencyIn, currencyOut] = getTradeCurrencies(args, false);
147
- const [rawAmountIn, rawAmountOut] = data.tradeType === 'EXACT_IN' ? [amount, data.quote.amount] : [data.quote.amount, amount];
148
- const inputAmount = sdk_core_1.CurrencyAmount.fromRawAmount(currencyIn, rawAmountIn);
149
- const outputAmount = sdk_core_1.CurrencyAmount.fromRawAmount(currencyOut, rawAmountOut);
150
- return new types_1.PreviewTrade({ inputAmount, outputAmount, tradeType });
151
- }
152
- function getUSDCostPerGas(gasUseEstimateUSD, gasUseEstimate) {
153
- // Some sus javascript float math but it's ok because its just an estimate for display purposes
154
- if (!gasUseEstimateUSD || !gasUseEstimate)
155
- return undefined;
156
- return gasUseEstimateUSD / gasUseEstimate;
157
- }
158
- async function transformQuoteToTrade(args, data, quoteMethod) {
159
- const { tradeType, needsWrapIfUniswapX, routerPreference, account, amount } = args;
160
- const showUniswapXTrade = data.routing === types_1.URAQuoteType.DUTCH_LIMIT && routerPreference === types_1.RouterPreference.X;
161
- const [currencyIn, currencyOut] = getTradeCurrencies(args, showUniswapXTrade);
162
- const { gasUseEstimateUSD, blockNumber, routes, gasUseEstimate, swapFee } = getClassicTradeDetails(args, data);
163
- const usdCostPerGas = getUSDCostPerGas(gasUseEstimateUSD, gasUseEstimate);
164
- const approveInfo = await (0, gas_1.getApproveInfo)(account, currencyIn, amount, usdCostPerGas);
165
- const classicTrade = new types_1.ClassicTrade({
166
- v2Routes: routes
167
- ?.filter((r) => r.routev2 !== null)
168
- .map(({ routev2, inputAmount, outputAmount }) => ({
169
- routev2,
170
- inputAmount,
171
- outputAmount,
172
- })) ?? [],
173
- v3Routes: routes
174
- ?.filter((r) => r.routev3 !== null)
175
- .map(({ routev3, inputAmount, outputAmount }) => ({
176
- routev3,
177
- inputAmount,
178
- outputAmount,
179
- })) ?? [],
180
- mixedRoutes: routes
181
- ?.filter((r) => r.mixedRoute !== null)
182
- .map(({ mixedRoute, inputAmount, outputAmount }) => ({
183
- mixedRoute,
184
- inputAmount,
185
- outputAmount,
186
- })) ?? [],
187
- tradeType,
188
- gasUseEstimateUSD,
189
- gasUseEstimate,
190
- approveInfo,
191
- blockNumber,
192
- requestId: data.quote.requestId,
193
- quoteMethod,
194
- swapFee,
195
- });
196
- // If the top-level URA quote type is DUTCH_LIMIT, then UniswapX is better for the user
197
- const isUniswapXBetter = data.routing === types_1.URAQuoteType.DUTCH_LIMIT;
198
- if (isUniswapXBetter) {
199
- const orderInfo = toDutchOrderInfo(data.quote.orderInfo);
200
- const swapFee = getSwapFee(data.quote);
201
- const wrapInfo = await (0, gas_1.getWrapInfo)(needsWrapIfUniswapX, account, currencyIn.chainId, amount, usdCostPerGas);
202
- const uniswapXTrade = new types_1.DutchOrderTrade({
203
- currencyIn,
204
- currenciesOut: [currencyOut],
205
- orderInfo,
206
- tradeType,
207
- quoteId: data.quote.quoteId,
208
- requestId: data.quote.requestId,
209
- classicGasUseEstimateUSD: classicTrade.totalGasUseEstimateUSD,
210
- wrapInfo,
211
- approveInfo,
212
- auctionPeriodSecs: data.quote.auctionPeriodSecs,
213
- startTimeBufferSecs: data.quote.startTimeBufferSecs,
214
- deadlineBufferSecs: data.quote.deadlineBufferSecs,
215
- slippageTolerance: toSlippagePercent(data.quote.slippageTolerance),
216
- swapFee,
217
- });
218
- return {
219
- state: types_1.QuoteState.SUCCESS,
220
- trade: uniswapXTrade,
221
- };
222
- }
223
- return { state: types_1.QuoteState.SUCCESS, trade: classicTrade };
224
- }
225
- function parseToken({ address, chainId, decimals, symbol, buyFeeBps, sellFeeBps }) {
226
- const buyFeeBpsBN = buyFeeBps ? bignumber_1.BigNumber.from(buyFeeBps) : undefined;
227
- const sellFeeBpsBN = sellFeeBps ? bignumber_1.BigNumber.from(sellFeeBps) : undefined;
228
- return new sdk_core_1.Token(chainId, address, parseInt(decimals.toString()), symbol, undefined, false, buyFeeBpsBN, sellFeeBpsBN);
229
- }
230
- function parsePool({ fee, sqrtRatioX96, liquidity, tickCurrent, tokenIn, tokenOut }) {
231
- return new v3_sdk_1.Pool(parseToken(tokenIn), parseToken(tokenOut), parseInt(fee), sqrtRatioX96, liquidity, parseInt(tickCurrent));
232
- }
233
- const parsePair = ({ reserve0, reserve1 }) => new v2_sdk_1.Pair(sdk_core_1.CurrencyAmount.fromRawAmount(parseToken(reserve0.token), reserve0.quotient), sdk_core_1.CurrencyAmount.fromRawAmount(parseToken(reserve1.token), reserve1.quotient));
234
- // TODO(WEB-2050): Convert other instances of tradeType comparison to use this utility function
235
- function isExactInput(tradeType) {
236
- return tradeType === sdk_core_1.TradeType.EXACT_INPUT;
237
- }
238
- function currencyAddressForSwapQuote(currency) {
239
- if (currency.isNative) {
240
- if ((0, tokens_1.isPolygon)(currency.chainId))
241
- return types_1.SwapRouterNativeAssets.MATIC;
242
- if ((0, tokens_1.isBsc)(currency.chainId))
243
- return types_1.SwapRouterNativeAssets.BNB;
244
- if ((0, tokens_1.isAvalanche)(currency.chainId))
245
- return types_1.SwapRouterNativeAssets.AVAX;
246
- return types_1.SwapRouterNativeAssets.ETH;
247
- }
248
- return currency.address;
249
- }
250
- function isClassicTrade(trade) {
251
- return trade?.fillType === types_1.TradeFillType.Classic;
252
- }
253
- function isPreviewTrade(trade) {
254
- return trade?.fillType === types_1.TradeFillType.None;
255
- }
256
- function isSubmittableTrade(trade) {
257
- return trade?.fillType === types_1.TradeFillType.Classic || trade?.fillType === types_1.TradeFillType.UniswapX;
258
- }
259
- function isUniswapXTrade(trade) {
260
- return trade?.fillType === types_1.TradeFillType.UniswapX;
261
- }
262
- function isLimitTrade(trade) {
263
- return trade?.fillType === types_1.TradeFillType.UniswapX && trade?.offchainOrderType === types_1.OffchainOrderType.LIMIT_ORDER;
264
- }
@@ -1,44 +0,0 @@
1
- import { JsonRpcProvider } from '@ethersproject/providers';
2
- import ConfiguredJsonRpcProvider from './ConfiguredJsonRpcProvider';
3
- /**
4
- * A controller which marks itself disabled on an error, and re-enables itself using exponential backoff.
5
- * After each retry, it will wait twice as long to retry again. After a success, it will reset the backoff.
6
- */
7
- declare class Controller {
8
- private minimumBackoffTime;
9
- private isEnabled;
10
- private timeout;
11
- private exponentialBackoffFactor;
12
- constructor(minimumBackoffTime: number);
13
- private reset;
14
- onSuccess(): void;
15
- /**
16
- * Called onError.
17
- * Idempotent - calling this multiple times will *not* reset the exponential backoff timer.
18
- */
19
- onError(): void;
20
- get enabled(): boolean;
21
- }
22
- interface ControlledProvider {
23
- provider: JsonRpcProvider;
24
- controller: Controller;
25
- }
26
- interface AppJsonRpcProviderOptions {
27
- minimumBackoffTime?: number;
28
- }
29
- /**
30
- * An application-specific JSON-RPC provider.
31
- *
32
- * This super-provider will instantiate providers for all supported JSON-RPC URLs, so that it may use them as fallbacks.
33
- * It will use the first (primary) JSON-RPC URL unless there is issue, at which point it will fallback to the next, &c.,
34
- * retrying the former using exponential backoff. This prevents secondary URLs from permanently overtaking primary URLs.
35
- */
36
- export default class AppJsonRpcProvider extends ConfiguredJsonRpcProvider {
37
- providers: ReadonlyArray<ControlledProvider>;
38
- constructor(providers: JsonRpcProvider[], { minimumBackoffTime }?: AppJsonRpcProviderOptions);
39
- perform(method: string, params: {
40
- [name: string]: any;
41
- }): Promise<any>;
42
- static sortProviders(providers: ReadonlyArray<ControlledProvider>): Array<ControlledProvider>;
43
- }
44
- export {};