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