@pioneer-platform/uniswap-client 0.0.22 → 0.0.24

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 (74) hide show
  1. package/lib/constants/chainInfo.d.ts +19 -22
  2. package/lib/constants/chainInfo.js +134 -117
  3. package/lib/constants/chains.d.ts +36 -47
  4. package/lib/constants/chains.js +118 -83
  5. package/lib/constants/chains.test.js +22 -25
  6. package/lib/constants/governance.d.ts +8 -0
  7. package/lib/constants/governance.js +24 -0
  8. package/lib/constants/lists.d.ts +12 -0
  9. package/lib/constants/lists.js +64 -0
  10. package/lib/constants/localCurrencies.d.ts +6 -0
  11. package/lib/constants/localCurrencies.js +94 -0
  12. package/lib/constants/localCurrencyIcons.d.ts +18 -0
  13. package/lib/constants/localCurrencyIcons.js +298 -0
  14. package/lib/constants/locales.d.ts +1 -1
  15. package/lib/constants/locales.js +0 -3
  16. package/lib/constants/misc.d.ts +2 -7
  17. package/lib/constants/misc.js +17 -23
  18. package/lib/constants/networks.d.ts +21 -0
  19. package/lib/constants/networks.js +170 -0
  20. package/lib/constants/proposals/index.d.ts +5 -0
  21. package/lib/constants/proposals/index.js +8 -0
  22. package/lib/constants/proposals/polygon_proposal_title.d.ts +1 -0
  23. package/lib/constants/proposals/polygon_proposal_title.js +4 -0
  24. package/lib/constants/proposals/uniswap_grants_proposal_description.d.ts +1 -0
  25. package/lib/constants/proposals/uniswap_grants_proposal_description.js +4 -0
  26. package/lib/constants/providers.d.ts +19 -0
  27. package/lib/constants/providers.js +33 -0
  28. package/lib/constants/routing.d.ts +9 -13
  29. package/lib/constants/routing.js +91 -55
  30. package/lib/constants/routing.test.d.ts +1 -0
  31. package/lib/constants/routing.test.js +32 -0
  32. package/lib/constants/supportArticles.d.ts +13 -0
  33. package/lib/constants/supportArticles.js +17 -0
  34. package/lib/constants/tokenLists/broken.tokenlist.json +22 -0
  35. package/lib/constants/tokenLogoLookup.d.ts +8 -0
  36. package/lib/constants/tokenLogoLookup.js +48 -0
  37. package/lib/constants/tokenSafety.js +129 -0
  38. package/lib/constants/tokenSafetyLookup.d.ts +18 -0
  39. package/lib/constants/tokenSafetyLookup.js +66 -0
  40. package/lib/constants/tokenSaftey.test.d.ts +1 -0
  41. package/lib/constants/tokenSaftey.test.js +31 -0
  42. package/lib/constants/tokens.d.ts +34 -42
  43. package/lib/constants/tokens.js +190 -147
  44. package/lib/index.d.ts +1 -40
  45. package/lib/index.js +150 -641
  46. package/lib/routing/clientSideSmartOrderRouter.d.ts +5 -0
  47. package/lib/routing/clientSideSmartOrderRouter.js +136 -0
  48. package/lib/routing/gas.d.ts +5 -0
  49. package/lib/routing/gas.js +158 -0
  50. package/lib/routing/types.d.ts +393 -0
  51. package/lib/routing/types.js +424 -0
  52. package/lib/routing/utils.d.ts +28 -0
  53. package/lib/routing/utils.js +319 -0
  54. package/lib/rpc/AppJsonRpcProvider.d.ts +44 -0
  55. package/lib/rpc/AppJsonRpcProvider.js +183 -0
  56. package/lib/rpc/ConfiguredJsonRpcProvider.d.ts +8 -0
  57. package/lib/rpc/ConfiguredJsonRpcProvider.js +35 -0
  58. package/lib/utils/contracts/getContract.d.ts +3 -0
  59. package/lib/utils/contracts/getContract.js +29 -0
  60. package/lib/utils/transformSwapRouteToGetQuoteResult.d.ts +4 -0
  61. package/lib/utils/transformSwapRouteToGetQuoteResult.js +116 -0
  62. package/lib/utils/uniswapData.d.ts +21 -0
  63. package/lib/utils/uniswapData.js +217 -0
  64. package/package.json +11 -8
  65. package/lib/constants/addresses.d.ts +0 -9
  66. package/lib/constants/addresses.js +0 -41
  67. package/lib/constants/eip1193.d.ts +0 -8
  68. package/lib/constants/eip1193.js +0 -14
  69. package/lib/constants/index.d.ts +0 -9
  70. package/lib/constants/index.js +0 -26
  71. package/lib/constants/jsonRpcEndpoints.d.ts +0 -12
  72. package/lib/constants/jsonRpcEndpoints.js +0 -101
  73. package/lib/constants/utils/constructSameAddressMap.d.ts +0 -4
  74. package/lib/constants/utils/constructSameAddressMap.js +0 -19
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.isLimitTrade = exports.isUniswapXTrade = exports.isSubmittableTrade = exports.isPreviewTrade = exports.isClassicTrade = exports.currencyAddressForSwapQuote = exports.isExactInput = exports.transformQuoteToTrade = exports.getUSDCostPerGas = exports.transformQuickRouteToTrade = exports.computeRoutes = void 0;
51
+ var bignumber_1 = require("@ethersproject/bignumber");
52
+ var router_sdk_1 = require("@uniswap/router-sdk");
53
+ var sdk_core_1 = require("@uniswap/sdk-core");
54
+ var v2_sdk_1 = require("@uniswap/v2-sdk");
55
+ var v3_sdk_1 = require("@uniswap/v3-sdk");
56
+ var misc_1 = require("../constants/misc");
57
+ var tokens_1 = require("../constants/tokens");
58
+ var PRECISION = 10000;
59
+ var DENOMINATOR = PRECISION * 100;
60
+ function toSlippagePercent(slippage) {
61
+ var numerator = Number(slippage) * PRECISION;
62
+ return new sdk_core_1.Percent(numerator, DENOMINATOR);
63
+ }
64
+ var gas_1 = require("./gas");
65
+ var types_1 = require("./types");
66
+ /**
67
+ * Transforms a Routing API quote into an array of routes that can be used to
68
+ * create a `Trade`.
69
+ */
70
+ function computeRoutes(args, routes) {
71
+ if (routes.length === 0)
72
+ return [];
73
+ var _a = getTradeCurrencies(args, false, routes), currencyIn = _a[0], currencyOut = _a[1];
74
+ try {
75
+ return routes.map(function (route) {
76
+ if (route.length === 0) {
77
+ throw new Error('Expected route to have at least one pair or pool');
78
+ }
79
+ var rawAmountIn = route[0].amountIn;
80
+ var rawAmountOut = route[route.length - 1].amountOut;
81
+ if (!rawAmountIn || !rawAmountOut) {
82
+ throw new Error('Expected both amountIn and amountOut to be present');
83
+ }
84
+ var isOnlyV2 = isVersionedRoute(types_1.PoolType.V2Pool, route);
85
+ var isOnlyV3 = isVersionedRoute(types_1.PoolType.V3Pool, route);
86
+ return {
87
+ routev3: isOnlyV3 ? new v3_sdk_1.Route(route.map(parsePool), currencyIn, currencyOut) : null,
88
+ routev2: isOnlyV2 ? new v2_sdk_1.Route(route.map(parsePair), currencyIn, currencyOut) : null,
89
+ mixedRoute: !isOnlyV3 && !isOnlyV2 ? new router_sdk_1.MixedRouteSDK(route.map(parsePoolOrPair), currencyIn, currencyOut) : null,
90
+ inputAmount: sdk_core_1.CurrencyAmount.fromRawAmount(currencyIn, rawAmountIn),
91
+ outputAmount: sdk_core_1.CurrencyAmount.fromRawAmount(currencyOut, rawAmountOut),
92
+ };
93
+ });
94
+ }
95
+ catch (e) {
96
+ console.error('Error computing routes', e);
97
+ return;
98
+ }
99
+ }
100
+ exports.computeRoutes = computeRoutes;
101
+ var parsePoolOrPair = function (pool) {
102
+ return pool.type === types_1.PoolType.V3Pool ? parsePool(pool) : parsePair(pool);
103
+ };
104
+ function isVersionedRoute(type, route) {
105
+ return route.every(function (pool) { return pool.type === type; });
106
+ }
107
+ function toDutchOrderInfo(orderInfoJSON) {
108
+ var nonce = orderInfoJSON.nonce, input = orderInfoJSON.input, outputs = orderInfoJSON.outputs, exclusivityOverrideBps = orderInfoJSON.exclusivityOverrideBps;
109
+ return __assign(__assign({}, orderInfoJSON), { nonce: bignumber_1.BigNumber.from(nonce), exclusivityOverrideBps: bignumber_1.BigNumber.from(exclusivityOverrideBps), input: __assign(__assign({}, input), { startAmount: bignumber_1.BigNumber.from(input.startAmount), endAmount: bignumber_1.BigNumber.from(input.endAmount) }), outputs: outputs.map(function (output) { return (__assign(__assign({}, output), { startAmount: bignumber_1.BigNumber.from(output.startAmount), endAmount: bignumber_1.BigNumber.from(output.endAmount) })); }) });
110
+ }
111
+ // Prepares the currencies used for the actual Swap (either UniswapX or Universal Router)
112
+ // May not match `currencyIn` that the user selected because for ETH inputs in UniswapX, the actual
113
+ // swap will use WETH.
114
+ function getTradeCurrencies(args, isUniswapXTrade, routes) {
115
+ var _a, _b, _c, _d, _e;
116
+ var tokenInAddress = args.tokenInAddress, tokenInChainId = args.tokenInChainId, tokenInDecimals = args.tokenInDecimals, tokenInSymbol = args.tokenInSymbol, tokenOutAddress = args.tokenOutAddress, tokenOutChainId = args.tokenOutChainId, tokenOutDecimals = args.tokenOutDecimals, tokenOutSymbol = args.tokenOutSymbol;
117
+ var tokenInIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenInAddress);
118
+ var tokenOutIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenOutAddress);
119
+ var serializedTokenIn = (_b = (_a = routes === null || routes === void 0 ? void 0 : routes[0]) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.tokenIn;
120
+ var serializedTokenOut = (_e = (_c = routes === null || routes === void 0 ? void 0 : routes[0]) === null || _c === void 0 ? void 0 : _c[((_d = routes[0]) === null || _d === void 0 ? void 0 : _d.length) - 1]) === null || _e === void 0 ? void 0 : _e.tokenOut;
121
+ var currencyIn = tokenInIsNative
122
+ ? (0, tokens_1.nativeOnChain)(tokenInChainId)
123
+ : parseToken({
124
+ address: tokenInAddress,
125
+ chainId: tokenInChainId,
126
+ decimals: tokenInDecimals,
127
+ symbol: tokenInSymbol,
128
+ buyFeeBps: serializedTokenIn === null || serializedTokenIn === void 0 ? void 0 : serializedTokenIn.buyFeeBps,
129
+ sellFeeBps: serializedTokenIn === null || serializedTokenIn === void 0 ? void 0 : serializedTokenIn.sellFeeBps,
130
+ });
131
+ var currencyOut = tokenOutIsNative
132
+ ? (0, tokens_1.nativeOnChain)(tokenOutChainId)
133
+ : parseToken({
134
+ address: tokenOutAddress,
135
+ chainId: tokenOutChainId,
136
+ decimals: tokenOutDecimals,
137
+ symbol: tokenOutSymbol,
138
+ buyFeeBps: serializedTokenOut === null || serializedTokenOut === void 0 ? void 0 : serializedTokenOut.buyFeeBps,
139
+ sellFeeBps: serializedTokenOut === null || serializedTokenOut === void 0 ? void 0 : serializedTokenOut.sellFeeBps,
140
+ });
141
+ if (!isUniswapXTrade) {
142
+ return [currencyIn, currencyOut];
143
+ }
144
+ return [currencyIn.isNative ? currencyIn.wrapped : currencyIn, currencyOut];
145
+ }
146
+ function getSwapFee(data) {
147
+ var portionAmount = data.portionAmount, portionBips = data.portionBips, portionRecipient = data.portionRecipient;
148
+ if (!portionAmount || !portionBips || !portionRecipient)
149
+ return undefined;
150
+ return {
151
+ recipient: portionRecipient,
152
+ percent: new sdk_core_1.Percent(portionBips, misc_1.BIPS_BASE),
153
+ amount: portionAmount,
154
+ };
155
+ }
156
+ function getClassicTradeDetails(args, data) {
157
+ var _a;
158
+ var classicQuote = data.routing === types_1.URAQuoteType.CLASSIC ? data.quote : (_a = data.allQuotes.find(types_1.isClassicQuoteResponse)) === null || _a === void 0 ? void 0 : _a.quote;
159
+ if (!classicQuote) {
160
+ return {};
161
+ }
162
+ return {
163
+ gasUseEstimate: classicQuote.gasUseEstimate ? parseFloat(classicQuote.gasUseEstimate) : undefined,
164
+ gasUseEstimateUSD: classicQuote.gasUseEstimateUSD ? parseFloat(classicQuote.gasUseEstimateUSD) : undefined,
165
+ blockNumber: classicQuote.blockNumber,
166
+ routes: computeRoutes(args, classicQuote.route),
167
+ swapFee: getSwapFee(classicQuote),
168
+ };
169
+ }
170
+ function transformQuickRouteToTrade(args, data) {
171
+ var amount = args.amount, tradeType = args.tradeType;
172
+ var _a = getTradeCurrencies(args, false), currencyIn = _a[0], currencyOut = _a[1];
173
+ var _b = data.tradeType === 'EXACT_IN' ? [amount, data.quote.amount] : [data.quote.amount, amount], rawAmountIn = _b[0], rawAmountOut = _b[1];
174
+ var inputAmount = sdk_core_1.CurrencyAmount.fromRawAmount(currencyIn, rawAmountIn);
175
+ var outputAmount = sdk_core_1.CurrencyAmount.fromRawAmount(currencyOut, rawAmountOut);
176
+ return new types_1.PreviewTrade({ inputAmount: inputAmount, outputAmount: outputAmount, tradeType: tradeType });
177
+ }
178
+ exports.transformQuickRouteToTrade = transformQuickRouteToTrade;
179
+ function getUSDCostPerGas(gasUseEstimateUSD, gasUseEstimate) {
180
+ // Some sus javascript float math but it's ok because its just an estimate for display purposes
181
+ if (!gasUseEstimateUSD || !gasUseEstimate)
182
+ return undefined;
183
+ return gasUseEstimateUSD / gasUseEstimate;
184
+ }
185
+ exports.getUSDCostPerGas = getUSDCostPerGas;
186
+ function transformQuoteToTrade(args, data, quoteMethod) {
187
+ var _a, _b, _c;
188
+ return __awaiter(this, void 0, void 0, function () {
189
+ var tradeType, needsWrapIfUniswapX, routerPreference, account, amount, showUniswapXTrade, _d, currencyIn, currencyOut, _e, gasUseEstimateUSD, blockNumber, routes, gasUseEstimate, swapFee, usdCostPerGas, approveInfo, classicTrade, isUniswapXBetter, orderInfo, swapFee_1, wrapInfo, uniswapXTrade;
190
+ return __generator(this, function (_f) {
191
+ switch (_f.label) {
192
+ case 0:
193
+ tradeType = args.tradeType, needsWrapIfUniswapX = args.needsWrapIfUniswapX, routerPreference = args.routerPreference, account = args.account, amount = args.amount;
194
+ showUniswapXTrade = data.routing === types_1.URAQuoteType.DUTCH_LIMIT && routerPreference === types_1.RouterPreference.X;
195
+ _d = getTradeCurrencies(args, showUniswapXTrade), currencyIn = _d[0], currencyOut = _d[1];
196
+ _e = getClassicTradeDetails(args, data), gasUseEstimateUSD = _e.gasUseEstimateUSD, blockNumber = _e.blockNumber, routes = _e.routes, gasUseEstimate = _e.gasUseEstimate, swapFee = _e.swapFee;
197
+ usdCostPerGas = getUSDCostPerGas(gasUseEstimateUSD, gasUseEstimate);
198
+ return [4 /*yield*/, (0, gas_1.getApproveInfo)(account, currencyIn, amount, usdCostPerGas)];
199
+ case 1:
200
+ approveInfo = _f.sent();
201
+ classicTrade = new types_1.ClassicTrade({
202
+ v2Routes: (_a = routes === null || routes === void 0 ? void 0 : routes.filter(function (r) { return r.routev2 !== null; }).map(function (_a) {
203
+ var routev2 = _a.routev2, inputAmount = _a.inputAmount, outputAmount = _a.outputAmount;
204
+ return ({
205
+ routev2: routev2,
206
+ inputAmount: inputAmount,
207
+ outputAmount: outputAmount,
208
+ });
209
+ })) !== null && _a !== void 0 ? _a : [],
210
+ v3Routes: (_b = routes === null || routes === void 0 ? void 0 : routes.filter(function (r) { return r.routev3 !== null; }).map(function (_a) {
211
+ var routev3 = _a.routev3, inputAmount = _a.inputAmount, outputAmount = _a.outputAmount;
212
+ return ({
213
+ routev3: routev3,
214
+ inputAmount: inputAmount,
215
+ outputAmount: outputAmount,
216
+ });
217
+ })) !== null && _b !== void 0 ? _b : [],
218
+ mixedRoutes: (_c = routes === null || routes === void 0 ? void 0 : routes.filter(function (r) { return r.mixedRoute !== null; }).map(function (_a) {
219
+ var mixedRoute = _a.mixedRoute, inputAmount = _a.inputAmount, outputAmount = _a.outputAmount;
220
+ return ({
221
+ mixedRoute: mixedRoute,
222
+ inputAmount: inputAmount,
223
+ outputAmount: outputAmount,
224
+ });
225
+ })) !== null && _c !== void 0 ? _c : [],
226
+ tradeType: tradeType,
227
+ gasUseEstimateUSD: gasUseEstimateUSD,
228
+ gasUseEstimate: gasUseEstimate,
229
+ approveInfo: approveInfo,
230
+ blockNumber: blockNumber,
231
+ requestId: data.quote.requestId,
232
+ quoteMethod: quoteMethod,
233
+ swapFee: swapFee,
234
+ });
235
+ isUniswapXBetter = data.routing === types_1.URAQuoteType.DUTCH_LIMIT;
236
+ if (!isUniswapXBetter) return [3 /*break*/, 3];
237
+ orderInfo = toDutchOrderInfo(data.quote.orderInfo);
238
+ swapFee_1 = getSwapFee(data.quote);
239
+ return [4 /*yield*/, (0, gas_1.getWrapInfo)(needsWrapIfUniswapX, account, currencyIn.chainId, amount, usdCostPerGas)];
240
+ case 2:
241
+ wrapInfo = _f.sent();
242
+ uniswapXTrade = new types_1.DutchOrderTrade({
243
+ currencyIn: currencyIn,
244
+ currenciesOut: [currencyOut],
245
+ orderInfo: orderInfo,
246
+ tradeType: tradeType,
247
+ quoteId: data.quote.quoteId,
248
+ requestId: data.quote.requestId,
249
+ classicGasUseEstimateUSD: classicTrade.totalGasUseEstimateUSD,
250
+ wrapInfo: wrapInfo,
251
+ approveInfo: approveInfo,
252
+ auctionPeriodSecs: data.quote.auctionPeriodSecs,
253
+ startTimeBufferSecs: data.quote.startTimeBufferSecs,
254
+ deadlineBufferSecs: data.quote.deadlineBufferSecs,
255
+ slippageTolerance: toSlippagePercent(data.quote.slippageTolerance),
256
+ swapFee: swapFee_1,
257
+ });
258
+ return [2 /*return*/, {
259
+ state: types_1.QuoteState.SUCCESS,
260
+ trade: uniswapXTrade,
261
+ }];
262
+ case 3: return [2 /*return*/, { state: types_1.QuoteState.SUCCESS, trade: classicTrade }];
263
+ }
264
+ });
265
+ });
266
+ }
267
+ exports.transformQuoteToTrade = transformQuoteToTrade;
268
+ function parseToken(_a) {
269
+ var address = _a.address, chainId = _a.chainId, decimals = _a.decimals, symbol = _a.symbol, buyFeeBps = _a.buyFeeBps, sellFeeBps = _a.sellFeeBps;
270
+ var buyFeeBpsBN = buyFeeBps ? bignumber_1.BigNumber.from(buyFeeBps) : undefined;
271
+ var sellFeeBpsBN = sellFeeBps ? bignumber_1.BigNumber.from(sellFeeBps) : undefined;
272
+ return new sdk_core_1.Token(chainId, address, parseInt(decimals.toString()), symbol, undefined, false, buyFeeBpsBN, sellFeeBpsBN);
273
+ }
274
+ function parsePool(_a) {
275
+ var fee = _a.fee, sqrtRatioX96 = _a.sqrtRatioX96, liquidity = _a.liquidity, tickCurrent = _a.tickCurrent, tokenIn = _a.tokenIn, tokenOut = _a.tokenOut;
276
+ return new v3_sdk_1.Pool(parseToken(tokenIn), parseToken(tokenOut), parseInt(fee), sqrtRatioX96, liquidity, parseInt(tickCurrent));
277
+ }
278
+ var parsePair = function (_a) {
279
+ var reserve0 = _a.reserve0, reserve1 = _a.reserve1;
280
+ return 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));
281
+ };
282
+ // TODO(WEB-2050): Convert other instances of tradeType comparison to use this utility function
283
+ function isExactInput(tradeType) {
284
+ return tradeType === sdk_core_1.TradeType.EXACT_INPUT;
285
+ }
286
+ exports.isExactInput = isExactInput;
287
+ function currencyAddressForSwapQuote(currency) {
288
+ if (currency.isNative) {
289
+ if ((0, tokens_1.isPolygon)(currency.chainId))
290
+ return types_1.SwapRouterNativeAssets.MATIC;
291
+ if ((0, tokens_1.isBsc)(currency.chainId))
292
+ return types_1.SwapRouterNativeAssets.BNB;
293
+ if ((0, tokens_1.isAvalanche)(currency.chainId))
294
+ return types_1.SwapRouterNativeAssets.AVAX;
295
+ return types_1.SwapRouterNativeAssets.ETH;
296
+ }
297
+ return currency.address;
298
+ }
299
+ exports.currencyAddressForSwapQuote = currencyAddressForSwapQuote;
300
+ function isClassicTrade(trade) {
301
+ return (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.Classic;
302
+ }
303
+ exports.isClassicTrade = isClassicTrade;
304
+ function isPreviewTrade(trade) {
305
+ return (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.None;
306
+ }
307
+ exports.isPreviewTrade = isPreviewTrade;
308
+ function isSubmittableTrade(trade) {
309
+ return (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.Classic || (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.UniswapX;
310
+ }
311
+ exports.isSubmittableTrade = isSubmittableTrade;
312
+ function isUniswapXTrade(trade) {
313
+ return (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.UniswapX;
314
+ }
315
+ exports.isUniswapXTrade = isUniswapXTrade;
316
+ function isLimitTrade(trade) {
317
+ return (trade === null || trade === void 0 ? void 0 : trade.fillType) === types_1.TradeFillType.UniswapX && (trade === null || trade === void 0 ? void 0 : trade.offchainOrderType) === types_1.OffchainOrderType.LIMIT_ORDER;
318
+ }
319
+ exports.isLimitTrade = isLimitTrade;
@@ -0,0 +1,44 @@
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 {};
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
54
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
55
+ if (ar || !(i in from)) {
56
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
57
+ ar[i] = from[i];
58
+ }
59
+ }
60
+ return to.concat(ar || Array.prototype.slice.call(from));
61
+ };
62
+ var __importDefault = (this && this.__importDefault) || function (mod) {
63
+ return (mod && mod.__esModule) ? mod : { "default": mod };
64
+ };
65
+ Object.defineProperty(exports, "__esModule", { value: true });
66
+ var chainInfo_1 = require("../constants/chainInfo");
67
+ var ConfiguredJsonRpcProvider_1 = __importDefault(require("./ConfiguredJsonRpcProvider"));
68
+ /**
69
+ * A controller which marks itself disabled on an error, and re-enables itself using exponential backoff.
70
+ * After each retry, it will wait twice as long to retry again. After a success, it will reset the backoff.
71
+ */
72
+ var Controller = /** @class */ (function () {
73
+ function Controller(minimumBackoffTime) {
74
+ this.minimumBackoffTime = minimumBackoffTime;
75
+ this.isEnabled = true;
76
+ this.exponentialBackoffFactor = 1;
77
+ }
78
+ Controller.prototype.reset = function () {
79
+ this.isEnabled = true;
80
+ // @ts-ignore
81
+ clearTimeout(this.timeout);
82
+ this.timeout = undefined;
83
+ };
84
+ Controller.prototype.onSuccess = function () {
85
+ this.reset();
86
+ this.exponentialBackoffFactor = 1;
87
+ };
88
+ /**
89
+ * Called onError.
90
+ * Idempotent - calling this multiple times will *not* reset the exponential backoff timer.
91
+ */
92
+ Controller.prototype.onError = function () {
93
+ var _this = this;
94
+ this.isEnabled = false;
95
+ if (!this.timeout) {
96
+ this.timeout = setTimeout(function () {
97
+ _this.reset();
98
+ _this.exponentialBackoffFactor *= 2;
99
+ }, this.minimumBackoffTime * this.exponentialBackoffFactor);
100
+ }
101
+ };
102
+ Object.defineProperty(Controller.prototype, "enabled", {
103
+ get: function () {
104
+ return this.isEnabled;
105
+ },
106
+ enumerable: false,
107
+ configurable: true
108
+ });
109
+ return Controller;
110
+ }());
111
+ /**
112
+ * An application-specific JSON-RPC provider.
113
+ *
114
+ * This super-provider will instantiate providers for all supported JSON-RPC URLs, so that it may use them as fallbacks.
115
+ * It will use the first (primary) JSON-RPC URL unless there is issue, at which point it will fallback to the next, &c.,
116
+ * retrying the former using exponential backoff. This prevents secondary URLs from permanently overtaking primary URLs.
117
+ */
118
+ var AppJsonRpcProvider = /** @class */ (function (_super) {
119
+ __extends(AppJsonRpcProvider, _super);
120
+ function AppJsonRpcProvider(providers, _a) {
121
+ var _b = _a === void 0 ? {} : _a, _c = _b.minimumBackoffTime, minimumBackoffTime = _c === void 0 ? chainInfo_1.AVERAGE_L1_BLOCK_TIME : _c;
122
+ var _this = this;
123
+ if (providers.length === 0)
124
+ throw new Error('Missing providers for AppJsonRpcProvider');
125
+ _this = _super.call(this, undefined, providers[0].network) || this;
126
+ // AppJsonRpcProvider configures its own pollingInterval, so the encapsulated providers do not need to poll.
127
+ // providers.forEach((provider) => (provider.pollingInterval = Infinity))
128
+ _this.providers = providers.map(function (provider) { return ({ provider: provider, controller: new Controller(minimumBackoffTime) }); });
129
+ return _this;
130
+ }
131
+ AppJsonRpcProvider.prototype.perform = function (method, params) {
132
+ return __awaiter(this, void 0, void 0, function () {
133
+ var sortedProviders, _i, sortedProviders_1, _a, provider, controller, result, error_1;
134
+ return __generator(this, function (_b) {
135
+ switch (_b.label) {
136
+ case 0:
137
+ sortedProviders = AppJsonRpcProvider.sortProviders(this.providers);
138
+ _i = 0, sortedProviders_1 = sortedProviders;
139
+ _b.label = 1;
140
+ case 1:
141
+ if (!(_i < sortedProviders_1.length)) return [3 /*break*/, 6];
142
+ _a = sortedProviders_1[_i], provider = _a.provider, controller = _a.controller;
143
+ _b.label = 2;
144
+ case 2:
145
+ _b.trys.push([2, 4, , 5]);
146
+ return [4 /*yield*/, provider.perform(method, params)];
147
+ case 3:
148
+ result = _b.sent();
149
+ controller.onSuccess();
150
+ return [2 /*return*/, result];
151
+ case 4:
152
+ error_1 = _b.sent();
153
+ console.warn('rpc action failed', error_1);
154
+ controller.onError();
155
+ return [3 /*break*/, 5];
156
+ case 5:
157
+ _i++;
158
+ return [3 /*break*/, 1];
159
+ case 6: throw new Error("All providers failed to perform the operation: ".concat(method));
160
+ }
161
+ });
162
+ });
163
+ };
164
+ AppJsonRpcProvider.sortProviders = function (providers) {
165
+ // Try enabled providers before resorting to disabled providers.
166
+ // Note that we do not filtered out disabled providers.
167
+ return __spreadArray([], providers, true).sort(function (_a, _b) {
168
+ var a = _a.controller.enabled;
169
+ var b = _b.controller.enabled;
170
+ if (a && !b) {
171
+ return -1;
172
+ }
173
+ else if (!a && b) {
174
+ return 1;
175
+ }
176
+ else {
177
+ return 0; // sort is stable
178
+ }
179
+ });
180
+ };
181
+ return AppJsonRpcProvider;
182
+ }(ConfiguredJsonRpcProvider_1.default));
183
+ exports.default = AppJsonRpcProvider;
@@ -0,0 +1,8 @@
1
+ import { Networkish } from '@ethersproject/networks';
2
+ import { StaticJsonRpcProvider } from '@ethersproject/providers';
3
+ import { SupportedInterfaceChain } from '../constants/chains';
4
+ export default class ConfiguredJsonRpcProvider extends StaticJsonRpcProvider {
5
+ constructor(url: string | undefined, networkish: Networkish & {
6
+ chainId: SupportedInterfaceChain;
7
+ }, pollingInterval?: any);
8
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ var providers_1 = require("@ethersproject/providers");
19
+ var chainInfo_1 = require("../constants/chainInfo");
20
+ var ConfiguredJsonRpcProvider = /** @class */ (function (_super) {
21
+ __extends(ConfiguredJsonRpcProvider, _super);
22
+ function ConfiguredJsonRpcProvider(url,
23
+ // Including networkish allows ethers to skip the initial detectNetwork call.
24
+ networkish, pollingInterval) {
25
+ if (pollingInterval === void 0) { pollingInterval = chainInfo_1.AVERAGE_L1_BLOCK_TIME; }
26
+ var _this = _super.call(this, url, networkish) || this;
27
+ // NB: Third-party providers (eg MetaMask) will have their own polling intervals,
28
+ // which should be left as-is to allow operations (eg transaction confirmation) to resolve faster.
29
+ // Network providers need to update less frequently to be considered responsive.
30
+ _this.pollingInterval = pollingInterval;
31
+ return _this;
32
+ }
33
+ return ConfiguredJsonRpcProvider;
34
+ }(providers_1.StaticJsonRpcProvider));
35
+ exports.default = ConfiguredJsonRpcProvider;
@@ -0,0 +1,3 @@
1
+ import { Contract, ContractInterface } from '@ethersproject/contracts';
2
+ import { JsonRpcProvider } from '@ethersproject/providers';
3
+ export declare function getContract(address: string, ABI: ContractInterface, provider: JsonRpcProvider, account?: string): Contract;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getContract = void 0;
4
+ var constants_1 = require("@ethersproject/constants");
5
+ var contracts_1 = require("@ethersproject/contracts");
6
+ var address_1 = require("@ethersproject/address");
7
+ function isAddress(value) {
8
+ if (!value) {
9
+ return false;
10
+ }
11
+ try {
12
+ // Alphabetical letters must be made lowercase for getAddress to work.
13
+ // See documentation here: https://docs.ethers.io/v5/api/utils/address/
14
+ return (0, address_1.getAddress)(value.toLowerCase());
15
+ }
16
+ catch (_a) {
17
+ return false;
18
+ }
19
+ }
20
+ function getContract(address, ABI, provider, account) {
21
+ if (!isAddress(address) || address === constants_1.AddressZero) {
22
+ throw Error("Invalid 'address' parameter '".concat(address, "'."));
23
+ }
24
+ return new contracts_1.Contract(address, ABI, getProviderOrSigner(provider, account));
25
+ }
26
+ exports.getContract = getContract;
27
+ function getProviderOrSigner(provider, account) {
28
+ return account ? provider.getSigner(account).connectUnchecked() : provider;
29
+ }
@@ -0,0 +1,4 @@
1
+ import { Currency, CurrencyAmount, TradeType } from '@uniswap/sdk-core';
2
+ import { SwapRoute } from '@uniswap/smart-order-router';
3
+ import { QuoteResult } from '../routing/types';
4
+ export declare function transformSwapRouteToGetQuoteResult(tradeType: TradeType, amount: CurrencyAmount<Currency>, { quote, quoteGasAdjusted, route, estimatedGasUsed, estimatedGasUsedQuoteToken, estimatedGasUsedUSD, gasPriceWei, methodParameters, blockNumber, }: SwapRoute): QuoteResult;