@pafi-dev/trading 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,12 +20,34 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ CALLDATA_BYTES_PER_CALL: () => CALLDATA_BYTES_PER_CALL,
24
+ LiquidityCurveError: () => LiquidityCurveError,
25
+ LiquidityCurveErrorCode: () => LiquidityCurveErrorCode,
26
+ MAX_SQRT_RATIO: () => MAX_SQRT_RATIO,
27
+ MAX_TICK: () => MAX_TICK,
28
+ MIN_SQRT_RATIO: () => MIN_SQRT_RATIO,
29
+ MIN_TICK: () => MIN_TICK,
23
30
  PAFI_SUBGRAPH_URL: () => import_core10.PAFI_SUBGRAPH_URL,
31
+ Q192: () => Q192,
32
+ Q96: () => Q96,
24
33
  TradingHandlers: () => TradingHandlers,
34
+ UINT128_MAX: () => UINT128_MAX2,
35
+ V3_NPM_ADDRESSES: () => V3_NPM_ADDRESSES,
25
36
  V3_SWAP_EXACT_IN: () => V3_SWAP_EXACT_IN,
26
37
  V3_SWAP_EXACT_OUT: () => V3_SWAP_EXACT_OUT,
38
+ addLiquidityDirect: () => addLiquidityDirect,
39
+ applyMintSlippage: () => applyMintSlippage,
40
+ applyRemoveSlippage: () => applyRemoveSlippage,
41
+ bitmapWordRange: () => bitmapWordRange,
27
42
  buildAllPaths: () => buildAllPaths,
43
+ buildBurn: () => buildBurn,
44
+ buildClosePosition: () => buildClosePosition,
45
+ buildCollect: () => buildCollect,
46
+ buildDecreaseLiquidity: () => buildDecreaseLiquidity,
28
47
  buildErc20ApprovalCalldata: () => buildErc20ApprovalCalldata,
48
+ buildIncreaseLiquidity: () => buildIncreaseLiquidity,
49
+ buildLiquidityCurve: () => buildLiquidityCurve,
50
+ buildMint: () => buildMint,
29
51
  buildPermit2ApprovalCalldata: () => buildPermit2ApprovalCalldata,
30
52
  buildSwapUserOp: () => buildSwapUserOp,
31
53
  buildSwapUserOpExactOut: () => buildSwapUserOpExactOut,
@@ -34,20 +56,49 @@ __export(index_exports, {
34
56
  buildV3SwapInputExactIn: () => buildV3SwapInputExactIn,
35
57
  buildV3SwapInputExactOut: () => buildV3SwapInputExactOut,
36
58
  checkAllowance: () => checkAllowance,
59
+ clipCurveToTickRange: () => clipCurveToTickRange,
60
+ closePositionDirect: () => closePositionDirect,
61
+ collectFeesDirect: () => collectFeesDirect,
37
62
  combineRoutes: () => combineRoutes,
63
+ decodeBitmapWord: () => decodeBitmapWord,
64
+ estimateLiquidityFromOneSide: () => estimateLiquidityFromOneSide,
65
+ fetchAllInitializedTicks: () => fetchAllInitializedTicks,
66
+ fetchLiquidityCurve: () => fetchLiquidityCurve,
38
67
  fetchPafiPools: () => import_core10.fetchPafiPools,
39
68
  findBestQuote: () => findBestQuote,
40
69
  findBestQuoteExactOut: () => findBestQuoteExactOut,
70
+ getAmount0ForLiquidity: () => getAmount0ForLiquidity,
71
+ getAmount1ForLiquidity: () => getAmount1ForLiquidity,
72
+ getAmountsForLiquidity: () => getAmountsForLiquidity,
73
+ getLiquidityForAmount0: () => getLiquidityForAmount0,
74
+ getLiquidityForAmount1: () => getLiquidityForAmount1,
75
+ increaseLiquidityDirect: () => increaseLiquidityDirect,
76
+ maxUsableTick: () => maxUsableTick,
77
+ minUsableTick: () => minUsableTick,
78
+ nearestUsableTick: () => nearestUsableTick,
79
+ nonfungiblePositionManagerAbi: () => nonfungiblePositionManagerAbi,
41
80
  perpDepositDirect: () => perpDepositDirect,
81
+ priceToTick: () => priceToTick,
42
82
  quoteBestRoute: () => quoteBestRoute,
43
83
  quoteBestRouteExactOut: () => quoteBestRouteExactOut,
44
84
  quoteExactInput: () => quoteExactInput,
45
85
  quoteExactInputSingle: () => quoteExactInputSingle,
46
86
  quoteExactOutput: () => quoteExactOutput,
47
87
  quoteExactOutputSingle: () => quoteExactOutputSingle,
88
+ readFeeGrowthGlobals: () => readFeeGrowthGlobals,
89
+ readPoolState: () => readPoolState,
90
+ readPosition: () => readPosition,
91
+ readTicksAt: () => readTicksAt,
92
+ removeLiquidityDirect: () => removeLiquidityDirect,
48
93
  simulateSwap: () => simulateSwap,
94
+ sqrtPriceX96ToTick: () => sqrtPriceX96ToTick,
49
95
  swapDirect: () => swapDirect,
50
- swapDirectExactOut: () => swapDirectExactOut
96
+ swapDirectExactOut: () => swapDirectExactOut,
97
+ tickSpacingForFee: () => tickSpacingForFee,
98
+ tickToBitmapPosition: () => tickToBitmapPosition,
99
+ tickToPrice: () => tickToPrice,
100
+ tickToSqrtPriceX96: () => tickToSqrtPriceX96,
101
+ v3PoolAbi: () => v3PoolAbi
51
102
  });
52
103
  module.exports = __toCommonJS(index_exports);
53
104
 
@@ -1134,6 +1185,117 @@ var TradingHandlers = class {
1134
1185
  feeRecipient: pafiFeeRecipient
1135
1186
  };
1136
1187
  }
1188
+ // =========================================================================
1189
+ // POST /erc20-transfer — gasless ERC-20 send (USDC/USDT/active-PT)
1190
+ // =========================================================================
1191
+ /**
1192
+ * Build a sponsored ERC-20 transfer UserOp pair (sponsored + fallback).
1193
+ *
1194
+ * Sponsored variant: `[token.transfer(PAFI, fee), token.transfer(recipient, amount)]`.
1195
+ * Fallback variant: `[token.transfer(recipient, amount)]` (user pays ETH).
1196
+ *
1197
+ * Both calls hit the SAME token contract — fee currency equals the
1198
+ * token being sent, so the user needs only ONE token (≥ `amount + fee`)
1199
+ * to complete a gasless send.
1200
+ *
1201
+ * Allowlist enforced HERE (client-side fail-fast) **and** server-side
1202
+ * by sponsor-relayer's IntentValidator:
1203
+ * - USDC (`getContractAddresses(chainId).usdc`)
1204
+ * - USDT (`getContractAddresses(chainId).usdt`)
1205
+ * - active PointToken (caller responsibility to check
1206
+ * `IssuerRegistry.isActiveByPointToken` if not stable)
1207
+ *
1208
+ * Recipient rejected when equal to `pafiFeeRecipient` (self-fee abuse)
1209
+ * or `0x0` (use the burn scenario for that).
1210
+ *
1211
+ * See `docs/SPONSORED_ERC20_TRANSFER_SPEC.md` for the full call
1212
+ * pattern, error codes, and edge cases.
1213
+ */
1214
+ async handleErc20Transfer(authenticatedAddress, request) {
1215
+ if ((0, import_viem4.getAddress)(authenticatedAddress) !== (0, import_viem4.getAddress)(request.userAddress)) {
1216
+ throw new import_core9.ValidationError(
1217
+ "USER_ADDRESS_MISMATCH",
1218
+ `handleErc20Transfer: authenticatedAddress (${authenticatedAddress}) does not match request.userAddress (${request.userAddress})`
1219
+ );
1220
+ }
1221
+ if (request.chainId !== this.chainId) {
1222
+ throw new import_core9.ValidationError(
1223
+ "UNSUPPORTED_CHAIN_ID",
1224
+ `handleErc20Transfer: unsupported chainId ${request.chainId}`,
1225
+ { requested: request.chainId, supported: this.chainId }
1226
+ );
1227
+ }
1228
+ if (request.amount <= 0n) {
1229
+ throw new import_core9.ValidationError(
1230
+ "ZERO_AMOUNT",
1231
+ "handleErc20Transfer: amount must be positive"
1232
+ );
1233
+ }
1234
+ const userAddress = (0, import_viem4.getAddress)(request.userAddress);
1235
+ const tokenAddress = (0, import_viem4.getAddress)(request.tokenAddress);
1236
+ const recipient = (0, import_viem4.getAddress)(request.recipient);
1237
+ const addrs = (0, import_core9.getContractAddresses)(request.chainId);
1238
+ const pafiFeeRecipient = addrs.pafiFeeRecipient;
1239
+ if (recipient.toLowerCase() === pafiFeeRecipient.toLowerCase()) {
1240
+ throw new import_core9.ValidationError(
1241
+ "SELF_FEE_ABUSE",
1242
+ "handleErc20Transfer: recipient cannot be the PAFI fee recipient",
1243
+ { recipient, pafiFeeRecipient }
1244
+ );
1245
+ }
1246
+ if (recipient === "0x0000000000000000000000000000000000000000") {
1247
+ throw new import_core9.ValidationError(
1248
+ "USE_BURN_SCENARIO",
1249
+ "handleErc20Transfer: recipient cannot be the zero address \u2014 use the burn scenario instead"
1250
+ );
1251
+ }
1252
+ const isStable = addrs.usdc && tokenAddress.toLowerCase() === addrs.usdc.toLowerCase() || tokenAddress.toLowerCase() === addrs.usdt.toLowerCase();
1253
+ let feeAmount;
1254
+ if (request.feeAmount !== void 0) {
1255
+ feeAmount = request.feeAmount > 0n ? request.feeAmount : 0n;
1256
+ } else {
1257
+ feeAmount = await (0, import_core9.quoteOperatorFeeForTransfer)({
1258
+ provider: this.provider,
1259
+ chainId: request.chainId,
1260
+ tokenAddress,
1261
+ allowStaleFallback: request.allowStaleFallback,
1262
+ fallbackEthPriceUsd: request.fallbackEthPriceUsd,
1263
+ fallbackPtPriceUsdt: request.fallbackPtPriceUsdt
1264
+ });
1265
+ }
1266
+ if (feeAmount > 0n && feeAmount >= request.amount) {
1267
+ throw new import_core9.ValidationError(
1268
+ "INVALID_AMOUNT",
1269
+ `handleErc20Transfer: fee (${feeAmount}) must be strictly less than amount (${request.amount})`,
1270
+ { feeAmount, amount: request.amount }
1271
+ );
1272
+ }
1273
+ const userOp = (0, import_core9.buildErc20TransferUserOp)({
1274
+ userAddress,
1275
+ aaNonce: request.aaNonce,
1276
+ tokenAddress,
1277
+ recipient,
1278
+ amount: request.amount,
1279
+ feeAmount: feeAmount > 0n ? feeAmount : void 0,
1280
+ feeRecipient: feeAmount > 0n ? pafiFeeRecipient : void 0
1281
+ });
1282
+ const userOpFallback = feeAmount > 0n ? (0, import_core9.buildErc20TransferUserOp)({
1283
+ userAddress,
1284
+ aaNonce: request.aaNonce,
1285
+ tokenAddress,
1286
+ recipient,
1287
+ amount: request.amount
1288
+ // No feeAmount → 1-call variant (transfer only).
1289
+ }) : void 0;
1290
+ void isStable;
1291
+ return {
1292
+ userOp,
1293
+ userOpFallback,
1294
+ feeAmountUsed: feeAmount,
1295
+ feeRecipient: pafiFeeRecipient,
1296
+ tokenAddress
1297
+ };
1298
+ }
1137
1299
  };
1138
1300
  function isPlaceholderAddress(addr) {
1139
1301
  return /^0x0{36}[0-9a-fA-F]{4}$/i.test(addr);
@@ -1520,14 +1682,1884 @@ async function perpDepositDirect(params) {
1520
1682
  relayAddress
1521
1683
  };
1522
1684
  }
