@panoptic-eng/sdk 1.0.38 → 1.0.40

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.
Files changed (81) hide show
  1. package/dist/cow/index.d.ts +804 -5
  2. package/dist/cow/index.d.ts.map +1 -0
  3. package/dist/cow/index.js +5268 -5
  4. package/dist/cow/index.js.map +1 -0
  5. package/dist/{cow-DB8siv6M.js → cow-tRUtAUZy.js} +2 -3
  6. package/dist/{getTrackedPositionIds-zYPIs5dt.js → getTrackedPositionIds-ms3W9dYB.js} +1 -2
  7. package/dist/greeks-GysWXct-.js +1 -2
  8. package/dist/index.d.ts +5752 -4
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +11952 -2130
  11. package/dist/index.js.map +1 -1
  12. package/dist/{irm-ChkvYphK.js → irm-SPC2KxLA.js} +321 -3
  13. package/dist/panoptic/v2/greeks/index.d.ts +277 -4
  14. package/dist/panoptic/v2/greeks/index.d.ts.map +1 -0
  15. package/dist/panoptic/v2/greeks/index.js +620 -2
  16. package/dist/panoptic/v2/greeks/index.js.map +1 -0
  17. package/dist/panoptic/v2/index.d.ts +14633 -7
  18. package/dist/panoptic/v2/index.d.ts.map +1 -0
  19. package/dist/panoptic/v2/index.js +27875 -9
  20. package/dist/panoptic/v2/index.js.map +1 -0
  21. package/dist/panoptic/v2/react-public.d.ts +14779 -15
  22. package/dist/panoptic/v2/react-public.d.ts.map +1 -1
  23. package/dist/panoptic/v2/react-public.js +29463 -89
  24. package/dist/panoptic/v2/react-public.js.map +1 -1
  25. package/dist/{router-tCRa0ekE.js → router-BTfbaRfg.js} +2 -3
  26. package/dist/{router-BCUJkY8j.js → router-mLWy0MD9.js} +3 -4
  27. package/dist/test/index.d.ts +3 -3
  28. package/dist/test/index.d.ts.map +1 -1
  29. package/dist/test/index.js +2 -2
  30. package/dist/{transactionFees-CVi2TrJh.js → transactionFees-C_Qx07mx.js} +1 -2
  31. package/dist/uniswap/index.d.ts +813 -78
  32. package/dist/uniswap/index.d.ts.map +1 -1
  33. package/dist/uniswap/index.js +5884 -13
  34. package/dist/uniswap/index.js.map +1 -1
  35. package/dist/{v2-BxtzpUnV.js → v2-DG7qG6di.js} +4 -5
  36. package/dist/vault-transaction-fees.d.ts +63 -2
  37. package/dist/vault-transaction-fees.d.ts.map +1 -0
  38. package/dist/vault-transaction-fees.js +174 -2
  39. package/dist/vault-transaction-fees.js.map +1 -0
  40. package/dist/{writes-D3bj1wth.js → writes-Xp9Wa8GQ.js} +2 -3
  41. package/dist/zodiac/index.d.ts.map +1 -1
  42. package/package.json +4 -3
  43. package/dist/cow/types.d.ts +0 -4
  44. package/dist/cow/types.js +0 -0
  45. package/dist/cow-DB8siv6M.js.map +0 -1
  46. package/dist/getTrackedPositionIds-zYPIs5dt.js.map +0 -1
  47. package/dist/greeks-GysWXct-.js.map +0 -1
  48. package/dist/hypoVault/vaultDisplayNames.d.ts +0 -2
  49. package/dist/hypoVault/vaultDisplayNames.js +0 -4
  50. package/dist/index-BhEBx83X.d.ts +0 -9760
  51. package/dist/index-BhEBx83X.d.ts.map +0 -1
  52. package/dist/index-Bo9tHtD7.d.ts +0 -1901
  53. package/dist/index-Bo9tHtD7.d.ts.map +0 -1
  54. package/dist/index-CttjEZ-S.d.ts +0 -275
  55. package/dist/index-CttjEZ-S.d.ts.map +0 -1
  56. package/dist/index-DktZq9Kb.d.ts +0 -261
  57. package/dist/index-DktZq9Kb.d.ts.map +0 -1
  58. package/dist/irm-ChkvYphK.js.map +0 -1
  59. package/dist/irm-D2WTHtuo.d.ts +0 -5667
  60. package/dist/irm-D2WTHtuo.d.ts.map +0 -1
  61. package/dist/irm-D5plRhpB.d.ts +0 -32
  62. package/dist/irm-D5plRhpB.d.ts.map +0 -1
  63. package/dist/panoptic/v2/types/index.d.ts +0 -3
  64. package/dist/panoptic/v2/types/index.js +0 -0
  65. package/dist/quote-DeHNUR0Z.d.ts +0 -52
  66. package/dist/quote-DeHNUR0Z.d.ts.map +0 -1
  67. package/dist/router-BCUJkY8j.js.map +0 -1
  68. package/dist/router-tCRa0ekE.js.map +0 -1
  69. package/dist/src-CRAtPwWk.js +0 -321
  70. package/dist/src-CRAtPwWk.js.map +0 -1
  71. package/dist/transactionFees-CVi2TrJh.js.map +0 -1
  72. package/dist/transactionFees-DzDyt50k.d.ts +0 -63
  73. package/dist/transactionFees-DzDyt50k.d.ts.map +0 -1
  74. package/dist/types-Cad5m4Td.d.ts +0 -246
  75. package/dist/types-Cad5m4Td.d.ts.map +0 -1
  76. package/dist/types-DM0nxlZr.d.ts +0 -128
  77. package/dist/types-DM0nxlZr.d.ts.map +0 -1
  78. package/dist/v2-BxtzpUnV.js.map +0 -1
  79. package/dist/vaultDisplayNames-CKpz51Hu.js +0 -0
  80. package/dist/vaultDisplayNames-Q6htUcch.d.ts +0 -2
  81. package/dist/writes-D3bj1wth.js.map +0 -1
