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