@uniswap/router-sdk 1.23.0 → 2.0.1

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