1685
+
1686
+ // src/direct/transferDirect.ts
1687
+ var import_core14 = require("@pafi-dev/core");
1688
+
1689
+ // src/direct/addLiquidityDirect.ts
1690
+ var import_viem10 = require("viem");
1691
+ var import_core17 = require("@pafi-dev/core");
1692
+
1693
+ // src/liquidity/abi/nonfungiblePositionManager.ts
1694
+ var nonfungiblePositionManagerAbi = [
1695
+ // ─── Write methods ───────────────────────────────────────────────────────
1696
+ {
1697
+ type: "function",
1698
+ name: "mint",
1699
+ stateMutability: "payable",
1700
+ inputs: [
1701
+ {
1702
+ name: "params",
1703
+ type: "tuple",
1704
+ components: [
1705
+ { name: "token0", type: "address" },
1706
+ { name: "token1", type: "address" },
1707
+ { name: "fee", type: "uint24" },
1708
+ { name: "tickLower", type: "int24" },
1709
+ { name: "tickUpper", type: "int24" },
1710
+ { name: "amount0Desired", type: "uint256" },
1711
+ { name: "amount1Desired", type: "uint256" },
1712
+ { name: "amount0Min", type: "uint256" },
1713
+ { name: "amount1Min", type: "uint256" },
1714
+ { name: "recipient", type: "address" },
1715
+ { name: "deadline", type: "uint256" }
1716
+ ]
1717
+ }
1718
+ ],
1719
+ outputs: [
1720
+ { name: "tokenId", type: "uint256" },
1721
+ { name: "liquidity", type: "uint128" },
1722
+ { name: "amount0", type: "uint256" },
1723
+ { name: "amount1", type: "uint256" }
1724
+ ]
1725
+ },
1726
+ {
1727
+ type: "function",
1728
+ name: "increaseLiquidity",
1729
+ stateMutability: "payable",
1730
+ inputs: [
1731
+ {
1732
+ name: "params",
1733
+ type: "tuple",
1734
+ components: [
1735
+ { name: "tokenId", type: "uint256" },
1736
+ { name: "amount0Desired", type: "uint256" },
1737
+ { name: "amount1Desired", type: "uint256" },
1738
+ { name: "amount0Min", type: "uint256" },
1739
+ { name: "amount1Min", type: "uint256" },
1740
+ { name: "deadline", type: "uint256" }
1741
+ ]
1742
+ }
1743
+ ],
1744
+ outputs: [
1745
+ { name: "liquidity", type: "uint128" },
1746
+ { name: "amount0", type: "uint256" },
1747
+ { name: "amount1", type: "uint256" }
1748
+ ]
1749
+ },
1750
+ {
1751
+ type: "function",
1752
+ name: "decreaseLiquidity",
1753
+ stateMutability: "payable",
1754
+ inputs: [
1755
+ {
1756
+ name: "params",
1757
+ type: "tuple",
1758
+ components: [
1759
+ { name: "tokenId", type: "uint256" },
1760
+ { name: "liquidity", type: "uint128" },
1761
+ { name: "amount0Min", type: "uint256" },
1762
+ { name: "amount1Min", type: "uint256" },
1763
+ { name: "deadline", type: "uint256" }
1764
+ ]
1765
+ }
1766
+ ],
1767
+ outputs: [
1768
+ { name: "amount0", type: "uint256" },
1769
+ { name: "amount1", type: "uint256" }
1770
+ ]
1771
+ },
1772
+ {
1773
+ type: "function",
1774
+ name: "collect",
1775
+ stateMutability: "payable",
1776
+ inputs: [
1777
+ {
1778
+ name: "params",
1779
+ type: "tuple",
1780
+ components: [
1781
+ { name: "tokenId", type: "uint256" },
1782
+ { name: "recipient", type: "address" },
1783
+ { name: "amount0Max", type: "uint128" },
1784
+ { name: "amount1Max", type: "uint128" }
1785
+ ]
1786
+ }
1787
+ ],
1788
+ outputs: [
1789
+ { name: "amount0", type: "uint256" },
1790
+ { name: "amount1", type: "uint256" }
1791
+ ]
1792
+ },
1793
+ {
1794
+ type: "function",
1795
+ name: "burn",
1796
+ stateMutability: "payable",
1797
+ inputs: [{ name: "tokenId", type: "uint256" }],
1798
+ outputs: []
1799
+ },
1800
+ // ─── Read methods ────────────────────────────────────────────────────────
1801
+ // Returns the legacy V3 12-tuple. `readPosition` wraps this into a struct.
1802
+ {
1803
+ type: "function",
1804
+ name: "positions",
1805
+ stateMutability: "view",
1806
+ inputs: [{ name: "tokenId", type: "uint256" }],
1807
+ outputs: [
1808
+ { name: "nonce", type: "uint96" },
1809
+ { name: "operator", type: "address" },
1810
+ { name: "token0", type: "address" },
1811
+ { name: "token1", type: "address" },
1812
+ { name: "fee", type: "uint24" },
1813
+ { name: "tickLower", type: "int24" },
1814
+ { name: "tickUpper", type: "int24" },
1815
+ { name: "liquidity", type: "uint128" },
1816
+ { name: "feeGrowthInside0LastX128", type: "uint256" },
1817
+ { name: "feeGrowthInside1LastX128", type: "uint256" },
1818
+ { name: "tokensOwed0", type: "uint128" },
1819
+ { name: "tokensOwed1", type: "uint128" }
1820
+ ]
1821
+ },
1822
+ // Used by the ABI smoke test to verify NPM is wired to the expected
1823
+ // PafiV3Factory.
1824
+ {
1825
+ type: "function",
1826
+ name: "factory",
1827
+ stateMutability: "view",
1828
+ inputs: [],
1829
+ outputs: [{ name: "", type: "address" }]
1830
+ },
1831
+ // ─── Events (for receipt parsing) ────────────────────────────────────────
1832
+ // Emitted from address(0) on mint; addLiquidityDirect parses this to
1833
+ // extract the newly-minted tokenId.
1834
+ {
1835
+ type: "event",
1836
+ name: "Transfer",
1837
+ inputs: [
1838
+ { name: "from", type: "address", indexed: true },
1839
+ { name: "to", type: "address", indexed: true },
1840
+ { name: "tokenId", type: "uint256", indexed: true }
1841
+ ]
1842
+ },
1843
+ {
1844
+ type: "event",
1845
+ name: "IncreaseLiquidity",
1846
+ inputs: [
1847
+ { name: "tokenId", type: "uint256", indexed: true },
1848
+ { name: "liquidity", type: "uint128", indexed: false },
1849
+ { name: "amount0", type: "uint256", indexed: false },
1850
+ { name: "amount1", type: "uint256", indexed: false }
1851
+ ]
1852
+ },
1853
+ {
1854
+ type: "event",
1855
+ name: "DecreaseLiquidity",
1856
+ inputs: [
1857
+ { name: "tokenId", type: "uint256", indexed: true },
1858
+ { name: "liquidity", type: "uint128", indexed: false },
1859
+ { name: "amount0", type: "uint256", indexed: false },
1860
+ { name: "amount1", type: "uint256", indexed: false }
1861
+ ]
1862
+ },
1863
+ {
1864
+ type: "event",
1865
+ name: "Collect",
1866
+ inputs: [
1867
+ { name: "tokenId", type: "uint256", indexed: true },
1868
+ { name: "recipient", type: "address", indexed: false },
1869
+ { name: "amount0", type: "uint256", indexed: false },
1870
+ { name: "amount1", type: "uint256", indexed: false }
1871
+ ]
1872
+ }
1873
+ ];
1874
+
1875
+ // src/liquidity/abi/v3Pool.ts
1876
+ var v3PoolAbi = [
1877
+ // Pool's underlying tokens. Read on-chain to verify the
1878
+ // `computeV3PoolAddress(factory, token0, token1, fee)` derivation matches
1879
+ // an already-deployed pool — and useful generally for consumers that
1880
+ // discovered a pool by address (e.g. from a Transfer log) and need the
1881
+ // tokens.
1882
+ {
1883
+ type: "function",
1884
+ name: "token0",
1885
+ stateMutability: "view",
1886
+ inputs: [],
1887
+ outputs: [{ name: "", type: "address" }]
1888
+ },
1889
+ {
1890
+ type: "function",
1891
+ name: "token1",
1892
+ stateMutability: "view",
1893
+ inputs: [],
1894
+ outputs: [{ name: "", type: "address" }]
1895
+ },
1896
+ // (sqrtPriceX96, tick, observationIndex, observationCardinality,
1897
+ // observationCardinalityNext, feeProtocol, unlocked)
1898
+ {
1899
+ type: "function",
1900
+ name: "slot0",
1901
+ stateMutability: "view",
1902
+ inputs: [],
1903
+ outputs: [
1904
+ { name: "sqrtPriceX96", type: "uint160" },
1905
+ { name: "tick", type: "int24" },
1906
+ { name: "observationIndex", type: "uint16" },
1907
+ { name: "observationCardinality", type: "uint16" },
1908
+ { name: "observationCardinalityNext", type: "uint16" },
1909
+ { name: "feeProtocol", type: "uint8" },
1910
+ { name: "unlocked", type: "bool" }
1911
+ ]
1912
+ },
1913
+ {
1914
+ type: "function",
1915
+ name: "liquidity",
1916
+ stateMutability: "view",
1917
+ inputs: [],
1918
+ outputs: [{ name: "", type: "uint128" }]
1919
+ },
1920
+ {
1921
+ type: "function",
1922
+ name: "tickSpacing",
1923
+ stateMutability: "view",
1924
+ inputs: [],
1925
+ outputs: [{ name: "", type: "int24" }]
1926
+ },
1927
+ {
1928
+ type: "function",
1929
+ name: "fee",
1930
+ stateMutability: "view",
1931
+ inputs: [],
1932
+ outputs: [{ name: "", type: "uint24" }]
1933
+ },
1934
+ // (Token-0 / token-1 cumulative fee growth per unit of liquidity, in
1935
+ // Q128.128.) Used with `ticks(...)` to derive the pending-fee estimate
1936
+ // for collectFeesDirect.
1937
+ {
1938
+ type: "function",
1939
+ name: "feeGrowthGlobal0X128",
1940
+ stateMutability: "view",
1941
+ inputs: [],
1942
+ outputs: [{ name: "", type: "uint256" }]
1943
+ },
1944
+ {
1945
+ type: "function",
1946
+ name: "feeGrowthGlobal1X128",
1947
+ stateMutability: "view",
1948
+ inputs: [],
1949
+ outputs: [{ name: "", type: "uint256" }]
1950
+ },
1951
+ // Per-tick state. The SDK reads `ticks(tickLower)` + `ticks(tickUpper)`
1952
+ // for a position to compute its `feeGrowthInside0/1` in the canonical
1953
+ // V3 formula (current global - outside lower - outside upper, branched
1954
+ // on whether `slot0.tick` is below / inside / above the range).
1955
+ {
1956
+ type: "function",
1957
+ name: "ticks",
1958
+ stateMutability: "view",
1959
+ inputs: [{ name: "tick", type: "int24" }],
1960
+ outputs: [
1961
+ { name: "liquidityGross", type: "uint128" },
1962
+ { name: "liquidityNet", type: "int128" },
1963
+ { name: "feeGrowthOutside0X128", type: "uint256" },
1964
+ { name: "feeGrowthOutside1X128", type: "uint256" },
1965
+ { name: "tickCumulativeOutside", type: "int56" },
1966
+ { name: "secondsPerLiquidityOutsideX128", type: "uint160" },
1967
+ { name: "secondsOutside", type: "uint56" },
1968
+ { name: "initialized", type: "bool" }
1969
+ ]
1970
+ },
1971
+ // Per-word initialized-tick bitset. Each uint256 word covers 256
1972
+ // compressed tick positions (compressed = tick / tickSpacing). The
1973
+ // off-chain liquidity-curve scanner reads every word in
1974
+ // `[wordOf(minUsableTick), wordOf(maxUsableTick)]` then decodes set
1975
+ // bits into absolute tick indices via `(wordPos * 256 + bit) * spacing`.
1976
+ // See `fetchAllInitializedTicks.ts`.
1977
+ {
1978
+ type: "function",
1979
+ name: "tickBitmap",
1980
+ stateMutability: "view",
1981
+ inputs: [{ name: "wordPosition", type: "int16" }],
1982
+ outputs: [{ name: "", type: "uint256" }]
1983
+ }
1984
+ ];
1985
+
1986
+ // src/liquidity/constants.ts
1987
+ var V3_NPM_ADDRESSES = {
1988
+ // Base mainnet — PAFI's V3 NPM deployment.
1989
+ 8453: "0xD7db6931B5EbeaE033605db0781DE6C91F05CCdf"
1990
+ };
1991
+ var UINT128_MAX2 = (1n << 128n) - 1n;
1992
+
1993
+ // src/liquidity/math.ts
1994
+ var MIN_TICK = -887272;
1995
+ var MAX_TICK = 887272;
1996
+ var MIN_SQRT_RATIO = 4295128739n;
1997
+ var MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342n;
1998
+ var Q96 = 1n << 96n;
1999
+ var Q192 = 1n << 192n;
2000
+ function mulShift(val, mulBy) {
2001
+ return val * mulBy >> 128n;
2002
+ }
2003
+ function mulDivFloor(a, b, denominator) {
2004
+ return a * b / denominator;
2005
+ }
2006
+ function mulDivCeil(a, b, denominator) {
2007
+ const product = a * b;
2008
+ return product % denominator === 0n ? product / denominator : product / denominator + 1n;
2009
+ }
2010
+ function tickToSqrtPriceX96(tick) {
2011
+ if (!Number.isInteger(tick)) {
2012
+ throw new Error(`tickToSqrtPriceX96: tick must be an integer, got ${tick}`);
2013
+ }
2014
+ if (tick < MIN_TICK || tick > MAX_TICK) {
2015
+ throw new Error(
2016
+ `tickToSqrtPriceX96: tick ${tick} out of range [${MIN_TICK}, ${MAX_TICK}]`
2017
+ );
2018
+ }
2019
+ const absTick = BigInt(tick < 0 ? -tick : tick);
2020
+ let ratio = (absTick & 0x1n) !== 0n ? 0xfffcb933bd6fad37aa2d162d1a594001n : 0x100000000000000000000000000000000n;
2021
+ if ((absTick & 0x2n) !== 0n)
2022
+ ratio = mulShift(ratio, 0xfff97272373d413259a46990580e213an);
2023
+ if ((absTick & 0x4n) !== 0n)
2024
+ ratio = mulShift(ratio, 0xfff2e50f5f656932ef12357cf3c7fdccn);
2025
+ if ((absTick & 0x8n) !== 0n)
2026
+ ratio = mulShift(ratio, 0xffe5caca7e10e4e61c3624eaa0941cd0n);
2027
+ if ((absTick & 0x10n) !== 0n)
2028
+ ratio = mulShift(ratio, 0xffcb9843d60f6159c9db58835c926644n);
2029
+ if ((absTick & 0x20n) !== 0n)
2030
+ ratio = mulShift(ratio, 0xff973b41fa98c081472e6896dfb254c0n);
2031
+ if ((absTick & 0x40n) !== 0n)
2032
+ ratio = mulShift(ratio, 0xff2ea16466c96a3843ec78b326b52861n);
2033
+ if ((absTick & 0x80n) !== 0n)
2034
+ ratio = mulShift(ratio, 0xfe5dee046a99a2a811c461f1969c3053n);
2035
+ if ((absTick & 0x100n) !== 0n)
2036
+ ratio = mulShift(ratio, 0xfcbe86c7900a88aedcffc83b479aa3a4n);
2037
+ if ((absTick & 0x200n) !== 0n)
2038
+ ratio = mulShift(ratio, 0xf987a7253ac413176f2b074cf7815e54n);
2039
+ if ((absTick & 0x400n) !== 0n)
2040
+ ratio = mulShift(ratio, 0xf3392b0822b70005940c7a398e4b70f3n);
2041
+ if ((absTick & 0x800n) !== 0n)
2042
+ ratio = mulShift(ratio, 0xe7159475a2c29b7443b29c7fa6e889d9n);
2043
+ if ((absTick & 0x1000n) !== 0n)
2044
+ ratio = mulShift(ratio, 0xd097f3bdfd2022b8845ad8f792aa5825n);
2045
+ if ((absTick & 0x2000n) !== 0n)
2046
+ ratio = mulShift(ratio, 0xa9f746462d870fdf8a65dc1f90e061e5n);
2047
+ if ((absTick & 0x4000n) !== 0n)
2048
+ ratio = mulShift(ratio, 0x70d869a156d2a1b890bb3df62baf32f7n);
2049
+ if ((absTick & 0x8000n) !== 0n)
2050
+ ratio = mulShift(ratio, 0x31be135f97d08fd981231505542fcfa6n);
2051
+ if ((absTick & 0x10000n) !== 0n)
2052
+ ratio = mulShift(ratio, 0x9aa508b5b7a84e1c677de54f3e99bc9n);
2053
+ if ((absTick & 0x20000n) !== 0n)
2054
+ ratio = mulShift(ratio, 0x5d6af8dedb81196699c329225ee604n);
2055
+ if ((absTick & 0x40000n) !== 0n)
2056
+ ratio = mulShift(ratio, 0x2216e584f5fa1ea926041bedfe98n);
2057
+ if ((absTick & 0x80000n) !== 0n)
2058
+ ratio = mulShift(ratio, 0x48a170391f7dc42444e8fa2n);
2059
+ if (tick > 0) {
2060
+ const max256 = (1n << 256n) - 1n;
2061
+ ratio = max256 / ratio;
2062
+ }
2063
+ return (ratio >> 32n) + (ratio % (1n << 32n) === 0n ? 0n : 1n);
2064
+ }
2065
+ function sqrtPriceX96ToTick(sqrtPriceX96) {
2066
+ if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) {
2067
+ throw new Error(
2068
+ `sqrtPriceX96ToTick: sqrtPriceX96 ${sqrtPriceX96} out of range [${MIN_SQRT_RATIO}, ${MAX_SQRT_RATIO})`
2069
+ );
2070
+ }
2071
+ const ratio = sqrtPriceX96 << 32n;
2072
+ let r = ratio;
2073
+ let msb = 0n;
2074
+ for (const [shift, value] of [
2075
+ [128n, 0xffffffffffffffffffffffffffffffffn],
2076
+ [64n, 0xffffffffffffffffn],
2077
+ [32n, 0xffffffffn],
2078
+ [16n, 0xffffn],
2079
+ [8n, 0xffn],
2080
+ [4n, 0xfn],
2081
+ [2n, 0x3n],
2082
+ [1n, 0x1n]
2083
+ ]) {
2084
+ const f = r > value ? shift : 0n;
2085
+ msb |= f;
2086
+ r >>= f;
2087
+ }
2088
+ r = msb >= 128n ? ratio >> msb - 127n : ratio << 127n - msb;
2089
+ let log2 = msb - 128n << 64n;
2090
+ for (let i = 0; i < 14; i++) {
2091
+ r = r * r >> 127n;
2092
+ const f = r >> 128n;
2093
+ log2 |= f << BigInt(63 - i);
2094
+ r >>= f;
2095
+ }
2096
+ const logSqrt10001 = log2 * 255738958999603826347141n;
2097
+ const tickLow = Number(
2098
+ logSqrt10001 - 3402992956809132418596140100660247210n >> 128n
2099
+ );
2100
+ const tickHigh = Number(
2101
+ logSqrt10001 + 291339464771989622907027621153398088495n >> 128n
2102
+ );
2103
+ if (tickLow === tickHigh) return tickLow;
2104
+ return tickToSqrtPriceX96(tickHigh) <= sqrtPriceX96 ? tickHigh : tickLow;
2105
+ }
2106
+ function nearestUsableTick(tick, tickSpacing) {
2107
+ if (!Number.isInteger(tick) || !Number.isInteger(tickSpacing)) {
2108
+ throw new Error("nearestUsableTick: both arguments must be integers");
2109
+ }
2110
+ if (tickSpacing <= 0) {
2111
+ throw new Error(
2112
+ `nearestUsableTick: tickSpacing must be positive, got ${tickSpacing}`
2113
+ );
2114
+ }
2115
+ const rounded = Math.round(tick / tickSpacing) * tickSpacing;
2116
+ if (rounded < MIN_TICK) return rounded + tickSpacing;
2117
+ if (rounded > MAX_TICK) return rounded - tickSpacing;
2118
+ return rounded;
2119
+ }
2120
+ function minUsableTick(tickSpacing) {
2121
+ return Math.ceil(MIN_TICK / tickSpacing) * tickSpacing;
2122
+ }
2123
+ function maxUsableTick(tickSpacing) {
2124
+ return Math.floor(MAX_TICK / tickSpacing) * tickSpacing;
2125
+ }
2126
+ function tickSpacingForFee(fee) {
2127
+ switch (fee) {
2128
+ case 100:
2129
+ return 1;
2130
+ case 500:
2131
+ return 10;
2132
+ case 3e3:
2133
+ return 60;
2134
+ case 1e4:
2135
+ return 200;
2136
+ default:
2137
+ return void 0;
2138
+ }
2139
+ }
2140
+ function priceToTick(params) {
2141
+ const { price, token0Decimals, token1Decimals } = params;
2142
+ if (price <= 0 || !Number.isFinite(price)) {
2143
+ throw new Error(`priceToTick: price must be a positive finite number, got ${price}`);
2144
+ }
2145
+ const rawPrice = price * 10 ** (token1Decimals - token0Decimals);
2146
+ return Math.floor(Math.log(rawPrice) / Math.log(1.0001));
2147
+ }
2148
+ function tickToPrice(params) {
2149
+ const { tick, token0Decimals, token1Decimals } = params;
2150
+ if (!Number.isInteger(tick)) {
2151
+ throw new Error(`tickToPrice: tick must be an integer, got ${tick}`);
2152
+ }
2153
+ const rawPrice = Math.pow(1.0001, tick);
2154
+ return rawPrice / 10 ** (token1Decimals - token0Decimals);
2155
+ }
2156
+ function getAmount0ForLiquidity(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidity) {
2157
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2158
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2159
+ sqrtPriceX96Upper,
2160
+ sqrtPriceX96Lower
2161
+ ];
2162
+ }
2163
+ if (liquidity <= 0n) return 0n;
2164
+ const numerator = liquidity << 96n;
2165
+ const diff = sqrtPriceX96Upper - sqrtPriceX96Lower;
2166
+ return mulDivCeil(numerator * diff, 1n, sqrtPriceX96Upper * sqrtPriceX96Lower);
2167
+ }
2168
+ function getAmount1ForLiquidity(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidity) {
2169
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2170
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2171
+ sqrtPriceX96Upper,
2172
+ sqrtPriceX96Lower
2173
+ ];
2174
+ }
2175
+ if (liquidity <= 0n) return 0n;
2176
+ return mulDivCeil(liquidity, sqrtPriceX96Upper - sqrtPriceX96Lower, Q96);
2177
+ }
2178
+ function getAmountsForLiquidity(params) {
2179
+ let { sqrtPriceX96Lower, sqrtPriceX96Upper } = params;
2180
+ const { sqrtPriceX96Current, liquidity } = params;
2181
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2182
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2183
+ sqrtPriceX96Upper,
2184
+ sqrtPriceX96Lower
2185
+ ];
2186
+ }
2187
+ if (sqrtPriceX96Current <= sqrtPriceX96Lower) {
2188
+ return {
2189
+ amount0: getAmount0ForLiquidity(
2190
+ sqrtPriceX96Lower,
2191
+ sqrtPriceX96Upper,
2192
+ liquidity
2193
+ ),
2194
+ amount1: 0n
2195
+ };
2196
+ } else if (sqrtPriceX96Current < sqrtPriceX96Upper) {
2197
+ return {
2198
+ amount0: getAmount0ForLiquidity(
2199
+ sqrtPriceX96Current,
2200
+ sqrtPriceX96Upper,
2201
+ liquidity
2202
+ ),
2203
+ amount1: getAmount1ForLiquidity(
2204
+ sqrtPriceX96Lower,
2205
+ sqrtPriceX96Current,
2206
+ liquidity
2207
+ )
2208
+ };
2209
+ } else {
2210
+ return {
2211
+ amount0: 0n,
2212
+ amount1: getAmount1ForLiquidity(
2213
+ sqrtPriceX96Lower,
2214
+ sqrtPriceX96Upper,
2215
+ liquidity
2216
+ )
2217
+ };
2218
+ }
2219
+ }
2220
+ function getLiquidityForAmount0(sqrtPriceX96Lower, sqrtPriceX96Upper, amount0) {
2221
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2222
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2223
+ sqrtPriceX96Upper,
2224
+ sqrtPriceX96Lower
2225
+ ];
2226
+ }
2227
+ if (amount0 <= 0n) return 0n;
2228
+ const intermediate = mulDivFloor(sqrtPriceX96Lower, sqrtPriceX96Upper, Q96);
2229
+ return mulDivFloor(amount0, intermediate, sqrtPriceX96Upper - sqrtPriceX96Lower);
2230
+ }
2231
+ function getLiquidityForAmount1(sqrtPriceX96Lower, sqrtPriceX96Upper, amount1) {
2232
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2233
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2234
+ sqrtPriceX96Upper,
2235
+ sqrtPriceX96Lower
2236
+ ];
2237
+ }
2238
+ if (amount1 <= 0n) return 0n;
2239
+ return mulDivFloor(amount1, Q96, sqrtPriceX96Upper - sqrtPriceX96Lower);
2240
+ }
2241
+ function estimateLiquidityFromOneSide(params) {
2242
+ let { sqrtPriceX96Lower, sqrtPriceX96Upper } = params;
2243
+ const {
2244
+ sqrtPriceX96Current,
2245
+ amount0Desired,
2246
+ amount1Desired
2247
+ } = params;
2248
+ if (sqrtPriceX96Lower > sqrtPriceX96Upper) {
2249
+ [sqrtPriceX96Lower, sqrtPriceX96Upper] = [
2250
+ sqrtPriceX96Upper,
2251
+ sqrtPriceX96Lower
2252
+ ];
2253
+ }
2254
+ const has0 = amount0Desired !== void 0 && amount0Desired > 0n;
2255
+ const has1 = amount1Desired !== void 0 && amount1Desired > 0n;
2256
+ if (has0 === has1) {
2257
+ throw new Error(
2258
+ "estimateLiquidityFromOneSide: exactly one of amount0Desired / amount1Desired must be a positive bigint"
2259
+ );
2260
+ }
2261
+ if (sqrtPriceX96Current <= sqrtPriceX96Lower) {
2262
+ if (!has0) {
2263
+ throw new Error(
2264
+ "estimateLiquidityFromOneSide: spot is below range; pin amount0Desired (token1 isn't required)"
2265
+ );
2266
+ }
2267
+ const liquidity2 = getLiquidityForAmount0(
2268
+ sqrtPriceX96Lower,
2269
+ sqrtPriceX96Upper,
2270
+ amount0Desired
2271
+ );
2272
+ return { liquidity: liquidity2, amount0: amount0Desired, amount1: 0n };
2273
+ }
2274
+ if (sqrtPriceX96Current >= sqrtPriceX96Upper) {
2275
+ if (!has1) {
2276
+ throw new Error(
2277
+ "estimateLiquidityFromOneSide: spot is above range; pin amount1Desired (token0 isn't required)"
2278
+ );
2279
+ }
2280
+ const liquidity2 = getLiquidityForAmount1(
2281
+ sqrtPriceX96Lower,
2282
+ sqrtPriceX96Upper,
2283
+ amount1Desired
2284
+ );
2285
+ return { liquidity: liquidity2, amount0: 0n, amount1: amount1Desired };
2286
+ }
2287
+ let liquidity;
2288
+ if (has0) {
2289
+ liquidity = getLiquidityForAmount0(
2290
+ sqrtPriceX96Current,
2291
+ sqrtPriceX96Upper,
2292
+ amount0Desired
2293
+ );
2294
+ } else {
2295
+ liquidity = getLiquidityForAmount1(
2296
+ sqrtPriceX96Lower,
2297
+ sqrtPriceX96Current,
2298
+ amount1Desired
2299
+ );
2300
+ }
2301
+ const amounts = getAmountsForLiquidity({
2302
+ sqrtPriceX96Current,
2303
+ sqrtPriceX96Lower,
2304
+ sqrtPriceX96Upper,
2305
+ liquidity
2306
+ });
2307
+ return {
2308
+ liquidity,
2309
+ amount0: has0 ? amount0Desired : amounts.amount0,
2310
+ amount1: has1 ? amount1Desired : amounts.amount1
2311
+ };
2312
+ }
2313
+ function applyMintSlippage(params) {
2314
+ const { amount0Desired, amount1Desired, slippageBps } = params;
2315
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
2316
+ throw new Error(
2317
+ `applyMintSlippage: slippageBps must be integer in [0, 10000], got ${slippageBps}`
2318
+ );
2319
+ }
2320
+ const num = BigInt(1e4 - slippageBps);
2321
+ return {
2322
+ amount0Min: amount0Desired * num / 10000n,
2323
+ amount1Min: amount1Desired * num / 10000n
2324
+ };
2325
+ }
2326
+ function applyRemoveSlippage(params) {
2327
+ const { amount0Expected, amount1Expected, slippageBps } = params;
2328
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
2329
+ throw new Error(
2330
+ `applyRemoveSlippage: slippageBps must be integer in [0, 10000], got ${slippageBps}`
2331
+ );
2332
+ }
2333
+ const num = BigInt(1e4 - slippageBps);
2334
+ return {
2335
+ amount0Min: amount0Expected * num / 10000n,
2336
+ amount1Min: amount1Expected * num / 10000n
2337
+ };
2338
+ }
2339
+
2340
+ // src/liquidity/readPosition.ts
2341
+ async function readPosition(client, npm, tokenId) {
2342
+ const result = await client.readContract({
2343
+ address: npm,
2344
+ abi: nonfungiblePositionManagerAbi,
2345
+ functionName: "positions",
2346
+ args: [tokenId]
2347
+ });
2348
+ return {
2349
+ nonce: result[0],
2350
+ operator: result[1],
2351
+ token0: result[2],
2352
+ token1: result[3],
2353
+ fee: result[4],
2354
+ tickLower: result[5],
2355
+ tickUpper: result[6],
2356
+ liquidity: result[7],
2357
+ feeGrowthInside0LastX128: result[8],
2358
+ feeGrowthInside1LastX128: result[9],
2359
+ tokensOwed0: result[10],
2360
+ tokensOwed1: result[11]
2361
+ };
2362
+ }
2363
+
2364
+ // src/liquidity/readPoolState.ts
2365
+ async function readPoolState(client, pool, blockNumber) {
2366
+ const results = await client.multicall({
2367
+ contracts: [
2368
+ { address: pool, abi: v3PoolAbi, functionName: "slot0" },
2369
+ { address: pool, abi: v3PoolAbi, functionName: "liquidity" },
2370
+ { address: pool, abi: v3PoolAbi, functionName: "tickSpacing" },
2371
+ { address: pool, abi: v3PoolAbi, functionName: "fee" }
2372
+ ],
2373
+ allowFailure: false,
2374
+ blockNumber
2375
+ });
2376
+ const slot0 = results[0];
2377
+ return {
2378
+ sqrtPriceX96: slot0[0],
2379
+ tick: slot0[1],
2380
+ liquidity: results[1],
2381
+ tickSpacing: results[2],
2382
+ fee: results[3]
2383
+ };
2384
+ }
2385
+ async function readTicksAt(client, pool, tickLower, tickUpper) {
2386
+ const results = await client.multicall({
2387
+ contracts: [
2388
+ { address: pool, abi: v3PoolAbi, functionName: "ticks", args: [tickLower] },
2389
+ { address: pool, abi: v3PoolAbi, functionName: "ticks", args: [tickUpper] }
2390
+ ],
2391
+ allowFailure: false
2392
+ });
2393
+ const toTickInfo = (r) => {
2394
+ const tuple = r;
2395
+ return {
2396
+ liquidityGross: tuple[0],
2397
+ liquidityNet: tuple[1],
2398
+ feeGrowthOutside0X128: tuple[2],
2399
+ feeGrowthOutside1X128: tuple[3],
2400
+ initialized: tuple[7]
2401
+ };
2402
+ };
2403
+ return {
2404
+ lower: toTickInfo(results[0]),
2405
+ upper: toTickInfo(results[1])
2406
+ };
2407
+ }
2408
+ async function readFeeGrowthGlobals(client, pool) {
2409
+ const results = await client.multicall({
2410
+ contracts: [
2411
+ { address: pool, abi: v3PoolAbi, functionName: "feeGrowthGlobal0X128" },
2412
+ { address: pool, abi: v3PoolAbi, functionName: "feeGrowthGlobal1X128" }
2413
+ ],
2414
+ allowFailure: false
2415
+ });
2416
+ return {
2417
+ feeGrowthGlobal0X128: results[0],
2418
+ feeGrowthGlobal1X128: results[1]
2419
+ };
2420
+ }
2421
+
2422
+ // src/liquidity/buildMint.ts
2423
+ var import_viem5 = require("viem");
2424
+ var import_core15 = require("@pafi-dev/core");
2425
+ function buildMint(params) {
2426
+ return [
2427
+ (0, import_core15.erc20ApproveOp)(params.token0, params.npm, params.amount0Desired),
2428
+ (0, import_core15.erc20ApproveOp)(params.token1, params.npm, params.amount1Desired),
2429
+ {
2430
+ target: params.npm,
2431
+ value: 0n,
2432
+ data: (0, import_viem5.encodeFunctionData)({
2433
+ abi: nonfungiblePositionManagerAbi,
2434
+ functionName: "mint",
2435
+ args: [
2436
+ {
2437
+ token0: params.token0,
2438
+ token1: params.token1,
2439
+ fee: params.fee,
2440
+ tickLower: params.tickLower,
2441
+ tickUpper: params.tickUpper,
2442
+ amount0Desired: params.amount0Desired,
2443
+ amount1Desired: params.amount1Desired,
2444
+ amount0Min: params.amount0Min,
2445
+ amount1Min: params.amount1Min,
2446
+ recipient: params.recipient,
2447
+ deadline: params.deadline
2448
+ }
2449
+ ]
2450
+ })
2451
+ }
2452
+ ];
2453
+ }
2454
+
2455
+ // src/liquidity/buildIncreaseLiquidity.ts
2456
+ var import_viem6 = require("viem");
2457
+ var import_core16 = require("@pafi-dev/core");
2458
+ function buildIncreaseLiquidity(params) {
2459
+ return [
2460
+ (0, import_core16.erc20ApproveOp)(params.token0, params.npm, params.amount0Desired),
2461
+ (0, import_core16.erc20ApproveOp)(params.token1, params.npm, params.amount1Desired),
2462
+ {
2463
+ target: params.npm,
2464
+ value: 0n,
2465
+ data: (0, import_viem6.encodeFunctionData)({
2466
+ abi: nonfungiblePositionManagerAbi,
2467
+ functionName: "increaseLiquidity",
2468
+ args: [
2469
+ {
2470
+ tokenId: params.tokenId,
2471
+ amount0Desired: params.amount0Desired,
2472
+ amount1Desired: params.amount1Desired,
2473
+ amount0Min: params.amount0Min,
2474
+ amount1Min: params.amount1Min,
2475
+ deadline: params.deadline
2476
+ }
2477
+ ]
2478
+ })
2479
+ }
2480
+ ];
2481
+ }
2482
+
2483
+ // src/liquidity/buildDecreaseLiquidity.ts
2484
+ var import_viem7 = require("viem");
2485
+ function buildDecreaseLiquidity(params) {
2486
+ return {
2487
+ target: params.npm,
2488
+ value: 0n,
2489
+ data: (0, import_viem7.encodeFunctionData)({
2490
+ abi: nonfungiblePositionManagerAbi,
2491
+ functionName: "decreaseLiquidity",
2492
+ args: [
2493
+ {
2494
+ tokenId: params.tokenId,
2495
+ liquidity: params.liquidity,
2496
+ amount0Min: params.amount0Min,
2497
+ amount1Min: params.amount1Min,
2498
+ deadline: params.deadline
2499
+ }
2500
+ ]
2501
+ })
2502
+ };
2503
+ }
2504
+
2505
+ // src/liquidity/buildCollect.ts
2506
+ var import_viem8 = require("viem");
2507
+ function buildCollect(params) {
2508
+ return {
2509
+ target: params.npm,
2510
+ value: 0n,
2511
+ data: (0, import_viem8.encodeFunctionData)({
2512
+ abi: nonfungiblePositionManagerAbi,
2513
+ functionName: "collect",
2514
+ args: [
2515
+ {
2516
+ tokenId: params.tokenId,
2517
+ recipient: params.recipient,
2518
+ amount0Max: params.amount0Max ?? UINT128_MAX2,
2519
+ amount1Max: params.amount1Max ?? UINT128_MAX2
2520
+ }
2521
+ ]
2522
+ })
2523
+ };
2524
+ }
2525
+
2526
+ // src/liquidity/buildBurn.ts
2527
+ var import_viem9 = require("viem");
2528
+ function buildBurn(params) {
2529
+ return {
2530
+ target: params.npm,
2531
+ value: 0n,
2532
+ data: (0, import_viem9.encodeFunctionData)({
2533
+ abi: nonfungiblePositionManagerAbi,
2534
+ functionName: "burn",
2535
+ args: [params.tokenId]
2536
+ })
2537
+ };
2538
+ }
2539
+
2540
+ // src/liquidity/buildClosePosition.ts
2541
+ function buildClosePosition(params) {
2542
+ const ops = [];
2543
+ if (params.liquidity > 0n) {
2544
+ ops.push(
2545
+ buildDecreaseLiquidity({
2546
+ npm: params.npm,
2547
+ tokenId: params.tokenId,
2548
+ liquidity: params.liquidity,
2549
+ amount0Min: params.amount0Min,
2550
+ amount1Min: params.amount1Min,
2551
+ deadline: params.deadline
2552
+ })
2553
+ );
2554
+ }
2555
+ if (params.liquidity > 0n || params.hasOutstandingFees) {
2556
+ ops.push(
2557
+ buildCollect({
2558
+ npm: params.npm,
2559
+ tokenId: params.tokenId,
2560
+ recipient: params.recipient
2561
+ })
2562
+ );
2563
+ }
2564
+ ops.push(buildBurn({ npm: params.npm, tokenId: params.tokenId }));
2565
+ return ops;
2566
+ }
2567
+
2568
+ // src/liquidity/readTickBitmap.ts
2569
+ function tickToBitmapPosition(tick, tickSpacing) {
2570
+ if (!Number.isInteger(tick)) {
2571
+ throw new Error(`tickToBitmapPosition: tick (${tick}) must be an integer`);
2572
+ }
2573
+ if (!Number.isInteger(tickSpacing) || tickSpacing <= 0) {
2574
+ throw new Error(
2575
+ `tickToBitmapPosition: tickSpacing (${tickSpacing}) must be a positive integer`
2576
+ );
2577
+ }
2578
+ if (tick % tickSpacing !== 0) {
2579
+ throw new Error(
2580
+ `tickToBitmapPosition: tick (${tick}) must be a multiple of tickSpacing ${tickSpacing}`
2581
+ );
2582
+ }
2583
+ const compressed = Math.floor(tick / tickSpacing);
2584
+ const word = compressed >> 8;
2585
+ const bit = (compressed % 256 + 256) % 256;
2586
+ return { word, bit };
2587
+ }
2588
+ function decodeBitmapWord(bitmap, wordPos, tickSpacing) {
2589
+ if (bitmap === 0n) return [];
2590
+ const out = [];
2591
+ for (let bit = 0; bit < 256; bit++) {
2592
+ if ((bitmap & 1n << BigInt(bit)) !== 0n) {
2593
+ out.push((wordPos * 256 + bit) * tickSpacing);
2594
+ }
2595
+ }
2596
+ return out;
2597
+ }
2598
+ function bitmapWordRange(tickSpacing) {
2599
+ const lo = minUsableTick(tickSpacing);
2600
+ const hi = maxUsableTick(tickSpacing);
2601
+ return {
2602
+ min: Math.floor(lo / tickSpacing) >> 8,
2603
+ max: Math.floor(hi / tickSpacing) >> 8
2604
+ };
2605
+ }
2606
+
2607
+ // src/liquidity/buildLiquidityCurve.ts
2608
+ var LiquidityCurveErrorCode = /* @__PURE__ */ ((LiquidityCurveErrorCode2) => {
2609
+ LiquidityCurveErrorCode2["TOO_MANY_TICKS"] = "TOO_MANY_TICKS";
2610
+ LiquidityCurveErrorCode2["ATOMICITY_VIOLATION"] = "ATOMICITY_VIOLATION";
2611
+ LiquidityCurveErrorCode2["CURVE_SUM_NONZERO"] = "CURVE_SUM_NONZERO";
2612
+ LiquidityCurveErrorCode2["CURVE_NEGATIVE_L"] = "CURVE_NEGATIVE_L";
2613
+ LiquidityCurveErrorCode2["CURVE_EDGE_NONZERO"] = "CURVE_EDGE_NONZERO";
2614
+ return LiquidityCurveErrorCode2;
2615
+ })(LiquidityCurveErrorCode || {});
2616
+ var LiquidityCurveError = class extends Error {
2617
+ code;
2618
+ constructor(code, message) {
2619
+ super(message);
2620
+ this.name = "LiquidityCurveError";
2621
+ this.code = code;
2622
+ }
2623
+ };
2624
+ function buildLiquidityCurve(params) {
2625
+ const { ticks, currentTick, currentLiquidity, tickSpacing } = params;
2626
+ const TICK_LO = minUsableTick(tickSpacing);
2627
+ const TICK_HI = maxUsableTick(tickSpacing);
2628
+ const N = ticks.length;
2629
+ const sumNet = ticks.reduce((acc, t) => acc + t.liquidityNet, 0n);
2630
+ if (sumNet !== 0n) {
2631
+ throw new LiquidityCurveError(
2632
+ "CURVE_SUM_NONZERO" /* CURVE_SUM_NONZERO */,
2633
+ `buildLiquidityCurve: sum(liquidityNet) = ${sumNet}, expected 0. Tick set is incomplete or fetched at a different block.`
2634
+ );
2635
+ }
2636
+ if (N === 0) {
2637
+ return [
2638
+ {
2639
+ tickLower: TICK_LO,
2640
+ tickUpper: TICK_HI,
2641
+ sqrtPriceLowerX96: tickToSqrtPriceX96(TICK_LO),
2642
+ sqrtPriceUpperX96: tickToSqrtPriceX96(TICK_HI),
2643
+ liquidityActive: currentLiquidity
2644
+ }
2645
+ ];
2646
+ }
2647
+ let lo = 0;
2648
+ let hi = N;
2649
+ while (lo < hi) {
2650
+ const mid = lo + hi >>> 1;
2651
+ if (ticks[mid].tick > currentTick) hi = mid;
2652
+ else lo = mid + 1;
2653
+ }
2654
+ const i_above = lo;
2655
+ const i_below = i_above - 1;
2656
+ const segments = new Array(N + 1);
2657
+ const anchorLower = i_below >= 0 ? ticks[i_below].tick : TICK_LO;
2658
+ const anchorUpper = i_above < N ? ticks[i_above].tick : TICK_HI;
2659
+ segments[i_above] = {
2660
+ tickLower: anchorLower,
2661
+ tickUpper: anchorUpper,
2662
+ sqrtPriceLowerX96: 0n,
2663
+ // filled below
2664
+ sqrtPriceUpperX96: 0n,
2665
+ liquidityActive: currentLiquidity
2666
+ };
2667
+ let L = currentLiquidity;
2668
+ for (let k = i_below; k >= 0; k--) {
2669
+ L = L - ticks[k].liquidityNet;
2670
+ if (L < 0n) {
2671
+ throw new LiquidityCurveError(
2672
+ "CURVE_NEGATIVE_L" /* CURVE_NEGATIVE_L */,
2673
+ `buildLiquidityCurve: active liquidity went negative at tick ${ticks[k].tick} during left walk. Indicates inconsistent input.`
2674
+ );
2675
+ }
2676
+ const lower = k - 1 >= 0 ? ticks[k - 1].tick : TICK_LO;
2677
+ segments[k] = {
2678
+ tickLower: lower,
2679
+ tickUpper: ticks[k].tick,
2680
+ sqrtPriceLowerX96: 0n,
2681
+ sqrtPriceUpperX96: 0n,
2682
+ liquidityActive: L
2683
+ };
2684
+ }
2685
+ L = currentLiquidity;
2686
+ for (let j = i_above; j < N; j++) {
2687
+ L = L + ticks[j].liquidityNet;
2688
+ if (L < 0n) {
2689
+ throw new LiquidityCurveError(
2690
+ "CURVE_NEGATIVE_L" /* CURVE_NEGATIVE_L */,
2691
+ `buildLiquidityCurve: active liquidity went negative at tick ${ticks[j].tick} during right walk.`
2692
+ );
2693
+ }
2694
+ const upper = j + 1 < N ? ticks[j + 1].tick : TICK_HI;
2695
+ segments[j + 1] = {
2696
+ tickLower: ticks[j].tick,
2697
+ tickUpper: upper,
2698
+ sqrtPriceLowerX96: 0n,
2699
+ sqrtPriceUpperX96: 0n,
2700
+ liquidityActive: L
2701
+ };
2702
+ }
2703
+ if (segments[0].liquidityActive !== 0n) {
2704
+ throw new LiquidityCurveError(
2705
+ "CURVE_EDGE_NONZERO" /* CURVE_EDGE_NONZERO */,
2706
+ `buildLiquidityCurve: leftmost L = ${segments[0].liquidityActive}, expected 0. currentLiquidity inconsistent with tick set.`
2707
+ );
2708
+ }
2709
+ if (segments[N].liquidityActive !== 0n) {
2710
+ throw new LiquidityCurveError(
2711
+ "CURVE_EDGE_NONZERO" /* CURVE_EDGE_NONZERO */,
2712
+ `buildLiquidityCurve: rightmost L = ${segments[N].liquidityActive}, expected 0.`
2713
+ );
2714
+ }
2715
+ for (const seg of segments) {
2716
+ seg.sqrtPriceLowerX96 = tickToSqrtPriceX96(seg.tickLower);
2717
+ seg.sqrtPriceUpperX96 = tickToSqrtPriceX96(seg.tickUpper);
2718
+ }
2719
+ return segments;
2720
+ }
2721
+ function clipCurveToTickRange(curve, tickLo, tickHi) {
2722
+ if (curve.length === 0 || tickHi <= tickLo) return [];
2723
+ let lo = 0;
2724
+ let hi = curve.length;
2725
+ while (lo < hi) {
2726
+ const mid = lo + hi >>> 1;
2727
+ if (curve[mid].tickUpper > tickLo) hi = mid;
2728
+ else lo = mid + 1;
2729
+ }
2730
+ const startIdx = lo;
2731
+ lo = 0;
2732
+ hi = curve.length;
2733
+ while (lo < hi) {
2734
+ const mid = lo + hi >>> 1;
2735
+ if (curve[mid].tickLower >= tickHi) hi = mid;
2736
+ else lo = mid + 1;
2737
+ }
2738
+ const endIdx = lo;
2739
+ if (startIdx >= endIdx) return [];
2740
+ const out = [];
2741
+ for (let i = startIdx; i < endIdx; i++) {
2742
+ const seg = curve[i];
2743
+ const newLower = Math.max(seg.tickLower, tickLo);
2744
+ const newUpper = Math.min(seg.tickUpper, tickHi);
2745
+ if (newLower === seg.tickLower && newUpper === seg.tickUpper) {
2746
+ out.push(seg);
2747
+ } else {
2748
+ out.push({
2749
+ tickLower: newLower,
2750
+ tickUpper: newUpper,
2751
+ sqrtPriceLowerX96: tickToSqrtPriceX96(newLower),
2752
+ sqrtPriceUpperX96: tickToSqrtPriceX96(newUpper),
2753
+ liquidityActive: seg.liquidityActive
2754
+ });
2755
+ }
2756
+ }
2757
+ return out;
2758
+ }
2759
+
2760
+ // src/liquidity/fetchAllInitializedTicks.ts
2761
+ var CALLDATA_BYTES_PER_CALL = 36;
2762
+ var DEFAULT_CALLS_PER_BATCH = 250;
2763
+ var DEFAULT_MAX_TICKS = 5e4;
2764
+ async function fetchAllInitializedTicks(params) {
2765
+ const callsPerBatch = params.callsPerBatch ?? DEFAULT_CALLS_PER_BATCH;
2766
+ const maxTicks = params.maxTicks ?? DEFAULT_MAX_TICKS;
2767
+ const batchSizeBytes = callsPerBatch * CALLDATA_BYTES_PER_CALL;
2768
+ const blockNumber = params.blockNumber ?? await params.client.getBlockNumber();
2769
+ let tickSpacing = params.tickSpacing;
2770
+ if (tickSpacing === void 0) {
2771
+ const [resolved] = await params.client.multicall({
2772
+ contracts: [
2773
+ {
2774
+ address: params.pool,
2775
+ abi: v3PoolAbi,
2776
+ functionName: "tickSpacing"
2777
+ }
2778
+ ],
2779
+ allowFailure: false,
2780
+ blockNumber,
2781
+ batchSize: batchSizeBytes
2782
+ });
2783
+ tickSpacing = Number(resolved);
2784
+ }
2785
+ const { min: wordLo, max: wordHi } = bitmapWordRange(tickSpacing);
2786
+ const bitmapContracts = [];
2787
+ for (let w = wordLo; w <= wordHi; w++) {
2788
+ bitmapContracts.push({
2789
+ address: params.pool,
2790
+ abi: v3PoolAbi,
2791
+ functionName: "tickBitmap",
2792
+ args: [w]
2793
+ });
2794
+ }
2795
+ const bitmaps = await params.client.multicall({
2796
+ contracts: bitmapContracts,
2797
+ allowFailure: false,
2798
+ blockNumber,
2799
+ batchSize: batchSizeBytes
2800
+ });
2801
+ const initTicks = [];
2802
+ for (let i = 0; i < bitmaps.length; i++) {
2803
+ const word = bitmaps[i];
2804
+ if (word === 0n) continue;
2805
+ const wordPos = wordLo + i;
2806
+ const decoded = decodeBitmapWord(word, wordPos, tickSpacing);
2807
+ for (const t of decoded) initTicks.push(t);
2808
+ }
2809
+ if (initTicks.length > maxTicks) {
2810
+ throw new LiquidityCurveError(
2811
+ "TOO_MANY_TICKS" /* TOO_MANY_TICKS */,
2812
+ `fetchAllInitializedTicks: pool ${params.pool} has ${initTicks.length} initialized ticks, exceeds maxTicks=${maxTicks}. Pass maxTicks explicitly if you want the full set.`
2813
+ );
2814
+ }
2815
+ if (initTicks.length === 0) {
2816
+ return { blockNumber, tickSpacing, ticks: [] };
2817
+ }
2818
+ const ticksContracts = initTicks.map(
2819
+ (tick) => ({
2820
+ address: params.pool,
2821
+ abi: v3PoolAbi,
2822
+ functionName: "ticks",
2823
+ args: [tick]
2824
+ })
2825
+ );
2826
+ const ticksTuples = await params.client.multicall({
2827
+ contracts: ticksContracts,
2828
+ allowFailure: false,
2829
+ blockNumber,
2830
+ batchSize: batchSizeBytes
2831
+ });
2832
+ const ticks = ticksTuples.map((tuple, i) => ({
2833
+ tick: initTicks[i],
2834
+ liquidityGross: tuple[0],
2835
+ liquidityNet: tuple[1],
2836
+ feeGrowthOutside0X128: tuple[2],
2837
+ feeGrowthOutside1X128: tuple[3],
2838
+ initialized: tuple[7]
2839
+ }));
2840
+ for (const t of ticks) {
2841
+ if (!t.initialized) {
2842
+ throw new LiquidityCurveError(
2843
+ "ATOMICITY_VIOLATION" /* ATOMICITY_VIOLATION */,
2844
+ `fetchAllInitializedTicks: tick ${t.tick} bitmap-set but ticks().initialized=false at block ${blockNumber}. Snapshot is torn \u2014 RPC node likely served different blocks across batches.`
2845
+ );
2846
+ }
2847
+ }
2848
+ return { blockNumber, tickSpacing, ticks };
2849
+ }
2850
+
2851
+ // src/liquidity/fetchLiquidityCurve.ts
2852
+ async function fetchLiquidityCurve(params) {
2853
+ const blockNumber = params.blockNumber ?? await params.client.getBlockNumber();
2854
+ const poolState = params.poolState ?? await readPoolState(params.client, params.pool, blockNumber);
2855
+ const ticksResult = await fetchAllInitializedTicks({
2856
+ client: params.client,
2857
+ pool: params.pool,
2858
+ blockNumber,
2859
+ tickSpacing: poolState.tickSpacing,
2860
+ callsPerBatch: params.callsPerBatch,
2861
+ maxTicks: params.maxTicks
2862
+ });
2863
+ const curve = buildLiquidityCurve({
2864
+ ticks: ticksResult.ticks,
2865
+ currentTick: poolState.tick,
2866
+ currentLiquidity: poolState.liquidity,
2867
+ tickSpacing: poolState.tickSpacing
2868
+ });
2869
+ let lo = 0;
2870
+ let hi = curve.length;
2871
+ while (lo < hi) {
2872
+ const mid = lo + hi >>> 1;
2873
+ if (curve[mid].tickUpper > poolState.tick) hi = mid;
2874
+ else lo = mid + 1;
2875
+ }
2876
+ const currentSegmentIndex = lo;
2877
+ return {
2878
+ blockNumber,
2879
+ poolState,
2880
+ ticks: ticksResult.ticks,
2881
+ curve,
2882
+ currentSegmentIndex
2883
+ };
2884
+ }
2885
+
2886
+ // src/direct/addLiquidityDirect.ts
2887
+ async function addLiquidityDirect(params) {
2888
+ const npm = V3_NPM_ADDRESSES[params.chainId];
2889
+ if (!npm) {
2890
+ throw new Error(
2891
+ `addLiquidityDirect: no NonfungiblePositionManager for chainId ${params.chainId}`
2892
+ );
2893
+ }
2894
+ const factory = import_core17.V3_FACTORY_ADDRESSES[params.chainId];
2895
+ if (!factory) {
2896
+ throw new Error(
2897
+ `addLiquidityDirect: no V3 factory for chainId ${params.chainId}`
2898
+ );
2899
+ }
2900
+ if (params.tickLower >= params.tickUpper) {
2901
+ throw new Error(
2902
+ `addLiquidityDirect: tickLower (${params.tickLower}) must be strictly less than tickUpper (${params.tickUpper})`
2903
+ );
2904
+ }
2905
+ const ts = tickSpacingForFee(params.fee);
2906
+ if (ts !== void 0) {
2907
+ if (params.tickLower % ts !== 0 || params.tickUpper % ts !== 0) {
2908
+ throw new Error(
2909
+ `addLiquidityDirect: ticks must be multiples of tickSpacing ${ts} for fee ${params.fee}`
2910
+ );
2911
+ }
2912
+ }
2913
+ const has0 = params.amount0Desired !== void 0 && params.amount0Desired > 0n;
2914
+ const has1 = params.amount1Desired !== void 0 && params.amount1Desired > 0n;
2915
+ if (has0 === has1) {
2916
+ throw new Error(
2917
+ "addLiquidityDirect: exactly one of amount0Desired / amount1Desired must be a positive bigint"
2918
+ );
2919
+ }
2920
+ const slippageBps = params.slippageBps ?? 50;
2921
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
2922
+ throw new Error(
2923
+ `addLiquidityDirect: slippageBps (${slippageBps}) must be an integer in [0, 10000]`
2924
+ );
2925
+ }
2926
+ const account = params.walletClient.account;
2927
+ if (!account) {
2928
+ throw new Error(
2929
+ "addLiquidityDirect: walletClient has no account attached \u2014 cannot send tx"
2930
+ );
2931
+ }
2932
+ if (account.address.toLowerCase() !== params.userAddress.toLowerCase()) {
2933
+ throw new Error(
2934
+ `addLiquidityDirect: walletClient.account.address (${account.address}) must equal userAddress (${params.userAddress})`
2935
+ );
2936
+ }
2937
+ const code = await params.publicClient.getCode({ address: params.userAddress });
2938
+ const delegate = (0, import_core17.parseEip7702DelegatedAddress)(code);
2939
+ if (!delegate) {
2940
+ throw new Error(
2941
+ `addLiquidityDirect: user ${params.userAddress} is not EIP-7702 delegated. Run \`delegateDirect()\` first or use the AA path.`
2942
+ );
2943
+ }
2944
+ const pool = (0, import_core17.computeV3PoolAddress)({
2945
+ factory,
2946
+ tokenA: params.token0,
2947
+ tokenB: params.token1,
2948
+ fee: params.fee,
2949
+ initCodeHash: import_core17.V3_POOL_INIT_CODE_HASH
2950
+ });
2951
+ const poolState = await readPoolState(params.publicClient, pool);
2952
+ const sqrtL = tickToSqrtPriceX96(params.tickLower);
2953
+ const sqrtU = tickToSqrtPriceX96(params.tickUpper);
2954
+ const { liquidity, amount0, amount1 } = estimateLiquidityFromOneSide({
2955
+ sqrtPriceX96Current: poolState.sqrtPriceX96,
2956
+ sqrtPriceX96Lower: sqrtL,
2957
+ sqrtPriceX96Upper: sqrtU,
2958
+ amount0Desired: params.amount0Desired,
2959
+ amount1Desired: params.amount1Desired
2960
+ });
2961
+ const { amount0Min, amount1Min } = applyMintSlippage({
2962
+ amount0Desired: amount0,
2963
+ amount1Desired: amount1,
2964
+ slippageBps
2965
+ });
2966
+ const deadline = params.deadline ?? BigInt(Math.floor(Date.now() / 1e3) + 5 * 60);
2967
+ const operations = buildMint({
2968
+ npm,
2969
+ token0: params.token0,
2970
+ token1: params.token1,
2971
+ fee: params.fee,
2972
+ tickLower: params.tickLower,
2973
+ tickUpper: params.tickUpper,
2974
+ amount0Desired: amount0,
2975
+ amount1Desired: amount1,
2976
+ amount0Min,
2977
+ amount1Min,
2978
+ recipient: params.userAddress,
2979
+ deadline
2980
+ });
2981
+ const partial = (0, import_core17.buildPartialUserOperation)({
2982
+ sender: params.userAddress,
2983
+ nonce: 0n,
2984
+ operations
2985
+ });
2986
+ const txHash = await params.walletClient.sendTransaction({
2987
+ account,
2988
+ chain: params.walletClient.chain,
2989
+ to: params.userAddress,
2990
+ value: 0n,
2991
+ data: partial.callData
2992
+ });
2993
+ let receipt;
2994
+ let tokenId;
2995
+ if (params.waitForReceipt !== false) {
2996
+ try {
2997
+ receipt = await params.publicClient.waitForTransactionReceipt({ hash: txHash });
2998
+ tokenId = parseMintedTokenId(receipt, npm, params.userAddress);
2999
+ } catch (err) {
3000
+ params.onWarning?.(
3001
+ `addLiquidityDirect: tx ${txHash} sent but receipt fetch failed: ${err instanceof Error ? err.message : String(err)}`
3002
+ );
3003
+ }
3004
+ }
3005
+ return {
3006
+ txHash,
3007
+ receipt,
3008
+ tokenId,
3009
+ amount0Desired: amount0,
3010
+ amount1Desired: amount1,
3011
+ amount0Min,
3012
+ amount1Min,
3013
+ liquidity,
3014
+ deadline
3015
+ };
3016
+ }
3017
+ function parseMintedTokenId(receipt, npm, user) {
3018
+ const userLower = user.toLowerCase();
3019
+ const zero = "0x0000000000000000000000000000000000000000";
3020
+ for (const log of receipt.logs) {
3021
+ if (log.address.toLowerCase() !== npm.toLowerCase()) continue;
3022
+ try {
3023
+ const decoded = (0, import_viem10.decodeEventLog)({
3024
+ abi: nonfungiblePositionManagerAbi,
3025
+ data: log.data,
3026
+ topics: log.topics
3027
+ });
3028
+ if (decoded.eventName !== "Transfer") continue;
3029
+ const args = decoded.args;
3030
+ if (args.from.toLowerCase() === zero && args.to.toLowerCase() === userLower) {
3031
+ return args.tokenId;
3032
+ }
3033
+ } catch {
3034
+ }
3035
+ }
3036
+ return void 0;
3037
+ }
3038
+
3039
+ // src/direct/increaseLiquidityDirect.ts
3040
+ var import_core18 = require("@pafi-dev/core");
3041
+ async function increaseLiquidityDirect(params) {
3042
+ const npm = V3_NPM_ADDRESSES[params.chainId];
3043
+ if (!npm) {
3044
+ throw new Error(
3045
+ `increaseLiquidityDirect: no NonfungiblePositionManager for chainId ${params.chainId}`
3046
+ );
3047
+ }
3048
+ const factory = import_core18.V3_FACTORY_ADDRESSES[params.chainId];
3049
+ if (!factory) {
3050
+ throw new Error(
3051
+ `increaseLiquidityDirect: no V3 factory for chainId ${params.chainId}`
3052
+ );
3053
+ }
3054
+ if (params.tokenId <= 0n) {
3055
+ throw new Error("increaseLiquidityDirect: tokenId must be positive");
3056
+ }
3057
+ const has0 = params.amount0Desired !== void 0 && params.amount0Desired > 0n;
3058
+ const has1 = params.amount1Desired !== void 0 && params.amount1Desired > 0n;
3059
+ if (has0 === has1) {
3060
+ throw new Error(
3061
+ "increaseLiquidityDirect: exactly one of amount0Desired / amount1Desired must be a positive bigint"
3062
+ );
3063
+ }
3064
+ const slippageBps = params.slippageBps ?? 50;
3065
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
3066
+ throw new Error(
3067
+ `increaseLiquidityDirect: slippageBps (${slippageBps}) must be an integer in [0, 10000]`
3068
+ );
3069
+ }
3070
+ const account = params.walletClient.account;
3071
+ if (!account) {
3072
+ throw new Error("increaseLiquidityDirect: walletClient has no account attached");
3073
+ }
3074
+ if (account.address.toLowerCase() !== params.userAddress.toLowerCase()) {
3075
+ throw new Error(
3076
+ `increaseLiquidityDirect: walletClient.account.address (${account.address}) must equal userAddress (${params.userAddress})`
3077
+ );
3078
+ }
3079
+ const code = await params.publicClient.getCode({ address: params.userAddress });
3080
+ const delegate = (0, import_core18.parseEip7702DelegatedAddress)(code);
3081
+ if (!delegate) {
3082
+ throw new Error(
3083
+ `increaseLiquidityDirect: user ${params.userAddress} is not EIP-7702 delegated.`
3084
+ );
3085
+ }
3086
+ const position = await readPosition(params.publicClient, npm, params.tokenId);
3087
+ const pool = (0, import_core18.computeV3PoolAddress)({
3088
+ factory,
3089
+ tokenA: position.token0,
3090
+ tokenB: position.token1,
3091
+ fee: position.fee,
3092
+ initCodeHash: import_core18.V3_POOL_INIT_CODE_HASH
3093
+ });
3094
+ const poolState = await readPoolState(params.publicClient, pool);
3095
+ const sqrtL = tickToSqrtPriceX96(position.tickLower);
3096
+ const sqrtU = tickToSqrtPriceX96(position.tickUpper);
3097
+ const { liquidity, amount0, amount1 } = estimateLiquidityFromOneSide({
3098
+ sqrtPriceX96Current: poolState.sqrtPriceX96,
3099
+ sqrtPriceX96Lower: sqrtL,
3100
+ sqrtPriceX96Upper: sqrtU,
3101
+ amount0Desired: params.amount0Desired,
3102
+ amount1Desired: params.amount1Desired
3103
+ });
3104
+ const { amount0Min, amount1Min } = applyMintSlippage({
3105
+ amount0Desired: amount0,
3106
+ amount1Desired: amount1,
3107
+ slippageBps
3108
+ });
3109
+ const deadline = params.deadline ?? BigInt(Math.floor(Date.now() / 1e3) + 5 * 60);
3110
+ const operations = buildIncreaseLiquidity({
3111
+ npm,
3112
+ token0: position.token0,
3113
+ token1: position.token1,
3114
+ tokenId: params.tokenId,
3115
+ amount0Desired: amount0,
3116
+ amount1Desired: amount1,
3117
+ amount0Min,
3118
+ amount1Min,
3119
+ deadline
3120
+ });
3121
+ const partial = (0, import_core18.buildPartialUserOperation)({
3122
+ sender: params.userAddress,
3123
+ nonce: 0n,
3124
+ operations
3125
+ });
3126
+ const txHash = await params.walletClient.sendTransaction({
3127
+ account,
3128
+ chain: params.walletClient.chain,
3129
+ to: params.userAddress,
3130
+ value: 0n,
3131
+ data: partial.callData
3132
+ });
3133
+ let receipt;
3134
+ if (params.waitForReceipt !== false) {
3135
+ try {
3136
+ receipt = await params.publicClient.waitForTransactionReceipt({ hash: txHash });
3137
+ } catch (err) {
3138
+ params.onWarning?.(
3139
+ `increaseLiquidityDirect: tx ${txHash} sent but receipt fetch failed: ${err instanceof Error ? err.message : String(err)}`
3140
+ );
3141
+ }
3142
+ }
3143
+ return {
3144
+ txHash,
3145
+ receipt,
3146
+ amount0Desired: amount0,
3147
+ amount1Desired: amount1,
3148
+ amount0Min,
3149
+ amount1Min,
3150
+ liquidityAdded: liquidity,
3151
+ deadline
3152
+ };
3153
+ }
3154
+
3155
+ // src/direct/removeLiquidityDirect.ts
3156
+ var import_core19 = require("@pafi-dev/core");
3157
+ async function removeLiquidityDirect(params) {
3158
+ const npm = V3_NPM_ADDRESSES[params.chainId];
3159
+ if (!npm) {
3160
+ throw new Error(
3161
+ `removeLiquidityDirect: no NonfungiblePositionManager for chainId ${params.chainId}`
3162
+ );
3163
+ }
3164
+ const factory = import_core19.V3_FACTORY_ADDRESSES[params.chainId];
3165
+ if (!factory) {
3166
+ throw new Error(`removeLiquidityDirect: no V3 factory for chainId ${params.chainId}`);
3167
+ }
3168
+ if (params.tokenId <= 0n) {
3169
+ throw new Error("removeLiquidityDirect: tokenId must be positive");
3170
+ }
3171
+ const hasL = params.liquidity !== void 0 && params.liquidity > 0n;
3172
+ const hasBps = params.liquidityBps !== void 0 && params.liquidityBps > 0 && params.liquidityBps <= 1e4;
3173
+ if (hasL === hasBps) {
3174
+ throw new Error(
3175
+ "removeLiquidityDirect: exactly one of liquidity (>0) or liquidityBps (1..10000) must be set"
3176
+ );
3177
+ }
3178
+ const slippageBps = params.slippageBps ?? 50;
3179
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
3180
+ throw new Error(
3181
+ `removeLiquidityDirect: slippageBps (${slippageBps}) must be an integer in [0, 10000]`
3182
+ );
3183
+ }
3184
+ const account = params.walletClient.account;
3185
+ if (!account) {
3186
+ throw new Error("removeLiquidityDirect: walletClient has no account attached");
3187
+ }
3188
+ if (account.address.toLowerCase() !== params.userAddress.toLowerCase()) {
3189
+ throw new Error(
3190
+ `removeLiquidityDirect: walletClient.account.address (${account.address}) must equal userAddress (${params.userAddress})`
3191
+ );
3192
+ }
3193
+ const code = await params.publicClient.getCode({ address: params.userAddress });
3194
+ if (!(0, import_core19.parseEip7702DelegatedAddress)(code)) {
3195
+ throw new Error(
3196
+ `removeLiquidityDirect: user ${params.userAddress} is not EIP-7702 delegated.`
3197
+ );
3198
+ }
3199
+ const position = await readPosition(params.publicClient, npm, params.tokenId);
3200
+ if (position.liquidity === 0n) {
3201
+ throw new Error(
3202
+ `removeLiquidityDirect: position ${params.tokenId} has zero liquidity \u2014 nothing to remove`
3203
+ );
3204
+ }
3205
+ const liquidityToRemove = hasL ? params.liquidity : position.liquidity * BigInt(params.liquidityBps) / 10000n;
3206
+ if (liquidityToRemove === 0n) {
3207
+ throw new Error(
3208
+ "removeLiquidityDirect: computed liquidity to remove is zero (bps too small for position size)"
3209
+ );
3210
+ }
3211
+ if (liquidityToRemove > position.liquidity) {
3212
+ throw new Error(
3213
+ `removeLiquidityDirect: liquidity to remove (${liquidityToRemove}) exceeds position liquidity (${position.liquidity})`
3214
+ );
3215
+ }
3216
+ const pool = (0, import_core19.computeV3PoolAddress)({
3217
+ factory,
3218
+ tokenA: position.token0,
3219
+ tokenB: position.token1,
3220
+ fee: position.fee,
3221
+ initCodeHash: import_core19.V3_POOL_INIT_CODE_HASH
3222
+ });
3223
+ const poolState = await readPoolState(params.publicClient, pool);
3224
+ const { amount0: amount0Expected, amount1: amount1Expected } = getAmountsForLiquidity({
3225
+ sqrtPriceX96Current: poolState.sqrtPriceX96,
3226
+ sqrtPriceX96Lower: tickToSqrtPriceX96(position.tickLower),
3227
+ sqrtPriceX96Upper: tickToSqrtPriceX96(position.tickUpper),
3228
+ liquidity: liquidityToRemove
3229
+ });
3230
+ const { amount0Min, amount1Min } = applyRemoveSlippage({
3231
+ amount0Expected,
3232
+ amount1Expected,
3233
+ slippageBps
3234
+ });
3235
+ const deadline = params.deadline ?? BigInt(Math.floor(Date.now() / 1e3) + 5 * 60);
3236
+ const operations = [
3237
+ buildDecreaseLiquidity({
3238
+ npm,
3239
+ tokenId: params.tokenId,
3240
+ liquidity: liquidityToRemove,
3241
+ amount0Min,
3242
+ amount1Min,
3243
+ deadline
3244
+ }),
3245
+ buildCollect({
3246
+ npm,
3247
+ tokenId: params.tokenId,
3248
+ recipient: params.userAddress
3249
+ })
3250
+ ];
3251
+ const partial = (0, import_core19.buildPartialUserOperation)({
3252
+ sender: params.userAddress,
3253
+ nonce: 0n,
3254
+ operations
3255
+ });
3256
+ const txHash = await params.walletClient.sendTransaction({
3257
+ account,
3258
+ chain: params.walletClient.chain,
3259
+ to: params.userAddress,
3260
+ value: 0n,
3261
+ data: partial.callData
3262
+ });
3263
+ let receipt;
3264
+ if (params.waitForReceipt !== false) {
3265
+ try {
3266
+ receipt = await params.publicClient.waitForTransactionReceipt({ hash: txHash });
3267
+ } catch (err) {
3268
+ params.onWarning?.(
3269
+ `removeLiquidityDirect: tx ${txHash} sent but receipt fetch failed: ${err instanceof Error ? err.message : String(err)}`
3270
+ );
3271
+ }
3272
+ }
3273
+ return {
3274
+ txHash,
3275
+ receipt,
3276
+ liquidityRemoved: liquidityToRemove,
3277
+ amount0Expected,
3278
+ amount1Expected,
3279
+ amount0Min,
3280
+ amount1Min,
3281
+ deadline
3282
+ };
3283
+ }
3284
+
3285
+ // src/direct/closePositionDirect.ts
3286
+ var import_core20 = require("@pafi-dev/core");
3287
+ async function closePositionDirect(params) {
3288
+ const npm = V3_NPM_ADDRESSES[params.chainId];
3289
+ if (!npm) {
3290
+ throw new Error(
3291
+ `closePositionDirect: no NonfungiblePositionManager for chainId ${params.chainId}`
3292
+ );
3293
+ }
3294
+ const factory = import_core20.V3_FACTORY_ADDRESSES[params.chainId];
3295
+ if (!factory) {
3296
+ throw new Error(`closePositionDirect: no V3 factory for chainId ${params.chainId}`);
3297
+ }
3298
+ if (params.tokenId <= 0n) {
3299
+ throw new Error("closePositionDirect: tokenId must be positive");
3300
+ }
3301
+ const slippageBps = params.slippageBps ?? 50;
3302
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 1e4) {
3303
+ throw new Error(
3304
+ `closePositionDirect: slippageBps (${slippageBps}) must be an integer in [0, 10000]`
3305
+ );
3306
+ }
3307
+ const account = params.walletClient.account;
3308
+ if (!account) {
3309
+ throw new Error("closePositionDirect: walletClient has no account attached");
3310
+ }
3311
+ if (account.address.toLowerCase() !== params.userAddress.toLowerCase()) {
3312
+ throw new Error(
3313
+ `closePositionDirect: walletClient.account.address (${account.address}) must equal userAddress (${params.userAddress})`
3314
+ );
3315
+ }
3316
+ const code = await params.publicClient.getCode({ address: params.userAddress });
3317
+ if (!(0, import_core20.parseEip7702DelegatedAddress)(code)) {
3318
+ throw new Error(
3319
+ `closePositionDirect: user ${params.userAddress} is not EIP-7702 delegated.`
3320
+ );
3321
+ }
3322
+ const position = await readPosition(params.publicClient, npm, params.tokenId);
3323
+ let amount0Expected = 0n;
3324
+ let amount1Expected = 0n;
3325
+ let amount0Min = 0n;
3326
+ let amount1Min = 0n;
3327
+ if (position.liquidity > 0n) {
3328
+ const pool = (0, import_core20.computeV3PoolAddress)({
3329
+ factory,
3330
+ tokenA: position.token0,
3331
+ tokenB: position.token1,
3332
+ fee: position.fee,
3333
+ initCodeHash: import_core20.V3_POOL_INIT_CODE_HASH
3334
+ });
3335
+ const poolState = await readPoolState(params.publicClient, pool);
3336
+ const amounts = getAmountsForLiquidity({
3337
+ sqrtPriceX96Current: poolState.sqrtPriceX96,
3338
+ sqrtPriceX96Lower: tickToSqrtPriceX96(position.tickLower),
3339
+ sqrtPriceX96Upper: tickToSqrtPriceX96(position.tickUpper),
3340
+ liquidity: position.liquidity
3341
+ });
3342
+ amount0Expected = amounts.amount0;
3343
+ amount1Expected = amounts.amount1;
3344
+ const min = applyRemoveSlippage({
3345
+ amount0Expected,
3346
+ amount1Expected,
3347
+ slippageBps
3348
+ });
3349
+ amount0Min = min.amount0Min;
3350
+ amount1Min = min.amount1Min;
3351
+ }
3352
+ const deadline = params.deadline ?? BigInt(Math.floor(Date.now() / 1e3) + 5 * 60);
3353
+ const operations = buildClosePosition({
3354
+ npm,
3355
+ tokenId: params.tokenId,
3356
+ liquidity: position.liquidity,
3357
+ hasOutstandingFees: position.tokensOwed0 + position.tokensOwed1 > 0n,
3358
+ recipient: params.userAddress,
3359
+ amount0Min,
3360
+ amount1Min,
3361
+ deadline
3362
+ });
3363
+ const partial = (0, import_core20.buildPartialUserOperation)({
3364
+ sender: params.userAddress,
3365
+ nonce: 0n,
3366
+ operations
3367
+ });
3368
+ const txHash = await params.walletClient.sendTransaction({
3369
+ account,
3370
+ chain: params.walletClient.chain,
3371
+ to: params.userAddress,
3372
+ value: 0n,
3373
+ data: partial.callData
3374
+ });
3375
+ let receipt;
3376
+ if (params.waitForReceipt !== false) {
3377
+ try {
3378
+ receipt = await params.publicClient.waitForTransactionReceipt({ hash: txHash });
3379
+ } catch (err) {
3380
+ params.onWarning?.(
3381
+ `closePositionDirect: tx ${txHash} sent but receipt fetch failed: ${err instanceof Error ? err.message : String(err)}`
3382
+ );
3383
+ }
3384
+ }
3385
+ return {
3386
+ txHash,
3387
+ receipt,
3388
+ liquidityRemoved: position.liquidity,
3389
+ amount0Expected,
3390
+ amount1Expected,
3391
+ amount0Min,
3392
+ amount1Min,
3393
+ deadline
3394
+ };
3395
+ }
3396
+
3397
+ // src/direct/collectFeesDirect.ts
3398
+ var import_core21 = require("@pafi-dev/core");
3399
+ async function collectFeesDirect(params) {
3400
+ const npm = V3_NPM_ADDRESSES[params.chainId];
3401
+ if (!npm) {
3402
+ throw new Error(
3403
+ `collectFeesDirect: no NonfungiblePositionManager for chainId ${params.chainId}`
3404
+ );
3405
+ }
3406
+ const factory = import_core21.V3_FACTORY_ADDRESSES[params.chainId];
3407
+ if (!factory) {
3408
+ throw new Error(`collectFeesDirect: no V3 factory for chainId ${params.chainId}`);
3409
+ }
3410
+ if (params.tokenId <= 0n) {
3411
+ throw new Error("collectFeesDirect: tokenId must be positive");
3412
+ }
3413
+ const account = params.walletClient.account;
3414
+ if (!account) {
3415
+ throw new Error("collectFeesDirect: walletClient has no account attached");
3416
+ }
3417
+ if (account.address.toLowerCase() !== params.userAddress.toLowerCase()) {
3418
+ throw new Error(
3419
+ `collectFeesDirect: walletClient.account.address (${account.address}) must equal userAddress (${params.userAddress})`
3420
+ );
3421
+ }
3422
+ const code = await params.publicClient.getCode({ address: params.userAddress });
3423
+ if (!(0, import_core21.parseEip7702DelegatedAddress)(code)) {
3424
+ throw new Error(
3425
+ `collectFeesDirect: user ${params.userAddress} is not EIP-7702 delegated.`
3426
+ );
3427
+ }
3428
+ const position = await readPosition(params.publicClient, npm, params.tokenId);
3429
+ let amount0Expected = position.tokensOwed0;
3430
+ let amount1Expected = position.tokensOwed1;
3431
+ if (position.liquidity > 0n) {
3432
+ const pool = (0, import_core21.computeV3PoolAddress)({
3433
+ factory,
3434
+ tokenA: position.token0,
3435
+ tokenB: position.token1,
3436
+ fee: position.fee,
3437
+ initCodeHash: import_core21.V3_POOL_INIT_CODE_HASH
3438
+ });
3439
+ const [poolState, ticks, globals] = await Promise.all([
3440
+ readPoolState(params.publicClient, pool),
3441
+ readTicksAt(params.publicClient, pool, position.tickLower, position.tickUpper),
3442
+ readFeeGrowthGlobals(params.publicClient, pool)
3443
+ ]);
3444
+ const feeGrowthInside0 = computeFeeGrowthInside({
3445
+ currentTick: poolState.tick,
3446
+ tickLower: position.tickLower,
3447
+ tickUpper: position.tickUpper,
3448
+ feeGrowthGlobalX128: globals.feeGrowthGlobal0X128,
3449
+ feeGrowthOutsideLowerX128: ticks.lower.feeGrowthOutside0X128,
3450
+ feeGrowthOutsideUpperX128: ticks.upper.feeGrowthOutside0X128
3451
+ });
3452
+ const feeGrowthInside1 = computeFeeGrowthInside({
3453
+ currentTick: poolState.tick,
3454
+ tickLower: position.tickLower,
3455
+ tickUpper: position.tickUpper,
3456
+ feeGrowthGlobalX128: globals.feeGrowthGlobal1X128,
3457
+ feeGrowthOutsideLowerX128: ticks.lower.feeGrowthOutside1X128,
3458
+ feeGrowthOutsideUpperX128: ticks.upper.feeGrowthOutside1X128
3459
+ });
3460
+ const pending0 = wrappingDelta(
3461
+ feeGrowthInside0,
3462
+ position.feeGrowthInside0LastX128
3463
+ ) * position.liquidity / (1n << 128n);
3464
+ const pending1 = wrappingDelta(
3465
+ feeGrowthInside1,
3466
+ position.feeGrowthInside1LastX128
3467
+ ) * position.liquidity / (1n << 128n);
3468
+ amount0Expected += pending0;
3469
+ amount1Expected += pending1;
3470
+ }
3471
+ const recipient = params.recipient ?? params.userAddress;
3472
+ const operations = [buildCollect({ npm, tokenId: params.tokenId, recipient })];
3473
+ const partial = (0, import_core21.buildPartialUserOperation)({
3474
+ sender: params.userAddress,
3475
+ nonce: 0n,
3476
+ operations
3477
+ });
3478
+ const txHash = await params.walletClient.sendTransaction({
3479
+ account,
3480
+ chain: params.walletClient.chain,
3481
+ to: params.userAddress,
3482
+ value: 0n,
3483
+ data: partial.callData
3484
+ });
3485
+ let receipt;
3486
+ if (params.waitForReceipt !== false) {
3487
+ try {
3488
+ receipt = await params.publicClient.waitForTransactionReceipt({ hash: txHash });
3489
+ } catch (err) {
3490
+ params.onWarning?.(
3491
+ `collectFeesDirect: tx ${txHash} sent but receipt fetch failed: ${err instanceof Error ? err.message : String(err)}`
3492
+ );
3493
+ }
3494
+ }
3495
+ return {
3496
+ txHash,
3497
+ receipt,
3498
+ amount0Expected,
3499
+ amount1Expected,
3500
+ recipient
3501
+ };
3502
+ }
3503
+ function computeFeeGrowthInside(params) {
3504
+ const {
3505
+ currentTick,
3506
+ tickLower,
3507
+ tickUpper,
3508
+ feeGrowthGlobalX128,
3509
+ feeGrowthOutsideLowerX128,
3510
+ feeGrowthOutsideUpperX128
3511
+ } = params;
3512
+ let feeGrowthBelow;
3513
+ if (currentTick >= tickLower) {
3514
+ feeGrowthBelow = feeGrowthOutsideLowerX128;
3515
+ } else {
3516
+ feeGrowthBelow = wrappingDelta(feeGrowthGlobalX128, feeGrowthOutsideLowerX128);
3517
+ }
3518
+ let feeGrowthAbove;
3519
+ if (currentTick < tickUpper) {
3520
+ feeGrowthAbove = feeGrowthOutsideUpperX128;
3521
+ } else {
3522
+ feeGrowthAbove = wrappingDelta(feeGrowthGlobalX128, feeGrowthOutsideUpperX128);
3523
+ }
3524
+ return wrappingDelta(
3525
+ wrappingDelta(feeGrowthGlobalX128, feeGrowthBelow),
3526
+ feeGrowthAbove
3527
+ );
3528
+ }
3529
+ function wrappingDelta(a, b) {
3530
+ const TWO_256 = 1n << 256n;
3531
+ return (a - b + TWO_256) % TWO_256;
3532
+ }
1523
3533
  // Annotate the CommonJS export names for ESM import in node:
