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