@panoptic-eng/sdk 1.0.44 → 1.0.46
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/cow/index.d.ts.map +1 -1
- package/dist/cow/index.js +10 -0
- package/dist/cow/index.js.map +1 -1
- package/dist/{cow-tRUtAUZy.js → cow-64lD-1vF.js} +1 -1
- package/dist/{getTrackedPositionIds-ms3W9dYB.js → getTrackedPositionIds-BwBtLpz-.js} +2 -2
- package/dist/{greeks-GysWXct-.js → greeks-9aTE-DwO.js} +11 -1
- package/dist/index.d.ts +1599 -197
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4199 -4056
- package/dist/index.js.map +1 -1
- package/dist/{irm-SPC2KxLA.js → irm-Cg08pWot.js} +7 -8
- package/dist/panoptic/v2/greeks/index.js +10 -0
- package/dist/panoptic/v2/greeks/index.js.map +1 -1
- package/dist/panoptic/v2/index.d.ts +499 -56
- package/dist/panoptic/v2/index.d.ts.map +1 -1
- package/dist/panoptic/v2/index.js +8925 -8027
- package/dist/panoptic/v2/index.js.map +1 -1
- package/dist/panoptic/v2/react-public.d.ts +532 -56
- package/dist/panoptic/v2/react-public.d.ts.map +1 -1
- package/dist/panoptic/v2/react-public.js +9305 -8223
- package/dist/panoptic/v2/react-public.js.map +1 -1
- package/dist/{router-mLWy0MD9.js → router-DR1NpQhi.js} +2 -2
- package/dist/{router-BTfbaRfg.js → router-Di45CFq9.js} +1 -1
- package/dist/uniswap/index.d.ts.map +1 -1
- package/dist/uniswap/index.js +10 -0
- package/dist/uniswap/index.js.map +1 -1
- package/dist/{v2-CDw-8xcY.js → v2-BYlZLfDi.js} +3904 -3207
- package/dist/{writes-_gfkBizf.js → writes-CmRf1Mok.js} +196 -4
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { MulticallNoDataError, MulticallResultFailedError, MulticallResultMissingError, PanopticValidationError, collateralTrackerV2Abi, decodeLeftRightUnsigned, getBlockMeta, getPool, getPositions, panopticPoolV2Abi, riskEngineAbi } from "./getTrackedPositionIds-
|
|
2
|
-
import { tickToSqrtPriceX96 } from "./greeks-
|
|
1
|
+
import { MulticallNoDataError, MulticallResultFailedError, MulticallResultMissingError, PanopticValidationError, collateralTrackerV2Abi, decodeLeftRightUnsigned, getBlockMeta, getPool, getPositions, panopticPoolV2Abi, riskEngineAbi } from "./getTrackedPositionIds-BwBtLpz-.js";
|
|
2
|
+
import { NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, tickToSqrtPriceX96 } from "./greeks-9aTE-DwO.js";
|
|
3
3
|
import { decodeFunctionResult, encodeFunctionData } from "viem";
|
|
4
4
|
import { call } from "viem/actions";
|
|
5
5
|
|
|
@@ -1977,8 +1977,6 @@ async function getNetLiquidationValues(params) {
|
|
|
1977
1977
|
async function getLiquidationPrices(params) {
|
|
1978
1978
|
const { client, poolAddress, account, tokenIds, queryAddress, blockNumber } = params;
|
|
1979
1979
|
const targetBlockNumber = blockNumber ?? params._meta?.blockNumber ?? await client.getBlockNumber();
|
|
1980
|
-
const MIN_TICK = -887272n;
|
|
1981
|
-
const MAX_TICK = 887272n;
|
|
1982
1980
|
const [result, _meta] = await Promise.all([client.readContract({
|
|
1983
1981
|
address: queryAddress,
|
|
1984
1982
|
abi: panopticQueryAbi,
|
|
@@ -1996,9 +1994,10 @@ async function getLiquidationPrices(params) {
|
|
|
1996
1994
|
const liqPriceDown = BigInt(result[0]);
|
|
1997
1995
|
const liqPriceUp = BigInt(result[1]);
|
|
1998
1996
|
return {
|
|
1999
|
-
lowerTick: liqPriceDown ===
|
|
2000
|
-
upperTick: liqPriceUp ===
|
|
2001
|
-
|
|
1997
|
+
lowerTick: liqPriceDown === NO_LOWER_LIQUIDATION_TICK ? null : liqPriceDown,
|
|
1998
|
+
upperTick: liqPriceUp === NO_UPPER_LIQUIDATION_TICK ? null : liqPriceUp,
|
|
1999
|
+
hasLiquidationBoundary: liqPriceDown !== NO_LOWER_LIQUIDATION_TICK || liqPriceUp !== NO_UPPER_LIQUIDATION_TICK,
|
|
2000
|
+
isLiquidatable: liqPriceDown !== NO_LOWER_LIQUIDATION_TICK || liqPriceUp !== NO_UPPER_LIQUIDATION_TICK,
|
|
2002
2001
|
_meta
|
|
2003
2002
|
};
|
|
2004
2003
|
}
|
|
@@ -3005,4 +3004,4 @@ async function getIrmCurve(params) {
|
|
|
3005
3004
|
}
|
|
3006
3005
|
|
|
3007
3006
|
//#endregion
|
|
3008
|
-
export { BASE_CHAIN_ID, BASE_DEPLOYMENT, BASE_ETH_USDC_5BPS_MARKET, BASE_HYPOVAULT_ADDRESSES, BASE_HYPOVAULT_CORE_ADDRESSES, BASE_HYPOVAULT_MANAGER_ADDRESSES, BASE_HYPOVAULT_MANAGER_TURNKEY_SIGNERS, BASE_PANOPTIC_POOL_ADDRESSES, BASE_PANOPTIC_V2_ADDRESSES, BORROW_INDEX_BITS, BPS_SCALE, CHAIN_DEPLOYMENTS, MAINNET_CHAIN_ID, MAINNET_DEPLOYMENT, MAINNET_ETH_USDC_5BPS_V3_PANOPTIC_POOL_ADDRESSES, MAINNET_PANOPTIC_V2_ADDRESSES, MAINNET_RISK_ENGINES, MARKET_EPOCH_BITS, MARKET_EPOCH_SHIFT, Multicall3Abi, RATE_AT_TARGET_BITS, SECONDS_PER_YEAR, SEPOLIA_CHAIN_ID, SEPOLIA_DEPLOYMENT, SEPOLIA_ETH_USDC_5BPS_MARKET, SEPOLIA_HYPOVAULT_ADDRESSES, SEPOLIA_HYPOVAULT_CORE_ADDRESSES, SEPOLIA_HYPOVAULT_MANAGER_ADDRESSES, SEPOLIA_HYPOVAULT_MANAGER_TURNKEY_SIGNERS, SEPOLIA_PANOPTIC_POOL_ADDRESSES, SEPOLIA_PANOPTIC_V2_ADDRESSES, StateViewAbi, UNREALIZED_INTEREST_BITS, VAULT_DISPLAY_NAMES_PER_CHAIN, VAULT_DISPLAY_NAME_RESOLVERS_PER_CHAIN, WAD as WAD$1, annualizePerSecondRateWad, deriveSupplyRatePerSecWad, formatPerSecondRateWadAsAprPct, formatPerSecondRateWadAsApyPct, formatRateWad, formatTokenAmount, formatTokenAmountSigned, formatTokenDelta, formatTokenFlow, formatWad, formatWadPercent, formatWadSigned, getAccountCollateral, getAccountSummaryBasic, getAccountSummaryRisk, getChainDeployment, getCollateralAddresses, getCollateralData, getCurrentRates, getEthUsdcMarket, getInterestState, getIrmCurrent, getIrmCurve, getLiquidationPrices, getNetLiquidationValue, getNetLiquidationValues, isLiquidatable, isSupportedChain, packMarketState, panopticQueryAbi
|
|
3007
|
+
export { BASE_CHAIN_ID, BASE_DEPLOYMENT, BASE_ETH_USDC_5BPS_MARKET, BASE_HYPOVAULT_ADDRESSES, BASE_HYPOVAULT_CORE_ADDRESSES, BASE_HYPOVAULT_MANAGER_ADDRESSES, BASE_HYPOVAULT_MANAGER_TURNKEY_SIGNERS, BASE_PANOPTIC_POOL_ADDRESSES, BASE_PANOPTIC_V2_ADDRESSES, BORROW_INDEX_BITS, BPS_SCALE, CHAIN_DEPLOYMENTS, MAINNET_CHAIN_ID, MAINNET_DEPLOYMENT, MAINNET_ETH_USDC_5BPS_V3_PANOPTIC_POOL_ADDRESSES, MAINNET_PANOPTIC_V2_ADDRESSES, MAINNET_RISK_ENGINES, MARKET_EPOCH_BITS, MARKET_EPOCH_SHIFT, Multicall3Abi, RATE_AT_TARGET_BITS, SECONDS_PER_YEAR, SEPOLIA_CHAIN_ID, SEPOLIA_DEPLOYMENT, SEPOLIA_ETH_USDC_5BPS_MARKET, SEPOLIA_HYPOVAULT_ADDRESSES, SEPOLIA_HYPOVAULT_CORE_ADDRESSES, SEPOLIA_HYPOVAULT_MANAGER_ADDRESSES, SEPOLIA_HYPOVAULT_MANAGER_TURNKEY_SIGNERS, SEPOLIA_PANOPTIC_POOL_ADDRESSES, SEPOLIA_PANOPTIC_V2_ADDRESSES, StateViewAbi, UNREALIZED_INTEREST_BITS, VAULT_DISPLAY_NAMES_PER_CHAIN, VAULT_DISPLAY_NAME_RESOLVERS_PER_CHAIN, WAD as WAD$1, annualizePerSecondRateWad, deriveSupplyRatePerSecWad, formatPerSecondRateWadAsAprPct, formatPerSecondRateWadAsApyPct, formatRateWad, formatTokenAmount, formatTokenAmountSigned, formatTokenDelta, formatTokenFlow, formatWad, formatWadPercent, formatWadSigned, getAccountCollateral, getAccountSummaryBasic, getAccountSummaryRisk, getChainDeployment, getCollateralAddresses, getCollateralData, getCurrentRates, getEthUsdcMarket, getInterestState, getIrmCurrent, getIrmCurve, getLiquidationPrices, getNetLiquidationValue, getNetLiquidationValues, isLiquidatable, isSupportedChain, packMarketState, panopticQueryAbi, parseTokenAmount, parseWad, ratePerSecWadToAprPct, readBlockAndAggregate, requireChainDeployment, requireReturnData, resolveVaultDisplayName, utilizationBpsToWad, utilizationPctToWad };
|
|
@@ -16,6 +16,16 @@ const MIN_TICK = -887272n;
|
|
|
16
16
|
* Maximum tick value for Uniswap v3/v4 pools.
|
|
17
17
|
*/
|
|
18
18
|
const MAX_TICK = 887272n;
|
|
19
|
+
/**
|
|
20
|
+
* PanopticQuery sentinel indicating that no lower liquidation boundary exists.
|
|
21
|
+
* This is int24.min, not Uniswap's minimum usable tick.
|
|
22
|
+
*/
|
|
23
|
+
const NO_LOWER_LIQUIDATION_TICK = -(1n << 23n);
|
|
24
|
+
/**
|
|
25
|
+
* PanopticQuery sentinel indicating that no upper liquidation boundary exists.
|
|
26
|
+
* This is int24.max, not Uniswap's maximum usable tick.
|
|
27
|
+
*/
|
|
28
|
+
const NO_UPPER_LIQUIDATION_TICK = (1n << 23n) - 1n;
|
|
19
29
|
|
|
20
30
|
//#endregion
|
|
21
31
|
//#region src/panoptic/v2/formatters/tick.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Q192","tick: bigint","tick: bigint","isAssetToken0: boolean","numerator: bigint","denominator: bigint","leg: Pick<TokenIdLeg, 'asset'>","assetIndex?: bigint","leg: TokenIdLeg","m: bigint","qCurrentTick: bigint","qStrikeTick: bigint","qMintTick: bigint","_definedRisk: boolean","swapAtMint: boolean","itmOffsetNotional: bigint","halfWidthTick: bigint","isPut: boolean","sqrtK","sqrtPm","sqrtR","rX192","diff","diffSqX192","tokenType: bigint","legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]","currentTick: bigint","mintTick: bigint","positionSize: bigint","poolTickSpacing: bigint","definedRisk: boolean","swapAtMint?: boolean","v: bigint","mintTick: bigint | undefined","vDelta","isPut","debtDelta","itmDelta","vDelta: bigint","delta: bigint","fromAsset: bigint","vaultAssetIndex: 0n | 1n","input: PositionGreeksInput","sum","input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n }","positions: PositionGreeksInput[]","input: PositionGreeksInput & { swapAtMint: boolean }"],"sources":["../../../../src/panoptic/v2/utils/constants.ts","../../../../src/panoptic/v2/formatters/tick.ts","../../../../src/panoptic/v2/greeks/index.ts"],"sourcesContent":["/**\n * Constants for the Panoptic v2 SDK.\n * @module v2/utils/constants\n */\n\n/**\n * WAD constant (10^18) used for fixed-point arithmetic.\n * Commonly used for spread calculations and other WAD-scaled values.\n */\nexport const WAD = 10n ** 18n\n\n/**\n * Zero collateral object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_COLLATERAL = {\n token0: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n token1: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n} as const\n\n/**\n * Zero valuation object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_VALUATION = {\n netLiquidationValue0: 0n,\n netLiquidationValue1: 0n,\n maintenanceMargin0: 0n,\n maintenanceMargin1: 0n,\n marginExcess0: 0n,\n marginExcess1: 0n,\n} as const\n\n/**\n * Storage schema version for the SDK.\n * Increment when storage format changes (triggers migration or clear).\n */\nexport const SCHEMA_VERSION = 1\n\n/**\n * Storage key prefix for all SDK data.\n */\nexport const STORAGE_PREFIX = 'panoptic-v2-sdk'\n\n/**\n * Maximum number of chunks that can be tracked per pool.\n * Exceeding this limit throws ChunkLimitError.\n */\nexport const MAX_TRACKED_CHUNKS = 1000\n\n/**\n * Default reorg depth for chain reorganization handling.\n * On reorg detection, rollback this many blocks and re-sync.\n */\nexport const REORG_DEPTH = 128n\n\n/**\n * Oracle epoch duration in seconds (64 seconds per epoch).\n */\nexport const ORACLE_EPOCH_SECONDS = 64n\n\n/**\n * Minimum tick value for Uniswap v3/v4 pools.\n */\nexport const MIN_TICK = -887272n\n\n/**\n * Maximum tick value for Uniswap v3/v4 pools.\n */\nexport const MAX_TICK = 887272n\n\n/**\n * Basis points denominator (100% = 10000 bps).\n */\nexport const BPS_DENOMINATOR = 10000n\n\n/**\n * Utilization denominator (100% = 10000).\n */\nexport const UTILIZATION_DENOMINATOR = 10000n\n","/**\n * Tick and price formatters for Uniswap V3/V4 pools.\n *\n * Ticks represent logarithmic prices where: price = 1.0001^tick\n *\n * @module v2/formatters/tick\n */\n\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\n\nconst Q192 = 1n << 192n\nconst RAW_PRICE_PRECISION = 40n\n\nfunction pow10(exponent: bigint): bigint {\n if (exponent < 0n) {\n throw new RangeError('Exponent must be non-negative')\n }\n return 10n ** exponent\n}\n\nfunction absBigint(value: bigint): bigint {\n return value < 0n ? -value : value\n}\n\nfunction trimTrailingZeros(value: string): string {\n const dotIndex = value.indexOf('.')\n if (dotIndex === -1) return value\n\n let end = value.length\n while (end > dotIndex && value[end - 1] === '0') {\n end -= 1\n }\n\n if (end === dotIndex + 1) {\n end = dotIndex\n }\n\n return value.slice(0, end)\n}\n\nfunction formatRatio(numerator: bigint, denominator: bigint, precision: bigint): string {\n if (precision < 0n) {\n throw new RangeError('Precision must be non-negative')\n }\n\n const sign = numerator < 0n ? '-' : ''\n const absNumerator = numerator < 0n ? -numerator : numerator\n\n const scale = pow10(precision)\n const scaled = (absNumerator * scale + denominator / 2n) / denominator\n const integerPart = scaled / scale\n const fractionalPart = scaled % scale\n\n if (precision === 0n) {\n return `${sign}${integerPart}`\n }\n\n return `${sign}${integerPart}.${fractionalPart.toString().padStart(Number(precision), '0')}`\n}\n\nfunction parseDecimalToFraction(value: string): { numerator: bigint; denominator: bigint } {\n const trimmed = value.trim()\n if (trimmed.length === 0) {\n throw new Error('Price must be a number')\n }\n\n const isNegative = trimmed.startsWith('-')\n const unsigned = isNegative || trimmed.startsWith('+') ? trimmed.slice(1) : trimmed\n\n const [basePart, exponentPart] = unsigned.toLowerCase().split('e')\n const [integerStr, fractionalStr = ''] = basePart.split('.')\n\n if (integerStr === '' && fractionalStr === '') {\n throw new Error('Price must be a number')\n }\n\n const integerDigits = integerStr === '' ? '0' : integerStr\n const digits = `${integerDigits}${fractionalStr}`\n\n let numerator = BigInt(digits === '' ? '0' : digits)\n let denominator = pow10(BigInt(fractionalStr.length))\n\n if (exponentPart !== undefined && exponentPart !== '') {\n const exponent = BigInt(exponentPart)\n if (exponent > 0n) {\n numerator *= pow10(exponent)\n } else if (exponent < 0n) {\n denominator *= pow10(-exponent)\n }\n }\n\n if (isNegative) {\n numerator = -numerator\n }\n\n return { numerator, denominator }\n}\n\nfunction compareRatios(\n leftNumerator: bigint,\n leftDenominator: bigint,\n rightNumerator: bigint,\n rightDenominator: bigint,\n): -1 | 0 | 1 {\n const left = leftNumerator * rightDenominator\n const right = rightNumerator * leftDenominator\n\n if (left === right) return 0\n return left < right ? -1 : 1\n}\n\nexport function tickToSqrtPriceX96(tick: bigint): bigint {\n if (tick < MIN_TICK || tick > MAX_TICK) {\n throw new RangeError('Tick out of bounds')\n }\n\n const absTick = tick < 0n ? -tick : tick\n\n let ratio =\n (absTick & 0x1n) !== 0n\n ? 0xfffcb933bd6fad37aa2d162d1a594001n\n : 0x100000000000000000000000000000000n\n if ((absTick & 0x2n) !== 0n) ratio = (ratio * 0xfff97272373d413259a46990580e213an) >> 128n\n if ((absTick & 0x4n) !== 0n) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn) >> 128n\n if ((absTick & 0x8n) !== 0n) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n) >> 128n\n if ((absTick & 0x10n) !== 0n) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n) >> 128n\n if ((absTick & 0x20n) !== 0n) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n) >> 128n\n if ((absTick & 0x40n) !== 0n) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n) >> 128n\n if ((absTick & 0x80n) !== 0n) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n) >> 128n\n if ((absTick & 0x100n) !== 0n) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n) >> 128n\n if ((absTick & 0x200n) !== 0n) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n) >> 128n\n if ((absTick & 0x400n) !== 0n) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n) >> 128n\n if ((absTick & 0x800n) !== 0n) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n) >> 128n\n if ((absTick & 0x1000n) !== 0n) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n) >> 128n\n if ((absTick & 0x2000n) !== 0n) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n) >> 128n\n if ((absTick & 0x4000n) !== 0n) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n) >> 128n\n if ((absTick & 0x8000n) !== 0n) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n) >> 128n\n if ((absTick & 0x10000n) !== 0n) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n) >> 128n\n if ((absTick & 0x20000n) !== 0n) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n) >> 128n\n if ((absTick & 0x40000n) !== 0n) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n) >> 128n\n if ((absTick & 0x80000n) !== 0n) ratio = (ratio * 0x48a170391f7dc42444e8fa2n) >> 128n\n\n if (tick > 0n) {\n ratio = ((1n << 256n) - 1n) / ratio\n }\n\n const remainderMask = (1n << 32n) - 1n\n const sqrtPriceX96 = (ratio >> 32n) + ((ratio & remainderMask) === 0n ? 0n : 1n)\n\n return sqrtPriceX96\n}\n\nconst MIN_SQRT_PRICE_X96 = tickToSqrtPriceX96(MIN_TICK)\nconst MAX_SQRT_PRICE_X96 = tickToSqrtPriceX96(MAX_TICK)\n\nfunction getPriceRatioFromSqrtPriceX96(sqrtPriceX96: bigint): {\n numerator: bigint\n denominator: bigint\n} {\n return {\n numerator: sqrtPriceX96 * sqrtPriceX96,\n denominator: Q192,\n }\n}\n\nfunction getRawPriceRatio(tick: bigint): { numerator: bigint; denominator: bigint } {\n return getPriceRatioFromSqrtPriceX96(tickToSqrtPriceX96(tick))\n}\n\nfunction adjustRatioForDecimals(\n numerator: bigint,\n denominator: bigint,\n decimals0: bigint,\n decimals1: bigint,\n): { numerator: bigint; denominator: bigint } {\n const diff = decimals0 - decimals1\n if (diff === 0n) {\n return { numerator, denominator }\n }\n\n if (diff > 0n) {\n return { numerator: numerator * pow10(diff), denominator }\n }\n\n return { numerator, denominator: denominator * pow10(-diff) }\n}\n\n/**\n * Convert a tick to a raw price string (no decimal adjustment).\n * Uses the formula: price = 1.0001^tick\n *\n * This returns the raw price ratio, not adjusted for token decimals.\n * A fixed internal precision is used and trailing zeros are trimmed.\n *\n * @param tick - The tick value\n * @returns Price string\n *\n * @example\n * ```typescript\n * tickToPrice(0n) // \"1\"\n * tickToPrice(1000n) // \"1.105...\" (approximately)\n * tickToPrice(-1000n) // \"0.904...\" (approximately)\n * tickToPrice(200000n) // Very large number\n * ```\n */\nexport function tickToPrice(tick: bigint): string {\n const { numerator, denominator } = getRawPriceRatio(tick)\n const price = formatRatio(numerator, denominator, RAW_PRICE_PRECISION)\n return trimTrailingZeros(price)\n}\n\n/**\n * Convert a tick to a human-readable price with decimal scaling.\n * Uses the formula: price = 1.0001^tick * 10^(decimals0-decimals1)\n *\n * This adjusts for the different decimals of the two tokens in the pair.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * // WETH/USDC pool (18 decimals / 6 decimals)\n * // At tick ~200000, price is roughly $2000 per ETH\n * tickToPriceDecimalScaled(200000n, 18n, 6n, 2n) // \"2000.00\" (approximately)\n *\n * // For token1/token0 price, swap the decimals\n * tickToPriceDecimalScaled(200000n, 6n, 18n, 6n) // \"0.000500\" (approximately)\n * ```\n */\nexport function tickToPriceDecimalScaled(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getRawPriceRatio(tick)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a sqrtPriceX96 to a human-readable price with decimal scaling.\n *\n * Uses the formula: price = (sqrtPriceX96^2 / 2^192) * 10^(decimals0-decimals1)\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * sqrtPriceX96ToPriceDecimalScaled(2n ** 96n, 18n, 18n, 2n) // \"1.00\"\n * ```\n */\nexport function sqrtPriceX96ToPriceDecimalScaled(\n sqrtPriceX96: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getPriceRatioFromSqrtPriceX96(sqrtPriceX96)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a price to a tick value.\n *\n * @param price - The price string\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * // WETH/USDC: What tick for $2000 per ETH?\n * priceToTick(\"2000\", 18n, 6n) // ~200000n\n *\n * // Inverse: What tick for 0.0005 ETH per USDC?\n * priceToTick(\"0.0005\", 6n, 18n) // ~200000n\n * ```\n */\nexport function priceToTick(price: string, decimals0: bigint, decimals1: bigint): bigint {\n const parsed = parseDecimalToFraction(price)\n if (parsed.numerator <= 0n) {\n throw new Error('Price must be positive')\n }\n\n let targetNumerator = parsed.numerator\n let targetDenominator = parsed.denominator\n\n const diff = decimals0 - decimals1\n if (diff > 0n) {\n targetDenominator *= pow10(diff)\n } else if (diff < 0n) {\n targetNumerator *= pow10(-diff)\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const { numerator, denominator } = getRawPriceRatio(mid)\n const cmp = compareRatios(numerator, denominator, targetNumerator, targetDenominator)\n\n if (cmp === 0) {\n return mid\n }\n\n if (cmp < 0) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorRatio = getRawPriceRatio(floorTick)\n const ceilRatio = getRawPriceRatio(ceilTick)\n\n const floorDiffNumerator = absBigint(\n targetNumerator * floorRatio.denominator - floorRatio.numerator * targetDenominator,\n )\n const ceilDiffNumerator = absBigint(\n targetNumerator * ceilRatio.denominator - ceilRatio.numerator * targetDenominator,\n )\n const floorDiffDenominator = targetDenominator * floorRatio.denominator\n const ceilDiffDenominator = targetDenominator * ceilRatio.denominator\n\n return floorDiffNumerator * ceilDiffDenominator <= ceilDiffNumerator * floorDiffDenominator\n ? floorTick\n : ceilTick\n}\n\n/**\n * Convert a sqrtPriceX96 value to the nearest tick.\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * const tick = sqrtPriceX96ToTick(2n ** 96n) // 0n\n * ```\n */\nexport function sqrtPriceX96ToTick(sqrtPriceX96: bigint): bigint {\n if (sqrtPriceX96 <= 0n) {\n throw new Error('Sqrt price must be positive')\n }\n\n if (sqrtPriceX96 < MIN_SQRT_PRICE_X96 || sqrtPriceX96 > MAX_SQRT_PRICE_X96) {\n throw new RangeError('Sqrt price out of bounds')\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const midSqrt = tickToSqrtPriceX96(mid)\n\n if (midSqrt === sqrtPriceX96) {\n return mid\n }\n\n if (midSqrt < sqrtPriceX96) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorSqrt = tickToSqrtPriceX96(floorTick)\n const ceilSqrt = tickToSqrtPriceX96(ceilTick)\n\n const floorDiff = absBigint(sqrtPriceX96 - floorSqrt)\n const ceilDiff = absBigint(ceilSqrt - sqrtPriceX96)\n\n return floorDiff <= ceilDiff ? floorTick : ceilTick\n}\n\n/**\n * Format a tick value for display.\n *\n * @param tick - The tick value\n * @returns Formatted tick string\n *\n * @example\n * ```typescript\n * formatTick(200000n) // \"200000\"\n * formatTick(-50000n) // \"-50000\"\n * ```\n */\nexport function formatTick(tick: bigint): string {\n return tick.toString()\n}\n\n/**\n * Get the price at a specific tick, returning both token0/token1 and token1/token0 prices.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Object with both price directions\n *\n * @example\n * ```typescript\n * const prices = getPricesAtTick(200000n, 18n, 6n, 2n)\n * // prices.token0PerToken1 = \"0.00\" (very small)\n * // prices.token1PerToken0 = \"2000.00\" (USDC per ETH)\n * ```\n */\nexport function getPricesAtTick(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): { token0PerToken1: string; token1PerToken0: string } {\n const rawRatio = getRawPriceRatio(tick)\n const adjustedRatio = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return {\n token0PerToken1: formatRatio(adjustedRatio.denominator, adjustedRatio.numerator, precision),\n token1PerToken0: formatRatio(adjustedRatio.numerator, adjustedRatio.denominator, precision),\n }\n}\n\n/**\n * Format a tick range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @returns Formatted tick range string\n *\n * @example\n * ```typescript\n * formatTickRange(-50000n, 200000n) // \"-50000 - 200000\"\n * ```\n */\nexport function formatTickRange(tickLower: bigint, tickUpper: bigint): string {\n return `${tickLower} - ${tickUpper}`\n}\n\n/**\n * Format a price range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price range string\n *\n * @example\n * ```typescript\n * formatPriceRange(0n, 0n, 18n, 18n, 2n) // \"1.00 - 1.00\"\n * ```\n */\nexport function formatPriceRange(\n tickLower: bigint,\n tickUpper: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const lower = tickToPriceDecimalScaled(tickLower, decimals0, decimals1, precision)\n const upper = tickToPriceDecimalScaled(tickUpper, decimals0, decimals1, precision)\n return `${lower} - ${upper}`\n}\n\n/**\n * Calculate the tick spacing for a given fee tier.\n *\n * @param feeBps - Fee in basis points (e.g., 500n for 0.05%)\n * @returns Tick spacing\n *\n * @example\n * ```typescript\n * getTickSpacing(100n) // 1n (0.01% fee tier)\n * getTickSpacing(500n) // 10n (0.05% fee tier)\n * getTickSpacing(3000n) // 60n (0.30% fee tier)\n * getTickSpacing(10000n) // 200n (1.00% fee tier)\n * ```\n */\nexport function getTickSpacing(feeBps: bigint): bigint {\n // Standard Uniswap V3 tick spacings\n switch (feeBps) {\n case 100n:\n return 1n\n case 500n:\n return 10n\n case 3000n:\n return 60n\n case 10000n:\n return 200n\n default: {\n const spacing = feeBps / 50n\n return spacing > 1n ? spacing : 1n\n }\n }\n}\n\n/**\n * Round a tick to the nearest valid tick for a given tick spacing.\n *\n * @param tick - The tick to round\n * @param tickSpacing - The tick spacing\n * @returns Rounded tick\n *\n * @example\n * ```typescript\n * roundToTickSpacing(12345n, 10n) // 12340n\n * roundToTickSpacing(12345n, 60n) // 12360n\n * roundToTickSpacing(-12345n, 10n) // -12350n\n * ```\n */\nexport function roundToTickSpacing(tick: bigint, tickSpacing: bigint): bigint {\n const remainder = tick % tickSpacing\n if (remainder === 0n) {\n return tick\n }\n // Round to nearest\n if (tick >= 0n) {\n return remainder >= tickSpacing / 2n ? tick + (tickSpacing - remainder) : tick - remainder\n }\n\n const absRemainder = -remainder\n return absRemainder >= tickSpacing / 2n\n ? tick - (tickSpacing - absRemainder)\n : tick + absRemainder\n}\n\n/**\n * Result of {@link tickLimits}.\n */\nexport interface TickLimitsResult {\n /** Lower tick limit (clamped to MIN_TICK). */\n low: bigint\n /** Upper tick limit (clamped to MAX_TICK). */\n high: bigint\n}\n\n/**\n * Compute slippage-bounded tick limits around the current tick.\n *\n * 1 tick ≈ 1 basis point (0.01 %) of price change, so a `toleranceBps`\n * of 500 allows roughly 5 % price movement. The result is clamped to\n * the protocol's `[MIN_TICK, MAX_TICK]` range.\n *\n * Useful for setting `tickLimitLow` / `tickLimitHigh` on `openPosition`\n * and `closePosition` to protect against MEV sandwiches and volatile\n * tick moves.\n *\n * @param currentTick - The current pool tick (must be within [MIN_TICK, MAX_TICK]).\n * @param toleranceBps - Slippage tolerance in basis points (≈ ticks). Must be non-negative.\n * @returns Clamped `{ low, high }` tick limits.\n * @throws {RangeError} If `toleranceBps` is negative or `currentTick` is out of bounds.\n *\n * @example\n * ```typescript\n * const { low, high } = tickLimits(200_000n, 500n)\n * // low = 199_500n\n * // high = 200_500n\n *\n * await openPosition({ ..., tickLimitLow: low, tickLimitHigh: high })\n * ```\n */\nexport function tickLimits(currentTick: bigint, toleranceBps: bigint): TickLimitsResult {\n if (toleranceBps < 0n) {\n throw new RangeError(`toleranceBps must be non-negative, got ${toleranceBps}`)\n }\n if (currentTick < MIN_TICK || currentTick > MAX_TICK) {\n throw new RangeError(`currentTick ${currentTick} is out of bounds [${MIN_TICK}, ${MAX_TICK}]`)\n }\n\n const rawLow = currentTick - toleranceBps\n const rawHigh = currentTick + toleranceBps\n const low = rawLow < MIN_TICK ? MIN_TICK : rawLow\n const high = rawHigh > MAX_TICK ? MAX_TICK : rawHigh\n\n if (low > high) {\n throw new RangeError(\n `Computed tick limits are inverted: low ${low} > high ${high} (currentTick=${currentTick}, toleranceBps=${toleranceBps})`,\n )\n }\n\n return { low, high }\n}\n","/**\n * Client-side greeks for the Panoptic v2 SDK.\n *\n * All functions accept bigint inputs (ticks, sizes) and return bigint values\n * in the natural token units — no artificial WAD scaling. The tick-based price\n * (1.0001^tick) naturally encodes the decimal conversion between tokens.\n *\n * Uses pure sqrtPriceX96 arithmetic for exact on-chain fidelity with PanopticQuery.\n * All intermediate calculations keep X96/X192 precision until final scaling.\n *\n * - Value: in numeraire token smallest units (e.g., USDC wei if numeraire is USDC)\n * - Delta: in asset token smallest units (e.g., WETH wei if asset is WETH)\n * - Gamma (dollar-gamma): in numeraire token smallest units\n *\n * @module v2/greeks\n */\n\nimport { tickToSqrtPriceX96 } from '../formatters/tick'\nimport type { TokenIdLeg } from '../types'\n\n// --- Internal Helpers ---\n\n/** Fixed-point scale constants for sqrtPriceX96 arithmetic */\nconst Q96 = 1n << 96n\nconst Q192 = 1n << 192n\n\n/**\n * Convert tick to quote-denominated tick based on asset direction.\n *\n * When isAssetToken0 = true (asset is token0, numeraire is token1):\n * - Tick already encodes price as token1/token0 (numeraire per asset)\n * - Return tick unchanged\n *\n * When isAssetToken0 = false (asset is token1, numeraire is token0):\n * - Tick encodes price as token1/token0, but we need token0/token1 (numeraire per asset)\n * - Invert by negating: 1/price = 1.0001^(-tick)\n */\nfunction quoteTick(tick: bigint, isAssetToken0: boolean): bigint {\n return isAssetToken0 ? tick : -tick\n}\n\n/**\n * Divide with truncation toward zero (matches Solidity division behavior).\n *\n * JavaScript bigint division uses floor (toward negative infinity), but Solidity\n * truncates toward zero. For on-chain fidelity, we must match Solidity.\n *\n * Example:\n * - Solidity: -7 / 2 = -3 (truncate toward zero)\n * - JS bigint: -7n / 2n = -4n (floor toward -∞)\n * - This function: divTrunc(-7n, 2n) = -3n ✓\n */\nfunction divTrunc(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) return 0n\n\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n\n // If signs differ and there's a remainder, JS floored when we need to truncate\n // Add 1 to move toward zero\n if (numerator < 0n !== denominator < 0n && remainder !== 0n) {\n return quotient + 1n\n }\n\n return quotient\n}\n\n/** Resolve isAssetToken0: optional assetIndex overrides leg.asset */\nfunction resolveAssetDirection(leg: Pick<TokenIdLeg, 'asset'>, assetIndex?: bigint): boolean {\n return assetIndex !== undefined ? assetIndex === 0n : leg.asset === 0n\n}\n\n/**\n * Compute the tokenType-denominated notional of a width=0 (loan/credit) leg.\n *\n * When leg.asset !== leg.tokenType, positionSize is in leg.asset units and\n * the borrowed notional is encoded via leg.strike: notional_tokenType_raw =\n * positionSize_raw × 1.0001^strike (a raw-to-raw ratio, unquoted by pool direction).\n * When leg.asset === leg.tokenType, m is already the notional (old convention).\n *\n * `m > 0` for loans (isLong=false), `m < 0` for credits (isLong=true), so the\n * returned notional is signed the same way.\n */\nfunction computeWidth0Notional(leg: TokenIdLeg, m: bigint): bigint {\n const scaleByStrike = leg.asset !== leg.tokenType\n if (!scaleByStrike) return m\n // The UI stores strike with a sign that depends on leg.asset:\n // priceTokenTypePerAsset = 1.0001^(leg.asset === 0 ? strike : -strike)\n // Mirror that here so K_raw matches the intended notional scaling.\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n return divTrunc(m * KrawX192, Q192)\n}\n\n/**\n * Calculate value for a width=0 (loan/credit) leg.\n * Width=0 means the range is a single tick (the strike), so there's no meaningful\n * \"in range\" — we use the below/above formulas which avoid division by (r-1)=0.\n *\n * This is the DEBT-ONLY value (the borrowed/lent obligation), used by delta/greeks\n * aggregation where the held-collateral side lives in a separate wallet/CT term. For\n * a standalone payoff chart that must reflect the net user-experienced payoff (which\n * depends on Zap vs Cover-at-mint), use `getLegNetValueWidth0`.\n */\nfunction getLegValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n _definedRisk: boolean,\n): bigint {\n // For loan/credit legs (width=0), value depends on the borrowed token.\n // m > 0 for loans (isLong=false), m < 0 for credits (isLong=true).\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n const notional = computeWidth0Notional(leg, m)\n\n if (borrowsAsset) {\n // Asset loan/credit: debt PnL = -notional*(P - Pm); crosses y=0 at mint price, delta=-notional.\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n } else {\n // Numeraire loan/credit: the obligation is a constant amount of the numeraire token,\n // so its value doesn't change with price. getLegValue is mint-relative PnL (option\n // legs cancel the mint baseline via `itm`; the asset branch above returns\n // -notional*(P - Pm), which is 0 at mint), so the numeraire branch's mint-relative PnL\n // is value(P) - value(Pm) = const - const = 0. Returning a nonzero constant here would\n // shift the whole PnL curve/baseline by the notional (double-counting the credit).\n return 0n\n }\n}\n\n/**\n * Calculate the NET (user-experienced) payoff value for a width=0 (loan/credit) leg.\n *\n * Unlike `getLegValueWidth0` (debt-only), this includes the collateral/holding side and\n * therefore depends on how the position was opened:\n *\n * - **Cover at mint** (`swapAtMint = false`): the collateral is sourced in the SAME token as\n * the debt/credit, so the holding side exactly offsets it → net PnL is FLAT (0 everywhere,\n * mint-relative), regardless of which token the leg is denominated in.\n * - **Zap** (`swapAtMint = true`): the collateral is sourced in the OTHER token, leaving a\n * ±1-delta line in the asset (ETH), anchored to 0 at the mint price:\n * - USDC loan → zap to ETH: +1 (long ETH)\n * - ETH loan → zap to USDC: −1 (short ETH)\n * - USDC credit ← zap from ETH: −1 (short ETH)\n * - ETH credit ← zap from USDC: +1 (long ETH)\n *\n * @returns Net leg value in numeraire token smallest units (mint-relative PnL).\n */\nexport function getLegNetValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n swapAtMint: boolean,\n itmOffsetNotional: bigint = 0n,\n): bigint {\n // Cover at mint: collateral in the same token as the debt/credit cancels it → flat.\n if (!swapAtMint) return 0n\n\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n // ITM-neutralizing credits/loans are sized to offset an option leg's mint-time ITM,\n // which was zapped into the other token under swapAtMint and therefore carries the same\n // ±delta line this leg would otherwise add. Net the leg's notional against that ITM\n // (`itmOffsetNotional`, same token side, opposite sign) so a correctly-sized credit\n // cancels to flat and only the residual (over/under-sizing) contributes a swap line.\n const notional = computeWidth0Notional(leg, m) + itmOffsetNotional\n\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n\n if (borrowsAsset) {\n // Debt/credit is in the asset (ETH); zapping the collateral into the numeraire leaves the\n // debt-only asset exposure -notional*(P - Pm). (Loan → short ETH; credit → long ETH.)\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n }\n\n // Debt/credit is in the numeraire (USDC); zapping sources/spends the asset (ETH). We hold\n // notional/Pm units of ETH, worth (notional/Pm)*(P - Pm) = notional*(P/Pm) - notional in\n // numeraire. (Loan → long ETH; credit → short ETH.) Zero at mint by construction.\n return divTrunc(notional * PX192, PmX192) - notional\n}\n\n/**\n * Compute the mint-time ITM (in-the-money) adjustment for an option leg.\n *\n * This is the `itm` baseline used by {@link getLegValue}: the amount by which the\n * position was already ITM at mint, expressed in the leg's natural units:\n * - Puts: numeraire units (added directly to the put's `debt*K + v` value).\n * - Calls: asset-ratio units (the call value multiplies it by price: `itm*P`/`itm*Pm`).\n *\n * Extracted so callers (e.g. {@link calculatePositionValue}) can build a per-side ITM\n * notional pool to net width=0 credit/loan legs against — an ITM-neutralizing credit\n * was sized to offset exactly this amount, so it should not add a spurious swap line.\n */\nfunction computeOptionItm(\n m: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n halfWidthTick: bigint,\n isPut: boolean,\n): bigint {\n if (isPut) {\n // Put ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = (K - Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (KX192 - PmX192), Q192)\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = 0\n return 0n\n }\n // In range: itm = m * (sqrt(K*r) - sqrt(Pm))^2 / (r - 1)\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const rX192 = sqrtR * sqrtR\n const diff = sqrtKR - sqrtPm // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n\n // Call ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = (1 - K/Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (PmX192 - KX192), PmX192)\n }\n // In range: itm = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const rX192 = sqrtR * sqrtR\n // sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = divTrunc(sqrtK * Q96, sqrtPm)\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n}\n\n// --- Public Helpers ---\n\n/**\n * Check if leg is a call option (vs put).\n *\n * A call is when the leg moves the asset token:\n * - If asset is token0: call when tokenType=0\n * - If asset is token1: call when tokenType=1\n */\nexport function isCall(tokenType: bigint, isAssetToken0: boolean): boolean {\n return isAssetToken0 ? tokenType === 0n : tokenType === 1n\n}\n\n/**\n * Check if position has defined risk (is a spread).\n *\n * A position is defined risk if it has 2+ legs of the same tokenType\n * with both long and short exposure.\n */\nexport function isDefinedRisk(legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]): boolean {\n if (legs.length < 2) return false\n\n for (const tt of [0n, 1n]) {\n const group = legs.filter((l) => l.tokenType === tt)\n if (group.length >= 2 && group.some((l) => l.isLong) && group.some((l) => !l.isLong)) {\n return true\n }\n }\n return false\n}\n\n// --- Per-Leg Greeks ---\n\n/**\n * Calculate the value of a single leg.\n *\n * Value represents the current P&L of the position in numeraire token units.\n * Combines base value (from Panoptic's piecewise formula), debt, and ITM adjustment.\n *\n * Uses sqrtPriceX96 for all calculations to maintain precision and on-chain fidelity.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param mintTick - Tick at position mint\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg value in numeraire token smallest units\n */\nexport function getLegValue(\n leg: TokenIdLeg,\n currentTick: bigint,\n mintTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n definedRisk: boolean,\n assetIndex?: bigint,\n swapAtMint?: boolean,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit (leg.width === 0n): when the caller specifies how the position was\n // opened (swapAtMint), return the NET user-experienced payoff (Zap vs Cover) instead of\n // the debt-only value. Narrow options whose halfWidth rounds to 0 are excluded.\n if (leg.width === 0n && swapAtMint !== undefined) {\n return getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint)\n }\n\n // Width=0 (loans/credits): single-tick position, no range to integrate over.\n if (halfWidthTick === 0n) {\n return getLegValueWidth0(\n leg,\n m,\n qCurrentTick,\n qStrikeTick,\n qMintTick,\n isAssetToken0,\n definedRisk,\n )\n }\n\n // Compute base value: v = f(P, K, r) from Panoptic's piecewise formula\n let v: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: v = m * P\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n v = divTrunc(m * PX192, Q192)\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: v = m * K\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n v = divTrunc(m * KX192, Q192)\n } else {\n // In range: v = m * (2*sqrt(P*K*r) - P - K) / (r - 1)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPKR = tickToSqrtPriceX96(qCurrentTick + qStrikeTick + halfWidthTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n\n const PX192 = sqrtP * sqrtP\n const KX192 = sqrtK * sqrtK\n const rX192 = sqrtR * sqrtR\n\n // v = m * (2*sqrtPKR/2^96 - PX192/2^192 - KX192/2^192) / ((rX192 - 2^192)/2^192)\n // = m * (2*sqrtPKR*2^96 - PX192 - KX192) / (rX192 - 2^192)\n const numerator = m * (2n * sqrtPKR * Q96 - PX192 - KX192)\n const denominator = rX192 - Q192\n v = divTrunc(numerator, denominator)\n }\n\n const debt = -m\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n // Compute ITM adjustment (differs for puts vs calls)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n\n // Compute final result based on option type\n if (isPut) {\n // Put: result = debt * K + v + itm\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n const debtK = divTrunc(debt * KX192, Q192)\n return debtK + v + itm\n } else {\n // Call: result = debt*P + v + itm*Pm (if defined risk) or debt*P + v + itm*P (if not)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n const debtP = divTrunc(debt * PX192, Q192)\n\n if (definedRisk) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PmX192 = sqrtPm * sqrtPm\n const itmPm = divTrunc(itm * PmX192, Q192)\n return debtP + v + itmPm\n } else {\n const itmP = divTrunc(itm * PX192, Q192)\n return debtP + v + itmP\n }\n }\n}\n\n/**\n * Calculate the delta of a single leg.\n *\n * Delta is the rate of change of position value with respect to price.\n * For puts: delta = vDelta\n * For calls: delta = debtDelta + vDelta + itmDelta (if not defined risk)\n *\n * Uses sqrtPriceX96 for all price calculations to maintain precision.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param mintTick - Tick at mint (optional, for ITM adjustment)\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg delta in asset token smallest units\n */\nexport function getLegDelta(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit: leg.width === 0n (not just halfWidth rounding to 0).\n // Debt-side exposure only — no option-like piecewise formula.\n if (leg.width === 0n) {\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n if (!borrowsAsset) return 0n\n // See getLegValueWidth0 for the notional-scaling rationale.\n if (leg.asset === leg.tokenType) return -m\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n const notional = divTrunc(m * KrawX192, Q192)\n return -notional\n }\n\n // Narrow option whose halfWidth rounds to 0: use option-like width=0 branch\n if (halfWidthTick === 0n) {\n const vDelta = qCurrentTick <= qStrikeTick ? m : 0n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n if (isPut) return vDelta\n\n // Call: add debt delta and ITM delta (same as normal path but no in-range branch)\n const debtDelta = -m\n let itmDelta = 0n\n if (mintTick !== undefined && !definedRisk) {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n if (qMintTick > qStrikeTick) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const PmX192 = sqrtPm * sqrtPm\n const KX192 = sqrtK * sqrtK\n itmDelta = divTrunc((PmX192 - KX192) * m, PmX192)\n }\n }\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n }\n\n // Compute vDelta: derivative of value with respect to price\n // vDelta = P < lo ? m : P > hi ? 0 : (m * (sqrt(K*r)/sqrt(P) - 1)) / (r - 1)\n let vDelta: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: vDelta = m\n vDelta = m\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: vDelta = 0\n vDelta = 0n\n } else {\n // In range: vDelta = m * (sqrt(K*r) - sqrt(P)) / (sqrt(P) * (r - 1))\n const sqrtP = tickToSqrtPriceX96(qCurrentTick) // X96\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick) // sqrt(K*r) in X96\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // vDelta = m * (sqrtKR - sqrtP)/2^96 / (sqrtP/2^96 * (rX192 - 2^192)/2^192)\n // = m * (sqrtKR - sqrtP) * 2^192 / (sqrtP * (rX192 - 2^192))\n const numerator = m * (sqrtKR - sqrtP) * Q192\n const denominator = sqrtP * (rX192 - Q192)\n vDelta = divTrunc(numerator, denominator)\n }\n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n if (isPut) {\n return vDelta\n }\n\n // Call: add debt delta and ITM delta\n const debtDelta = -m\n\n const itmDelta =\n mintTick === undefined\n ? 0n\n : (() => {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itmDelta = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itmDelta = (1 - K/Pm) * m = (Pm - K) * m / Pm\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const PmX192 = sqrtPm * sqrtPm // X192\n const KX192 = sqrtK * sqrtK // X192\n\n // itmDelta = (1 - K/Pm) * m = (PmX192 - KX192) * m / PmX192\n return divTrunc((PmX192 - KX192) * m, PmX192)\n } else {\n // In range: itmDelta = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // sqrt(K/Pm) = sqrtK / sqrtPm (both X96, so scale cancels)\n // But we need (sqrt(r) - sqrt(K/Pm))^2, so work in X96:\n // sqrtKPm = sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = (sqrtK * Q96) / sqrtPm // X96\n\n // (sqrt(r) - sqrt(K/Pm))^2 = (sqrtR - sqrtKPmX96)^2 / 2^192\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n\n // itmDelta = m * diffSqX192 / 2^192 / (rX192 / 2^192 - 1)\n // = m * diffSqX192 / (rX192 - 2^192)\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n })()\n\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n}\n\n/** Convert a delta between token frames at the current pool tick. */\nexport function toVaultFrameAtTick(\n delta: bigint,\n fromAsset: bigint,\n vaultAssetIndex: 0n | 1n,\n currentTick: bigint,\n flipSignOnAssetInversion = false,\n): bigint {\n if (fromAsset === vaultAssetIndex) return delta\n const sqrtPriceX96 = tickToSqrtPriceX96(currentTick)\n const converted =\n vaultAssetIndex === 0n\n ? (delta * Q192) / (sqrtPriceX96 * sqrtPriceX96)\n : (delta * sqrtPriceX96 * sqrtPriceX96) / Q192\n return flipSignOnAssetInversion ? -converted : converted\n}\n\n/**\n * Calculate one leg's wallet-aware delta in the vault asset frame.\n *\n * Width-zero loans and credits must be evaluated directly in the vault frame.\n * Option legs remain in their natural leg frame until converted at the mark tick.\n */\nexport function getLegDeltaInVaultFrame(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n vaultAssetIndex: 0n | 1n,\n): bigint {\n if (leg.width === 0n) {\n return getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n vaultAssetIndex,\n )\n }\n\n const legDelta = getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n )\n return toVaultFrameAtTick(legDelta, leg.asset, vaultAssetIndex, currentTick, true)\n}\n\n/**\n * Calculate the gamma (dollar gamma) of a single leg.\n *\n * Formula: gamma = (m * sqrt(K * P * r)) / (2 * (r - 1))\n * where:\n * - m = positionSize * optionRatio (with sign based on long/short)\n * - K = strike price (numeraire/asset)\n * - P = current price (numeraire/asset)\n * - r = 1.0001^(width*tickSpacing/2) ≈ 1 (dimensionless ratio)\n *\n * Uses sqrtPriceX96 arithmetic:\n * - sqrt(K*P*r) = tickToSqrtPriceX96(strikeₜ + currentₜ + widthₜ/2)\n * - Keeps X96/X192 precision until final division\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg gamma in numeraire token smallest units\n */\nexport function getLegGamma(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n\n // Convert to quote-denominated ticks (negate if asset is token0)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n // True loan: no gamma\n if (leg.width === 0n) return 0n\n\n // Narrow option whose halfWidth rounds to 0: no curvature (denominator 2*(r-1)=0)\n if (halfWidthTick === 0n) return 0n\n\n // Range check: gamma is zero outside [strike - halfWidth, strike + halfWidth]\n // This works in both normal and inverted tick space\n if (qCurrentTick < qStrikeTick - halfWidthTick || qCurrentTick > qStrikeTick + halfWidthTick) {\n return 0n\n }\n\n // Position size with sign: gamma uses inverted multiplier (long = positive, short = negative)\n const m = leg.isLong ? positionSize * leg.optionRatio : -(positionSize * leg.optionRatio)\n\n // sqrt(K * P * r) using tick addition: sqrt(K*P*r) = sqrt(1.0001^(K_tick + P_tick + r_tick))\n const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick) // X96 scale\n\n // r = 1.0001^(halfWidthTick), compute as (sqrtR)^2 to maintain precision\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96 scale\n const rX192 = sqrtR * sqrtR // X192 scale: r * 2^192\n\n // gamma = m * sqrt(K*P*r) / (2 * (r - 1))\n // = m * (sqrtKPR / 2^96) / (2 * (rX192/2^192 - 1))\n // = m * sqrtKPR * 2^192 / (2^96 * 2 * (rX192 - 2^192))\n // = m * sqrtKPR * 2^96 / (2 * (rX192 - 2^192))\n const numerator = m * sqrtKPR * Q96 // [asset] * [numeraire/asset * 2^96] * 2^96 = [numeraire * 2^192]\n const denominator = 2n * (rX192 - Q192) // 2 * (r - 1) in X192 scale\n\n return divTrunc(numerator, denominator) // [numeraire]\n}\n\n// --- Position-Level Aggregates ---\n\n/**\n * Parameters for position-level greek calculations.\n */\nexport interface PositionGreeksInput {\n /** Position legs */\n legs: TokenIdLeg[]\n /** Current pool tick */\n currentTick: bigint\n /** Tick at position mint */\n mintTick: bigint\n /** Position size in asset token smallest units */\n positionSize: bigint\n /** Pool tick spacing */\n poolTickSpacing: bigint\n /** Optional override for leg.asset on all legs (0n = token0 is asset, 1n = token1) */\n assetIndex?: bigint\n /**\n * How width=0 (loan/credit) legs were opened. When provided, `calculatePositionValue`\n * returns the NET user-experienced payoff for those legs (Zap = ±1 line, Cover = flat)\n * instead of the debt-only value. Leave undefined for delta/greeks aggregation, which\n * accounts for the held collateral separately.\n */\n swapAtMint?: boolean\n}\n\n/**\n * Calculate total value across all legs.\n */\nexport function calculatePositionValue(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const definedRisk = isDefinedRisk(legs)\n\n // Fast path: without swapAtMint there is no width=0 net-payoff (delta/greeks aggregation),\n // so no ITM netting is needed — value each leg independently.\n if (swapAtMint === undefined) {\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n ),\n 0n,\n )\n }\n\n // Pass 1: accumulate each option leg's mint-time ITM into a per-side notional pool. Under\n // swapAtMint the ITM was zapped into the other token, so a width=0 credit/loan that was\n // created to neutralize it (see getLegNetValueWidth0) should net against this pool instead\n // of adding a duplicate swap line. Puts contribute numeraire ITM; calls contribute asset ITM.\n let numeraireItmPool = 0n\n let assetItmPool = 0n\n for (const leg of legs) {\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n if (leg.width === 0n || halfWidthTick === 0n) continue // not a valued option leg\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n if (isPut) numeraireItmPool += itm\n else assetItmPool += itm\n }\n\n // Pass 2: sum leg values, netting width=0 legs against the matching ITM pool (consumed once).\n let sum = 0n\n for (const leg of legs) {\n if (leg.width === 0n) {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n const offset = borrowsAsset ? assetItmPool : numeraireItmPool\n if (borrowsAsset) assetItmPool = 0n\n else numeraireItmPool = 0n\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n sum += getLegNetValueWidth0(\n leg,\n m,\n qCurrentTick,\n qMintTick,\n isAssetToken0,\n swapAtMint,\n offset,\n )\n } else {\n sum += getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n )\n }\n }\n return sum\n}\n\n/**\n * Calculate total delta across all legs.\n */\nexport function calculatePositionDelta(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate debt-only position delta in a single target asset frame.\n *\n * Option legs are first valued in their natural `leg.asset` frame, then\n * converted into `assetIndex` using the current pool price. Width-zero legs\n * are evaluated directly in the target frame.\n *\n * Width=0 loan/credit legs include only their debt obligation. The held-token\n * side must be added separately from account collateral balances, preventing a\n * zap from being counted once in the position and again in collateral.\n */\nexport function calculatePositionDeltaDebtOnly(\n input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDeltaInVaultFrame(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate total gamma across all legs.\n */\nexport function calculatePositionGamma(input: PositionGreeksInput): bigint {\n const { legs, currentTick, positionSize, poolTickSpacing, assetIndex } = input\n\n return legs.reduce(\n (sum, leg) => sum + getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex),\n 0n,\n )\n}\n\n/**\n * Position greeks result.\n */\nexport interface PositionGreeksResult {\n /** Position value in numeraire token smallest units */\n value: bigint\n /** Position delta in asset token smallest units */\n delta: bigint\n /** Position gamma in numeraire token smallest units */\n gamma: bigint\n}\n\n/**\n * Calculate all greeks for a position.\n */\nexport function calculatePositionGreeks(input: PositionGreeksInput): PositionGreeksResult {\n return {\n value: calculatePositionValue(input),\n delta: calculatePositionDelta(input),\n gamma: calculatePositionGamma(input),\n }\n}\n\n// --- Portfolio (Multi-Position) Aggregates ---\n\n/**\n * Aggregate value across multiple independent positions.\n *\n * Each entry is valued with its OWN `positionSize`, `mintTick`, and legs, then\n * summed. Do NOT collapse multiple positions into one synthetic `PositionGreeksInput`\n * with a shared `positionSize` — `m = positionSize * optionRatio` is per-position, so a\n * shared size double-counts (and integer `optionRatio` cannot encode fractional shares).\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total value in numeraire token smallest units\n */\nexport function calculatePortfolioValue(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionValue(input), 0n)\n}\n\n/**\n * Aggregate delta across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePortfolioDelta(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionDelta(input), 0n)\n}\n\n/**\n * Aggregate gamma across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total gamma in numeraire token smallest units\n */\nexport function calculatePortfolioGamma(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionGamma(input), 0n)\n}\n\n/**\n * Calculate all greeks aggregated across multiple independent positions.\n */\nexport function calculatePortfolioGreeks(positions: PositionGreeksInput[]): PositionGreeksResult {\n return {\n value: calculatePortfolioValue(positions),\n delta: calculatePortfolioDelta(positions),\n gamma: calculatePortfolioGamma(positions),\n }\n}\n\n// --- Loan/Credit Swap-Aware Delta ---\n\n/**\n * Calculate the effective delta of a loan leg accounting for swapAtMint.\n *\n * A loan borrows one token and (optionally) swaps it for the other at mint.\n * The net delta depends on whether the swap occurred:\n *\n * | Scenario | Result |\n * |-----------------------|-------------------------------------------------|\n * | No swap | 0n (hold what you owe, net zero) |\n * | Swap + borrows asset | -m (hold numeraire, owe asset → short exposure) |\n * | Swap + borrows numer. | +m (hold asset, owe numeraire → long exposure) |\n *\n * Only meaningful for legs with `width === 0n`. For options, use `getLegDelta`.\n *\n * @param leg - The loan leg\n * @param positionSize - Position size in asset token smallest units\n * @param swapAtMint - Whether the borrowed tokens were swapped at mint\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset)\n * @returns Effective delta in asset token smallest units\n */\nexport function getLoanEffectiveDelta(\n leg: TokenIdLeg,\n positionSize: bigint,\n swapAtMint: boolean,\n assetIndex?: bigint,\n): bigint {\n if (!swapAtMint) return 0n\n\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n\n return borrowsAsset ? -m : m\n}\n\n/**\n * Calculate total delta for a position, using swap-aware delta for loan legs.\n *\n * For legs with `width === 0n` (loans/credits), uses `getLoanEffectiveDelta`\n * which accounts for the swapAtMint flag. For option legs (`width > 0n`),\n * uses the standard `getLegDelta`.\n *\n * @param input - Position greeks input plus swapAtMint flag\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePositionDeltaWithSwap(\n input: PositionGreeksInput & { swapAtMint: boolean },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const optionLegs = legs.filter((l) => l.width !== 0n)\n const definedRisk = isDefinedRisk(optionLegs)\n\n return legs.reduce((sum, leg) => {\n if (leg.width === 0n) {\n return sum + getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex)\n }\n return (\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n )\n )\n }, 0n)\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,MAAM,OAAO;;;;AAiE1B,MAAa,YAAY;;;;AAKzB,MAAa,WAAW;;;;ACrExB,MAAMA,SAAO,MAAM;AAqGnB,SAAgB,mBAAmBC,MAAsB;AACvD,KAAI,OAAO,YAAY,OAAO,SAC5B,OAAM,IAAI,WAAW;CAGvB,MAAM,UAAU,OAAO,MAAM,OAAO;CAEpC,IAAI,SACD,UAAU,UAAU,KACjB,sCACA;AACN,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,YAAY,GAAI,SAAS,QAAQ,uCAAwC;AACxF,MAAK,UAAU,YAAY,GAAI,SAAS,QAAQ,uCAA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F;;;;;;;;;;AAWD,SAAgB,wBAAwBA,WAA0C;AAChF,QAAO,UAAU,OAAO,CAAC,KAAK,UAAU,MAAM,uBAAuB,MAAM,EAAE,GAAG;AACjF;;;;AAKD,SAAgB,yBAAyBA,WAAwD;AAC/F,QAAO;EACL,OAAO,wBAAwB,UAAU;EACzC,OAAO,wBAAwB,UAAU;EACzC,OAAO,wBAAwB,UAAU;CAC1C;AACF;;;;;;;;;;;;;;;;;;;;;AAwBD,SAAgB,sBACdrC,KACAoB,cACAd,YACAP,YACQ;AACR,MAAK,WAAY,QAAO;CAExB,MAAM,gBAAgB,sBAAsB,KAAK,WAAW;CAC5D,MAAM,IAAI,IAAI,WAAW,eAAe,IAAI,eAAe,eAAe,IAAI;CAC9E,MAAM,eAAe,gBAAgB,IAAI,cAAc,KAAK,IAAI,cAAc;AAE9E,QAAO,gBAAgB,IAAI;AAC5B;;;;;;;;;;;AAYD,SAAgB,+BACduC,OACQ;CACR,MAAM,EAAE,MAAM,aAAa,UAAU,cAAc,iBAAiB,YAAY,YAAY,GAC1F;CACF,MAAM,aAAa,KAAK,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG;CACrD,MAAM,cAAc,cAAc,WAAW;AAE7C,QAAO,KAAK,OAAO,CAAC,KAAK,QAAQ;AAC/B,MAAI,IAAI,UAAU,GAChB,QAAO,MAAM,sBAAsB,KAAK,cAAc,YAAY,WAAW;AAE/E,SACE,MACA,YACE,KACA,aACA,cACA,iBACA,UACA,aACA,WACD;CAEJ,GAAE,GAAG;AACP"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Q192","tick: bigint","tick: bigint","isAssetToken0: boolean","numerator: bigint","denominator: bigint","leg: Pick<TokenIdLeg, 'asset'>","assetIndex?: bigint","leg: TokenIdLeg","m: bigint","qCurrentTick: bigint","qStrikeTick: bigint","qMintTick: bigint","_definedRisk: boolean","swapAtMint: boolean","itmOffsetNotional: bigint","halfWidthTick: bigint","isPut: boolean","sqrtK","sqrtPm","sqrtR","rX192","diff","diffSqX192","tokenType: bigint","legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]","currentTick: bigint","mintTick: bigint","positionSize: bigint","poolTickSpacing: bigint","definedRisk: boolean","swapAtMint?: boolean","v: bigint","mintTick: bigint | undefined","vDelta","isPut","debtDelta","itmDelta","vDelta: bigint","delta: bigint","fromAsset: bigint","vaultAssetIndex: 0n | 1n","input: PositionGreeksInput","sum","input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n }","positions: PositionGreeksInput[]","input: PositionGreeksInput & { swapAtMint: boolean }"],"sources":["../../../../src/panoptic/v2/utils/constants.ts","../../../../src/panoptic/v2/formatters/tick.ts","../../../../src/panoptic/v2/greeks/index.ts"],"sourcesContent":["/**\n * Constants for the Panoptic v2 SDK.\n * @module v2/utils/constants\n */\n\n/**\n * WAD constant (10^18) used for fixed-point arithmetic.\n * Commonly used for spread calculations and other WAD-scaled values.\n */\nexport const WAD = 10n ** 18n\n\n/**\n * Zero collateral object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_COLLATERAL = {\n token0: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n token1: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n} as const\n\n/**\n * Zero valuation object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_VALUATION = {\n netLiquidationValue0: 0n,\n netLiquidationValue1: 0n,\n maintenanceMargin0: 0n,\n maintenanceMargin1: 0n,\n marginExcess0: 0n,\n marginExcess1: 0n,\n} as const\n\n/**\n * Storage schema version for the SDK.\n * Increment when storage format changes (triggers migration or clear).\n */\nexport const SCHEMA_VERSION = 1\n\n/**\n * Storage key prefix for all SDK data.\n */\nexport const STORAGE_PREFIX = 'panoptic-v2-sdk'\n\n/**\n * Maximum number of chunks that can be tracked per pool.\n * Exceeding this limit throws ChunkLimitError.\n */\nexport const MAX_TRACKED_CHUNKS = 1000\n\n/**\n * Default reorg depth for chain reorganization handling.\n * On reorg detection, rollback this many blocks and re-sync.\n */\nexport const REORG_DEPTH = 128n\n\n/**\n * Oracle epoch duration in seconds (64 seconds per epoch).\n */\nexport const ORACLE_EPOCH_SECONDS = 64n\n\n/**\n * Minimum tick value for Uniswap v3/v4 pools.\n */\nexport const MIN_TICK = -887272n\n\n/**\n * Maximum tick value for Uniswap v3/v4 pools.\n */\nexport const MAX_TICK = 887272n\n\n/**\n * PanopticQuery sentinel indicating that no lower liquidation boundary exists.\n * This is int24.min, not Uniswap's minimum usable tick.\n */\nexport const NO_LOWER_LIQUIDATION_TICK = -(1n << 23n)\n\n/**\n * PanopticQuery sentinel indicating that no upper liquidation boundary exists.\n * This is int24.max, not Uniswap's maximum usable tick.\n */\nexport const NO_UPPER_LIQUIDATION_TICK = (1n << 23n) - 1n\n\n/**\n * Basis points denominator (100% = 10000 bps).\n */\nexport const BPS_DENOMINATOR = 10000n\n\n/**\n * Utilization denominator (100% = 10000).\n */\nexport const UTILIZATION_DENOMINATOR = 10000n\n","/**\n * Tick and price formatters for Uniswap V3/V4 pools.\n *\n * Ticks represent logarithmic prices where: price = 1.0001^tick\n *\n * @module v2/formatters/tick\n */\n\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\n\nconst Q192 = 1n << 192n\nconst RAW_PRICE_PRECISION = 40n\n\nfunction pow10(exponent: bigint): bigint {\n if (exponent < 0n) {\n throw new RangeError('Exponent must be non-negative')\n }\n return 10n ** exponent\n}\n\nfunction absBigint(value: bigint): bigint {\n return value < 0n ? -value : value\n}\n\nfunction trimTrailingZeros(value: string): string {\n const dotIndex = value.indexOf('.')\n if (dotIndex === -1) return value\n\n let end = value.length\n while (end > dotIndex && value[end - 1] === '0') {\n end -= 1\n }\n\n if (end === dotIndex + 1) {\n end = dotIndex\n }\n\n return value.slice(0, end)\n}\n\nfunction formatRatio(numerator: bigint, denominator: bigint, precision: bigint): string {\n if (precision < 0n) {\n throw new RangeError('Precision must be non-negative')\n }\n\n const sign = numerator < 0n ? '-' : ''\n const absNumerator = numerator < 0n ? -numerator : numerator\n\n const scale = pow10(precision)\n const scaled = (absNumerator * scale + denominator / 2n) / denominator\n const integerPart = scaled / scale\n const fractionalPart = scaled % scale\n\n if (precision === 0n) {\n return `${sign}${integerPart}`\n }\n\n return `${sign}${integerPart}.${fractionalPart.toString().padStart(Number(precision), '0')}`\n}\n\nfunction parseDecimalToFraction(value: string): { numerator: bigint; denominator: bigint } {\n const trimmed = value.trim()\n if (trimmed.length === 0) {\n throw new Error('Price must be a number')\n }\n\n const isNegative = trimmed.startsWith('-')\n const unsigned = isNegative || trimmed.startsWith('+') ? trimmed.slice(1) : trimmed\n\n const [basePart, exponentPart] = unsigned.toLowerCase().split('e')\n const [integerStr, fractionalStr = ''] = basePart.split('.')\n\n if (integerStr === '' && fractionalStr === '') {\n throw new Error('Price must be a number')\n }\n\n const integerDigits = integerStr === '' ? '0' : integerStr\n const digits = `${integerDigits}${fractionalStr}`\n\n let numerator = BigInt(digits === '' ? '0' : digits)\n let denominator = pow10(BigInt(fractionalStr.length))\n\n if (exponentPart !== undefined && exponentPart !== '') {\n const exponent = BigInt(exponentPart)\n if (exponent > 0n) {\n numerator *= pow10(exponent)\n } else if (exponent < 0n) {\n denominator *= pow10(-exponent)\n }\n }\n\n if (isNegative) {\n numerator = -numerator\n }\n\n return { numerator, denominator }\n}\n\nfunction compareRatios(\n leftNumerator: bigint,\n leftDenominator: bigint,\n rightNumerator: bigint,\n rightDenominator: bigint,\n): -1 | 0 | 1 {\n const left = leftNumerator * rightDenominator\n const right = rightNumerator * leftDenominator\n\n if (left === right) return 0\n return left < right ? -1 : 1\n}\n\nexport function tickToSqrtPriceX96(tick: bigint): bigint {\n if (tick < MIN_TICK || tick > MAX_TICK) {\n throw new RangeError('Tick out of bounds')\n }\n\n const absTick = tick < 0n ? -tick : tick\n\n let ratio =\n (absTick & 0x1n) !== 0n\n ? 0xfffcb933bd6fad37aa2d162d1a594001n\n : 0x100000000000000000000000000000000n\n if ((absTick & 0x2n) !== 0n) ratio = (ratio * 0xfff97272373d413259a46990580e213an) >> 128n\n if ((absTick & 0x4n) !== 0n) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn) >> 128n\n if ((absTick & 0x8n) !== 0n) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n) >> 128n\n if ((absTick & 0x10n) !== 0n) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n) >> 128n\n if ((absTick & 0x20n) !== 0n) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n) >> 128n\n if ((absTick & 0x40n) !== 0n) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n) >> 128n\n if ((absTick & 0x80n) !== 0n) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n) >> 128n\n if ((absTick & 0x100n) !== 0n) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n) >> 128n\n if ((absTick & 0x200n) !== 0n) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n) >> 128n\n if ((absTick & 0x400n) !== 0n) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n) >> 128n\n if ((absTick & 0x800n) !== 0n) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n) >> 128n\n if ((absTick & 0x1000n) !== 0n) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n) >> 128n\n if ((absTick & 0x2000n) !== 0n) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n) >> 128n\n if ((absTick & 0x4000n) !== 0n) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n) >> 128n\n if ((absTick & 0x8000n) !== 0n) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n) >> 128n\n if ((absTick & 0x10000n) !== 0n) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n) >> 128n\n if ((absTick & 0x20000n) !== 0n) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n) >> 128n\n if ((absTick & 0x40000n) !== 0n) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n) >> 128n\n if ((absTick & 0x80000n) !== 0n) ratio = (ratio * 0x48a170391f7dc42444e8fa2n) >> 128n\n\n if (tick > 0n) {\n ratio = ((1n << 256n) - 1n) / ratio\n }\n\n const remainderMask = (1n << 32n) - 1n\n const sqrtPriceX96 = (ratio >> 32n) + ((ratio & remainderMask) === 0n ? 0n : 1n)\n\n return sqrtPriceX96\n}\n\nconst MIN_SQRT_PRICE_X96 = tickToSqrtPriceX96(MIN_TICK)\nconst MAX_SQRT_PRICE_X96 = tickToSqrtPriceX96(MAX_TICK)\n\nfunction getPriceRatioFromSqrtPriceX96(sqrtPriceX96: bigint): {\n numerator: bigint\n denominator: bigint\n} {\n return {\n numerator: sqrtPriceX96 * sqrtPriceX96,\n denominator: Q192,\n }\n}\n\nfunction getRawPriceRatio(tick: bigint): { numerator: bigint; denominator: bigint } {\n return getPriceRatioFromSqrtPriceX96(tickToSqrtPriceX96(tick))\n}\n\nfunction adjustRatioForDecimals(\n numerator: bigint,\n denominator: bigint,\n decimals0: bigint,\n decimals1: bigint,\n): { numerator: bigint; denominator: bigint } {\n const diff = decimals0 - decimals1\n if (diff === 0n) {\n return { numerator, denominator }\n }\n\n if (diff > 0n) {\n return { numerator: numerator * pow10(diff), denominator }\n }\n\n return { numerator, denominator: denominator * pow10(-diff) }\n}\n\n/**\n * Convert a tick to a raw price string (no decimal adjustment).\n * Uses the formula: price = 1.0001^tick\n *\n * This returns the raw price ratio, not adjusted for token decimals.\n * A fixed internal precision is used and trailing zeros are trimmed.\n *\n * @param tick - The tick value\n * @returns Price string\n *\n * @example\n * ```typescript\n * tickToPrice(0n) // \"1\"\n * tickToPrice(1000n) // \"1.105...\" (approximately)\n * tickToPrice(-1000n) // \"0.904...\" (approximately)\n * tickToPrice(200000n) // Very large number\n * ```\n */\nexport function tickToPrice(tick: bigint): string {\n const { numerator, denominator } = getRawPriceRatio(tick)\n const price = formatRatio(numerator, denominator, RAW_PRICE_PRECISION)\n return trimTrailingZeros(price)\n}\n\n/**\n * Convert a tick to a human-readable price with decimal scaling.\n * Uses the formula: price = 1.0001^tick * 10^(decimals0-decimals1)\n *\n * This adjusts for the different decimals of the two tokens in the pair.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * // WETH/USDC pool (18 decimals / 6 decimals)\n * // At tick ~200000, price is roughly $2000 per ETH\n * tickToPriceDecimalScaled(200000n, 18n, 6n, 2n) // \"2000.00\" (approximately)\n *\n * // For token1/token0 price, swap the decimals\n * tickToPriceDecimalScaled(200000n, 6n, 18n, 6n) // \"0.000500\" (approximately)\n * ```\n */\nexport function tickToPriceDecimalScaled(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getRawPriceRatio(tick)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a sqrtPriceX96 to a human-readable price with decimal scaling.\n *\n * Uses the formula: price = (sqrtPriceX96^2 / 2^192) * 10^(decimals0-decimals1)\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * sqrtPriceX96ToPriceDecimalScaled(2n ** 96n, 18n, 18n, 2n) // \"1.00\"\n * ```\n */\nexport function sqrtPriceX96ToPriceDecimalScaled(\n sqrtPriceX96: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getPriceRatioFromSqrtPriceX96(sqrtPriceX96)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a price to a tick value.\n *\n * @param price - The price string\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * // WETH/USDC: What tick for $2000 per ETH?\n * priceToTick(\"2000\", 18n, 6n) // ~200000n\n *\n * // Inverse: What tick for 0.0005 ETH per USDC?\n * priceToTick(\"0.0005\", 6n, 18n) // ~200000n\n * ```\n */\nexport function priceToTick(price: string, decimals0: bigint, decimals1: bigint): bigint {\n const parsed = parseDecimalToFraction(price)\n if (parsed.numerator <= 0n) {\n throw new Error('Price must be positive')\n }\n\n let targetNumerator = parsed.numerator\n let targetDenominator = parsed.denominator\n\n const diff = decimals0 - decimals1\n if (diff > 0n) {\n targetDenominator *= pow10(diff)\n } else if (diff < 0n) {\n targetNumerator *= pow10(-diff)\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const { numerator, denominator } = getRawPriceRatio(mid)\n const cmp = compareRatios(numerator, denominator, targetNumerator, targetDenominator)\n\n if (cmp === 0) {\n return mid\n }\n\n if (cmp < 0) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorRatio = getRawPriceRatio(floorTick)\n const ceilRatio = getRawPriceRatio(ceilTick)\n\n const floorDiffNumerator = absBigint(\n targetNumerator * floorRatio.denominator - floorRatio.numerator * targetDenominator,\n )\n const ceilDiffNumerator = absBigint(\n targetNumerator * ceilRatio.denominator - ceilRatio.numerator * targetDenominator,\n )\n const floorDiffDenominator = targetDenominator * floorRatio.denominator\n const ceilDiffDenominator = targetDenominator * ceilRatio.denominator\n\n return floorDiffNumerator * ceilDiffDenominator <= ceilDiffNumerator * floorDiffDenominator\n ? floorTick\n : ceilTick\n}\n\n/**\n * Convert a sqrtPriceX96 value to the nearest tick.\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * const tick = sqrtPriceX96ToTick(2n ** 96n) // 0n\n * ```\n */\nexport function sqrtPriceX96ToTick(sqrtPriceX96: bigint): bigint {\n if (sqrtPriceX96 <= 0n) {\n throw new Error('Sqrt price must be positive')\n }\n\n if (sqrtPriceX96 < MIN_SQRT_PRICE_X96 || sqrtPriceX96 > MAX_SQRT_PRICE_X96) {\n throw new RangeError('Sqrt price out of bounds')\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const midSqrt = tickToSqrtPriceX96(mid)\n\n if (midSqrt === sqrtPriceX96) {\n return mid\n }\n\n if (midSqrt < sqrtPriceX96) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorSqrt = tickToSqrtPriceX96(floorTick)\n const ceilSqrt = tickToSqrtPriceX96(ceilTick)\n\n const floorDiff = absBigint(sqrtPriceX96 - floorSqrt)\n const ceilDiff = absBigint(ceilSqrt - sqrtPriceX96)\n\n return floorDiff <= ceilDiff ? floorTick : ceilTick\n}\n\n/**\n * Format a tick value for display.\n *\n * @param tick - The tick value\n * @returns Formatted tick string\n *\n * @example\n * ```typescript\n * formatTick(200000n) // \"200000\"\n * formatTick(-50000n) // \"-50000\"\n * ```\n */\nexport function formatTick(tick: bigint): string {\n return tick.toString()\n}\n\n/**\n * Get the price at a specific tick, returning both token0/token1 and token1/token0 prices.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Object with both price directions\n *\n * @example\n * ```typescript\n * const prices = getPricesAtTick(200000n, 18n, 6n, 2n)\n * // prices.token0PerToken1 = \"0.00\" (very small)\n * // prices.token1PerToken0 = \"2000.00\" (USDC per ETH)\n * ```\n */\nexport function getPricesAtTick(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): { token0PerToken1: string; token1PerToken0: string } {\n const rawRatio = getRawPriceRatio(tick)\n const adjustedRatio = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return {\n token0PerToken1: formatRatio(adjustedRatio.denominator, adjustedRatio.numerator, precision),\n token1PerToken0: formatRatio(adjustedRatio.numerator, adjustedRatio.denominator, precision),\n }\n}\n\n/**\n * Format a tick range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @returns Formatted tick range string\n *\n * @example\n * ```typescript\n * formatTickRange(-50000n, 200000n) // \"-50000 - 200000\"\n * ```\n */\nexport function formatTickRange(tickLower: bigint, tickUpper: bigint): string {\n return `${tickLower} - ${tickUpper}`\n}\n\n/**\n * Format a price range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price range string\n *\n * @example\n * ```typescript\n * formatPriceRange(0n, 0n, 18n, 18n, 2n) // \"1.00 - 1.00\"\n * ```\n */\nexport function formatPriceRange(\n tickLower: bigint,\n tickUpper: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const lower = tickToPriceDecimalScaled(tickLower, decimals0, decimals1, precision)\n const upper = tickToPriceDecimalScaled(tickUpper, decimals0, decimals1, precision)\n return `${lower} - ${upper}`\n}\n\n/**\n * Calculate the tick spacing for a given fee tier.\n *\n * @param feeBps - Fee in basis points (e.g., 500n for 0.05%)\n * @returns Tick spacing\n *\n * @example\n * ```typescript\n * getTickSpacing(100n) // 1n (0.01% fee tier)\n * getTickSpacing(500n) // 10n (0.05% fee tier)\n * getTickSpacing(3000n) // 60n (0.30% fee tier)\n * getTickSpacing(10000n) // 200n (1.00% fee tier)\n * ```\n */\nexport function getTickSpacing(feeBps: bigint): bigint {\n // Standard Uniswap V3 tick spacings\n switch (feeBps) {\n case 100n:\n return 1n\n case 500n:\n return 10n\n case 3000n:\n return 60n\n case 10000n:\n return 200n\n default: {\n const spacing = feeBps / 50n\n return spacing > 1n ? spacing : 1n\n }\n }\n}\n\n/**\n * Round a tick to the nearest valid tick for a given tick spacing.\n *\n * @param tick - The tick to round\n * @param tickSpacing - The tick spacing\n * @returns Rounded tick\n *\n * @example\n * ```typescript\n * roundToTickSpacing(12345n, 10n) // 12340n\n * roundToTickSpacing(12345n, 60n) // 12360n\n * roundToTickSpacing(-12345n, 10n) // -12350n\n * ```\n */\nexport function roundToTickSpacing(tick: bigint, tickSpacing: bigint): bigint {\n const remainder = tick % tickSpacing\n if (remainder === 0n) {\n return tick\n }\n // Round to nearest\n if (tick >= 0n) {\n return remainder >= tickSpacing / 2n ? tick + (tickSpacing - remainder) : tick - remainder\n }\n\n const absRemainder = -remainder\n return absRemainder >= tickSpacing / 2n\n ? tick - (tickSpacing - absRemainder)\n : tick + absRemainder\n}\n\n/**\n * Result of {@link tickLimits}.\n */\nexport interface TickLimitsResult {\n /** Lower tick limit (clamped to MIN_TICK). */\n low: bigint\n /** Upper tick limit (clamped to MAX_TICK). */\n high: bigint\n}\n\n/**\n * Compute slippage-bounded tick limits around the current tick.\n *\n * 1 tick ≈ 1 basis point (0.01 %) of price change, so a `toleranceBps`\n * of 500 allows roughly 5 % price movement. The result is clamped to\n * the protocol's `[MIN_TICK, MAX_TICK]` range.\n *\n * Useful for setting `tickLimitLow` / `tickLimitHigh` on `openPosition`\n * and `closePosition` to protect against MEV sandwiches and volatile\n * tick moves.\n *\n * @param currentTick - The current pool tick (must be within [MIN_TICK, MAX_TICK]).\n * @param toleranceBps - Slippage tolerance in basis points (≈ ticks). Must be non-negative.\n * @returns Clamped `{ low, high }` tick limits.\n * @throws {RangeError} If `toleranceBps` is negative or `currentTick` is out of bounds.\n *\n * @example\n * ```typescript\n * const { low, high } = tickLimits(200_000n, 500n)\n * // low = 199_500n\n * // high = 200_500n\n *\n * await openPosition({ ..., tickLimitLow: low, tickLimitHigh: high })\n * ```\n */\nexport function tickLimits(currentTick: bigint, toleranceBps: bigint): TickLimitsResult {\n if (toleranceBps < 0n) {\n throw new RangeError(`toleranceBps must be non-negative, got ${toleranceBps}`)\n }\n if (currentTick < MIN_TICK || currentTick > MAX_TICK) {\n throw new RangeError(`currentTick ${currentTick} is out of bounds [${MIN_TICK}, ${MAX_TICK}]`)\n }\n\n const rawLow = currentTick - toleranceBps\n const rawHigh = currentTick + toleranceBps\n const low = rawLow < MIN_TICK ? MIN_TICK : rawLow\n const high = rawHigh > MAX_TICK ? MAX_TICK : rawHigh\n\n if (low > high) {\n throw new RangeError(\n `Computed tick limits are inverted: low ${low} > high ${high} (currentTick=${currentTick}, toleranceBps=${toleranceBps})`,\n )\n }\n\n return { low, high }\n}\n","/**\n * Client-side greeks for the Panoptic v2 SDK.\n *\n * All functions accept bigint inputs (ticks, sizes) and return bigint values\n * in the natural token units — no artificial WAD scaling. The tick-based price\n * (1.0001^tick) naturally encodes the decimal conversion between tokens.\n *\n * Uses pure sqrtPriceX96 arithmetic for exact on-chain fidelity with PanopticQuery.\n * All intermediate calculations keep X96/X192 precision until final scaling.\n *\n * - Value: in numeraire token smallest units (e.g., USDC wei if numeraire is USDC)\n * - Delta: in asset token smallest units (e.g., WETH wei if asset is WETH)\n * - Gamma (dollar-gamma): in numeraire token smallest units\n *\n * @module v2/greeks\n */\n\nimport { tickToSqrtPriceX96 } from '../formatters/tick'\nimport type { TokenIdLeg } from '../types'\n\n// --- Internal Helpers ---\n\n/** Fixed-point scale constants for sqrtPriceX96 arithmetic */\nconst Q96 = 1n << 96n\nconst Q192 = 1n << 192n\n\n/**\n * Convert tick to quote-denominated tick based on asset direction.\n *\n * When isAssetToken0 = true (asset is token0, numeraire is token1):\n * - Tick already encodes price as token1/token0 (numeraire per asset)\n * - Return tick unchanged\n *\n * When isAssetToken0 = false (asset is token1, numeraire is token0):\n * - Tick encodes price as token1/token0, but we need token0/token1 (numeraire per asset)\n * - Invert by negating: 1/price = 1.0001^(-tick)\n */\nfunction quoteTick(tick: bigint, isAssetToken0: boolean): bigint {\n return isAssetToken0 ? tick : -tick\n}\n\n/**\n * Divide with truncation toward zero (matches Solidity division behavior).\n *\n * JavaScript bigint division uses floor (toward negative infinity), but Solidity\n * truncates toward zero. For on-chain fidelity, we must match Solidity.\n *\n * Example:\n * - Solidity: -7 / 2 = -3 (truncate toward zero)\n * - JS bigint: -7n / 2n = -4n (floor toward -∞)\n * - This function: divTrunc(-7n, 2n) = -3n ✓\n */\nfunction divTrunc(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) return 0n\n\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n\n // If signs differ and there's a remainder, JS floored when we need to truncate\n // Add 1 to move toward zero\n if (numerator < 0n !== denominator < 0n && remainder !== 0n) {\n return quotient + 1n\n }\n\n return quotient\n}\n\n/** Resolve isAssetToken0: optional assetIndex overrides leg.asset */\nfunction resolveAssetDirection(leg: Pick<TokenIdLeg, 'asset'>, assetIndex?: bigint): boolean {\n return assetIndex !== undefined ? assetIndex === 0n : leg.asset === 0n\n}\n\n/**\n * Compute the tokenType-denominated notional of a width=0 (loan/credit) leg.\n *\n * When leg.asset !== leg.tokenType, positionSize is in leg.asset units and\n * the borrowed notional is encoded via leg.strike: notional_tokenType_raw =\n * positionSize_raw × 1.0001^strike (a raw-to-raw ratio, unquoted by pool direction).\n * When leg.asset === leg.tokenType, m is already the notional (old convention).\n *\n * `m > 0` for loans (isLong=false), `m < 0` for credits (isLong=true), so the\n * returned notional is signed the same way.\n */\nfunction computeWidth0Notional(leg: TokenIdLeg, m: bigint): bigint {\n const scaleByStrike = leg.asset !== leg.tokenType\n if (!scaleByStrike) return m\n // The UI stores strike with a sign that depends on leg.asset:\n // priceTokenTypePerAsset = 1.0001^(leg.asset === 0 ? strike : -strike)\n // Mirror that here so K_raw matches the intended notional scaling.\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n return divTrunc(m * KrawX192, Q192)\n}\n\n/**\n * Calculate value for a width=0 (loan/credit) leg.\n * Width=0 means the range is a single tick (the strike), so there's no meaningful\n * \"in range\" — we use the below/above formulas which avoid division by (r-1)=0.\n *\n * This is the DEBT-ONLY value (the borrowed/lent obligation), used by delta/greeks\n * aggregation where the held-collateral side lives in a separate wallet/CT term. For\n * a standalone payoff chart that must reflect the net user-experienced payoff (which\n * depends on Zap vs Cover-at-mint), use `getLegNetValueWidth0`.\n */\nfunction getLegValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n _definedRisk: boolean,\n): bigint {\n // For loan/credit legs (width=0), value depends on the borrowed token.\n // m > 0 for loans (isLong=false), m < 0 for credits (isLong=true).\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n const notional = computeWidth0Notional(leg, m)\n\n if (borrowsAsset) {\n // Asset loan/credit: debt PnL = -notional*(P - Pm); crosses y=0 at mint price, delta=-notional.\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n } else {\n // Numeraire loan/credit: the obligation is a constant amount of the numeraire token,\n // so its value doesn't change with price. getLegValue is mint-relative PnL (option\n // legs cancel the mint baseline via `itm`; the asset branch above returns\n // -notional*(P - Pm), which is 0 at mint), so the numeraire branch's mint-relative PnL\n // is value(P) - value(Pm) = const - const = 0. Returning a nonzero constant here would\n // shift the whole PnL curve/baseline by the notional (double-counting the credit).\n return 0n\n }\n}\n\n/**\n * Calculate the NET (user-experienced) payoff value for a width=0 (loan/credit) leg.\n *\n * Unlike `getLegValueWidth0` (debt-only), this includes the collateral/holding side and\n * therefore depends on how the position was opened:\n *\n * - **Cover at mint** (`swapAtMint = false`): the collateral is sourced in the SAME token as\n * the debt/credit, so the holding side exactly offsets it → net PnL is FLAT (0 everywhere,\n * mint-relative), regardless of which token the leg is denominated in.\n * - **Zap** (`swapAtMint = true`): the collateral is sourced in the OTHER token, leaving a\n * ±1-delta line in the asset (ETH), anchored to 0 at the mint price:\n * - USDC loan → zap to ETH: +1 (long ETH)\n * - ETH loan → zap to USDC: −1 (short ETH)\n * - USDC credit ← zap from ETH: −1 (short ETH)\n * - ETH credit ← zap from USDC: +1 (long ETH)\n *\n * @returns Net leg value in numeraire token smallest units (mint-relative PnL).\n */\nexport function getLegNetValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n swapAtMint: boolean,\n itmOffsetNotional: bigint = 0n,\n): bigint {\n // Cover at mint: collateral in the same token as the debt/credit cancels it → flat.\n if (!swapAtMint) return 0n\n\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n // ITM-neutralizing credits/loans are sized to offset an option leg's mint-time ITM,\n // which was zapped into the other token under swapAtMint and therefore carries the same\n // ±delta line this leg would otherwise add. Net the leg's notional against that ITM\n // (`itmOffsetNotional`, same token side, opposite sign) so a correctly-sized credit\n // cancels to flat and only the residual (over/under-sizing) contributes a swap line.\n const notional = computeWidth0Notional(leg, m) + itmOffsetNotional\n\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n\n if (borrowsAsset) {\n // Debt/credit is in the asset (ETH); zapping the collateral into the numeraire leaves the\n // debt-only asset exposure -notional*(P - Pm). (Loan → short ETH; credit → long ETH.)\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n }\n\n // Debt/credit is in the numeraire (USDC); zapping sources/spends the asset (ETH). We hold\n // notional/Pm units of ETH, worth (notional/Pm)*(P - Pm) = notional*(P/Pm) - notional in\n // numeraire. (Loan → long ETH; credit → short ETH.) Zero at mint by construction.\n return divTrunc(notional * PX192, PmX192) - notional\n}\n\n/**\n * Compute the mint-time ITM (in-the-money) adjustment for an option leg.\n *\n * This is the `itm` baseline used by {@link getLegValue}: the amount by which the\n * position was already ITM at mint, expressed in the leg's natural units:\n * - Puts: numeraire units (added directly to the put's `debt*K + v` value).\n * - Calls: asset-ratio units (the call value multiplies it by price: `itm*P`/`itm*Pm`).\n *\n * Extracted so callers (e.g. {@link calculatePositionValue}) can build a per-side ITM\n * notional pool to net width=0 credit/loan legs against — an ITM-neutralizing credit\n * was sized to offset exactly this amount, so it should not add a spurious swap line.\n */\nfunction computeOptionItm(\n m: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n halfWidthTick: bigint,\n isPut: boolean,\n): bigint {\n if (isPut) {\n // Put ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = (K - Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (KX192 - PmX192), Q192)\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = 0\n return 0n\n }\n // In range: itm = m * (sqrt(K*r) - sqrt(Pm))^2 / (r - 1)\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const rX192 = sqrtR * sqrtR\n const diff = sqrtKR - sqrtPm // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n\n // Call ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = (1 - K/Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (PmX192 - KX192), PmX192)\n }\n // In range: itm = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const rX192 = sqrtR * sqrtR\n // sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = divTrunc(sqrtK * Q96, sqrtPm)\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n}\n\n// --- Public Helpers ---\n\n/**\n * Check if leg is a call option (vs put).\n *\n * A call is when the leg moves the asset token:\n * - If asset is token0: call when tokenType=0\n * - If asset is token1: call when tokenType=1\n */\nexport function isCall(tokenType: bigint, isAssetToken0: boolean): boolean {\n return isAssetToken0 ? tokenType === 0n : tokenType === 1n\n}\n\n/**\n * Check if position has defined risk (is a spread).\n *\n * A position is defined risk if it has 2+ legs of the same tokenType\n * with both long and short exposure.\n */\nexport function isDefinedRisk(legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]): boolean {\n if (legs.length < 2) return false\n\n for (const tt of [0n, 1n]) {\n const group = legs.filter((l) => l.tokenType === tt)\n if (group.length >= 2 && group.some((l) => l.isLong) && group.some((l) => !l.isLong)) {\n return true\n }\n }\n return false\n}\n\n// --- Per-Leg Greeks ---\n\n/**\n * Calculate the value of a single leg.\n *\n * Value represents the current P&L of the position in numeraire token units.\n * Combines base value (from Panoptic's piecewise formula), debt, and ITM adjustment.\n *\n * Uses sqrtPriceX96 for all calculations to maintain precision and on-chain fidelity.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param mintTick - Tick at position mint\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg value in numeraire token smallest units\n */\nexport function getLegValue(\n leg: TokenIdLeg,\n currentTick: bigint,\n mintTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n definedRisk: boolean,\n assetIndex?: bigint,\n swapAtMint?: boolean,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit (leg.width === 0n): when the caller specifies how the position was\n // opened (swapAtMint), return the NET user-experienced payoff (Zap vs Cover) instead of\n // the debt-only value. Narrow options whose halfWidth rounds to 0 are excluded.\n if (leg.width === 0n && swapAtMint !== undefined) {\n return getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint)\n }\n\n // Width=0 (loans/credits): single-tick position, no range to integrate over.\n if (halfWidthTick === 0n) {\n return getLegValueWidth0(\n leg,\n m,\n qCurrentTick,\n qStrikeTick,\n qMintTick,\n isAssetToken0,\n definedRisk,\n )\n }\n\n // Compute base value: v = f(P, K, r) from Panoptic's piecewise formula\n let v: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: v = m * P\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n v = divTrunc(m * PX192, Q192)\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: v = m * K\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n v = divTrunc(m * KX192, Q192)\n } else {\n // In range: v = m * (2*sqrt(P*K*r) - P - K) / (r - 1)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPKR = tickToSqrtPriceX96(qCurrentTick + qStrikeTick + halfWidthTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n\n const PX192 = sqrtP * sqrtP\n const KX192 = sqrtK * sqrtK\n const rX192 = sqrtR * sqrtR\n\n // v = m * (2*sqrtPKR/2^96 - PX192/2^192 - KX192/2^192) / ((rX192 - 2^192)/2^192)\n // = m * (2*sqrtPKR*2^96 - PX192 - KX192) / (rX192 - 2^192)\n const numerator = m * (2n * sqrtPKR * Q96 - PX192 - KX192)\n const denominator = rX192 - Q192\n v = divTrunc(numerator, denominator)\n }\n\n const debt = -m\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n // Compute ITM adjustment (differs for puts vs calls)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n\n // Compute final result based on option type\n if (isPut) {\n // Put: result = debt * K + v + itm\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n const debtK = divTrunc(debt * KX192, Q192)\n return debtK + v + itm\n } else {\n // Call: result = debt*P + v + itm*Pm (if defined risk) or debt*P + v + itm*P (if not)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n const debtP = divTrunc(debt * PX192, Q192)\n\n if (definedRisk) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PmX192 = sqrtPm * sqrtPm\n const itmPm = divTrunc(itm * PmX192, Q192)\n return debtP + v + itmPm\n } else {\n const itmP = divTrunc(itm * PX192, Q192)\n return debtP + v + itmP\n }\n }\n}\n\n/**\n * Calculate the delta of a single leg.\n *\n * Delta is the rate of change of position value with respect to price.\n * For puts: delta = vDelta\n * For calls: delta = debtDelta + vDelta + itmDelta (if not defined risk)\n *\n * Uses sqrtPriceX96 for all price calculations to maintain precision.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param mintTick - Tick at mint (optional, for ITM adjustment)\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg delta in asset token smallest units\n */\nexport function getLegDelta(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit: leg.width === 0n (not just halfWidth rounding to 0).\n // Debt-side exposure only — no option-like piecewise formula.\n if (leg.width === 0n) {\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n if (!borrowsAsset) return 0n\n // See getLegValueWidth0 for the notional-scaling rationale.\n if (leg.asset === leg.tokenType) return -m\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n const notional = divTrunc(m * KrawX192, Q192)\n return -notional\n }\n\n // Narrow option whose halfWidth rounds to 0: use option-like width=0 branch\n if (halfWidthTick === 0n) {\n const vDelta = qCurrentTick <= qStrikeTick ? m : 0n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n if (isPut) return vDelta\n\n // Call: add debt delta and ITM delta (same as normal path but no in-range branch)\n const debtDelta = -m\n let itmDelta = 0n\n if (mintTick !== undefined && !definedRisk) {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n if (qMintTick > qStrikeTick) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const PmX192 = sqrtPm * sqrtPm\n const KX192 = sqrtK * sqrtK\n itmDelta = divTrunc((PmX192 - KX192) * m, PmX192)\n }\n }\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n }\n\n // Compute vDelta: derivative of value with respect to price\n // vDelta = P < lo ? m : P > hi ? 0 : (m * (sqrt(K*r)/sqrt(P) - 1)) / (r - 1)\n let vDelta: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: vDelta = m\n vDelta = m\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: vDelta = 0\n vDelta = 0n\n } else {\n // In range: vDelta = m * (sqrt(K*r) - sqrt(P)) / (sqrt(P) * (r - 1))\n const sqrtP = tickToSqrtPriceX96(qCurrentTick) // X96\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick) // sqrt(K*r) in X96\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // vDelta = m * (sqrtKR - sqrtP)/2^96 / (sqrtP/2^96 * (rX192 - 2^192)/2^192)\n // = m * (sqrtKR - sqrtP) * 2^192 / (sqrtP * (rX192 - 2^192))\n const numerator = m * (sqrtKR - sqrtP) * Q192\n const denominator = sqrtP * (rX192 - Q192)\n vDelta = divTrunc(numerator, denominator)\n }\n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n if (isPut) {\n return vDelta\n }\n\n // Call: add debt delta and ITM delta\n const debtDelta = -m\n\n const itmDelta =\n mintTick === undefined\n ? 0n\n : (() => {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itmDelta = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itmDelta = (1 - K/Pm) * m = (Pm - K) * m / Pm\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const PmX192 = sqrtPm * sqrtPm // X192\n const KX192 = sqrtK * sqrtK // X192\n\n // itmDelta = (1 - K/Pm) * m = (PmX192 - KX192) * m / PmX192\n return divTrunc((PmX192 - KX192) * m, PmX192)\n } else {\n // In range: itmDelta = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // sqrt(K/Pm) = sqrtK / sqrtPm (both X96, so scale cancels)\n // But we need (sqrt(r) - sqrt(K/Pm))^2, so work in X96:\n // sqrtKPm = sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = (sqrtK * Q96) / sqrtPm // X96\n\n // (sqrt(r) - sqrt(K/Pm))^2 = (sqrtR - sqrtKPmX96)^2 / 2^192\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n\n // itmDelta = m * diffSqX192 / 2^192 / (rX192 / 2^192 - 1)\n // = m * diffSqX192 / (rX192 - 2^192)\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n })()\n\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n}\n\n/** Convert a delta between token frames at the current pool tick. */\nexport function toVaultFrameAtTick(\n delta: bigint,\n fromAsset: bigint,\n vaultAssetIndex: 0n | 1n,\n currentTick: bigint,\n flipSignOnAssetInversion = false,\n): bigint {\n if (fromAsset === vaultAssetIndex) return delta\n const sqrtPriceX96 = tickToSqrtPriceX96(currentTick)\n const converted =\n vaultAssetIndex === 0n\n ? (delta * Q192) / (sqrtPriceX96 * sqrtPriceX96)\n : (delta * sqrtPriceX96 * sqrtPriceX96) / Q192\n return flipSignOnAssetInversion ? -converted : converted\n}\n\n/**\n * Calculate one leg's wallet-aware delta in the vault asset frame.\n *\n * Width-zero loans and credits must be evaluated directly in the vault frame.\n * Option legs remain in their natural leg frame until converted at the mark tick.\n */\nexport function getLegDeltaInVaultFrame(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n vaultAssetIndex: 0n | 1n,\n): bigint {\n if (leg.width === 0n) {\n return getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n vaultAssetIndex,\n )\n }\n\n const legDelta = getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n )\n return toVaultFrameAtTick(legDelta, leg.asset, vaultAssetIndex, currentTick, true)\n}\n\n/**\n * Calculate the gamma (dollar gamma) of a single leg.\n *\n * Formula: gamma = (m * sqrt(K * P * r)) / (2 * (r - 1))\n * where:\n * - m = positionSize * optionRatio (with sign based on long/short)\n * - K = strike price (numeraire/asset)\n * - P = current price (numeraire/asset)\n * - r = 1.0001^(width*tickSpacing/2) ≈ 1 (dimensionless ratio)\n *\n * Uses sqrtPriceX96 arithmetic:\n * - sqrt(K*P*r) = tickToSqrtPriceX96(strikeₜ + currentₜ + widthₜ/2)\n * - Keeps X96/X192 precision until final division\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg gamma in numeraire token smallest units\n */\nexport function getLegGamma(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n\n // Convert to quote-denominated ticks (negate if asset is token0)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n // True loan: no gamma\n if (leg.width === 0n) return 0n\n\n // Narrow option whose halfWidth rounds to 0: no curvature (denominator 2*(r-1)=0)\n if (halfWidthTick === 0n) return 0n\n\n // Range check: gamma is zero outside [strike - halfWidth, strike + halfWidth]\n // This works in both normal and inverted tick space\n if (qCurrentTick < qStrikeTick - halfWidthTick || qCurrentTick > qStrikeTick + halfWidthTick) {\n return 0n\n }\n\n // Position size with sign: gamma uses inverted multiplier (long = positive, short = negative)\n const m = leg.isLong ? positionSize * leg.optionRatio : -(positionSize * leg.optionRatio)\n\n // sqrt(K * P * r) using tick addition: sqrt(K*P*r) = sqrt(1.0001^(K_tick + P_tick + r_tick))\n const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick) // X96 scale\n\n // r = 1.0001^(halfWidthTick), compute as (sqrtR)^2 to maintain precision\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96 scale\n const rX192 = sqrtR * sqrtR // X192 scale: r * 2^192\n\n // gamma = m * sqrt(K*P*r) / (2 * (r - 1))\n // = m * (sqrtKPR / 2^96) / (2 * (rX192/2^192 - 1))\n // = m * sqrtKPR * 2^192 / (2^96 * 2 * (rX192 - 2^192))\n // = m * sqrtKPR * 2^96 / (2 * (rX192 - 2^192))\n const numerator = m * sqrtKPR * Q96 // [asset] * [numeraire/asset * 2^96] * 2^96 = [numeraire * 2^192]\n const denominator = 2n * (rX192 - Q192) // 2 * (r - 1) in X192 scale\n\n return divTrunc(numerator, denominator) // [numeraire]\n}\n\n// --- Position-Level Aggregates ---\n\n/**\n * Parameters for position-level greek calculations.\n */\nexport interface PositionGreeksInput {\n /** Position legs */\n legs: TokenIdLeg[]\n /** Current pool tick */\n currentTick: bigint\n /** Tick at position mint */\n mintTick: bigint\n /** Position size in asset token smallest units */\n positionSize: bigint\n /** Pool tick spacing */\n poolTickSpacing: bigint\n /** Optional override for leg.asset on all legs (0n = token0 is asset, 1n = token1) */\n assetIndex?: bigint\n /**\n * How width=0 (loan/credit) legs were opened. When provided, `calculatePositionValue`\n * returns the NET user-experienced payoff for those legs (Zap = ±1 line, Cover = flat)\n * instead of the debt-only value. Leave undefined for delta/greeks aggregation, which\n * accounts for the held collateral separately.\n */\n swapAtMint?: boolean\n}\n\n/**\n * Calculate total value across all legs.\n */\nexport function calculatePositionValue(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const definedRisk = isDefinedRisk(legs)\n\n // Fast path: without swapAtMint there is no width=0 net-payoff (delta/greeks aggregation),\n // so no ITM netting is needed — value each leg independently.\n if (swapAtMint === undefined) {\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n ),\n 0n,\n )\n }\n\n // Pass 1: accumulate each option leg's mint-time ITM into a per-side notional pool. Under\n // swapAtMint the ITM was zapped into the other token, so a width=0 credit/loan that was\n // created to neutralize it (see getLegNetValueWidth0) should net against this pool instead\n // of adding a duplicate swap line. Puts contribute numeraire ITM; calls contribute asset ITM.\n let numeraireItmPool = 0n\n let assetItmPool = 0n\n for (const leg of legs) {\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n if (leg.width === 0n || halfWidthTick === 0n) continue // not a valued option leg\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n if (isPut) numeraireItmPool += itm\n else assetItmPool += itm\n }\n\n // Pass 2: sum leg values, netting width=0 legs against the matching ITM pool (consumed once).\n let sum = 0n\n for (const leg of legs) {\n if (leg.width === 0n) {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n const offset = borrowsAsset ? assetItmPool : numeraireItmPool\n if (borrowsAsset) assetItmPool = 0n\n else numeraireItmPool = 0n\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n sum += getLegNetValueWidth0(\n leg,\n m,\n qCurrentTick,\n qMintTick,\n isAssetToken0,\n swapAtMint,\n offset,\n )\n } else {\n sum += getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n )\n }\n }\n return sum\n}\n\n/**\n * Calculate total delta across all legs.\n */\nexport function calculatePositionDelta(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate debt-only position delta in a single target asset frame.\n *\n * Option legs are first valued in their natural `leg.asset` frame, then\n * converted into `assetIndex` using the current pool price. Width-zero legs\n * are evaluated directly in the target frame.\n *\n * Width=0 loan/credit legs include only their debt obligation. The held-token\n * side must be added separately from account collateral balances, preventing a\n * zap from being counted once in the position and again in collateral.\n */\nexport function calculatePositionDeltaDebtOnly(\n input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDeltaInVaultFrame(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate total gamma across all legs.\n */\nexport function calculatePositionGamma(input: PositionGreeksInput): bigint {\n const { legs, currentTick, positionSize, poolTickSpacing, assetIndex } = input\n\n return legs.reduce(\n (sum, leg) => sum + getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex),\n 0n,\n )\n}\n\n/**\n * Position greeks result.\n */\nexport interface PositionGreeksResult {\n /** Position value in numeraire token smallest units */\n value: bigint\n /** Position delta in asset token smallest units */\n delta: bigint\n /** Position gamma in numeraire token smallest units */\n gamma: bigint\n}\n\n/**\n * Calculate all greeks for a position.\n */\nexport function calculatePositionGreeks(input: PositionGreeksInput): PositionGreeksResult {\n return {\n value: calculatePositionValue(input),\n delta: calculatePositionDelta(input),\n gamma: calculatePositionGamma(input),\n }\n}\n\n// --- Portfolio (Multi-Position) Aggregates ---\n\n/**\n * Aggregate value across multiple independent positions.\n *\n * Each entry is valued with its OWN `positionSize`, `mintTick`, and legs, then\n * summed. Do NOT collapse multiple positions into one synthetic `PositionGreeksInput`\n * with a shared `positionSize` — `m = positionSize * optionRatio` is per-position, so a\n * shared size double-counts (and integer `optionRatio` cannot encode fractional shares).\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total value in numeraire token smallest units\n */\nexport function calculatePortfolioValue(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionValue(input), 0n)\n}\n\n/**\n * Aggregate delta across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePortfolioDelta(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionDelta(input), 0n)\n}\n\n/**\n * Aggregate gamma across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total gamma in numeraire token smallest units\n */\nexport function calculatePortfolioGamma(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionGamma(input), 0n)\n}\n\n/**\n * Calculate all greeks aggregated across multiple independent positions.\n */\nexport function calculatePortfolioGreeks(positions: PositionGreeksInput[]): PositionGreeksResult {\n return {\n value: calculatePortfolioValue(positions),\n delta: calculatePortfolioDelta(positions),\n gamma: calculatePortfolioGamma(positions),\n }\n}\n\n// --- Loan/Credit Swap-Aware Delta ---\n\n/**\n * Calculate the effective delta of a loan leg accounting for swapAtMint.\n *\n * A loan borrows one token and (optionally) swaps it for the other at mint.\n * The net delta depends on whether the swap occurred:\n *\n * | Scenario | Result |\n * |-----------------------|-------------------------------------------------|\n * | No swap | 0n (hold what you owe, net zero) |\n * | Swap + borrows asset | -m (hold numeraire, owe asset → short exposure) |\n * | Swap + borrows numer. | +m (hold asset, owe numeraire → long exposure) |\n *\n * Only meaningful for legs with `width === 0n`. For options, use `getLegDelta`.\n *\n * @param leg - The loan leg\n * @param positionSize - Position size in asset token smallest units\n * @param swapAtMint - Whether the borrowed tokens were swapped at mint\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset)\n * @returns Effective delta in asset token smallest units\n */\nexport function getLoanEffectiveDelta(\n leg: TokenIdLeg,\n positionSize: bigint,\n swapAtMint: boolean,\n assetIndex?: bigint,\n): bigint {\n if (!swapAtMint) return 0n\n\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n\n return borrowsAsset ? -m : m\n}\n\n/**\n * Calculate total delta for a position, using swap-aware delta for loan legs.\n *\n * For legs with `width === 0n` (loans/credits), uses `getLoanEffectiveDelta`\n * which accounts for the swapAtMint flag. For option legs (`width > 0n`),\n * uses the standard `getLegDelta`.\n *\n * @param input - Position greeks input plus swapAtMint flag\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePositionDeltaWithSwap(\n input: PositionGreeksInput & { swapAtMint: boolean },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const optionLegs = legs.filter((l) => l.width !== 0n)\n const definedRisk = isDefinedRisk(optionLegs)\n\n return legs.reduce((sum, leg) => {\n if (leg.width === 0n) {\n return sum + getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex)\n }\n return (\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n )\n )\n }, 0n)\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,MAAM,OAAO;;;;AAiE1B,MAAa,YAAY;;;;AAKzB,MAAa,WAAW;;;;;AAMxB,MAAa,8BAA8B,MAAM;;;;;AAMjD,MAAa,6BAA6B,MAAM,OAAO;;;;ACjFvD,MAAMA,SAAO,MAAM;AAqGnB,SAAgB,mBAAmBC,MAAsB;AACvD,KAAI,OAAO,YAAY,OAAO,SAC5B,OAAM,IAAI,WAAW;CAGvB,MAAM,UAAU,OAAO,MAAM,OAAO;CAEpC,IAAI,SACD,UAAU,UAAU,KACjB,sCACA;AACN,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,UAAU,GAAI,SAAS,QAAQ,uCAAwC;AACtF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,WAAW,GAAI,SAAS,QAAQ,uCAAwC;AACvF,MAAK,UAAU,WAAW,G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