@@ -1,3 +1,621 @@
1
- import { calculatePortfolioDelta, calculatePortfolioGamma, calculatePortfolioGreeks, calculatePortfolioValue, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionDeltaWithSwap, calculatePositionGamma, calculatePositionGreeks, calculatePositionValue, getLegDelta, getLegDeltaInVaultFrame, getLegGamma, getLegNetValueWidth0, getLegValue, getLoanEffectiveDelta, isCall, isDefinedRisk, toVaultFrameAtTick } from "../../../greeks-GysWXct-.js";
1
+ //#region src/panoptic/v2/utils/constants.ts
2
+ /**
3
+ * Constants for the Panoptic v2 SDK.
4
+ * @module v2/utils/constants
5
+ */
6
+ /**
7
+ * WAD constant (10^18) used for fixed-point arithmetic.
8
+ * Commonly used for spread calculations and other WAD-scaled values.
9
+ */
10
+ const WAD = 10n ** 18n;
11
+ /**
12
+ * Minimum tick value for Uniswap v3/v4 pools.
13
+ */
14
+ const MIN_TICK = -887272n;
15
+ /**
16
+ * Maximum tick value for Uniswap v3/v4 pools.
17
+ */
18
+ const MAX_TICK = 887272n;
2
19
 
3
- export { calculatePortfolioDelta, calculatePortfolioGamma, calculatePortfolioGreeks, calculatePortfolioValue, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionDeltaWithSwap, calculatePositionGamma, calculatePositionGreeks, calculatePositionValue, getLegDelta, getLegDeltaInVaultFrame, getLegGamma, getLegNetValueWidth0, getLegValue, getLoanEffectiveDelta, isCall, isDefinedRisk, toVaultFrameAtTick };
20
+ //#endregion
21
+ //#region src/panoptic/v2/formatters/tick.ts
22
+ const Q192$1 = 1n << 192n;
23
+ function tickToSqrtPriceX96(tick) {
24
+ if (tick < MIN_TICK || tick > MAX_TICK) throw new RangeError("Tick out of bounds");
25
+ const absTick = tick < 0n ? -tick : tick;
26
+ let ratio = (absTick & 0x1n) !== 0n ? 0xfffcb933bd6fad37aa2d162d1a594001n : 0x100000000000000000000000000000000n;
27
+ if ((absTick & 0x2n) !== 0n) ratio = ratio * 0xfff97272373d413259a46990580e213an >> 128n;
28
+ if ((absTick & 0x4n) !== 0n) ratio = ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn >> 128n;
29
+ if ((absTick & 0x8n) !== 0n) ratio = ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n >> 128n;
30
+ if ((absTick & 0x10n) !== 0n) ratio = ratio * 0xffcb9843d60f6159c9db58835c926644n >> 128n;
31
+ if ((absTick & 0x20n) !== 0n) ratio = ratio * 0xff973b41fa98c081472e6896dfb254c0n >> 128n;
32
+ if ((absTick & 0x40n) !== 0n) ratio = ratio * 0xff2ea16466c96a3843ec78b326b52861n >> 128n;
33
+ if ((absTick & 0x80n) !== 0n) ratio = ratio * 0xfe5dee046a99a2a811c461f1969c3053n >> 128n;
34
+ if ((absTick & 0x100n) !== 0n) ratio = ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n >> 128n;
35
+ if ((absTick & 0x200n) !== 0n) ratio = ratio * 0xf987a7253ac413176f2b074cf7815e54n >> 128n;
36
+ if ((absTick & 0x400n) !== 0n) ratio = ratio * 0xf3392b0822b70005940c7a398e4b70f3n >> 128n;
37
+ if ((absTick & 0x800n) !== 0n) ratio = ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n >> 128n;
38
+ if ((absTick & 0x1000n) !== 0n) ratio = ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n >> 128n;
39
+ if ((absTick & 0x2000n) !== 0n) ratio = ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n >> 128n;
40
+ if ((absTick & 0x4000n) !== 0n) ratio = ratio * 0x70d869a156d2a1b890bb3df62baf32f7n >> 128n;
41
+ if ((absTick & 0x8000n) !== 0n) ratio = ratio * 0x31be135f97d08fd981231505542fcfa6n >> 128n;
42
+ if ((absTick & 0x10000n) !== 0n) ratio = ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n >> 128n;
43
+ if ((absTick & 0x20000n) !== 0n) ratio = ratio * 0x5d6af8dedb81196699c329225ee604n >> 128n;
44
+ if ((absTick & 0x40000n) !== 0n) ratio = ratio * 0x2216e584f5fa1ea926041bedfe98n >> 128n;
45
+ if ((absTick & 0x80000n) !== 0n) ratio = ratio * 0x48a170391f7dc42444e8fa2n >> 128n;
46
+ if (tick > 0n) ratio = ((1n << 256n) - 1n) / ratio;
47
+ const remainderMask = (1n << 32n) - 1n;
48
+ const sqrtPriceX96 = (ratio >> 32n) + ((ratio & remainderMask) === 0n ? 0n : 1n);
49
+ return sqrtPriceX96;
50
+ }
51
+ const MIN_SQRT_PRICE_X96 = tickToSqrtPriceX96(MIN_TICK);
52
+ const MAX_SQRT_PRICE_X96 = tickToSqrtPriceX96(MAX_TICK);
53
+
54
+ //#endregion
55
+ //#region src/panoptic/v2/greeks/index.ts
56
+ /** Fixed-point scale constants for sqrtPriceX96 arithmetic */
57
+ const Q96 = 1n << 96n;
58
+ const Q192 = 1n << 192n;
59
+ /**
60
+ * Convert tick to quote-denominated tick based on asset direction.
61
+ *
62
+ * When isAssetToken0 = true (asset is token0, numeraire is token1):
63
+ * - Tick already encodes price as token1/token0 (numeraire per asset)
64
+ * - Return tick unchanged
65
+ *
66
+ * When isAssetToken0 = false (asset is token1, numeraire is token0):
67
+ * - Tick encodes price as token1/token0, but we need token0/token1 (numeraire per asset)
68
+ * - Invert by negating: 1/price = 1.0001^(-tick)
69
+ */
70
+ function quoteTick(tick, isAssetToken0) {
71
+ return isAssetToken0 ? tick : -tick;
72
+ }
73
+ /**
74
+ * Divide with truncation toward zero (matches Solidity division behavior).
75
+ *
76
+ * JavaScript bigint division uses floor (toward negative infinity), but Solidity
77
+ * truncates toward zero. For on-chain fidelity, we must match Solidity.
78
+ *
79
+ * Example:
80
+ * - Solidity: -7 / 2 = -3 (truncate toward zero)
81
+ * - JS bigint: -7n / 2n = -4n (floor toward -∞)
82
+ * - This function: divTrunc(-7n, 2n) = -3n ✓
83
+ */
84
+ function divTrunc(numerator, denominator) {
85
+ if (denominator === 0n) return 0n;
86
+ const quotient = numerator / denominator;
87
+ const remainder = numerator % denominator;
88
+ if (numerator < 0n !== denominator < 0n && remainder !== 0n) return quotient + 1n;
89
+ return quotient;
90
+ }
91
+ /** Resolve isAssetToken0: optional assetIndex overrides leg.asset */
92
+ function resolveAssetDirection(leg, assetIndex) {
93
+ return assetIndex !== void 0 ? assetIndex === 0n : leg.asset === 0n;
94
+ }
95
+ /**
96
+ * Compute the tokenType-denominated notional of a width=0 (loan/credit) leg.
97
+ *
98
+ * When leg.asset !== leg.tokenType, positionSize is in leg.asset units and
99
+ * the borrowed notional is encoded via leg.strike: notional_tokenType_raw =
100
+ * positionSize_raw × 1.0001^strike (a raw-to-raw ratio, unquoted by pool direction).
101
+ * When leg.asset === leg.tokenType, m is already the notional (old convention).
102
+ *
103
+ * `m > 0` for loans (isLong=false), `m < 0` for credits (isLong=true), so the
104
+ * returned notional is signed the same way.
105
+ */
106
+ function computeWidth0Notional(leg, m) {
107
+ const scaleByStrike = leg.asset !== leg.tokenType;
108
+ if (!scaleByStrike) return m;
109
+ const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike;
110
+ const sqrtKraw = tickToSqrtPriceX96(signedStrike);
111
+ const KrawX192 = sqrtKraw * sqrtKraw;
112
+ return divTrunc(m * KrawX192, Q192);
113
+ }
114
+ /**
115
+ * Calculate value for a width=0 (loan/credit) leg.
116
+ * Width=0 means the range is a single tick (the strike), so there's no meaningful
117
+ * "in range" — we use the below/above formulas which avoid division by (r-1)=0.
118
+ *
119
+ * This is the DEBT-ONLY value (the borrowed/lent obligation), used by delta/greeks
120
+ * aggregation where the held-collateral side lives in a separate wallet/CT term. For
121
+ * a standalone payoff chart that must reflect the net user-experienced payoff (which
122
+ * depends on Zap vs Cover-at-mint), use `getLegNetValueWidth0`.
123
+ */
124
+ function getLegValueWidth0(leg, m, qCurrentTick, qStrikeTick, qMintTick, isAssetToken0, _definedRisk) {
125
+ const borrowsAsset = isCall(leg.tokenType, isAssetToken0);
126
+ const notional = computeWidth0Notional(leg, m);
127
+ if (borrowsAsset) {
128
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
129
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
130
+ const PX192 = sqrtP * sqrtP;
131
+ const PmX192 = sqrtPm * sqrtPm;
132
+ return divTrunc(-notional * (PX192 - PmX192), Q192);
133
+ } else return 0n;
134
+ }
135
+ /**
136
+ * Calculate the NET (user-experienced) payoff value for a width=0 (loan/credit) leg.
137
+ *
138
+ * Unlike `getLegValueWidth0` (debt-only), this includes the collateral/holding side and
139
+ * therefore depends on how the position was opened:
140
+ *
141
+ * - **Cover at mint** (`swapAtMint = false`): the collateral is sourced in the SAME token as
142
+ * the debt/credit, so the holding side exactly offsets it → net PnL is FLAT (0 everywhere,
143
+ * mint-relative), regardless of which token the leg is denominated in.
144
+ * - **Zap** (`swapAtMint = true`): the collateral is sourced in the OTHER token, leaving a
145
+ * ±1-delta line in the asset (ETH), anchored to 0 at the mint price:
146
+ * - USDC loan → zap to ETH: +1 (long ETH)
147
+ * - ETH loan → zap to USDC: −1 (short ETH)
148
+ * - USDC credit ← zap from ETH: −1 (short ETH)
149
+ * - ETH credit ← zap from USDC: +1 (long ETH)
150
+ *
151
+ * @returns Net leg value in numeraire token smallest units (mint-relative PnL).
152
+ */
153
+ function getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint, itmOffsetNotional = 0n) {
154
+ if (!swapAtMint) return 0n;
155
+ const borrowsAsset = isCall(leg.tokenType, isAssetToken0);
156
+ const notional = computeWidth0Notional(leg, m) + itmOffsetNotional;
157
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
158
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
159
+ const PX192 = sqrtP * sqrtP;
160
+ const PmX192 = sqrtPm * sqrtPm;
161
+ if (borrowsAsset) return divTrunc(-notional * (PX192 - PmX192), Q192);
162
+ return divTrunc(notional * PX192, PmX192) - notional;
163
+ }
164
+ /**
165
+ * Compute the mint-time ITM (in-the-money) adjustment for an option leg.
166
+ *
167
+ * This is the `itm` baseline used by {@link getLegValue}: the amount by which the
168
+ * position was already ITM at mint, expressed in the leg's natural units:
169
+ * - Puts: numeraire units (added directly to the put's `debt*K + v` value).
170
+ * - Calls: asset-ratio units (the call value multiplies it by price: `itm*P`/`itm*Pm`).
171
+ *
172
+ * Extracted so callers (e.g. {@link calculatePositionValue}) can build a per-side ITM
173
+ * notional pool to net width=0 credit/loan legs against — an ITM-neutralizing credit
174
+ * was sized to offset exactly this amount, so it should not add a spurious swap line.
175
+ */
176
+ function computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut) {
177
+ if (isPut) {
178
+ if (qMintTick < qStrikeTick - halfWidthTick) {
179
+ const sqrtK$1 = tickToSqrtPriceX96(qStrikeTick);
180
+ const sqrtPm$2 = tickToSqrtPriceX96(qMintTick);
181
+ const KX192 = sqrtK$1 * sqrtK$1;
182
+ const PmX192 = sqrtPm$2 * sqrtPm$2;
183
+ return divTrunc(m * (KX192 - PmX192), Q192);
184
+ } else if (qMintTick > qStrikeTick + halfWidthTick) return 0n;
185
+ const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick);
186
+ const sqrtPm$1 = tickToSqrtPriceX96(qMintTick);
187
+ const sqrtR$1 = tickToSqrtPriceX96(halfWidthTick);
188
+ const rX192$1 = sqrtR$1 * sqrtR$1;
189
+ const diff$1 = sqrtKR - sqrtPm$1;
190
+ const diffSqX192$1 = diff$1 * diff$1;
191
+ return divTrunc(m * diffSqX192$1, rX192$1 - Q192);
192
+ }
193
+ if (qMintTick < qStrikeTick - halfWidthTick) return 0n;
194
+ else if (qMintTick > qStrikeTick + halfWidthTick) {
195
+ const sqrtK$1 = tickToSqrtPriceX96(qStrikeTick);
196
+ const sqrtPm$1 = tickToSqrtPriceX96(qMintTick);
197
+ const KX192 = sqrtK$1 * sqrtK$1;
198
+ const PmX192 = sqrtPm$1 * sqrtPm$1;
199
+ return divTrunc(m * (PmX192 - KX192), PmX192);
200
+ }
201
+ const sqrtR = tickToSqrtPriceX96(halfWidthTick);
202
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
203
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
204
+ const rX192 = sqrtR * sqrtR;
205
+ const sqrtKPmX96 = divTrunc(sqrtK * Q96, sqrtPm);
206
+ const diff = sqrtR - sqrtKPmX96;
207
+ const diffSqX192 = diff * diff;
208
+ return divTrunc(m * diffSqX192, rX192 - Q192);
209
+ }
210
+ /**
211
+ * Check if leg is a call option (vs put).
212
+ *
213
+ * A call is when the leg moves the asset token:
214
+ * - If asset is token0: call when tokenType=0
215
+ * - If asset is token1: call when tokenType=1
216
+ */
217
+ function isCall(tokenType, isAssetToken0) {
218
+ return isAssetToken0 ? tokenType === 0n : tokenType === 1n;
219
+ }
220
+ /**
221
+ * Check if position has defined risk (is a spread).
222
+ *
223
+ * A position is defined risk if it has 2+ legs of the same tokenType
224
+ * with both long and short exposure.
225
+ */
226
+ function isDefinedRisk(legs) {
227
+ if (legs.length < 2) return false;
228
+ for (const tt of [0n, 1n]) {
229
+ const group = legs.filter((l) => l.tokenType === tt);
230
+ if (group.length >= 2 && group.some((l) => l.isLong) && group.some((l) => !l.isLong)) return true;
231
+ }
232
+ return false;
233
+ }
234
+ /**
235
+ * Calculate the value of a single leg.
236
+ *
237
+ * Value represents the current P&L of the position in numeraire token units.
238
+ * Combines base value (from Panoptic's piecewise formula), debt, and ITM adjustment.
239
+ *
240
+ * Uses sqrtPriceX96 for all calculations to maintain precision and on-chain fidelity.
241
+ *
242
+ * @param leg - The leg to calculate
243
+ * @param currentTick - Current pool tick
244
+ * @param mintTick - Tick at position mint
245
+ * @param positionSize - Position size in asset token smallest units
246
+ * @param poolTickSpacing - Pool tick spacing
247
+ * @param definedRisk - Whether position is defined risk
248
+ * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)
249
+ * @returns Leg value in numeraire token smallest units
250
+ */
251
+ function getLegValue(leg, currentTick, mintTick, positionSize, poolTickSpacing, definedRisk, assetIndex, swapAtMint) {
252
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
253
+ const qCurrentTick = quoteTick(currentTick, isAssetToken0);
254
+ const qMintTick = quoteTick(mintTick, isAssetToken0);
255
+ const qStrikeTick = quoteTick(leg.strike, isAssetToken0);
256
+ const halfWidthTick = leg.width * poolTickSpacing / 2n;
257
+ const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio;
258
+ if (leg.width === 0n && swapAtMint !== void 0) return getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint);
259
+ if (halfWidthTick === 0n) return getLegValueWidth0(leg, m, qCurrentTick, qStrikeTick, qMintTick, isAssetToken0, definedRisk);
260
+ let v;
261
+ if (qCurrentTick < qStrikeTick - halfWidthTick) {
262
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
263
+ const PX192 = sqrtP * sqrtP;
264
+ v = divTrunc(m * PX192, Q192);
265
+ } else if (qCurrentTick > qStrikeTick + halfWidthTick) {
266
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
267
+ const KX192 = sqrtK * sqrtK;
268
+ v = divTrunc(m * KX192, Q192);
269
+ } else {
270
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
271
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
272
+ const sqrtPKR = tickToSqrtPriceX96(qCurrentTick + qStrikeTick + halfWidthTick);
273
+ const sqrtR = tickToSqrtPriceX96(halfWidthTick);
274
+ const PX192 = sqrtP * sqrtP;
275
+ const KX192 = sqrtK * sqrtK;
276
+ const rX192 = sqrtR * sqrtR;
277
+ const numerator = m * (2n * sqrtPKR * Q96 - PX192 - KX192);
278
+ const denominator = rX192 - Q192;
279
+ v = divTrunc(numerator, denominator);
280
+ }
281
+ const debt = -m;
282
+ const isPut = !isCall(leg.tokenType, isAssetToken0);
283
+ const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut);
284
+ if (isPut) {
285
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
286
+ const KX192 = sqrtK * sqrtK;
287
+ const debtK = divTrunc(debt * KX192, Q192);
288
+ return debtK + v + itm;
289
+ } else {
290
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
291
+ const PX192 = sqrtP * sqrtP;
292
+ const debtP = divTrunc(debt * PX192, Q192);
293
+ if (definedRisk) {
294
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
295
+ const PmX192 = sqrtPm * sqrtPm;
296
+ const itmPm = divTrunc(itm * PmX192, Q192);
297
+ return debtP + v + itmPm;
298
+ } else {
299
+ const itmP = divTrunc(itm * PX192, Q192);
300
+ return debtP + v + itmP;
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Calculate the delta of a single leg.
306
+ *
307
+ * Delta is the rate of change of position value with respect to price.
308
+ * For puts: delta = vDelta
309
+ * For calls: delta = debtDelta + vDelta + itmDelta (if not defined risk)
310
+ *
311
+ * Uses sqrtPriceX96 for all price calculations to maintain precision.
312
+ *
313
+ * @param leg - The leg to calculate
314
+ * @param currentTick - Current pool tick
315
+ * @param positionSize - Position size in asset token smallest units
316
+ * @param poolTickSpacing - Pool tick spacing
317
+ * @param mintTick - Tick at mint (optional, for ITM adjustment)
318
+ * @param definedRisk - Whether position is defined risk
319
+ * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)
320
+ * @returns Leg delta in asset token smallest units
321
+ */
322
+ function getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, assetIndex) {
323
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
324
+ const qCurrentTick = quoteTick(currentTick, isAssetToken0);
325
+ const qStrikeTick = quoteTick(leg.strike, isAssetToken0);
326
+ const halfWidthTick = leg.width * poolTickSpacing / 2n;
327
+ const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio;
328
+ if (leg.width === 0n) {
329
+ const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n;
330
+ if (!borrowsAsset) return 0n;
331
+ if (leg.asset === leg.tokenType) return -m;
332
+ const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike;
333
+ const sqrtKraw = tickToSqrtPriceX96(signedStrike);
334
+ const KrawX192 = sqrtKraw * sqrtKraw;
335
+ const notional = divTrunc(m * KrawX192, Q192);
336
+ return -notional;
337
+ }
338
+ if (halfWidthTick === 0n) {
339
+ const vDelta$1 = qCurrentTick <= qStrikeTick ? m : 0n;
340
+ const isPut$1 = !isCall(leg.tokenType, isAssetToken0);
341
+ if (isPut$1) return vDelta$1;
342
+ const debtDelta$1 = -m;
343
+ let itmDelta$1 = 0n;
344
+ if (mintTick !== void 0 && !definedRisk) {
345
+ const qMintTick = quoteTick(mintTick, isAssetToken0);
346
+ if (qMintTick > qStrikeTick) {
347
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
348
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
349
+ const PmX192 = sqrtPm * sqrtPm;
350
+ const KX192 = sqrtK * sqrtK;
351
+ itmDelta$1 = divTrunc((PmX192 - KX192) * m, PmX192);
352
+ }
353
+ }
354
+ return definedRisk ? debtDelta$1 + vDelta$1 : debtDelta$1 + vDelta$1 + itmDelta$1;
355
+ }
356
+ let vDelta;
357
+ if (qCurrentTick < qStrikeTick - halfWidthTick) vDelta = m;
358
+ else if (qCurrentTick > qStrikeTick + halfWidthTick) vDelta = 0n;
359
+ else {
360
+ const sqrtP = tickToSqrtPriceX96(qCurrentTick);
361
+ const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick);
362
+ const sqrtR = tickToSqrtPriceX96(halfWidthTick);
363
+ const rX192 = sqrtR * sqrtR;
364
+ const numerator = m * (sqrtKR - sqrtP) * Q192;
365
+ const denominator = sqrtP * (rX192 - Q192);
366
+ vDelta = divTrunc(numerator, denominator);
367
+ }
368
+ const isPut = !isCall(leg.tokenType, isAssetToken0);
369
+ if (isPut) return vDelta;
370
+ const debtDelta = -m;
371
+ const itmDelta = mintTick === void 0 ? 0n : (() => {
372
+ const qMintTick = quoteTick(mintTick, isAssetToken0);
373
+ if (qMintTick < qStrikeTick - halfWidthTick) return 0n;
374
+ else if (qMintTick > qStrikeTick + halfWidthTick) {
375
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
376
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
377
+ const PmX192 = sqrtPm * sqrtPm;
378
+ const KX192 = sqrtK * sqrtK;
379
+ return divTrunc((PmX192 - KX192) * m, PmX192);
380
+ } else {
381
+ const sqrtR = tickToSqrtPriceX96(halfWidthTick);
382
+ const sqrtK = tickToSqrtPriceX96(qStrikeTick);
383
+ const sqrtPm = tickToSqrtPriceX96(qMintTick);
384
+ const rX192 = sqrtR * sqrtR;
385
+ const sqrtKPmX96 = sqrtK * Q96 / sqrtPm;
386
+ const diff = sqrtR - sqrtKPmX96;
387
+ const diffSqX192 = diff * diff;
388
+ return divTrunc(m * diffSqX192, rX192 - Q192);
389
+ }
390
+ })();
391
+ return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta;
392
+ }
393
+ /** Convert a delta between token frames at the current pool tick. */
394
+ function toVaultFrameAtTick(delta, fromAsset, vaultAssetIndex, currentTick, flipSignOnAssetInversion = false) {
395
+ if (fromAsset === vaultAssetIndex) return delta;
396
+ const sqrtPriceX96 = tickToSqrtPriceX96(currentTick);
397
+ const converted = vaultAssetIndex === 0n ? delta * Q192 / (sqrtPriceX96 * sqrtPriceX96) : delta * sqrtPriceX96 * sqrtPriceX96 / Q192;
398
+ return flipSignOnAssetInversion ? -converted : converted;
399
+ }
400
+ /**
401
+ * Calculate one leg's wallet-aware delta in the vault asset frame.
402
+ *
403
+ * Width-zero loans and credits must be evaluated directly in the vault frame.
404
+ * Option legs remain in their natural leg frame until converted at the mark tick.
405
+ */
406
+ function getLegDeltaInVaultFrame(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, vaultAssetIndex) {
407
+ if (leg.width === 0n) return getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, vaultAssetIndex);
408
+ const legDelta = getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk);
409
+ return toVaultFrameAtTick(legDelta, leg.asset, vaultAssetIndex, currentTick, true);
410
+ }
411
+ /**
412
+ * Calculate the gamma (dollar gamma) of a single leg.
413
+ *
414
+ * Formula: gamma = (m * sqrt(K * P * r)) / (2 * (r - 1))
415
+ * where:
416
+ * - m = positionSize * optionRatio (with sign based on long/short)
417
+ * - K = strike price (numeraire/asset)
418
+ * - P = current price (numeraire/asset)
419
+ * - r = 1.0001^(width*tickSpacing/2) ≈ 1 (dimensionless ratio)
420
+ *
421
+ * Uses sqrtPriceX96 arithmetic:
422
+ * - sqrt(K*P*r) = tickToSqrtPriceX96(strikeₜ + currentₜ + widthₜ/2)
423
+ * - Keeps X96/X192 precision until final division
424
+ *
425
+ * @param leg - The leg to calculate
426
+ * @param currentTick - Current pool tick
427
+ * @param positionSize - Position size in asset token smallest units
428
+ * @param poolTickSpacing - Pool tick spacing
429
+ * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)
430
+ * @returns Leg gamma in numeraire token smallest units
431
+ */
432
+ function getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex) {
433
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
434
+ const qCurrentTick = quoteTick(currentTick, isAssetToken0);
435
+ const qStrikeTick = quoteTick(leg.strike, isAssetToken0);
436
+ const halfWidthTick = leg.width * poolTickSpacing / 2n;
437
+ if (leg.width === 0n) return 0n;
438
+ if (halfWidthTick === 0n) return 0n;
439
+ if (qCurrentTick < qStrikeTick - halfWidthTick || qCurrentTick > qStrikeTick + halfWidthTick) return 0n;
440
+ const m = leg.isLong ? positionSize * leg.optionRatio : -(positionSize * leg.optionRatio);
441
+ const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick);
442
+ const sqrtR = tickToSqrtPriceX96(halfWidthTick);
443
+ const rX192 = sqrtR * sqrtR;
444
+ const numerator = m * sqrtKPR * Q96;
445
+ const denominator = 2n * (rX192 - Q192);
446
+ return divTrunc(numerator, denominator);
447
+ }
448
+ /**
449
+ * Calculate total value across all legs.
450
+ */
451
+ function calculatePositionValue(input) {
452
+ const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } = input;
453
+ const definedRisk = isDefinedRisk(legs);
454
+ if (swapAtMint === void 0) return legs.reduce((sum$1, leg) => sum$1 + getLegValue(leg, currentTick, mintTick, positionSize, poolTickSpacing, definedRisk, assetIndex, swapAtMint), 0n);
455
+ let numeraireItmPool = 0n;
456
+ let assetItmPool = 0n;
457
+ for (const leg of legs) {
458
+ const halfWidthTick = leg.width * poolTickSpacing / 2n;
459
+ if (leg.width === 0n || halfWidthTick === 0n) continue;
460
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
461
+ const qStrikeTick = quoteTick(leg.strike, isAssetToken0);
462
+ const qMintTick = quoteTick(mintTick, isAssetToken0);
463
+ const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio;
464
+ const isPut = !isCall(leg.tokenType, isAssetToken0);
465
+ const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut);
466
+ if (isPut) numeraireItmPool += itm;
467
+ else assetItmPool += itm;
468
+ }
469
+ let sum = 0n;
470
+ for (const leg of legs) if (leg.width === 0n) {
471
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
472
+ const borrowsAsset = isCall(leg.tokenType, isAssetToken0);
473
+ const offset = borrowsAsset ? assetItmPool : numeraireItmPool;
474
+ if (borrowsAsset) assetItmPool = 0n;
475
+ else numeraireItmPool = 0n;
476
+ const qCurrentTick = quoteTick(currentTick, isAssetToken0);
477
+ const qMintTick = quoteTick(mintTick, isAssetToken0);
478
+ const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio;
479
+ sum += getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint, offset);
480
+ } else sum += getLegValue(leg, currentTick, mintTick, positionSize, poolTickSpacing, definedRisk, assetIndex, swapAtMint);
481
+ return sum;
482
+ }
483
+ /**
484
+ * Calculate total delta across all legs.
485
+ */
486
+ function calculatePositionDelta(input) {
487
+ const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input;
488
+ const definedRisk = isDefinedRisk(legs);
489
+ return legs.reduce((sum, leg) => sum + getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, assetIndex), 0n);
490
+ }
491
+ /**
492
+ * Calculate debt-only position delta in a single target asset frame.
493
+ *
494
+ * Option legs are first valued in their natural `leg.asset` frame, then
495
+ * converted into `assetIndex` using the current pool price. Width-zero legs
496
+ * are evaluated directly in the target frame.
497
+ *
498
+ * Width=0 loan/credit legs include only their debt obligation. The held-token
499
+ * side must be added separately from account collateral balances, preventing a
500
+ * zap from being counted once in the position and again in collateral.
501
+ */
502
+ function calculatePositionDeltaDebtOnly(input) {
503
+ const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input;
504
+ const definedRisk = isDefinedRisk(legs);
505
+ return legs.reduce((sum, leg) => sum + getLegDeltaInVaultFrame(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, assetIndex), 0n);
506
+ }
507
+ /**
508
+ * Calculate total gamma across all legs.
509
+ */
510
+ function calculatePositionGamma(input) {
511
+ const { legs, currentTick, positionSize, poolTickSpacing, assetIndex } = input;
512
+ return legs.reduce((sum, leg) => sum + getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex), 0n);
513
+ }
514
+ /**
515
+ * Calculate all greeks for a position.
516
+ */
517
+ function calculatePositionGreeks(input) {
518
+ return {
519
+ value: calculatePositionValue(input),
520
+ delta: calculatePositionDelta(input),
521
+ gamma: calculatePositionGamma(input)
522
+ };
523
+ }
524
+ /**
525
+ * Aggregate value across multiple independent positions.
526
+ *
527
+ * Each entry is valued with its OWN `positionSize`, `mintTick`, and legs, then
528
+ * summed. Do NOT collapse multiple positions into one synthetic `PositionGreeksInput`
529
+ * with a shared `positionSize` — `m = positionSize * optionRatio` is per-position, so a
530
+ * shared size double-counts (and integer `optionRatio` cannot encode fractional shares).
531
+ *
532
+ * @param positions - One `PositionGreeksInput` per open position
533
+ * @returns Total value in numeraire token smallest units
534
+ */
535
+ function calculatePortfolioValue(positions) {
536
+ return positions.reduce((sum, input) => sum + calculatePositionValue(input), 0n);
537
+ }
538
+ /**
539
+ * Aggregate delta across multiple independent positions.
540
+ *
541
+ * See {@link calculatePortfolioValue} for why each position must keep its own
542
+ * `positionSize` rather than being merged into one synthetic position.
543
+ *
544
+ * @param positions - One `PositionGreeksInput` per open position
545
+ * @returns Total delta in asset token smallest units
546
+ */
547
+ function calculatePortfolioDelta(positions) {
548
+ return positions.reduce((sum, input) => sum + calculatePositionDelta(input), 0n);
549
+ }
550
+ /**
551
+ * Aggregate gamma across multiple independent positions.
552
+ *
553
+ * See {@link calculatePortfolioValue} for why each position must keep its own
554
+ * `positionSize` rather than being merged into one synthetic position.
555
+ *
556
+ * @param positions - One `PositionGreeksInput` per open position
557
+ * @returns Total gamma in numeraire token smallest units
558
+ */
559
+ function calculatePortfolioGamma(positions) {
560
+ return positions.reduce((sum, input) => sum + calculatePositionGamma(input), 0n);
561
+ }
562
+ /**
563
+ * Calculate all greeks aggregated across multiple independent positions.
564
+ */
565
+ function calculatePortfolioGreeks(positions) {
566
+ return {
567
+ value: calculatePortfolioValue(positions),
568
+ delta: calculatePortfolioDelta(positions),
569
+ gamma: calculatePortfolioGamma(positions)
570
+ };
571
+ }
572
+ /**
573
+ * Calculate the effective delta of a loan leg accounting for swapAtMint.
574
+ *
575
+ * A loan borrows one token and (optionally) swaps it for the other at mint.
576
+ * The net delta depends on whether the swap occurred:
577
+ *
578
+ * | Scenario | Result |
579
+ * |-----------------------|-------------------------------------------------|
580
+ * | No swap | 0n (hold what you owe, net zero) |
581
+ * | Swap + borrows asset | -m (hold numeraire, owe asset → short exposure) |
582
+ * | Swap + borrows numer. | +m (hold asset, owe numeraire → long exposure) |
583
+ *
584
+ * Only meaningful for legs with `width === 0n`. For options, use `getLegDelta`.
585
+ *
586
+ * @param leg - The loan leg
587
+ * @param positionSize - Position size in asset token smallest units
588
+ * @param swapAtMint - Whether the borrowed tokens were swapped at mint
589
+ * @param assetIndex - Optional override for leg.asset (0n = token0 is asset)
590
+ * @returns Effective delta in asset token smallest units
591
+ */
592
+ function getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex) {
593
+ if (!swapAtMint) return 0n;
594
+ const isAssetToken0 = resolveAssetDirection(leg, assetIndex);
595
+ const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio;
596
+ const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n;
597
+ return borrowsAsset ? -m : m;
598
+ }
599
+ /**
600
+ * Calculate total delta for a position, using swap-aware delta for loan legs.
601
+ *
602
+ * For legs with `width === 0n` (loans/credits), uses `getLoanEffectiveDelta`
603
+ * which accounts for the swapAtMint flag. For option legs (`width > 0n`),
604
+ * uses the standard `getLegDelta`.
605
+ *
606
+ * @param input - Position greeks input plus swapAtMint flag
607
+ * @returns Total delta in asset token smallest units
608
+ */
609
+ function calculatePositionDeltaWithSwap(input) {
610
+ const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } = input;
611
+ const optionLegs = legs.filter((l) => l.width !== 0n);
612
+ const definedRisk = isDefinedRisk(optionLegs);
613
+ return legs.reduce((sum, leg) => {
614
+ if (leg.width === 0n) return sum + getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex);
615
+ return sum + getLegDelta(leg, currentTick, positionSize, poolTickSpacing, mintTick, definedRisk, assetIndex);
616
+ }, 0n);
617
+ }
618
+
619
+ //#endregion
620
+ export { calculatePortfolioDelta, calculatePortfolioGamma, calculatePortfolioGreeks, calculatePortfolioValue, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionDeltaWithSwap, calculatePositionGamma, calculatePositionGreeks, calculatePositionValue, getLegDelta, getLegDeltaInVaultFrame, getLegGamma, getLegNetValueWidth0, getLegValue, getLoanEffectiveDelta, isCall, isDefinedRisk, toVaultFrameAtTick };
621
+ //# sourceMappingURL=index.js.map