@uniswap/router-sdk 2.0.0 → 2.0.2

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