@juiceswapxyz/router-sdk 0.0.1-beta.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.
- package/LICENSE +21 -0
- package/README.md +10 -0
- package/dist/approveAndCall.d.ts +33 -0
- package/dist/constants.d.ts +13 -0
- package/dist/entities/mixedRoute/route.d.ts +29 -0
- package/dist/entities/mixedRoute/trade.d.ts +183 -0
- package/dist/entities/protocol.d.ts +6 -0
- package/dist/entities/route.d.ts +40 -0
- package/dist/entities/trade.d.ts +127 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +8 -0
- package/dist/multicallExtended.d.ts +11 -0
- package/dist/paymentsExtended.d.ts +15 -0
- package/dist/router-sdk.cjs.development.js +2250 -0
- package/dist/router-sdk.cjs.development.js.map +1 -0
- package/dist/router-sdk.cjs.production.min.js +2 -0
- package/dist/router-sdk.cjs.production.min.js.map +1 -0
- package/dist/router-sdk.esm.js +2217 -0
- package/dist/router-sdk.esm.js.map +1 -0
- package/dist/swapRouter.d.ts +95 -0
- package/dist/utils/TPool.d.ts +4 -0
- package/dist/utils/encodeMixedRouteToPath.d.ts +10 -0
- package/dist/utils/index.d.ts +16 -0
- package/dist/utils/pathCurrency.d.ts +4 -0
- package/package.json +73 -0
|
@@ -0,0 +1,2217 @@
|
|
|
1
|
+
import { Percent, validateAndParseAddress, CurrencyAmount, Price, Fraction, TradeType, sortedInsert, Ether, WETH9 } from '@juiceswapxyz/sdk-core';
|
|
2
|
+
import JSBI from 'jsbi';
|
|
3
|
+
import { Interface } from '@ethersproject/abi';
|
|
4
|
+
import invariant from 'tiny-invariant';
|
|
5
|
+
import IApproveAndCall from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IApproveAndCall.sol/IApproveAndCall.json';
|
|
6
|
+
import { NonfungiblePositionManager, toHex, Multicall, Payments, Pool as Pool$1, Route as Route$1, Trade as Trade$2, encodeRouteToPath, SelfPermit, Position } from '@juiceswapxyz/v3-sdk';
|
|
7
|
+
import IMulticallExtended from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IMulticallExtended.sol/IMulticallExtended.json';
|
|
8
|
+
import IPeripheryPaymentsWithFeeExtended from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IPeripheryPaymentsWithFeeExtended.sol/IPeripheryPaymentsWithFeeExtended.json';
|
|
9
|
+
import ISwapRouter02 from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/ISwapRouter02.sol/ISwapRouter02.json';
|
|
10
|
+
import { Pair, Route, Trade as Trade$3 } from '@juiceswapxyz/v2-sdk';
|
|
11
|
+
import { Pool, Route as Route$2, Trade as Trade$1 } from '@juiceswapxyz/v4-sdk';
|
|
12
|
+
import { pack } from '@ethersproject/solidity';
|
|
13
|
+
|
|
14
|
+
var ADDRESS_ZERO = '0x0000000000000000000000000000000000000000';
|
|
15
|
+
var MSG_SENDER = '0x0000000000000000000000000000000000000001';
|
|
16
|
+
var ADDRESS_THIS = '0x0000000000000000000000000000000000000002';
|
|
17
|
+
var ZERO = /*#__PURE__*/JSBI.BigInt(0);
|
|
18
|
+
var ONE = /*#__PURE__*/JSBI.BigInt(1);
|
|
19
|
+
// = 1 << 23 or 0b0100000000000000000000000
|
|
20
|
+
var MIXED_QUOTER_V1_V2_FEE_PATH_PLACEHOLDER = 1 << 23;
|
|
21
|
+
// = 10 << 4 or 0b00100000
|
|
22
|
+
var MIXED_QUOTER_V2_V2_FEE_PATH_PLACEHOLDER = 2 << 4;
|
|
23
|
+
// = 11 << 20 or 0b001100000000000000000000
|
|
24
|
+
var MIXED_QUOTER_V2_V3_FEE_PATH_PLACEHOLDER = 3 << 20;
|
|
25
|
+
// = 100 << 20 or 0b010000000000000000000000
|
|
26
|
+
var MIXED_QUOTER_V2_V4_FEE_PATH_PLACEHOLDER = 4 << 20;
|
|
27
|
+
var ZERO_PERCENT = /*#__PURE__*/new Percent(ZERO);
|
|
28
|
+
var ONE_HUNDRED_PERCENT = /*#__PURE__*/new Percent(100, 100);
|
|
29
|
+
|
|
30
|
+
var ApprovalTypes;
|
|
31
|
+
(function (ApprovalTypes) {
|
|
32
|
+
ApprovalTypes[ApprovalTypes["NOT_REQUIRED"] = 0] = "NOT_REQUIRED";
|
|
33
|
+
ApprovalTypes[ApprovalTypes["MAX"] = 1] = "MAX";
|
|
34
|
+
ApprovalTypes[ApprovalTypes["MAX_MINUS_ONE"] = 2] = "MAX_MINUS_ONE";
|
|
35
|
+
ApprovalTypes[ApprovalTypes["ZERO_THEN_MAX"] = 3] = "ZERO_THEN_MAX";
|
|
36
|
+
ApprovalTypes[ApprovalTypes["ZERO_THEN_MAX_MINUS_ONE"] = 4] = "ZERO_THEN_MAX_MINUS_ONE";
|
|
37
|
+
})(ApprovalTypes || (ApprovalTypes = {}));
|
|
38
|
+
// type guard
|
|
39
|
+
function isMint(options) {
|
|
40
|
+
return Object.keys(options).some(function (k) {
|
|
41
|
+
return k === 'recipient';
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
var ApproveAndCall = /*#__PURE__*/function () {
|
|
45
|
+
/**
|
|
46
|
+
* Cannot be constructed.
|
|
47
|
+
*/
|
|
48
|
+
function ApproveAndCall() {}
|
|
49
|
+
ApproveAndCall.encodeApproveMax = function encodeApproveMax(token) {
|
|
50
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('approveMax', [token.address]);
|
|
51
|
+
};
|
|
52
|
+
ApproveAndCall.encodeApproveMaxMinusOne = function encodeApproveMaxMinusOne(token) {
|
|
53
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('approveMaxMinusOne', [token.address]);
|
|
54
|
+
};
|
|
55
|
+
ApproveAndCall.encodeApproveZeroThenMax = function encodeApproveZeroThenMax(token) {
|
|
56
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMax', [token.address]);
|
|
57
|
+
};
|
|
58
|
+
ApproveAndCall.encodeApproveZeroThenMaxMinusOne = function encodeApproveZeroThenMaxMinusOne(token) {
|
|
59
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMaxMinusOne', [token.address]);
|
|
60
|
+
};
|
|
61
|
+
ApproveAndCall.encodeCallPositionManager = function encodeCallPositionManager(calldatas) {
|
|
62
|
+
!(calldatas.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NULL_CALLDATA') : invariant(false) : void 0;
|
|
63
|
+
if (calldatas.length === 1) {
|
|
64
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', calldatas);
|
|
65
|
+
} else {
|
|
66
|
+
var encodedMulticall = NonfungiblePositionManager.INTERFACE.encodeFunctionData('multicall', [calldatas]);
|
|
67
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', [encodedMulticall]);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Encode adding liquidity to a position in the nft manager contract
|
|
72
|
+
* @param position Forcasted position with expected amount out from swap
|
|
73
|
+
* @param minimalPosition Forcasted position with custom minimal token amounts
|
|
74
|
+
* @param addLiquidityOptions Options for adding liquidity
|
|
75
|
+
* @param slippageTolerance Defines maximum slippage
|
|
76
|
+
*/;
|
|
77
|
+
ApproveAndCall.encodeAddLiquidity = function encodeAddLiquidity(position, minimalPosition, addLiquidityOptions, slippageTolerance) {
|
|
78
|
+
var _position$mintAmounts = position.mintAmountsWithSlippage(slippageTolerance),
|
|
79
|
+
amount0Min = _position$mintAmounts.amount0,
|
|
80
|
+
amount1Min = _position$mintAmounts.amount1;
|
|
81
|
+
// position.mintAmountsWithSlippage() can create amounts not dependenable in scenarios
|
|
82
|
+
// such as range orders. Allow the option to provide a position with custom minimum amounts
|
|
83
|
+
// for these scenarios
|
|
84
|
+
if (JSBI.lessThan(minimalPosition.amount0.quotient, amount0Min)) {
|
|
85
|
+
amount0Min = minimalPosition.amount0.quotient;
|
|
86
|
+
}
|
|
87
|
+
if (JSBI.lessThan(minimalPosition.amount1.quotient, amount1Min)) {
|
|
88
|
+
amount1Min = minimalPosition.amount1.quotient;
|
|
89
|
+
}
|
|
90
|
+
if (isMint(addLiquidityOptions)) {
|
|
91
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('mint', [{
|
|
92
|
+
token0: position.pool.token0.address,
|
|
93
|
+
token1: position.pool.token1.address,
|
|
94
|
+
fee: position.pool.fee,
|
|
95
|
+
tickLower: position.tickLower,
|
|
96
|
+
tickUpper: position.tickUpper,
|
|
97
|
+
amount0Min: toHex(amount0Min),
|
|
98
|
+
amount1Min: toHex(amount1Min),
|
|
99
|
+
recipient: addLiquidityOptions.recipient
|
|
100
|
+
}]);
|
|
101
|
+
} else {
|
|
102
|
+
return ApproveAndCall.INTERFACE.encodeFunctionData('increaseLiquidity', [{
|
|
103
|
+
token0: position.pool.token0.address,
|
|
104
|
+
token1: position.pool.token1.address,
|
|
105
|
+
amount0Min: toHex(amount0Min),
|
|
106
|
+
amount1Min: toHex(amount1Min),
|
|
107
|
+
tokenId: toHex(addLiquidityOptions.tokenId)
|
|
108
|
+
}]);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
ApproveAndCall.encodeApprove = function encodeApprove(token, approvalType) {
|
|
112
|
+
switch (approvalType) {
|
|
113
|
+
case ApprovalTypes.MAX:
|
|
114
|
+
return ApproveAndCall.encodeApproveMax(token.wrapped);
|
|
115
|
+
case ApprovalTypes.MAX_MINUS_ONE:
|
|
116
|
+
return ApproveAndCall.encodeApproveMaxMinusOne(token.wrapped);
|
|
117
|
+
case ApprovalTypes.ZERO_THEN_MAX:
|
|
118
|
+
return ApproveAndCall.encodeApproveZeroThenMax(token.wrapped);
|
|
119
|
+
case ApprovalTypes.ZERO_THEN_MAX_MINUS_ONE:
|
|
120
|
+
return ApproveAndCall.encodeApproveZeroThenMaxMinusOne(token.wrapped);
|
|
121
|
+
default:
|
|
122
|
+
throw new Error('Error: invalid ApprovalType');
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
return ApproveAndCall;
|
|
126
|
+
}();
|
|
127
|
+
ApproveAndCall.INTERFACE = /*#__PURE__*/new Interface(IApproveAndCall.abi);
|
|
128
|
+
|
|
129
|
+
function validateAndParseBytes32(bytes32) {
|
|
130
|
+
if (!bytes32.match(/^0x[0-9a-fA-F]{64}$/)) {
|
|
131
|
+
throw new Error(bytes32 + " is not valid bytes32.");
|
|
132
|
+
}
|
|
133
|
+
return bytes32.toLowerCase();
|
|
134
|
+
}
|
|
135
|
+
var MulticallExtended = /*#__PURE__*/function () {
|
|
136
|
+
/**
|
|
137
|
+
* Cannot be constructed.
|
|
138
|
+
*/
|
|
139
|
+
function MulticallExtended() {}
|
|
140
|
+
MulticallExtended.encodeMulticall = function encodeMulticall(calldatas, validation) {
|
|
141
|
+
// if there's no validation, we can just fall back to regular multicall
|
|
142
|
+
if (typeof validation === 'undefined') {
|
|
143
|
+
return Multicall.encodeMulticall(calldatas);
|
|
144
|
+
}
|
|
145
|
+
// if there is validation, we have to normalize calldatas
|
|
146
|
+
if (!Array.isArray(calldatas)) {
|
|
147
|
+
calldatas = [calldatas];
|
|
148
|
+
}
|
|
149
|
+
// this means the validation value should be a previousBlockhash
|
|
150
|
+
if (typeof validation === 'string' && validation.startsWith('0x')) {
|
|
151
|
+
var previousBlockhash = validateAndParseBytes32(validation);
|
|
152
|
+
return MulticallExtended.INTERFACE.encodeFunctionData('multicall(bytes32,bytes[])', [previousBlockhash, calldatas]);
|
|
153
|
+
} else {
|
|
154
|
+
var deadline = toHex(validation);
|
|
155
|
+
return MulticallExtended.INTERFACE.encodeFunctionData('multicall(uint256,bytes[])', [deadline, calldatas]);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
return MulticallExtended;
|
|
159
|
+
}();
|
|
160
|
+
MulticallExtended.INTERFACE = /*#__PURE__*/new Interface(IMulticallExtended.abi);
|
|
161
|
+
|
|
162
|
+
function encodeFeeBips(fee) {
|
|
163
|
+
return toHex(fee.multiply(10000).quotient);
|
|
164
|
+
}
|
|
165
|
+
var PaymentsExtended = /*#__PURE__*/function () {
|
|
166
|
+
/**
|
|
167
|
+
* Cannot be constructed.
|
|
168
|
+
*/
|
|
169
|
+
function PaymentsExtended() {}
|
|
170
|
+
PaymentsExtended.encodeUnwrapWETH9 = function encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
|
|
171
|
+
// if there's a recipient, just pass it along
|
|
172
|
+
if (typeof recipient === 'string') {
|
|
173
|
+
return Payments.encodeUnwrapWETH9(amountMinimum, recipient, feeOptions);
|
|
174
|
+
}
|
|
175
|
+
if (!!feeOptions) {
|
|
176
|
+
var feeBips = encodeFeeBips(feeOptions.fee);
|
|
177
|
+
var feeRecipient = validateAndParseAddress(feeOptions.recipient);
|
|
178
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9WithFee(uint256,uint256,address)', [toHex(amountMinimum), feeBips, feeRecipient]);
|
|
179
|
+
} else {
|
|
180
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9(uint256)', [toHex(amountMinimum)]);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
PaymentsExtended.encodeSweepToken = function encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
|
|
184
|
+
// if there's a recipient, just pass it along
|
|
185
|
+
if (typeof recipient === 'string') {
|
|
186
|
+
return Payments.encodeSweepToken(token, amountMinimum, recipient, feeOptions);
|
|
187
|
+
}
|
|
188
|
+
if (!!feeOptions) {
|
|
189
|
+
var feeBips = encodeFeeBips(feeOptions.fee);
|
|
190
|
+
var feeRecipient = validateAndParseAddress(feeOptions.recipient);
|
|
191
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('sweepTokenWithFee(address,uint256,uint256,address)', [token.address, toHex(amountMinimum), feeBips, feeRecipient]);
|
|
192
|
+
} else {
|
|
193
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('sweepToken(address,uint256)', [token.address, toHex(amountMinimum)]);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
PaymentsExtended.encodePull = function encodePull(token, amount) {
|
|
197
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('pull', [token.address, toHex(amount)]);
|
|
198
|
+
};
|
|
199
|
+
PaymentsExtended.encodeWrapETH = function encodeWrapETH(amount) {
|
|
200
|
+
return PaymentsExtended.INTERFACE.encodeFunctionData('wrapETH', [toHex(amount)]);
|
|
201
|
+
};
|
|
202
|
+
return PaymentsExtended;
|
|
203
|
+
}();
|
|
204
|
+
PaymentsExtended.INTERFACE = /*#__PURE__*/new Interface(IPeripheryPaymentsWithFeeExtended.abi);
|
|
205
|
+
|
|
206
|
+
function _arrayLikeToArray(r, a) {
|
|
207
|
+
(null == a || a > r.length) && (a = r.length);
|
|
208
|
+
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
|
|
209
|
+
return n;
|
|
210
|
+
}
|
|
211
|
+
function asyncGeneratorStep(n, t, e, r, o, a, c) {
|
|
212
|
+
try {
|
|
213
|
+
var i = n[a](c),
|
|
214
|
+
u = i.value;
|
|
215
|
+
} catch (n) {
|
|
216
|
+
return void e(n);
|
|
217
|
+
}
|
|
218
|
+
i.done ? t(u) : Promise.resolve(u).then(r, o);
|
|
219
|
+
}
|
|
220
|
+
function _asyncToGenerator(n) {
|
|
221
|
+
return function () {
|
|
222
|
+
var t = this,
|
|
223
|
+
e = arguments;
|
|
224
|
+
return new Promise(function (r, o) {
|
|
225
|
+
var a = n.apply(t, e);
|
|
226
|
+
function _next(n) {
|
|
227
|
+
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
|
|
228
|
+
}
|
|
229
|
+
function _throw(n) {
|
|
230
|
+
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
|
|
231
|
+
}
|
|
232
|
+
_next(void 0);
|
|
233
|
+
});
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function _defineProperties(e, r) {
|
|
237
|
+
for (var t = 0; t < r.length; t++) {
|
|
238
|
+
var o = r[t];
|
|
239
|
+
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function _createClass(e, r, t) {
|
|
243
|
+
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
|
|
244
|
+
writable: !1
|
|
245
|
+
}), e;
|
|
246
|
+
}
|
|
247
|
+
function _createForOfIteratorHelperLoose(r, e) {
|
|
248
|
+
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
|
|
249
|
+
if (t) return (t = t.call(r)).next.bind(t);
|
|
250
|
+
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
|
|
251
|
+
t && (r = t);
|
|
252
|
+
var o = 0;
|
|
253
|
+
return function () {
|
|
254
|
+
return o >= r.length ? {
|
|
255
|
+
done: !0
|
|
256
|
+
} : {
|
|
257
|
+
done: !1,
|
|
258
|
+
value: r[o++]
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
263
|
+
}
|
|
264
|
+
function _extends() {
|
|
265
|
+
return _extends = Object.assign ? Object.assign.bind() : function (n) {
|
|
266
|
+
for (var e = 1; e < arguments.length; e++) {
|
|
267
|
+
var t = arguments[e];
|
|
268
|
+
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
|
|
269
|
+
}
|
|
270
|
+
return n;
|
|
271
|
+
}, _extends.apply(null, arguments);
|
|
272
|
+
}
|
|
273
|
+
function _inheritsLoose(t, o) {
|
|
274
|
+
t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
|
|
275
|
+
}
|
|
276
|
+
function _regenerator() {
|
|
277
|
+
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
|
|
278
|
+
var e,
|
|
279
|
+
t,
|
|
280
|
+
r = "function" == typeof Symbol ? Symbol : {},
|
|
281
|
+
n = r.iterator || "@@iterator",
|
|
282
|
+
o = r.toStringTag || "@@toStringTag";
|
|
283
|
+
function i(r, n, o, i) {
|
|
284
|
+
var c = n && n.prototype instanceof Generator ? n : Generator,
|
|
285
|
+
u = Object.create(c.prototype);
|
|
286
|
+
return _regeneratorDefine(u, "_invoke", function (r, n, o) {
|
|
287
|
+
var i,
|
|
288
|
+
c,
|
|
289
|
+
u,
|
|
290
|
+
f = 0,
|
|
291
|
+
p = o || [],
|
|
292
|
+
y = !1,
|
|
293
|
+
G = {
|
|
294
|
+
p: 0,
|
|
295
|
+
n: 0,
|
|
296
|
+
v: e,
|
|
297
|
+
a: d,
|
|
298
|
+
f: d.bind(e, 4),
|
|
299
|
+
d: function (t, r) {
|
|
300
|
+
return i = t, c = 0, u = e, G.n = r, a;
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
function d(r, n) {
|
|
304
|
+
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
|
|
305
|
+
var o,
|
|
306
|
+
i = p[t],
|
|
307
|
+
d = G.p,
|
|
308
|
+
l = i[2];
|
|
309
|
+
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
|
|
310
|
+
}
|
|
311
|
+
if (o || r > 1) return a;
|
|
312
|
+
throw y = !0, n;
|
|
313
|
+
}
|
|
314
|
+
return function (o, p, l) {
|
|
315
|
+
if (f > 1) throw TypeError("Generator is already running");
|
|
316
|
+
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
|
|
317
|
+
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
|
|
318
|
+
try {
|
|
319
|
+
if (f = 2, i) {
|
|
320
|
+
if (c || (o = "next"), t = i[o]) {
|
|
321
|
+
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
|
|
322
|
+
if (!t.done) return t;
|
|
323
|
+
u = t.value, c < 2 && (c = 0);
|
|
324
|
+
} else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
|
|
325
|
+
i = e;
|
|
326
|
+
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
|
|
327
|
+
} catch (t) {
|
|
328
|
+
i = e, c = 1, u = t;
|
|
329
|
+
} finally {
|
|
330
|
+
f = 1;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
value: t,
|
|
335
|
+
done: y
|
|
336
|
+
};
|
|
337
|
+
};
|
|
338
|
+
}(r, o, i), !0), u;
|
|
339
|
+
}
|
|
340
|
+
var a = {};
|
|
341
|
+
function Generator() {}
|
|
342
|
+
function GeneratorFunction() {}
|
|
343
|
+
function GeneratorFunctionPrototype() {}
|
|
344
|
+
t = Object.getPrototypeOf;
|
|
345
|
+
var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
|
|
346
|
+
return this;
|
|
347
|
+
}), t),
|
|
348
|
+
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
|
|
349
|
+
function f(e) {
|
|
350
|
+
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
|
|
351
|
+
}
|
|
352
|
+
return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
|
|
353
|
+
return this;
|
|
354
|
+
}), _regeneratorDefine(u, "toString", function () {
|
|
355
|
+
return "[object Generator]";
|
|
356
|
+
}), (_regenerator = function () {
|
|
357
|
+
return {
|
|
358
|
+
w: i,
|
|
359
|
+
m: f
|
|
360
|
+
};
|
|
361
|
+
})();
|
|
362
|
+
}
|
|
363
|
+
function _regeneratorDefine(e, r, n, t) {
|
|
364
|
+
var i = Object.defineProperty;
|
|
365
|
+
try {
|
|
366
|
+
i({}, "", {});
|
|
367
|
+
} catch (e) {
|
|
368
|
+
i = 0;
|
|
369
|
+
}
|
|
370
|
+
_regeneratorDefine = function (e, r, n, t) {
|
|
371
|
+
function o(r, n) {
|
|
372
|
+
_regeneratorDefine(e, r, function (e) {
|
|
373
|
+
return this._invoke(r, n, e);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
r ? i ? i(e, r, {
|
|
377
|
+
value: n,
|
|
378
|
+
enumerable: !t,
|
|
379
|
+
configurable: !t,
|
|
380
|
+
writable: !t
|
|
381
|
+
}) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
|
|
382
|
+
}, _regeneratorDefine(e, r, n, t);
|
|
383
|
+
}
|
|
384
|
+
function _setPrototypeOf(t, e) {
|
|
385
|
+
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
|
|
386
|
+
return t.__proto__ = e, t;
|
|
387
|
+
}, _setPrototypeOf(t, e);
|
|
388
|
+
}
|
|
389
|
+
function _toPrimitive(t, r) {
|
|
390
|
+
if ("object" != typeof t || !t) return t;
|
|
391
|
+
var e = t[Symbol.toPrimitive];
|
|
392
|
+
if (void 0 !== e) {
|
|
393
|
+
var i = e.call(t, r || "default");
|
|
394
|
+
if ("object" != typeof i) return i;
|
|
395
|
+
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
396
|
+
}
|
|
397
|
+
return ("string" === r ? String : Number)(t);
|
|
398
|
+
}
|
|
399
|
+
function _toPropertyKey(t) {
|
|
400
|
+
var i = _toPrimitive(t, "string");
|
|
401
|
+
return "symbol" == typeof i ? i : i + "";
|
|
402
|
+
}
|
|
403
|
+
function _unsupportedIterableToArray(r, a) {
|
|
404
|
+
if (r) {
|
|
405
|
+
if ("string" == typeof r) return _arrayLikeToArray(r, a);
|
|
406
|
+
var t = {}.toString.call(r).slice(8, -1);
|
|
407
|
+
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function amountWithPathCurrency(amount, pool) {
|
|
412
|
+
return CurrencyAmount.fromFractionalAmount(getPathCurrency(amount.currency, pool), amount.numerator, amount.denominator);
|
|
413
|
+
}
|
|
414
|
+
function getPathCurrency(currency, pool) {
|
|
415
|
+
// return currency if the currency matches a currency of the pool
|
|
416
|
+
if (pool.involvesToken(currency)) {
|
|
417
|
+
return currency;
|
|
418
|
+
// return if currency.wrapped if pool involves wrapped currency
|
|
419
|
+
} else if (pool.involvesToken(currency.wrapped)) {
|
|
420
|
+
return currency.wrapped;
|
|
421
|
+
// return native currency if pool involves native version of wrapped currency (only applies to V4)
|
|
422
|
+
} else if (pool instanceof Pool) {
|
|
423
|
+
if (pool.token0.wrapped.equals(currency)) {
|
|
424
|
+
return pool.token0;
|
|
425
|
+
} else if (pool.token1.wrapped.equals(currency)) {
|
|
426
|
+
return pool.token1;
|
|
427
|
+
}
|
|
428
|
+
// otherwise the token is invalid
|
|
429
|
+
} else {
|
|
430
|
+
throw new Error("Expected currency " + currency.symbol + " to be either " + pool.token0.symbol + " or " + pool.token1.symbol);
|
|
431
|
+
}
|
|
432
|
+
return currency; // this line needed for typescript to compile
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Represents a list of pools or pairs through which a swap can occur
|
|
437
|
+
* @template TInput The input token
|
|
438
|
+
* @template TOutput The output token
|
|
439
|
+
*/
|
|
440
|
+
var MixedRouteSDK = /*#__PURE__*/function () {
|
|
441
|
+
/**
|
|
442
|
+
* Creates an instance of route.
|
|
443
|
+
* @param pools An array of `TPool` objects (pools or pairs), ordered by the route the swap will take
|
|
444
|
+
* @param input The input token
|
|
445
|
+
* @param output The output token
|
|
446
|
+
* @param retainsFakePool Set to true to filter out a pool that has a fake eth-weth pool
|
|
447
|
+
*/
|
|
448
|
+
function MixedRouteSDK(pools, input, output, retainFakePools) {
|
|
449
|
+
if (retainFakePools === void 0) {
|
|
450
|
+
retainFakePools = false;
|
|
451
|
+
}
|
|
452
|
+
this._midPrice = null;
|
|
453
|
+
pools = retainFakePools ? pools : pools.filter(function (pool) {
|
|
454
|
+
return !(pool instanceof Pool && pool.tickSpacing === 0);
|
|
455
|
+
});
|
|
456
|
+
!(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
|
|
457
|
+
// there is a pool mismatched to the path if we do not retain the fake eth-weth pools
|
|
458
|
+
var chainId = pools[0].chainId;
|
|
459
|
+
var allOnSameChain = pools.every(function (pool) {
|
|
460
|
+
return pool.chainId === chainId;
|
|
461
|
+
});
|
|
462
|
+
!allOnSameChain ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
|
|
463
|
+
this.pathInput = getPathCurrency(input, pools[0]);
|
|
464
|
+
this.pathOutput = getPathCurrency(output, pools[pools.length - 1]);
|
|
465
|
+
if (!(pools[0] instanceof Pool)) {
|
|
466
|
+
!pools[0].involvesToken(this.pathInput) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
|
|
467
|
+
} else {
|
|
468
|
+
!pools[0].v4InvolvesToken(this.pathInput) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
|
|
469
|
+
}
|
|
470
|
+
var lastPool = pools[pools.length - 1];
|
|
471
|
+
if (lastPool instanceof Pool) {
|
|
472
|
+
!(lastPool.v4InvolvesToken(output) || lastPool.v4InvolvesToken(output.wrapped)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
|
|
473
|
+
} else {
|
|
474
|
+
!lastPool.involvesToken(output.wrapped) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Normalizes token0-token1 order and selects the next token/fee step to add to the path
|
|
478
|
+
* */
|
|
479
|
+
var tokenPath = [this.pathInput];
|
|
480
|
+
pools[0].token0.equals(this.pathInput) ? tokenPath.push(pools[0].token1) : tokenPath.push(pools[0].token0);
|
|
481
|
+
for (var i = 1; i < pools.length; i++) {
|
|
482
|
+
var pool = pools[i];
|
|
483
|
+
var inputToken = tokenPath[i];
|
|
484
|
+
var outputToken = void 0;
|
|
485
|
+
if (
|
|
486
|
+
// we hit an edge case if it's a v4 pool and neither of the tokens are in the pool OR it is not a v4 pool but the input currency is eth
|
|
487
|
+
pool instanceof Pool && !pool.involvesToken(inputToken) || !(pool instanceof Pool) && inputToken.isNative) {
|
|
488
|
+
// We handle the case where the inputToken =/= pool.token0 or pool.token1. There are 2 specific cases.
|
|
489
|
+
if (inputToken.equals(pool.token0.wrapped)) {
|
|
490
|
+
// 1) the inputToken is WETH and the current pool has ETH
|
|
491
|
+
// for example, pools: USDC-WETH, ETH-PEPE, path: USDC, WETH, PEPE
|
|
492
|
+
// second pool is a v4 pool, the first could be any version
|
|
493
|
+
outputToken = pool.token1;
|
|
494
|
+
} else if (inputToken.wrapped.equals(pool.token0) || inputToken.wrapped.equals(pool.token1)) {
|
|
495
|
+
// 2) the inputToken is ETH and the current pool has WETH
|
|
496
|
+
// for example, pools: USDC-ETH, WETH-PEPE, path: USDC, ETH, PEPE
|
|
497
|
+
// first pool is a v4 pool, the second could be any version
|
|
498
|
+
outputToken = inputToken.wrapped.equals(pool.token0) ? pool.token1 : pool.token0;
|
|
499
|
+
} else {
|
|
500
|
+
throw new Error("POOL_MISMATCH pool: " + JSON.stringify(pool) + " inputToken: " + JSON.stringify(inputToken));
|
|
501
|
+
}
|
|
502
|
+
} else {
|
|
503
|
+
// then the input token must equal either token0 or token1
|
|
504
|
+
!(inputToken.equals(pool.token0) || inputToken.equals(pool.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, "PATH pool " + JSON.stringify(pool) + " inputToken " + JSON.stringify(inputToken)) : invariant(false) : void 0;
|
|
505
|
+
outputToken = inputToken.equals(pool.token0) ? pool.token1 : pool.token0;
|
|
506
|
+
}
|
|
507
|
+
tokenPath.push(outputToken);
|
|
508
|
+
}
|
|
509
|
+
this.pools = pools;
|
|
510
|
+
this.path = tokenPath;
|
|
511
|
+
this.input = input;
|
|
512
|
+
this.output = output != null ? output : tokenPath[tokenPath.length - 1];
|
|
513
|
+
}
|
|
514
|
+
return _createClass(MixedRouteSDK, [{
|
|
515
|
+
key: "chainId",
|
|
516
|
+
get: function get() {
|
|
517
|
+
return this.pools[0].chainId;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Returns the mid price of the route
|
|
521
|
+
*/
|
|
522
|
+
}, {
|
|
523
|
+
key: "midPrice",
|
|
524
|
+
get: function get() {
|
|
525
|
+
if (this._midPrice !== null) return this._midPrice;
|
|
526
|
+
var price = this.pools.slice(1).reduce(function (_ref, pool) {
|
|
527
|
+
var nextInput = _ref.nextInput,
|
|
528
|
+
price = _ref.price;
|
|
529
|
+
return nextInput.equals(pool.token0) ? {
|
|
530
|
+
nextInput: pool.token1,
|
|
531
|
+
price: price.multiply(pool.token0Price.asFraction)
|
|
532
|
+
} : {
|
|
533
|
+
nextInput: pool.token0,
|
|
534
|
+
price: price.multiply(pool.token1Price.asFraction)
|
|
535
|
+
};
|
|
536
|
+
}, this.pools[0].token0.equals(this.pathInput) ? {
|
|
537
|
+
nextInput: this.pools[0].token1,
|
|
538
|
+
price: this.pools[0].token0Price.asFraction
|
|
539
|
+
} : {
|
|
540
|
+
nextInput: this.pools[0].token0,
|
|
541
|
+
price: this.pools[0].token1Price.asFraction
|
|
542
|
+
}).price;
|
|
543
|
+
return this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator);
|
|
544
|
+
}
|
|
545
|
+
}]);
|
|
546
|
+
}();
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
|
|
550
|
+
* @template TInput The input token, either Ether or an ERC-20
|
|
551
|
+
* @template TOutput The output token, either Ether or an ERC-20
|
|
552
|
+
* @template TTradeType The trade type, either exact input or exact output
|
|
553
|
+
* @param a The first trade to compare
|
|
554
|
+
* @param b The second trade to compare
|
|
555
|
+
* @returns A sorted ordering for two neighboring elements in a trade array
|
|
556
|
+
*/
|
|
557
|
+
function tradeComparator(a, b) {
|
|
558
|
+
// must have same input and output token for comparison
|
|
559
|
+
!a.inputAmount.currency.equals(b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
|
|
560
|
+
!a.outputAmount.currency.equals(b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
|
|
561
|
+
if (a.outputAmount.equalTo(b.outputAmount)) {
|
|
562
|
+
if (a.inputAmount.equalTo(b.inputAmount)) {
|
|
563
|
+
// consider the number of hops since each hop costs gas
|
|
564
|
+
var aHops = a.swaps.reduce(function (total, cur) {
|
|
565
|
+
return total + cur.route.path.length;
|
|
566
|
+
}, 0);
|
|
567
|
+
var bHops = b.swaps.reduce(function (total, cur) {
|
|
568
|
+
return total + cur.route.path.length;
|
|
569
|
+
}, 0);
|
|
570
|
+
return aHops - bHops;
|
|
571
|
+
}
|
|
572
|
+
// trade A requires less input than trade B, so A should come first
|
|
573
|
+
if (a.inputAmount.lessThan(b.inputAmount)) {
|
|
574
|
+
return -1;
|
|
575
|
+
} else {
|
|
576
|
+
return 1;
|
|
577
|
+
}
|
|
578
|
+
} else {
|
|
579
|
+
// tradeA has less output than trade B, so should come second
|
|
580
|
+
if (a.outputAmount.lessThan(b.outputAmount)) {
|
|
581
|
+
return 1;
|
|
582
|
+
} else {
|
|
583
|
+
return -1;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Represents a trade executed against a set of routes where some percentage of the input is
|
|
589
|
+
* split across each route.
|
|
590
|
+
*
|
|
591
|
+
* Each route has its own set of pools. Pools can not be re-used across routes.
|
|
592
|
+
*
|
|
593
|
+
* Does not account for slippage, i.e., changes in price environment that can occur between
|
|
594
|
+
* the time the trade is submitted and when it is executed.
|
|
595
|
+
* @notice This class is functionally the same as the `Trade` class in the `@juiceswapxyz/v3-sdk` package, aside from typing and some input validation.
|
|
596
|
+
* @template TInput The input token, either Ether or an ERC-20
|
|
597
|
+
* @template TOutput The output token, either Ether or an ERC-20
|
|
598
|
+
* @template TTradeType The trade type, either exact input or exact output
|
|
599
|
+
*/
|
|
600
|
+
var MixedRouteTrade = /*#__PURE__*/function () {
|
|
601
|
+
/**
|
|
602
|
+
* Construct a trade by passing in the pre-computed property values
|
|
603
|
+
* @param routes The routes through which the trade occurs
|
|
604
|
+
* @param tradeType The type of trade, exact input or exact output
|
|
605
|
+
*/
|
|
606
|
+
function MixedRouteTrade(_ref) {
|
|
607
|
+
var routes = _ref.routes,
|
|
608
|
+
tradeType = _ref.tradeType;
|
|
609
|
+
var inputCurrency = routes[0].inputAmount.currency;
|
|
610
|
+
var outputCurrency = routes[0].outputAmount.currency;
|
|
611
|
+
!routes.every(function (_ref2) {
|
|
612
|
+
var route = _ref2.route;
|
|
613
|
+
return inputCurrency.wrapped.equals(route.input.wrapped);
|
|
614
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY_MATCH') : invariant(false) : void 0;
|
|
615
|
+
!routes.every(function (_ref3) {
|
|
616
|
+
var route = _ref3.route;
|
|
617
|
+
return outputCurrency.wrapped.equals(route.output.wrapped);
|
|
618
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : invariant(false) : void 0;
|
|
619
|
+
var numPools = routes.map(function (_ref4) {
|
|
620
|
+
var route = _ref4.route;
|
|
621
|
+
return route.pools.length;
|
|
622
|
+
}).reduce(function (total, cur) {
|
|
623
|
+
return total + cur;
|
|
624
|
+
}, 0);
|
|
625
|
+
var poolIdentifierSet = new Set();
|
|
626
|
+
for (var _iterator = _createForOfIteratorHelperLoose(routes), _step; !(_step = _iterator()).done;) {
|
|
627
|
+
var route = _step.value.route;
|
|
628
|
+
for (var _iterator2 = _createForOfIteratorHelperLoose(route.pools), _step2; !(_step2 = _iterator2()).done;) {
|
|
629
|
+
var pool = _step2.value;
|
|
630
|
+
if (pool instanceof Pool) {
|
|
631
|
+
poolIdentifierSet.add(pool.poolId);
|
|
632
|
+
} else if (pool instanceof Pool$1) {
|
|
633
|
+
poolIdentifierSet.add(Pool$1.getAddress(pool.token0, pool.token1, pool.fee));
|
|
634
|
+
} else if (pool instanceof Pair) {
|
|
635
|
+
var pair = pool;
|
|
636
|
+
poolIdentifierSet.add(Pair.getAddress(pair.token0, pair.token1));
|
|
637
|
+
} else {
|
|
638
|
+
throw new Error('Unexpected pool type in route when constructing trade object');
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
!(numPools === poolIdentifierSet.size) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS_DUPLICATED') : invariant(false) : void 0;
|
|
643
|
+
!(tradeType === TradeType.EXACT_INPUT) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TRADE_TYPE') : invariant(false) : void 0;
|
|
644
|
+
this.swaps = routes;
|
|
645
|
+
this.tradeType = tradeType;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
|
|
649
|
+
* this will return an error.
|
|
650
|
+
*
|
|
651
|
+
* When the trade consists of just a single route, this returns the route of the trade,
|
|
652
|
+
* i.e. which pools the trade goes through.
|
|
653
|
+
*/
|
|
654
|
+
/**
|
|
655
|
+
* Constructs a trade by simulating swaps through the given route
|
|
656
|
+
* @template TInput The input token, either Ether or an ERC-20.
|
|
657
|
+
* @template TOutput The output token, either Ether or an ERC-20.
|
|
658
|
+
* @template TTradeType The type of the trade, either exact in or exact out.
|
|
659
|
+
* @param route route to swap through
|
|
660
|
+
* @param amount the amount specified, either input or output, depending on tradeType
|
|
661
|
+
* @param tradeType whether the trade is an exact input or exact output swap
|
|
662
|
+
* @returns The route
|
|
663
|
+
*/
|
|
664
|
+
MixedRouteTrade.fromRoute =
|
|
665
|
+
/*#__PURE__*/
|
|
666
|
+
function () {
|
|
667
|
+
var _fromRoute = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(route, amount, tradeType) {
|
|
668
|
+
var amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput, _outputAmount;
|
|
669
|
+
return _regenerator().w(function (_context) {
|
|
670
|
+
while (1) switch (_context.n) {
|
|
671
|
+
case 0:
|
|
672
|
+
amounts = new Array(route.path.length);
|
|
673
|
+
!(tradeType === TradeType.EXACT_INPUT) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TRADE_TYPE') : invariant(false) : void 0;
|
|
674
|
+
!amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
|
|
675
|
+
amounts[0] = amountWithPathCurrency(amount, route.pools[0]);
|
|
676
|
+
i = 0;
|
|
677
|
+
case 1:
|
|
678
|
+
if (!(i < route.path.length - 1)) {
|
|
679
|
+
_context.n = 4;
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
pool = route.pools[i];
|
|
683
|
+
_context.n = 2;
|
|
684
|
+
return pool.getOutputAmount(amountWithPathCurrency(amounts[i], pool));
|
|
685
|
+
case 2:
|
|
686
|
+
_yield$pool$getOutput = _context.v;
|
|
687
|
+
_outputAmount = _yield$pool$getOutput[0];
|
|
688
|
+
amounts[i + 1] = _outputAmount;
|
|
689
|
+
case 3:
|
|
690
|
+
i++;
|
|
691
|
+
_context.n = 1;
|
|
692
|
+
break;
|
|
693
|
+
case 4:
|
|
694
|
+
inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
|
|
695
|
+
outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
|
|
696
|
+
return _context.a(2, new MixedRouteTrade({
|
|
697
|
+
routes: [{
|
|
698
|
+
inputAmount: inputAmount,
|
|
699
|
+
outputAmount: outputAmount,
|
|
700
|
+
route: route
|
|
701
|
+
}],
|
|
702
|
+
tradeType: tradeType
|
|
703
|
+
}));
|
|
704
|
+
}
|
|
705
|
+
}, _callee);
|
|
706
|
+
}));
|
|
707
|
+
function fromRoute(_x, _x2, _x3) {
|
|
708
|
+
return _fromRoute.apply(this, arguments);
|
|
709
|
+
}
|
|
710
|
+
return fromRoute;
|
|
711
|
+
}()
|
|
712
|
+
/**
|
|
713
|
+
* Constructs a trade from routes by simulating swaps
|
|
714
|
+
*
|
|
715
|
+
* @template TInput The input token, either Ether or an ERC-20.
|
|
716
|
+
* @template TOutput The output token, either Ether or an ERC-20.
|
|
717
|
+
* @template TTradeType The type of the trade, either exact in or exact out.
|
|
718
|
+
* @param routes the routes to swap through and how much of the amount should be routed through each
|
|
719
|
+
* @param tradeType whether the trade is an exact input or exact output swap
|
|
720
|
+
* @returns The trade
|
|
721
|
+
*/
|
|
722
|
+
;
|
|
723
|
+
MixedRouteTrade.fromRoutes =
|
|
724
|
+
/*#__PURE__*/
|
|
725
|
+
function () {
|
|
726
|
+
var _fromRoutes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(routes, tradeType) {
|
|
727
|
+
var populatedRoutes, _iterator3, _step3, _step3$value, route, amount, amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput2, _outputAmount2;
|
|
728
|
+
return _regenerator().w(function (_context2) {
|
|
729
|
+
while (1) switch (_context2.n) {
|
|
730
|
+
case 0:
|
|
731
|
+
populatedRoutes = [];
|
|
732
|
+
!(tradeType === TradeType.EXACT_INPUT) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TRADE_TYPE') : invariant(false) : void 0;
|
|
733
|
+
_iterator3 = _createForOfIteratorHelperLoose(routes);
|
|
734
|
+
case 1:
|
|
735
|
+
if ((_step3 = _iterator3()).done) {
|
|
736
|
+
_context2.n = 7;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
_step3$value = _step3.value, route = _step3$value.route, amount = _step3$value.amount;
|
|
740
|
+
amounts = new Array(route.path.length);
|
|
741
|
+
inputAmount = void 0;
|
|
742
|
+
outputAmount = void 0;
|
|
743
|
+
!amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
|
|
744
|
+
inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
|
|
745
|
+
amounts[0] = CurrencyAmount.fromFractionalAmount(route.pathInput, amount.numerator, amount.denominator);
|
|
746
|
+
i = 0;
|
|
747
|
+
case 2:
|
|
748
|
+
if (!(i < route.path.length - 1)) {
|
|
749
|
+
_context2.n = 5;
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
pool = route.pools[i];
|
|
753
|
+
_context2.n = 3;
|
|
754
|
+
return pool.getOutputAmount(amountWithPathCurrency(amounts[i], pool));
|
|
755
|
+
case 3:
|
|
756
|
+
_yield$pool$getOutput2 = _context2.v;
|
|
757
|
+
_outputAmount2 = _yield$pool$getOutput2[0];
|
|
758
|
+
amounts[i + 1] = _outputAmount2;
|
|
759
|
+
case 4:
|
|
760
|
+
i++;
|
|
761
|
+
_context2.n = 2;
|
|
762
|
+
break;
|
|
763
|
+
case 5:
|
|
764
|
+
outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
|
|
765
|
+
populatedRoutes.push({
|
|
766
|
+
route: route,
|
|
767
|
+
inputAmount: inputAmount,
|
|
768
|
+
outputAmount: outputAmount
|
|
769
|
+
});
|
|
770
|
+
case 6:
|
|
771
|
+
_context2.n = 1;
|
|
772
|
+
break;
|
|
773
|
+
case 7:
|
|
774
|
+
return _context2.a(2, new MixedRouteTrade({
|
|
775
|
+
routes: populatedRoutes,
|
|
776
|
+
tradeType: tradeType
|
|
777
|
+
}));
|
|
778
|
+
}
|
|
779
|
+
}, _callee2);
|
|
780
|
+
}));
|
|
781
|
+
function fromRoutes(_x4, _x5) {
|
|
782
|
+
return _fromRoutes.apply(this, arguments);
|
|
783
|
+
}
|
|
784
|
+
return fromRoutes;
|
|
785
|
+
}()
|
|
786
|
+
/**
|
|
787
|
+
* Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
|
|
788
|
+
* elsewhere and do not have any tick data
|
|
789
|
+
* @template TInput The input token, either Ether or an ERC-20
|
|
790
|
+
* @template TOutput The output token, either Ether or an ERC-20
|
|
791
|
+
* @template TTradeType The type of the trade, either exact in or exact out
|
|
792
|
+
* @param constructorArguments The arguments passed to the trade constructor
|
|
793
|
+
* @returns The unchecked trade
|
|
794
|
+
*/
|
|
795
|
+
;
|
|
796
|
+
MixedRouteTrade.createUncheckedTrade = function createUncheckedTrade(constructorArguments) {
|
|
797
|
+
return new MixedRouteTrade(_extends({}, constructorArguments, {
|
|
798
|
+
routes: [{
|
|
799
|
+
inputAmount: constructorArguments.inputAmount,
|
|
800
|
+
outputAmount: constructorArguments.outputAmount,
|
|
801
|
+
route: constructorArguments.route
|
|
802
|
+
}]
|
|
803
|
+
}));
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
|
|
807
|
+
* elsewhere and do not have any tick data
|
|
808
|
+
* @template TInput The input token, either Ether or an ERC-20
|
|
809
|
+
* @template TOutput The output token, either Ether or an ERC-20
|
|
810
|
+
* @template TTradeType The type of the trade, either exact in or exact out
|
|
811
|
+
* @param constructorArguments The arguments passed to the trade constructor
|
|
812
|
+
* @returns The unchecked trade
|
|
813
|
+
*/;
|
|
814
|
+
MixedRouteTrade.createUncheckedTradeWithMultipleRoutes = function createUncheckedTradeWithMultipleRoutes(constructorArguments) {
|
|
815
|
+
return new MixedRouteTrade(constructorArguments);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Get the minimum amount that must be received from this trade for the given slippage tolerance
|
|
819
|
+
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
|
|
820
|
+
* @returns The amount out
|
|
821
|
+
*/;
|
|
822
|
+
var _proto = MixedRouteTrade.prototype;
|
|
823
|
+
_proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
|
|
824
|
+
if (amountOut === void 0) {
|
|
825
|
+
amountOut = this.outputAmount;
|
|
826
|
+
}
|
|
827
|
+
!!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
|
|
828
|
+
/// does not support exactOutput, as enforced in the constructor
|
|
829
|
+
var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
|
|
830
|
+
return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Get the maximum amount in that can be spent via this trade for the given slippage tolerance
|
|
834
|
+
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
|
|
835
|
+
* @returns The amount in
|
|
836
|
+
*/;
|
|
837
|
+
_proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
|
|
838
|
+
if (amountIn === void 0) {
|
|
839
|
+
amountIn = this.inputAmount;
|
|
840
|
+
}
|
|
841
|
+
!!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
|
|
842
|
+
return amountIn;
|
|
843
|
+
/// does not support exactOutput
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Return the execution price after accounting for slippage tolerance
|
|
847
|
+
* @param slippageTolerance the allowed tolerated slippage
|
|
848
|
+
* @returns The execution price
|
|
849
|
+
*/;
|
|
850
|
+
_proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
|
|
851
|
+
return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
|
|
855
|
+
* amount to an output token, making at most `maxHops` hops.
|
|
856
|
+
* Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
|
|
857
|
+
* the amount in among multiple routes.
|
|
858
|
+
* @param pools the pools to consider in finding the best trade
|
|
859
|
+
* @param nextAmountIn exact amount of input currency to spend
|
|
860
|
+
* @param currencyOut the desired currency out
|
|
861
|
+
* @param maxNumResults maximum number of results to return
|
|
862
|
+
* @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
|
|
863
|
+
* @param currentPools used in recursion; the current list of pools
|
|
864
|
+
* @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
|
|
865
|
+
* @param bestTrades used in recursion; the current list of best trades
|
|
866
|
+
* @returns The exact in trade
|
|
867
|
+
*/;
|
|
868
|
+
MixedRouteTrade.bestTradeExactIn =
|
|
869
|
+
/*#__PURE__*/
|
|
870
|
+
function () {
|
|
871
|
+
var _bestTradeExactIn = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(pools, currencyAmountIn, currencyOut, _temp,
|
|
872
|
+
// used in recursion.
|
|
873
|
+
currentPools, nextAmountIn, bestTrades) {
|
|
874
|
+
var _ref5, _ref5$maxNumResults, maxNumResults, _ref5$maxHops, maxHops, amountIn, i, pool, amountInAdjusted, amountOut, _ref6, poolsExcludingThisPool, _t, _t2, _t3, _t4;
|
|
875
|
+
return _regenerator().w(function (_context3) {
|
|
876
|
+
while (1) switch (_context3.p = _context3.n) {
|
|
877
|
+
case 0:
|
|
878
|
+
_ref5 = _temp === void 0 ? {} : _temp, _ref5$maxNumResults = _ref5.maxNumResults, maxNumResults = _ref5$maxNumResults === void 0 ? 3 : _ref5$maxNumResults, _ref5$maxHops = _ref5.maxHops, maxHops = _ref5$maxHops === void 0 ? 3 : _ref5$maxHops;
|
|
879
|
+
if (currentPools === void 0) {
|
|
880
|
+
currentPools = [];
|
|
881
|
+
}
|
|
882
|
+
if (nextAmountIn === void 0) {
|
|
883
|
+
nextAmountIn = currencyAmountIn;
|
|
884
|
+
}
|
|
885
|
+
if (bestTrades === void 0) {
|
|
886
|
+
bestTrades = [];
|
|
887
|
+
}
|
|
888
|
+
!(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
|
|
889
|
+
!(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
|
|
890
|
+
!(currencyAmountIn === nextAmountIn || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
|
|
891
|
+
amountIn = nextAmountIn;
|
|
892
|
+
i = 0;
|
|
893
|
+
case 1:
|
|
894
|
+
if (!(i < pools.length)) {
|
|
895
|
+
_context3.n = 15;
|
|
896
|
+
break;
|
|
897
|
+
}
|
|
898
|
+
pool = pools[i];
|
|
899
|
+
amountInAdjusted = pool instanceof Pool ? amountIn : amountIn.wrapped; // pool irrelevant
|
|
900
|
+
if (!(!pool.token0.equals(amountInAdjusted.currency) && !pool.token1.equals(amountInAdjusted.currency))) {
|
|
901
|
+
_context3.n = 2;
|
|
902
|
+
break;
|
|
903
|
+
}
|
|
904
|
+
return _context3.a(3, 14);
|
|
905
|
+
case 2:
|
|
906
|
+
if (!(pool instanceof Pair)) {
|
|
907
|
+
_context3.n = 3;
|
|
908
|
+
break;
|
|
909
|
+
}
|
|
910
|
+
if (!(pool.reserve0.equalTo(ZERO) || pool.reserve1.equalTo(ZERO))) {
|
|
911
|
+
_context3.n = 3;
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
return _context3.a(3, 14);
|
|
915
|
+
case 3:
|
|
916
|
+
amountOut = void 0;
|
|
917
|
+
_context3.p = 4;
|
|
918
|
+
if (!(pool instanceof Pool)) {
|
|
919
|
+
_context3.n = 6;
|
|
920
|
+
break;
|
|
921
|
+
}
|
|
922
|
+
_context3.n = 5;
|
|
923
|
+
return pool.getOutputAmount(amountInAdjusted);
|
|
924
|
+
case 5:
|
|
925
|
+
_t = _context3.v;
|
|
926
|
+
_context3.n = 8;
|
|
927
|
+
break;
|
|
928
|
+
case 6:
|
|
929
|
+
_context3.n = 7;
|
|
930
|
+
return pool.getOutputAmount(amountInAdjusted.wrapped);
|
|
931
|
+
case 7:
|
|
932
|
+
_t = _context3.v;
|
|
933
|
+
case 8:
|
|
934
|
+
_ref6 = _t;
|
|
935
|
+
amountOut = _ref6[0];
|
|
936
|
+
_context3.n = 11;
|
|
937
|
+
break;
|
|
938
|
+
case 9:
|
|
939
|
+
_context3.p = 9;
|
|
940
|
+
_t2 = _context3.v;
|
|
941
|
+
if (!_t2.isInsufficientInputAmountError) {
|
|
942
|
+
_context3.n = 10;
|
|
943
|
+
break;
|
|
944
|
+
}
|
|
945
|
+
return _context3.a(3, 14);
|
|
946
|
+
case 10:
|
|
947
|
+
throw _t2;
|
|
948
|
+
case 11:
|
|
949
|
+
if (!amountOut.currency.wrapped.equals(currencyOut.wrapped)) {
|
|
950
|
+
_context3.n = 13;
|
|
951
|
+
break;
|
|
952
|
+
}
|
|
953
|
+
_t3 = sortedInsert;
|
|
954
|
+
_t4 = bestTrades;
|
|
955
|
+
_context3.n = 12;
|
|
956
|
+
return MixedRouteTrade.fromRoute(new MixedRouteSDK([].concat(currentPools, [pool]), currencyAmountIn.currency, currencyOut), currencyAmountIn, TradeType.EXACT_INPUT);
|
|
957
|
+
case 12:
|
|
958
|
+
_t3(_t4, _context3.v, maxNumResults, tradeComparator);
|
|
959
|
+
_context3.n = 14;
|
|
960
|
+
break;
|
|
961
|
+
case 13:
|
|
962
|
+
if (!(maxHops > 1 && pools.length > 1)) {
|
|
963
|
+
_context3.n = 14;
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
|
|
967
|
+
_context3.n = 14;
|
|
968
|
+
return MixedRouteTrade.bestTradeExactIn(poolsExcludingThisPool, currencyAmountIn, currencyOut, {
|
|
969
|
+
maxNumResults: maxNumResults,
|
|
970
|
+
maxHops: maxHops - 1
|
|
971
|
+
}, [].concat(currentPools, [pool]), amountOut, bestTrades);
|
|
972
|
+
case 14:
|
|
973
|
+
i++;
|
|
974
|
+
_context3.n = 1;
|
|
975
|
+
break;
|
|
976
|
+
case 15:
|
|
977
|
+
return _context3.a(2, bestTrades);
|
|
978
|
+
}
|
|
979
|
+
}, _callee3, null, [[4, 9]]);
|
|
980
|
+
}));
|
|
981
|
+
function bestTradeExactIn(_x6, _x7, _x8, _x9, _x0, _x1, _x10) {
|
|
982
|
+
return _bestTradeExactIn.apply(this, arguments);
|
|
983
|
+
}
|
|
984
|
+
return bestTradeExactIn;
|
|
985
|
+
}();
|
|
986
|
+
return _createClass(MixedRouteTrade, [{
|
|
987
|
+
key: "route",
|
|
988
|
+
get: function get() {
|
|
989
|
+
!(this.swaps.length === 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIPLE_ROUTES') : invariant(false) : void 0;
|
|
990
|
+
return this.swaps[0].route;
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* The input amount for the trade assuming no slippage.
|
|
994
|
+
*/
|
|
995
|
+
}, {
|
|
996
|
+
key: "inputAmount",
|
|
997
|
+
get: function get() {
|
|
998
|
+
if (this._inputAmount) {
|
|
999
|
+
return this._inputAmount;
|
|
1000
|
+
}
|
|
1001
|
+
var inputCurrency = this.swaps[0].inputAmount.currency;
|
|
1002
|
+
var totalInputFromRoutes = this.swaps.map(function (_ref7) {
|
|
1003
|
+
var inputAmount = _ref7.inputAmount;
|
|
1004
|
+
return inputAmount;
|
|
1005
|
+
}).reduce(function (total, cur) {
|
|
1006
|
+
return total.add(cur);
|
|
1007
|
+
}, CurrencyAmount.fromRawAmount(inputCurrency, 0));
|
|
1008
|
+
this._inputAmount = totalInputFromRoutes;
|
|
1009
|
+
return this._inputAmount;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* The output amount for the trade assuming no slippage.
|
|
1013
|
+
*/
|
|
1014
|
+
}, {
|
|
1015
|
+
key: "outputAmount",
|
|
1016
|
+
get: function get() {
|
|
1017
|
+
if (this._outputAmount) {
|
|
1018
|
+
return this._outputAmount;
|
|
1019
|
+
}
|
|
1020
|
+
var outputCurrency = this.swaps[0].outputAmount.currency;
|
|
1021
|
+
var totalOutputFromRoutes = this.swaps.map(function (_ref8) {
|
|
1022
|
+
var outputAmount = _ref8.outputAmount;
|
|
1023
|
+
return outputAmount;
|
|
1024
|
+
}).reduce(function (total, cur) {
|
|
1025
|
+
return total.add(cur);
|
|
1026
|
+
}, CurrencyAmount.fromRawAmount(outputCurrency, 0));
|
|
1027
|
+
this._outputAmount = totalOutputFromRoutes;
|
|
1028
|
+
return this._outputAmount;
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* The price expressed in terms of output amount/input amount.
|
|
1032
|
+
*/
|
|
1033
|
+
}, {
|
|
1034
|
+
key: "executionPrice",
|
|
1035
|
+
get: function get() {
|
|
1036
|
+
var _this$_executionPrice;
|
|
1037
|
+
return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Returns the percent difference between the route's mid price and the price impact
|
|
1041
|
+
*/
|
|
1042
|
+
}, {
|
|
1043
|
+
key: "priceImpact",
|
|
1044
|
+
get: function get() {
|
|
1045
|
+
if (this._priceImpact) {
|
|
1046
|
+
return this._priceImpact;
|
|
1047
|
+
}
|
|
1048
|
+
var spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
|
|
1049
|
+
for (var _iterator4 = _createForOfIteratorHelperLoose(this.swaps), _step4; !(_step4 = _iterator4()).done;) {
|
|
1050
|
+
var _step4$value = _step4.value,
|
|
1051
|
+
route = _step4$value.route,
|
|
1052
|
+
inputAmount = _step4$value.inputAmount;
|
|
1053
|
+
var midPrice = route.midPrice;
|
|
1054
|
+
spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
|
|
1055
|
+
}
|
|
1056
|
+
var priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
|
|
1057
|
+
this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator);
|
|
1058
|
+
return this._priceImpact;
|
|
1059
|
+
}
|
|
1060
|
+
}]);
|
|
1061
|
+
}();
|
|
1062
|
+
|
|
1063
|
+
var Protocol;
|
|
1064
|
+
(function (Protocol) {
|
|
1065
|
+
Protocol["V2"] = "V2";
|
|
1066
|
+
Protocol["V3"] = "V3";
|
|
1067
|
+
Protocol["V4"] = "V4";
|
|
1068
|
+
Protocol["MIXED"] = "MIXED";
|
|
1069
|
+
})(Protocol || (Protocol = {}));
|
|
1070
|
+
|
|
1071
|
+
// Helper function to get the pathInput and pathOutput for a V2 / V3 route
|
|
1072
|
+
// currency could be native so we check against the wrapped version as they don't support native ETH in path
|
|
1073
|
+
function getPathToken(currency, pool) {
|
|
1074
|
+
if (pool.token0.wrapped.equals(currency.wrapped)) {
|
|
1075
|
+
return pool.token0;
|
|
1076
|
+
} else if (pool.token1.wrapped.equals(currency.wrapped)) {
|
|
1077
|
+
return pool.token1;
|
|
1078
|
+
} else {
|
|
1079
|
+
throw new Error("Expected token " + currency.symbol + " to be either " + pool.token0.symbol + " or " + pool.token1.symbol);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// V2 route wrapper
|
|
1083
|
+
var RouteV2 = /*#__PURE__*/function (_V2RouteSDK) {
|
|
1084
|
+
function RouteV2(v2Route) {
|
|
1085
|
+
var _this;
|
|
1086
|
+
_this = _V2RouteSDK.call(this, v2Route.pairs, v2Route.input, v2Route.output) || this;
|
|
1087
|
+
_this.protocol = Protocol.V2;
|
|
1088
|
+
_this.pools = _this.pairs;
|
|
1089
|
+
_this.pathInput = getPathToken(v2Route.input, _this.pairs[0]);
|
|
1090
|
+
_this.pathOutput = getPathToken(v2Route.output, _this.pairs[_this.pairs.length - 1]);
|
|
1091
|
+
return _this;
|
|
1092
|
+
}
|
|
1093
|
+
_inheritsLoose(RouteV2, _V2RouteSDK);
|
|
1094
|
+
return RouteV2;
|
|
1095
|
+
}(Route);
|
|
1096
|
+
// V3 route wrapper
|
|
1097
|
+
var RouteV3 = /*#__PURE__*/function (_V3RouteSDK) {
|
|
1098
|
+
function RouteV3(v3Route) {
|
|
1099
|
+
var _this2;
|
|
1100
|
+
_this2 = _V3RouteSDK.call(this, v3Route.pools, v3Route.input, v3Route.output) || this;
|
|
1101
|
+
_this2.protocol = Protocol.V3;
|
|
1102
|
+
_this2.path = v3Route.tokenPath;
|
|
1103
|
+
_this2.pathInput = getPathToken(v3Route.input, _this2.pools[0]);
|
|
1104
|
+
_this2.pathOutput = getPathToken(v3Route.output, _this2.pools[_this2.pools.length - 1]);
|
|
1105
|
+
return _this2;
|
|
1106
|
+
}
|
|
1107
|
+
_inheritsLoose(RouteV3, _V3RouteSDK);
|
|
1108
|
+
return RouteV3;
|
|
1109
|
+
}(Route$1);
|
|
1110
|
+
// V4 route wrapper
|
|
1111
|
+
var RouteV4 = /*#__PURE__*/function (_V4RouteSDK) {
|
|
1112
|
+
function RouteV4(v4Route) {
|
|
1113
|
+
var _this3;
|
|
1114
|
+
_this3 = _V4RouteSDK.call(this, v4Route.pools, v4Route.input, v4Route.output) || this;
|
|
1115
|
+
_this3.protocol = Protocol.V4;
|
|
1116
|
+
_this3.path = v4Route.currencyPath;
|
|
1117
|
+
return _this3;
|
|
1118
|
+
}
|
|
1119
|
+
_inheritsLoose(RouteV4, _V4RouteSDK);
|
|
1120
|
+
return RouteV4;
|
|
1121
|
+
}(Route$2);
|
|
1122
|
+
// Mixed route wrapper
|
|
1123
|
+
var MixedRoute = /*#__PURE__*/function (_MixedRouteSDK) {
|
|
1124
|
+
function MixedRoute(mixedRoute) {
|
|
1125
|
+
var _this4;
|
|
1126
|
+
_this4 = _MixedRouteSDK.call(this, mixedRoute.pools, mixedRoute.input, mixedRoute.output) || this;
|
|
1127
|
+
_this4.protocol = Protocol.MIXED;
|
|
1128
|
+
return _this4;
|
|
1129
|
+
}
|
|
1130
|
+
_inheritsLoose(MixedRoute, _MixedRouteSDK);
|
|
1131
|
+
return MixedRoute;
|
|
1132
|
+
}(MixedRouteSDK);
|
|
1133
|
+
|
|
1134
|
+
var Trade = /*#__PURE__*/function () {
|
|
1135
|
+
// construct a trade across v2 and v3 routes from pre-computed amounts
|
|
1136
|
+
function Trade(_ref) {
|
|
1137
|
+
var _ref$v2Routes = _ref.v2Routes,
|
|
1138
|
+
v2Routes = _ref$v2Routes === void 0 ? [] : _ref$v2Routes,
|
|
1139
|
+
_ref$v3Routes = _ref.v3Routes,
|
|
1140
|
+
v3Routes = _ref$v3Routes === void 0 ? [] : _ref$v3Routes,
|
|
1141
|
+
_ref$v4Routes = _ref.v4Routes,
|
|
1142
|
+
v4Routes = _ref$v4Routes === void 0 ? [] : _ref$v4Routes,
|
|
1143
|
+
_ref$mixedRoutes = _ref.mixedRoutes,
|
|
1144
|
+
mixedRoutes = _ref$mixedRoutes === void 0 ? [] : _ref$mixedRoutes,
|
|
1145
|
+
tradeType = _ref.tradeType;
|
|
1146
|
+
this.swaps = [];
|
|
1147
|
+
this.routes = [];
|
|
1148
|
+
// wrap v2 routes
|
|
1149
|
+
for (var _iterator = _createForOfIteratorHelperLoose(v2Routes), _step; !(_step = _iterator()).done;) {
|
|
1150
|
+
var _step$value = _step.value,
|
|
1151
|
+
routev2 = _step$value.routev2,
|
|
1152
|
+
inputAmount = _step$value.inputAmount,
|
|
1153
|
+
outputAmount = _step$value.outputAmount;
|
|
1154
|
+
var route = new RouteV2(routev2);
|
|
1155
|
+
this.routes.push(route);
|
|
1156
|
+
this.swaps.push({
|
|
1157
|
+
route: route,
|
|
1158
|
+
inputAmount: inputAmount,
|
|
1159
|
+
outputAmount: outputAmount
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
// wrap v3 routes
|
|
1163
|
+
for (var _iterator2 = _createForOfIteratorHelperLoose(v3Routes), _step2; !(_step2 = _iterator2()).done;) {
|
|
1164
|
+
var _step2$value = _step2.value,
|
|
1165
|
+
routev3 = _step2$value.routev3,
|
|
1166
|
+
_inputAmount = _step2$value.inputAmount,
|
|
1167
|
+
_outputAmount = _step2$value.outputAmount;
|
|
1168
|
+
var _route = new RouteV3(routev3);
|
|
1169
|
+
this.routes.push(_route);
|
|
1170
|
+
this.swaps.push({
|
|
1171
|
+
route: _route,
|
|
1172
|
+
inputAmount: _inputAmount,
|
|
1173
|
+
outputAmount: _outputAmount
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
// wrap v4 routes
|
|
1177
|
+
for (var _iterator3 = _createForOfIteratorHelperLoose(v4Routes), _step3; !(_step3 = _iterator3()).done;) {
|
|
1178
|
+
var _step3$value = _step3.value,
|
|
1179
|
+
routev4 = _step3$value.routev4,
|
|
1180
|
+
_inputAmount2 = _step3$value.inputAmount,
|
|
1181
|
+
_outputAmount2 = _step3$value.outputAmount;
|
|
1182
|
+
var _route2 = new RouteV4(routev4);
|
|
1183
|
+
this.routes.push(_route2);
|
|
1184
|
+
this.swaps.push({
|
|
1185
|
+
route: _route2,
|
|
1186
|
+
inputAmount: _inputAmount2,
|
|
1187
|
+
outputAmount: _outputAmount2
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
for (var _iterator4 = _createForOfIteratorHelperLoose(mixedRoutes), _step4; !(_step4 = _iterator4()).done;) {
|
|
1191
|
+
var _step4$value = _step4.value,
|
|
1192
|
+
mixedRoute = _step4$value.mixedRoute,
|
|
1193
|
+
_inputAmount3 = _step4$value.inputAmount,
|
|
1194
|
+
_outputAmount3 = _step4$value.outputAmount;
|
|
1195
|
+
var _route3 = new MixedRoute(mixedRoute);
|
|
1196
|
+
this.routes.push(_route3);
|
|
1197
|
+
this.swaps.push({
|
|
1198
|
+
route: _route3,
|
|
1199
|
+
inputAmount: _inputAmount3,
|
|
1200
|
+
outputAmount: _outputAmount3
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
if (this.swaps.length === 0) {
|
|
1204
|
+
throw new Error('No routes provided when calling Trade constructor');
|
|
1205
|
+
}
|
|
1206
|
+
this.tradeType = tradeType;
|
|
1207
|
+
// each route must have the same input and output currency
|
|
1208
|
+
var inputCurrency = this.swaps[0].inputAmount.currency;
|
|
1209
|
+
var outputCurrency = this.swaps[0].outputAmount.currency;
|
|
1210
|
+
!this.swaps.every(function (_ref2) {
|
|
1211
|
+
var route = _ref2.route;
|
|
1212
|
+
return inputCurrency.wrapped.equals(route.input.wrapped);
|
|
1213
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY_MATCH') : invariant(false) : void 0;
|
|
1214
|
+
!this.swaps.every(function (_ref3) {
|
|
1215
|
+
var route = _ref3.route;
|
|
1216
|
+
return outputCurrency.wrapped.equals(route.output.wrapped);
|
|
1217
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : invariant(false) : void 0;
|
|
1218
|
+
// pools must be unique inter protocols
|
|
1219
|
+
var numPools = this.swaps.map(function (_ref4) {
|
|
1220
|
+
var route = _ref4.route;
|
|
1221
|
+
return route.pools.length;
|
|
1222
|
+
}).reduce(function (total, cur) {
|
|
1223
|
+
return total + cur;
|
|
1224
|
+
}, 0);
|
|
1225
|
+
var poolIdentifierSet = new Set();
|
|
1226
|
+
for (var _iterator5 = _createForOfIteratorHelperLoose(this.swaps), _step5; !(_step5 = _iterator5()).done;) {
|
|
1227
|
+
var _route4 = _step5.value.route;
|
|
1228
|
+
for (var _iterator6 = _createForOfIteratorHelperLoose(_route4.pools), _step6; !(_step6 = _iterator6()).done;) {
|
|
1229
|
+
var pool = _step6.value;
|
|
1230
|
+
if (pool instanceof Pool) {
|
|
1231
|
+
poolIdentifierSet.add(pool.poolId);
|
|
1232
|
+
} else if (pool instanceof Pool$1) {
|
|
1233
|
+
poolIdentifierSet.add(Pool$1.getAddress(pool.token0, pool.token1, pool.fee));
|
|
1234
|
+
} else if (pool instanceof Pair) {
|
|
1235
|
+
var pair = pool;
|
|
1236
|
+
poolIdentifierSet.add(Pair.getAddress(pair.token0, pair.token1));
|
|
1237
|
+
} else {
|
|
1238
|
+
throw new Error('Unexpected pool type in route when constructing trade object');
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
!(numPools === poolIdentifierSet.size) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS_DUPLICATED') : invariant(false) : void 0;
|
|
1243
|
+
}
|
|
1244
|
+
var _proto = Trade.prototype;
|
|
1245
|
+
_proto.isWrappedNative = function isWrappedNative(currency) {
|
|
1246
|
+
var chainId = currency.chainId;
|
|
1247
|
+
return currency.equals(Ether.onChain(chainId).wrapped);
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Returns the percent difference between the route's mid price and the expected execution price
|
|
1251
|
+
* In order to exclude token taxes from the price impact calculation, the spot price is calculated
|
|
1252
|
+
* using a ratio of values that go into the pools, which are the post-tax input amount and pre-tax output amount.
|
|
1253
|
+
*/;
|
|
1254
|
+
/**
|
|
1255
|
+
* Get the minimum amount that must be received from this trade for the given slippage tolerance
|
|
1256
|
+
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
|
|
1257
|
+
* @returns The amount out
|
|
1258
|
+
*/
|
|
1259
|
+
_proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
|
|
1260
|
+
if (amountOut === void 0) {
|
|
1261
|
+
amountOut = this.outputAmount;
|
|
1262
|
+
}
|
|
1263
|
+
!!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
|
|
1264
|
+
if (this.tradeType === TradeType.EXACT_OUTPUT) {
|
|
1265
|
+
return amountOut;
|
|
1266
|
+
} else {
|
|
1267
|
+
var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
|
|
1268
|
+
return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Get the maximum amount in that can be spent via this trade for the given slippage tolerance
|
|
1273
|
+
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
|
|
1274
|
+
* @returns The amount in
|
|
1275
|
+
*/;
|
|
1276
|
+
_proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
|
|
1277
|
+
if (amountIn === void 0) {
|
|
1278
|
+
amountIn = this.inputAmount;
|
|
1279
|
+
}
|
|
1280
|
+
!!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
|
|
1281
|
+
if (this.tradeType === TradeType.EXACT_INPUT) {
|
|
1282
|
+
return amountIn;
|
|
1283
|
+
} else {
|
|
1284
|
+
var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
|
|
1285
|
+
return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Return the execution price after accounting for slippage tolerance
|
|
1290
|
+
* @param slippageTolerance the allowed tolerated slippage
|
|
1291
|
+
* @returns The execution price
|
|
1292
|
+
*/;
|
|
1293
|
+
_proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
|
|
1294
|
+
return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
|
|
1295
|
+
};
|
|
1296
|
+
Trade.fromRoutes = /*#__PURE__*/function () {
|
|
1297
|
+
var _fromRoutes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(v2Routes, v3Routes, tradeType, mixedRoutes, v4Routes) {
|
|
1298
|
+
var populatedV2Routes, populatedV3Routes, populatedV4Routes, populatedMixedRoutes, _iterator7, _step7, _step7$value, routev2, _amount2, v2Trade, _inputAmount5, _outputAmount5, _iterator8, _step8, _step8$value, routev3, _amount3, v3Trade, _inputAmount6, _outputAmount6, _iterator9, _step9, _step9$value, routev4, amount, v4Trade, inputAmount, outputAmount, _iterator0, _step0, _step0$value, mixedRoute, _amount, mixedRouteTrade, _inputAmount4, _outputAmount4;
|
|
1299
|
+
return _regenerator().w(function (_context) {
|
|
1300
|
+
while (1) switch (_context.n) {
|
|
1301
|
+
case 0:
|
|
1302
|
+
populatedV2Routes = [];
|
|
1303
|
+
populatedV3Routes = [];
|
|
1304
|
+
populatedV4Routes = [];
|
|
1305
|
+
populatedMixedRoutes = [];
|
|
1306
|
+
for (_iterator7 = _createForOfIteratorHelperLoose(v2Routes); !(_step7 = _iterator7()).done;) {
|
|
1307
|
+
_step7$value = _step7.value, routev2 = _step7$value.routev2, _amount2 = _step7$value.amount;
|
|
1308
|
+
v2Trade = new Trade$3(routev2, _amount2, tradeType);
|
|
1309
|
+
_inputAmount5 = v2Trade.inputAmount, _outputAmount5 = v2Trade.outputAmount;
|
|
1310
|
+
populatedV2Routes.push({
|
|
1311
|
+
routev2: routev2,
|
|
1312
|
+
inputAmount: _inputAmount5,
|
|
1313
|
+
outputAmount: _outputAmount5
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
_iterator8 = _createForOfIteratorHelperLoose(v3Routes);
|
|
1317
|
+
case 1:
|
|
1318
|
+
if ((_step8 = _iterator8()).done) {
|
|
1319
|
+
_context.n = 4;
|
|
1320
|
+
break;
|
|
1321
|
+
}
|
|
1322
|
+
_step8$value = _step8.value, routev3 = _step8$value.routev3, _amount3 = _step8$value.amount;
|
|
1323
|
+
_context.n = 2;
|
|
1324
|
+
return Trade$2.fromRoute(routev3, _amount3, tradeType);
|
|
1325
|
+
case 2:
|
|
1326
|
+
v3Trade = _context.v;
|
|
1327
|
+
_inputAmount6 = v3Trade.inputAmount, _outputAmount6 = v3Trade.outputAmount;
|
|
1328
|
+
populatedV3Routes.push({
|
|
1329
|
+
routev3: routev3,
|
|
1330
|
+
inputAmount: _inputAmount6,
|
|
1331
|
+
outputAmount: _outputAmount6
|
|
1332
|
+
});
|
|
1333
|
+
case 3:
|
|
1334
|
+
_context.n = 1;
|
|
1335
|
+
break;
|
|
1336
|
+
case 4:
|
|
1337
|
+
if (!v4Routes) {
|
|
1338
|
+
_context.n = 8;
|
|
1339
|
+
break;
|
|
1340
|
+
}
|
|
1341
|
+
_iterator9 = _createForOfIteratorHelperLoose(v4Routes);
|
|
1342
|
+
case 5:
|
|
1343
|
+
if ((_step9 = _iterator9()).done) {
|
|
1344
|
+
_context.n = 8;
|
|
1345
|
+
break;
|
|
1346
|
+
}
|
|
1347
|
+
_step9$value = _step9.value, routev4 = _step9$value.routev4, amount = _step9$value.amount;
|
|
1348
|
+
_context.n = 6;
|
|
1349
|
+
return Trade$1.fromRoute(routev4, amount, tradeType);
|
|
1350
|
+
case 6:
|
|
1351
|
+
v4Trade = _context.v;
|
|
1352
|
+
inputAmount = v4Trade.inputAmount, outputAmount = v4Trade.outputAmount;
|
|
1353
|
+
populatedV4Routes.push({
|
|
1354
|
+
routev4: routev4,
|
|
1355
|
+
inputAmount: inputAmount,
|
|
1356
|
+
outputAmount: outputAmount
|
|
1357
|
+
});
|
|
1358
|
+
case 7:
|
|
1359
|
+
_context.n = 5;
|
|
1360
|
+
break;
|
|
1361
|
+
case 8:
|
|
1362
|
+
if (!mixedRoutes) {
|
|
1363
|
+
_context.n = 12;
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
_iterator0 = _createForOfIteratorHelperLoose(mixedRoutes);
|
|
1367
|
+
case 9:
|
|
1368
|
+
if ((_step0 = _iterator0()).done) {
|
|
1369
|
+
_context.n = 12;
|
|
1370
|
+
break;
|
|
1371
|
+
}
|
|
1372
|
+
_step0$value = _step0.value, mixedRoute = _step0$value.mixedRoute, _amount = _step0$value.amount;
|
|
1373
|
+
_context.n = 10;
|
|
1374
|
+
return MixedRouteTrade.fromRoute(mixedRoute, _amount, tradeType);
|
|
1375
|
+
case 10:
|
|
1376
|
+
mixedRouteTrade = _context.v;
|
|
1377
|
+
_inputAmount4 = mixedRouteTrade.inputAmount, _outputAmount4 = mixedRouteTrade.outputAmount;
|
|
1378
|
+
populatedMixedRoutes.push({
|
|
1379
|
+
mixedRoute: mixedRoute,
|
|
1380
|
+
inputAmount: _inputAmount4,
|
|
1381
|
+
outputAmount: _outputAmount4
|
|
1382
|
+
});
|
|
1383
|
+
case 11:
|
|
1384
|
+
_context.n = 9;
|
|
1385
|
+
break;
|
|
1386
|
+
case 12:
|
|
1387
|
+
return _context.a(2, new Trade({
|
|
1388
|
+
v2Routes: populatedV2Routes,
|
|
1389
|
+
v3Routes: populatedV3Routes,
|
|
1390
|
+
v4Routes: populatedV4Routes,
|
|
1391
|
+
mixedRoutes: populatedMixedRoutes,
|
|
1392
|
+
tradeType: tradeType
|
|
1393
|
+
}));
|
|
1394
|
+
}
|
|
1395
|
+
}, _callee);
|
|
1396
|
+
}));
|
|
1397
|
+
function fromRoutes(_x, _x2, _x3, _x4, _x5) {
|
|
1398
|
+
return _fromRoutes.apply(this, arguments);
|
|
1399
|
+
}
|
|
1400
|
+
return fromRoutes;
|
|
1401
|
+
}();
|
|
1402
|
+
Trade.fromRoute = /*#__PURE__*/function () {
|
|
1403
|
+
var _fromRoute = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(route, amount, tradeType) {
|
|
1404
|
+
var v2Routes, v3Routes, v4Routes, mixedRoutes, v2Trade, inputAmount, outputAmount, v3Trade, _inputAmount7, _outputAmount7, v4Trade, _inputAmount8, _outputAmount8, mixedRouteTrade, _inputAmount9, _outputAmount9;
|
|
1405
|
+
return _regenerator().w(function (_context2) {
|
|
1406
|
+
while (1) switch (_context2.n) {
|
|
1407
|
+
case 0:
|
|
1408
|
+
v2Routes = [];
|
|
1409
|
+
v3Routes = [];
|
|
1410
|
+
v4Routes = [];
|
|
1411
|
+
mixedRoutes = [];
|
|
1412
|
+
if (!(route instanceof Route)) {
|
|
1413
|
+
_context2.n = 1;
|
|
1414
|
+
break;
|
|
1415
|
+
}
|
|
1416
|
+
v2Trade = new Trade$3(route, amount, tradeType);
|
|
1417
|
+
inputAmount = v2Trade.inputAmount, outputAmount = v2Trade.outputAmount;
|
|
1418
|
+
v2Routes = [{
|
|
1419
|
+
routev2: route,
|
|
1420
|
+
inputAmount: inputAmount,
|
|
1421
|
+
outputAmount: outputAmount
|
|
1422
|
+
}];
|
|
1423
|
+
_context2.n = 8;
|
|
1424
|
+
break;
|
|
1425
|
+
case 1:
|
|
1426
|
+
if (!(route instanceof Route$1)) {
|
|
1427
|
+
_context2.n = 3;
|
|
1428
|
+
break;
|
|
1429
|
+
}
|
|
1430
|
+
_context2.n = 2;
|
|
1431
|
+
return Trade$2.fromRoute(route, amount, tradeType);
|
|
1432
|
+
case 2:
|
|
1433
|
+
v3Trade = _context2.v;
|
|
1434
|
+
_inputAmount7 = v3Trade.inputAmount, _outputAmount7 = v3Trade.outputAmount;
|
|
1435
|
+
v3Routes = [{
|
|
1436
|
+
routev3: route,
|
|
1437
|
+
inputAmount: _inputAmount7,
|
|
1438
|
+
outputAmount: _outputAmount7
|
|
1439
|
+
}];
|
|
1440
|
+
_context2.n = 8;
|
|
1441
|
+
break;
|
|
1442
|
+
case 3:
|
|
1443
|
+
if (!(route instanceof Route$2)) {
|
|
1444
|
+
_context2.n = 5;
|
|
1445
|
+
break;
|
|
1446
|
+
}
|
|
1447
|
+
_context2.n = 4;
|
|
1448
|
+
return Trade$1.fromRoute(route, amount, tradeType);
|
|
1449
|
+
case 4:
|
|
1450
|
+
v4Trade = _context2.v;
|
|
1451
|
+
_inputAmount8 = v4Trade.inputAmount, _outputAmount8 = v4Trade.outputAmount;
|
|
1452
|
+
v4Routes = [{
|
|
1453
|
+
routev4: route,
|
|
1454
|
+
inputAmount: _inputAmount8,
|
|
1455
|
+
outputAmount: _outputAmount8
|
|
1456
|
+
}];
|
|
1457
|
+
_context2.n = 8;
|
|
1458
|
+
break;
|
|
1459
|
+
case 5:
|
|
1460
|
+
if (!(route instanceof MixedRouteSDK)) {
|
|
1461
|
+
_context2.n = 7;
|
|
1462
|
+
break;
|
|
1463
|
+
}
|
|
1464
|
+
_context2.n = 6;
|
|
1465
|
+
return MixedRouteTrade.fromRoute(route, amount, tradeType);
|
|
1466
|
+
case 6:
|
|
1467
|
+
mixedRouteTrade = _context2.v;
|
|
1468
|
+
_inputAmount9 = mixedRouteTrade.inputAmount, _outputAmount9 = mixedRouteTrade.outputAmount;
|
|
1469
|
+
mixedRoutes = [{
|
|
1470
|
+
mixedRoute: route,
|
|
1471
|
+
inputAmount: _inputAmount9,
|
|
1472
|
+
outputAmount: _outputAmount9
|
|
1473
|
+
}];
|
|
1474
|
+
_context2.n = 8;
|
|
1475
|
+
break;
|
|
1476
|
+
case 7:
|
|
1477
|
+
throw new Error('Invalid route type');
|
|
1478
|
+
case 8:
|
|
1479
|
+
return _context2.a(2, new Trade({
|
|
1480
|
+
v2Routes: v2Routes,
|
|
1481
|
+
v3Routes: v3Routes,
|
|
1482
|
+
v4Routes: v4Routes,
|
|
1483
|
+
mixedRoutes: mixedRoutes,
|
|
1484
|
+
tradeType: tradeType
|
|
1485
|
+
}));
|
|
1486
|
+
}
|
|
1487
|
+
}, _callee2);
|
|
1488
|
+
}));
|
|
1489
|
+
function fromRoute(_x6, _x7, _x8) {
|
|
1490
|
+
return _fromRoute.apply(this, arguments);
|
|
1491
|
+
}
|
|
1492
|
+
return fromRoute;
|
|
1493
|
+
}();
|
|
1494
|
+
return _createClass(Trade, [{
|
|
1495
|
+
key: "inputAmount",
|
|
1496
|
+
get: function get() {
|
|
1497
|
+
if (this._inputAmount) {
|
|
1498
|
+
return this._inputAmount;
|
|
1499
|
+
}
|
|
1500
|
+
var inputAmountCurrency = this.swaps[0].inputAmount.currency;
|
|
1501
|
+
var totalInputFromRoutes = this.swaps.map(function (_ref5) {
|
|
1502
|
+
var routeInputAmount = _ref5.inputAmount;
|
|
1503
|
+
return routeInputAmount;
|
|
1504
|
+
}).reduce(function (total, cur) {
|
|
1505
|
+
return total.add(cur);
|
|
1506
|
+
}, CurrencyAmount.fromRawAmount(inputAmountCurrency, 0));
|
|
1507
|
+
this._inputAmount = totalInputFromRoutes;
|
|
1508
|
+
return this._inputAmount;
|
|
1509
|
+
}
|
|
1510
|
+
}, {
|
|
1511
|
+
key: "outputAmount",
|
|
1512
|
+
get: function get() {
|
|
1513
|
+
if (this._outputAmount) {
|
|
1514
|
+
return this._outputAmount;
|
|
1515
|
+
}
|
|
1516
|
+
var outputCurrency = this.swaps[0].outputAmount.currency;
|
|
1517
|
+
var totalOutputFromRoutes = this.swaps.map(function (_ref6) {
|
|
1518
|
+
var routeOutputAmount = _ref6.outputAmount;
|
|
1519
|
+
return routeOutputAmount;
|
|
1520
|
+
}).reduce(function (total, cur) {
|
|
1521
|
+
return total.add(cur);
|
|
1522
|
+
}, CurrencyAmount.fromRawAmount(outputCurrency, 0));
|
|
1523
|
+
this._outputAmount = totalOutputFromRoutes;
|
|
1524
|
+
return this._outputAmount;
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Returns the sum of all swaps within the trade
|
|
1528
|
+
* @returns
|
|
1529
|
+
* inputAmount: total input amount
|
|
1530
|
+
* inputAmountNative: total amount of native currency required for ETH input paths
|
|
1531
|
+
* - 0 if inputAmount is native but no native input paths
|
|
1532
|
+
* - undefined if inputAmount is not native
|
|
1533
|
+
* outputAmount: total output amount
|
|
1534
|
+
* outputAmountNative: total amount of native currency returned from ETH output paths
|
|
1535
|
+
* - 0 if outputAmount is native but no native output paths
|
|
1536
|
+
* - undefined if outputAmount is not native
|
|
1537
|
+
*/
|
|
1538
|
+
}, {
|
|
1539
|
+
key: "amounts",
|
|
1540
|
+
get: function get() {
|
|
1541
|
+
var _this$swaps$find, _this$swaps$find2;
|
|
1542
|
+
// Find native currencies for reduce below
|
|
1543
|
+
var inputNativeCurrency = (_this$swaps$find = this.swaps.find(function (_ref7) {
|
|
1544
|
+
var inputAmount = _ref7.inputAmount;
|
|
1545
|
+
return inputAmount.currency.isNative;
|
|
1546
|
+
})) == null ? void 0 : _this$swaps$find.inputAmount.currency;
|
|
1547
|
+
var outputNativeCurrency = (_this$swaps$find2 = this.swaps.find(function (_ref8) {
|
|
1548
|
+
var outputAmount = _ref8.outputAmount;
|
|
1549
|
+
return outputAmount.currency.isNative;
|
|
1550
|
+
})) == null ? void 0 : _this$swaps$find2.outputAmount.currency;
|
|
1551
|
+
return {
|
|
1552
|
+
inputAmount: this.inputAmount,
|
|
1553
|
+
inputAmountNative: inputNativeCurrency ? this.swaps.reduce(function (total, swap) {
|
|
1554
|
+
return swap.route.pathInput.isNative ? total.add(swap.inputAmount) : total;
|
|
1555
|
+
}, CurrencyAmount.fromRawAmount(inputNativeCurrency, 0)) : undefined,
|
|
1556
|
+
outputAmount: this.outputAmount,
|
|
1557
|
+
outputAmountNative: outputNativeCurrency ? this.swaps.reduce(function (total, swap) {
|
|
1558
|
+
return swap.route.pathOutput.isNative ? total.add(swap.outputAmount) : total;
|
|
1559
|
+
}, CurrencyAmount.fromRawAmount(outputNativeCurrency, 0)) : undefined
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
}, {
|
|
1563
|
+
key: "numberOfInputWraps",
|
|
1564
|
+
get: function get() {
|
|
1565
|
+
// if the trade's input is eth it may require a wrap
|
|
1566
|
+
if (this.inputAmount.currency.isNative) {
|
|
1567
|
+
return this.wethInputRoutes.length;
|
|
1568
|
+
} else return 0;
|
|
1569
|
+
}
|
|
1570
|
+
}, {
|
|
1571
|
+
key: "numberOfInputUnwraps",
|
|
1572
|
+
get: function get() {
|
|
1573
|
+
// if the trade's input is weth, it may require an unwrap
|
|
1574
|
+
if (this.isWrappedNative(this.inputAmount.currency)) {
|
|
1575
|
+
return this.nativeInputRoutes.length;
|
|
1576
|
+
} else return 0;
|
|
1577
|
+
}
|
|
1578
|
+
}, {
|
|
1579
|
+
key: "nativeInputRoutes",
|
|
1580
|
+
get: function get() {
|
|
1581
|
+
if (this._nativeInputRoutes) {
|
|
1582
|
+
return this._nativeInputRoutes;
|
|
1583
|
+
}
|
|
1584
|
+
this._nativeInputRoutes = this.routes.filter(function (route) {
|
|
1585
|
+
return route.pathInput.isNative;
|
|
1586
|
+
});
|
|
1587
|
+
return this._nativeInputRoutes;
|
|
1588
|
+
}
|
|
1589
|
+
}, {
|
|
1590
|
+
key: "wethInputRoutes",
|
|
1591
|
+
get: function get() {
|
|
1592
|
+
var _this = this;
|
|
1593
|
+
if (this._wethInputRoutes) {
|
|
1594
|
+
return this._wethInputRoutes;
|
|
1595
|
+
}
|
|
1596
|
+
this._wethInputRoutes = this.routes.filter(function (route) {
|
|
1597
|
+
return _this.isWrappedNative(route.pathInput);
|
|
1598
|
+
});
|
|
1599
|
+
return this._wethInputRoutes;
|
|
1600
|
+
}
|
|
1601
|
+
/**
|
|
1602
|
+
* The price expressed in terms of output amount/input amount.
|
|
1603
|
+
*/
|
|
1604
|
+
}, {
|
|
1605
|
+
key: "executionPrice",
|
|
1606
|
+
get: function get() {
|
|
1607
|
+
var _this$_executionPrice;
|
|
1608
|
+
return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Returns the sell tax of the input token
|
|
1612
|
+
*/
|
|
1613
|
+
}, {
|
|
1614
|
+
key: "inputTax",
|
|
1615
|
+
get: function get() {
|
|
1616
|
+
var inputCurrency = this.inputAmount.currency;
|
|
1617
|
+
if (inputCurrency.isNative || !inputCurrency.wrapped.sellFeeBps) return ZERO_PERCENT;
|
|
1618
|
+
return new Percent(inputCurrency.wrapped.sellFeeBps.toNumber(), 10000);
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Returns the buy tax of the output token
|
|
1622
|
+
*/
|
|
1623
|
+
}, {
|
|
1624
|
+
key: "outputTax",
|
|
1625
|
+
get: function get() {
|
|
1626
|
+
var outputCurrency = this.outputAmount.currency;
|
|
1627
|
+
if (outputCurrency.isNative || !outputCurrency.wrapped.buyFeeBps) return ZERO_PERCENT;
|
|
1628
|
+
return new Percent(outputCurrency.wrapped.buyFeeBps.toNumber(), 10000);
|
|
1629
|
+
}
|
|
1630
|
+
}, {
|
|
1631
|
+
key: "priceImpact",
|
|
1632
|
+
get: function get() {
|
|
1633
|
+
if (this._priceImpact) {
|
|
1634
|
+
return this._priceImpact;
|
|
1635
|
+
}
|
|
1636
|
+
// returns 0% price impact even though this may be inaccurate as a swap may have occured.
|
|
1637
|
+
// because we're unable to derive the pre-buy-tax amount, use 0% as a placeholder.
|
|
1638
|
+
if (this.outputTax.equalTo(ONE_HUNDRED_PERCENT)) return ZERO_PERCENT;
|
|
1639
|
+
var spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
|
|
1640
|
+
for (var _iterator1 = _createForOfIteratorHelperLoose(this.swaps), _step1; !(_step1 = _iterator1()).done;) {
|
|
1641
|
+
var _step1$value = _step1.value,
|
|
1642
|
+
route = _step1$value.route,
|
|
1643
|
+
inputAmount = _step1$value.inputAmount;
|
|
1644
|
+
var midPrice = route.midPrice;
|
|
1645
|
+
var postTaxInputAmount = inputAmount.multiply(new Fraction(ONE).subtract(this.inputTax));
|
|
1646
|
+
spotOutputAmount = spotOutputAmount.add(midPrice.quote(postTaxInputAmount));
|
|
1647
|
+
}
|
|
1648
|
+
// if the total output of this trade is 0, then most likely the post-tax input was also 0, and therefore this swap
|
|
1649
|
+
// does not move the pools' market price
|
|
1650
|
+
if (spotOutputAmount.equalTo(ZERO)) return ZERO_PERCENT;
|
|
1651
|
+
var preTaxOutputAmount = this.outputAmount.divide(new Fraction(ONE).subtract(this.outputTax));
|
|
1652
|
+
var priceImpact = spotOutputAmount.subtract(preTaxOutputAmount).divide(spotOutputAmount);
|
|
1653
|
+
this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator);
|
|
1654
|
+
return this._priceImpact;
|
|
1655
|
+
}
|
|
1656
|
+
}]);
|
|
1657
|
+
}();
|
|
1658
|
+
|
|
1659
|
+
/**
|
|
1660
|
+
* Converts a route to a hex encoded path
|
|
1661
|
+
* @notice only supports exactIn route encodings
|
|
1662
|
+
* @param route the mixed path to convert to an encoded path
|
|
1663
|
+
* @param useMixedRouterQuoteV2 if true, uses the Mixed Quoter V2 encoding for v4 pools. By default, we do not set it. This is only used in SOR for explicit setting during onchain quoting.
|
|
1664
|
+
* @returns the exactIn encoded path
|
|
1665
|
+
*/
|
|
1666
|
+
function encodeMixedRouteToPath(route, useMixedRouterQuoteV2) {
|
|
1667
|
+
var containsV4Pool = useMixedRouterQuoteV2 != null ? useMixedRouterQuoteV2 : route.pools.some(function (pool) {
|
|
1668
|
+
return pool instanceof Pool;
|
|
1669
|
+
});
|
|
1670
|
+
var path;
|
|
1671
|
+
var types;
|
|
1672
|
+
if (containsV4Pool) {
|
|
1673
|
+
path = [route.pathInput.isNative ? ADDRESS_ZERO : route.pathInput.address];
|
|
1674
|
+
types = ['address'];
|
|
1675
|
+
var currencyIn = route.pathInput;
|
|
1676
|
+
for (var _iterator = _createForOfIteratorHelperLoose(route.pools), _step; !(_step = _iterator()).done;) {
|
|
1677
|
+
var pool = _step.value;
|
|
1678
|
+
var currencyOut = currencyIn.equals(pool.token0) ? pool.token1 : pool.token0;
|
|
1679
|
+
if (pool instanceof Pool) {
|
|
1680
|
+
// a tickSpacing of 0 indicates a "fake" v4 pool where the quote actually requires a wrap or unwrap
|
|
1681
|
+
// the fake v4 pool will always have native as token0 and wrapped native as token1
|
|
1682
|
+
if (pool.tickSpacing === 0) {
|
|
1683
|
+
var wrapOrUnwrapEncoding = 0;
|
|
1684
|
+
path.push(wrapOrUnwrapEncoding, currencyOut.isNative ? ADDRESS_ZERO : currencyOut.wrapped.address);
|
|
1685
|
+
types.push('uint8', 'address');
|
|
1686
|
+
} else {
|
|
1687
|
+
var v4Fee = pool.fee + MIXED_QUOTER_V2_V4_FEE_PATH_PLACEHOLDER;
|
|
1688
|
+
path.push(v4Fee, pool.tickSpacing, pool.hooks, currencyOut.isNative ? ADDRESS_ZERO : currencyOut.wrapped.address);
|
|
1689
|
+
types.push('uint24', 'uint24', 'address', 'address');
|
|
1690
|
+
}
|
|
1691
|
+
} else if (pool instanceof Pool$1) {
|
|
1692
|
+
var v3Fee = pool.fee + MIXED_QUOTER_V2_V3_FEE_PATH_PLACEHOLDER;
|
|
1693
|
+
path.push(v3Fee, currencyOut.wrapped.address);
|
|
1694
|
+
types.push('uint24', 'address');
|
|
1695
|
+
} else if (pool instanceof Pair) {
|
|
1696
|
+
var v2Fee = MIXED_QUOTER_V2_V2_FEE_PATH_PLACEHOLDER;
|
|
1697
|
+
path.push(v2Fee, currencyOut.wrapped.address);
|
|
1698
|
+
types.push('uint8', 'address');
|
|
1699
|
+
} else {
|
|
1700
|
+
throw new Error("Unsupported pool type " + JSON.stringify(pool));
|
|
1701
|
+
}
|
|
1702
|
+
currencyIn = currencyOut;
|
|
1703
|
+
}
|
|
1704
|
+
} else {
|
|
1705
|
+
// TODO: ROUTE-276 - delete this else block
|
|
1706
|
+
// We introduced this else block as a safety measure to prevent non-v4 mixed routes from potentially regressing
|
|
1707
|
+
// We'd like to gain more confidence in the new implementation before removing this block
|
|
1708
|
+
var result = route.pools.reduce(function (_ref, pool, index) {
|
|
1709
|
+
var inputToken = _ref.inputToken,
|
|
1710
|
+
path = _ref.path,
|
|
1711
|
+
types = _ref.types;
|
|
1712
|
+
var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
|
|
1713
|
+
if (index === 0) {
|
|
1714
|
+
return {
|
|
1715
|
+
inputToken: outputToken,
|
|
1716
|
+
types: ['address', 'uint24', 'address'],
|
|
1717
|
+
path: [inputToken.wrapped.address, pool instanceof Pool$1 ? pool.fee : MIXED_QUOTER_V1_V2_FEE_PATH_PLACEHOLDER, outputToken.wrapped.address]
|
|
1718
|
+
};
|
|
1719
|
+
} else {
|
|
1720
|
+
return {
|
|
1721
|
+
inputToken: outputToken,
|
|
1722
|
+
types: [].concat(types, ['uint24', 'address']),
|
|
1723
|
+
path: [].concat(path, [pool instanceof Pool$1 ? pool.fee : MIXED_QUOTER_V1_V2_FEE_PATH_PLACEHOLDER, outputToken.wrapped.address])
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
}, {
|
|
1727
|
+
inputToken: route.input,
|
|
1728
|
+
path: [],
|
|
1729
|
+
types: []
|
|
1730
|
+
});
|
|
1731
|
+
path = result.path;
|
|
1732
|
+
types = result.types;
|
|
1733
|
+
}
|
|
1734
|
+
return pack(types, path);
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* Utility function to return each consecutive section of Pools or Pairs in a MixedRoute
|
|
1739
|
+
* @param route
|
|
1740
|
+
* @returns a nested array of Pools or Pairs in the order of the route
|
|
1741
|
+
*/
|
|
1742
|
+
var partitionMixedRouteByProtocol = function partitionMixedRouteByProtocol(route) {
|
|
1743
|
+
var acc = [];
|
|
1744
|
+
var left = 0;
|
|
1745
|
+
var right = 0;
|
|
1746
|
+
while (right < route.pools.length) {
|
|
1747
|
+
if (route.pools[left] instanceof Pool && !(route.pools[right] instanceof Pool) || route.pools[left] instanceof Pool$1 && !(route.pools[right] instanceof Pool$1) || route.pools[left] instanceof Pair && !(route.pools[right] instanceof Pair)) {
|
|
1748
|
+
acc.push(route.pools.slice(left, right));
|
|
1749
|
+
left = right;
|
|
1750
|
+
}
|
|
1751
|
+
// seek forward with right pointer
|
|
1752
|
+
right++;
|
|
1753
|
+
if (right === route.pools.length) {
|
|
1754
|
+
/// we reached the end, take the rest
|
|
1755
|
+
acc.push(route.pools.slice(left, right));
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
return acc;
|
|
1759
|
+
};
|
|
1760
|
+
/**
|
|
1761
|
+
* Simple utility function to get the output of an array of Pools or Pairs
|
|
1762
|
+
* @param pools
|
|
1763
|
+
* @param firstInputToken
|
|
1764
|
+
* @returns the output token of the last pool in the array
|
|
1765
|
+
*/
|
|
1766
|
+
var getOutputOfPools = function getOutputOfPools(pools, firstInputToken) {
|
|
1767
|
+
var _pools$reduce = pools.reduce(function (_ref, pool) {
|
|
1768
|
+
var inputToken = _ref.inputToken;
|
|
1769
|
+
if (!pool.involvesToken(inputToken)) throw new Error('PATH');
|
|
1770
|
+
var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
|
|
1771
|
+
return {
|
|
1772
|
+
inputToken: outputToken
|
|
1773
|
+
};
|
|
1774
|
+
}, {
|
|
1775
|
+
inputToken: firstInputToken
|
|
1776
|
+
}),
|
|
1777
|
+
outputToken = _pools$reduce.inputToken;
|
|
1778
|
+
return outputToken;
|
|
1779
|
+
};
|
|
1780
|
+
|
|
1781
|
+
var ZERO$1 = /*#__PURE__*/JSBI.BigInt(0);
|
|
1782
|
+
var REFUND_ETH_PRICE_IMPACT_THRESHOLD = /*#__PURE__*/new Percent(/*#__PURE__*/JSBI.BigInt(50), /*#__PURE__*/JSBI.BigInt(100));
|
|
1783
|
+
/**
|
|
1784
|
+
* Represents the Uniswap V2 + V3 SwapRouter02, and has static methods for helping execute trades.
|
|
1785
|
+
*/
|
|
1786
|
+
var SwapRouter = /*#__PURE__*/function () {
|
|
1787
|
+
/**
|
|
1788
|
+
* Cannot be constructed.
|
|
1789
|
+
*/
|
|
1790
|
+
function SwapRouter() {}
|
|
1791
|
+
/**
|
|
1792
|
+
* @notice Generates the calldata for a Swap with a V2 Route.
|
|
1793
|
+
* @param trade The V2Trade to encode.
|
|
1794
|
+
* @param options SwapOptions to use for the trade.
|
|
1795
|
+
* @param routerMustCustody Flag for whether funds should be sent to the router
|
|
1796
|
+
* @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
|
|
1797
|
+
* @returns A string array of calldatas for the trade.
|
|
1798
|
+
*/
|
|
1799
|
+
SwapRouter.encodeV2Swap = function encodeV2Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck) {
|
|
1800
|
+
var amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance).quotient);
|
|
1801
|
+
var amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance).quotient);
|
|
1802
|
+
var path = trade.route.path.map(function (token) {
|
|
1803
|
+
return token.address;
|
|
1804
|
+
});
|
|
1805
|
+
var recipient = routerMustCustody ? ADDRESS_THIS : typeof options.recipient === 'undefined' ? MSG_SENDER : validateAndParseAddress(options.recipient);
|
|
1806
|
+
if (trade.tradeType === TradeType.EXACT_INPUT) {
|
|
1807
|
+
var exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient];
|
|
1808
|
+
return SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams);
|
|
1809
|
+
} else {
|
|
1810
|
+
var exactOutputParams = [amountOut, amountIn, path, recipient];
|
|
1811
|
+
return SwapRouter.INTERFACE.encodeFunctionData('swapTokensForExactTokens', exactOutputParams);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* @notice Generates the calldata for a Swap with a V3 Route.
|
|
1816
|
+
* @param trade The V3Trade to encode.
|
|
1817
|
+
* @param options SwapOptions to use for the trade.
|
|
1818
|
+
* @param routerMustCustody Flag for whether funds should be sent to the router
|
|
1819
|
+
* @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
|
|
1820
|
+
* @returns A string array of calldatas for the trade.
|
|
1821
|
+
*/;
|
|
1822
|
+
SwapRouter.encodeV3Swap = function encodeV3Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck) {
|
|
1823
|
+
var calldatas = [];
|
|
1824
|
+
for (var _iterator = _createForOfIteratorHelperLoose(trade.swaps), _step; !(_step = _iterator()).done;) {
|
|
1825
|
+
var _step$value = _step.value,
|
|
1826
|
+
route = _step$value.route,
|
|
1827
|
+
inputAmount = _step$value.inputAmount,
|
|
1828
|
+
outputAmount = _step$value.outputAmount;
|
|
1829
|
+
var amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
|
|
1830
|
+
var amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
|
|
1831
|
+
// flag for whether the trade is single hop or not
|
|
1832
|
+
var singleHop = route.pools.length === 1;
|
|
1833
|
+
var recipient = routerMustCustody ? ADDRESS_THIS : typeof options.recipient === 'undefined' ? MSG_SENDER : validateAndParseAddress(options.recipient);
|
|
1834
|
+
if (singleHop) {
|
|
1835
|
+
if (trade.tradeType === TradeType.EXACT_INPUT) {
|
|
1836
|
+
var exactInputSingleParams = {
|
|
1837
|
+
tokenIn: route.tokenPath[0].address,
|
|
1838
|
+
tokenOut: route.tokenPath[1].address,
|
|
1839
|
+
fee: route.pools[0].fee,
|
|
1840
|
+
recipient: recipient,
|
|
1841
|
+
amountIn: amountIn,
|
|
1842
|
+
amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,
|
|
1843
|
+
sqrtPriceLimitX96: 0
|
|
1844
|
+
};
|
|
1845
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]));
|
|
1846
|
+
} else {
|
|
1847
|
+
var exactOutputSingleParams = {
|
|
1848
|
+
tokenIn: route.tokenPath[0].address,
|
|
1849
|
+
tokenOut: route.tokenPath[1].address,
|
|
1850
|
+
fee: route.pools[0].fee,
|
|
1851
|
+
recipient: recipient,
|
|
1852
|
+
amountOut: amountOut,
|
|
1853
|
+
amountInMaximum: amountIn,
|
|
1854
|
+
sqrtPriceLimitX96: 0
|
|
1855
|
+
};
|
|
1856
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]));
|
|
1857
|
+
}
|
|
1858
|
+
} else {
|
|
1859
|
+
var path = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT);
|
|
1860
|
+
if (trade.tradeType === TradeType.EXACT_INPUT) {
|
|
1861
|
+
var exactInputParams = {
|
|
1862
|
+
path: path,
|
|
1863
|
+
recipient: recipient,
|
|
1864
|
+
amountIn: amountIn,
|
|
1865
|
+
amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut
|
|
1866
|
+
};
|
|
1867
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]));
|
|
1868
|
+
} else {
|
|
1869
|
+
var exactOutputParams = {
|
|
1870
|
+
path: path,
|
|
1871
|
+
recipient: recipient,
|
|
1872
|
+
amountOut: amountOut,
|
|
1873
|
+
amountInMaximum: amountIn
|
|
1874
|
+
};
|
|
1875
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]));
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
return calldatas;
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* @notice Generates the calldata for a MixedRouteSwap. Since single hop routes are not MixedRoutes, we will instead generate
|
|
1883
|
+
* them via the existing encodeV3Swap and encodeV2Swap methods.
|
|
1884
|
+
* @param trade The MixedRouteTrade to encode.
|
|
1885
|
+
* @param options SwapOptions to use for the trade.
|
|
1886
|
+
* @param routerMustCustody Flag for whether funds should be sent to the router
|
|
1887
|
+
* @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
|
|
1888
|
+
* @returns A string array of calldatas for the trade.
|
|
1889
|
+
*/;
|
|
1890
|
+
SwapRouter.encodeMixedRouteSwap = function encodeMixedRouteSwap(trade, options, routerMustCustody, performAggregatedSlippageCheck) {
|
|
1891
|
+
var calldatas = [];
|
|
1892
|
+
!(trade.tradeType === TradeType.EXACT_INPUT) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TRADE_TYPE') : invariant(false) : void 0;
|
|
1893
|
+
var _loop = function _loop() {
|
|
1894
|
+
var _step2$value = _step2.value,
|
|
1895
|
+
route = _step2$value.route,
|
|
1896
|
+
inputAmount = _step2$value.inputAmount,
|
|
1897
|
+
outputAmount = _step2$value.outputAmount;
|
|
1898
|
+
if (route.pools.some(function (pool) {
|
|
1899
|
+
return pool instanceof Pool;
|
|
1900
|
+
})) throw new Error('Encoding mixed routes with V4 not supported');
|
|
1901
|
+
var amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
|
|
1902
|
+
var amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
|
|
1903
|
+
// flag for whether the trade is single hop or not
|
|
1904
|
+
var singleHop = route.pools.length === 1;
|
|
1905
|
+
var recipient = routerMustCustody ? ADDRESS_THIS : typeof options.recipient === 'undefined' ? MSG_SENDER : validateAndParseAddress(options.recipient);
|
|
1906
|
+
var mixedRouteIsAllV3 = function mixedRouteIsAllV3(route) {
|
|
1907
|
+
return route.pools.every(function (pool) {
|
|
1908
|
+
return pool instanceof Pool$1;
|
|
1909
|
+
});
|
|
1910
|
+
};
|
|
1911
|
+
if (singleHop) {
|
|
1912
|
+
/// For single hop, since it isn't really a mixedRoute, we'll just mimic behavior of V3 or V2
|
|
1913
|
+
/// We don't use encodeV3Swap() or encodeV2Swap() because casting the trade to a V3Trade or V2Trade is overcomplex
|
|
1914
|
+
if (mixedRouteIsAllV3(route)) {
|
|
1915
|
+
var exactInputSingleParams = {
|
|
1916
|
+
tokenIn: route.path[0].wrapped.address,
|
|
1917
|
+
tokenOut: route.path[1].wrapped.address,
|
|
1918
|
+
fee: route.pools[0].fee,
|
|
1919
|
+
recipient: recipient,
|
|
1920
|
+
amountIn: amountIn,
|
|
1921
|
+
amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,
|
|
1922
|
+
sqrtPriceLimitX96: 0
|
|
1923
|
+
};
|
|
1924
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]));
|
|
1925
|
+
} else {
|
|
1926
|
+
var path = route.path.map(function (token) {
|
|
1927
|
+
return token.wrapped.address;
|
|
1928
|
+
});
|
|
1929
|
+
var exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient];
|
|
1930
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams));
|
|
1931
|
+
}
|
|
1932
|
+
} else {
|
|
1933
|
+
var sections = partitionMixedRouteByProtocol(route);
|
|
1934
|
+
var isLastSectionInRoute = function isLastSectionInRoute(i) {
|
|
1935
|
+
return i === sections.length - 1;
|
|
1936
|
+
};
|
|
1937
|
+
var outputToken;
|
|
1938
|
+
var inputToken = route.input.wrapped;
|
|
1939
|
+
for (var i = 0; i < sections.length; i++) {
|
|
1940
|
+
var section = sections[i];
|
|
1941
|
+
/// Now, we get output of this section
|
|
1942
|
+
outputToken = getOutputOfPools(section, inputToken);
|
|
1943
|
+
var newRouteOriginal = new MixedRouteSDK([].concat(section), section[0].token0.equals(inputToken) ? section[0].token0 : section[0].token1, outputToken);
|
|
1944
|
+
var newRoute = new MixedRoute(newRouteOriginal);
|
|
1945
|
+
/// Previous output is now input
|
|
1946
|
+
inputToken = outputToken.wrapped;
|
|
1947
|
+
if (mixedRouteIsAllV3(newRoute)) {
|
|
1948
|
+
var _path = encodeMixedRouteToPath(newRoute);
|
|
1949
|
+
var _exactInputParams = {
|
|
1950
|
+
path: _path,
|
|
1951
|
+
// By default router holds funds until the last swap, then it is sent to the recipient
|
|
1952
|
+
// special case exists where we are unwrapping WETH output, in which case `routerMustCustody` is set to true
|
|
1953
|
+
// and router still holds the funds. That logic bundled into how the value of `recipient` is calculated
|
|
1954
|
+
recipient: isLastSectionInRoute(i) ? recipient : ADDRESS_THIS,
|
|
1955
|
+
amountIn: i === 0 ? amountIn : 0,
|
|
1956
|
+
amountOutMinimum: !isLastSectionInRoute(i) ? 0 : amountOut
|
|
1957
|
+
};
|
|
1958
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [_exactInputParams]));
|
|
1959
|
+
} else {
|
|
1960
|
+
var _exactInputParams2 = [i === 0 ? amountIn : 0, !isLastSectionInRoute(i) ? 0 : amountOut, newRoute.path.map(function (token) {
|
|
1961
|
+
return token.wrapped.address;
|
|
1962
|
+
}), isLastSectionInRoute(i) ? recipient : ADDRESS_THIS];
|
|
1963
|
+
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', _exactInputParams2));
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
for (var _iterator2 = _createForOfIteratorHelperLoose(trade.swaps), _step2; !(_step2 = _iterator2()).done;) {
|
|
1969
|
+
_loop();
|
|
1970
|
+
}
|
|
1971
|
+
return calldatas;
|
|
1972
|
+
};
|
|
1973
|
+
SwapRouter.encodeSwaps = function encodeSwaps(trades, options, isSwapAndAdd) {
|
|
1974
|
+
// If dealing with an instance of the aggregated Trade object, unbundle it to individual trade objects.
|
|
1975
|
+
if (trades instanceof Trade) {
|
|
1976
|
+
!trades.swaps.every(function (swap) {
|
|
1977
|
+
return swap.route.protocol === Protocol.V3 || swap.route.protocol === Protocol.V2 || swap.route.protocol === Protocol.MIXED;
|
|
1978
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'UNSUPPORTED_PROTOCOL (encoding routes with v4 not supported)') : invariant(false) : void 0;
|
|
1979
|
+
var individualTrades = [];
|
|
1980
|
+
for (var _iterator3 = _createForOfIteratorHelperLoose(trades.swaps), _step3; !(_step3 = _iterator3()).done;) {
|
|
1981
|
+
var _step3$value = _step3.value,
|
|
1982
|
+
route = _step3$value.route,
|
|
1983
|
+
inputAmount = _step3$value.inputAmount,
|
|
1984
|
+
outputAmount = _step3$value.outputAmount;
|
|
1985
|
+
if (route.protocol === Protocol.V2) {
|
|
1986
|
+
individualTrades.push(new Trade$3(route, trades.tradeType === TradeType.EXACT_INPUT ? inputAmount : outputAmount, trades.tradeType));
|
|
1987
|
+
} else if (route.protocol === Protocol.V3) {
|
|
1988
|
+
individualTrades.push(Trade$2.createUncheckedTrade({
|
|
1989
|
+
route: route,
|
|
1990
|
+
inputAmount: inputAmount,
|
|
1991
|
+
outputAmount: outputAmount,
|
|
1992
|
+
tradeType: trades.tradeType
|
|
1993
|
+
}));
|
|
1994
|
+
} else if (route.protocol === Protocol.MIXED) {
|
|
1995
|
+
individualTrades.push(
|
|
1996
|
+
/// we can change the naming of this function on MixedRouteTrade if needed
|
|
1997
|
+
MixedRouteTrade.createUncheckedTrade({
|
|
1998
|
+
route: route,
|
|
1999
|
+
inputAmount: inputAmount,
|
|
2000
|
+
outputAmount: outputAmount,
|
|
2001
|
+
tradeType: trades.tradeType
|
|
2002
|
+
}));
|
|
2003
|
+
} else {
|
|
2004
|
+
throw new Error('UNSUPPORTED_TRADE_PROTOCOL');
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
trades = individualTrades;
|
|
2008
|
+
}
|
|
2009
|
+
if (!Array.isArray(trades)) {
|
|
2010
|
+
trades = [trades];
|
|
2011
|
+
}
|
|
2012
|
+
var numberOfTrades = trades.reduce(function (numberOfTrades, trade) {
|
|
2013
|
+
return numberOfTrades + (trade instanceof Trade$2 || trade instanceof MixedRouteTrade ? trade.swaps.length : 1);
|
|
2014
|
+
}, 0);
|
|
2015
|
+
var sampleTrade = trades[0];
|
|
2016
|
+
// All trades should have the same starting/ending currency and trade type
|
|
2017
|
+
!trades.every(function (trade) {
|
|
2018
|
+
return trade.inputAmount.currency.equals(sampleTrade.inputAmount.currency);
|
|
2019
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_IN_DIFF') : invariant(false) : void 0;
|
|
2020
|
+
!trades.every(function (trade) {
|
|
2021
|
+
return trade.outputAmount.currency.equals(sampleTrade.outputAmount.currency);
|
|
2022
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_OUT_DIFF') : invariant(false) : void 0;
|
|
2023
|
+
!trades.every(function (trade) {
|
|
2024
|
+
return trade.tradeType === sampleTrade.tradeType;
|
|
2025
|
+
}) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TRADE_TYPE_DIFF') : invariant(false) : void 0;
|
|
2026
|
+
var calldatas = [];
|
|
2027
|
+
var inputIsNative = sampleTrade.inputAmount.currency.isNative;
|
|
2028
|
+
var outputIsNative = sampleTrade.outputAmount.currency.isNative;
|
|
2029
|
+
// flag for whether we want to perform an aggregated slippage check
|
|
2030
|
+
// 1. when there are >2 exact input trades. this is only a heuristic,
|
|
2031
|
+
// as it's still more gas-expensive even in this case, but has benefits
|
|
2032
|
+
// in that the reversion probability is lower
|
|
2033
|
+
var performAggregatedSlippageCheck = sampleTrade.tradeType === TradeType.EXACT_INPUT && numberOfTrades > 2;
|
|
2034
|
+
// flag for whether funds should be send first to the router
|
|
2035
|
+
// 1. when receiving ETH (which much be unwrapped from WETH)
|
|
2036
|
+
// 2. when a fee on the output is being taken
|
|
2037
|
+
// 3. when performing swap and add
|
|
2038
|
+
// 4. when performing an aggregated slippage check
|
|
2039
|
+
var routerMustCustody = outputIsNative || !!options.fee || !!isSwapAndAdd || performAggregatedSlippageCheck;
|
|
2040
|
+
// encode permit if necessary
|
|
2041
|
+
if (options.inputTokenPermit) {
|
|
2042
|
+
!sampleTrade.inputAmount.currency.isToken ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON_TOKEN_PERMIT') : invariant(false) : void 0;
|
|
2043
|
+
calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
|
|
2044
|
+
}
|
|
2045
|
+
for (var _iterator4 = _createForOfIteratorHelperLoose(trades), _step4; !(_step4 = _iterator4()).done;) {
|
|
2046
|
+
var trade = _step4.value;
|
|
2047
|
+
if (trade instanceof Trade$3) {
|
|
2048
|
+
calldatas.push(SwapRouter.encodeV2Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck));
|
|
2049
|
+
} else if (trade instanceof Trade$2) {
|
|
2050
|
+
for (var _iterator5 = _createForOfIteratorHelperLoose(SwapRouter.encodeV3Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck)), _step5; !(_step5 = _iterator5()).done;) {
|
|
2051
|
+
var calldata = _step5.value;
|
|
2052
|
+
calldatas.push(calldata);
|
|
2053
|
+
}
|
|
2054
|
+
} else if (trade instanceof MixedRouteTrade) {
|
|
2055
|
+
for (var _iterator6 = _createForOfIteratorHelperLoose(SwapRouter.encodeMixedRouteSwap(trade, options, routerMustCustody, performAggregatedSlippageCheck)), _step6; !(_step6 = _iterator6()).done;) {
|
|
2056
|
+
var _calldata = _step6.value;
|
|
2057
|
+
calldatas.push(_calldata);
|
|
2058
|
+
}
|
|
2059
|
+
} else {
|
|
2060
|
+
throw new Error('Unsupported trade object');
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
var ZERO_IN = CurrencyAmount.fromRawAmount(sampleTrade.inputAmount.currency, 0);
|
|
2064
|
+
var ZERO_OUT = CurrencyAmount.fromRawAmount(sampleTrade.outputAmount.currency, 0);
|
|
2065
|
+
var minimumAmountOut = trades.reduce(function (sum, trade) {
|
|
2066
|
+
return sum.add(trade.minimumAmountOut(options.slippageTolerance));
|
|
2067
|
+
}, ZERO_OUT);
|
|
2068
|
+
var quoteAmountOut = trades.reduce(function (sum, trade) {
|
|
2069
|
+
return sum.add(trade.outputAmount);
|
|
2070
|
+
}, ZERO_OUT);
|
|
2071
|
+
var totalAmountIn = trades.reduce(function (sum, trade) {
|
|
2072
|
+
return sum.add(trade.maximumAmountIn(options.slippageTolerance));
|
|
2073
|
+
}, ZERO_IN);
|
|
2074
|
+
return {
|
|
2075
|
+
calldatas: calldatas,
|
|
2076
|
+
sampleTrade: sampleTrade,
|
|
2077
|
+
routerMustCustody: routerMustCustody,
|
|
2078
|
+
inputIsNative: inputIsNative,
|
|
2079
|
+
outputIsNative: outputIsNative,
|
|
2080
|
+
totalAmountIn: totalAmountIn,
|
|
2081
|
+
minimumAmountOut: minimumAmountOut,
|
|
2082
|
+
quoteAmountOut: quoteAmountOut
|
|
2083
|
+
};
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
|
|
2087
|
+
* @param trades to produce call parameters for
|
|
2088
|
+
* @param options options for the call parameters
|
|
2089
|
+
*/;
|
|
2090
|
+
SwapRouter.swapCallParameters = function swapCallParameters(trades, options) {
|
|
2091
|
+
var _SwapRouter$encodeSwa = SwapRouter.encodeSwaps(trades, options),
|
|
2092
|
+
calldatas = _SwapRouter$encodeSwa.calldatas,
|
|
2093
|
+
sampleTrade = _SwapRouter$encodeSwa.sampleTrade,
|
|
2094
|
+
routerMustCustody = _SwapRouter$encodeSwa.routerMustCustody,
|
|
2095
|
+
inputIsNative = _SwapRouter$encodeSwa.inputIsNative,
|
|
2096
|
+
outputIsNative = _SwapRouter$encodeSwa.outputIsNative,
|
|
2097
|
+
totalAmountIn = _SwapRouter$encodeSwa.totalAmountIn,
|
|
2098
|
+
minimumAmountOut = _SwapRouter$encodeSwa.minimumAmountOut;
|
|
2099
|
+
// unwrap or sweep
|
|
2100
|
+
if (routerMustCustody) {
|
|
2101
|
+
if (outputIsNative) {
|
|
2102
|
+
calldatas.push(PaymentsExtended.encodeUnwrapWETH9(minimumAmountOut.quotient, options.recipient, options.fee));
|
|
2103
|
+
} else {
|
|
2104
|
+
calldatas.push(PaymentsExtended.encodeSweepToken(sampleTrade.outputAmount.currency.wrapped, minimumAmountOut.quotient, options.recipient, options.fee));
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
// must refund when paying in ETH: either with an uncertain input amount OR if there's a chance of a partial fill.
|
|
2108
|
+
// unlike ERC20's, the full ETH value must be sent in the transaction, so the rest must be refunded.
|
|
2109
|
+
if (inputIsNative && (sampleTrade.tradeType === TradeType.EXACT_OUTPUT || SwapRouter.riskOfPartialFill(trades))) {
|
|
2110
|
+
calldatas.push(Payments.encodeRefundETH());
|
|
2111
|
+
}
|
|
2112
|
+
return {
|
|
2113
|
+
calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),
|
|
2114
|
+
value: toHex(inputIsNative ? totalAmountIn.quotient : ZERO$1)
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
|
|
2119
|
+
* @param trades to produce call parameters for
|
|
2120
|
+
* @param options options for the call parameters
|
|
2121
|
+
*/;
|
|
2122
|
+
SwapRouter.swapAndAddCallParameters = function swapAndAddCallParameters(trades, options, position, addLiquidityOptions, tokenInApprovalType, tokenOutApprovalType) {
|
|
2123
|
+
var _SwapRouter$encodeSwa2 = SwapRouter.encodeSwaps(trades, options, true),
|
|
2124
|
+
calldatas = _SwapRouter$encodeSwa2.calldatas,
|
|
2125
|
+
inputIsNative = _SwapRouter$encodeSwa2.inputIsNative,
|
|
2126
|
+
outputIsNative = _SwapRouter$encodeSwa2.outputIsNative,
|
|
2127
|
+
sampleTrade = _SwapRouter$encodeSwa2.sampleTrade,
|
|
2128
|
+
totalAmountSwapped = _SwapRouter$encodeSwa2.totalAmountIn,
|
|
2129
|
+
quoteAmountOut = _SwapRouter$encodeSwa2.quoteAmountOut,
|
|
2130
|
+
minimumAmountOut = _SwapRouter$encodeSwa2.minimumAmountOut;
|
|
2131
|
+
// encode output token permit if necessary
|
|
2132
|
+
if (options.outputTokenPermit) {
|
|
2133
|
+
!quoteAmountOut.currency.isToken ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON_TOKEN_PERMIT_OUTPUT') : invariant(false) : void 0;
|
|
2134
|
+
calldatas.push(SelfPermit.encodePermit(quoteAmountOut.currency, options.outputTokenPermit));
|
|
2135
|
+
}
|
|
2136
|
+
var chainId = sampleTrade.route.chainId;
|
|
2137
|
+
var zeroForOne = position.pool.token0.wrapped.address === totalAmountSwapped.currency.wrapped.address;
|
|
2138
|
+
var _SwapRouter$getPositi = SwapRouter.getPositionAmounts(position, zeroForOne),
|
|
2139
|
+
positionAmountIn = _SwapRouter$getPositi.positionAmountIn,
|
|
2140
|
+
positionAmountOut = _SwapRouter$getPositi.positionAmountOut;
|
|
2141
|
+
// if tokens are native they will be converted to WETH9
|
|
2142
|
+
var tokenIn = inputIsNative ? WETH9[chainId] : positionAmountIn.currency.wrapped;
|
|
2143
|
+
var tokenOut = outputIsNative ? WETH9[chainId] : positionAmountOut.currency.wrapped;
|
|
2144
|
+
// if swap output does not make up whole outputTokenBalanceDesired, pull in remaining tokens for adding liquidity
|
|
2145
|
+
var amountOutRemaining = positionAmountOut.subtract(quoteAmountOut.wrapped);
|
|
2146
|
+
if (amountOutRemaining.greaterThan(CurrencyAmount.fromRawAmount(positionAmountOut.currency, 0))) {
|
|
2147
|
+
// if output is native, this means the remaining portion is included as native value in the transaction
|
|
2148
|
+
// and must be wrapped. Otherwise, pull in remaining ERC20 token.
|
|
2149
|
+
outputIsNative ? calldatas.push(PaymentsExtended.encodeWrapETH(amountOutRemaining.quotient)) : calldatas.push(PaymentsExtended.encodePull(tokenOut, amountOutRemaining.quotient));
|
|
2150
|
+
}
|
|
2151
|
+
// if input is native, convert to WETH9, else pull ERC20 token
|
|
2152
|
+
inputIsNative ? calldatas.push(PaymentsExtended.encodeWrapETH(positionAmountIn.quotient)) : calldatas.push(PaymentsExtended.encodePull(tokenIn, positionAmountIn.quotient));
|
|
2153
|
+
// approve token balances to NFTManager
|
|
2154
|
+
if (tokenInApprovalType !== ApprovalTypes.NOT_REQUIRED) calldatas.push(ApproveAndCall.encodeApprove(tokenIn, tokenInApprovalType));
|
|
2155
|
+
if (tokenOutApprovalType !== ApprovalTypes.NOT_REQUIRED) calldatas.push(ApproveAndCall.encodeApprove(tokenOut, tokenOutApprovalType));
|
|
2156
|
+
// represents a position with token amounts resulting from a swap with maximum slippage
|
|
2157
|
+
// hence the minimal amount out possible.
|
|
2158
|
+
var minimalPosition = Position.fromAmounts({
|
|
2159
|
+
pool: position.pool,
|
|
2160
|
+
tickLower: position.tickLower,
|
|
2161
|
+
tickUpper: position.tickUpper,
|
|
2162
|
+
amount0: zeroForOne ? position.amount0.quotient.toString() : minimumAmountOut.quotient.toString(),
|
|
2163
|
+
amount1: zeroForOne ? minimumAmountOut.quotient.toString() : position.amount1.quotient.toString(),
|
|
2164
|
+
useFullPrecision: false
|
|
2165
|
+
});
|
|
2166
|
+
// encode NFTManager add liquidity
|
|
2167
|
+
calldatas.push(ApproveAndCall.encodeAddLiquidity(position, minimalPosition, addLiquidityOptions, options.slippageTolerance));
|
|
2168
|
+
// sweep remaining tokens
|
|
2169
|
+
inputIsNative ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO$1)) : calldatas.push(PaymentsExtended.encodeSweepToken(tokenIn, ZERO$1));
|
|
2170
|
+
outputIsNative ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO$1)) : calldatas.push(PaymentsExtended.encodeSweepToken(tokenOut, ZERO$1));
|
|
2171
|
+
var value;
|
|
2172
|
+
if (inputIsNative) {
|
|
2173
|
+
value = totalAmountSwapped.wrapped.add(positionAmountIn.wrapped).quotient;
|
|
2174
|
+
} else if (outputIsNative) {
|
|
2175
|
+
value = amountOutRemaining.quotient;
|
|
2176
|
+
} else {
|
|
2177
|
+
value = ZERO$1;
|
|
2178
|
+
}
|
|
2179
|
+
return {
|
|
2180
|
+
calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),
|
|
2181
|
+
value: value.toString()
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
// if price impact is very high, there's a chance of hitting max/min prices resulting in a partial fill of the swap
|
|
2185
|
+
;
|
|
2186
|
+
SwapRouter.riskOfPartialFill = function riskOfPartialFill(trades) {
|
|
2187
|
+
if (Array.isArray(trades)) {
|
|
2188
|
+
return trades.some(function (trade) {
|
|
2189
|
+
return SwapRouter.v3TradeWithHighPriceImpact(trade);
|
|
2190
|
+
});
|
|
2191
|
+
} else {
|
|
2192
|
+
return SwapRouter.v3TradeWithHighPriceImpact(trades);
|
|
2193
|
+
}
|
|
2194
|
+
};
|
|
2195
|
+
SwapRouter.v3TradeWithHighPriceImpact = function v3TradeWithHighPriceImpact(trade) {
|
|
2196
|
+
return !(trade instanceof Trade$3) && trade.priceImpact.greaterThan(REFUND_ETH_PRICE_IMPACT_THRESHOLD);
|
|
2197
|
+
};
|
|
2198
|
+
SwapRouter.getPositionAmounts = function getPositionAmounts(position, zeroForOne) {
|
|
2199
|
+
var _position$mintAmounts = position.mintAmounts,
|
|
2200
|
+
amount0 = _position$mintAmounts.amount0,
|
|
2201
|
+
amount1 = _position$mintAmounts.amount1;
|
|
2202
|
+
var currencyAmount0 = CurrencyAmount.fromRawAmount(position.pool.token0, amount0);
|
|
2203
|
+
var currencyAmount1 = CurrencyAmount.fromRawAmount(position.pool.token1, amount1);
|
|
2204
|
+
var _ref = zeroForOne ? [currencyAmount0, currencyAmount1] : [currencyAmount1, currencyAmount0],
|
|
2205
|
+
positionAmountIn = _ref[0],
|
|
2206
|
+
positionAmountOut = _ref[1];
|
|
2207
|
+
return {
|
|
2208
|
+
positionAmountIn: positionAmountIn,
|
|
2209
|
+
positionAmountOut: positionAmountOut
|
|
2210
|
+
};
|
|
2211
|
+
};
|
|
2212
|
+
return SwapRouter;
|
|
2213
|
+
}();
|
|
2214
|
+
SwapRouter.INTERFACE = /*#__PURE__*/new Interface(ISwapRouter02.abi);
|
|
2215
|
+
|
|
2216
|
+
export { ADDRESS_THIS, ADDRESS_ZERO, ApprovalTypes, ApproveAndCall, MIXED_QUOTER_V1_V2_FEE_PATH_PLACEHOLDER, MIXED_QUOTER_V2_V2_FEE_PATH_PLACEHOLDER, MIXED_QUOTER_V2_V3_FEE_PATH_PLACEHOLDER, MIXED_QUOTER_V2_V4_FEE_PATH_PLACEHOLDER, MSG_SENDER, MixedRoute, MixedRouteSDK, MixedRouteTrade, MulticallExtended, ONE, ONE_HUNDRED_PERCENT, PaymentsExtended, Protocol, RouteV2, RouteV3, RouteV4, SwapRouter, Trade, ZERO, ZERO_PERCENT, amountWithPathCurrency, encodeMixedRouteToPath, getOutputOfPools, getPathCurrency, getPathToken, isMint, partitionMixedRouteByProtocol, tradeComparator };
|
|
2217
|
+
//# sourceMappingURL=router-sdk.esm.js.map
|