@panoptic-eng/sdk 1.0.71 → 1.0.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- import { UniswapV3PoolAbi, getAccountCollateral, getNetLiquidationValue, panopticQueryAbi$1 as panopticQueryAbi, readBlockAndAggregate, requireReturnData } from "./irm-HM0KEH12.js";
2
- import { AccountInsolventError, ChunkLimitError, DEFAULT_VEGOID, InvalidHistoryRangeError, MulticallResultMissingError, NotEnoughTokensError, PanopticError, PanopticValidationError, SafeModeError, StaleDataError, StorageDataNotFoundError, UnhealthyPoolError, WrongUniswapPoolError, applyMintBufferPerToken, availableToBorrow, collateralTrackerV2Abi, decodeLeftRightSigned, decodeLeftRightUnsigned, decodePositionBalance, getBlockMeta, getClosedPositionsKey, getPendingPositionsKey, getPool, getPoolMetaKey, getPoolMetadata, getPositionMetaKey, getPositionsKey, getTrackedChunksKey, getTrackedPositionIds, isPanopticErrorType, jsonSerializer, mintableAfterBuffer, panopticFactoryV3Abi, panopticFactoryV4Abi, panopticGuardianAbi, panopticLiquidatorAbi, panopticPoolV2Abi, panopticQueryAbi as panopticQueryAbi$1, parsePanopticError, riskEngineAbi, riskEngineMulticall, semiFungiblePositionManagerV3Abi, semiFungiblePositionManagerV4Abi, stateViewAbi, uniswapV3PoolAbi } from "./rates-DlqTkuXt.js";
3
- import { MAX_TICK, MAX_TRACKED_CHUNKS, MIN_TICK, NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, WAD, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionGamma, calculatePositionValue, getLegLiquidityRange, priceToTick, sqrtPriceX96ToTick, tickLimits, tickToPriceDecimalScaled, tickToSqrtPriceX96, toVaultFrameAtTick } from "./greeks-DNPP24KL.js";
4
- import { addLegToTokenId, buildBatchDispatchArgs, buildProtectedSettlePlan, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, countLegs, createTokenIdBuilder, decodeAllLegs, decodeTokenId, getCurrentPositionSizes, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateDispatch, simulateOpenPosition, simulateWithTokenFlow } from "./writes-DBu2ltcP.js";
5
- import { feesFromFeeGrowthDelta, getLpPositionFunding, getMaxLpPositionSize, getPriceHistory, preparePositionGamma, quoteSwapExactOutViaRouter, quoteSwapExactOutViaV3Router } from "./router-DDJ3OnDA.js";
6
- import { ContractFunctionExecutionError, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, getAddress, hexToString, isAddress, isAddressEqual, isHex, keccak256, parseAbi, parseEventLogs, trim, zeroAddress } from "viem";
7
- import { multicall } from "viem/actions";
1
+ import { UniswapV3PoolAbi, applyOwedInterest, getAccountBuyingPower, getAccountCollateral, getNetLiquidationValue, panopticQueryAbi$1 as panopticQueryAbi, readBlockAndAggregate, requireReturnData } from "./irm-BntFNP1P.js";
2
+ import { AccountInsolventError, ChunkLimitError, DEFAULT_VEGOID, InvalidHistoryRangeError, MulticallResultMissingError, NotEnoughTokensError, PanopticError, PanopticValidationError, SafeModeError, StaleDataError, StorageDataNotFoundError, UnhealthyPoolError, WrongUniswapPoolError, addLegToTokenId, applyMintBufferPerToken, availableToBorrow, collateralTrackerV2Abi, countLegs, decodeAllLegs, decodeLeftRightSigned, decodeLeftRightUnsigned, decodePositionBalance, decodeTokenId, getBlockMeta, getClosedPositionsKey, getPendingPositionsKey, getPool, getPoolMetaKey, getPoolMetadata, getPositionMetaKey, getPositionsKey, getTrackedChunksKey, getTrackedPositionIds, isPanopticErrorType, jsonSerializer, mintableAfterBuffer, panopticFactoryV3Abi, panopticFactoryV4Abi, panopticGuardianAbi, panopticLiquidatorAbi, panopticPoolV2Abi, panopticQueryAbi as panopticQueryAbi$1, parsePanopticError, riskEngineAbi, riskEngineMulticall, semiFungiblePositionManagerV3Abi, semiFungiblePositionManagerV4Abi, stateViewAbi, uniswapV3PoolAbi } from "./rates-c9XVKm3m.js";
3
+ import { MAX_TICK, MAX_TRACKED_CHUNKS, MIN_TICK, NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, WAD, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionGamma, calculatePositionValue, getLegLiquidityRange, priceToTick, sqrtPriceX96ToTick, tickLimits, tickToPriceDecimalScaled, tickToSqrtPriceX96, toVaultFrameAtTick } from "./greeks-CEv-Uex1.js";
4
+ import { buildBatchDispatchArgs, buildProtectedSettlePlan, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, createTokenIdBuilder, getCurrentPositionSizes, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateDispatch, simulateOpenPosition, simulateWithTokenFlow } from "./writes-_ZxthOkP.js";
5
+ import { feesFromFeeGrowthDelta, getLpPositionFunding, getMaxLpPositionSize, getPriceHistory, preparePositionGamma, quoteSwapExactOutViaRouter, quoteSwapExactOutViaV3Router } from "./router-lUA1kp8A.js";
6
+ import { ContractFunctionExecutionError, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, getAddress, hexToString, isAddress, isAddressEqual, isHex, keccak256, parseEventLogs, trim, zeroAddress } from "viem";
8
7
  import Decimal from "decimal.js";
