@panoptic-eng/sdk 1.0.55 → 1.0.57

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 (33) hide show
  1. package/dist/chainDeployments-D_bvyWEm.js +408 -0
  2. package/dist/{cow-BahYFov0.js → cow-45nsAaEr.js} +1 -1
  3. package/dist/deployments.js +2 -2
  4. package/dist/deployments.js.map +1 -1
  5. package/dist/index.d.ts +83 -41
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +323 -78
  8. package/dist/index.js.map +1 -1
  9. package/dist/{irm-BsRdsXMS.js → irm-DsM35dGO.js} +2 -409
  10. package/dist/panoptic/v2/index.d.ts +147 -1
  11. package/dist/panoptic/v2/index.d.ts.map +1 -1
  12. package/dist/panoptic/v2/index.js +266 -22
  13. package/dist/panoptic/v2/index.js.map +1 -1
  14. package/dist/panoptic/v2/react-public.d.ts +147 -1
  15. package/dist/panoptic/v2/react-public.d.ts.map +1 -1
  16. package/dist/panoptic/v2/react-public.js +266 -22
  17. package/dist/panoptic/v2/react-public.js.map +1 -1
  18. package/dist/{rates-B0uPUed1.js → rates-CEJz8fjw.js} +1 -1
  19. package/dist/{router-BhJqStSJ.js → router-DOUAKfn6.js} +2 -2
  20. package/dist/{router-kAllFA4i.js → router-DUOHNdYZ.js} +21 -12
  21. package/dist/{transactionFees-DE-Whxab.js → transactionFees-qweht4Rd.js} +54 -28
  22. package/dist/uniswap/index.d.ts +6 -1
  23. package/dist/uniswap/index.d.ts.map +1 -1
  24. package/dist/uniswap/index.js +19 -10
  25. package/dist/uniswap/index.js.map +1 -1
  26. package/dist/{v2-bpvC_P3W.js → v2-B3MqHVHt.js} +247 -12
  27. package/dist/vault-transaction-fees.d.ts +5 -3
  28. package/dist/vault-transaction-fees.d.ts.map +1 -1
  29. package/dist/vault-transaction-fees.js +443 -28
  30. package/dist/vault-transaction-fees.js.map +1 -1
  31. package/dist/{writes-B4nGIi6h.js → writes-CQrevcCu.js} +2 -2
  32. package/dist/zodiac/index.d.ts.map +1 -1
  33. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
- import { StateViewAbi, getAccountCollateral, panopticQueryAbi$1 as panopticQueryAbi, readBlockAndAggregate, requireReturnData } from "./irm-BsRdsXMS.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, semiFungiblePositionManagerV3Abi, semiFungiblePositionManagerV4Abi, stateViewAbi, uniswapV3PoolAbi } from "./rates-B0uPUed1.js";
1
+ import { StateViewAbi, getAccountCollateral, panopticQueryAbi$1 as panopticQueryAbi, readBlockAndAggregate, requireReturnData } from "./irm-DsM35dGO.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, semiFungiblePositionManagerV3Abi, semiFungiblePositionManagerV4Abi, stateViewAbi, uniswapV3PoolAbi } from "./rates-CEJz8fjw.js";
3
3
  import { MAX_TICK, MAX_TRACKED_CHUNKS, MIN_TICK, NO_LOWER_LIQUIDATION_TICK, NO_UPPER_LIQUIDATION_TICK, WAD, calculatePositionDelta, calculatePositionDeltaDebtOnly, calculatePositionGamma, calculatePositionValue, priceToTick, sqrtPriceX96ToTick, tickLimits, tickToPriceDecimalScaled, tickToSqrtPriceX96, toVaultFrameAtTick } from "./greeks-CNi1-cnp.js";
4
- import { addLegToTokenId, buildBatchDispatchArgs, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, countLegs, createTokenIdBuilder, decodeAllLegs, decodeTokenId, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateOpenPosition, simulateWithTokenFlow } from "./writes-B4nGIi6h.js";
5
- import { getLpPositionFunding, getMaxLpPositionSize } from "./router-kAllFA4i.js";
6
- import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, ExecutionRevertedError, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, getAddress, keccak256, toHex, zeroAddress } from "viem";
4
+ import { addLegToTokenId, buildBatchDispatchArgs, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, countLegs, createTokenIdBuilder, decodeAllLegs, decodeTokenId, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateOpenPosition, simulateWithTokenFlow } from "./writes-CQrevcCu.js";
5
+ import { getLpPositionFunding, getMaxLpPositionSize } from "./router-DUOHNdYZ.js";
6
+ import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, ExecutionRevertedError, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, getAddress, keccak256, parseAbi, toHex, zeroAddress } from "viem";
7
7
  import { multicall } from "viem/actions";
