@panoptic-eng/sdk 1.0.61 → 1.0.62

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.
@@ -1,4 +1,4 @@
1
- import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, ExecutionRevertedError, decodeAbiParameters, decodeErrorResult, decodeEventLog, decodeFunctionData, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, erc20Abi, getAbiItem, getAddress, hexToString, keccak256, parseAbi, toFunctionSelector, toHex, trim, zeroAddress } from "viem";
1
+ import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, ExecutionRevertedError, decodeAbiParameters, decodeErrorResult, decodeEventLog, decodeFunctionData, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, erc20Abi, getAbiItem, getAddress, hexToString, keccak256, parseAbi, parseEventLogs, toFunctionSelector, toHex, trim, zeroAddress } from "viem";
2
2
  import { call, multicall } from "viem/actions";
3
3
  import Decimal from "decimal.js";
4
4
 
@@ -11274,7 +11274,7 @@ function splitTokenIdByTimescale(tokenId, positionSize, targetTimescale) {
11274
11274
 
11275
11275
  //#endregion
11276
11276
  //#region src/uniswap/lpDeposit.ts
11277
- const Q96$2 = 1n << 96n;
11277
+ const Q96$3 = 1n << 96n;
11278
11278
  const ceilDiv$4 = (n, d) => (n + d - 1n) / d;
11279
11279
  /** Principal and separately identified funding headroom, in native token units. */
11280
11280
  function getLpDepositBreakdown(ranges, sqrtPriceX96) {
@@ -11286,8 +11286,8 @@ function getLpDepositBreakdown(ranges, sqrtPriceX96) {
11286
11286
  const lower = tickToSqrtPriceX96(BigInt(tickLower));
11287
11287
  const upper = tickToSqrtPriceX96(BigInt(tickUpper));
11288
11288
  const price = sqrtPriceX96 < lower ? lower : sqrtPriceX96 > upper ? upper : sqrtPriceX96;
11289
- amount0 += ceilDiv$4(liquidity * Q96$2 * (upper - price), upper * price);
11290
- amount1 += ceilDiv$4(liquidity * (price - lower), Q96$2);
11289
+ amount0 += ceilDiv$4(liquidity * Q96$3 * (upper - price), upper * price);
11290
+ amount1 += ceilDiv$4(liquidity * (price - lower), Q96$3);
11291
11291
  }
11292
11292
  const buffer = {
11293
11293
  amount0: ceilDiv$4(amount0 * 5n, 100n),
@@ -11315,7 +11315,7 @@ function getUnhedgedLpRanges({ tokenId, positionSize, tickSpacing }) {
11315
11315
  const lower = tickToSqrtPriceX96(tickLower);
11316
11316
  const upper = tickToSqrtPriceX96(tickUpper);
11317
11317
  const amount = positionSize * leg.optionRatio;
11318
- const liquidity = leg.asset === 0n ? amount * (lower * upper / Q96$2) / (upper - lower) : amount * Q96$2 / (upper - lower);
11318
+ const liquidity = leg.asset === 0n ? amount * (lower * upper / Q96$3) / (upper - lower) : amount * Q96$3 / (upper - lower);
11319
11319
  return liquidity <= 0n ? [] : [{
11320
11320
  tickLower: Number(tickLower),
11321
11321
  tickUpper: Number(tickUpper),
@@ -11336,7 +11336,7 @@ function getLpPositionFunding(params) {
11336
11336
  });
11337
11337
  const breakdown = getLpDepositBreakdown(ranges, sqrtPriceX96);
11338
11338
  const priceSquared = valuationSqrtPriceX96 * valuationSqrtPriceX96;
11339
- const value = ({ amount0, amount1 }) => quoteTokenIndex === 0 ? amount0 + ceilDiv$4(amount1 * Q96$2 * Q96$2, priceSquared) : amount1 + ceilDiv$4(amount0 * priceSquared, Q96$2 * Q96$2);
11339
+ const value = ({ amount0, amount1 }) => quoteTokenIndex === 0 ? amount0 + ceilDiv$4(amount1 * Q96$3 * Q96$3, priceSquared) : amount1 + ceilDiv$4(amount0 * priceSquared, Q96$3 * Q96$3);
11340
11340
  const principalInQuote = value(breakdown.principal);
11341
11341
  const totalInQuote = value(breakdown.total);
11342
11342
  return {
@@ -14480,7 +14480,7 @@ async function assertLpPositionFunded(params) {
14480
14480
  //#endregion
14481
14481
  //#region src/panoptic/v2/greeks/index.ts
14482
14482
  /** Fixed-point scale constants for sqrtPriceX96 arithmetic */
14483
- const Q96$1 = 1n << 96n;
14483
+ const Q96$2 = 1n << 96n;
14484
14484
  const Q192$3 = 1n << 192n;
14485
14485
  /**
14486
14486
  * Convert tick to quote-denominated tick based on asset direction.
@@ -14628,7 +14628,7 @@ function computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut) {
14628
14628
  const sqrtK = tickToSqrtPriceX96(qStrikeTick);
14629
14629
  const sqrtPm = tickToSqrtPriceX96(qMintTick);
14630
14630
  const rX192 = sqrtR * sqrtR;
14631
- const sqrtKPmX96 = divTrunc(sqrtK * Q96$1, sqrtPm);
14631
+ const sqrtKPmX96 = divTrunc(sqrtK * Q96$2, sqrtPm);
14632
14632
  const diff = sqrtR - sqrtKPmX96;
14633
14633
  const diffSqX192 = diff * diff;
14634
14634
  return divTrunc(m * diffSqX192, rX192 - Q192$3);
@@ -14700,7 +14700,7 @@ function getLegValue(leg, currentTick, mintTick, positionSize, poolTickSpacing,
14700
14700
  const PX192 = sqrtP * sqrtP;
14701
14701
  const KX192 = sqrtK * sqrtK;
14702
14702
  const rX192 = sqrtR * sqrtR;
14703
- const numerator = m * (2n * sqrtPKR * Q96$1 - PX192 - KX192);
14703
+ const numerator = m * (2n * sqrtPKR * Q96$2 - PX192 - KX192);
14704
14704
  const denominator = rX192 - Q192$3;
14705
14705
  v = divTrunc(numerator, denominator);
14706
14706
  }
@@ -14808,7 +14808,7 @@ function getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick,
14808
14808
  const sqrtK = tickToSqrtPriceX96(qStrikeTick);
14809
14809
  const sqrtPm = tickToSqrtPriceX96(qMintTick);
14810
14810
  const rX192 = sqrtR * sqrtR;
14811
- const sqrtKPmX96 = sqrtK * Q96$1 / sqrtPm;
14811
+ const sqrtKPmX96 = sqrtK * Q96$2 / sqrtPm;
14812
14812
  const diff = sqrtR - sqrtKPmX96;
14813
14813
  const diffSqX192 = diff * diff;
14814
14814
  return divTrunc(m * diffSqX192, rX192 - Q192$3);
@@ -14867,7 +14867,7 @@ function getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex
14867
14867
  const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick);
14868
14868
  const sqrtR = tickToSqrtPriceX96(halfWidthTick);
14869
14869
  const rX192 = sqrtR * sqrtR;
14870
- const numerator = m * sqrtKPR * Q96$1;
14870
+ const numerator = m * sqrtKPR * Q96$2;
14871
14871
  const denominator = 2n * (rX192 - Q192$3);
14872
14872
  return divTrunc(numerator, denominator);
14873
14873
  }
@@ -22914,6 +22914,7 @@ async function fetchV3BlockSnapshot(client, poolAddress, blockNumber, uniqueTick
22914
22914
  for (let i = 0; i < uniqueTicks.length; i++) {
22915
22915
  const tickResult = results[3 + i];
22916
22916
  tickData.set(uniqueTicks[i], {
22917
+ liquidityGross: tickResult[0],
22917
22918
  feeGrowthOutside0: tickResult[2],
22918
22919
  feeGrowthOutside1: tickResult[3]
22919
22920
  });
@@ -22959,6 +22960,7 @@ async function fetchV4BlockSnapshot(client, stateViewAddress, poolId, blockNumbe
22959
22960
  for (let i = 0; i < uniqueTicks.length; i++) {
22960
22961
  const tickResult = results[2 + i];
22961
22962
  tickData.set(uniqueTicks[i], {
22963
+ liquidityGross: tickResult[0],
22962
22964
  feeGrowthOutside0: tickResult[2],
22963
22965
  feeGrowthOutside1: tickResult[3]
22964
22966
  });
@@ -26213,7 +26215,7 @@ async function forceExerciseAndWait(params) {
26213
26215
  //#endregion
26214
26216
  //#region src/panoptic/v2/writes/protectedSettle.ts
26215
26217
  const POOL_ID_MASK = (1n << 64n) - 1n;
26216
- const Q96 = 1n << 96n;
26218
+ const Q96$1 = 1n << 96n;
26217
26219
  const MAX_UINT128$1 = (1n << 128n) - 1n;
26218
26220
  const SETTLE_LIMITS = [
26219
26221
  -887272n,
@@ -26233,7 +26235,7 @@ function minimumPokeSize(legs, tickSpacing) {
26233
26235
  const sqrtLower = tickToSqrtPriceX96(lowerTick);
26234
26236
  const sqrtUpper = tickToSqrtPriceX96(upperTick);
26235
26237
  const delta = sqrtUpper - sqrtLower;
26236
- const liquidityFactor = leg.asset === 0n ? sqrtLower * sqrtUpper / Q96 : Q96;
26238
+ const liquidityFactor = leg.asset === 0n ? sqrtLower * sqrtUpper / Q96$1 : Q96$1;
26237
26239
  if (liquidityFactor === 0n) return void 0;
26238
26240
  const requiredAmount = ceilDiv$1(delta, liquidityFactor);
26239
26241
  const legSize = ceilDiv$1(requiredAmount, leg.optionRatio);
@@ -31521,15 +31523,29 @@ var _4663 = {
31521
31523
  "panoptic": {
31522
31524
  "pool": {
31523
31525
  "version": "v4",
31524
- "panopticPool": "0x00000000989bcb6f24af4a1Ab2A6d6a31c98A58E",
31525
- "collateralTracker0": "0x49eaAC32A7CD4B8fB2209a12859a95E0b20aB0e5",
31526
- "collateralTracker1": "0x670C44a0FC35dbC410498e47A6290a1C3196d191"
31526
+ "panopticPool": "0x000000000c21b38c54AcA7c7145Df01ff09d69Bb",
31527
+ "collateralTracker0": "0xDc508622CD7e3850c8240e88c10361Cf493465b6",
31528
+ "collateralTracker1": "0x9212d804953bAf89C24ceFa6545aA293bA08a876"
31529
+ },
31530
+ "additionalPools": {
31531
+ "spyUsdg30bpsV4": {
31532
+ "version": "v4",
31533
+ "panopticPool": "0x00000000989bcb6f24af4a1Ab2A6d6a31c98A58E",
31534
+ "collateralTracker0": "0x49eaAC32A7CD4B8fB2209a12859a95E0b20aB0e5",
31535
+ "collateralTracker1": "0x670C44a0FC35dbC410498e47A6290a1C3196d191"
31536
+ },
31537
+ "spyUsdg5bpsV4": {
31538
+ "version": "v4",
31539
+ "panopticPool": "0x000000000c21b38c54AcA7c7145Df01ff09d69Bb",
31540
+ "collateralTracker0": "0xDc508622CD7e3850c8240e88c10361Cf493465b6",
31541
+ "collateralTracker1": "0x9212d804953bAf89C24ceFa6545aA293bA08a876"
31542
+ }
31527
31543
  },
31528
31544
  "v2": {
31529
31545
  "semiFungiblePositionManagerV4": "0x00000000000005C3287f136Ef5AF56c68Ea6849f",
31530
31546
  "semiFungiblePositionManagerV3": "0x00000000000005E4693aDc8Ec0f12D686f728198",
31531
31547
  "builderFactory": "0x0000000000000a3D22E158417AA639D7F71b0FF7",
31532
- "riskEngine": "0x000000000000075e29cdaa9cb640a69e148ca7da",
31548
+ "riskEngine": "0x0000000000000fE1E261f66ce2F44def4F5Ae0CB",
31533
31549
  "panopticPoolImplementation": "0x000000000000135429F0DaCaB61639Bf6a63EbbC",
31534
31550
  "collateralTrackerImplementation": "0x0000000000001d9c38CA405A2e04420865A08A33",
31535
31551
  "panopticFactoryV4": "0x0000000000000c51d0f8cf4bd9adE7191372a625",
@@ -31545,13 +31561,29 @@ var _4663 = {
31545
31561
  "0x0000000000000fe1e261f66ce2f44def4f5ae0cb",
31546
31562
  "0x0000000000000f3fb82469581A74776178E76Ca4"
31547
31563
  ],
31548
- "markets": { "spyUsdg": {
31549
- "currency0": "0x117cc2133c37B721F49dE2A7a74833232B3B4C0C",
31550
- "currency1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
31551
- "fee": 3e3,
31552
- "tickSpacing": 60,
31553
- "poolId": "0xfe2a80bb5618fd14984b92ca6d45bf5ba67443ddb1435e28b2e48df2fc1526cd"
31554
- } },
31564
+ "markets": {
31565
+ "spyUsdg": {
31566
+ "currency0": "0x117cc2133c37B721F49dE2A7a74833232B3B4C0C",
31567
+ "currency1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
31568
+ "fee": 500,
31569
+ "tickSpacing": 5,
31570
+ "poolId": "0xe5923c8a8be481ec89a2ca784a2bbfa4235de6d88f92260fd66b660c4babf907"
31571
+ },
31572
+ "spyUsdg30bps": {
31573
+ "currency0": "0x117cc2133c37B721F49dE2A7a74833232B3B4C0C",
31574
+ "currency1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
31575
+ "fee": 3e3,
31576
+ "tickSpacing": 60,
31577
+ "poolId": "0xfe2a80bb5618fd14984b92ca6d45bf5ba67443ddb1435e28b2e48df2fc1526cd"
31578
+ },
31579
+ "spyUsdg5bps": {
31580
+ "currency0": "0x117cc2133c37B721F49dE2A7a74833232B3B4C0C",
31581
+ "currency1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
31582
+ "fee": 500,
31583
+ "tickSpacing": 5,
31584
+ "poolId": "0xe5923c8a8be481ec89a2ca784a2bbfa4235de6d88f92260fd66b660c4babf907"
31585
+ }
31586
+ },
31555
31587
  "subgraphs": {
31556
31588
  "hypovault": "https://api.goldsky.com/api/public/project_cl9gc21q105380hxuh8ks53k3/subgraphs/hypovault-subgraph-robinhood/prod/gn",
31557
31589
  "panoptic": "https://api.goldsky.com/api/public/project_cl9gc21q105380hxuh8ks53k3/subgraphs/panoptic-subgraph-robinhood/v2_prod/gn"
@@ -31719,6 +31751,10 @@ function getSpyUsdgMarket(deployment) {
31719
31751
  if (market === void 0) throw new Error(`Missing SPY/USDG market for chainId ${deployment.chainId}`);
31720
31752
  return market;
31721
31753
  }
31754
+ function requireDeploymentValue(value, label) {
31755
+ if (value === void 0) throw new Error(`Missing deployment value: ${label}`);
31756
+ return value;
31757
+ }
31722
31758
  const MAINNET_DEPLOYMENT = CHAIN_DEPLOYMENTS[MAINNET_CHAIN_ID];
31723
31759
  const MAINNET_ETH_USDC_5BPS_V3_PANOPTIC_POOL_ADDRESSES = MAINNET_DEPLOYMENT.panoptic.additionalPools?.ethUsdc5bpsV3;
31724
31760
  const MAINNET_PANOPTIC_V2_ADDRESSES = MAINNET_DEPLOYMENT.panoptic.v2;
@@ -31747,9 +31783,13 @@ const ROBINHOOD_HYPOVAULT_ADDRESSES = ROBINHOOD_DEPLOYMENT.hypovault.vaults;
31747
31783
  const ROBINHOOD_HYPOVAULT_MANAGER_ADDRESSES = ROBINHOOD_DEPLOYMENT.hypovault.managers;
31748
31784
  const ROBINHOOD_HYPOVAULT_MANAGER_TURNKEY_SIGNERS = ROBINHOOD_DEPLOYMENT.hypovault.turnkeySigners;
31749
31785
  const ROBINHOOD_PANOPTIC_POOL_ADDRESSES = ROBINHOOD_DEPLOYMENT.panoptic.pool;
31786
+ const ROBINHOOD_SPY_USDG_30BPS_PANOPTIC_POOL_ADDRESSES = requireDeploymentValue(ROBINHOOD_DEPLOYMENT.panoptic.additionalPools?.spyUsdg30bpsV4, "Robinhood SPY/USDG 30bps Panoptic pool");
31787
+ const ROBINHOOD_SPY_USDG_5BPS_PANOPTIC_POOL_ADDRESSES = requireDeploymentValue(ROBINHOOD_DEPLOYMENT.panoptic.additionalPools?.spyUsdg5bpsV4, "Robinhood SPY/USDG 5bps Panoptic pool");
31750
31788
  const ROBINHOOD_PANOPTIC_V2_ADDRESSES = ROBINHOOD_DEPLOYMENT.panoptic.v2;
31751
31789
  const ROBINHOOD_RISK_ENGINES = ROBINHOOD_DEPLOYMENT.riskEngines;
31752
31790
  const ROBINHOOD_SPY_USDG_MARKET = getSpyUsdgMarket(ROBINHOOD_DEPLOYMENT);
31791
+ const ROBINHOOD_SPY_USDG_30BPS_MARKET = requireDeploymentValue(ROBINHOOD_DEPLOYMENT.markets.spyUsdg30bps, "Robinhood SPY/USDG 30bps market");
31792
+ const ROBINHOOD_SPY_USDG_5BPS_MARKET = requireDeploymentValue(ROBINHOOD_DEPLOYMENT.markets.spyUsdg5bps, "Robinhood SPY/USDG 5bps market");
31753
31793
 
31754
31794
  //#endregion
31755
31795
  //#region ../deployments/src/vaultDisplayNames.js
@@ -31840,6 +31880,131 @@ function marketRiskFromValues({ lower, current, upper }) {
31840
31880
  };
31841
31881
  }
31842
31882
 
31883
+ //#endregion
31884
+ //#region src/panoptic/v2/greeks/positionVolatility.ts
31885
+ const Precision = Decimal.clone({ precision: 80 });
31886
+ const Q96 = 1n << 96n;
31887
+ const YEAR_SECONDS = new Precision(31536e3);
31888
+ /** The premium-free position curve, expressed in one quote token's human units. */
31889
+ function preparePositionGamma({ tokenId, positionSize, quoteIsToken0, quoteDecimals }) {
31890
+ if (positionSize <= 0n || positionSize >= 1n << 128n) throw new RangeError("Invalid position size");
31891
+ if (!Number.isInteger(quoteDecimals) || quoteDecimals < 0 || quoteDecimals > 255) throw new RangeError("Invalid quote decimals");
31892
+ const decoded = decodeTokenId(tokenId);
31893
+ const chunks = decoded.legs.flatMap((leg) => {
31894
+ if (leg.width === 0n) return [];
31895
+ const width = leg.width * decoded.tickSpacing;
31896
+ const lowerTick = leg.strike - width / 2n;
31897
+ const upperTick = leg.strike + (width + 1n) / 2n;
31898
+ if (lowerTick < -887272n || upperTick > 887272n || lowerTick >= upperTick) throw new RangeError("Invalid position range");
31899
+ const lower = tickToSqrtPriceX96(lowerTick);
31900
+ const upper = tickToSqrtPriceX96(upperTick);
31901
+ const amount = positionSize * leg.optionRatio;
31902
+ const liquidity = leg.asset === 0n ? amount * (lower * upper / Q96) / (upper - lower) : amount * Q96 / (upper - lower);
31903
+ if (liquidity >= 1n << 128n) throw new RangeError("Liquidity exceeds uint128");
31904
+ return [{
31905
+ lowerTick: Number(lowerTick),
31906
+ upperTick: Number(upperTick),
31907
+ liquidity,
31908
+ isLong: leg.isLong
31909
+ }];
31910
+ });
31911
+ const scale = new Precision(10).pow(quoteDecimals);
31912
+ const atTick = (tick) => {
31913
+ const netLiquidity = chunks.reduce((sum$1, chunk) => tick >= BigInt(chunk.lowerTick) && tick < BigInt(chunk.upperTick) ? sum$1 + (chunk.isLong ? -chunk.liquidity : chunk.liquidity) : sum$1, 0n);
31914
+ const sqrt = new Precision(tickToSqrtPriceX96(tick).toString()).div(Q96.toString());
31915
+ const gamma = new Precision(netLiquidity.toString()).neg().div(2).div(scale);
31916
+ return quoteIsToken0 ? gamma.div(sqrt) : gamma.mul(sqrt);
31917
+ };
31918
+ const inRange = (low, high) => {
31919
+ if (low > high) throw new RangeError("Invalid candle range");
31920
+ const ticks = new Set([low, high]);
31921
+ for (const chunk of chunks) for (const boundary of [BigInt(chunk.lowerTick), BigInt(chunk.upperTick)]) {
31922
+ if (boundary >= low && boundary <= high) ticks.add(boundary);
31923
+ if (boundary - 1n >= low && boundary - 1n <= high) ticks.add(boundary - 1n);
31924
+ }
31925
+ return [...ticks].map(atTick);
31926
+ };
31927
+ return {
31928
+ chunks,
31929
+ atTick,
31930
+ inRange
31931
+ };
31932
+ }
31933
+ /** Historical whole-position diagnostics, with signs retained independently of eligibility. */
31934
+ function calculatePositionVolatilityMetrics({ observations, netPremium, baseFees, quoteDecimals }) {
31935
+ if (observations.length < 2) throw new RangeError("At least two price observations are required");
31936
+ if (!Number.isInteger(quoteDecimals) || quoteDecimals < 0 || quoteDecimals > 255) throw new RangeError("Invalid quote decimals");
31937
+ const points = observations.map((point) => ({
31938
+ ...point,
31939
+ price: new Precision(point.price),
31940
+ gamma: new Precision(point.gamma),
31941
+ rangeGammas: (point.rangeGammas ?? []).map((gamma) => new Precision(gamma))
31942
+ }));
31943
+ for (const point of points) if (!point.price.isFinite() || point.price.lte(0) || !point.gamma.isFinite() || point.rangeGammas.some((gamma) => !gamma.isFinite())) throw new RangeError("Invalid price or gamma observation");
31944
+ const quantum = new Precision(10).pow(-quoteDecimals);
31945
+ const gammas = points.flatMap((point) => [point.gamma, ...point.rangeGammas]);
31946
+ const peak = gammas.reduce((max, gamma) => Precision.max(max, gamma.abs()), new Precision(0));
31947
+ const tolerance = Precision.max(quantum, peak.mul("1e-12"));
31948
+ const positive = gammas.some((gamma) => gamma.gt(tolerance));
31949
+ const negative = gammas.some((gamma) => gamma.lt(tolerance.neg()));
31950
+ const gammaSign = positive && negative ? "changing" : positive ? "positive" : negative ? "negative" : "zero";
31951
+ let exposure = new Precision(0);
31952
+ let signedConvexity = new Precision(0);
31953
+ let absoluteConvexity = new Precision(0);
31954
+ let years = new Precision(0);
31955
+ for (let i = 1; i < points.length; i++) {
31956
+ const previous = points[i - 1];
31957
+ const point = points[i];
31958
+ const seconds = point.timestamp - previous.timestamp;
31959
+ if (seconds <= 0n) throw new RangeError("Observations must have increasing timestamps");
31960
+ const elapsed = new Precision(seconds.toString()).div(YEAR_SECONDS);
31961
+ const squaredReturn = point.price.div(previous.price).ln().pow(2);
31962
+ exposure = exposure.plus(previous.gamma.abs().mul(elapsed));
31963
+ signedConvexity = signedConvexity.plus(previous.gamma.mul(squaredReturn).div(2));
31964
+ absoluteConvexity = absoluteConvexity.plus(previous.gamma.abs().mul(squaredReturn).div(2));
31965
+ years = years.plus(elapsed);
31966
+ }
31967
+ const sufficientExposure = exposure.gt(tolerance.mul(years).mul(100));
31968
+ const premium = netPremium === null ? null : new Precision(netPremium);
31969
+ const fees = baseFees == null ? null : new Precision(baseFees);
31970
+ if (premium !== null && !premium.isFinite() || fees !== null && !fees.isFinite()) throw new RangeError("Invalid accounting amount");
31971
+ const consistent = (amount) => gammaSign === "positive" ? amount.lte(quantum) : gammaSign === "negative" && amount.gte(quantum.neg());
31972
+ const reason = !sufficientExposure ? "insufficient-exposure" : gammaSign === "changing" ? "changing-sign" : premium === null ? "premium-unavailable" : !consistent(premium) ? "inconsistent-premium-direction" : null;
31973
+ const equivalent = (amount) => amount.abs().mul(2).div(exposure).sqrt().toString();
31974
+ const coverage = (amount) => absoluteConvexity.gt(quantum) ? amount.abs().div(absoluteConvexity).toString() : null;
31975
+ const eligibleFees = sufficientExposure && fees !== null && consistent(fees);
31976
+ return {
31977
+ gammaSign,
31978
+ exposure: exposure.toString(),
31979
+ signedConvexity: signedConvexity.toString(),
31980
+ absoluteConvexity: absoluteConvexity.toString(),
31981
+ netPremium: premium?.toString() ?? null,
31982
+ estimatedHedgedResult: premium?.plus(signedConvexity).toString() ?? null,
31983
+ weightedRealizedVolatility: sufficientExposure ? equivalent(absoluteConvexity) : null,
31984
+ premiumEquivalentVolatility: reason === null && premium !== null ? equivalent(premium) : null,
31985
+ premiumToConvexity: reason === null && premium !== null ? coverage(premium) : null,
31986
+ baseFees: fees?.toString() ?? null,
31987
+ feeEquivalentVolatility: eligibleFees ? equivalent(fees) : null,
31988
+ feeToConvexity: eligibleFees ? coverage(fees) : null,
31989
+ comparisonReason: reason
31990
+ };
31991
+ }
31992
+ /** Quote-value signed cumulative token increments, excluding revaluation of previous accrual. */
31993
+ function valuePositionAccrual({ snapshots, quoteIsToken0, quoteDecimals }) {
31994
+ let previous0 = 0n;
31995
+ let previous1 = 0n;
31996
+ let total = new Precision(0);
31997
+ for (const snapshot of snapshots) {
31998
+ const amount0 = new Precision((snapshot.token0 - previous0).toString());
31999
+ const amount1 = new Precision((snapshot.token1 - previous1).toString());
32000
+ const price = new Precision("1.0001").pow(snapshot.tick.toString());
32001
+ total = total.plus(quoteIsToken0 ? amount0.plus(amount1.div(price)) : amount1.plus(amount0.mul(price)));
32002
+ previous0 = snapshot.token0;
32003
+ previous1 = snapshot.token1;
32004
+ }
32005
+ return total.div(new Precision(10).pow(quoteDecimals));
32006
+ }
32007
+
31843
32008
  //#endregion
31844
32009
  //#region src/panoptic/v2/reads/collateralCurve.ts
31845
32010
  /** Native-token margin inputs, independent of the tick used to display the curve. */
@@ -32033,5 +32198,220 @@ function preparePositionValueCurve(curve) {
32033
32198
  }
32034
32199
 
32035
32200
  //#endregion
32036
- export { AccountInsolventError, AlreadyInitializedError, BORROW_INDEX_BITS, BPS_DENOMINATOR, BPS_SCALE, BatchValidationError, BelowMinimumRedemptionError, CastingError, ChunkHasZeroLiquidityError, ChunkLimitError, CrossPoolError, DEFAULT_MAX_SPREAD, DEFAULT_MINT_BUFFER, DEFAULT_MIN_SWAP_RATIO_BPS, DEFAULT_RECONNECT_CONFIG, DEFAULT_VEGOID, DepositTooLargeError, DuplicateTokenIdError, EffectiveLiquidityAboveThresholdError, ExceedsMaximumRedemptionError, InputListFailError, InsufficientCreditLiquidityError, InvalidBuilderCodeError, InvalidHistoryRangeError, InvalidTickBoundError, InvalidTickError, InvalidTokenIdParameterError, InvalidUniswapCallbackError, LEG_BITS, LEG_LIMITS, LEG_MASKS, LengthMismatchError, LiquidityTooHighError, LoanSlotExhaustedError, MARKET_EPOCH_BITS, MARKET_EPOCH_SHIFT, MARKET_INDICATOR_PERIODS, MAX_TICK, MAX_TRACKED_CHUNKS, MINT_BUFFER, MINT_BUFFER_DENOMINATOR, MIN_TICK, MaxRetriesExceededError, MissingPositionIdsError, NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, NetLiquidityZeroError, NetworkMismatchError, NoLegsExercisableError, NotALongLegError, NotBuilderError, NotEnoughLiquidityInChunkError, NotEnoughTokensError, NotGuardianError, NotMarginCalledError, NotPanopticPoolError, ORACLE_EPOCH_SECONDS, OracleRateLimitedError, PanopticError, PanopticHelperNotDeployedError, PanopticValidationError, PoolNotInitializedError, PositionCountNotZeroError, PositionNotOwnedError, PositionSnapshotNotFoundError, PositionTooLargeError, PriceBoundFailError, PriceImpactTooLargeError, ProviderLagError, RATE_AT_TARGET_BITS, REORG_DEPTH, REQUIRED_BASE_ERROR_SENTINEL, ReentrancyError, RpcError, RpcResponseError, SCHEMA_VERSION, SECONDS_PER_YEAR, STANDARD_TICK_WIDTHS, STORAGE_PREFIX, STRIKE_LADDER_TARGET_STRIKES, SafeModeError, StaleDataError, StaleOracleError, SwapTokenMismatchError, SyncTimeoutError, TOKEN_ID_BITS, TokenIdHasZeroLegsError, TooManyLegsOpenError, TransferFailedError, UNREALIZED_INTEREST_BITS, UTILIZATION_DENOMINATOR, UnauthorizedUniswapCallbackError, UnderOverFlowError, UnhealthyPoolError, UnsafePremiumSettlementError, VARIANCE_RATIO_LAG, WAD, WrongPoolIdError, WrongUniswapPoolError, ZERO_COLLATERAL, ZERO_VALUATION, ZeroAddressError, ZeroCollateralRequirementError, addLegToTokenId, addPendingPosition, addTrackedChunks, annualizePerSecondRateWad, applyMintBuffer, applyMintBufferPerToken, apportion, approve, approveAndWait, approvePool, assertCanBurn, assertCanForceExercise, assertCanLiquidate, assertCanMint, assertFresh, assertHealthy, assertLpPositionFunded, assertTradeable, borrow, borrowAndWait, buildBatchDispatchArgs, buildCreditSwapCall, buildCreditWrappedDispatch, buildOpenPositionCalldata, buildProtectedSettleDispatch, buildProtectedSettlePlan, buildSettleSequenceCalls, buildSfpmSwapCalldata, buildSfpmSwapPlan, buildTemporaryLoanRecoveryDispatch, buildTokenShortfallRecoveryDispatch, buildUniqueCredit, buildUniqueLoan, buildUniqueWidthZeroLeg, calculateAccountGreeksPure, calculateMarketIndicator, calculatePortfolioDelta, calculatePortfolioGamma, calculatePortfolioGreeks, calculatePortfolioValue, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionDeltaWithSwap, calculatePositionGamma, calculatePositionGreeks, calculatePositionValue, calculatePositionValues, calculateResyncBlock, calculateSpreadWad, calculateVarianceProfile, cancelTransaction, checkApproval, checkCollateralAcrossTicks, classifyStrategyGroups, classifyStrike, cleanupStalePendingPositions, clearCheckpoint, clearPendingPositions, clearTrackedChunks, clearTrackedPositions, clearTradeHistory, closePosition, closePositionAndWait, collateralCurveTicks, collateralRuleKindFor, collateralTrackerV2Abi, computeV4PoolId, confirmPendingPosition, convertToAssets, convertToShares, countLegs, createEventPoller, createEventSubscription, createFileStorage, createFlowNeutralTokenId, createMemoryStorage, createNonceManager, createPoolFormatters, createTokenIdBuilder, decodeAllDispatchCalldata, decodeAllLegs, decodeDispatchCalldata, decodeLeftRightSigned, decodeLeftRightUnsigned, decodeLeg, decodeOraclePack, decodeOracleRiskParameters, decodeOracleTiming, decodePanopticTokenURI, decodePoolId, decodeTickSpacing, decodeTokenId, decodeVegoid, deployNewPool, deployNewPoolAndWait, deposit, depositAndWait, deriveSupplyRatePerSecWad, deriveUniqueTokenId, detectReorg, diagnoseOracleSafeMode, dispatch, dispatchAndWait, emptyLiquidateParams, encodeLeg, encodePoolId, encodePoolKeyBytes, encodeV3PoolKeyBytes, encodeV4PoolId, ensureSfpmV3PoolInitialized, estimateBlockNumbers, estimateCollateralBreakdown, estimateCollateralRequired, executeBatchDispatch, executeBatchDispatchAndWait, executeSettleSequence, executeSettleSequenceAndWait, failPendingPosition, feeGrowthInsideX128, feesFromFeeGrowthDelta, fetchPoolId, fetchSfpmV3PoolId, fetchUniswapFeeData, forceExercise, forceExerciseAndWait, formatBlockNumber, formatBps, formatCompact, formatDatetime, formatDuration, formatDurationSeconds, formatFeeTier, formatGas, formatGwei, formatPerSecondRateWadAsAprPct, formatPerSecondRateWadAsApyPct, formatPoolIdHex, formatPriceRange, formatRateWad, formatRatioPercent, formatTick, formatTickRange, formatTimestamp, formatTimestampLocale, formatTokenAmount, formatTokenAmountSigned, formatTokenDelta, formatTokenFlow, formatTokenIdHex, formatTokenIdShort, formatTxHash, formatUtilization, formatWad, formatWadPercent, formatWadSigned, formatWei, generateOverlappingTokenIds, getAccountBuyingPower, getAccountCollateral, getAccountGreeks, getAccountHistory, getAccountPremia, getAccountSummaryBasic, getAccountSummaryRisk, getAssetIndex, getBlockMeta, getChainDeployment, getChunkLiquidities, getChunkSpreads, getClosedPositions, getClosedPositionsKey, getCollateralAddresses, getCollateralCurve, getCollateralCurveInputs, getCollateralData, getCollateralRequiredBase, getCollateralSharePrices, getCollateralTotalAssetsBatch, getCurrentRates, getDeltaHedgeParams, getEnforcedTickLimits, getExecutableLpMaxSize, getFactoryConstructMetadata, getFactoryOwnerOf, getFactoryTokenURI, getForfeitablePremium, getGuardianUnlockState, getHedgeLimits, getInterestState, getIrmCurrent, getIrmCurve, getItmAmounts, getLegDelta, getLegDeltaInVaultFrame, getLegGamma, getLegNetValueWidth0, getLegValue, getLiquidationPrices, getMarginBuffer, getMaxPositionSize, getMaxRedeem, getMaxWithdrawable, getNativeTokenPrice, getNetLiquidationValue, getNetLiquidationValues, getNotEnoughTokensError, getOpenPositionIds, getOpenPositionPreview, getOracleRiskParameters, getOracleState, getPanopticPoolAddress, getPanopticPoolFromPoolId, getPendingPositions, getPendingPositionsKey, getPool, getPoolCurrentTick, getPoolDeploymentBlock, getPoolDisplayId, getPoolLiquidities, getPoolMetaKey, getPoolMetadata, getPoolPrefix, getPortfolioValue, getPosition, getPositionChunkData, getPositionDeltaMetrics, getPositionEnrichmentData, getPositionGreeks, getPositionMetaKey, getPositionValueCurve, getPositions, getPositionsKey, getPositionsWithPremia, getPriceHistory, getPricesAtTick, getRealizedPnL, getRequiredCreditForITM, getRiskParameters, getSafeMode, getSchemaVersionKey, getSimpleLoanTokenIndex, getStreamiaHistory, getSyncCheckpointKey, getSyncStatus, getTickSpacing, getTokenListId, getTrackedChunks, getTrackedChunksKey, getTrackedPositionIds, getTradeHistory, getUniswapFeeHistory, getUniswapV3LpPositionState, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4LpPositionState, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, getUtilization, hasLoanOrCredit, hasLongLeg, interpolateBlocks, isCall, isCredit, isCreditLeg, isDefinedRisk, isGasError, isInputListFailError, isLiquidatable, isLoan, isLoanLeg, isNonceError, isPanopticErrorType, isPositionTracked, isRetryableRpcError, isShortOnly, isSpread, isSupportedChain, isolateGroupTokenId, jsonSerializer, ladderStrikeSequence, liquidate, liquidateAndWait, loadCheckpoint, logReturns, marketPnlInQuote, marketRiskFromValues, marketScenario, minePoolAddress, mint, mintAndWait, mintableAfterBuffer, multicallRead, netLiquidationValueInQuote, openPosition, openPositionAndWait, optimizeTokenIdRiskPartners, oracleEpochAt, orderListForSettle, packMarketState, panopticLiquidatorAbi, panopticPoolV2Abi, panopticQueryAbi, parseBps, parseCollateralLog, parsePanopticError, parsePoolLog, parseTokenAmount, parseTokenListId, parseWad, planDeriveStrategy, pokeOracle, pokeOracleAndWait, positionValueKey, positionValueTicks, prepareIndicatorCandles, preparePositionValue, preparePositionValueCurve, previewBorrow, previewDeposit, previewMint, previewRedeem, previewRepay, previewUnwrap, previewWithdraw, previewWrap, priceToTick, publicBroadcaster, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, quoteV3ExactIn, ratePerSecWadToAprPct, realizedBeta, reconstructFromEvents, recoverSnapshot, recoverSnapshotFromTx, redeem, redeemAndWait, removeTrackedChunks, repay, repayAndWait, requireChainDeployment, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveTokenIndex, resolveUniswapV4PoolKey, riskEngineAbi, rollPosition, rollPositionAndWait, roundToTickSpacing, saveCheckpoint, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, selectDispatchForAccount, settleAccumulatedPremia, settleAccumulatedPremiaAndWait, settlePremiumFrom, settlePremiumFromAndWait, simulateBatchDispatch, simulateClosePosition, simulateDeployNewPool, simulateDeposit, simulateDispatch, simulateForceExercise, simulateLiquidate, simulateOpenPosition, simulateSFPMBurn, simulateSFPMMint, simulateSettle, simulateSettlePremiumBatch, simulateSettlePremiumFrom, simulateSettleSequence, simulateSwapExactIn, simulateSwapExactOut, simulateWithTokenFlow, simulateWithdraw, slippageBpsToTickDistance, smartRepay, smartRepayAndWait, speedUpTransaction, splitTokenIdByTimescale, sqrtPriceX96ToPriceDecimalScaled, sqrtPriceX96ToTick, supply, supplyAndWait, swapExactIn, swapExactInAndWait, swapExactOut, swapExactOutAndWait, syncPositions, tickLimits, tickToPrice, tickToPriceDecimalScaled, tickToSqrtPriceX96, toVaultFrameAtTick, truncateAddress, unsupply, unsupplyAndWait, unwrapWeth, unwrapWethAndWait, unwrapXstock, unwrapXstockAndWait, utilizationBpsToWad, utilizationPctToWad, validateBatch, validateBuilderCode, validatePoolId, verifyBlockContinuity, watchEvents, wethWrapAbi, withdraw, withdrawAndWait, withdrawWithPositions, withdrawWithPositionsAndWait, wrapEth, wrapEthAndWait, wrapXstock, wrapXstockAndWait, xstockWrapperAbi };
32201
+ //#region src/panoptic/v2/reads/positionVolatilityHistory.ts
32202
+ const signedSlot = (value) => BigInt.asIntN(128, value);
32203
+ const unpack = (value) => ({
32204
+ token0: signedSlot(value),
32205
+ token1: signedSlot(value >> 128n)
32206
+ });
32207
+ /** RPC accounting for exactly one mint lifecycle; candle prices are supplied by the application. */
32208
+ async function getPositionVolatilityHistory({ client, poolAddress, account, tokenId, mintBlock, endBlock, poolConfig, includeBaseFees = false }) {
32209
+ if (mintBlock <= 0n || endBlock <= mintBlock) throw new RangeError("Insufficient lifecycle history");
32210
+ const [mints, burns] = await Promise.all([client.getContractEvents({
32211
+ address: poolAddress,
32212
+ abi: panopticPoolV2Abi,
32213
+ eventName: "OptionMinted",
32214
+ args: {
32215
+ recipient: account,
32216
+ tokenId
32217
+ },
32218
+ fromBlock: mintBlock,
32219
+ toBlock: mintBlock,
32220
+ strict: true
32221
+ }), client.getContractEvents({
32222
+ address: poolAddress,
32223
+ abi: panopticPoolV2Abi,
32224
+ eventName: "OptionBurnt",
32225
+ args: {
32226
+ recipient: account,
32227
+ tokenId
32228
+ },
32229
+ fromBlock: mintBlock,
32230
+ toBlock: endBlock,
32231
+ strict: true
32232
+ })]);
32233
+ const mint$1 = mints[0];
32234
+ if (mints.length !== 1 || !mint$1) throw new Error("Opening event is missing or ambiguous");
32235
+ const balance = decodePositionBalance$1(mint$1.args.balanceData);
32236
+ const close = burns.filter((burn) => burn.blockNumber > mintBlock || burn.logIndex > mint$1.logIndex).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1)[0];
32237
+ const finalBlock = close?.blockNumber ?? endBlock;
32238
+ if (finalBlock <= mintBlock) throw new Error("Intrablock lifecycle cannot be reconstructed");
32239
+ if (close && close.args.positionSize !== balance.positionSize) throw new Error("Position size changed");
32240
+ const [start, end, boundaryPrices] = await Promise.all([
32241
+ getBlockMeta({
32242
+ client,
32243
+ blockNumber: mintBlock
32244
+ }),
32245
+ getBlockMeta({
32246
+ client,
32247
+ blockNumber: finalBlock
32248
+ }),
32249
+ getPriceHistory({
32250
+ client,
32251
+ poolConfig,
32252
+ blockNumbers: [mintBlock, finalBlock]
32253
+ })
32254
+ ]);
32255
+ const openingPrice = boundaryPrices.snapshots[0];
32256
+ const endingPrice = boundaryPrices.snapshots[1];
32257
+ if (!openingPrice || !endingPrice) throw new Error("Boundary prices unavailable");
32258
+ const pointCount = Math.min(200, Math.max(2, Number((end.blockTimestamp - start.blockTimestamp) / 900n) + 2));
32259
+ const blockNumbers = [...new Set(interpolateBlocks(mintBlock, finalBlock, pointCount))];
32260
+ const metadata = [];
32261
+ for (let i = 0; i < blockNumbers.length; i += 16) metadata.push(...await Promise.all(blockNumbers.slice(i, i + 16).map((blockNumber) => getBlockMeta({
32262
+ client,
32263
+ blockNumber
32264
+ }))));
32265
+ const timestamps = new Map(metadata.map((meta) => [meta.blockNumber, meta.blockTimestamp]));
32266
+ const chunks = preparePositionGamma({
32267
+ tokenId,
32268
+ positionSize: balance.positionSize,
32269
+ quoteIsToken0: false,
32270
+ quoteDecimals: 0
32271
+ }).chunks.filter((chunk) => chunk.liquidity > 0n);
32272
+ let premiumError = null;
32273
+ let feeError = includeBaseFees ? null : "Base fee history was not requested";
32274
+ let premium = null;
32275
+ let fees = null;
32276
+ try {
32277
+ const settlementLogs = await client.getContractEvents({
32278
+ address: poolAddress,
32279
+ abi: panopticPoolV2Abi,
32280
+ eventName: "PremiumSettled",
32281
+ args: {
32282
+ user: account,
32283
+ tokenId
32284
+ },
32285
+ fromBlock: mintBlock,
32286
+ toBlock: finalBlock,
32287
+ strict: true
32288
+ });
32289
+ const settled = [];
32290
+ const seen = new Set();
32291
+ for (const log of settlementLogs) {
32292
+ if (log.blockNumber === mintBlock && log.logIndex <= mint$1.logIndex) continue;
32293
+ if (close && log.blockNumber === finalBlock && log.logIndex >= close.logIndex) continue;
32294
+ const key = `${log.transactionHash}:${log.logIndex}`;
32295
+ if (seen.has(key)) continue;
32296
+ seen.add(key);
32297
+ const amounts = unpack(log.args.settledAmounts);
32298
+ settled.push({
32299
+ blockNumber: log.blockNumber,
32300
+ settled0: amounts.token0,
32301
+ settled1: amounts.token1
32302
+ });
32303
+ }
32304
+ if (close) {
32305
+ const receipt = await client.getTransactionReceipt({ hash: close.transactionHash });
32306
+ const liquidations = parseEventLogs({
32307
+ abi: panopticPoolV2Abi,
32308
+ logs: receipt.logs.filter((log) => log.address.toLowerCase() === poolAddress.toLowerCase()),
32309
+ eventName: "AccountLiquidated"
32310
+ });
32311
+ if (liquidations.some((event) => event.args.liquidatee.toLowerCase() === account.toLowerCase())) throw new Error("Liquidation premium requires haircut reconciliation");
32312
+ for (const packed of close.args.premiaByLeg) {
32313
+ const amounts = unpack(packed);
32314
+ settled.push({
32315
+ blockNumber: finalBlock,
32316
+ settled0: amounts.token0,
32317
+ settled1: amounts.token1
32318
+ });
32319
+ }
32320
+ }
32321
+ const readableBlocks = close ? blockNumbers.filter((block) => block < finalBlock) : blockNumbers;
32322
+ premium = [];
32323
+ for (let i = 0; i < readableBlocks.length; i += 16) {
32324
+ const history = await getStreamiaHistory({
32325
+ client,
32326
+ panopticPoolAddress: poolAddress,
32327
+ account,
32328
+ tokenId,
32329
+ blockNumbers: readableBlocks.slice(i, i + 16),
32330
+ legs: [],
32331
+ poolConfig,
32332
+ includeUniswapFees: false,
32333
+ settledEvents: settled,
32334
+ _meta: end
32335
+ });
32336
+ for (const snapshot of history.snapshots) {
32337
+ const timestamp = snapshot.blockNumber === void 0 ? void 0 : timestamps.get(snapshot.blockNumber);
32338
+ if (timestamp === void 0) throw new Error("Accounting timestamp missing");
32339
+ premium.push({
32340
+ timestamp,
32341
+ ...snapshot.cumulativePanopticPremia
32342
+ });
32343
+ }
32344
+ }
32345
+ if (close) premium.push({
32346
+ timestamp: end.blockTimestamp,
32347
+ ...settled.reduce((sum$1, event) => ({
32348
+ token0: sum$1.token0 + event.settled0,
32349
+ token1: sum$1.token1 + event.settled1
32350
+ }), {
32351
+ token0: 0n,
32352
+ token1: 0n
32353
+ })
32354
+ });
32355
+ const openingAccrual = premium[0];
32356
+ if (!openingAccrual || openingAccrual.timestamp !== start.blockTimestamp) throw new Error("Opening premium snapshot missing");
32357
+ premium = premium.map((snapshot) => ({
32358
+ timestamp: snapshot.timestamp,
32359
+ token0: snapshot.token0 - openingAccrual.token0,
32360
+ token1: snapshot.token1 - openingAccrual.token1
32361
+ }));
32362
+ } catch (error) {
32363
+ premium = null;
32364
+ premiumError = error instanceof Error ? error.message : "Premium history unavailable";
32365
+ }
32366
+ if (includeBaseFees) try {
32367
+ const feeBlocks = close ? blockNumbers.filter((block) => block < finalBlock) : blockNumbers;
32368
+ const data = [];
32369
+ for (let i = 0; i < feeBlocks.length; i += 16) data.push(...await fetchUniswapFeeData(client, feeBlocks.slice(i, i + 16), chunks, poolConfig));
32370
+ let total0 = 0n;
32371
+ let total1 = 0n;
32372
+ fees = [];
32373
+ for (let i = 0; i < data.length; i++) {
32374
+ const current = data[i];
32375
+ for (const chunk of chunks) {
32376
+ if ((current.tickData.get(chunk.lowerTick)?.liquidityGross ?? 0n) === 0n || (current.tickData.get(chunk.upperTick)?.liquidityGross ?? 0n) === 0n) throw new Error("LP range was uninitialized; complete base fee history is unavailable");
32377
+ if (i === 0) continue;
32378
+ const previous = feeGrowthInsideX128(data[i - 1], chunk.lowerTick, chunk.upperTick);
32379
+ const next = feeGrowthInsideX128(current, chunk.lowerTick, chunk.upperTick);
32380
+ if (!previous || !next) throw new Error("Range fee growth missing");
32381
+ if (BigInt.asUintN(256, next.feeGrowthInside0X128 - previous.feeGrowthInside0X128) > BigInt.asUintN(256, current.feeGrowthGlobal0 - data[i - 1].feeGrowthGlobal0) || BigInt.asUintN(256, next.feeGrowthInside1X128 - previous.feeGrowthInside1X128) > BigInt.asUintN(256, current.feeGrowthGlobal1 - data[i - 1].feeGrowthGlobal1)) throw new Error("Range fee growth is inconsistent with pool fee growth");
32382
+ const sign = chunk.isLong ? -1n : 1n;
32383
+ total0 += sign * feesFromFeeGrowthDelta(next.feeGrowthInside0X128, previous.feeGrowthInside0X128, chunk.liquidity);
32384
+ total1 += sign * feesFromFeeGrowthDelta(next.feeGrowthInside1X128, previous.feeGrowthInside1X128, chunk.liquidity);
32385
+ }
32386
+ fees.push({
32387
+ timestamp: metadata[i].blockTimestamp,
32388
+ token0: total0,
32389
+ token1: total1
32390
+ });
32391
+ }
32392
+ } catch (error) {
32393
+ fees = null;
32394
+ feeError = error instanceof Error ? error.message : "Base fee history unavailable";
32395
+ }
32396
+ return {
32397
+ start,
32398
+ end,
32399
+ positionSize: balance.positionSize,
32400
+ closed: close !== void 0,
32401
+ openingTick: BigInt(openingPrice.tick),
32402
+ endingTick: BigInt(endingPrice.tick),
32403
+ premium,
32404
+ fees,
32405
+ premiumError,
32406
+ feeError,
32407
+ accountingSamples: blockNumbers.length,
32408
+ maxAccountingIntervalSeconds: metadata.slice(1).reduce((maximum, meta, index) => {
32409
+ const interval = meta.blockTimestamp - metadata[index].blockTimestamp;
32410
+ return interval > maximum ? interval : maximum;
32411
+ }, 0n)
32412
+ };
32413
+ }
32414
+
32415
+ //#endregion
32416
+ export { AccountInsolventError, AlreadyInitializedError, BORROW_INDEX_BITS, BPS_DENOMINATOR, BPS_SCALE, BatchValidationError, BelowMinimumRedemptionError, CastingError, ChunkHasZeroLiquidityError, ChunkLimitError, CrossPoolError, DEFAULT_MAX_SPREAD, DEFAULT_MINT_BUFFER, DEFAULT_MIN_SWAP_RATIO_BPS, DEFAULT_RECONNECT_CONFIG, DEFAULT_VEGOID, DepositTooLargeError, DuplicateTokenIdError, EffectiveLiquidityAboveThresholdError, ExceedsMaximumRedemptionError, InputListFailError, InsufficientCreditLiquidityError, InvalidBuilderCodeError, InvalidHistoryRangeError, InvalidTickBoundError, InvalidTickError, InvalidTokenIdParameterError, InvalidUniswapCallbackError, LEG_BITS, LEG_LIMITS, LEG_MASKS, LengthMismatchError, LiquidityTooHighError, LoanSlotExhaustedError, MARKET_EPOCH_BITS, MARKET_EPOCH_SHIFT, MARKET_INDICATOR_PERIODS, MAX_TICK, MAX_TRACKED_CHUNKS, MINT_BUFFER, MINT_BUFFER_DENOMINATOR, MIN_TICK, MaxRetriesExceededError, MissingPositionIdsError, NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, NetLiquidityZeroError, NetworkMismatchError, NoLegsExercisableError, NotALongLegError, NotBuilderError, NotEnoughLiquidityInChunkError, NotEnoughTokensError, NotGuardianError, NotMarginCalledError, NotPanopticPoolError, ORACLE_EPOCH_SECONDS, OracleRateLimitedError, PanopticError, PanopticHelperNotDeployedError, PanopticValidationError, PoolNotInitializedError, PositionCountNotZeroError, PositionNotOwnedError, PositionSnapshotNotFoundError, PositionTooLargeError, PriceBoundFailError, PriceImpactTooLargeError, ProviderLagError, RATE_AT_TARGET_BITS, REORG_DEPTH, REQUIRED_BASE_ERROR_SENTINEL, ReentrancyError, RpcError, RpcResponseError, SCHEMA_VERSION, SECONDS_PER_YEAR, STANDARD_TICK_WIDTHS, STORAGE_PREFIX, STRIKE_LADDER_TARGET_STRIKES, SafeModeError, StaleDataError, StaleOracleError, SwapTokenMismatchError, SyncTimeoutError, TOKEN_ID_BITS, TokenIdHasZeroLegsError, TooManyLegsOpenError, TransferFailedError, UNREALIZED_INTEREST_BITS, UTILIZATION_DENOMINATOR, UnauthorizedUniswapCallbackError, UnderOverFlowError, UnhealthyPoolError, UnsafePremiumSettlementError, VARIANCE_RATIO_LAG, WAD, WrongPoolIdError, WrongUniswapPoolError, ZERO_COLLATERAL, ZERO_VALUATION, ZeroAddressError, ZeroCollateralRequirementError, addLegToTokenId, addPendingPosition, addTrackedChunks, annualizePerSecondRateWad, applyMintBuffer, applyMintBufferPerToken, apportion, approve, approveAndWait, approvePool, assertCanBurn, assertCanForceExercise, assertCanLiquidate, assertCanMint, assertFresh, assertHealthy, assertLpPositionFunded, assertTradeable, borrow, borrowAndWait, buildBatchDispatchArgs, buildCreditSwapCall, buildCreditWrappedDispatch, buildOpenPositionCalldata, buildProtectedSettleDispatch, buildProtectedSettlePlan, buildSettleSequenceCalls, buildSfpmSwapCalldata, buildSfpmSwapPlan, buildTemporaryLoanRecoveryDispatch, buildTokenShortfallRecoveryDispatch, buildUniqueCredit, buildUniqueLoan, buildUniqueWidthZeroLeg, calculateAccountGreeksPure, calculateMarketIndicator, calculatePortfolioDelta, calculatePortfolioGamma, calculatePortfolioGreeks, calculatePortfolioValue, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionDeltaWithSwap, calculatePositionGamma, calculatePositionGreeks, calculatePositionValue, calculatePositionValues, calculatePositionVolatilityMetrics, calculateResyncBlock, calculateSpreadWad, calculateVarianceProfile, cancelTransaction, checkApproval, checkCollateralAcrossTicks, classifyStrategyGroups, classifyStrike, cleanupStalePendingPositions, clearCheckpoint, clearPendingPositions, clearTrackedChunks, clearTrackedPositions, clearTradeHistory, closePosition, closePositionAndWait, collateralCurveTicks, collateralRuleKindFor, collateralTrackerV2Abi, computeV4PoolId, confirmPendingPosition, convertToAssets, convertToShares, countLegs, createEventPoller, createEventSubscription, createFileStorage, createFlowNeutralTokenId, createMemoryStorage, createNonceManager, createPoolFormatters, createTokenIdBuilder, decodeAllDispatchCalldata, decodeAllLegs, decodeDispatchCalldata, decodeLeftRightSigned, decodeLeftRightUnsigned, decodeLeg, decodeOraclePack, decodeOracleRiskParameters, decodeOracleTiming, decodePanopticTokenURI, decodePoolId, decodeTickSpacing, decodeTokenId, decodeVegoid, deployNewPool, deployNewPoolAndWait, deposit, depositAndWait, deriveSupplyRatePerSecWad, deriveUniqueTokenId, detectReorg, diagnoseOracleSafeMode, dispatch, dispatchAndWait, emptyLiquidateParams, encodeLeg, encodePoolId, encodePoolKeyBytes, encodeV3PoolKeyBytes, encodeV4PoolId, ensureSfpmV3PoolInitialized, estimateBlockNumbers, estimateCollateralBreakdown, estimateCollateralRequired, executeBatchDispatch, executeBatchDispatchAndWait, executeSettleSequence, executeSettleSequenceAndWait, failPendingPosition, feeGrowthInsideX128, feesFromFeeGrowthDelta, fetchPoolId, fetchSfpmV3PoolId, fetchUniswapFeeData, forceExercise, forceExerciseAndWait, formatBlockNumber, formatBps, formatCompact, formatDatetime, formatDuration, formatDurationSeconds, formatFeeTier, formatGas, formatGwei, formatPerSecondRateWadAsAprPct, formatPerSecondRateWadAsApyPct, formatPoolIdHex, formatPriceRange, formatRateWad, formatRatioPercent, formatTick, formatTickRange, formatTimestamp, formatTimestampLocale, formatTokenAmount, formatTokenAmountSigned, formatTokenDelta, formatTokenFlow, formatTokenIdHex, formatTokenIdShort, formatTxHash, formatUtilization, formatWad, formatWadPercent, formatWadSigned, formatWei, generateOverlappingTokenIds, getAccountBuyingPower, getAccountCollateral, getAccountGreeks, getAccountHistory, getAccountPremia, getAccountSummaryBasic, getAccountSummaryRisk, getAssetIndex, getBlockMeta, getChainDeployment, getChunkLiquidities, getChunkSpreads, getClosedPositions, getClosedPositionsKey, getCollateralAddresses, getCollateralCurve, getCollateralCurveInputs, getCollateralData, getCollateralRequiredBase, getCollateralSharePrices, getCollateralTotalAssetsBatch, getCurrentRates, getDeltaHedgeParams, getEnforcedTickLimits, getExecutableLpMaxSize, getFactoryConstructMetadata, getFactoryOwnerOf, getFactoryTokenURI, getForfeitablePremium, getGuardianUnlockState, getHedgeLimits, getInterestState, getIrmCurrent, getIrmCurve, getItmAmounts, getLegDelta, getLegDeltaInVaultFrame, getLegGamma, getLegNetValueWidth0, getLegValue, getLiquidationPrices, getMarginBuffer, getMaxPositionSize, getMaxRedeem, getMaxWithdrawable, getNativeTokenPrice, getNetLiquidationValue, getNetLiquidationValues, getNotEnoughTokensError, getOpenPositionIds, getOpenPositionPreview, getOracleRiskParameters, getOracleState, getPanopticPoolAddress, getPanopticPoolFromPoolId, getPendingPositions, getPendingPositionsKey, getPool, getPoolCurrentTick, getPoolDeploymentBlock, getPoolDisplayId, getPoolLiquidities, getPoolMetaKey, getPoolMetadata, getPoolPrefix, getPortfolioValue, getPosition, getPositionChunkData, getPositionDeltaMetrics, getPositionEnrichmentData, getPositionGreeks, getPositionMetaKey, getPositionValueCurve, getPositionVolatilityHistory, getPositions, getPositionsKey, getPositionsWithPremia, getPriceHistory, getPricesAtTick, getRealizedPnL, getRequiredCreditForITM, getRiskParameters, getSafeMode, getSchemaVersionKey, getSimpleLoanTokenIndex, getStreamiaHistory, getSyncCheckpointKey, getSyncStatus, getTickSpacing, getTokenListId, getTrackedChunks, getTrackedChunksKey, getTrackedPositionIds, getTradeHistory, getUniswapFeeHistory, getUniswapV3LpPositionState, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4LpPositionState, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, getUtilization, hasLoanOrCredit, hasLongLeg, interpolateBlocks, isCall, isCredit, isCreditLeg, isDefinedRisk, isGasError, isInputListFailError, isLiquidatable, isLoan, isLoanLeg, isNonceError, isPanopticErrorType, isPositionTracked, isRetryableRpcError, isShortOnly, isSpread, isSupportedChain, isolateGroupTokenId, jsonSerializer, ladderStrikeSequence, liquidate, liquidateAndWait, loadCheckpoint, logReturns, marketPnlInQuote, marketRiskFromValues, marketScenario, minePoolAddress, mint, mintAndWait, mintableAfterBuffer, multicallRead, netLiquidationValueInQuote, openPosition, openPositionAndWait, optimizeTokenIdRiskPartners, oracleEpochAt, orderListForSettle, packMarketState, panopticLiquidatorAbi, panopticPoolV2Abi, panopticQueryAbi, parseBps, parseCollateralLog, parsePanopticError, parsePoolLog, parseTokenAmount, parseTokenListId, parseWad, planDeriveStrategy, pokeOracle, pokeOracleAndWait, positionValueKey, positionValueTicks, prepareIndicatorCandles, preparePositionGamma, preparePositionValue, preparePositionValueCurve, previewBorrow, previewDeposit, previewMint, previewRedeem, previewRepay, previewUnwrap, previewWithdraw, previewWrap, priceToTick, publicBroadcaster, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, quoteV3ExactIn, ratePerSecWadToAprPct, realizedBeta, reconstructFromEvents, recoverSnapshot, recoverSnapshotFromTx, redeem, redeemAndWait, removeTrackedChunks, repay, repayAndWait, requireChainDeployment, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveTokenIndex, resolveUniswapV4PoolKey, riskEngineAbi, rollPosition, rollPositionAndWait, roundToTickSpacing, saveCheckpoint, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, selectDispatchForAccount, settleAccumulatedPremia, settleAccumulatedPremiaAndWait, settlePremiumFrom, settlePremiumFromAndWait, simulateBatchDispatch, simulateClosePosition, simulateDeployNewPool, simulateDeposit, simulateDispatch, simulateForceExercise, simulateLiquidate, simulateOpenPosition, simulateSFPMBurn, simulateSFPMMint, simulateSettle, simulateSettlePremiumBatch, simulateSettlePremiumFrom, simulateSettleSequence, simulateSwapExactIn, simulateSwapExactOut, simulateWithTokenFlow, simulateWithdraw, slippageBpsToTickDistance, smartRepay, smartRepayAndWait, speedUpTransaction, splitTokenIdByTimescale, sqrtPriceX96ToPriceDecimalScaled, sqrtPriceX96ToTick, supply, supplyAndWait, swapExactIn, swapExactInAndWait, swapExactOut, swapExactOutAndWait, syncPositions, tickLimits, tickToPrice, tickToPriceDecimalScaled, tickToSqrtPriceX96, toVaultFrameAtTick, truncateAddress, unsupply, unsupplyAndWait, unwrapWeth, unwrapWethAndWait, unwrapXstock, unwrapXstockAndWait, utilizationBpsToWad, utilizationPctToWad, validateBatch, validateBuilderCode, validatePoolId, valuePositionAccrual, verifyBlockContinuity, watchEvents, wethWrapAbi, withdraw, withdrawAndWait, withdrawWithPositions, withdrawWithPositionsAndWait, wrapEth, wrapEthAndWait, wrapXstock, wrapXstockAndWait, xstockWrapperAbi };
32037
32417
  //# sourceMappingURL=index.js.map