8
+ import { multicall } from "viem/actions";
9
9
 
10
10
  //#region src/panoptic/v2/clients/blocksByTimestamp.ts
11
11
  /**
@@ -165,7 +165,7 @@ async function multicallRead(params) {
165
165
 
166
166
  //#endregion
167
167
  //#region src/panoptic/v2/utils/priceConvert.ts
168
- const Q128$2 = 1n << 128n;
168
+ const Q128$1 = 1n << 128n;
169
169
  /**
170
170
  * A non-positive price has no meaningful conversion, and `convert1to0` would
171
171
  * divide by zero — surface that as a typed SDK error rather than a RangeError
@@ -175,16 +175,16 @@ function assertPositivePrice(sqrtPriceX96) {
175
175
  if (sqrtPriceX96 <= 0n) throw new PanopticError(`sqrtPriceX96 must be positive, got ${sqrtPriceX96}`);
176
176
  }
177
177
  /** Convert a token0 amount to its token1-equivalent at the given sqrtPriceX96. */
178
- function convert0to1$2(amount, sqrtPriceX96) {
178
+ function convert0to1$1(amount, sqrtPriceX96) {
179
179
  assertPositivePrice(sqrtPriceX96);
180
- if (sqrtPriceX96 < Q128$2) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
180
+ if (sqrtPriceX96 < Q128$1) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
181
181
  const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
182
182
  return amount * sp2Hi >> 128n;
183
183
  }
184
184
  /** Convert a token1 amount to its token0-equivalent at the given sqrtPriceX96. */
185
- function convert1to0$2(amount, sqrtPriceX96) {
185
+ function convert1to0$1(amount, sqrtPriceX96) {
186
186
  assertPositivePrice(sqrtPriceX96);
187
- if (sqrtPriceX96 < Q128$2) {
187
+ if (sqrtPriceX96 < Q128$1) {
188
188
  const denom = sqrtPriceX96 * sqrtPriceX96;
189
189
  return amount * (1n << 192n) / denom;
190
190
  }
@@ -197,13 +197,13 @@ function convert1to0$2(amount, sqrtPriceX96) {
197
197
  */
198
198
  function convertToTokenIndex(amount, fromTokenIndex, toTokenIndex, sqrtPriceX96) {
199
199
  if (fromTokenIndex === toTokenIndex) return amount;
200
- return fromTokenIndex === 0n ? convert0to1$2(amount, sqrtPriceX96) : convert1to0$2(amount, sqrtPriceX96);
200
+ return fromTokenIndex === 0n ? convert0to1$1(amount, sqrtPriceX96) : convert1to0$1(amount, sqrtPriceX96);
201
201
  }
202
202
 
203
203
  //#endregion
204
204
  //#region src/panoptic/v2/reads/margin.ts
205
205
  const FP96$1 = 1n << 96n;
206
- const Q128$1 = 1n << 128n;
206
+ const Q128 = 1n << 128n;
207
207
  /** Cap for a usage ratio with no collateral behind it. */
208
208
  const MAX_USAGE_BPS = 1000000n;
209
209
  const bigintMax = (a, b) => a > b ? a : b;
@@ -214,16 +214,16 @@ const bigintMin = (a, b) => a < b ? a : b;
214
214
  * Matches the on-chain `PanopticMath.convert0to1` truncation, with an
215
215
  * overflow-safe branch when `sqrtPriceX96^2` would not fit in uint256.
216
216
  */
217
- function convert0to1$1(amount, sqrtPriceX96) {
218
- if (sqrtPriceX96 < Q128$1) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
217
+ function convert0to1(amount, sqrtPriceX96) {
218
+ if (sqrtPriceX96 < Q128) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
219
219
  const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
220
220
  return amount * sp2Hi >> 128n;
221
221
  }
222
222
  /**
223
223
  * Convert a token1 amount to its token0-equivalent at the given sqrtPriceX96.
224
224
  */
225
- function convert1to0$1(amount, sqrtPriceX96) {
226
- if (sqrtPriceX96 < Q128$1) {
225
+ function convert1to0(amount, sqrtPriceX96) {
226
+ if (sqrtPriceX96 < Q128) {
227
227
  const denom = sqrtPriceX96 * sqrtPriceX96;
228
228
  return amount * (1n << 192n) / denom;
229
229
  }
@@ -236,7 +236,7 @@ function convert1to0$1(amount, sqrtPriceX96) {
236
236
  * Reads, all pinned to the same block:
237
237
  * - `getCurrentTick` (sequencing dependency for sqrtPrice conversion)
238
238
  * - `getFullPositionsData(account, true, tokenIds)` → collateralRequirements
239
- * - `CollateralTracker.assetsOf(account)` on both trackers → gross collateral
239
+ * - `CollateralTracker.assetsAndInterest(account)` on both trackers → collateral and owed interest
240
240
  * - `PanopticQuery.getLiquidationPrices(...)` → liquidation boundaries
241
241
  *
242
242
  * @param params - The parameters
@@ -317,6 +317,14 @@ function requireMulticallResult(results, index, label) {
317
317
  if (result.status === "failure") throw result.error;
318
318
  return result.result;
319
319
  }
320
+ function requireAssetsAndInterestResult(results, index, label) {
321
+ const result = requireMulticallResult(results, index, label);
322
+ if (!Array.isArray(result) || result.length < 2 || typeof result[0] !== "bigint" || typeof result[1] !== "bigint") throw new PanopticError(`${label} returned an invalid value`);
323
+ return {
324
+ assets: result[0],
325
+ interest: result[1]
326
+ };
327
+ }
320
328
  function requireBigIntResult(results, index, label) {
321
329
  const result = requireMulticallResult(results, index, label);
322
330
  if (typeof result !== "bigint" && typeof result !== "number") throw new PanopticError(`${label} returned an invalid value`);
@@ -333,13 +341,13 @@ function prepareMarginBufferRead({ poolAddress, account, tokenIds, queryAddress,
333
341
  {
334
342
  address: collateralAddresses.collateralToken0,
335
343
  abi: collateralTrackerV2Abi,
336
- functionName: "assetsOf",
344
+ functionName: "assetsAndInterest",
337
345
  args: [account]
338
346
  },
339
347
  {
340
348
  address: collateralAddresses.collateralToken1,
341
349
  abi: collateralTrackerV2Abi,
342
- functionName: "assetsOf",
350
+ functionName: "assetsAndInterest",
343
351
  args: [account]
344
352
  }
345
353
  ];
@@ -390,8 +398,10 @@ function prepareMarginBufferRead({ poolAddress, account, tokenIds, queryAddress,
390
398
  }
391
399
  function decodeMarginBufferResults({ results, _meta, positionDataIndex, liqPricesIndex, checkCollateralIndex, mintBuffer }) {
392
400
  const currentTick = requireBigIntResult(results, 0, "PanopticPool.getCurrentTick");
393
- const assets0 = requireBigIntResult(results, 1, "CollateralTracker.assetsOf token0");
394
- const assets1 = requireBigIntResult(results, 2, "CollateralTracker.assetsOf token1");
401
+ const tracker0 = requireAssetsAndInterestResult(results, 1, "CollateralTracker.assetsAndInterest token0");
402
+ const tracker1 = requireAssetsAndInterestResult(results, 2, "CollateralTracker.assetsAndInterest token1");
403
+ const { balance: assets0, requirementExtra: interestDue0 } = applyOwedInterest(tracker0.assets, tracker0.interest);
404
+ const { balance: assets1, requirementExtra: interestDue1 } = applyOwedInterest(tracker1.assets, tracker1.interest);
395
405
  const positionDataResult = positionDataIndex === null ? null : requireMulticallResult(results, positionDataIndex, "PanopticPool.getFullPositionsData");
396
406
  const liqPricesResult = liqPricesIndex === null ? null : requireMulticallResult(results, liqPricesIndex, "PanopticQuery.getLiquidationPrices");
397
407
  const checkCollateralResult = checkCollateralIndex === null ? null : requireMulticallResult(results, checkCollateralIndex, "PanopticQuery.checkCollateral");
@@ -414,8 +424,8 @@ function decodeMarginBufferResults({ results, _meta, positionDataIndex, liqPrice
414
424
  const mintable1 = mintable(balances1[0], requireds1[0]);
415
425
  if (mintable0 !== null || mintable1 !== null) mintableMarginBinding = mintable0 === null ? mintable1 : mintable1 === null ? mintable0 : bigintMin(mintable0, mintable1);
416
426
  }
417
- let required0Native = 0n;
418
- let required1Native = 0n;
427
+ let required0Native = interestDue0;
428
+ let required1Native = interestDue1;
419
429
  if (positionDataResult) {
420
430
  const collateralRequirements = positionDataResult[3];
421
431
  for (const packed of collateralRequirements) {
@@ -426,10 +436,10 @@ function decodeMarginBufferResults({ results, _meta, positionDataIndex, liqPrice
426
436
  }
427
437
  const sqrtPriceX96 = tickToSqrtPriceX96(currentTick);
428
438
  const denominatedInToken = sqrtPriceX96 < FP96$1 ? 0 : 1;
429
- const currentMargin0 = assets0 + convert1to0$1(assets1, sqrtPriceX96);
430
- const requiredMargin0 = required0Native + convert1to0$1(required1Native, sqrtPriceX96);
431
- const currentMargin1 = assets1 + convert0to1$1(assets0, sqrtPriceX96);
432
- const requiredMargin1 = required1Native + convert0to1$1(required0Native, sqrtPriceX96);
439
+ const currentMargin0 = assets0 + convert1to0(assets1, sqrtPriceX96);
440
+ const requiredMargin0 = required0Native + convert1to0(required1Native, sqrtPriceX96);
441
+ const currentMargin1 = assets1 + convert0to1(assets0, sqrtPriceX96);
442
+ const requiredMargin1 = required1Native + convert0to1(required0Native, sqrtPriceX96);
433
443
  const buffer0 = currentMargin0 - requiredMargin0;
434
444
  const buffer1 = currentMargin1 - requiredMargin1;
435
445
  const bufferPercent0 = requiredMargin0 === 0n ? null : buffer0 * 10000n / requiredMargin0;
@@ -1454,10 +1464,10 @@ async function getChunkLiquidities(params) {
1454
1464
  */
1455
1465
  async function getFactoryTokenURI(params) {
1456
1466
  const { client, factoryAddress, version, tokenId } = params;
1457
- const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1467
+ const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1458
1468
  return client.readContract({
1459
1469
  address: factoryAddress,
1460
- abi: abi$1,
1470
+ abi,
1461
1471
  functionName: "tokenURI",
1462
1472
  args: [tokenId]
1463
1473
  });
@@ -1467,10 +1477,10 @@ async function getFactoryTokenURI(params) {
1467
1477
  */
1468
1478
  async function getFactoryOwnerOf(params) {
1469
1479
  const { client, factoryAddress, version, tokenId } = params;
1470
- const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1480
+ const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1471
1481
  return client.readContract({
1472
1482
  address: factoryAddress,
1473
- abi: abi$1,
1483
+ abi,
1474
1484
  functionName: "ownerOf",
1475
1485
  args: [tokenId]
1476
1486
  });
@@ -1480,10 +1490,10 @@ async function getFactoryOwnerOf(params) {
1480
1490
  */
1481
1491
  async function getFactoryConstructMetadata(params) {
1482
1492
  const { client, factoryAddress, version, panopticPoolAddress, symbol0, symbol1, fee } = params;
1483
- const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1493
+ const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1484
1494
  return client.readContract({
1485
1495
  address: factoryAddress,
1486
- abi: abi$1,
1496
+ abi,
1487
1497
  functionName: "constructMetadata",
1488
1498
  args: [
1489
1499
  panopticPoolAddress,
@@ -3974,161 +3984,6 @@ async function getCollateralTotalAssetsBatch(client, collateralTrackerAddresses,
3974
3984
  }
3975
3985
  }
3976
3986
 
3977
- //#endregion
3978
- //#region src/panoptic/v2/reads/buyingPower.ts
3979
- const Q128 = 1n << 128n;
3980
- /** Immutable collateral tracker addresses, suitable for a pool-scoped cache. */
3981
- async function getPoolCollateralAddresses(params) {
3982
- const [collateralToken0, collateralToken1] = await multicall(params.client, {
3983
- contracts: [{
3984
- address: params.poolAddress,
3985
- abi: panopticPoolV2Abi,
3986
- functionName: "collateralToken0"
3987
- }, {
3988
- address: params.poolAddress,
3989
- abi: panopticPoolV2Abi,
3990
- functionName: "collateralToken1"
3991
- }],
3992
- blockNumber: params.blockNumber,
3993
- allowFailure: false
3994
- });
3995
- return {
3996
- collateralToken0,
3997
- collateralToken1
3998
- };
3999
- }
4000
- function convert0to1(amount, sqrtPriceX96) {
4001
- if (sqrtPriceX96 < Q128) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
4002
- const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
4003
- return amount * sp2Hi >> 128n;
4004
- }
4005
- function convert1to0(amount, sqrtPriceX96) {
4006
- if (sqrtPriceX96 < Q128) {
4007
- const denom = sqrtPriceX96 * sqrtPriceX96;
4008
- return amount * (1n << 192n) / denom;
4009
- }
4010
- const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
4011
- return amount * (1n << 128n) / sp2Hi;
4012
- }
4013
- /**
4014
- * Get account-level buying power.
4015
- *
4016
- * Uses {@link https://github.com/panoptic-xyz CollateralTracker.assetsOf} for
4017
- * gross collateral and `PanopticPool.getFullPositionsData.collateralRequirements[]`
4018
- * for the per-position required margin — so loan tokenIds (width=0 shorts)
4019
- * contribute to the requirement instead of being netted out of the balance.
4020
- *
4021
- * Accepts a plain viem `Client` (not just `PublicClient`) so it works with wagmi's
4022
- * `useClient()` without needing a cast.
4023
- *
4024
- * @param params - The parameters
4025
- * @returns Account buying power data with optional block metadata
4026
- */
4027
- async function getAccountBuyingPower(params) {
4028
- const { client, poolAddress, account, tokenIds } = params;
4029
- const blockNumber = params.blockNumber ?? params._meta?.blockNumber;
4030
- let collateralToken0;
4031
- let collateralToken1;
4032
- if (params.collateralAddresses) {
4033
- collateralToken0 = params.collateralAddresses.collateralToken0;
4034
- collateralToken1 = params.collateralAddresses.collateralToken1;
4035
- } else {
4036
- const addresses = await getPoolCollateralAddresses({
4037
- client,
4038
- poolAddress,
4039
- blockNumber
4040
- });
4041
- collateralToken0 = addresses.collateralToken0;
4042
- collateralToken1 = addresses.collateralToken1;
4043
- }
4044
- const calls = [
4045
- {
4046
- target: poolAddress,
4047
- callData: encodeFunctionData({
4048
- abi: panopticPoolV2Abi,
4049
- functionName: "getCurrentTick"
4050
- })
4051
- },
4052
- {
4053
- target: collateralToken0,
4054
- callData: encodeFunctionData({
4055
- abi: collateralTrackerV2Abi,
4056
- functionName: "assetsOf",
4057
- args: [account]
4058
- })
4059
- },
4060
- {
4061
- target: collateralToken1,
4062
- callData: encodeFunctionData({
4063
- abi: collateralTrackerV2Abi,
4064
- functionName: "assetsOf",
4065
- args: [account]
4066
- })
4067
- }
4068
- ];
4069
- const positionDataIndex = tokenIds.length > 0 ? calls.length : null;
4070
- if (positionDataIndex !== null) calls.push({
4071
- target: poolAddress,
4072
- callData: encodeFunctionData({
4073
- abi: panopticPoolV2Abi,
4074
- functionName: "getFullPositionsData",
4075
- args: [
4076
- account,
4077
- true,
4078
- tokenIds
4079
- ]
4080
- })
4081
- });
4082
- const { _meta, results } = await readBlockAndAggregate({
4083
- client,
4084
- calls,
4085
- blockNumber
4086
- });
4087
- const currentTickResult = decodeFunctionResult({
4088
- abi: panopticPoolV2Abi,
4089
- functionName: "getCurrentTick",
4090
- data: requireReturnData(results, 0, "PanopticPool.getCurrentTick")
4091
- });
4092
- const assets0 = decodeFunctionResult({
4093
- abi: collateralTrackerV2Abi,
4094
- functionName: "assetsOf",
4095
- data: requireReturnData(results, 1, "CollateralTracker.assetsOf token0")
4096
- });
4097
- const assets1 = decodeFunctionResult({
4098
- abi: collateralTrackerV2Abi,
4099
- functionName: "assetsOf",
4100
- data: requireReturnData(results, 2, "CollateralTracker.assetsOf token1")
4101
- });
4102
- const currentTick = BigInt(currentTickResult);
4103
- const positionDataResult = positionDataIndex === null ? null : decodeFunctionResult({
4104
- abi: panopticPoolV2Abi,
4105
- functionName: "getFullPositionsData",
4106
- data: requireReturnData(results, positionDataIndex, "PanopticPool.getFullPositionsData")
4107
- });
4108
- let required0Native = 0n;
4109
- let required1Native = 0n;
4110
- if (positionDataResult) {
4111
- const collateralRequirements = positionDataResult[3];
4112
- for (const packed of collateralRequirements) {
4113
- const decoded = decodeLeftRightUnsigned(packed);
4114
- required0Native += decoded.right;
4115
- required1Native += decoded.left;
4116
- }
4117
- }
4118
- const sqrtPriceX96 = tickToSqrtPriceX96(currentTick);
4119
- const collateralBalance0 = assets0 + convert1to0(assets1, sqrtPriceX96);
4120
- const requiredCollateral0 = required0Native + convert1to0(required1Native, sqrtPriceX96);
4121
- const collateralBalance1 = assets1 + convert0to1(assets0, sqrtPriceX96);
4122
- const requiredCollateral1 = required1Native + convert0to1(required0Native, sqrtPriceX96);
4123
- return {
4124
- collateralBalance0,
4125
- requiredCollateral0,
4126
- collateralBalance1,
4127
- requiredCollateral1,
4128
- _meta
4129
- };
4130
- }
4131
-
4132
3987
  //#endregion
4133
3988
  //#region src/panoptic/v2/reads/openPositionPreview.ts
4134
3989
  /**
@@ -10448,84 +10303,6 @@ async function getCollateralCurve({ client, poolAddress, account, queryAddress,
10448
10303
  };
10449
10304
  }
10450
10305
 
10451
- //#endregion
10452
- //#region src/panoptic/v2/reads/positionValueCurve.ts
10453
- const abi = parseAbi(["function computeNetLiquidationValue(uint256[] positionIdList, uint256 shortPremium, uint256 longPremium, uint256[] positionBalanceArray, int24[] atTicks) pure returns (int256[] value0, int256[] value1)"]);
10454
- /** Stable identity for a position-dependent curve; streamia and spot are separate inputs. */
10455
- function positionValueKey(positions) {
10456
- return [...positions].sort((a, b) => a.tokenId < b.tokenId ? -1 : a.tokenId > b.tokenId ? 1 : 0).map(({ tokenId, positionSize }) => `${tokenId}:${positionSize}`).join(",");
10457
- }
10458
- /** All changes in the curve's active liquidity, independent of the current market tick. */
10459
- function positionValueTicks(positions) {
10460
- const ticks = new Set([-887272n, 887272n]);
10461
- for (const { tokenId, positionSize } of positions) {
10462
- if (tokenId < 0n || tokenId >= 1n << 256n || positionSize <= 0n || positionSize >= 1n << 128n) throw new RangeError("Invalid position id or size");
10463
- const { legs, tickSpacing } = decodeTokenId(tokenId);
10464
- for (const leg of legs) {
10465
- if (leg.width === 0n) continue;
10466
- const width = leg.width * tickSpacing;
10467
- const lower = leg.strike - width / 2n;
10468
- const upper = leg.strike + (width + 1n) / 2n;
10469
- if (lower < -887272n || upper > 887272n || lower >= upper) throw new RangeError("Invalid position range");
10470
- ticks.add(lower);
10471
- ticks.add(upper);
10472
- }
10473
- }
10474
- return [...ticks].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
10475
- }
10476
- /** Read the immutable, premium-free part of NLV from the deployed pure calculation. */
10477
- async function getPositionValueCurve({ client, queryAddress, positions }) {
10478
- const ticks = positionValueTicks(positions);
10479
- const [values0, values1] = await client.readContract({
10480
- address: queryAddress,
10481
- abi,
10482
- functionName: "computeNetLiquidationValue",
10483
- args: [
10484
- positions.map((p) => p.tokenId),
10485
- 0n,
10486
- 0n,
10487
- positions.map((p) => p.positionSize),
10488
- ticks.map(Number)
10489
- ]
10490
- });
10491
- return ticks.map((tick, i) => ({
10492
- tick,
10493
- value0: values0[i],
10494
- value1: values1[i]
10495
- }));
10496
- }
10497
- /**
10498
- * Between leg boundaries, token0 is affine in inverse sqrt price and token1 in sqrt price.
10499
- * Endpoint interpolation differs from contract integer rounding by at most a few wei per leg.
10500
- */
10501
- function preparePositionValueCurve(curve) {
10502
- if (curve.length < 2) throw new RangeError("Incomplete position value curve");
10503
- for (let i = 0; i < curve.length; i++) if (curve[i].tick < -887272n || curve[i].tick > 887272n || i > 0 && curve[i].tick <= curve[i - 1].tick) throw new RangeError("Invalid position value curve ticks");
10504
- const points = curve.map((point) => ({
10505
- ...point,
10506
- sqrt: tickToSqrtPriceX96(point.tick)
10507
- }));
10508
- return (tick) => {
10509
- if (tick < points[0].tick || tick > points[points.length - 1].tick) throw new RangeError("Tick outside position value curve");
10510
- let lo = 0;
10511
- let hi = points.length - 1;
10512
- while (hi - lo > 1) {
10513
- const mid = Math.floor((lo + hi) / 2);
10514
- if (points[mid].tick <= tick) lo = mid;
10515
- else hi = mid;
10516
- }
10517
- const left = points[lo];
10518
- const right = points[hi];
10519
- const sqrt = tickToSqrtPriceX96(tick);
10520
- const numerator = sqrt - left.sqrt;
10521
- const denominator = right.sqrt - left.sqrt;
10522
- return {
10523
- value0: left.value0 + (right.value0 - left.value0) * numerator * right.sqrt / (denominator * sqrt),
10524
- value1: left.value1 + (right.value1 - left.value1) * numerator / denominator
10525
- };
10526
- };
10527
- }
10528
-
10529
10306
  //#endregion
10530
10307
  //#region src/panoptic/v2/reads/positionVolatilityHistory.ts
10531
10308
  const signedSlot = (value) => BigInt.asIntN(128, value);
@@ -10742,4 +10519,4 @@ async function getPositionVolatilityHistory({ client, poolAddress, account, toke
10742
10519
  }
10743
10520
 
10744
10521
  //#endregion
10745
- export { DEFAULT_MIN_SWAP_RATIO_BPS, DEFAULT_RECONNECT_CONFIG, MARKET_INDICATOR_PERIODS, REQUIRED_BASE_ERROR_SENTINEL, STRIKE_LADDER_TARGET_STRIKES, VARIANCE_RATIO_LAG, addPendingPosition, addTrackedChunks, apportion, assertCanBurn, assertCanForceExercise, assertCanLiquidate, assertCanMint, assertFresh, assertHealthy, assertLpPositionFunded, assertTradeable, buildCreditWrappedDispatch, buildSfpmSwapCalldata, buildSfpmSwapPlan, buildTemporaryLoanRecoveryDispatch, buildTokenShortfallRecoveryDispatch, calculateAccountGreeksPure, calculateMarketIndicator, calculateSpreadWad, calculateVarianceProfile, checkCollateralAcrossTicks, classifyStrategyGroups, classifyStrike, cleanupStalePendingPositions, clearPendingPositions, clearTrackedChunks, clearTradeHistory, collateralCurveTicks, collateralRuleKindFor, computeV4PoolId, confirmPendingPosition, convertToAssets, convertToShares, createEventPoller, createEventSubscription, createFlowNeutralTokenId, decodePanopticTokenURI, emptyLiquidateParams, encodePoolKeyBytes, encodeV3PoolKeyBytes, ensureSfpmV3PoolInitialized, estimateBlockNumbers, estimateCloseZapSwap, estimateCollateralBreakdown, estimateCollateralRequired, failPendingPosition, feeGrowthInsideX128, fetchPoolSwaps, fetchSfpmV3PoolId, fetchUniswapFeeData, getAccountBuyingPower, getAccountGreeks, getAccountHistory, getChunkLiquidities, getChunkSpreads, getClosePositionTransferEstimate, getClosedPositions, getCollateralCurve, getCollateralCurveInputs, getCollateralRequiredBase, getCollateralSharePrices, getCollateralTotalAssetsBatch, getDeltaHedgeParams, getEnforcedTickLimits, getExecutableLpMaxSize, getFactoryConstructMetadata, getFactoryOwnerOf, getFactoryTokenURI, getGuardianUnlockState, getHedgeLimits, getItmAmounts, getMarginBuffer, getMaxPositionSize, getMaxRedeem, getMaxWithdrawable, getNativeTokenPrice, getNotEnoughTokensError, getOpenPositionPreview, getPanopticPoolAddress, getPanopticPoolFromPoolId, getPendingPositions, getPoolCollateralAddresses, getPoolLiquidities, getPortfolioValue, getPositionChunkData, getPositionEnrichmentData, getPositionMintFunding, getPositionValueCurve, getPositionVolatilityHistory, getRealizedPnL, getRequiredCreditForITM, getSafeMode, getStreamiaHistory, getSyncStatus, getTrackedChunks, getTradeHistory, getUniswapFeeHistory, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, interpolateBlocks, isGasError, isNonceError, isRetryableRpcError, isolateGroupTokenId, ladderStrikeSequence, logReturns, marketPnlInQuote, marketRiskFromValues, marketScenario, minePoolAddress, minePoolAddressLocalAsync, multicallRead, netLiquidationValueInQuote, optimizeTokenIdRiskPartners, parseCollateralLog, parsePoolLog, parseStreamedKey, parseStreamedSwap, parseSwapLog, positionValueKey, positionValueTicks, prepareIndicatorCandles, preparePositionValueCurve, previewDeposit, previewMint, previewRedeem, previewWithdraw, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, quoteTokenShortfallSwap, realizedBeta, removeTrackedChunks, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveUniswapV4PoolKey, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, simulateBatchDispatch, simulateClosePosition, simulateClosePremiumProtection, simulateDeployNewPool, simulateDeposit, simulateForceExercise, simulateLiquidate, simulateSFPMBurn, simulateSFPMMint, simulateSwapExactIn, simulateSwapExactOut, simulateWithdraw, slippageBpsToTickDistance, streamPoolSwaps, subscribePoolSwaps, watchEvents, watchPoolSwaps };
10522
+ export { DEFAULT_MIN_SWAP_RATIO_BPS, DEFAULT_RECONNECT_CONFIG, MARKET_INDICATOR_PERIODS, REQUIRED_BASE_ERROR_SENTINEL, STRIKE_LADDER_TARGET_STRIKES, VARIANCE_RATIO_LAG, addPendingPosition, addTrackedChunks, apportion, assertCanBurn, assertCanForceExercise, assertCanLiquidate, assertCanMint, assertFresh, assertHealthy, assertLpPositionFunded, assertTradeable, buildCreditWrappedDispatch, buildSfpmSwapCalldata, buildSfpmSwapPlan, buildTemporaryLoanRecoveryDispatch, buildTokenShortfallRecoveryDispatch, calculateAccountGreeksPure, calculateMarketIndicator, calculateSpreadWad, calculateVarianceProfile, checkCollateralAcrossTicks, classifyStrategyGroups, classifyStrike, cleanupStalePendingPositions, clearPendingPositions, clearTrackedChunks, clearTradeHistory, collateralCurveTicks, collateralRuleKindFor, computeV4PoolId, confirmPendingPosition, convertToAssets, convertToShares, createEventPoller, createEventSubscription, createFlowNeutralTokenId, decodePanopticTokenURI, emptyLiquidateParams, encodePoolKeyBytes, encodeV3PoolKeyBytes, ensureSfpmV3PoolInitialized, estimateBlockNumbers, estimateCloseZapSwap, estimateCollateralBreakdown, estimateCollateralRequired, failPendingPosition, feeGrowthInsideX128, fetchPoolSwaps, fetchSfpmV3PoolId, fetchUniswapFeeData, getAccountGreeks, getAccountHistory, getChunkLiquidities, getChunkSpreads, getClosePositionTransferEstimate, getClosedPositions, getCollateralCurve, getCollateralCurveInputs, getCollateralRequiredBase, getCollateralSharePrices, getCollateralTotalAssetsBatch, getDeltaHedgeParams, getEnforcedTickLimits, getExecutableLpMaxSize, getFactoryConstructMetadata, getFactoryOwnerOf, getFactoryTokenURI, getGuardianUnlockState, getHedgeLimits, getItmAmounts, getMarginBuffer, getMaxPositionSize, getMaxRedeem, getMaxWithdrawable, getNativeTokenPrice, getNotEnoughTokensError, getOpenPositionPreview, getPanopticPoolAddress, getPanopticPoolFromPoolId, getPendingPositions, getPoolLiquidities, getPortfolioValue, getPositionChunkData, getPositionEnrichmentData, getPositionMintFunding, getPositionVolatilityHistory, getRealizedPnL, getRequiredCreditForITM, getSafeMode, getStreamiaHistory, getSyncStatus, getTrackedChunks, getTradeHistory, getUniswapFeeHistory, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, interpolateBlocks, isGasError, isNonceError, isRetryableRpcError, isolateGroupTokenId, ladderStrikeSequence, logReturns, marketPnlInQuote, marketRiskFromValues, marketScenario, minePoolAddress, minePoolAddressLocalAsync, multicallRead, netLiquidationValueInQuote, optimizeTokenIdRiskPartners, parseCollateralLog, parsePoolLog, parseStreamedKey, parseStreamedSwap, parseSwapLog, prepareIndicatorCandles, previewDeposit, previewMint, previewRedeem, previewWithdraw, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, quoteTokenShortfallSwap, realizedBeta, removeTrackedChunks, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveUniswapV4PoolKey, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, simulateBatchDispatch, simulateClosePosition, simulateClosePremiumProtection, simulateDeployNewPool, simulateDeposit, simulateForceExercise, simulateLiquidate, simulateSFPMBurn, simulateSFPMMint, simulateSwapExactIn, simulateSwapExactOut, simulateWithdraw, slippageBpsToTickDistance, streamPoolSwaps, subscribePoolSwaps, watchEvents, watchPoolSwaps };