8
8
  import Decimal from "decimal.js";
9
9
 
@@ -1605,10 +1605,10 @@ async function getChunkLiquidities(params) {
1605
1605
  */
1606
1606
  async function getFactoryTokenURI(params) {
1607
1607
  const { client, factoryAddress, version, tokenId } = params;
1608
- const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1608
+ const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1609
1609
  return client.readContract({
1610
1610
  address: factoryAddress,
1611
- abi,
1611
+ abi: abi$1,
1612
1612
  functionName: "tokenURI",
1613
1613
  args: [tokenId]
1614
1614
  });
@@ -1618,10 +1618,10 @@ async function getFactoryTokenURI(params) {
1618
1618
  */
1619
1619
  async function getFactoryOwnerOf(params) {
1620
1620
  const { client, factoryAddress, version, tokenId } = params;
1621
- const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1621
+ const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1622
1622
  return client.readContract({
1623
1623
  address: factoryAddress,
1624
- abi,
1624
+ abi: abi$1,
1625
1625
  functionName: "ownerOf",
1626
1626
  args: [tokenId]
1627
1627
  });
@@ -1631,10 +1631,10 @@ async function getFactoryOwnerOf(params) {
1631
1631
  */
1632
1632
  async function getFactoryConstructMetadata(params) {
1633
1633
  const { client, factoryAddress, version, panopticPoolAddress, symbol0, symbol1, fee } = params;
1634
- const abi = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1634
+ const abi$1 = version === "v3" ? panopticFactoryV3Abi : panopticFactoryV4Abi;
1635
1635
  return client.readContract({
1636
1636
  address: factoryAddress,
1637
- abi,
1637
+ abi: abi$1,
1638
1638
  functionName: "constructMetadata",
1639
1639
  args: [
1640
1640
  panopticPoolAddress,
@@ -4420,6 +4420,8 @@ async function getUniswapFeeHistory(params) {
4420
4420
  return {
4421
4421
  blockNumber: blockMetadata[i].blockNumber,
4422
4422
  blockTimestamp: blockMetadata[i].blockTimestamp,
4423
+ currentTick: bd.currentTick,
4424
+ sqrtPriceX96: bd.sqrtPriceX96,
4423
4425
  fees: {
4424
4426
  token0: total0 - initialFees0,
4425
4427
  token1: total1 - initialFees1
@@ -4519,6 +4521,7 @@ async function fetchV3BlockSnapshot(client, poolAddress, blockNumber, uniqueTick
4519
4521
  }
4520
4522
  return {
4521
4523
  currentTick: slot0Result[1],
4524
+ sqrtPriceX96: slot0Result[0],
4522
4525
  feeGrowthGlobal0,
4523
4526
  feeGrowthGlobal1,
4524
4527
  tickData
@@ -4562,6 +4565,7 @@ async function fetchV4BlockSnapshot(client, stateViewAddress, poolId, blockNumbe
4562
4565
  }
4563
4566
  return {
4564
4567
  currentTick: slot0Result[1],
4568
+ sqrtPriceX96: slot0Result[0],
4565
4569
  feeGrowthGlobal0: feeGrowthResult[0],
4566
4570
  feeGrowthGlobal1: feeGrowthResult[1],
4567
4571
  tickData
@@ -9844,4 +9848,235 @@ function calculateVarianceProfile(candles, isAssetToken0, intervalSeconds = 3600
9844
9848
  }
9845
9849
 
9846
9850
  //#endregion
9847
- 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, collateralRuleKindFor, computeV4PoolId, confirmPendingPosition, convertToAssets, convertToShares, createEventPoller, createEventSubscription, createFlowNeutralTokenId, decodePanopticTokenURI, emptyLiquidateParams, encodePoolKeyBytes, encodeV3PoolKeyBytes, ensureSfpmV3PoolInitialized, estimateBlockNumbers, estimateCollateralBreakdown, estimateCollateralRequired, failPendingPosition, feesFromFeeGrowthDelta, fetchSfpmV3PoolId, getAccountBuyingPower, getAccountGreeks, getAccountHistory, getChunkLiquidities, getChunkSpreads, getClosedPositions, 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, getPriceHistory, getRealizedPnL, getRequiredCreditForITM, getSafeMode, getStreamiaHistory, getSyncStatus, getTrackedChunks, getTradeHistory, getUniswapFeeHistory, getUniswapV3LpPositionState, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4LpPositionState, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, interpolateBlocks, isGasError, isNonceError, isRetryableRpcError, isolateGroupTokenId, ladderStrikeSequence, logReturns, minePoolAddress, minePoolAddressLocalAsync, multicallRead, optimizeTokenIdRiskPartners, parseCollateralLog, parsePoolLog, prepareIndicatorCandles, previewDeposit, previewMint, previewRedeem, previewWithdraw, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, realizedBeta, removeTrackedChunks, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveUniswapV4PoolKey, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, simulateBatchDispatch, simulateClosePosition, simulateDeployNewPool, simulateDeposit, simulateDispatch, simulateForceExercise, simulateLiquidate, simulateSFPMBurn, simulateSFPMMint, simulateSwapExactIn, simulateSwapExactOut, simulateWithdraw, slippageBpsToTickDistance, watchEvents };
9851
+ //#region src/panoptic/v2/greeks/marketPnl.ts
9852
+ /** Values and prices use raw token units, matching the net-liquidation-value read. */
9853
+ function netLiquidationValueInQuote(value0, value1, tick, isAssetToken0) {
9854
+ const price = new Decimal("1.0001").pow(tick.toString());
9855
+ return isAssetToken0 ? new Decimal(value1.toString()).plus(new Decimal(value0.toString()).mul(price)) : new Decimal(value0.toString()).plus(new Decimal(value1.toString()).div(price));
9856
+ }
9857
+ /** Apply the accrued-premium offset and optional asset collateral to a relative NLV curve. */
9858
+ function marketPnlInQuote({ relativeValue, premium, assetBalance = 0n, price, baselinePrice }) {
9859
+ return new Decimal(relativeValue).plus(premium).plus(new Decimal(assetBalance.toString()).mul(new Decimal(price).minus(baselinePrice)));
9860
+ }
9861
+ /** Map a common reference-asset shock into a pool tick and quote-token USD multiplier. */
9862
+ function marketScenario({ currentTick, isAssetToken0, assetBeta, quoteBeta, shock }) {
9863
+ const assetFactor = new Decimal(assetBeta).mul(shock).plus(1);
9864
+ const quoteFactor = new Decimal(quoteBeta).mul(shock).plus(1);
9865
+ if (!assetFactor.isFinite() || !quoteFactor.isFinite() || assetFactor.lte(0) || quoteFactor.lte(0)) return null;
9866
+ const shift = assetFactor.div(quoteFactor).ln().div(new Decimal("1.0001").ln());
9867
+ const tick = currentTick + BigInt(shift.mul(isAssetToken0 ? 1 : -1).round().toFixed(0));
9868
+ return tick < -887272n || tick > 887272n ? null : {
9869
+ tick,
9870
+ quoteFactor
9871
+ };
9872
+ }
9873
+ /** Finite-difference risk in raw asset/quote units from three ordered quote prices. */
9874
+ function marketRiskFromValues({ lower, current, upper }) {
9875
+ const left = new Decimal(current.price).minus(lower.price);
9876
+ const right = new Decimal(upper.price).minus(current.price);
9877
+ if (left.lte(0) || right.lte(0)) return null;
9878
+ const leftSlope = new Decimal(current.value).minus(lower.value).div(left);
9879
+ const rightSlope = new Decimal(upper.value).minus(current.value).div(right);
9880
+ const delta = leftSlope.mul(right).plus(rightSlope.mul(left)).div(left.plus(right));
9881
+ const gamma = rightSlope.minus(leftSlope).mul(2).div(left.plus(right)).mul(new Decimal(current.price).pow(2));
9882
+ return {
9883
+ asset: delta,
9884
+ quote: new Decimal(current.value).minus(delta.mul(current.price)),
9885
+ gamma
9886
+ };
9887
+ }
9888
+
9889
+ //#endregion
9890
+ //#region src/panoptic/v2/reads/collateralCurve.ts
9891
+ /** Native-token margin inputs, independent of the tick used to display the curve. */
9892
+ async function getCollateralCurveInputs({ client, poolAddress, account, tokenIds, collateral0, collateral1, blockNumber }) {
9893
+ const ids = [...tokenIds].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
9894
+ const [tracker0, tracker1] = await Promise.all([collateral0 ?? client.readContract({
9895
+ address: poolAddress,
9896
+ abi: panopticPoolV2Abi,
9897
+ functionName: "collateralToken0",
9898
+ blockNumber
9899
+ }), collateral1 ?? client.readContract({
9900
+ address: poolAddress,
9901
+ abi: panopticPoolV2Abi,
9902
+ functionName: "collateralToken1",
9903
+ blockNumber
9904
+ })]);
9905
+ const [positions, balances0, balances1] = await Promise.all([
9906
+ client.readContract({
9907
+ address: poolAddress,
9908
+ abi: panopticPoolV2Abi,
9909
+ functionName: "getFullPositionsData",
9910
+ args: [
9911
+ account,
9912
+ false,
9913
+ ids
9914
+ ],
9915
+ blockNumber
9916
+ }),
9917
+ client.readContract({
9918
+ address: tracker0,
9919
+ abi: collateralTrackerV2Abi,
9920
+ functionName: "assetsAndInterest",
9921
+ args: [account],
9922
+ blockNumber
9923
+ }),
9924
+ client.readContract({
9925
+ address: tracker1,
9926
+ abi: collateralTrackerV2Abi,
9927
+ functionName: "assetsAndInterest",
9928
+ args: [account],
9929
+ blockNumber
9930
+ })
9931
+ ]);
9932
+ return [
9933
+ positions[0],
9934
+ positions[1],
9935
+ ...positions[2],
9936
+ ...balances0,
9937
+ ...balances1
9938
+ ];
9939
+ }
9940
+ /** A spot-independent sampling grid, including exact liquidation boundaries and their neighbours. */
9941
+ function collateralCurveTicks(tokenIds, liquidationTicks) {
9942
+ const strikes = tokenIds.flatMap((id) => decodeTokenId(id).legs.map((leg) => leg.strike));
9943
+ const center = strikes.length === 0 ? 0n : strikes.reduce((a, b) => a + b, 0n) / BigInt(strikes.length);
9944
+ const ticks = new Set([-887272n, 887272n]);
9945
+ for (let i = 0n; i < 250n; i++) {
9946
+ ticks.add(center - 25000n + 50000n * i / 249n);
9947
+ ticks.add(-887272n + 1774544n * i / 249n);
9948
+ }
9949
+ for (const tick of liquidationTicks) {
9950
+ ticks.add(tick - 1n);
9951
+ ticks.add(tick);
9952
+ ticks.add(tick + 1n);
9953
+ }
9954
+ return [...ticks].filter((tick) => tick >= -887272n && tick <= 887272n).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
9955
+ }
9956
+ /** Collateral requirements and liquidation boundaries evaluated at one block. */
9957
+ async function getCollateralCurve({ client, poolAddress, account, queryAddress, tokenIds, blockNumber: requestedBlockNumber }) {
9958
+ const blockNumber = requestedBlockNumber ?? await client.getBlockNumber();
9959
+ const boundaries = await client.readContract({
9960
+ address: queryAddress,
9961
+ abi: panopticQueryAbi,
9962
+ functionName: "getLiquidationPrices",
9963
+ args: [
9964
+ poolAddress,
9965
+ account,
9966
+ tokenIds
9967
+ ],
9968
+ blockNumber
9969
+ });
9970
+ const liquidationTicks = boundaries.map(BigInt).filter((tick) => tick >= -887272n && tick <= 887272n);
9971
+ const ticks = collateralCurveTicks(tokenIds, liquidationTicks);
9972
+ const contracts = ticks.map((tick) => ({
9973
+ address: queryAddress,
9974
+ abi: panopticQueryAbi,
9975
+ functionName: "checkCollateral",
9976
+ args: [
9977
+ poolAddress,
9978
+ account,
9979
+ tokenIds,
9980
+ Number(tick)
9981
+ ]
9982
+ }));
9983
+ const chunks = [];
9984
+ for (let i = 0; i < contracts.length; i += 100) chunks.push(contracts.slice(i, i + 100));
9985
+ const results = (await Promise.all(chunks.map((batch) => multicall(client, {
9986
+ contracts: batch,
9987
+ blockNumber,
9988
+ allowFailure: false
9989
+ })))).flat();
9990
+ return {
9991
+ blockNumber,
9992
+ liquidationTicks,
9993
+ points: results.map(([collateral0, required0, collateral1, required1], i) => ({
9994
+ tick: ticks[i],
9995
+ collateral0,
9996
+ required0,
9997
+ collateral1,
9998
+ required1
9999
+ }))
10000
+ };
10001
+ }
10002
+
10003
+ //#endregion
10004
+ //#region src/panoptic/v2/reads/positionValueCurve.ts
10005
+ const abi = parseAbi(["function computeNetLiquidationValue(uint256[] positionIdList, uint256 shortPremium, uint256 longPremium, uint256[] positionBalanceArray, int24[] atTicks) pure returns (int256[] value0, int256[] value1)"]);
10006
+ /** Stable identity for a position-dependent curve; premiums and spot are separate inputs. */
10007
+ function positionValueKey(positions) {
10008
+ return [...positions].sort((a, b) => a.tokenId < b.tokenId ? -1 : a.tokenId > b.tokenId ? 1 : 0).map(({ tokenId, positionSize }) => `${tokenId}:${positionSize}`).join(",");
10009
+ }
10010
+ /** All changes in the curve's active liquidity, independent of the current market tick. */
10011
+ function positionValueTicks(positions) {
10012
+ const ticks = new Set([-887272n, 887272n]);
10013
+ for (const { tokenId, positionSize } of positions) {
10014
+ if (tokenId < 0n || tokenId >= 1n << 256n || positionSize <= 0n || positionSize >= 1n << 128n) throw new RangeError("Invalid position id or size");
10015
+ const { legs, tickSpacing } = decodeTokenId(tokenId);
10016
+ for (const leg of legs) {
10017
+ if (leg.width === 0n) continue;
10018
+ const width = leg.width * tickSpacing;
10019
+ const lower = leg.strike - width / 2n;
10020
+ const upper = leg.strike + (width + 1n) / 2n;
10021
+ if (lower < -887272n || upper > 887272n || lower >= upper) throw new RangeError("Invalid position range");
10022
+ ticks.add(lower);
10023
+ ticks.add(upper);
10024
+ }
10025
+ }
10026
+ return [...ticks].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
10027
+ }
10028
+ /** Read the immutable, premium-free part of NLV from the deployed pure calculation. */
10029
+ async function getPositionValueCurve({ client, queryAddress, positions }) {
10030
+ const ticks = positionValueTicks(positions);
10031
+ const [values0, values1] = await client.readContract({
10032
+ address: queryAddress,
10033
+ abi,
10034
+ functionName: "computeNetLiquidationValue",
10035
+ args: [
10036
+ positions.map((p) => p.tokenId),
10037
+ 0n,
10038
+ 0n,
10039
+ positions.map((p) => p.positionSize),
10040
+ ticks.map(Number)
10041
+ ]
10042
+ });
10043
+ return ticks.map((tick, i) => ({
10044
+ tick,
10045
+ value0: values0[i],
10046
+ value1: values1[i]
10047
+ }));
10048
+ }
10049
+ /**
10050
+ * Between leg boundaries, token0 is affine in inverse sqrt price and token1 in sqrt price.
10051
+ * Endpoint interpolation differs from contract integer rounding by at most a few wei per leg.
10052
+ */
10053
+ function preparePositionValueCurve(curve) {
10054
+ if (curve.length < 2) throw new RangeError("Incomplete position value curve");
10055
+ 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");
10056
+ const points = curve.map((point) => ({
10057
+ ...point,
10058
+ sqrt: tickToSqrtPriceX96(point.tick)
10059
+ }));
10060
+ return (tick) => {
10061
+ if (tick < points[0].tick || tick > points[points.length - 1].tick) throw new RangeError("Tick outside position value curve");
10062
+ let lo = 0;
10063
+ let hi = points.length - 1;
10064
+ while (hi - lo > 1) {
10065
+ const mid = Math.floor((lo + hi) / 2);
10066
+ if (points[mid].tick <= tick) lo = mid;
10067
+ else hi = mid;
10068
+ }
10069
+ const left = points[lo];
10070
+ const right = points[hi];
10071
+ const sqrt = tickToSqrtPriceX96(tick);
10072
+ const numerator = sqrt - left.sqrt;
10073
+ const denominator = right.sqrt - left.sqrt;
10074
+ return {
10075
+ value0: left.value0 + (right.value0 - left.value0) * numerator * right.sqrt / (denominator * sqrt),
10076
+ value1: left.value1 + (right.value1 - left.value1) * numerator / denominator
10077
+ };
10078
+ };
10079
+ }
10080
+
10081
+ //#endregion
10082
+ 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, estimateCollateralBreakdown, estimateCollateralRequired, failPendingPosition, feesFromFeeGrowthDelta, fetchSfpmV3PoolId, getAccountBuyingPower, getAccountGreeks, getAccountHistory, getChunkLiquidities, getChunkSpreads, 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, getPositionValueCurve, getPriceHistory, getRealizedPnL, getRequiredCreditForITM, getSafeMode, getStreamiaHistory, getSyncStatus, getTrackedChunks, getTradeHistory, getUniswapFeeHistory, getUniswapV3LpPositionState, getUniswapV3PoolFromId, getUniswapV3PoolInfo, getUniswapV3PoolLiquidities, getUniswapV4LpPositionState, getUniswapV4PoolBasicState, getUniswapV4PoolInfo, getUniswapV4PoolKeyFromId, getUniswapV4PoolLiquidities, interpolateBlocks, isGasError, isNonceError, isRetryableRpcError, isolateGroupTokenId, ladderStrikeSequence, logReturns, marketPnlInQuote, marketRiskFromValues, marketScenario, minePoolAddress, minePoolAddressLocalAsync, multicallRead, netLiquidationValueInQuote, optimizeTokenIdRiskPartners, parseCollateralLog, parsePoolLog, positionValueKey, positionValueTicks, prepareIndicatorCandles, preparePositionValueCurve, previewDeposit, previewMint, previewRedeem, previewWithdraw, quoteLiquidation, quoteOneTokenFlow, quoteSfpmSwap, quoteTemporaryLoanRecovery, quoteTokenShortfallRecovery, realizedBeta, removeTrackedChunks, resolveBlockNumbers, resolveLadderStrike, resolvePanopticPoolFromPoolId, resolveUniswapV4PoolKey, saveClosedPosition, scaleCollateralRequired, scanChunks, screenAccountExact, simulateBatchDispatch, simulateClosePosition, simulateDeployNewPool, simulateDeposit, simulateDispatch, simulateForceExercise, simulateLiquidate, simulateSFPMBurn, simulateSFPMMint, simulateSwapExactIn, simulateSwapExactOut, simulateWithdraw, slippageBpsToTickDistance, watchEvents };
@@ -9,12 +9,14 @@ type VaultTransactionFeeQuote = {
9
9
  maxFeePerGas: bigint;
10
10
  maxPriorityFeePerGas: bigint;
11
11
  minimumMaxFeePerGas: bigint;
12
+ minimumPriorityFeePerGas?: bigint;
12
13
  source: 'fee_history' | 'viem_fallback' | 'rpc_priority_fee' | 'fee_history_p25';
13
14
  };
14
15
  type VaultDeltaHedgeFeeQuote = VaultTransactionFeeQuote & {
15
16
  rawPriorityFeePerGas: bigint;
16
17
  };
17
18
  type VaultSignedTransactionFeeCaps = {
19
+ chainId?: number;
18
20
  gasLimit?: bigint | null;
19
21
  maxFeePerGas: bigint | null;
20
22
  maxPriorityFeePerGas: bigint | null;
@@ -90,9 +92,9 @@ declare function validateVaultSignedTransactionFeeCaps(feeCaps: VaultSignedTrans
90
92
  * Resolve explicit EIP-1559 fees for operator-controlled vault transactions.
91
93
  *
92
94
  * The normal path follows the median p90 priority fee from the last 20 blocks,
93
- * with a 0.1 gwei floor and 3 gwei ceiling. If fee history is unavailable,
94
- * Viem's estimate is used while preserving those bounds and its original
95
- * base-fee allowance.
95
+ * with a 3 gwei ceiling and a 0.1 gwei floor except on chains that do not use
96
+ * tips for ordering. If fee history is unavailable, Viem's estimate is used
97
+ * while preserving those bounds and its original base-fee allowance.
96
98
  */
97
99
  declare function getVaultTransactionFeeQuote<chain extends Chain | undefined>(client: Client<Transport, chain>): Promise<VaultTransactionFeeQuote>;
98
100
  declare function getVaultDeltaHedgeHistoricalFeeQuote<chain extends Chain | undefined>(client: Client<Transport, chain>): Promise<VaultDeltaHedgeFeeQuote>;
@@ -1 +1 @@
1
- {"version":3,"file":"vault-transaction-fees.d.ts","names":["Chain","Client","Transport","MIN_VAULT_PRIORITY_FEE_PER_GAS","MAX_VAULT_PRIORITY_FEE_PER_GAS","MAX_STALE_DELTA_HEDGE_PRIORITY_FEE_PER_GAS","MAX_VAULT_TRANSACTION_GAS_COST","VaultTransactionFeeQuote","VaultDeltaHedgeFeeQuote","VaultSignedTransactionFeeCaps","VaultSignedTransactionFeeValidationResult","VaultTransactionFeeEstimationError","feeHistoryError","fallbackError","Error","VaultTransactionGasCostLimitError","gasLimit","maximumAffordableFeePerGas","minimumRequiredFeePerGas","VaultTransactionReplacementLimitError","code","requiredMaxFeePerGas","requiredMaxPriorityFeePerGas","FeeHistorySnapshot","FallbackFeeEstimate","clampPriorityFee","resolveFeeHistoryQuote","baseFeePerGas","reward","resolveDeltaHedgeFeeHistoryQuote","resolveRpcPriorityFeeQuote","rawPriorityFeePerGas","getVaultTransactionReplacementFeeQuote","originalQuote","historicalQuote","finalReplacement","staleBoundsReplacement","Pick","resolveFallbackQuote","estimatedMaxFeePerGas","estimatedPriorityFeePerGas","applyVaultTransactionGasCostLimit","bufferVaultTransactionGasEstimate","validateVaultSignedTransactionFeeCaps","resolveVaultTransactionFeeQuote","readFeeHistory","readFallbackEstimate","Promise","getVaultTransactionFeeQuote","chain","getVaultDeltaHedgeHistoricalFeeQuote","resolveVaultDeltaHedgeInitialFeeQuote","readRpcQuote","readHistoricalQuote","getVaultDeltaHedgeInitialFeeQuote","__transactionFeeTestUtils"],"sources":["../src/hypoVault/transactionFees.d.ts"],"sourcesContent":null,"mappings":";;;cACqBG,8BAAAA;cACAC,8BAAAA;AADAD,cAEAE,0CAAAA,GAF8B,WAAA;AAC9BD,cAEAE,8BAAAA,GAF8B,kBAAA;AAC9BD,KAETE,wBAAAA,GAFSF;EACAC,YAAAA,EAAAA,MAAAA;EACTC,oBAAAA,EAAAA,MAAwB;EAMxBC,mBAAAA,EAAAA,MAAuB;EAGvBC,MAAAA,EAAAA,aAAAA,GAAAA,eAA6B,GAAA,kBAAA,GAAA,iBAAA;AAKzC,CAAA;AAOqBE,KAfTH,uBAAAA,GAA0BD,wBAeiB,GAAA;EAAA,oBAAA,EAAA,MAAA;CAAA;AAGpBM,KAfvBJ,6BAAAA,GAeuBI;EAAa,QAHgBC,CAAAA,EAAAA,MAAAA,GAAAA,IAAAA;EAAK,YAAA,EAAA,MAAA,GAAA,IAAA;EAQhDC,oBAAAA,EAAAA,MAAAA,GAAAA,IAAAA;CAAiC;AAIpCC,KAnBNN,yCAAAA,GAmBMM;EAAQ,KAAEC,EAAAA,IAAAA;CAA0B,GAAA;EAA0B,KAJjBH,EAAAA,KAAAA;EAAK,IAAA,EAAA,oBAAA,GAAA,gBAAA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;EAAA,eAAA;EAAA,QAAA;EAAA,gBAAA;EAAA;CAAA,EAAA;EAAA,aAAehC,EA1BxDqC,IA0BwDrC,CA1BnDO,wBA0BmDP,EAAAA,cAAAA,GAAAA,sBAAAA,CAAAA;EAAK,eAA6BE,EAzBxFM,uBAyBwFN;EAAS,QAAE+C,EAAAA,MAAAA;EAAK,gBAAvBhD,CAAAA,EAAAA,OAAAA;EAAM,sBAA6BO,CAAAA,EAAAA,OAAAA;CAAuB,CAAA,EArB5JA,uBAqB6HuC;iBAhBzGN,iCAAAA,QAAyClC,6CAA6CA;iBACtFmC,iCAAAA;AA4BAY,iBA3BAX,qCAAAA,CA2BiC,OAAA,EA3BclC,6BA2Bd,EAAA,KAAA,CAAA,EA3BqDF,wBA2BrD,CAAA,EA3BgFG,yCA2BhF;;;;AAA4E;;;;;iBAd7GsC,0CAA0ChD,2BAA2BC,OAAOC,WAAW+C,SAASF,QAAQxC;iBACxG2C,mDAAmDlD,2BAA2BC,OAAOC,WAAW+C,SAASF,QAAQvC;;;;;;iBAajH8C,gDAAgDtD,2BAA2BC,OAAOC,WAAW+C,SAASF,QAAQvC"}
1
+ {"version":3,"file":"vault-transaction-fees.d.ts","names":["Chain","Client","Transport","MIN_VAULT_PRIORITY_FEE_PER_GAS","MAX_VAULT_PRIORITY_FEE_PER_GAS","MAX_STALE_DELTA_HEDGE_PRIORITY_FEE_PER_GAS","MAX_VAULT_TRANSACTION_GAS_COST","VaultTransactionFeeQuote","VaultDeltaHedgeFeeQuote","VaultSignedTransactionFeeCaps","VaultSignedTransactionFeeValidationResult","VaultTransactionFeeEstimationError","feeHistoryError","fallbackError","Error","VaultTransactionGasCostLimitError","gasLimit","maximumAffordableFeePerGas","minimumRequiredFeePerGas","VaultTransactionReplacementLimitError","code","requiredMaxFeePerGas","requiredMaxPriorityFeePerGas","FeeHistorySnapshot","FallbackFeeEstimate","getChainPriorityFeeFloor","clampPriorityFee","resolveFeeHistoryQuote","baseFeePerGas","reward","minimumPriorityFeePerGas","resolveDeltaHedgeFeeHistoryQuote","resolveRpcPriorityFeeQuote","rawPriorityFeePerGas","getVaultTransactionReplacementFeeQuote","originalQuote","historicalQuote","finalReplacement","staleBoundsReplacement","Pick","resolveFallbackQuote","estimatedMaxFeePerGas","estimatedPriorityFeePerGas","applyVaultTransactionGasCostLimit","bufferVaultTransactionGasEstimate","validateVaultSignedTransactionFeeCaps","resolveVaultTransactionFeeQuote","readFeeHistory","readFallbackEstimate","Promise","getVaultTransactionFeeQuote","chain","getVaultDeltaHedgeHistoricalFeeQuote","resolveVaultDeltaHedgeInitialFeeQuote","readRpcQuote","readHistoricalQuote","getVaultDeltaHedgeInitialFeeQuote","__transactionFeeTestUtils"],"sources":["../src/hypoVault/transactionFees.d.ts"],"sourcesContent":null,"mappings":";;;cACqBG,8BAAAA;cACAC,8BAAAA;AADAD,cAEAE,0CAAAA,GAF8B,WAAA;AAC9BD,cAEAE,8BAAAA,GAF8B,kBAAA;AAC9BD,KAETE,wBAAAA,GAFSF;EACAC,YAAAA,EAAAA,MAAAA;EACTC,oBAAAA,EAAAA,MAAwB;EAOxBC,mBAAAA,EAAAA,MAAuB;EAGvBC,wBAAAA,CAAAA,EAAAA,MAA6B;EAM7BC,MAAAA,EAAAA,aAAAA,GAAAA,eAAAA,GAAAA,kBAAyC,GAAA,iBAAA;AAOrD,CAAA;AAAuD,KAhB3CF,uBAAAA,GAA0BD,wBAgBiB,GAAA;EAAA,oBAGrCK,EAAAA,MAAAA;CAAe;AAH+BE,KAbpDL,6BAAAA,GAaoDK;EAAK,OAAA,CAAA,EAAA,MAAA;EAQhDC,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,IAAAA;EAAiC,YAAA,EAAA,MAAA,GAAA,IAAA;EAAA,oBAIpCC,EAAAA,MAAAA,GAAAA,IAAAA;CAAQ;AAA8BE,KAnB5CR,yCAAAA,GAmB4CQ;EAAwB,KAJjBJ,EAAAA,IAAAA;AAAK,CAAA,GAAA;EAU/CK,KAAAA,EA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