@pafi-dev/trading 0.9.0 → 0.10.0

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