@sun-protocol/sun-sdk-sunswap-v3 0.1.0-beta.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,3024 @@
1
+ // src/actions.ts
2
+ import { getContractAddress } from "@sun-protocol/sun-sdk-chains";
3
+ import {
4
+ assertTronAddress,
5
+ createContractCallAction
6
+ } from "@sun-protocol/sun-sdk-core";
7
+ import JSBI from "jsbi";
8
+ var V3_POSITION_MANAGER_SELECTORS = {
9
+ createAndInitializePoolIfNecessary: "createAndInitializePoolIfNecessary(address,address,uint24,uint160)",
10
+ mint: "mint((address,address,uint24,int24,int24,uint256,uint256,uint256,uint256,address,uint256))",
11
+ increaseLiquidity: "increaseLiquidity((uint256,uint256,uint256,uint256,uint256,uint256))",
12
+ decreaseLiquidity: "decreaseLiquidity((uint256,uint128,uint256,uint256,uint256))",
13
+ collect: "collect((uint256,address,uint128,uint128))"
14
+ };
15
+ var MaxUint128 = JSBI.subtract(JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(128)), JSBI.BigInt(1));
16
+ function positionManagerTarget(params) {
17
+ return params.positionManager ?? getContractAddress(params.network, "sunswapV3PositionManager");
18
+ }
19
+ function valueOf(value) {
20
+ return JSBI.BigInt(value).toString();
21
+ }
22
+ function actionId(params, suffix) {
23
+ return params.id ?? `sunswap-v3-${suffix}-${params.network}`;
24
+ }
25
+ function buildV3CreatePoolAction(params) {
26
+ return createContractCallAction({
27
+ id: actionId(params, "create-pool"),
28
+ target: positionManagerTarget(params),
29
+ functionSelector: V3_POSITION_MANAGER_SELECTORS.createAndInitializePoolIfNecessary,
30
+ parameters: [
31
+ { type: "address", value: params.pool.token0.address },
32
+ { type: "address", value: params.pool.token1.address },
33
+ { type: "uint24", value: params.pool.fee },
34
+ { type: "uint160", value: params.pool.sqrtRatioX96.toString() }
35
+ ],
36
+ ...params.feeLimit !== void 0 ? { feeLimit: params.feeLimit } : {}
37
+ });
38
+ }
39
+ function buildV3MintPositionAction(params) {
40
+ const { amount0: amount0Desired, amount1: amount1Desired } = params.position.mintAmounts;
41
+ return createContractCallAction({
42
+ id: actionId(params, "mint"),
43
+ target: positionManagerTarget(params),
44
+ functionSelector: V3_POSITION_MANAGER_SELECTORS.mint,
45
+ parameters: [
46
+ {
47
+ type: "tuple",
48
+ value: {
49
+ token0: params.position.pool.token0.address,
50
+ token1: params.position.pool.token1.address,
51
+ fee: params.position.pool.fee,
52
+ tickLower: params.position.tickLower,
53
+ tickUpper: params.position.tickUpper,
54
+ amount0Desired: amount0Desired.toString(),
55
+ amount1Desired: amount1Desired.toString(),
56
+ amount0Min: valueOf(params.amount0Min),
57
+ amount1Min: valueOf(params.amount1Min),
58
+ recipient: assertTronAddress(params.recipient),
59
+ deadline: valueOf(params.deadline)
60
+ }
61
+ }
62
+ ],
63
+ ...params.feeLimit !== void 0 ? { feeLimit: params.feeLimit } : {}
64
+ });
65
+ }
66
+ function buildV3IncreaseLiquidityAction(params) {
67
+ const { amount0: amount0Desired, amount1: amount1Desired } = params.position.mintAmounts;
68
+ return createContractCallAction({
69
+ id: actionId(params, "increase-liquidity"),
70
+ target: positionManagerTarget(params),
71
+ functionSelector: V3_POSITION_MANAGER_SELECTORS.increaseLiquidity,
72
+ parameters: [
73
+ {
74
+ type: "tuple",
75
+ value: {
76
+ tokenId: valueOf(params.tokenId),
77
+ amount0Desired: amount0Desired.toString(),
78
+ amount1Desired: amount1Desired.toString(),
79
+ amount0Min: valueOf(params.amount0Min),
80
+ amount1Min: valueOf(params.amount1Min),
81
+ deadline: valueOf(params.deadline)
82
+ }
83
+ }
84
+ ],
85
+ ...params.feeLimit !== void 0 ? { feeLimit: params.feeLimit } : {}
86
+ });
87
+ }
88
+ function buildV3DecreaseLiquidityAction(params) {
89
+ return createContractCallAction({
90
+ id: actionId(params, "decrease-liquidity"),
91
+ target: positionManagerTarget(params),
92
+ functionSelector: V3_POSITION_MANAGER_SELECTORS.decreaseLiquidity,
93
+ parameters: [
94
+ {
95
+ type: "tuple",
96
+ value: {
97
+ tokenId: valueOf(params.tokenId),
98
+ liquidity: valueOf(params.liquidity),
99
+ amount0Min: valueOf(params.amount0Min),
100
+ amount1Min: valueOf(params.amount1Min),
101
+ deadline: valueOf(params.deadline)
102
+ }
103
+ }
104
+ ],
105
+ ...params.feeLimit !== void 0 ? { feeLimit: params.feeLimit } : {}
106
+ });
107
+ }
108
+ function buildV3CollectAction(params) {
109
+ return createContractCallAction({
110
+ id: actionId(params, "collect"),
111
+ target: positionManagerTarget(params),
112
+ functionSelector: V3_POSITION_MANAGER_SELECTORS.collect,
113
+ parameters: [
114
+ {
115
+ type: "tuple",
116
+ value: {
117
+ tokenId: valueOf(params.tokenId),
118
+ recipient: assertTronAddress(params.recipient),
119
+ amount0Max: valueOf(params.amount0Max ?? MaxUint128),
120
+ amount1Max: valueOf(params.amount1Max ?? MaxUint128)
121
+ }
122
+ }
123
+ ],
124
+ ...params.feeLimit !== void 0 ? { feeLimit: params.feeLimit } : {}
125
+ });
126
+ }
127
+
128
+ // src/abi.ts
129
+ var V3_POOL_SLOT0_ABI = {
130
+ type: "function",
131
+ name: "slot0",
132
+ stateMutability: "view",
133
+ inputs: [],
134
+ outputs: [
135
+ { name: "sqrtPriceX96", type: "uint160" },
136
+ { name: "tick", type: "int24" },
137
+ { name: "observationIndex", type: "uint16" },
138
+ { name: "observationCardinality", type: "uint16" },
139
+ { name: "observationCardinalityNext", type: "uint16" },
140
+ { name: "feeProtocol", type: "uint8" },
141
+ { name: "unlocked", type: "bool" }
142
+ ]
143
+ };
144
+ var V3_POOL_LIQUIDITY_ABI = {
145
+ type: "function",
146
+ name: "liquidity",
147
+ stateMutability: "view",
148
+ inputs: [],
149
+ outputs: [{ type: "uint128" }]
150
+ };
151
+ var V3_POOL_FEE_ABI = {
152
+ type: "function",
153
+ name: "fee",
154
+ stateMutability: "view",
155
+ inputs: [],
156
+ outputs: [{ type: "uint24" }]
157
+ };
158
+ var V3_POOL_TICK_SPACING_ABI = {
159
+ type: "function",
160
+ name: "tickSpacing",
161
+ stateMutability: "view",
162
+ inputs: [],
163
+ outputs: [{ type: "int24" }]
164
+ };
165
+ var V3_POSITION_MANAGER_POSITIONS_ABI = {
166
+ type: "function",
167
+ name: "positions",
168
+ stateMutability: "view",
169
+ inputs: [{ name: "tokenId", type: "uint256" }],
170
+ outputs: [
171
+ { name: "nonce", type: "uint96" },
172
+ { name: "operator", type: "address" },
173
+ { name: "token0", type: "address" },
174
+ { name: "token1", type: "address" },
175
+ { name: "fee", type: "uint24" },
176
+ { name: "tickLower", type: "int24" },
177
+ { name: "tickUpper", type: "int24" },
178
+ { name: "liquidity", type: "uint128" },
179
+ { name: "feeGrowthInside0LastX128", type: "uint256" },
180
+ { name: "feeGrowthInside1LastX128", type: "uint256" },
181
+ { name: "tokensOwed0", type: "uint128" },
182
+ { name: "tokensOwed1", type: "uint128" }
183
+ ]
184
+ };
185
+ var V3_POSITION_MANAGER_OWNER_OF_ABI = {
186
+ type: "function",
187
+ name: "ownerOf",
188
+ stateMutability: "view",
189
+ inputs: [{ name: "tokenId", type: "uint256" }],
190
+ outputs: [{ type: "address" }]
191
+ };
192
+ var V3_POSITION_MANAGER_GET_APPROVED_ABI = {
193
+ type: "function",
194
+ name: "getApproved",
195
+ stateMutability: "view",
196
+ inputs: [{ name: "tokenId", type: "uint256" }],
197
+ outputs: [{ type: "address" }]
198
+ };
199
+ var V3_POSITION_MANAGER_IS_APPROVED_FOR_ALL_ABI = {
200
+ type: "function",
201
+ name: "isApprovedForAll",
202
+ stateMutability: "view",
203
+ inputs: [
204
+ { name: "owner", type: "address" },
205
+ { name: "operator", type: "address" }
206
+ ],
207
+ outputs: [{ type: "bool" }]
208
+ };
209
+
210
+ // src/constants.ts
211
+ var IS_TVM = true;
212
+ var FACTORY_ADDRESS = "0xc2708485c99cd8cf058de1a9a7e3c2d8261a995c";
213
+ var ADDRESS_ZERO = "0x0000000000000000000000000000000000000000";
214
+ var POOL_INIT_CODE_HASH = "0xba928a717d71946d75999ef1adef801a79cd34a20efecea8b2876b85f5f49580";
215
+ var FeeAmount = /* @__PURE__ */ ((FeeAmount2) => {
216
+ FeeAmount2[FeeAmount2["LOWEST"] = 100] = "LOWEST";
217
+ FeeAmount2[FeeAmount2["LOW"] = 500] = "LOW";
218
+ FeeAmount2[FeeAmount2["MEDIUM"] = 3e3] = "MEDIUM";
219
+ FeeAmount2[FeeAmount2["HIGH"] = 1e4] = "HIGH";
220
+ return FeeAmount2;
221
+ })(FeeAmount || {});
222
+ var TICK_SPACINGS = {
223
+ [100 /* LOWEST */]: 1,
224
+ [500 /* LOW */]: 10,
225
+ [3e3 /* MEDIUM */]: 60,
226
+ [1e4 /* HIGH */]: 200
227
+ };
228
+
229
+ // src/entities/pool.ts
230
+ import { CurrencyAmount, Price as Price2, Token } from "@sun-protocol/sun-sdk-core";
231
+ import JSBI17 from "jsbi";
232
+ import invariant7 from "tiny-invariant";
233
+
234
+ // src/internal-constants.ts
235
+ import JSBI2 from "jsbi";
236
+ var NEGATIVE_ONE = JSBI2.BigInt(-1);
237
+ var ZERO = JSBI2.BigInt(0);
238
+ var ONE = JSBI2.BigInt(1);
239
+ var Q96 = JSBI2.exponentiate(JSBI2.BigInt(2), JSBI2.BigInt(96));
240
+ var Q192 = JSBI2.exponentiate(Q96, JSBI2.BigInt(2));
241
+
242
+ // src/utils/computePoolAddress.ts
243
+ import { defaultAbiCoder } from "@ethersproject/abi";
244
+ import { getCreate2Address } from "@ethersproject/address";
245
+ import { keccak256 as keccak2562 } from "@ethersproject/solidity";
246
+
247
+ // src/utils/computeTronPoolAddress.ts
248
+ import { getAddress } from "@ethersproject/address";
249
+ import { concat, hexDataLength, hexDataSlice } from "@ethersproject/bytes";
250
+ import { keccak256 } from "@ethersproject/keccak256";
251
+ import { Logger } from "@ethersproject/logger";
252
+ var logger = new Logger("");
253
+ function getTronCreate2Address(from, salt, initCodeHash) {
254
+ if (hexDataLength(salt) !== 32) {
255
+ logger.throwArgumentError("salt must be 32 bytes", "salt", salt);
256
+ }
257
+ if (hexDataLength(initCodeHash) !== 32) {
258
+ logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash);
259
+ }
260
+ return getAddress(hexDataSlice(keccak256(concat(["0x41", getAddress(from), salt, initCodeHash])), 12));
261
+ }
262
+
263
+ // src/utils/computePoolAddress.ts
264
+ function computePoolAddress({
265
+ factoryAddress,
266
+ tokenA,
267
+ tokenB,
268
+ fee,
269
+ initCodeHashManualOverride
270
+ }) {
271
+ const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
272
+ if (IS_TVM) {
273
+ return getTronCreate2Address(
274
+ factoryAddress,
275
+ keccak2562(
276
+ ["bytes"],
277
+ [defaultAbiCoder.encode(["address", "address", "uint24"], [token0.address, token1.address, fee])]
278
+ ),
279
+ initCodeHashManualOverride ?? POOL_INIT_CODE_HASH
280
+ );
281
+ } else {
282
+ return getCreate2Address(
283
+ factoryAddress,
284
+ keccak2562(
285
+ ["bytes"],
286
+ [defaultAbiCoder.encode(["address", "address", "uint24"], [token0.address, token1.address, fee])]
287
+ ),
288
+ initCodeHashManualOverride ?? POOL_INIT_CODE_HASH
289
+ );
290
+ }
291
+ }
292
+
293
+ // src/utils/liquidityMath.ts
294
+ import JSBI3 from "jsbi";
295
+ var LiquidityMath = class {
296
+ /**
297
+ * Cannot be constructed.
298
+ */
299
+ constructor() {
300
+ }
301
+ static addDelta(x, y) {
302
+ if (JSBI3.lessThan(y, ZERO)) {
303
+ return JSBI3.subtract(x, JSBI3.multiply(y, NEGATIVE_ONE));
304
+ } else {
305
+ return JSBI3.add(x, y);
306
+ }
307
+ }
308
+ };
309
+
310
+ // src/utils/swapMath.ts
311
+ import JSBI6 from "jsbi";
312
+
313
+ // src/utils/full-math.ts
314
+ import JSBI4 from "jsbi";
315
+ var FullMath = class {
316
+ constructor() {
317
+ }
318
+ static mulDivRoundingUp(a, b, denominator) {
319
+ const product = JSBI4.multiply(a, b);
320
+ let result = JSBI4.divide(product, denominator);
321
+ if (JSBI4.notEqual(JSBI4.remainder(product, denominator), ZERO)) result = JSBI4.add(result, ONE);
322
+ return result;
323
+ }
324
+ };
325
+
326
+ // src/utils/sqrt-price-math.ts
327
+ import { MaxUint256 } from "@sun-protocol/sun-sdk-core";
328
+ import JSBI5 from "jsbi";
329
+ import invariant from "tiny-invariant";
330
+ var MaxUint160 = JSBI5.subtract(JSBI5.exponentiate(JSBI5.BigInt(2), JSBI5.BigInt(160)), ONE);
331
+ function multiplyIn256(x, y) {
332
+ const product = JSBI5.multiply(x, y);
333
+ return JSBI5.bitwiseAnd(product, MaxUint256);
334
+ }
335
+ function addIn256(x, y) {
336
+ const sum = JSBI5.add(x, y);
337
+ return JSBI5.bitwiseAnd(sum, MaxUint256);
338
+ }
339
+ var SqrtPriceMath = class {
340
+ constructor() {
341
+ }
342
+ static getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
343
+ if (JSBI5.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
344
+ ;
345
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
346
+ }
347
+ const numerator1 = JSBI5.leftShift(liquidity, JSBI5.BigInt(96));
348
+ const numerator2 = JSBI5.subtract(sqrtRatioBX96, sqrtRatioAX96);
349
+ return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : JSBI5.divide(JSBI5.divide(JSBI5.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96);
350
+ }
351
+ static getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
352
+ if (JSBI5.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
353
+ ;
354
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
355
+ }
356
+ return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI5.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI5.divide(JSBI5.multiply(liquidity, JSBI5.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96);
357
+ }
358
+ static getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
359
+ invariant(JSBI5.greaterThan(sqrtPX96, ZERO));
360
+ invariant(JSBI5.greaterThan(liquidity, ZERO));
361
+ return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
362
+ }
363
+ static getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
364
+ invariant(JSBI5.greaterThan(sqrtPX96, ZERO));
365
+ invariant(JSBI5.greaterThan(liquidity, ZERO));
366
+ return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
367
+ }
368
+ static getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
369
+ if (JSBI5.equal(amount, ZERO)) return sqrtPX96;
370
+ const numerator1 = JSBI5.leftShift(liquidity, JSBI5.BigInt(96));
371
+ if (add) {
372
+ const product2 = multiplyIn256(amount, sqrtPX96);
373
+ if (JSBI5.equal(JSBI5.divide(product2, amount), sqrtPX96)) {
374
+ const denominator2 = addIn256(numerator1, product2);
375
+ if (JSBI5.greaterThanOrEqual(denominator2, numerator1)) {
376
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator2);
377
+ }
378
+ }
379
+ return FullMath.mulDivRoundingUp(numerator1, ONE, JSBI5.add(JSBI5.divide(numerator1, sqrtPX96), amount));
380
+ }
381
+ const product = multiplyIn256(amount, sqrtPX96);
382
+ invariant(JSBI5.equal(JSBI5.divide(product, amount), sqrtPX96));
383
+ invariant(JSBI5.greaterThan(numerator1, product));
384
+ const denominator = JSBI5.subtract(numerator1, product);
385
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
386
+ }
387
+ static getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
388
+ if (add) {
389
+ const quotient2 = JSBI5.lessThanOrEqual(amount, MaxUint160) ? JSBI5.divide(JSBI5.leftShift(amount, JSBI5.BigInt(96)), liquidity) : JSBI5.divide(JSBI5.multiply(amount, Q96), liquidity);
390
+ return JSBI5.add(sqrtPX96, quotient2);
391
+ }
392
+ const quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
393
+ invariant(JSBI5.greaterThan(sqrtPX96, quotient));
394
+ return JSBI5.subtract(sqrtPX96, quotient);
395
+ }
396
+ };
397
+
398
+ // src/utils/swapMath.ts
399
+ var MAX_FEE = JSBI6.exponentiate(JSBI6.BigInt(10), JSBI6.BigInt(6));
400
+ var SwapMath = class {
401
+ /**
402
+ * Cannot be constructed.
403
+ */
404
+ constructor() {
405
+ }
406
+ static computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) {
407
+ const returnValues = {};
408
+ const zeroForOne = JSBI6.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96);
409
+ const exactIn = JSBI6.greaterThanOrEqual(amountRemaining, ZERO);
410
+ if (exactIn) {
411
+ const amountRemainingLessFee = JSBI6.divide(
412
+ JSBI6.multiply(amountRemaining, JSBI6.subtract(MAX_FEE, JSBI6.BigInt(feePips))),
413
+ MAX_FEE
414
+ );
415
+ returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
416
+ if (JSBI6.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) {
417
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
418
+ } else {
419
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
420
+ sqrtRatioCurrentX96,
421
+ liquidity,
422
+ amountRemainingLessFee,
423
+ zeroForOne
424
+ );
425
+ }
426
+ } else {
427
+ returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
428
+ if (JSBI6.greaterThanOrEqual(JSBI6.multiply(amountRemaining, NEGATIVE_ONE), returnValues.amountOut)) {
429
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
430
+ } else {
431
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
432
+ sqrtRatioCurrentX96,
433
+ liquidity,
434
+ JSBI6.multiply(amountRemaining, NEGATIVE_ONE),
435
+ zeroForOne
436
+ );
437
+ }
438
+ }
439
+ const max = JSBI6.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96);
440
+ if (zeroForOne) {
441
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
442
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
443
+ } else {
444
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true);
445
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false);
446
+ }
447
+ if (!exactIn && JSBI6.greaterThan(returnValues.amountOut, JSBI6.multiply(amountRemaining, NEGATIVE_ONE))) {
448
+ returnValues.amountOut = JSBI6.multiply(amountRemaining, NEGATIVE_ONE);
449
+ }
450
+ if (exactIn && JSBI6.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) {
451
+ returnValues.feeAmount = JSBI6.subtract(amountRemaining, returnValues.amountIn);
452
+ } else {
453
+ returnValues.feeAmount = FullMath.mulDivRoundingUp(
454
+ returnValues.amountIn,
455
+ JSBI6.BigInt(feePips),
456
+ JSBI6.subtract(MAX_FEE, JSBI6.BigInt(feePips))
457
+ );
458
+ }
459
+ return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
460
+ }
461
+ };
462
+
463
+ // src/utils/tick-math.ts
464
+ import { MaxUint256 as MaxUint2562 } from "@sun-protocol/sun-sdk-core";
465
+ import JSBI8 from "jsbi";
466
+ import invariant3 from "tiny-invariant";
467
+
468
+ // src/utils/most-significant-bit.ts
469
+ import JSBI7 from "jsbi";
470
+ import invariant2 from "tiny-invariant";
471
+ var MAX_SAFE_INTEGER = JSBI7.BigInt(Number.MAX_SAFE_INTEGER);
472
+ function invariantSafeInteger(value) {
473
+ invariant2(Number.isSafeInteger(value), "NUMERIC_FAULT");
474
+ }
475
+ function mostSignificantBit(x) {
476
+ invariant2(JSBI7.greaterThan(x, JSBI7.BigInt(0)), "ZERO");
477
+ invariant2(JSBI7.lessThanOrEqual(x, JSBI7.exponentiate(JSBI7.BigInt(2), JSBI7.BigInt(256))), "MAX");
478
+ let msb = 0;
479
+ for (const [power, min] of [
480
+ [128, "0x100000000000000000000000000000000"],
481
+ [64, "0x10000000000000000"],
482
+ [32, "0x100000000"],
483
+ [16, "0x10000"],
484
+ [8, "0x100"],
485
+ [4, "0x10"],
486
+ [2, "0x4"],
487
+ [1, "0x2"]
488
+ ]) {
489
+ if (JSBI7.greaterThanOrEqual(x, JSBI7.BigInt(min))) {
490
+ x = JSBI7.signedRightShift(x, JSBI7.BigInt(power));
491
+ msb += power;
492
+ }
493
+ }
494
+ invariantSafeInteger(msb);
495
+ invariant2(JSBI7.lessThanOrEqual(JSBI7.BigInt(msb), MAX_SAFE_INTEGER), "NUMERIC_FAULT");
496
+ return msb;
497
+ }
498
+
499
+ // src/utils/tick-math.ts
500
+ function mulShift(value, multiplier) {
501
+ return JSBI8.signedRightShift(JSBI8.multiply(value, JSBI8.BigInt(multiplier)), JSBI8.BigInt(128));
502
+ }
503
+ var Q32 = JSBI8.exponentiate(JSBI8.BigInt(2), JSBI8.BigInt(32));
504
+ var TickMath = class _TickMath {
505
+ constructor() {
506
+ }
507
+ static MIN_TICK = -887272;
508
+ static MAX_TICK = -_TickMath.MIN_TICK;
509
+ static MIN_SQRT_RATIO = JSBI8.BigInt("4295128739");
510
+ static MAX_SQRT_RATIO = JSBI8.BigInt("1461446703485210103287273052203988822378723970342");
511
+ static getSqrtRatioAtTick(tick) {
512
+ invariant3(tick >= _TickMath.MIN_TICK && tick <= _TickMath.MAX_TICK && Number.isInteger(tick), "TICK");
513
+ const absTick = tick < 0 ? tick * -1 : tick;
514
+ let ratio = (absTick & 1) !== 0 ? JSBI8.BigInt("0xfffcb933bd6fad37aa2d162d1a594001") : JSBI8.BigInt("0x100000000000000000000000000000000");
515
+ if ((absTick & 2) !== 0) ratio = mulShift(ratio, "0xfff97272373d413259a46990580e213a");
516
+ if ((absTick & 4) !== 0) ratio = mulShift(ratio, "0xfff2e50f5f656932ef12357cf3c7fdcc");
517
+ if ((absTick & 8) !== 0) ratio = mulShift(ratio, "0xffe5caca7e10e4e61c3624eaa0941cd0");
518
+ if ((absTick & 16) !== 0) ratio = mulShift(ratio, "0xffcb9843d60f6159c9db58835c926644");
519
+ if ((absTick & 32) !== 0) ratio = mulShift(ratio, "0xff973b41fa98c081472e6896dfb254c0");
520
+ if ((absTick & 64) !== 0) ratio = mulShift(ratio, "0xff2ea16466c96a3843ec78b326b52861");
521
+ if ((absTick & 128) !== 0) ratio = mulShift(ratio, "0xfe5dee046a99a2a811c461f1969c3053");
522
+ if ((absTick & 256) !== 0) ratio = mulShift(ratio, "0xfcbe86c7900a88aedcffc83b479aa3a4");
523
+ if ((absTick & 512) !== 0) ratio = mulShift(ratio, "0xf987a7253ac413176f2b074cf7815e54");
524
+ if ((absTick & 1024) !== 0) ratio = mulShift(ratio, "0xf3392b0822b70005940c7a398e4b70f3");
525
+ if ((absTick & 2048) !== 0) ratio = mulShift(ratio, "0xe7159475a2c29b7443b29c7fa6e889d9");
526
+ if ((absTick & 4096) !== 0) ratio = mulShift(ratio, "0xd097f3bdfd2022b8845ad8f792aa5825");
527
+ if ((absTick & 8192) !== 0) ratio = mulShift(ratio, "0xa9f746462d870fdf8a65dc1f90e061e5");
528
+ if ((absTick & 16384) !== 0) ratio = mulShift(ratio, "0x70d869a156d2a1b890bb3df62baf32f7");
529
+ if ((absTick & 32768) !== 0) ratio = mulShift(ratio, "0x31be135f97d08fd981231505542fcfa6");
530
+ if ((absTick & 65536) !== 0) ratio = mulShift(ratio, "0x9aa508b5b7a84e1c677de54f3e99bc9");
531
+ if ((absTick & 131072) !== 0) ratio = mulShift(ratio, "0x5d6af8dedb81196699c329225ee604");
532
+ if ((absTick & 262144) !== 0) ratio = mulShift(ratio, "0x2216e584f5fa1ea926041bedfe98");
533
+ if ((absTick & 524288) !== 0) ratio = mulShift(ratio, "0x48a170391f7dc42444e8fa2");
534
+ if (tick > 0) ratio = JSBI8.divide(MaxUint2562, ratio);
535
+ return JSBI8.greaterThan(JSBI8.remainder(ratio, Q32), ZERO) ? JSBI8.add(JSBI8.divide(ratio, Q32), ONE) : JSBI8.divide(ratio, Q32);
536
+ }
537
+ static getTickAtSqrtRatio(sqrtRatioX96) {
538
+ invariant3(
539
+ JSBI8.greaterThanOrEqual(sqrtRatioX96, _TickMath.MIN_SQRT_RATIO) && JSBI8.lessThan(sqrtRatioX96, _TickMath.MAX_SQRT_RATIO),
540
+ "SQRT_RATIO"
541
+ );
542
+ const sqrtRatioX128 = JSBI8.leftShift(sqrtRatioX96, JSBI8.BigInt(32));
543
+ const msb = mostSignificantBit(sqrtRatioX128);
544
+ let r;
545
+ if (JSBI8.greaterThanOrEqual(JSBI8.BigInt(msb), JSBI8.BigInt(128))) {
546
+ r = JSBI8.signedRightShift(sqrtRatioX128, JSBI8.BigInt(msb - 127));
547
+ } else {
548
+ r = JSBI8.leftShift(sqrtRatioX128, JSBI8.BigInt(127 - msb));
549
+ }
550
+ let log2 = JSBI8.leftShift(JSBI8.subtract(JSBI8.BigInt(msb), JSBI8.BigInt(128)), JSBI8.BigInt(64));
551
+ for (let i = 0; i < 14; i++) {
552
+ r = JSBI8.signedRightShift(JSBI8.multiply(r, r), JSBI8.BigInt(127));
553
+ const f = JSBI8.signedRightShift(r, JSBI8.BigInt(128));
554
+ log2 = JSBI8.bitwiseOr(log2, JSBI8.leftShift(f, JSBI8.BigInt(63 - i)));
555
+ r = JSBI8.signedRightShift(r, f);
556
+ }
557
+ const logSqrt10001 = JSBI8.multiply(log2, JSBI8.BigInt("255738958999603826347141"));
558
+ const tickLow = JSBI8.toNumber(
559
+ JSBI8.signedRightShift(
560
+ JSBI8.subtract(logSqrt10001, JSBI8.BigInt("3402992956809132418596140100660247210")),
561
+ JSBI8.BigInt(128)
562
+ )
563
+ );
564
+ const tickHigh = JSBI8.toNumber(
565
+ JSBI8.signedRightShift(
566
+ JSBI8.add(logSqrt10001, JSBI8.BigInt("291339464771989622907027621153398088495")),
567
+ JSBI8.BigInt(128)
568
+ )
569
+ );
570
+ return tickLow === tickHigh ? tickLow : JSBI8.lessThanOrEqual(_TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow;
571
+ }
572
+ };
573
+
574
+ // src/entities/tickDataProvider.ts
575
+ var NoTickDataProvider = class _NoTickDataProvider {
576
+ static ERROR_MESSAGE = "No tick data provider was given";
577
+ async getTick(_tick) {
578
+ throw new Error(_NoTickDataProvider.ERROR_MESSAGE);
579
+ }
580
+ async nextInitializedTickWithinOneWord(_tick, _lte, _tickSpacing) {
581
+ throw new Error(_NoTickDataProvider.ERROR_MESSAGE);
582
+ }
583
+ };
584
+
585
+ // src/utils/tickList.ts
586
+ import JSBI9 from "jsbi";
587
+ import invariant4 from "tiny-invariant";
588
+
589
+ // src/utils/isSorted.ts
590
+ function isSorted(list, comparator) {
591
+ for (let i = 0; i < list.length - 1; i++) {
592
+ if (comparator(list[i], list[i + 1]) > 0) {
593
+ return false;
594
+ }
595
+ }
596
+ return true;
597
+ }
598
+
599
+ // src/utils/tickList.ts
600
+ function tickComparator(a, b) {
601
+ return a.index - b.index;
602
+ }
603
+ var TickList = class _TickList {
604
+ /**
605
+ * Cannot be constructed
606
+ */
607
+ constructor() {
608
+ }
609
+ static validateList(ticks, tickSpacing) {
610
+ invariant4(tickSpacing > 0, "TICK_SPACING_NONZERO");
611
+ invariant4(
612
+ ticks.every(({ index }) => index % tickSpacing === 0),
613
+ "TICK_SPACING"
614
+ );
615
+ invariant4(
616
+ JSBI9.equal(
617
+ ticks.reduce((accumulator, { liquidityNet }) => JSBI9.add(accumulator, liquidityNet), ZERO),
618
+ ZERO
619
+ ),
620
+ "ZERO_NET"
621
+ );
622
+ invariant4(isSorted(ticks, tickComparator), "SORTED");
623
+ }
624
+ static isBelowSmallest(ticks, tick) {
625
+ invariant4(ticks.length > 0, "LENGTH");
626
+ return tick < ticks[0].index;
627
+ }
628
+ static isAtOrAboveLargest(ticks, tick) {
629
+ invariant4(ticks.length > 0, "LENGTH");
630
+ return tick >= ticks[ticks.length - 1].index;
631
+ }
632
+ static getTick(ticks, index) {
633
+ const tick = ticks[this.binarySearch(ticks, index)];
634
+ invariant4(tick.index === index, "NOT_CONTAINED");
635
+ return tick;
636
+ }
637
+ /**
638
+ * Finds the largest tick in the list of ticks that is less than or equal to tick
639
+ * @param ticks list of ticks
640
+ * @param tick tick to find the largest tick that is less than or equal to tick
641
+ * @private
642
+ */
643
+ static binarySearch(ticks, tick) {
644
+ invariant4(!this.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
645
+ let l = 0;
646
+ let r = ticks.length - 1;
647
+ let i;
648
+ while (true) {
649
+ i = Math.floor((l + r) / 2);
650
+ if (ticks[i].index <= tick && (i === ticks.length - 1 || ticks[i + 1].index > tick)) {
651
+ return i;
652
+ }
653
+ if (ticks[i].index < tick) {
654
+ l = i + 1;
655
+ } else {
656
+ r = i - 1;
657
+ }
658
+ }
659
+ }
660
+ static nextInitializedTick(ticks, tick, lte) {
661
+ if (lte) {
662
+ invariant4(!_TickList.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
663
+ if (_TickList.isAtOrAboveLargest(ticks, tick)) {
664
+ return ticks[ticks.length - 1];
665
+ }
666
+ const index = this.binarySearch(ticks, tick);
667
+ return ticks[index];
668
+ } else {
669
+ invariant4(!this.isAtOrAboveLargest(ticks, tick), "AT_OR_ABOVE_LARGEST");
670
+ if (this.isBelowSmallest(ticks, tick)) {
671
+ return ticks[0];
672
+ }
673
+ const index = this.binarySearch(ticks, tick);
674
+ return ticks[index + 1];
675
+ }
676
+ }
677
+ static nextInitializedTickWithinOneWord(ticks, tick, lte, tickSpacing) {
678
+ const compressed = Math.floor(tick / tickSpacing);
679
+ if (lte) {
680
+ const wordPos = compressed >> 8;
681
+ const minimum = (wordPos << 8) * tickSpacing;
682
+ if (_TickList.isBelowSmallest(ticks, tick)) {
683
+ return [minimum, false];
684
+ }
685
+ const index = _TickList.nextInitializedTick(ticks, tick, lte).index;
686
+ const nextInitializedTick = Math.max(minimum, index);
687
+ return [nextInitializedTick, nextInitializedTick === index];
688
+ } else {
689
+ const wordPos = compressed + 1 >> 8;
690
+ const maximum = ((wordPos + 1 << 8) - 1) * tickSpacing;
691
+ if (this.isAtOrAboveLargest(ticks, tick)) {
692
+ return [maximum, false];
693
+ }
694
+ const index = this.nextInitializedTick(ticks, tick, lte).index;
695
+ const nextInitializedTick = Math.min(maximum, index);
696
+ return [nextInitializedTick, nextInitializedTick === index];
697
+ }
698
+ }
699
+ };
700
+
701
+ // src/entities/tick.ts
702
+ import JSBI16 from "jsbi";
703
+ import invariant6 from "tiny-invariant";
704
+
705
+ // src/utils/calldata.ts
706
+ import JSBI10 from "jsbi";
707
+ function toHex(bigintIsh) {
708
+ const bigInt = JSBI10.BigInt(bigintIsh);
709
+ let hex = bigInt.toString(16);
710
+ if (hex.length % 2 !== 0) {
711
+ hex = `0${hex}`;
712
+ }
713
+ return `0x${hex}`;
714
+ }
715
+
716
+ // src/utils/encode-sqrt-ratio-x96.ts
717
+ import { sqrt } from "@sun-protocol/sun-sdk-core";
718
+ import JSBI11 from "jsbi";
719
+ function encodeSqrtRatioX96(amount1, amount0) {
720
+ const numerator = JSBI11.leftShift(JSBI11.BigInt(amount1), JSBI11.BigInt(192));
721
+ const denominator = JSBI11.BigInt(amount0);
722
+ const ratioX192 = JSBI11.divide(numerator, denominator);
723
+ return sqrt(ratioX192);
724
+ }
725
+
726
+ // src/utils/encodeRouteToPath.ts
727
+ import { pack } from "@ethersproject/solidity";
728
+ function encodeRouteToPath(route, exactOutput) {
729
+ const firstInputToken = route.input.wrapped;
730
+ const { path, types } = route.pools.reduce(
731
+ ({ inputToken, path: path2, types: types2 }, pool, index) => {
732
+ const outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
733
+ if (index === 0) {
734
+ return {
735
+ inputToken: outputToken,
736
+ types: ["address", "uint24", "address"],
737
+ path: [inputToken.address, pool.fee, outputToken.address]
738
+ };
739
+ } else {
740
+ return {
741
+ inputToken: outputToken,
742
+ types: [...types2, "uint24", "address"],
743
+ path: [...path2, pool.fee, outputToken.address]
744
+ };
745
+ }
746
+ },
747
+ { inputToken: firstInputToken, path: [], types: [] }
748
+ );
749
+ return exactOutput ? pack(types.reverse(), path.reverse()) : pack(types, path);
750
+ }
751
+
752
+ // src/utils/max-liquidity-for-amounts.ts
753
+ import JSBI12 from "jsbi";
754
+ function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
755
+ if (JSBI12.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
756
+ ;
757
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
758
+ }
759
+ const intermediate = JSBI12.divide(JSBI12.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96);
760
+ return JSBI12.divide(JSBI12.multiply(JSBI12.BigInt(amount0), intermediate), JSBI12.subtract(sqrtRatioBX96, sqrtRatioAX96));
761
+ }
762
+ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
763
+ if (JSBI12.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
764
+ ;
765
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
766
+ }
767
+ const numerator = JSBI12.multiply(JSBI12.multiply(JSBI12.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96);
768
+ const denominator = JSBI12.multiply(Q96, JSBI12.subtract(sqrtRatioBX96, sqrtRatioAX96));
769
+ return JSBI12.divide(numerator, denominator);
770
+ }
771
+ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
772
+ if (JSBI12.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
773
+ ;
774
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
775
+ }
776
+ return JSBI12.divide(JSBI12.multiply(JSBI12.BigInt(amount1), Q96), JSBI12.subtract(sqrtRatioBX96, sqrtRatioAX96));
777
+ }
778
+ function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) {
779
+ if (JSBI12.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
780
+ ;
781
+ [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
782
+ }
783
+ const maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise;
784
+ if (JSBI12.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) {
785
+ return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
786
+ }
787
+ if (JSBI12.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) {
788
+ const liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0);
789
+ const liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1);
790
+ return JSBI12.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1;
791
+ }
792
+ return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
793
+ }
794
+
795
+ // src/utils/nearest-usable-tick.ts
796
+ import invariant5 from "tiny-invariant";
797
+ function nearestUsableTick(tick, tickSpacing) {
798
+ invariant5(Number.isInteger(tick) && Number.isInteger(tickSpacing), "INTEGERS");
799
+ invariant5(tickSpacing > 0, "TICK_SPACING");
800
+ invariant5(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK, "TICK_BOUND");
801
+ const rounded = Math.round(tick / tickSpacing) * tickSpacing;
802
+ if (rounded < TickMath.MIN_TICK) return rounded + tickSpacing;
803
+ if (rounded > TickMath.MAX_TICK) return rounded - tickSpacing;
804
+ return rounded;
805
+ }
806
+
807
+ // src/utils/position.ts
808
+ import JSBI13 from "jsbi";
809
+ var Q128 = JSBI13.exponentiate(JSBI13.BigInt(2), JSBI13.BigInt(128));
810
+ var PositionLibrary = class {
811
+ /**
812
+ * Cannot be constructed.
813
+ */
814
+ constructor() {
815
+ }
816
+ // replicates the portions of Position#update required to compute unaccounted fees
817
+ static getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
818
+ const tokensOwed0 = JSBI13.divide(
819
+ JSBI13.multiply(subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128), liquidity),
820
+ Q128
821
+ );
822
+ const tokensOwed1 = JSBI13.divide(
823
+ JSBI13.multiply(subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128), liquidity),
824
+ Q128
825
+ );
826
+ return [tokensOwed0, tokensOwed1];
827
+ }
828
+ };
829
+
830
+ // src/utils/priceTickConversions.ts
831
+ import { Price } from "@sun-protocol/sun-sdk-core";
832
+ import JSBI14 from "jsbi";
833
+ function tickToPrice(baseToken, quoteToken, tick) {
834
+ const sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
835
+ const ratioX192 = JSBI14.multiply(sqrtRatioX96, sqrtRatioX96);
836
+ return baseToken.sortsBefore(quoteToken) ? new Price(baseToken, quoteToken, Q192, ratioX192) : new Price(baseToken, quoteToken, ratioX192, Q192);
837
+ }
838
+ function priceToClosestTick(price) {
839
+ const sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
840
+ const sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator);
841
+ let tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
842
+ const nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1);
843
+ if (sorted) {
844
+ if (!price.lessThan(nextTickPrice)) {
845
+ tick++;
846
+ }
847
+ } else {
848
+ if (!price.greaterThan(nextTickPrice)) {
849
+ tick++;
850
+ }
851
+ }
852
+ return tick;
853
+ }
854
+
855
+ // src/utils/tickLibrary.ts
856
+ import JSBI15 from "jsbi";
857
+ var Q256 = JSBI15.exponentiate(JSBI15.BigInt(2), JSBI15.BigInt(256));
858
+ function subIn256(x, y) {
859
+ const difference = JSBI15.subtract(x, y);
860
+ if (JSBI15.lessThan(difference, ZERO)) {
861
+ return JSBI15.add(Q256, difference);
862
+ } else {
863
+ return difference;
864
+ }
865
+ }
866
+ var TickLibrary = class {
867
+ /**
868
+ * Cannot be constructed.
869
+ */
870
+ constructor() {
871
+ }
872
+ static getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
873
+ let feeGrowthBelow0X128;
874
+ let feeGrowthBelow1X128;
875
+ if (tickCurrent >= tickLower) {
876
+ feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
877
+ feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
878
+ } else {
879
+ feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
880
+ feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
881
+ }
882
+ let feeGrowthAbove0X128;
883
+ let feeGrowthAbove1X128;
884
+ if (tickCurrent < tickUpper) {
885
+ feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
886
+ feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
887
+ } else {
888
+ feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
889
+ feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
890
+ }
891
+ return [
892
+ subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128),
893
+ subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)
894
+ ];
895
+ }
896
+ };
897
+
898
+ // src/utils/ticks.ts
899
+ import { SDK_ERROR_CODES, sdkInvariant } from "@sun-protocol/sun-sdk-core";
900
+ function isSupportedFeeAmount(fee) {
901
+ return Object.prototype.hasOwnProperty.call(TICK_SPACINGS, fee);
902
+ }
903
+ function getTickSpacing(fee) {
904
+ sdkInvariant(isSupportedFeeAmount(fee), SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Unsupported V3 fee tier", { fee });
905
+ return TICK_SPACINGS[fee];
906
+ }
907
+ function validateTickSpacing(tickSpacing) {
908
+ sdkInvariant(Number.isInteger(tickSpacing), SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Tick spacing must be an integer", {
909
+ tickSpacing
910
+ });
911
+ sdkInvariant(tickSpacing > 0, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Tick spacing must be positive", { tickSpacing });
912
+ return tickSpacing;
913
+ }
914
+ function validateTickRange(tickLower, tickUpper, tickSpacing) {
915
+ validateTickSpacing(tickSpacing);
916
+ sdkInvariant(Number.isInteger(tickLower), SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Lower tick must be an integer", {
917
+ tickLower
918
+ });
919
+ sdkInvariant(Number.isInteger(tickUpper), SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Upper tick must be an integer", {
920
+ tickUpper
921
+ });
922
+ sdkInvariant(tickLower < tickUpper, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Lower tick must be below upper tick", {
923
+ tickLower,
924
+ tickUpper
925
+ });
926
+ sdkInvariant(tickLower >= TickMath.MIN_TICK, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Lower tick is below min tick", {
927
+ tickLower,
928
+ minTick: TickMath.MIN_TICK
929
+ });
930
+ sdkInvariant(tickUpper <= TickMath.MAX_TICK, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Upper tick is above max tick", {
931
+ tickUpper,
932
+ maxTick: TickMath.MAX_TICK
933
+ });
934
+ sdkInvariant(tickLower % tickSpacing === 0, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Lower tick is not usable", {
935
+ tickLower,
936
+ tickSpacing
937
+ });
938
+ sdkInvariant(tickUpper % tickSpacing === 0, SDK_ERROR_CODES.SDK_INVALID_ARGUMENT, "Upper tick is not usable", {
939
+ tickUpper,
940
+ tickSpacing
941
+ });
942
+ return { tickLower, tickUpper };
943
+ }
944
+ function validateTickRangeForFee(tickLower, tickUpper, fee) {
945
+ const tickSpacing = getTickSpacing(fee);
946
+ return { ...validateTickRange(tickLower, tickUpper, tickSpacing), tickSpacing };
947
+ }
948
+
949
+ // src/entities/tick.ts
950
+ var Tick = class {
951
+ index;
952
+ liquidityGross;
953
+ liquidityNet;
954
+ constructor({ index, liquidityGross, liquidityNet }) {
955
+ invariant6(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK, "TICK");
956
+ this.index = index;
957
+ this.liquidityGross = JSBI16.BigInt(liquidityGross);
958
+ this.liquidityNet = JSBI16.BigInt(liquidityNet);
959
+ }
960
+ };
961
+
962
+ // src/entities/tickListDataProvider.ts
963
+ var TickListDataProvider = class {
964
+ ticks;
965
+ constructor(ticks, tickSpacing) {
966
+ const ticksMapped = ticks.map((t) => t instanceof Tick ? t : new Tick(t));
967
+ TickList.validateList(ticksMapped, tickSpacing);
968
+ this.ticks = ticksMapped;
969
+ }
970
+ async getTick(tick) {
971
+ return TickList.getTick(this.ticks, tick);
972
+ }
973
+ async nextInitializedTickWithinOneWord(tick, lte, tickSpacing) {
974
+ return TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing);
975
+ }
976
+ };
977
+
978
+ // src/entities/pool.ts
979
+ var NO_TICK_DATA_PROVIDER_DEFAULT = new NoTickDataProvider();
980
+ var Pool = class _Pool {
981
+ token0;
982
+ token1;
983
+ fee;
984
+ sqrtRatioX96;
985
+ liquidity;
986
+ tickCurrent;
987
+ tickDataProvider;
988
+ _tickSpacing;
989
+ isV4;
990
+ _token0Price;
991
+ _token1Price;
992
+ static getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, factoryAddressOverride) {
993
+ return computePoolAddress({
994
+ factoryAddress: factoryAddressOverride ?? FACTORY_ADDRESS,
995
+ fee,
996
+ tokenA,
997
+ tokenB,
998
+ ...initCodeHashManualOverride !== void 0 ? { initCodeHashManualOverride } : {}
999
+ });
1000
+ }
1001
+ constructor(tokenAOrArgs, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks = NO_TICK_DATA_PROVIDER_DEFAULT, isV4, tickSpacing) {
1002
+ const args = tokenAOrArgs instanceof Token ? { tokenA: tokenAOrArgs, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks, isV4, tickSpacing } : tokenAOrArgs;
1003
+ const resolvedTicks = args.ticks ?? NO_TICK_DATA_PROVIDER_DEFAULT;
1004
+ const { fee: resolvedFee } = args;
1005
+ if (!args.isV4) {
1006
+ invariant7(Number.isInteger(resolvedFee) && resolvedFee < 1e6, "FEE");
1007
+ }
1008
+ this.isV4 = args.isV4;
1009
+ this._tickSpacing = args.tickSpacing;
1010
+ const tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(args.tickCurrent);
1011
+ const nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(args.tickCurrent + 1);
1012
+ invariant7(
1013
+ JSBI17.greaterThanOrEqual(JSBI17.BigInt(args.sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI17.lessThanOrEqual(JSBI17.BigInt(args.sqrtRatioX96), nextTickSqrtRatioX96),
1014
+ "PRICE_BOUNDS"
1015
+ );
1016
+ [this.token0, this.token1] = args.tokenA.sortsBefore(args.tokenB) ? [args.tokenA, args.tokenB] : [args.tokenB, args.tokenA];
1017
+ this.fee = resolvedFee;
1018
+ this.sqrtRatioX96 = JSBI17.BigInt(args.sqrtRatioX96);
1019
+ this.liquidity = JSBI17.BigInt(args.liquidity);
1020
+ this.tickCurrent = args.tickCurrent;
1021
+ if (args.isV4) {
1022
+ this.tickDataProvider = Array.isArray(resolvedTicks) ? new TickListDataProvider(resolvedTicks, args.tickSpacing) : resolvedTicks;
1023
+ } else {
1024
+ this.tickDataProvider = Array.isArray(resolvedTicks) ? new TickListDataProvider(resolvedTicks, TICK_SPACINGS[resolvedFee]) : resolvedTicks;
1025
+ }
1026
+ }
1027
+ /**
1028
+ * Returns true if the token is either token0 or token1
1029
+ * @param token The token to check
1030
+ * @returns True if token is either token0 or token
1031
+ */
1032
+ involvesToken(token) {
1033
+ return token.equals(this.token0) || token.equals(this.token1);
1034
+ }
1035
+ /**
1036
+ * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
1037
+ */
1038
+ get token0Price() {
1039
+ return this._token0Price ?? (this._token0Price = new Price2(
1040
+ this.token0,
1041
+ this.token1,
1042
+ Q192,
1043
+ JSBI17.multiply(this.sqrtRatioX96, this.sqrtRatioX96)
1044
+ ));
1045
+ }
1046
+ /**
1047
+ * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
1048
+ */
1049
+ get token1Price() {
1050
+ return this._token1Price ?? (this._token1Price = new Price2(
1051
+ this.token1,
1052
+ this.token0,
1053
+ JSBI17.multiply(this.sqrtRatioX96, this.sqrtRatioX96),
1054
+ Q192
1055
+ ));
1056
+ }
1057
+ /**
1058
+ * Return the price of the given token in terms of the other token in the pool.
1059
+ * @param token The token to return price of
1060
+ * @returns The price of the given token, in terms of the other.
1061
+ */
1062
+ priceOf(token) {
1063
+ invariant7(this.involvesToken(token), "TOKEN");
1064
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
1065
+ }
1066
+ /**
1067
+ * Returns the chain ID of the tokens in the pool.
1068
+ */
1069
+ get chainId() {
1070
+ return this.token0.chainId;
1071
+ }
1072
+ /**
1073
+ * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
1074
+ * @param inputAmount The input amount for which to quote the output amount
1075
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
1076
+ * @returns The output amount and the pool with updated state
1077
+ */
1078
+ async getOutputAmount(inputAmount, sqrtPriceLimitX96) {
1079
+ invariant7(this.involvesToken(inputAmount.currency), "TOKEN");
1080
+ const zeroForOne = inputAmount.currency.equals(this.token0);
1081
+ const { amountCalculated: outputAmount, sqrtRatioX96, liquidity, tickCurrent } = await this.swap(
1082
+ zeroForOne,
1083
+ inputAmount.quotient,
1084
+ sqrtPriceLimitX96
1085
+ );
1086
+ const outputToken = zeroForOne ? this.token1 : this.token0;
1087
+ return [
1088
+ CurrencyAmount.fromRawAmount(outputToken, JSBI17.multiply(outputAmount, NEGATIVE_ONE)),
1089
+ new _Pool(
1090
+ this.token0,
1091
+ this.token1,
1092
+ this.fee,
1093
+ sqrtRatioX96,
1094
+ liquidity,
1095
+ tickCurrent,
1096
+ this.tickDataProvider,
1097
+ this.isV4,
1098
+ this._tickSpacing
1099
+ )
1100
+ ];
1101
+ }
1102
+ /**
1103
+ * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
1104
+ * @param outputAmount the output amount for which to quote the input amount
1105
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
1106
+ * @returns The input amount and the pool with updated state
1107
+ */
1108
+ async getInputAmount(outputAmount, sqrtPriceLimitX96) {
1109
+ invariant7(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency), "TOKEN");
1110
+ const zeroForOne = outputAmount.currency.equals(this.token1);
1111
+ const { amountCalculated: inputAmount, sqrtRatioX96, liquidity, tickCurrent } = await this.swap(
1112
+ zeroForOne,
1113
+ JSBI17.multiply(outputAmount.quotient, NEGATIVE_ONE),
1114
+ sqrtPriceLimitX96
1115
+ );
1116
+ const inputToken = zeroForOne ? this.token0 : this.token1;
1117
+ return [
1118
+ CurrencyAmount.fromRawAmount(inputToken, inputAmount),
1119
+ new _Pool(
1120
+ this.token0,
1121
+ this.token1,
1122
+ this.fee,
1123
+ sqrtRatioX96,
1124
+ liquidity,
1125
+ tickCurrent,
1126
+ this.tickDataProvider,
1127
+ this.isV4,
1128
+ this._tickSpacing
1129
+ )
1130
+ ];
1131
+ }
1132
+ /**
1133
+ * Executes a swap
1134
+ * @param zeroForOne Whether the amount in is token0 or token1
1135
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
1136
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
1137
+ * @returns amountCalculated
1138
+ * @returns sqrtRatioX96
1139
+ * @returns liquidity
1140
+ * @returns tickCurrent
1141
+ */
1142
+ async swap(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
1143
+ if (!sqrtPriceLimitX96)
1144
+ sqrtPriceLimitX96 = zeroForOne ? JSBI17.add(TickMath.MIN_SQRT_RATIO, ONE) : JSBI17.subtract(TickMath.MAX_SQRT_RATIO, ONE);
1145
+ if (zeroForOne) {
1146
+ invariant7(JSBI17.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO), "RATIO_MIN");
1147
+ invariant7(JSBI17.lessThan(sqrtPriceLimitX96, this.sqrtRatioX96), "RATIO_CURRENT");
1148
+ } else {
1149
+ invariant7(JSBI17.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO), "RATIO_MAX");
1150
+ invariant7(JSBI17.greaterThan(sqrtPriceLimitX96, this.sqrtRatioX96), "RATIO_CURRENT");
1151
+ }
1152
+ const exactInput = JSBI17.greaterThanOrEqual(amountSpecified, ZERO);
1153
+ const state = {
1154
+ amountSpecifiedRemaining: amountSpecified,
1155
+ amountCalculated: ZERO,
1156
+ sqrtPriceX96: this.sqrtRatioX96,
1157
+ tick: this.tickCurrent,
1158
+ liquidity: this.liquidity
1159
+ };
1160
+ while (JSBI17.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 != sqrtPriceLimitX96) {
1161
+ const step = {};
1162
+ step.sqrtPriceStartX96 = state.sqrtPriceX96;
1163
+ [step.tickNext, step.initialized] = await this.tickDataProvider.nextInitializedTickWithinOneWord(
1164
+ state.tick,
1165
+ zeroForOne,
1166
+ this.tickSpacing
1167
+ );
1168
+ if (step.tickNext < TickMath.MIN_TICK) {
1169
+ step.tickNext = TickMath.MIN_TICK;
1170
+ } else if (step.tickNext > TickMath.MAX_TICK) {
1171
+ step.tickNext = TickMath.MAX_TICK;
1172
+ }
1173
+ step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
1174
+ [state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.computeSwapStep(
1175
+ state.sqrtPriceX96,
1176
+ (zeroForOne ? JSBI17.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI17.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96,
1177
+ state.liquidity,
1178
+ state.amountSpecifiedRemaining,
1179
+ this.fee
1180
+ );
1181
+ if (exactInput) {
1182
+ state.amountSpecifiedRemaining = JSBI17.subtract(
1183
+ state.amountSpecifiedRemaining,
1184
+ JSBI17.add(step.amountIn, step.feeAmount)
1185
+ );
1186
+ state.amountCalculated = JSBI17.subtract(state.amountCalculated, step.amountOut);
1187
+ } else {
1188
+ state.amountSpecifiedRemaining = JSBI17.add(state.amountSpecifiedRemaining, step.amountOut);
1189
+ state.amountCalculated = JSBI17.add(state.amountCalculated, JSBI17.add(step.amountIn, step.feeAmount));
1190
+ }
1191
+ if (JSBI17.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) {
1192
+ if (step.initialized) {
1193
+ let liquidityNet = JSBI17.BigInt((await this.tickDataProvider.getTick(step.tickNext)).liquidityNet);
1194
+ if (zeroForOne) liquidityNet = JSBI17.multiply(liquidityNet, NEGATIVE_ONE);
1195
+ state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
1196
+ }
1197
+ state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
1198
+ } else if (JSBI17.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) {
1199
+ state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
1200
+ }
1201
+ }
1202
+ return {
1203
+ amountCalculated: state.amountCalculated,
1204
+ sqrtRatioX96: state.sqrtPriceX96,
1205
+ liquidity: state.liquidity,
1206
+ tickCurrent: state.tick
1207
+ };
1208
+ }
1209
+ get tickSpacing() {
1210
+ if (this.isV4) {
1211
+ return this._tickSpacing;
1212
+ }
1213
+ return TICK_SPACINGS[this.fee];
1214
+ }
1215
+ };
1216
+
1217
+ // src/entities/position.ts
1218
+ import { MaxUint256 as MaxUint2563, Percent, CurrencyAmount as CurrencyAmount2 } from "@sun-protocol/sun-sdk-core";
1219
+ import JSBI18 from "jsbi";
1220
+ import invariant8 from "tiny-invariant";
1221
+ var Position = class _Position {
1222
+ pool;
1223
+ tickLower;
1224
+ tickUpper;
1225
+ liquidity;
1226
+ // cached resuts for the getters
1227
+ _token0Amount = null;
1228
+ _token1Amount = null;
1229
+ _mintAmounts = null;
1230
+ /**
1231
+ * Constructs a position for a given pool with the given liquidity
1232
+ * @param pool For which pool the liquidity is assigned
1233
+ * @param liquidity The amount of liquidity that is in the position
1234
+ * @param tickLower The lower tick of the position
1235
+ * @param tickUpper The upper tick of the position
1236
+ */
1237
+ constructor({ pool, liquidity, tickLower, tickUpper }) {
1238
+ invariant8(tickLower < tickUpper, "TICK_ORDER");
1239
+ invariant8(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0, "TICK_LOWER");
1240
+ invariant8(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0, "TICK_UPPER");
1241
+ this.pool = pool;
1242
+ this.tickLower = tickLower;
1243
+ this.tickUpper = tickUpper;
1244
+ this.liquidity = JSBI18.BigInt(liquidity);
1245
+ }
1246
+ /**
1247
+ * Returns the price of token0 at the lower tick
1248
+ */
1249
+ get token0PriceLower() {
1250
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
1251
+ }
1252
+ /**
1253
+ * Returns the price of token0 at the upper tick
1254
+ */
1255
+ get token0PriceUpper() {
1256
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
1257
+ }
1258
+ /**
1259
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
1260
+ */
1261
+ get amount0() {
1262
+ if (this._token0Amount === null) {
1263
+ if (this.pool.tickCurrent < this.tickLower) {
1264
+ this._token0Amount = CurrencyAmount2.fromRawAmount(
1265
+ this.pool.token0,
1266
+ SqrtPriceMath.getAmount0Delta(
1267
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1268
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1269
+ this.liquidity,
1270
+ false
1271
+ )
1272
+ );
1273
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1274
+ this._token0Amount = CurrencyAmount2.fromRawAmount(
1275
+ this.pool.token0,
1276
+ SqrtPriceMath.getAmount0Delta(
1277
+ this.pool.sqrtRatioX96,
1278
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1279
+ this.liquidity,
1280
+ false
1281
+ )
1282
+ );
1283
+ } else {
1284
+ this._token0Amount = CurrencyAmount2.fromRawAmount(this.pool.token0, ZERO);
1285
+ }
1286
+ }
1287
+ return this._token0Amount;
1288
+ }
1289
+ /**
1290
+ * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
1291
+ */
1292
+ get amount1() {
1293
+ if (this._token1Amount === null) {
1294
+ if (this.pool.tickCurrent < this.tickLower) {
1295
+ this._token1Amount = CurrencyAmount2.fromRawAmount(this.pool.token1, ZERO);
1296
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1297
+ this._token1Amount = CurrencyAmount2.fromRawAmount(
1298
+ this.pool.token1,
1299
+ SqrtPriceMath.getAmount1Delta(
1300
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1301
+ this.pool.sqrtRatioX96,
1302
+ this.liquidity,
1303
+ false
1304
+ )
1305
+ );
1306
+ } else {
1307
+ this._token1Amount = CurrencyAmount2.fromRawAmount(
1308
+ this.pool.token1,
1309
+ SqrtPriceMath.getAmount1Delta(
1310
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1311
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1312
+ this.liquidity,
1313
+ false
1314
+ )
1315
+ );
1316
+ }
1317
+ }
1318
+ return this._token1Amount;
1319
+ }
1320
+ /**
1321
+ * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
1322
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
1323
+ * @returns The sqrt ratios after slippage
1324
+ */
1325
+ ratiosAfterSlippage(slippageTolerance) {
1326
+ const priceLower = this.pool.token0Price.asFraction.multiply(new Percent(1).subtract(slippageTolerance));
1327
+ const priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
1328
+ let sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
1329
+ if (JSBI18.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
1330
+ sqrtRatioX96Lower = JSBI18.add(TickMath.MIN_SQRT_RATIO, JSBI18.BigInt(1));
1331
+ }
1332
+ let sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
1333
+ if (JSBI18.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
1334
+ sqrtRatioX96Upper = JSBI18.subtract(TickMath.MAX_SQRT_RATIO, JSBI18.BigInt(1));
1335
+ }
1336
+ return {
1337
+ sqrtRatioX96Lower,
1338
+ sqrtRatioX96Upper
1339
+ };
1340
+ }
1341
+ /**
1342
+ * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
1343
+ * with the given slippage tolerance
1344
+ * @param slippageTolerance Tolerance of unfavorable slippage from the current price
1345
+ * @returns The amounts, with slippage
1346
+ */
1347
+ mintAmountsWithSlippage(slippageTolerance) {
1348
+ const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
1349
+ const poolLower = new Pool({
1350
+ tokenA: this.pool.token0,
1351
+ tokenB: this.pool.token1,
1352
+ fee: this.pool.fee,
1353
+ sqrtRatioX96: sqrtRatioX96Lower,
1354
+ liquidity: 0,
1355
+ tickCurrent: TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower),
1356
+ ...this.pool.isV4 ? { isV4: true, tickSpacing: this.pool.tickSpacing } : {}
1357
+ });
1358
+ const poolUpper = new Pool({
1359
+ tokenA: this.pool.token0,
1360
+ tokenB: this.pool.token1,
1361
+ fee: this.pool.fee,
1362
+ sqrtRatioX96: sqrtRatioX96Upper,
1363
+ liquidity: 0,
1364
+ tickCurrent: TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper),
1365
+ ...this.pool.isV4 ? { isV4: true, tickSpacing: this.pool.tickSpacing } : {}
1366
+ });
1367
+ const positionThatWillBeCreated = _Position.fromAmounts({
1368
+ pool: this.pool,
1369
+ tickLower: this.tickLower,
1370
+ tickUpper: this.tickUpper,
1371
+ ...this.mintAmounts,
1372
+ // the mint amounts are what will be passed as calldata
1373
+ useFullPrecision: false
1374
+ });
1375
+ const { amount0 } = new _Position({
1376
+ pool: poolUpper,
1377
+ liquidity: positionThatWillBeCreated.liquidity,
1378
+ tickLower: this.tickLower,
1379
+ tickUpper: this.tickUpper
1380
+ }).mintAmounts;
1381
+ const { amount1 } = new _Position({
1382
+ pool: poolLower,
1383
+ liquidity: positionThatWillBeCreated.liquidity,
1384
+ tickLower: this.tickLower,
1385
+ tickUpper: this.tickUpper
1386
+ }).mintAmounts;
1387
+ return { amount0, amount1 };
1388
+ }
1389
+ /**
1390
+ * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
1391
+ * position with the given slippage tolerance
1392
+ * @param slippageTolerance tolerance of unfavorable slippage from the current price
1393
+ * @returns The amounts, with slippage
1394
+ */
1395
+ burnAmountsWithSlippage(slippageTolerance) {
1396
+ const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
1397
+ const poolLower = new Pool({
1398
+ tokenA: this.pool.token0,
1399
+ tokenB: this.pool.token1,
1400
+ fee: this.pool.fee,
1401
+ sqrtRatioX96: sqrtRatioX96Lower,
1402
+ liquidity: 0,
1403
+ tickCurrent: TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower),
1404
+ ...this.pool.isV4 ? { isV4: true, tickSpacing: this.pool.tickSpacing } : {}
1405
+ });
1406
+ const poolUpper = new Pool({
1407
+ tokenA: this.pool.token0,
1408
+ tokenB: this.pool.token1,
1409
+ fee: this.pool.fee,
1410
+ sqrtRatioX96: sqrtRatioX96Upper,
1411
+ liquidity: 0,
1412
+ tickCurrent: TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper),
1413
+ ...this.pool.isV4 ? { isV4: true, tickSpacing: this.pool.tickSpacing } : {}
1414
+ });
1415
+ const amount0 = new _Position({
1416
+ pool: poolUpper,
1417
+ liquidity: this.liquidity,
1418
+ tickLower: this.tickLower,
1419
+ tickUpper: this.tickUpper
1420
+ }).amount0;
1421
+ const amount1 = new _Position({
1422
+ pool: poolLower,
1423
+ liquidity: this.liquidity,
1424
+ tickLower: this.tickLower,
1425
+ tickUpper: this.tickUpper
1426
+ }).amount1;
1427
+ return { amount0: amount0.quotient, amount1: amount1.quotient };
1428
+ }
1429
+ /**
1430
+ * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
1431
+ * the current price for the pool
1432
+ */
1433
+ get mintAmounts() {
1434
+ if (this._mintAmounts === null) {
1435
+ if (this.pool.tickCurrent < this.tickLower) {
1436
+ return {
1437
+ amount0: SqrtPriceMath.getAmount0Delta(
1438
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1439
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1440
+ this.liquidity,
1441
+ true
1442
+ ),
1443
+ amount1: ZERO
1444
+ };
1445
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1446
+ return {
1447
+ amount0: SqrtPriceMath.getAmount0Delta(
1448
+ this.pool.sqrtRatioX96,
1449
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1450
+ this.liquidity,
1451
+ true
1452
+ ),
1453
+ amount1: SqrtPriceMath.getAmount1Delta(
1454
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1455
+ this.pool.sqrtRatioX96,
1456
+ this.liquidity,
1457
+ true
1458
+ )
1459
+ };
1460
+ } else {
1461
+ return {
1462
+ amount0: ZERO,
1463
+ amount1: SqrtPriceMath.getAmount1Delta(
1464
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1465
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1466
+ this.liquidity,
1467
+ true
1468
+ )
1469
+ };
1470
+ }
1471
+ }
1472
+ return this._mintAmounts;
1473
+ }
1474
+ /**
1475
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1476
+ * and the prices at the tick boundaries.
1477
+ * @param pool The pool for which the position should be created
1478
+ * @param tickLower The lower tick of the position
1479
+ * @param tickUpper The upper tick of the position
1480
+ * @param amount0 token0 amount
1481
+ * @param amount1 token1 amount
1482
+ * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
1483
+ * not what core can theoretically support
1484
+ * @returns The amount of liquidity for the position
1485
+ */
1486
+ static fromAmounts({
1487
+ pool,
1488
+ tickLower,
1489
+ tickUpper,
1490
+ amount0,
1491
+ amount1,
1492
+ useFullPrecision
1493
+ }) {
1494
+ const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1495
+ const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1496
+ return new _Position({
1497
+ pool,
1498
+ tickLower,
1499
+ tickUpper,
1500
+ liquidity: maxLiquidityForAmounts(
1501
+ pool.sqrtRatioX96,
1502
+ sqrtRatioAX96,
1503
+ sqrtRatioBX96,
1504
+ amount0,
1505
+ amount1,
1506
+ useFullPrecision
1507
+ )
1508
+ });
1509
+ }
1510
+ /**
1511
+ * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
1512
+ * @param pool The pool for which the position is created
1513
+ * @param tickLower The lower tick
1514
+ * @param tickUpper The upper tick
1515
+ * @param amount0 The desired amount of token0
1516
+ * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
1517
+ * not what core can theoretically support
1518
+ * @returns The position
1519
+ */
1520
+ static fromAmount0({
1521
+ pool,
1522
+ tickLower,
1523
+ tickUpper,
1524
+ amount0,
1525
+ useFullPrecision
1526
+ }) {
1527
+ return _Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1: MaxUint2563, useFullPrecision });
1528
+ }
1529
+ /**
1530
+ * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
1531
+ * @param pool The pool for which the position is created
1532
+ * @param tickLower The lower tick
1533
+ * @param tickUpper The upper tick
1534
+ * @param amount1 The desired amount of token1
1535
+ * @returns The position
1536
+ */
1537
+ static fromAmount1({
1538
+ pool,
1539
+ tickLower,
1540
+ tickUpper,
1541
+ amount1
1542
+ }) {
1543
+ return _Position.fromAmounts({ pool, tickLower, tickUpper, amount0: MaxUint2563, amount1, useFullPrecision: true });
1544
+ }
1545
+ };
1546
+
1547
+ // src/entities/route.ts
1548
+ import invariant9 from "tiny-invariant";
1549
+ import { Price as Price3 } from "@sun-protocol/sun-sdk-core";
1550
+ var Route = class {
1551
+ pools;
1552
+ tokenPath;
1553
+ input;
1554
+ output;
1555
+ _midPrice = null;
1556
+ /**
1557
+ * Creates an instance of route.
1558
+ * @param pools An array of `Pool` objects, ordered by the route the swap will take
1559
+ * @param input The input token
1560
+ * @param output The output token
1561
+ */
1562
+ constructor(pools, input, output) {
1563
+ invariant9(pools.length > 0, "POOLS");
1564
+ const firstPool = pools[0];
1565
+ const chainId = firstPool.chainId;
1566
+ const allOnSameChain = pools.every((pool) => pool.chainId === chainId);
1567
+ invariant9(allOnSameChain, "CHAIN_IDS");
1568
+ const wrappedInput = input.wrapped;
1569
+ invariant9(firstPool.involvesToken(wrappedInput), "INPUT");
1570
+ invariant9(pools[pools.length - 1].involvesToken(output.wrapped), "OUTPUT");
1571
+ const tokenPath = [wrappedInput];
1572
+ for (const [i, pool] of pools.entries()) {
1573
+ const currentInputToken = tokenPath[i];
1574
+ invariant9(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), "PATH");
1575
+ const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
1576
+ tokenPath.push(nextToken);
1577
+ }
1578
+ this.pools = pools;
1579
+ this.tokenPath = tokenPath;
1580
+ this.input = input;
1581
+ this.output = output ?? tokenPath[tokenPath.length - 1];
1582
+ }
1583
+ get chainId() {
1584
+ return this.pools[0].chainId;
1585
+ }
1586
+ /**
1587
+ * Returns the mid price of the route
1588
+ */
1589
+ get midPrice() {
1590
+ if (this._midPrice !== null) return this._midPrice;
1591
+ const price = this.pools.slice(1).reduce(
1592
+ ({ nextInput, price: price2 }, pool) => {
1593
+ return nextInput.equals(pool.token0) ? {
1594
+ nextInput: pool.token1,
1595
+ price: price2.multiply(pool.token0Price)
1596
+ } : {
1597
+ nextInput: pool.token0,
1598
+ price: price2.multiply(pool.token1Price)
1599
+ };
1600
+ },
1601
+ this.pools[0].token0.equals(this.input.wrapped) ? {
1602
+ nextInput: this.pools[0].token1,
1603
+ price: this.pools[0].token0Price
1604
+ } : {
1605
+ nextInput: this.pools[0].token0,
1606
+ price: this.pools[0].token1Price
1607
+ }
1608
+ ).price;
1609
+ return this._midPrice = new Price3(this.input, this.output, price.denominator, price.numerator);
1610
+ }
1611
+ };
1612
+
1613
+ // src/entities/trade.ts
1614
+ import { Fraction, Percent as Percent2, Price as Price4, sortedInsert, CurrencyAmount as CurrencyAmount3, TradeType } from "@sun-protocol/sun-sdk-core";
1615
+ import invariant10 from "tiny-invariant";
1616
+ function tradeComparator(a, b) {
1617
+ invariant10(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
1618
+ invariant10(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
1619
+ if (a.outputAmount.equalTo(b.outputAmount)) {
1620
+ if (a.inputAmount.equalTo(b.inputAmount)) {
1621
+ const aHops = a.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1622
+ const bHops = b.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1623
+ return aHops - bHops;
1624
+ }
1625
+ if (a.inputAmount.lessThan(b.inputAmount)) {
1626
+ return -1;
1627
+ } else {
1628
+ return 1;
1629
+ }
1630
+ } else {
1631
+ if (a.outputAmount.lessThan(b.outputAmount)) {
1632
+ return 1;
1633
+ } else {
1634
+ return -1;
1635
+ }
1636
+ }
1637
+ }
1638
+ var Trade = class _Trade {
1639
+ /**
1640
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
1641
+ * this will return an error.
1642
+ *
1643
+ * When the trade consists of just a single route, this returns the route of the trade,
1644
+ * i.e. which pools the trade goes through.
1645
+ */
1646
+ get route() {
1647
+ invariant10(this.swaps.length == 1, "MULTIPLE_ROUTES");
1648
+ return this.swaps[0].route;
1649
+ }
1650
+ /**
1651
+ * The swaps of the trade, i.e. which routes and how much is swapped in each that
1652
+ * make up the trade.
1653
+ */
1654
+ swaps;
1655
+ /**
1656
+ * The type of the trade, either exact in or exact out.
1657
+ */
1658
+ tradeType;
1659
+ /**
1660
+ * The cached result of the input amount computation
1661
+ * @private
1662
+ */
1663
+ _inputAmount;
1664
+ /**
1665
+ * The input amount for the trade assuming no slippage.
1666
+ */
1667
+ get inputAmount() {
1668
+ if (this._inputAmount) {
1669
+ return this._inputAmount;
1670
+ }
1671
+ const inputCurrency = this.swaps[0].inputAmount.currency;
1672
+ const totalInputFromRoutes = this.swaps.map(({ inputAmount }) => inputAmount).reduce((total, cur) => total.add(cur), CurrencyAmount3.fromRawAmount(inputCurrency, 0));
1673
+ this._inputAmount = totalInputFromRoutes;
1674
+ return this._inputAmount;
1675
+ }
1676
+ /**
1677
+ * The cached result of the output amount computation
1678
+ * @private
1679
+ */
1680
+ _outputAmount;
1681
+ /**
1682
+ * The output amount for the trade assuming no slippage.
1683
+ */
1684
+ get outputAmount() {
1685
+ if (this._outputAmount) {
1686
+ return this._outputAmount;
1687
+ }
1688
+ const outputCurrency = this.swaps[0].outputAmount.currency;
1689
+ const totalOutputFromRoutes = this.swaps.map(({ outputAmount }) => outputAmount).reduce((total, cur) => total.add(cur), CurrencyAmount3.fromRawAmount(outputCurrency, 0));
1690
+ this._outputAmount = totalOutputFromRoutes;
1691
+ return this._outputAmount;
1692
+ }
1693
+ /**
1694
+ * The cached result of the computed execution price
1695
+ * @private
1696
+ */
1697
+ _executionPrice;
1698
+ /**
1699
+ * The price expressed in terms of output amount/input amount.
1700
+ */
1701
+ get executionPrice() {
1702
+ return this._executionPrice ?? (this._executionPrice = new Price4(
1703
+ this.inputAmount.currency,
1704
+ this.outputAmount.currency,
1705
+ this.inputAmount.quotient,
1706
+ this.outputAmount.quotient
1707
+ ));
1708
+ }
1709
+ /**
1710
+ * The cached result of the price impact computation
1711
+ * @private
1712
+ */
1713
+ _priceImpact;
1714
+ /**
1715
+ * Returns the percent difference between the route's mid price and the price impact
1716
+ */
1717
+ get priceImpact() {
1718
+ if (this._priceImpact) {
1719
+ return this._priceImpact;
1720
+ }
1721
+ let spotOutputAmount = CurrencyAmount3.fromRawAmount(this.outputAmount.currency, 0);
1722
+ for (const { route, inputAmount } of this.swaps) {
1723
+ const midPrice = route.midPrice;
1724
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
1725
+ }
1726
+ const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
1727
+ this._priceImpact = new Percent2(priceImpact.numerator, priceImpact.denominator);
1728
+ return this._priceImpact;
1729
+ }
1730
+ /**
1731
+ * Constructs an exact in trade with the given amount in and route
1732
+ * @template TInput The input token, either Ether or an ERC-20
1733
+ * @template TOutput The output token, either Ether or an ERC-20
1734
+ * @param route The route of the exact in trade
1735
+ * @param amountIn The amount being passed in
1736
+ * @returns The exact in trade
1737
+ */
1738
+ static async exactIn(route, amountIn) {
1739
+ return _Trade.fromRoute(route, amountIn, TradeType.EXACT_INPUT);
1740
+ }
1741
+ /**
1742
+ * Constructs an exact out trade with the given amount out and route
1743
+ * @template TInput The input token, either Ether or an ERC-20
1744
+ * @template TOutput The output token, either Ether or an ERC-20
1745
+ * @param route The route of the exact out trade
1746
+ * @param amountOut The amount returned by the trade
1747
+ * @returns The exact out trade
1748
+ */
1749
+ static async exactOut(route, amountOut) {
1750
+ return _Trade.fromRoute(route, amountOut, TradeType.EXACT_OUTPUT);
1751
+ }
1752
+ /**
1753
+ * Constructs a trade by simulating swaps through the given route
1754
+ * @template TInput The input token, either Ether or an ERC-20.
1755
+ * @template TOutput The output token, either Ether or an ERC-20.
1756
+ * @template TTradeType The type of the trade, either exact in or exact out.
1757
+ * @param route route to swap through
1758
+ * @param amount the amount specified, either input or output, depending on tradeType
1759
+ * @param tradeType whether the trade is an exact input or exact output swap
1760
+ * @returns The route
1761
+ */
1762
+ static async fromRoute(route, amount, tradeType) {
1763
+ const amounts = new Array(route.tokenPath.length);
1764
+ let inputAmount;
1765
+ let outputAmount;
1766
+ if (tradeType === TradeType.EXACT_INPUT) {
1767
+ invariant10(amount.currency.equals(route.input), "INPUT");
1768
+ amounts[0] = amount.wrapped;
1769
+ for (let i = 0; i < route.tokenPath.length - 1; i++) {
1770
+ const pool = route.pools[i];
1771
+ const [outputAmount2] = await pool.getOutputAmount(amounts[i]);
1772
+ amounts[i + 1] = outputAmount2;
1773
+ }
1774
+ inputAmount = CurrencyAmount3.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1775
+ outputAmount = CurrencyAmount3.fromFractionalAmount(
1776
+ route.output,
1777
+ amounts[amounts.length - 1].numerator,
1778
+ amounts[amounts.length - 1].denominator
1779
+ );
1780
+ } else {
1781
+ invariant10(amount.currency.equals(route.output), "OUTPUT");
1782
+ amounts[amounts.length - 1] = amount.wrapped;
1783
+ for (let i = route.tokenPath.length - 1; i > 0; i--) {
1784
+ const pool = route.pools[i - 1];
1785
+ const [inputAmount2] = await pool.getInputAmount(amounts[i]);
1786
+ amounts[i - 1] = inputAmount2;
1787
+ }
1788
+ inputAmount = CurrencyAmount3.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1789
+ outputAmount = CurrencyAmount3.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1790
+ }
1791
+ return new _Trade({
1792
+ routes: [{ inputAmount, outputAmount, route }],
1793
+ tradeType
1794
+ });
1795
+ }
1796
+ /**
1797
+ * Constructs a trade from routes by simulating swaps
1798
+ *
1799
+ * @template TInput The input token, either Ether or an ERC-20.
1800
+ * @template TOutput The output token, either Ether or an ERC-20.
1801
+ * @template TTradeType The type of the trade, either exact in or exact out.
1802
+ * @param routes the routes to swap through and how much of the amount should be routed through each
1803
+ * @param tradeType whether the trade is an exact input or exact output swap
1804
+ * @returns The trade
1805
+ */
1806
+ static async fromRoutes(routes, tradeType) {
1807
+ const populatedRoutes = [];
1808
+ for (const { route, amount } of routes) {
1809
+ const amounts = new Array(route.tokenPath.length);
1810
+ let inputAmount;
1811
+ let outputAmount;
1812
+ if (tradeType === TradeType.EXACT_INPUT) {
1813
+ invariant10(amount.currency.equals(route.input), "INPUT");
1814
+ inputAmount = CurrencyAmount3.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1815
+ amounts[0] = CurrencyAmount3.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
1816
+ for (let i = 0; i < route.tokenPath.length - 1; i++) {
1817
+ const pool = route.pools[i];
1818
+ const [outputAmount2] = await pool.getOutputAmount(amounts[i]);
1819
+ amounts[i + 1] = outputAmount2;
1820
+ }
1821
+ outputAmount = CurrencyAmount3.fromFractionalAmount(
1822
+ route.output,
1823
+ amounts[amounts.length - 1].numerator,
1824
+ amounts[amounts.length - 1].denominator
1825
+ );
1826
+ } else {
1827
+ invariant10(amount.currency.equals(route.output), "OUTPUT");
1828
+ outputAmount = CurrencyAmount3.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1829
+ amounts[amounts.length - 1] = CurrencyAmount3.fromFractionalAmount(
1830
+ route.output.wrapped,
1831
+ amount.numerator,
1832
+ amount.denominator
1833
+ );
1834
+ for (let i = route.tokenPath.length - 1; i > 0; i--) {
1835
+ const pool = route.pools[i - 1];
1836
+ const [inputAmount2] = await pool.getInputAmount(amounts[i]);
1837
+ amounts[i - 1] = inputAmount2;
1838
+ }
1839
+ inputAmount = CurrencyAmount3.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1840
+ }
1841
+ populatedRoutes.push({ route, inputAmount, outputAmount });
1842
+ }
1843
+ return new _Trade({
1844
+ routes: populatedRoutes,
1845
+ tradeType
1846
+ });
1847
+ }
1848
+ /**
1849
+ * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
1850
+ * elsewhere and do not have any tick data
1851
+ * @template TInput The input token, either Ether or an ERC-20
1852
+ * @template TOutput The output token, either Ether or an ERC-20
1853
+ * @template TTradeType The type of the trade, either exact in or exact out
1854
+ * @param constructorArguments The arguments passed to the trade constructor
1855
+ * @returns The unchecked trade
1856
+ */
1857
+ static createUncheckedTrade(constructorArguments) {
1858
+ return new _Trade({
1859
+ ...constructorArguments,
1860
+ routes: [
1861
+ {
1862
+ inputAmount: constructorArguments.inputAmount,
1863
+ outputAmount: constructorArguments.outputAmount,
1864
+ route: constructorArguments.route
1865
+ }
1866
+ ]
1867
+ });
1868
+ }
1869
+ /**
1870
+ * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
1871
+ * elsewhere and do not have any tick data
1872
+ * @template TInput The input token, either Ether or an ERC-20
1873
+ * @template TOutput The output token, either Ether or an ERC-20
1874
+ * @template TTradeType The type of the trade, either exact in or exact out
1875
+ * @param constructorArguments The arguments passed to the trade constructor
1876
+ * @returns The unchecked trade
1877
+ */
1878
+ static createUncheckedTradeWithMultipleRoutes(constructorArguments) {
1879
+ return new _Trade(constructorArguments);
1880
+ }
1881
+ /**
1882
+ * Construct a trade by passing in the pre-computed property values
1883
+ * @param routes The routes through which the trade occurs
1884
+ * @param tradeType The type of trade, exact input or exact output
1885
+ */
1886
+ constructor({
1887
+ routes,
1888
+ tradeType
1889
+ }) {
1890
+ const inputCurrency = routes[0].inputAmount.currency;
1891
+ const outputCurrency = routes[0].outputAmount.currency;
1892
+ invariant10(
1893
+ routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),
1894
+ "INPUT_CURRENCY_MATCH"
1895
+ );
1896
+ invariant10(
1897
+ routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),
1898
+ "OUTPUT_CURRENCY_MATCH"
1899
+ );
1900
+ const numPools = routes.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0);
1901
+ const poolAddressSet = /* @__PURE__ */ new Set();
1902
+ for (const { route } of routes) {
1903
+ for (const pool of route.pools) {
1904
+ poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
1905
+ }
1906
+ }
1907
+ invariant10(numPools == poolAddressSet.size, "POOLS_DUPLICATED");
1908
+ this.swaps = routes;
1909
+ this.tradeType = tradeType;
1910
+ }
1911
+ /**
1912
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
1913
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1914
+ * @returns The amount out
1915
+ */
1916
+ minimumAmountOut(slippageTolerance, amountOut = this.outputAmount) {
1917
+ invariant10(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1918
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
1919
+ return amountOut;
1920
+ } else {
1921
+ const slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
1922
+ return CurrencyAmount3.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
1923
+ }
1924
+ }
1925
+ /**
1926
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1927
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1928
+ * @returns The amount in
1929
+ */
1930
+ maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
1931
+ invariant10(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1932
+ if (this.tradeType === TradeType.EXACT_INPUT) {
1933
+ return amountIn;
1934
+ } else {
1935
+ const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1936
+ return CurrencyAmount3.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1937
+ }
1938
+ }
1939
+ /**
1940
+ * Return the execution price after accounting for slippage tolerance
1941
+ * @param slippageTolerance the allowed tolerated slippage
1942
+ * @returns The execution price
1943
+ */
1944
+ worstExecutionPrice(slippageTolerance) {
1945
+ return new Price4(
1946
+ this.inputAmount.currency,
1947
+ this.outputAmount.currency,
1948
+ this.maximumAmountIn(slippageTolerance).quotient,
1949
+ this.minimumAmountOut(slippageTolerance).quotient
1950
+ );
1951
+ }
1952
+ /**
1953
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1954
+ * amount to an output token, making at most `maxHops` hops.
1955
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1956
+ * the amount in among multiple routes.
1957
+ * @param pools the pools to consider in finding the best trade
1958
+ * @param nextAmountIn exact amount of input currency to spend
1959
+ * @param currencyOut the desired currency out
1960
+ * @param maxNumResults maximum number of results to return
1961
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1962
+ * @param currentPools used in recursion; the current list of pools
1963
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1964
+ * @param bestTrades used in recursion; the current list of best trades
1965
+ * @returns The exact in trade
1966
+ */
1967
+ static async bestTradeExactIn(pools, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
1968
+ invariant10(pools.length > 0, "POOLS");
1969
+ invariant10(maxHops > 0, "MAX_HOPS");
1970
+ invariant10(currencyAmountIn === nextAmountIn || currentPools.length > 0, "INVALID_RECURSION");
1971
+ const amountIn = nextAmountIn.wrapped;
1972
+ const tokenOut = currencyOut.wrapped;
1973
+ for (let i = 0; i < pools.length; i++) {
1974
+ const pool = pools[i];
1975
+ if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency)) continue;
1976
+ let amountOut;
1977
+ try {
1978
+ ;
1979
+ [amountOut] = await pool.getOutputAmount(amountIn);
1980
+ } catch (error) {
1981
+ if (error.isInsufficientInputAmountError) {
1982
+ continue;
1983
+ }
1984
+ throw error;
1985
+ }
1986
+ if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {
1987
+ sortedInsert(
1988
+ bestTrades,
1989
+ await _Trade.fromRoute(
1990
+ new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
1991
+ currencyAmountIn,
1992
+ TradeType.EXACT_INPUT
1993
+ ),
1994
+ maxNumResults,
1995
+ tradeComparator
1996
+ );
1997
+ } else if (maxHops > 1 && pools.length > 1) {
1998
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1999
+ await _Trade.bestTradeExactIn(
2000
+ poolsExcludingThisPool,
2001
+ currencyAmountIn,
2002
+ currencyOut,
2003
+ {
2004
+ maxNumResults,
2005
+ maxHops: maxHops - 1
2006
+ },
2007
+ [...currentPools, pool],
2008
+ amountOut,
2009
+ bestTrades
2010
+ );
2011
+ }
2012
+ }
2013
+ return bestTrades;
2014
+ }
2015
+ /**
2016
+ * similar to the above method but instead targets a fixed output amount
2017
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
2018
+ * to an output token amount, making at most `maxHops` hops
2019
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
2020
+ * the amount in among multiple routes.
2021
+ * @param pools the pools to consider in finding the best trade
2022
+ * @param currencyIn the currency to spend
2023
+ * @param currencyAmountOut the desired currency amount out
2024
+ * @param nextAmountOut the exact amount of currency out
2025
+ * @param maxNumResults maximum number of results to return
2026
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
2027
+ * @param currentPools used in recursion; the current list of pools
2028
+ * @param bestTrades used in recursion; the current list of best trades
2029
+ * @returns The exact out trade
2030
+ */
2031
+ static async bestTradeExactOut(pools, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
2032
+ invariant10(pools.length > 0, "POOLS");
2033
+ invariant10(maxHops > 0, "MAX_HOPS");
2034
+ invariant10(currencyAmountOut === nextAmountOut || currentPools.length > 0, "INVALID_RECURSION");
2035
+ const amountOut = nextAmountOut.wrapped;
2036
+ const tokenIn = currencyIn.wrapped;
2037
+ for (let i = 0; i < pools.length; i++) {
2038
+ const pool = pools[i];
2039
+ if (!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency)) continue;
2040
+ let amountIn;
2041
+ try {
2042
+ ;
2043
+ [amountIn] = await pool.getInputAmount(amountOut);
2044
+ } catch (error) {
2045
+ if (error.isInsufficientReservesError) {
2046
+ continue;
2047
+ }
2048
+ throw error;
2049
+ }
2050
+ if (amountIn.currency.equals(tokenIn)) {
2051
+ sortedInsert(
2052
+ bestTrades,
2053
+ await _Trade.fromRoute(
2054
+ new Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency),
2055
+ currencyAmountOut,
2056
+ TradeType.EXACT_OUTPUT
2057
+ ),
2058
+ maxNumResults,
2059
+ tradeComparator
2060
+ );
2061
+ } else if (maxHops > 1 && pools.length > 1) {
2062
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
2063
+ await _Trade.bestTradeExactOut(
2064
+ poolsExcludingThisPool,
2065
+ currencyIn,
2066
+ currencyAmountOut,
2067
+ {
2068
+ maxNumResults,
2069
+ maxHops: maxHops - 1
2070
+ },
2071
+ [pool, ...currentPools],
2072
+ amountIn,
2073
+ bestTrades
2074
+ );
2075
+ }
2076
+ }
2077
+ return bestTrades;
2078
+ }
2079
+ };
2080
+
2081
+ // src/multicall.ts
2082
+ import { Interface } from "@ethersproject/abi";
2083
+
2084
+ // src/abi/v3-periphery/IMulticall.json
2085
+ var IMulticall_default = {
2086
+ abi: [
2087
+ {
2088
+ type: "function",
2089
+ name: "multicall",
2090
+ stateMutability: "payable",
2091
+ inputs: [{ name: "data", type: "bytes[]" }],
2092
+ outputs: [{ name: "results", type: "bytes[]" }]
2093
+ }
2094
+ ]
2095
+ };
2096
+
2097
+ // src/multicall.ts
2098
+ var Multicall = class _Multicall {
2099
+ static INTERFACE = new Interface(IMulticall_default.abi);
2100
+ /**
2101
+ * Cannot be constructed.
2102
+ */
2103
+ constructor() {
2104
+ }
2105
+ static encodeMulticall(calldatas) {
2106
+ if (!Array.isArray(calldatas)) {
2107
+ calldatas = [calldatas];
2108
+ }
2109
+ return calldatas.length === 1 ? calldatas[0] : _Multicall.INTERFACE.encodeFunctionData("multicall", [calldatas]);
2110
+ }
2111
+ };
2112
+
2113
+ // src/nonfungiblePositionManager.ts
2114
+ import {
2115
+ CurrencyAmount as CurrencyAmount4,
2116
+ validateAndParseAddress as validateAndParseAddress2
2117
+ } from "@sun-protocol/sun-sdk-core";
2118
+ import JSBI19 from "jsbi";
2119
+ import invariant11 from "tiny-invariant";
2120
+ import { Interface as Interface4 } from "@ethersproject/abi";
2121
+
2122
+ // src/abi/v3-periphery/NonfungiblePositionManager.json
2123
+ var NonfungiblePositionManager_default = {
2124
+ abi: [
2125
+ {
2126
+ type: "function",
2127
+ name: "createAndInitializePoolIfNecessary",
2128
+ stateMutability: "payable",
2129
+ inputs: [
2130
+ { name: "token0", type: "address" },
2131
+ { name: "token1", type: "address" },
2132
+ { name: "fee", type: "uint24" },
2133
+ { name: "sqrtPriceX96", type: "uint160" }
2134
+ ],
2135
+ outputs: [{ name: "pool", type: "address" }]
2136
+ },
2137
+ {
2138
+ type: "function",
2139
+ name: "mint",
2140
+ stateMutability: "payable",
2141
+ inputs: [
2142
+ {
2143
+ name: "params",
2144
+ type: "tuple",
2145
+ components: [
2146
+ { name: "token0", type: "address" },
2147
+ { name: "token1", type: "address" },
2148
+ { name: "fee", type: "uint24" },
2149
+ { name: "tickLower", type: "int24" },
2150
+ { name: "tickUpper", type: "int24" },
2151
+ { name: "amount0Desired", type: "uint256" },
2152
+ { name: "amount1Desired", type: "uint256" },
2153
+ { name: "amount0Min", type: "uint256" },
2154
+ { name: "amount1Min", type: "uint256" },
2155
+ { name: "recipient", type: "address" },
2156
+ { name: "deadline", type: "uint256" }
2157
+ ]
2158
+ }
2159
+ ],
2160
+ outputs: [
2161
+ { name: "tokenId", type: "uint256" },
2162
+ { name: "liquidity", type: "uint128" },
2163
+ { name: "amount0", type: "uint256" },
2164
+ { name: "amount1", type: "uint256" }
2165
+ ]
2166
+ },
2167
+ {
2168
+ type: "function",
2169
+ name: "increaseLiquidity",
2170
+ stateMutability: "payable",
2171
+ inputs: [
2172
+ {
2173
+ name: "params",
2174
+ type: "tuple",
2175
+ components: [
2176
+ { name: "tokenId", type: "uint256" },
2177
+ { name: "amount0Desired", type: "uint256" },
2178
+ { name: "amount1Desired", type: "uint256" },
2179
+ { name: "amount0Min", type: "uint256" },
2180
+ { name: "amount1Min", type: "uint256" },
2181
+ { name: "deadline", type: "uint256" }
2182
+ ]
2183
+ }
2184
+ ],
2185
+ outputs: [
2186
+ { name: "liquidity", type: "uint128" },
2187
+ { name: "amount0", type: "uint256" },
2188
+ { name: "amount1", type: "uint256" }
2189
+ ]
2190
+ },
2191
+ {
2192
+ type: "function",
2193
+ name: "decreaseLiquidity",
2194
+ stateMutability: "payable",
2195
+ inputs: [
2196
+ {
2197
+ name: "params",
2198
+ type: "tuple",
2199
+ components: [
2200
+ { name: "tokenId", type: "uint256" },
2201
+ { name: "liquidity", type: "uint128" },
2202
+ { name: "amount0Min", type: "uint256" },
2203
+ { name: "amount1Min", type: "uint256" },
2204
+ { name: "deadline", type: "uint256" }
2205
+ ]
2206
+ }
2207
+ ],
2208
+ outputs: [
2209
+ { name: "amount0", type: "uint256" },
2210
+ { name: "amount1", type: "uint256" }
2211
+ ]
2212
+ },
2213
+ {
2214
+ type: "function",
2215
+ name: "collect",
2216
+ stateMutability: "payable",
2217
+ inputs: [
2218
+ {
2219
+ name: "params",
2220
+ type: "tuple",
2221
+ components: [
2222
+ { name: "tokenId", type: "uint256" },
2223
+ { name: "recipient", type: "address" },
2224
+ { name: "amount0Max", type: "uint128" },
2225
+ { name: "amount1Max", type: "uint128" }
2226
+ ]
2227
+ }
2228
+ ],
2229
+ outputs: [
2230
+ { name: "amount0", type: "uint256" },
2231
+ { name: "amount1", type: "uint256" }
2232
+ ]
2233
+ },
2234
+ {
2235
+ type: "function",
2236
+ name: "permit",
2237
+ stateMutability: "payable",
2238
+ inputs: [
2239
+ { name: "spender", type: "address" },
2240
+ { name: "tokenId", type: "uint256" },
2241
+ { name: "deadline", type: "uint256" },
2242
+ { name: "v", type: "uint8" },
2243
+ { name: "r", type: "bytes32" },
2244
+ { name: "s", type: "bytes32" }
2245
+ ],
2246
+ outputs: []
2247
+ },
2248
+ { type: "function", name: "burn", stateMutability: "payable", inputs: [{ name: "tokenId", type: "uint256" }], outputs: [] },
2249
+ {
2250
+ type: "function",
2251
+ name: "safeTransferFrom",
2252
+ stateMutability: "payable",
2253
+ inputs: [
2254
+ { name: "from", type: "address" },
2255
+ { name: "to", type: "address" },
2256
+ { name: "tokenId", type: "uint256" }
2257
+ ],
2258
+ outputs: []
2259
+ },
2260
+ {
2261
+ type: "function",
2262
+ name: "safeTransferFrom",
2263
+ stateMutability: "payable",
2264
+ inputs: [
2265
+ { name: "from", type: "address" },
2266
+ { name: "to", type: "address" },
2267
+ { name: "tokenId", type: "uint256" },
2268
+ { name: "data", type: "bytes" }
2269
+ ],
2270
+ outputs: []
2271
+ }
2272
+ ]
2273
+ };
2274
+
2275
+ // src/selfPermit.ts
2276
+ import { Interface as Interface2 } from "@ethersproject/abi";
2277
+
2278
+ // src/abi/v3-periphery/ISelfPermit.json
2279
+ var ISelfPermit_default = {
2280
+ abi: [
2281
+ {
2282
+ type: "function",
2283
+ name: "selfPermit",
2284
+ stateMutability: "payable",
2285
+ inputs: [
2286
+ { name: "token", type: "address" },
2287
+ { name: "value", type: "uint256" },
2288
+ { name: "deadline", type: "uint256" },
2289
+ { name: "v", type: "uint8" },
2290
+ { name: "r", type: "bytes32" },
2291
+ { name: "s", type: "bytes32" }
2292
+ ],
2293
+ outputs: []
2294
+ },
2295
+ {
2296
+ type: "function",
2297
+ name: "selfPermitAllowed",
2298
+ stateMutability: "payable",
2299
+ inputs: [
2300
+ { name: "token", type: "address" },
2301
+ { name: "nonce", type: "uint256" },
2302
+ { name: "expiry", type: "uint256" },
2303
+ { name: "v", type: "uint8" },
2304
+ { name: "r", type: "bytes32" },
2305
+ { name: "s", type: "bytes32" }
2306
+ ],
2307
+ outputs: []
2308
+ }
2309
+ ]
2310
+ };
2311
+
2312
+ // src/selfPermit.ts
2313
+ function isAllowedPermit(permitOptions) {
2314
+ return "nonce" in permitOptions;
2315
+ }
2316
+ var SelfPermit = class _SelfPermit {
2317
+ static INTERFACE = new Interface2(ISelfPermit_default.abi);
2318
+ /**
2319
+ * Cannot be constructed.
2320
+ */
2321
+ constructor() {
2322
+ }
2323
+ static encodePermit(token, options) {
2324
+ return isAllowedPermit(options) ? _SelfPermit.INTERFACE.encodeFunctionData("selfPermitAllowed", [
2325
+ token.address,
2326
+ toHex(options.nonce),
2327
+ toHex(options.expiry),
2328
+ options.v,
2329
+ options.r,
2330
+ options.s
2331
+ ]) : _SelfPermit.INTERFACE.encodeFunctionData("selfPermit", [
2332
+ token.address,
2333
+ toHex(options.amount),
2334
+ toHex(options.deadline),
2335
+ options.v,
2336
+ options.r,
2337
+ options.s
2338
+ ]);
2339
+ }
2340
+ };
2341
+
2342
+ // src/payments.ts
2343
+ import { Interface as Interface3 } from "@ethersproject/abi";
2344
+
2345
+ // src/abi/v3-periphery/IPeripheryPaymentsWithFee.json
2346
+ var IPeripheryPaymentsWithFee_default = {
2347
+ abi: [
2348
+ {
2349
+ type: "function",
2350
+ name: "unwrapWETH9",
2351
+ stateMutability: "payable",
2352
+ inputs: [
2353
+ { name: "amountMinimum", type: "uint256" },
2354
+ { name: "recipient", type: "address" }
2355
+ ],
2356
+ outputs: []
2357
+ },
2358
+ {
2359
+ type: "function",
2360
+ name: "unwrapWETH9WithFee",
2361
+ stateMutability: "payable",
2362
+ inputs: [
2363
+ { name: "amountMinimum", type: "uint256" },
2364
+ { name: "recipient", type: "address" },
2365
+ { name: "feeBips", type: "uint256" },
2366
+ { name: "feeRecipient", type: "address" }
2367
+ ],
2368
+ outputs: []
2369
+ },
2370
+ {
2371
+ type: "function",
2372
+ name: "sweepToken",
2373
+ stateMutability: "payable",
2374
+ inputs: [
2375
+ { name: "token", type: "address" },
2376
+ { name: "amountMinimum", type: "uint256" },
2377
+ { name: "recipient", type: "address" }
2378
+ ],
2379
+ outputs: []
2380
+ },
2381
+ {
2382
+ type: "function",
2383
+ name: "sweepTokenWithFee",
2384
+ stateMutability: "payable",
2385
+ inputs: [
2386
+ { name: "token", type: "address" },
2387
+ { name: "amountMinimum", type: "uint256" },
2388
+ { name: "recipient", type: "address" },
2389
+ { name: "feeBips", type: "uint256" },
2390
+ { name: "feeRecipient", type: "address" }
2391
+ ],
2392
+ outputs: []
2393
+ },
2394
+ {
2395
+ type: "function",
2396
+ name: "refundETH",
2397
+ stateMutability: "payable",
2398
+ inputs: [],
2399
+ outputs: []
2400
+ }
2401
+ ]
2402
+ };
2403
+
2404
+ // src/payments.ts
2405
+ import { validateAndParseAddress } from "@sun-protocol/sun-sdk-core";
2406
+ var Payments = class _Payments {
2407
+ static INTERFACE = new Interface3(IPeripheryPaymentsWithFee_default.abi);
2408
+ /**
2409
+ * Cannot be constructed.
2410
+ */
2411
+ constructor() {
2412
+ }
2413
+ static encodeFeeBips(fee) {
2414
+ return toHex(fee.multiply(1e4).quotient);
2415
+ }
2416
+ static encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
2417
+ recipient = validateAndParseAddress(recipient);
2418
+ if (feeOptions) {
2419
+ const feeBips = this.encodeFeeBips(feeOptions.fee);
2420
+ const feeRecipient = validateAndParseAddress(feeOptions.recipient);
2421
+ return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9WithFee", [
2422
+ toHex(amountMinimum),
2423
+ recipient,
2424
+ feeBips,
2425
+ feeRecipient
2426
+ ]);
2427
+ } else {
2428
+ return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9", [toHex(amountMinimum), recipient]);
2429
+ }
2430
+ }
2431
+ static encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
2432
+ recipient = validateAndParseAddress(recipient);
2433
+ if (feeOptions) {
2434
+ const feeBips = this.encodeFeeBips(feeOptions.fee);
2435
+ const feeRecipient = validateAndParseAddress(feeOptions.recipient);
2436
+ return _Payments.INTERFACE.encodeFunctionData("sweepTokenWithFee", [
2437
+ token.address,
2438
+ toHex(amountMinimum),
2439
+ recipient,
2440
+ feeBips,
2441
+ feeRecipient
2442
+ ]);
2443
+ } else {
2444
+ return _Payments.INTERFACE.encodeFunctionData("sweepToken", [token.address, toHex(amountMinimum), recipient]);
2445
+ }
2446
+ }
2447
+ static encodeRefundETH() {
2448
+ return _Payments.INTERFACE.encodeFunctionData("refundETH");
2449
+ }
2450
+ };
2451
+
2452
+ // src/nonfungiblePositionManager.ts
2453
+ var MaxUint1282 = toHex(JSBI19.subtract(JSBI19.exponentiate(JSBI19.BigInt(2), JSBI19.BigInt(128)), JSBI19.BigInt(1)));
2454
+ function isMint(options) {
2455
+ return Object.keys(options).some((k) => k === "recipient");
2456
+ }
2457
+ var NonfungiblePositionManager = class _NonfungiblePositionManager {
2458
+ static INTERFACE = new Interface4(NonfungiblePositionManager_default.abi);
2459
+ /**
2460
+ * Cannot be constructed.
2461
+ */
2462
+ constructor() {
2463
+ }
2464
+ static encodeCreate(pool) {
2465
+ return _NonfungiblePositionManager.INTERFACE.encodeFunctionData("createAndInitializePoolIfNecessary", [
2466
+ pool.token0.address,
2467
+ pool.token1.address,
2468
+ pool.fee,
2469
+ toHex(pool.sqrtRatioX96)
2470
+ ]);
2471
+ }
2472
+ static createCallParameters(pool) {
2473
+ return {
2474
+ calldata: this.encodeCreate(pool),
2475
+ function_selector: "createAndInitializePoolIfNecessary(address,address,uint24,uint160)",
2476
+ parameter: [
2477
+ { type: "address", value: pool.token0.address },
2478
+ { type: "address", value: pool.token1.address },
2479
+ { type: "uint24", value: pool.fee },
2480
+ { type: "uint160", value: pool.sqrtRatioX96 }
2481
+ ],
2482
+ value: toHex(0)
2483
+ };
2484
+ }
2485
+ static addCallParameters(position, options) {
2486
+ invariant11(JSBI19.greaterThan(position.liquidity, ZERO), "ZERO_LIQUIDITY");
2487
+ const calldatas = [];
2488
+ const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts;
2489
+ const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
2490
+ const amount0Min = toHex(minimumAmounts.amount0);
2491
+ const amount1Min = toHex(minimumAmounts.amount1);
2492
+ const deadline = toHex(options.deadline);
2493
+ if (isMint(options) && options.createPool) {
2494
+ calldatas.push(this.encodeCreate(position.pool));
2495
+ }
2496
+ if (options.token0Permit) {
2497
+ calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
2498
+ }
2499
+ if (options.token1Permit) {
2500
+ calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
2501
+ }
2502
+ if (isMint(options)) {
2503
+ const recipient = validateAndParseAddress2(options.recipient);
2504
+ calldatas.push(
2505
+ _NonfungiblePositionManager.INTERFACE.encodeFunctionData("mint", [
2506
+ {
2507
+ token0: position.pool.token0.address,
2508
+ token1: position.pool.token1.address,
2509
+ fee: position.pool.fee,
2510
+ tickLower: position.tickLower,
2511
+ tickUpper: position.tickUpper,
2512
+ amount0Desired: toHex(amount0Desired),
2513
+ amount1Desired: toHex(amount1Desired),
2514
+ amount0Min,
2515
+ amount1Min,
2516
+ recipient,
2517
+ deadline
2518
+ }
2519
+ ])
2520
+ );
2521
+ } else {
2522
+ calldatas.push(
2523
+ _NonfungiblePositionManager.INTERFACE.encodeFunctionData("increaseLiquidity", [
2524
+ {
2525
+ tokenId: toHex(options.tokenId),
2526
+ amount0Desired: toHex(amount0Desired),
2527
+ amount1Desired: toHex(amount1Desired),
2528
+ amount0Min,
2529
+ amount1Min,
2530
+ deadline
2531
+ }
2532
+ ])
2533
+ );
2534
+ }
2535
+ let value = toHex(0);
2536
+ if (options.useNative) {
2537
+ const wrapped = options.useNative.wrapped;
2538
+ invariant11(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
2539
+ const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
2540
+ if (JSBI19.greaterThan(wrappedValue, ZERO)) {
2541
+ calldatas.push(Payments.encodeRefundETH());
2542
+ }
2543
+ value = toHex(wrappedValue);
2544
+ }
2545
+ const parameter = [];
2546
+ parameter.push({
2547
+ type: "bytes[]",
2548
+ value: calldatas
2549
+ });
2550
+ return {
2551
+ calldata: Multicall.encodeMulticall(calldatas),
2552
+ function_selector: "multicall(bytes[])",
2553
+ parameter,
2554
+ value
2555
+ };
2556
+ }
2557
+ static encodeCollect(options) {
2558
+ const calldatas = [];
2559
+ const tokenId = toHex(options.tokenId);
2560
+ const involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
2561
+ const recipient = validateAndParseAddress2(options.recipient);
2562
+ calldatas.push(
2563
+ _NonfungiblePositionManager.INTERFACE.encodeFunctionData("collect", [
2564
+ {
2565
+ tokenId,
2566
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
2567
+ amount0Max: MaxUint1282,
2568
+ amount1Max: MaxUint1282
2569
+ }
2570
+ ])
2571
+ );
2572
+ if (involvesETH) {
2573
+ const ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
2574
+ const token = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.currency : options.expectedCurrencyOwed0.currency;
2575
+ const tokenAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.quotient : options.expectedCurrencyOwed0.quotient;
2576
+ calldatas.push(Payments.encodeUnwrapWETH9(ethAmount, recipient));
2577
+ calldatas.push(Payments.encodeSweepToken(token, tokenAmount, recipient));
2578
+ }
2579
+ return calldatas;
2580
+ }
2581
+ static collectCallParameters(options) {
2582
+ const calldatas = _NonfungiblePositionManager.encodeCollect(options);
2583
+ const parameter = [];
2584
+ parameter.push({
2585
+ type: "bytes[]",
2586
+ value: calldatas
2587
+ });
2588
+ return {
2589
+ calldata: Multicall.encodeMulticall(calldatas),
2590
+ function_selector: "multicall(bytes[])",
2591
+ parameter,
2592
+ value: toHex(0)
2593
+ };
2594
+ }
2595
+ /**
2596
+ * Produces the calldata for completely or partially exiting a position
2597
+ * @param position The position to exit
2598
+ * @param options Additional information necessary for generating the calldata
2599
+ * @returns The call parameters
2600
+ */
2601
+ static removeCallParameters(position, options) {
2602
+ const calldatas = [];
2603
+ const deadline = toHex(options.deadline);
2604
+ const tokenId = toHex(options.tokenId);
2605
+ const partialPosition = new Position({
2606
+ pool: position.pool,
2607
+ liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
2608
+ tickLower: position.tickLower,
2609
+ tickUpper: position.tickUpper
2610
+ });
2611
+ invariant11(JSBI19.greaterThan(partialPosition.liquidity, ZERO), "ZERO_LIQUIDITY");
2612
+ const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
2613
+ options.slippageTolerance
2614
+ );
2615
+ if (options.permit) {
2616
+ calldatas.push(
2617
+ _NonfungiblePositionManager.INTERFACE.encodeFunctionData("permit", [
2618
+ validateAndParseAddress2(options.permit.spender),
2619
+ tokenId,
2620
+ toHex(options.permit.deadline),
2621
+ options.permit.v,
2622
+ options.permit.r,
2623
+ options.permit.s
2624
+ ])
2625
+ );
2626
+ }
2627
+ calldatas.push(
2628
+ _NonfungiblePositionManager.INTERFACE.encodeFunctionData("decreaseLiquidity", [
2629
+ {
2630
+ tokenId,
2631
+ liquidity: toHex(partialPosition.liquidity),
2632
+ amount0Min: toHex(amount0Min),
2633
+ amount1Min: toHex(amount1Min),
2634
+ deadline
2635
+ }
2636
+ ])
2637
+ );
2638
+ const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions;
2639
+ calldatas.push(
2640
+ ..._NonfungiblePositionManager.encodeCollect({
2641
+ tokenId: toHex(options.tokenId),
2642
+ // add the underlying value to the expected currency already owed
2643
+ expectedCurrencyOwed0: expectedCurrencyOwed0.add(
2644
+ CurrencyAmount4.fromRawAmount(expectedCurrencyOwed0.currency, amount0Min)
2645
+ ),
2646
+ expectedCurrencyOwed1: expectedCurrencyOwed1.add(
2647
+ CurrencyAmount4.fromRawAmount(expectedCurrencyOwed1.currency, amount1Min)
2648
+ ),
2649
+ ...rest
2650
+ })
2651
+ );
2652
+ if (options.liquidityPercentage.equalTo(ONE)) {
2653
+ if (options.burnToken) {
2654
+ calldatas.push(_NonfungiblePositionManager.INTERFACE.encodeFunctionData("burn", [tokenId]));
2655
+ }
2656
+ } else {
2657
+ invariant11(options.burnToken !== true, "CANNOT_BURN");
2658
+ }
2659
+ const parameter = [];
2660
+ parameter.push({
2661
+ type: "bytes[]",
2662
+ value: calldatas
2663
+ });
2664
+ return {
2665
+ calldata: Multicall.encodeMulticall(calldatas),
2666
+ function_selector: "multicall(bytes[])",
2667
+ parameter,
2668
+ value: toHex(0)
2669
+ };
2670
+ }
2671
+ static safeTransferFromParameters(options) {
2672
+ const recipient = validateAndParseAddress2(options.recipient);
2673
+ const sender = validateAndParseAddress2(options.sender);
2674
+ let calldata;
2675
+ let function_selector;
2676
+ let parameter;
2677
+ if (options.data) {
2678
+ calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData(
2679
+ "safeTransferFrom(address,address,uint256,bytes)",
2680
+ [sender, recipient, toHex(options.tokenId), options.data]
2681
+ );
2682
+ function_selector = "safeTransferFrom(address,address,uint256,bytes)";
2683
+ parameter = [
2684
+ { type: "address", value: sender },
2685
+ { type: "address", value: recipient },
2686
+ { type: "uint256", value: options.tokenId },
2687
+ { type: "bytes", value: options.data }
2688
+ ];
2689
+ } else {
2690
+ calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData("safeTransferFrom(address,address,uint256)", [
2691
+ sender,
2692
+ recipient,
2693
+ toHex(options.tokenId)
2694
+ ]);
2695
+ function_selector = "safeTransferFrom(address,address,uint256)";
2696
+ parameter = [
2697
+ { type: "address", value: sender },
2698
+ { type: "address", value: recipient },
2699
+ { type: "uint256", value: options.tokenId }
2700
+ ];
2701
+ }
2702
+ return {
2703
+ calldata,
2704
+ function_selector,
2705
+ parameter,
2706
+ value: toHex(0)
2707
+ };
2708
+ }
2709
+ };
2710
+
2711
+ // src/pool-address.ts
2712
+ import { getContractAddress as getContractAddress2, getWrappedNativeAddress } from "@sun-protocol/sun-sdk-chains";
2713
+ import { keccak256 as keccak2563 } from "@ethersproject/keccak256";
2714
+ import { sha256 } from "@noble/hashes/sha256";
2715
+ import { SDK_ERROR_CODES as SDK_ERROR_CODES2, sdkInvariant as sdkInvariant2 } from "@sun-protocol/sun-sdk-core";
2716
+ var V3_INIT_CODE_HASH = {
2717
+ mainnet: "0xba928a717d71946d75999ef1adef801a79cd34a20efecea8b2876b85f5f49580",
2718
+ nile: "0xbdafe9a36668104a2d371dedf31aac9583722f1b2c2fe98dde229f50a1e81689"
2719
+ };
2720
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2721
+ var BASE58_ZERO = "1";
2722
+ var HEX_20_BYTES_PATTERN = /^0x[a-fA-F0-9]{40}$/;
2723
+ var HEX_32_BYTES_PATTERN = /^0x?[a-fA-F0-9]{64}$/;
2724
+ var TRON_ADDRESS_PAYLOAD_BYTES = 25;
2725
+ var TRON_ADDRESS_BYTES = 21;
2726
+ var TRON_PREFIX_HEX = "41";
2727
+ var TRON_ZERO_ADDRESS = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb";
2728
+ function decodeBase58(value) {
2729
+ let decoded = 0n;
2730
+ for (const char of value) {
2731
+ const index = BASE58_ALPHABET.indexOf(char);
2732
+ sdkInvariant2(index >= 0, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, "Invalid base58 character", { value, char });
2733
+ decoded = decoded * 58n + BigInt(index);
2734
+ }
2735
+ const bytes = [];
2736
+ while (decoded > 0n) {
2737
+ bytes.unshift(Number(decoded & 0xffn));
2738
+ decoded >>= 8n;
2739
+ }
2740
+ for (const char of value) {
2741
+ if (char !== BASE58_ZERO) break;
2742
+ bytes.unshift(0);
2743
+ }
2744
+ return Uint8Array.from(bytes);
2745
+ }
2746
+ function encodeBase58(bytes) {
2747
+ let value = 0n;
2748
+ for (const byte of bytes) {
2749
+ value = (value << 8n) + BigInt(byte);
2750
+ }
2751
+ let encoded = "";
2752
+ while (value > 0n) {
2753
+ const mod = Number(value % 58n);
2754
+ const char = BASE58_ALPHABET[mod];
2755
+ sdkInvariant2(char !== void 0, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, "Invalid base58 remainder", { mod });
2756
+ encoded = char + encoded;
2757
+ value /= 58n;
2758
+ }
2759
+ for (const byte of bytes) {
2760
+ if (byte !== 0) break;
2761
+ encoded = `${BASE58_ZERO}${encoded}`;
2762
+ }
2763
+ return encoded || BASE58_ZERO;
2764
+ }
2765
+ function bytesToHex(bytes) {
2766
+ return Array.from(bytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
2767
+ }
2768
+ function hexToBytes(hex, label) {
2769
+ const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
2770
+ sdkInvariant2(/^[a-fA-F0-9]*$/.test(normalized) && normalized.length % 2 === 0, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, `${label} must be even-length hex`, {
2771
+ label,
2772
+ value: hex
2773
+ });
2774
+ const bytes = new Uint8Array(normalized.length / 2);
2775
+ for (let i = 0; i < bytes.length; i += 1) {
2776
+ bytes[i] = Number.parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
2777
+ }
2778
+ return bytes;
2779
+ }
2780
+ function checksum(payload) {
2781
+ return sha256(sha256(payload)).slice(0, 4);
2782
+ }
2783
+ function tronPayloadToBase58(payload) {
2784
+ const bytes = new Uint8Array(TRON_ADDRESS_PAYLOAD_BYTES);
2785
+ bytes.set(payload, 0);
2786
+ bytes.set(checksum(payload), TRON_ADDRESS_BYTES);
2787
+ return encodeBase58(bytes);
2788
+ }
2789
+ function tronAddressToEvmHex(address, label) {
2790
+ if (HEX_20_BYTES_PATTERN.test(address)) return address.slice(2).toLowerCase();
2791
+ const decoded = decodeBase58(address);
2792
+ sdkInvariant2(
2793
+ decoded.length === TRON_ADDRESS_PAYLOAD_BYTES,
2794
+ SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT,
2795
+ `${label} must be a TRON base58 address or 20-byte EVM hex address`,
2796
+ { label, value: address }
2797
+ );
2798
+ const body = decoded.slice(0, TRON_ADDRESS_BYTES);
2799
+ const expectedChecksum = checksum(body);
2800
+ const actualChecksum = decoded.slice(TRON_ADDRESS_BYTES);
2801
+ sdkInvariant2(
2802
+ bytesToHex(expectedChecksum) === bytesToHex(actualChecksum),
2803
+ SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT,
2804
+ `${label} has invalid TRON base58 checksum`,
2805
+ { label, value: address }
2806
+ );
2807
+ sdkInvariant2(body[0] === 65, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, `${label} must use TRON 0x41 prefix`, {
2808
+ label,
2809
+ value: address
2810
+ });
2811
+ return bytesToHex(body.slice(1));
2812
+ }
2813
+ function normalizeV3InitCodeHash(value) {
2814
+ sdkInvariant2(HEX_32_BYTES_PATTERN.test(value), SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, "V3 initCodeHash must be bytes32 hex", {
2815
+ value
2816
+ });
2817
+ return value.startsWith("0x") ? value.slice(2).toLowerCase() : value.toLowerCase();
2818
+ }
2819
+ function normalizeV3TokenAddress(token, wrappedNative, label) {
2820
+ const address = typeof token === "string" ? token : token.address;
2821
+ const normalized = address === TRON_ZERO_ADDRESS ? wrappedNative : address;
2822
+ return tronAddressToEvmHex(normalized, label);
2823
+ }
2824
+ function encodeV3PoolSalt(token0, token1, fee) {
2825
+ sdkInvariant2(Number.isInteger(fee) && fee >= 0 && fee <= 16777215, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, "V3 fee must be uint24", {
2826
+ fee
2827
+ });
2828
+ return `${token0.padStart(64, "0")}${token1.padStart(64, "0")}${fee.toString(16).padStart(64, "0")}`;
2829
+ }
2830
+ function computeV3PoolAddress(params) {
2831
+ const wrappedNative = params.wrappedNative ?? getWrappedNativeAddress(params.network);
2832
+ const tokenA = normalizeV3TokenAddress(params.tokenA, wrappedNative, "tokenA");
2833
+ const tokenB = normalizeV3TokenAddress(params.tokenB, wrappedNative, "tokenB");
2834
+ sdkInvariant2(tokenA !== tokenB, SDK_ERROR_CODES2.SDK_INVALID_ARGUMENT, "V3 pool tokens must be different", {
2835
+ tokenA: typeof params.tokenA === "string" ? params.tokenA : params.tokenA.address,
2836
+ tokenB: typeof params.tokenB === "string" ? params.tokenB : params.tokenB.address
2837
+ });
2838
+ const [token0, token1] = tokenA < tokenB ? [tokenA, tokenB] : [tokenB, tokenA];
2839
+ const factory = tronAddressToEvmHex(params.factory ?? getContractAddress2(params.network, "sunswapV3Factory"), "factory");
2840
+ const salt = keccak2563(hexToBytes(encodeV3PoolSalt(token0, token1, params.fee), "pool salt")).slice(2);
2841
+ const initCodeHash = normalizeV3InitCodeHash(params.initCodeHash ?? V3_INIT_CODE_HASH[params.network]);
2842
+ const hash = keccak2563(hexToBytes(`${TRON_PREFIX_HEX}${factory}${salt}${initCodeHash}`, "CREATE2 input")).slice(2);
2843
+ return tronPayloadToBase58(hexToBytes(`${TRON_PREFIX_HEX}${hash.slice(-40)}`, "pool address"));
2844
+ }
2845
+
2846
+ // src/reads.ts
2847
+ import { getContractAddress as getContractAddress3 } from "@sun-protocol/sun-sdk-chains";
2848
+ import JSBI20 from "jsbi";
2849
+ var V3_POOL_READ_SELECTORS = {
2850
+ slot0: "slot0()",
2851
+ liquidity: "liquidity()",
2852
+ fee: "fee()",
2853
+ tickSpacing: "tickSpacing()"
2854
+ };
2855
+ var V3_POSITION_MANAGER_READ_SELECTORS = {
2856
+ positions: "positions(uint256)",
2857
+ ownerOf: "ownerOf(uint256)",
2858
+ getApproved: "getApproved(uint256)",
2859
+ isApprovedForAll: "isApprovedForAll(address,address)"
2860
+ };
2861
+ function valueOf2(value) {
2862
+ return JSBI20.BigInt(value).toString();
2863
+ }
2864
+ function positionManagerTarget2(params) {
2865
+ return params.positionManager ?? getContractAddress3(params.network, "sunswapV3PositionManager");
2866
+ }
2867
+ function poolRead(pool, functionSelector, abiFunction) {
2868
+ return {
2869
+ target: pool,
2870
+ functionSelector,
2871
+ abiFunction,
2872
+ metadata: { protocol: "sunswap-v3", contract: "pool" }
2873
+ };
2874
+ }
2875
+ function positionManagerRead(params, functionSelector, parameters, abiFunction, action) {
2876
+ return {
2877
+ target: positionManagerTarget2(params),
2878
+ functionSelector,
2879
+ parameters,
2880
+ abiFunction,
2881
+ metadata: { protocol: "sunswap-v3", contract: "position-manager", action, network: params.network }
2882
+ };
2883
+ }
2884
+ function buildV3PoolSlot0Read(params) {
2885
+ return poolRead(params.pool, V3_POOL_READ_SELECTORS.slot0, V3_POOL_SLOT0_ABI);
2886
+ }
2887
+ function buildV3PoolLiquidityRead(params) {
2888
+ return poolRead(params.pool, V3_POOL_READ_SELECTORS.liquidity, V3_POOL_LIQUIDITY_ABI);
2889
+ }
2890
+ function buildV3PoolFeeRead(params) {
2891
+ return poolRead(params.pool, V3_POOL_READ_SELECTORS.fee, V3_POOL_FEE_ABI);
2892
+ }
2893
+ function buildV3PoolTickSpacingRead(params) {
2894
+ return poolRead(params.pool, V3_POOL_READ_SELECTORS.tickSpacing, V3_POOL_TICK_SPACING_ABI);
2895
+ }
2896
+ function buildV3PoolStateReads(params) {
2897
+ return [
2898
+ buildV3PoolSlot0Read(params),
2899
+ buildV3PoolLiquidityRead(params),
2900
+ buildV3PoolFeeRead(params),
2901
+ buildV3PoolTickSpacingRead(params)
2902
+ ];
2903
+ }
2904
+ function buildV3PositionRead(params) {
2905
+ return positionManagerRead(
2906
+ params,
2907
+ V3_POSITION_MANAGER_READ_SELECTORS.positions,
2908
+ [{ type: "uint256", value: valueOf2(params.tokenId) }],
2909
+ V3_POSITION_MANAGER_POSITIONS_ABI,
2910
+ "positions"
2911
+ );
2912
+ }
2913
+ function buildV3PositionOwnerRead(params) {
2914
+ return positionManagerRead(
2915
+ params,
2916
+ V3_POSITION_MANAGER_READ_SELECTORS.ownerOf,
2917
+ [{ type: "uint256", value: valueOf2(params.tokenId) }],
2918
+ V3_POSITION_MANAGER_OWNER_OF_ABI,
2919
+ "owner-of"
2920
+ );
2921
+ }
2922
+ function buildV3PositionApprovedRead(params) {
2923
+ return positionManagerRead(
2924
+ params,
2925
+ V3_POSITION_MANAGER_READ_SELECTORS.getApproved,
2926
+ [{ type: "uint256", value: valueOf2(params.tokenId) }],
2927
+ V3_POSITION_MANAGER_GET_APPROVED_ABI,
2928
+ "get-approved"
2929
+ );
2930
+ }
2931
+ function buildV3PositionApprovalForAllRead(params) {
2932
+ return positionManagerRead(
2933
+ params,
2934
+ V3_POSITION_MANAGER_READ_SELECTORS.isApprovedForAll,
2935
+ [
2936
+ { type: "address", value: params.owner },
2937
+ { type: "address", value: params.operator }
2938
+ ],
2939
+ V3_POSITION_MANAGER_IS_APPROVED_FOR_ALL_ABI,
2940
+ "is-approved-for-all"
2941
+ );
2942
+ }
2943
+ function buildV3PositionReads(params) {
2944
+ return [
2945
+ buildV3PositionRead(params),
2946
+ buildV3PositionOwnerRead(params),
2947
+ buildV3PositionApprovedRead(params)
2948
+ ];
2949
+ }
2950
+ export {
2951
+ ADDRESS_ZERO,
2952
+ FACTORY_ADDRESS,
2953
+ FeeAmount,
2954
+ FullMath,
2955
+ IS_TVM,
2956
+ LiquidityMath,
2957
+ MaxUint128,
2958
+ Multicall,
2959
+ NoTickDataProvider,
2960
+ NonfungiblePositionManager,
2961
+ POOL_INIT_CODE_HASH,
2962
+ Payments,
2963
+ Pool,
2964
+ Position,
2965
+ PositionLibrary,
2966
+ Route,
2967
+ SelfPermit,
2968
+ SqrtPriceMath,
2969
+ SwapMath,
2970
+ TICK_SPACINGS,
2971
+ Tick,
2972
+ TickLibrary,
2973
+ TickList,
2974
+ TickListDataProvider,
2975
+ TickMath,
2976
+ Trade,
2977
+ V3_INIT_CODE_HASH,
2978
+ V3_POOL_FEE_ABI,
2979
+ V3_POOL_LIQUIDITY_ABI,
2980
+ V3_POOL_READ_SELECTORS,
2981
+ V3_POOL_SLOT0_ABI,
2982
+ V3_POOL_TICK_SPACING_ABI,
2983
+ V3_POSITION_MANAGER_GET_APPROVED_ABI,
2984
+ V3_POSITION_MANAGER_IS_APPROVED_FOR_ALL_ABI,
2985
+ V3_POSITION_MANAGER_OWNER_OF_ABI,
2986
+ V3_POSITION_MANAGER_POSITIONS_ABI,
2987
+ V3_POSITION_MANAGER_READ_SELECTORS,
2988
+ V3_POSITION_MANAGER_SELECTORS,
2989
+ buildV3CollectAction,
2990
+ buildV3CreatePoolAction,
2991
+ buildV3DecreaseLiquidityAction,
2992
+ buildV3IncreaseLiquidityAction,
2993
+ buildV3MintPositionAction,
2994
+ buildV3PoolFeeRead,
2995
+ buildV3PoolLiquidityRead,
2996
+ buildV3PoolSlot0Read,
2997
+ buildV3PoolStateReads,
2998
+ buildV3PoolTickSpacingRead,
2999
+ buildV3PositionApprovalForAllRead,
3000
+ buildV3PositionApprovedRead,
3001
+ buildV3PositionOwnerRead,
3002
+ buildV3PositionRead,
3003
+ buildV3PositionReads,
3004
+ computePoolAddress,
3005
+ computeV3PoolAddress,
3006
+ encodeRouteToPath,
3007
+ encodeSqrtRatioX96,
3008
+ getTickSpacing,
3009
+ getTronCreate2Address,
3010
+ isSorted,
3011
+ isSupportedFeeAmount,
3012
+ maxLiquidityForAmounts,
3013
+ mostSignificantBit,
3014
+ nearestUsableTick,
3015
+ priceToClosestTick,
3016
+ subIn256,
3017
+ tickToPrice,
3018
+ toHex,
3019
+ tradeComparator,
3020
+ validateTickRange,
3021
+ validateTickRangeForFee,
3022
+ validateTickSpacing
3023
+ };
3024
+ //# sourceMappingURL=index.js.map