@centurion_project/router-sdk 2.11.11 → 2.11.13

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 (58) hide show
  1. package/dist/cjs/src/entities/mixedRoute/route.js +4 -19
  2. package/dist/cjs/src/entities/mixedRoute/route.js.map +1 -1
  3. package/dist/cjs/src/utils/index.js +19 -7
  4. package/dist/cjs/src/utils/index.js.map +1 -1
  5. package/dist/esm/src/entities/mixedRoute/route.js +5 -20
  6. package/dist/esm/src/entities/mixedRoute/route.js.map +1 -1
  7. package/dist/esm/src/utils/index.js +19 -7
  8. package/dist/esm/src/utils/index.js.map +1 -1
  9. package/dist/types/src/approveAndCall.d.ts +1 -0
  10. package/dist/types/src/approveAndCall.d.ts.map +1 -0
  11. package/dist/types/src/constants.d.ts +1 -0
  12. package/dist/types/src/constants.d.ts.map +1 -0
  13. package/dist/types/src/entities/mixedRoute/route.d.ts +1 -0
  14. package/dist/types/src/entities/mixedRoute/route.d.ts.map +1 -0
  15. package/dist/types/src/entities/mixedRoute/trade.d.ts +1 -0
  16. package/dist/types/src/entities/mixedRoute/trade.d.ts.map +1 -0
  17. package/dist/types/src/entities/protocol.d.ts +1 -0
  18. package/dist/types/src/entities/protocol.d.ts.map +1 -0
  19. package/dist/types/src/entities/route.d.ts +1 -0
  20. package/dist/types/src/entities/route.d.ts.map +1 -0
  21. package/dist/types/src/entities/trade.d.ts +1 -0
  22. package/dist/types/src/entities/trade.d.ts.map +1 -0
  23. package/dist/types/src/index.d.ts +1 -0
  24. package/dist/types/src/index.d.ts.map +1 -0
  25. package/dist/types/src/multicallExtended.d.ts +1 -0
  26. package/dist/types/src/multicallExtended.d.ts.map +1 -0
  27. package/dist/types/src/paymentsExtended.d.ts +1 -0
  28. package/dist/types/src/paymentsExtended.d.ts.map +1 -0
  29. package/dist/types/src/swapRouter.d.ts +1 -0
  30. package/dist/types/src/swapRouter.d.ts.map +1 -0
  31. package/dist/types/src/utils/TPool.d.ts +1 -0
  32. package/dist/types/src/utils/TPool.d.ts.map +1 -0
  33. package/dist/types/src/utils/encodeMixedRouteToPath.d.ts +1 -0
  34. package/dist/types/src/utils/encodeMixedRouteToPath.d.ts.map +1 -0
  35. package/dist/types/src/utils/index.d.ts +1 -0
  36. package/dist/types/src/utils/index.d.ts.map +1 -0
  37. package/dist/types/src/utils/pathCurrency.d.ts +1 -0
  38. package/dist/types/src/utils/pathCurrency.d.ts.map +1 -0
  39. package/package.json +12 -9
  40. package/src/abis/IApproveAndCall.json +213 -0
  41. package/src/abis/IMulticallExtended.json +78 -0
  42. package/src/abis/IPeripheryPaymentsWithFeeExtended.json +233 -0
  43. package/src/abis/ISwapRouter02.json +717 -0
  44. package/src/approveAndCall.ts +129 -0
  45. package/src/constants.ts +24 -0
  46. package/src/entities/mixedRoute/route.ts +121 -0
  47. package/src/entities/mixedRoute/trade.ts +530 -0
  48. package/src/entities/protocol.ts +6 -0
  49. package/src/entities/route.ts +94 -0
  50. package/src/entities/trade.ts +550 -0
  51. package/src/index.ts +14 -0
  52. package/src/multicallExtended.ts +48 -0
  53. package/src/paymentsExtended.ts +75 -0
  54. package/src/swapRouter.ts +700 -0
  55. package/src/utils/TPool.ts +5 -0
  56. package/src/utils/encodeMixedRouteToPath.ts +112 -0
  57. package/src/utils/index.ts +66 -0
  58. package/src/utils/pathCurrency.ts +36 -0