1524
3534
  0 && (module.exports = {
3535
+ CALLDATA_BYTES_PER_CALL,
3536
+ LiquidityCurveError,
3537
+ LiquidityCurveErrorCode,
3538
+ MAX_SQRT_RATIO,
3539
+ MAX_TICK,
3540
+ MIN_SQRT_RATIO,
3541
+ MIN_TICK,
1525
3542
  PAFI_SUBGRAPH_URL,
3543
+ Q192,
3544
+ Q96,
1526
3545
  TradingHandlers,
3546
+ UINT128_MAX,
3547
+ V3_NPM_ADDRESSES,
1527
3548
  V3_SWAP_EXACT_IN,
1528
3549
  V3_SWAP_EXACT_OUT,
3550
+ addLiquidityDirect,
3551
+ applyMintSlippage,
3552
+ applyRemoveSlippage,
3553
+ bitmapWordRange,
1529
3554
  buildAllPaths,
3555
+ buildBurn,
3556
+ buildClosePosition,
3557
+ buildCollect,
3558
+ buildDecreaseLiquidity,
1530
3559
  buildErc20ApprovalCalldata,
3560
+ buildIncreaseLiquidity,
3561
+ buildLiquidityCurve,
3562
+ buildMint,
1531
3563
  buildPermit2ApprovalCalldata,
1532
3564
  buildSwapUserOp,
1533
3565
  buildSwapUserOpExactOut,
@@ -1536,19 +3568,48 @@ async function perpDepositDirect(params) {
1536
3568
  buildV3SwapInputExactIn,
1537
3569
  buildV3SwapInputExactOut,
1538
3570
  checkAllowance,
3571
+ clipCurveToTickRange,
3572
+ closePositionDirect,
3573
+ collectFeesDirect,
1539
3574
  combineRoutes,
3575
+ decodeBitmapWord,
3576
+ estimateLiquidityFromOneSide,
3577
+ fetchAllInitializedTicks,
3578
+ fetchLiquidityCurve,
1540
3579
  fetchPafiPools,
1541
3580
  findBestQuote,
1542
3581
  findBestQuoteExactOut,
3582
+ getAmount0ForLiquidity,
3583
+ getAmount1ForLiquidity,
3584
+ getAmountsForLiquidity,
3585
+ getLiquidityForAmount0,
3586
+ getLiquidityForAmount1,
3587
+ increaseLiquidityDirect,
3588
+ maxUsableTick,
3589
+ minUsableTick,
3590
+ nearestUsableTick,
3591
+ nonfungiblePositionManagerAbi,
1543
3592
  perpDepositDirect,
3593
+ priceToTick,
1544
3594
  quoteBestRoute,
1545
3595
  quoteBestRouteExactOut,
1546
3596
  quoteExactInput,
1547
3597
  quoteExactInputSingle,
1548
3598
  quoteExactOutput,
1549
3599
  quoteExactOutputSingle,
3600
+ readFeeGrowthGlobals,
3601
+ readPoolState,
3602
+ readPosition,
3603
+ readTicksAt,
3604
+ removeLiquidityDirect,
1550
3605
  simulateSwap,
3606
+ sqrtPriceX96ToTick,
1551
3607
  swapDirect,
1552
- swapDirectExactOut
3608
+ swapDirectExactOut,
3609
+ tickSpacingForFee,
3610
+ tickToBitmapPosition,
3611
+ tickToPrice,
3612
+ tickToSqrtPriceX96,
3613
+ v3PoolAbi
1553
3614
  });
1554
3615
  //# sourceMappingURL=index.cjs.map