@@ -0,0 +1,700 @@
1
+ import { Interface } from '@ethersproject/abi'
2
+ import {
3
+ Currency,
4
+ CurrencyAmount,
5
+ Percent,
6
+ Token,
7
+ TradeType,
8
+ validateAndParseAddress,
9
+ WETH9,
10
+ } from '@centurion_project/sdk-core'
11
+ import ISwapRouter02 from './abis/ISwapRouter02.json'
12
+ import { Trade as V2Trade } from '@centurion_project/v2-sdk'
13
+ import {
14
+ encodeRouteToPath,
15
+ FeeOptions,
16
+ MethodParameters,
17
+ Payments,
18
+ PermitOptions,
19
+ Pool as V3Pool,
20
+ Position,
21
+ SelfPermit,
22
+ toHex,
23
+ Trade as V3Trade,
24
+ } from '@centurion_project/v3-sdk'
25
+ import { Pool as V4Pool } from '@centurion_project/v4-sdk'
26
+ import invariant from 'tiny-invariant'
27
+ import JSBI from 'jsbi'
28
+ import { ADDRESS_THIS, MSG_SENDER } from './constants'
29
+ import { ApproveAndCall, ApprovalTypes, CondensedAddLiquidityOptions } from './approveAndCall'
30
+ import { Trade } from './entities/trade'
31
+ import { Protocol } from './entities/protocol'
32
+ import { MixedRoute, RouteV2, RouteV3 } from './entities/route'
33
+ import { MulticallExtended, Validation } from './multicallExtended'
34
+ import { PaymentsExtended } from './paymentsExtended'
35
+ import { MixedRouteTrade } from './entities/mixedRoute/trade'
36
+ import { encodeMixedRouteToPath } from './utils/encodeMixedRouteToPath'
37
+ import { MixedRouteSDK } from './entities/mixedRoute/route'
38
+ import { partitionMixedRouteByProtocol, getOutputOfPools } from './utils'
39
+
40
+ const ZERO = JSBI.BigInt(0)
41
+ const REFUND_ETH_PRICE_IMPACT_THRESHOLD = new Percent(JSBI.BigInt(50), JSBI.BigInt(100))
42
+
43
+ /**
44
+ * Options for producing the arguments to send calls to the router.
45
+ */
46
+ export interface SwapOptions {
47
+ /**
48
+ * How much the execution price is allowed to move unfavorably from the trade execution price.
49
+ */
50
+ slippageTolerance: Percent
51
+
52
+ /**
53
+ * The account that should receive the output. If omitted, output is sent to msg.sender.
54
+ */
55
+ recipient?: string
56
+
57
+ /**
58
+ * Either deadline (when the transaction expires, in epoch seconds), or previousBlockhash.
59
+ */
60
+ deadlineOrPreviousBlockhash?: Validation
61
+
62
+ /**
63
+ * The optional permit parameters for spending the input.
64
+ */
65
+ inputTokenPermit?: PermitOptions
66
+
67
+ /**
68
+ * Optional information for taking a fee on output.
69
+ */
70
+ fee?: FeeOptions
71
+ }
72
+
73
+ export interface SwapAndAddOptions extends SwapOptions {
74
+ /**
75
+ * The optional permit parameters for pulling in remaining output token.
76
+ */
77
+ outputTokenPermit?: PermitOptions
78
+ }
79
+
80
+ type AnyTradeType =
81
+ | Trade<Currency, Currency, TradeType>
82
+ | V2Trade<Currency, Currency, TradeType>
83
+ | V3Trade<Currency, Currency, TradeType>
84
+ | MixedRouteTrade<Currency, Currency, TradeType>
85
+ | (
86
+ | V2Trade<Currency, Currency, TradeType>
87
+ | V3Trade<Currency, Currency, TradeType>
88
+ | MixedRouteTrade<Currency, Currency, TradeType>
89
+ )[]
90
+
91
+ /**
92
+ * Represents the Uniswap V2 + V3 SwapRouter02, and has static methods for helping execute trades.
93
+ */
94
+ export abstract class SwapRouter {
95
+ public static INTERFACE: Interface = new Interface(ISwapRouter02.abi)
96
+
97
+ /**
98
+ * Cannot be constructed.
99
+ */
100
+ private constructor() {}
101
+
102
+ /**
103
+ * @notice Generates the calldata for a Swap with a V2 Route.
104
+ * @param trade The V2Trade to encode.
105
+ * @param options SwapOptions to use for the trade.
106
+ * @param routerMustCustody Flag for whether funds should be sent to the router
107
+ * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
108
+ * @returns A string array of calldatas for the trade.
109
+ */
110
+ private static encodeV2Swap(
111
+ trade: V2Trade<Currency, Currency, TradeType>,
112
+ options: SwapOptions,
113
+ routerMustCustody: boolean,
114
+ performAggregatedSlippageCheck: boolean
115
+ ): string {
116
+ const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance).quotient)
117
+ const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance).quotient)
118
+
119
+ const path = trade.route.path.map((token) => token.address)
120
+ const recipient = routerMustCustody
121
+ ? ADDRESS_THIS
122
+ : typeof options.recipient === 'undefined'
123
+ ? MSG_SENDER
124
+ : validateAndParseAddress(options.recipient)
125
+
126
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
127
+ const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]
128
+
129
+ return SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams)
130
+ } else {
131
+ const exactOutputParams = [amountOut, amountIn, path, recipient]
132
+
133
+ return SwapRouter.INTERFACE.encodeFunctionData('swapTokensForExactTokens', exactOutputParams)
134
+ }
135
+ }
136
+
137
+ /**
138
+ * @notice Generates the calldata for a Swap with a V3 Route.
139
+ * @param trade The V3Trade to encode.
140
+ * @param options SwapOptions to use for the trade.
141
+ * @param routerMustCustody Flag for whether funds should be sent to the router
142
+ * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
143
+ * @returns A string array of calldatas for the trade.
144
+ */
145
+ private static encodeV3Swap(
146
+ trade: V3Trade<Currency, Currency, TradeType>,
147
+ options: SwapOptions,
148
+ routerMustCustody: boolean,
149
+ performAggregatedSlippageCheck: boolean
150
+ ): string[] {
151
+ const calldatas: string[] = []
152
+
153
+ for (const { route, inputAmount, outputAmount } of trade.swaps) {
154
+ const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)
155
+ const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)
156
+
157
+ // flag for whether the trade is single hop or not
158
+ const singleHop = route.pools.length === 1
159
+
160
+ const recipient = routerMustCustody
161
+ ? ADDRESS_THIS
162
+ : typeof options.recipient === 'undefined'
163
+ ? MSG_SENDER
164
+ : validateAndParseAddress(options.recipient)
165
+
166
+ if (singleHop) {
167
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
168
+ const exactInputSingleParams = {
169
+ tokenIn: route.tokenPath[0].address,
170
+ tokenOut: route.tokenPath[1].address,
171
+ fee: route.pools[0].fee,
172
+ recipient,
173
+ amountIn,
174
+ amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,
175
+ sqrtPriceLimitX96: 0,
176
+ }
177
+
178
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))
179
+ } else {
180
+ const exactOutputSingleParams = {
181
+ tokenIn: route.tokenPath[0].address,
182
+ tokenOut: route.tokenPath[1].address,
183
+ fee: route.pools[0].fee,
184
+ recipient,
185
+ amountOut,
186
+ amountInMaximum: amountIn,
187
+ sqrtPriceLimitX96: 0,
188
+ }
189
+
190
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]))
191
+ }
192
+ } else {
193
+ const path: string = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT)
194
+
195
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
196
+ const exactInputParams = {
197
+ path,
198
+ recipient,
199
+ amountIn,
200
+ amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,
201
+ }
202
+
203
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))
204
+ } else {
205
+ const exactOutputParams = {
206
+ path,
207
+ recipient,
208
+ amountOut,
209
+ amountInMaximum: amountIn,
210
+ }
211
+
212
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]))
213
+ }
214
+ }
215
+ }
216
+
217
+ return calldatas
218
+ }
219
+
220
+ /**
221
+ * @notice Generates the calldata for a MixedRouteSwap. Since single hop routes are not MixedRoutes, we will instead generate
222
+ * them via the existing encodeV3Swap and encodeV2Swap methods.
223
+ * @param trade The MixedRouteTrade to encode.
224
+ * @param options SwapOptions to use for the trade.
225
+ * @param routerMustCustody Flag for whether funds should be sent to the router
226
+ * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check
227
+ * @returns A string array of calldatas for the trade.
228
+ */
229
+ private static encodeMixedRouteSwap(
230
+ trade: MixedRouteTrade<Currency, Currency, TradeType>,
231
+ options: SwapOptions,
232
+ routerMustCustody: boolean,
233
+ performAggregatedSlippageCheck: boolean
234
+ ): string[] {
235
+ const calldatas: string[] = []
236
+
237
+ invariant(trade.tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')
238
+
239
+ for (const { route, inputAmount, outputAmount } of trade.swaps) {
240
+ if (route.pools.some((pool) => pool instanceof V4Pool))
241
+ throw new Error('Encoding mixed routes with V4 not supported')
242
+ const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)
243
+ const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)
244
+
245
+ // flag for whether the trade is single hop or not
246
+ const singleHop = route.pools.length === 1
247
+
248
+ const recipient = routerMustCustody
249
+ ? ADDRESS_THIS
250
+ : typeof options.recipient === 'undefined'
251
+ ? MSG_SENDER
252
+ : validateAndParseAddress(options.recipient)
253
+
254
+ const mixedRouteIsAllV3 = (route: MixedRouteSDK<Currency, Currency>) => {
255
+ return route.pools.every((pool) => pool instanceof V3Pool)
256
+ }
257
+
258
+ if (singleHop) {
259
+ /// For single hop, since it isn't really a mixedRoute, we'll just mimic behavior of V3 or V2
260
+ /// We don't use encodeV3Swap() or encodeV2Swap() because casting the trade to a V3Trade or V2Trade is overcomplex
261
+ if (mixedRouteIsAllV3(route)) {
262
+ const exactInputSingleParams = {
263
+ tokenIn: route.path[0].wrapped.address,
264
+ tokenOut: route.path[1].wrapped.address,
265
+ fee: (route.pools as V3Pool[])[0].fee,
266
+ recipient,
267
+ amountIn,
268
+ amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,
269
+ sqrtPriceLimitX96: 0,
270
+ }
271
+
272
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))
273
+ } else {
274
+ const path = route.path.map((token) => token.wrapped.address)
275
+
276
+ const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]
277
+
278
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))
279
+ }
280
+ } else {
281
+ const sections = partitionMixedRouteByProtocol(route)
282
+
283
+ const isLastSectionInRoute = (i: number) => {
284
+ return i === sections.length - 1
285
+ }
286
+
287
+ let outputToken
288
+ let inputToken = route.input.wrapped
289
+
290
+ for (let i = 0; i < sections.length; i++) {
291
+ const section = sections[i]
292
+ /// Now, we get output of this section
293
+ outputToken = getOutputOfPools(section, inputToken)
294
+
295
+ const newRouteOriginal = new MixedRouteSDK(
296
+ [...section],
297
+ section[0].token0.equals(inputToken) ? section[0].token0 : section[0].token1,
298
+ outputToken
299
+ )
300
+ const newRoute = new MixedRoute(newRouteOriginal)
301
+
302
+ /// Previous output is now input
303
+ inputToken = outputToken.wrapped
304
+
305
+ if (mixedRouteIsAllV3(newRoute)) {
306
+ const path: string = encodeMixedRouteToPath(newRoute)
307
+ const exactInputParams = {
308
+ path,
309
+ // By default router holds funds until the last swap, then it is sent to the recipient
310
+ // special case exists where we are unwrapping WETH output, in which case `routerMustCustody` is set to true
311
+ // and router still holds the funds. That logic bundled into how the value of `recipient` is calculated
312
+ recipient: isLastSectionInRoute(i) ? recipient : ADDRESS_THIS,
313
+ amountIn: i === 0 ? amountIn : 0,
314
+ amountOutMinimum: !isLastSectionInRoute(i) ? 0 : amountOut,
315
+ }
316
+
317
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))
318
+ } else {
319
+ const exactInputParams = [
320
+ i === 0 ? amountIn : 0, // amountIn
321
+ !isLastSectionInRoute(i) ? 0 : amountOut, // amountOutMin
322
+ newRoute.path.map((token) => token.wrapped.address),
323
+ isLastSectionInRoute(i) ? recipient : ADDRESS_THIS, // to
324
+ ]
325
+
326
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))
327
+ }
328
+ }
329
+ }
330
+ }
331
+
332
+ return calldatas
333
+ }
334
+
335
+ private static encodeSwaps(
336
+ trades: AnyTradeType,
337
+ options: SwapOptions,
338
+ isSwapAndAdd?: boolean
339
+ ): {
340
+ calldatas: string[]
341
+ sampleTrade:
342
+ | V2Trade<Currency, Currency, TradeType>
343
+ | V3Trade<Currency, Currency, TradeType>
344
+ | MixedRouteTrade<Currency, Currency, TradeType>
345
+ routerMustCustody: boolean
346
+ inputIsNative: boolean
347
+ outputIsNative: boolean
348
+ totalAmountIn: CurrencyAmount<Currency>
349
+ minimumAmountOut: CurrencyAmount<Currency>
350
+ quoteAmountOut: CurrencyAmount<Currency>
351
+ } {
352
+ // If dealing with an instance of the aggregated Trade object, unbundle it to individual trade objects.
353
+ if (trades instanceof Trade) {
354
+ invariant(
355
+ trades.swaps.every(
356
+ (swap) =>
357
+ swap.route.protocol === Protocol.V3 ||
358
+ swap.route.protocol === Protocol.V2 ||
359
+ swap.route.protocol === Protocol.MIXED
360
+ ),
361
+ 'UNSUPPORTED_PROTOCOL (encoding routes with v4 not supported)'
362
+ )
363
+
364
+ let individualTrades: (
365
+ | V2Trade<Currency, Currency, TradeType>
366
+ | V3Trade<Currency, Currency, TradeType>
367
+ | MixedRouteTrade<Currency, Currency, TradeType>
368
+ )[] = []
369
+
370
+ for (const { route, inputAmount, outputAmount } of trades.swaps) {
371
+ if (route.protocol === Protocol.V2) {
372
+ individualTrades.push(
373
+ new V2Trade(
374
+ route as RouteV2<Currency, Currency>,
375
+ trades.tradeType === TradeType.EXACT_INPUT ? inputAmount : outputAmount,
376
+ trades.tradeType
377
+ )
378
+ )
379
+ } else if (route.protocol === Protocol.V3) {
380
+ individualTrades.push(
381
+ V3Trade.createUncheckedTrade({
382
+ route: route as RouteV3<Currency, Currency>,
383
+ inputAmount,
384
+ outputAmount,
385
+ tradeType: trades.tradeType,
386
+ })
387
+ )
388
+ } else if (route.protocol === Protocol.MIXED) {
389
+ individualTrades.push(
390
+ /// we can change the naming of this function on MixedRouteTrade if needed
391
+ MixedRouteTrade.createUncheckedTrade({
392
+ route: route as MixedRoute<Currency, Currency>,
393
+ inputAmount,
394
+ outputAmount,
395
+ tradeType: trades.tradeType,
396
+ })
397
+ )
398
+ } else {
399
+ throw new Error('UNSUPPORTED_TRADE_PROTOCOL')
400
+ }
401
+ }
402
+ trades = individualTrades
403
+ }
404
+
405
+ if (!Array.isArray(trades)) {
406
+ trades = [trades]
407
+ }
408
+
409
+ const numberOfTrades = trades.reduce(
410
+ (numberOfTrades, trade) =>
411
+ numberOfTrades + (trade instanceof V3Trade || trade instanceof MixedRouteTrade ? trade.swaps.length : 1),
412
+ 0
413
+ )
414
+
415
+ const sampleTrade = trades[0]
416
+
417
+ // All trades should have the same starting/ending currency and trade type
418
+ invariant(
419
+ trades.every((trade) => trade.inputAmount.currency.equals(sampleTrade.inputAmount.currency)),
420
+ 'TOKEN_IN_DIFF'
421
+ )
422
+ invariant(
423
+ trades.every((trade) => trade.outputAmount.currency.equals(sampleTrade.outputAmount.currency)),
424
+ 'TOKEN_OUT_DIFF'
425
+ )
426
+ invariant(
427
+ trades.every((trade) => trade.tradeType === sampleTrade.tradeType),
428
+ 'TRADE_TYPE_DIFF'
429
+ )
430
+
431
+ const calldatas: string[] = []
432
+
433
+ const inputIsNative = sampleTrade.inputAmount.currency.isNative
434
+ const outputIsNative = sampleTrade.outputAmount.currency.isNative
435
+
436
+ // flag for whether we want to perform an aggregated slippage check
437
+ // 1. when there are >2 exact input trades. this is only a heuristic,
438
+ // as it's still more gas-expensive even in this case, but has benefits
439
+ // in that the reversion probability is lower
440
+ const performAggregatedSlippageCheck = sampleTrade.tradeType === TradeType.EXACT_INPUT && numberOfTrades > 2
441
+ // flag for whether funds should be send first to the router
442
+ // 1. when receiving ETH (which much be unwrapped from WETH)
443
+ // 2. when a fee on the output is being taken
444
+ // 3. when performing swap and add
445
+ // 4. when performing an aggregated slippage check
446
+ const routerMustCustody = outputIsNative || !!options.fee || !!isSwapAndAdd || performAggregatedSlippageCheck
447
+
448
+ // encode permit if necessary
449
+ if (options.inputTokenPermit) {
450
+ invariant(sampleTrade.inputAmount.currency.isToken, 'NON_TOKEN_PERMIT')
451
+ calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency as Token, options.inputTokenPermit))
452
+ }
453
+
454
+ for (const trade of trades) {
455
+ if (trade instanceof V2Trade) {
456
+ calldatas.push(SwapRouter.encodeV2Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck))
457
+ } else if (trade instanceof V3Trade) {
458
+ for (const calldata of SwapRouter.encodeV3Swap(
459
+ trade,
460
+ options,
461
+ routerMustCustody,
462
+ performAggregatedSlippageCheck
463
+ )) {
464
+ calldatas.push(calldata)
465
+ }
466
+ } else if (trade instanceof MixedRouteTrade) {
467
+ for (const calldata of SwapRouter.encodeMixedRouteSwap(
468
+ trade,
469
+ options,
470
+ routerMustCustody,
471
+ performAggregatedSlippageCheck
472
+ )) {
473
+ calldatas.push(calldata)
474
+ }
475
+ } else {
476
+ throw new Error('Unsupported trade object')
477
+ }
478
+ }
479
+
480
+ const ZERO_IN: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.inputAmount.currency, 0)
481
+ const ZERO_OUT: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.outputAmount.currency, 0)
482
+
483
+ const minimumAmountOut: CurrencyAmount<Currency> = trades.reduce(
484
+ (sum, trade) => sum.add(trade.minimumAmountOut(options.slippageTolerance)),
485
+ ZERO_OUT
486
+ )
487
+
488
+ const quoteAmountOut: CurrencyAmount<Currency> = trades.reduce(
489
+ (sum, trade) => sum.add(trade.outputAmount),
490
+ ZERO_OUT
491
+ )
492
+
493
+ const totalAmountIn: CurrencyAmount<Currency> = trades.reduce(
494
+ (sum, trade) => sum.add(trade.maximumAmountIn(options.slippageTolerance)),
495
+ ZERO_IN
496
+ )
497
+
498
+ return {
499
+ calldatas,
500
+ sampleTrade,
501
+ routerMustCustody,
502
+ inputIsNative,
503
+ outputIsNative,
504
+ totalAmountIn,
505
+ minimumAmountOut,
506
+ quoteAmountOut,
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
512
+ * @param trades to produce call parameters for
513
+ * @param options options for the call parameters
514
+ */
515
+ public static swapCallParameters(
516
+ trades:
517
+ | Trade<Currency, Currency, TradeType>
518
+ | V2Trade<Currency, Currency, TradeType>
519
+ | V3Trade<Currency, Currency, TradeType>
520
+ | MixedRouteTrade<Currency, Currency, TradeType>
521
+ | (
522
+ | V2Trade<Currency, Currency, TradeType>
523
+ | V3Trade<Currency, Currency, TradeType>
524
+ | MixedRouteTrade<Currency, Currency, TradeType>
525
+ )[],
526
+ options: SwapOptions
527
+ ): MethodParameters {
528
+ const {
529
+ calldatas,
530
+ sampleTrade,
531
+ routerMustCustody,
532
+ inputIsNative,
533
+ outputIsNative,
534
+ totalAmountIn,
535
+ minimumAmountOut,
536
+ } = SwapRouter.encodeSwaps(trades, options)
537
+
538
+ // unwrap or sweep
539
+ if (routerMustCustody) {
540
+ if (outputIsNative) {
541
+ calldatas.push(PaymentsExtended.encodeUnwrapWETH9(minimumAmountOut.quotient, options.recipient, options.fee))
542
+ } else {
543
+ calldatas.push(
544
+ PaymentsExtended.encodeSweepToken(
545
+ sampleTrade.outputAmount.currency.wrapped,
546
+ minimumAmountOut.quotient,
547
+ options.recipient,
548
+ options.fee
549
+ )
550
+ )
551
+ }
552
+ }
553
+
554
+ // must refund when paying in ETH: either with an uncertain input amount OR if there's a chance of a partial fill.
555
+ // unlike ERC20's, the full ETH value must be sent in the transaction, so the rest must be refunded.
556
+ if (inputIsNative && (sampleTrade.tradeType === TradeType.EXACT_OUTPUT || SwapRouter.riskOfPartialFill(trades))) {
557
+ calldatas.push(Payments.encodeRefundETH())
558
+ }
559
+
560
+ return {
561
+ calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),
562
+ value: toHex(inputIsNative ? totalAmountIn.quotient : ZERO),
563
+ }
564
+ }
565
+
566
+ /**
567
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
568
+ * @param trades to produce call parameters for
569
+ * @param options options for the call parameters
570
+ */
571
+ public static swapAndAddCallParameters(
572
+ trades: AnyTradeType,
573
+ options: SwapAndAddOptions,
574
+ position: Position,
575
+ addLiquidityOptions: CondensedAddLiquidityOptions,
576
+ tokenInApprovalType: ApprovalTypes,
577
+ tokenOutApprovalType: ApprovalTypes
578
+ ): MethodParameters {
579
+ const {
580
+ calldatas,
581
+ inputIsNative,
582
+ outputIsNative,
583
+ sampleTrade,
584
+ totalAmountIn: totalAmountSwapped,
585
+ quoteAmountOut,
586
+ minimumAmountOut,
587
+ } = SwapRouter.encodeSwaps(trades, options, true)
588
+
589
+ // encode output token permit if necessary
590
+ if (options.outputTokenPermit) {
591
+ invariant(quoteAmountOut.currency.isToken, 'NON_TOKEN_PERMIT_OUTPUT')
592
+ calldatas.push(SelfPermit.encodePermit(quoteAmountOut.currency as Token, options.outputTokenPermit))
593
+ }
594
+
595
+ const chainId = sampleTrade.route.chainId
596
+ const zeroForOne = position.pool.token0.wrapped.address === totalAmountSwapped.currency.wrapped.address
597
+ const { positionAmountIn, positionAmountOut } = SwapRouter.getPositionAmounts(position, zeroForOne)
598
+
599
+ // if tokens are native they will be converted to WETH9
600
+ const tokenIn = inputIsNative ? WETH9[chainId] : positionAmountIn.currency.wrapped
601
+ const tokenOut = outputIsNative ? WETH9[chainId] : positionAmountOut.currency.wrapped
602
+
603
+ // if swap output does not make up whole outputTokenBalanceDesired, pull in remaining tokens for adding liquidity
604
+ const amountOutRemaining = positionAmountOut.subtract(quoteAmountOut.wrapped)
605
+ if (amountOutRemaining.greaterThan(CurrencyAmount.fromRawAmount(positionAmountOut.currency, 0))) {
606
+ // if output is native, this means the remaining portion is included as native value in the transaction
607
+ // and must be wrapped. Otherwise, pull in remaining ERC20 token.
608
+ outputIsNative
609
+ ? calldatas.push(PaymentsExtended.encodeWrapETH(amountOutRemaining.quotient))
610
+ : calldatas.push(PaymentsExtended.encodePull(tokenOut, amountOutRemaining.quotient))
611
+ }
612
+
613
+ // if input is native, convert to WETH9, else pull ERC20 token
614
+ inputIsNative
615
+ ? calldatas.push(PaymentsExtended.encodeWrapETH(positionAmountIn.quotient))
616
+ : calldatas.push(PaymentsExtended.encodePull(tokenIn, positionAmountIn.quotient))
617
+
618
+ // approve token balances to NFTManager
619
+ if (tokenInApprovalType !== ApprovalTypes.NOT_REQUIRED)
620
+ calldatas.push(ApproveAndCall.encodeApprove(tokenIn, tokenInApprovalType))
621
+ if (tokenOutApprovalType !== ApprovalTypes.NOT_REQUIRED)
622
+ calldatas.push(ApproveAndCall.encodeApprove(tokenOut, tokenOutApprovalType))
623
+
624
+ // represents a position with token amounts resulting from a swap with maximum slippage
625
+ // hence the minimal amount out possible.
626
+ const minimalPosition = Position.fromAmounts({
627
+ pool: position.pool,
628
+ tickLower: position.tickLower,
629
+ tickUpper: position.tickUpper,
630
+ amount0: zeroForOne ? position.amount0.quotient.toString() : minimumAmountOut.quotient.toString(),
631
+ amount1: zeroForOne ? minimumAmountOut.quotient.toString() : position.amount1.quotient.toString(),
632
+ useFullPrecision: false,
633
+ })
634
+
635
+ // encode NFTManager add liquidity
636
+ calldatas.push(
637
+ ApproveAndCall.encodeAddLiquidity(position, minimalPosition, addLiquidityOptions, options.slippageTolerance)
638
+ )
639
+
640
+ // sweep remaining tokens
641
+ inputIsNative
642
+ ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))
643
+ : calldatas.push(PaymentsExtended.encodeSweepToken(tokenIn, ZERO))
644
+ outputIsNative
645
+ ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))
646
+ : calldatas.push(PaymentsExtended.encodeSweepToken(tokenOut, ZERO))
647
+
648
+ let value: JSBI
649
+ if (inputIsNative) {
650
+ value = totalAmountSwapped.wrapped.add(positionAmountIn.wrapped).quotient
651
+ } else if (outputIsNative) {
652
+ value = amountOutRemaining.quotient
653
+ } else {
654
+ value = ZERO
655
+ }
656
+
657
+ return {
658
+ calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),
659
+ value: value.toString(),
660
+ }
661
+ }
662
+
663
+ // if price impact is very high, there's a chance of hitting max/min prices resulting in a partial fill of the swap
664
+ private static riskOfPartialFill(trades: AnyTradeType): boolean {
665
+ if (Array.isArray(trades)) {
666
+ return trades.some((trade) => {
667
+ return SwapRouter.v3TradeWithHighPriceImpact(trade)
668
+ })
669
+ } else {
670
+ return SwapRouter.v3TradeWithHighPriceImpact(trades)
671
+ }
672
+ }
673
+
674
+ private static v3TradeWithHighPriceImpact(
675
+ trade:
676
+ | Trade<Currency, Currency, TradeType>
677
+ | V2Trade<Currency, Currency, TradeType>
678
+ | V3Trade<Currency, Currency, TradeType>
679
+ | MixedRouteTrade<Currency, Currency, TradeType>
680
+ ): boolean {
681
+ return !(trade instanceof V2Trade) && trade.priceImpact.greaterThan(REFUND_ETH_PRICE_IMPACT_THRESHOLD)
682
+ }
683
+
684
+ private static getPositionAmounts(
685
+ position: Position,
686
+ zeroForOne: boolean
687
+ ): {
688
+ positionAmountIn: CurrencyAmount<Currency>
689
+ positionAmountOut: CurrencyAmount<Currency>
690
+ } {
691
+ const { amount0, amount1 } = position.mintAmounts
692
+ const currencyAmount0 = CurrencyAmount.fromRawAmount(position.pool.token0, amount0)
693
+ const currencyAmount1 = CurrencyAmount.fromRawAmount(position.pool.token1, amount1)
694
+
695
+ const [positionAmountIn, positionAmountOut] = zeroForOne
696
+ ? [currencyAmount0, currencyAmount1]
697
+ : [currencyAmount1, currencyAmount0]
698
+ return { positionAmountIn, positionAmountOut }
699
+ }
700
+ }
@@ -0,0 +1,5 @@
1
+ import { Pool as V4Pool } from '@centurion_project/v4-sdk'
2
+ import { Pair } from '@centurion_project/v2-sdk'
3
+ import { Pool as V3Pool } from '@centurion_project/v3-sdk'
4
+
5
+ export type TPool = Pair | V3Pool | V4Pool