@panoptic-eng/sdk 1.0.63 → 1.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/StateView-q4yMpBY6.js +323 -0
- package/dist/cow/index.d.ts +1 -1
- package/dist/cow/index.js +1 -1
- package/dist/cow/index.js.map +1 -1
- package/dist/{cow-BsSaoahK.js → cow-BU9YOHkh.js} +1 -1
- package/dist/index.d.ts +34 -34
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/{irm-BDlcUNgJ.js → irm-DGyKOQXz.js} +4 -326
- package/dist/panoptic/v2/index.d.ts +161 -137
- package/dist/panoptic/v2/index.d.ts.map +1 -1
- package/dist/panoptic/v2/index.js +61 -51
- package/dist/panoptic/v2/index.js.map +1 -1
- package/dist/panoptic/v2/react-public.d.ts +168 -144
- package/dist/panoptic/v2/react-public.d.ts.map +1 -1
- package/dist/panoptic/v2/react-public.js +64 -54
- package/dist/panoptic/v2/react-public.js.map +1 -1
- package/dist/{rates-BwZnK0tG.js → rates-Y0Pbv1_x.js} +4 -4
- package/dist/{router-pm9PDlyH.js → router-CheXbrfz.js} +2 -2
- package/dist/{router-Dejb6MWu.js → router-DxE-iwYF.js} +304 -6
- package/dist/{transactionFees-aXQlx-lq.js → transactionFees-BF033Mob.js} +1 -1
- package/dist/uniswap/index.d.ts +194 -4
- package/dist/uniswap/index.d.ts.map +1 -1
- package/dist/uniswap/index.js +1316 -789
- package/dist/uniswap/index.js.map +1 -1
- package/dist/{v2-ccGPXWvq.js → v2-QFSAShVj.js} +29 -316
- package/dist/{writes--fM_8ggw.js → writes-BA21eyGF.js} +38 -38
- package/dist/zodiac/index.d.ts +3 -3
- package/dist/zodiac/index.js +3 -3
- package/dist/zodiac/index.js.map +1 -1
- package/package.json +1 -1
- /package/dist/{chainDeployments-BhXMBZ4B.js → chainDeployments-Do4NaZA_.js} +0 -0
- /package/dist/{greeks-CNi1-cnp.js → greeks-CGtgLUyh.js} +0 -0
- /package/dist/{providers-1WdiaRbY.js → providers-DubVMHWU.js} +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
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-
|
|
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-
|
|
4
|
-
import { addLegToTokenId, buildBatchDispatchArgs, buildUniqueCredit, buildUniqueLoan, countLegs, createTokenIdBuilder, decodeAllLegs, decodeTokenId, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateDispatch, simulateOpenPosition, simulateWithTokenFlow } from "./writes
|
|
5
|
-
import { getLpPositionFunding, getMaxLpPositionSize, preparePositionGamma } from "./router-
|
|
6
|
-
import {
|
|
1
|
+
import { getAccountCollateral, panopticQueryAbi$1 as panopticQueryAbi, readBlockAndAggregate, requireReturnData } from "./irm-DGyKOQXz.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-Y0Pbv1_x.js";
|
|
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-CGtgLUyh.js";
|
|
4
|
+
import { addLegToTokenId, buildBatchDispatchArgs, buildUniqueCredit, buildUniqueLoan, countLegs, createTokenIdBuilder, decodeAllLegs, decodeTokenId, getPoolTokensForSimulation, loadCheckpoint, resolveTokenIndex, simulateDispatch, simulateOpenPosition, simulateWithTokenFlow } from "./writes-BA21eyGF.js";
|
|
5
|
+
import { feesFromFeeGrowthDelta, getLpPositionFunding, getMaxLpPositionSize, getPriceHistory, preparePositionGamma } from "./router-DxE-iwYF.js";
|
|
6
|
+
import { ContractFunctionExecutionError, decodeFunctionResult, encodeAbiParameters, encodeFunctionData, getAddress, hexToString, keccak256, parseAbi, parseEventLogs, trim, zeroAddress } from "viem";
|
|
7
7
|
import { multicall } from "viem/actions";
|
|
8
8
|
import Decimal from "decimal.js";
|
|
9
9
|
|
|
@@ -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$
|
|
168
|
+
const Q128$2 = 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
|
|
@@ -177,14 +177,14 @@ function assertPositivePrice(sqrtPriceX96) {
|
|
|
177
177
|
/** Convert a token0 amount to its token1-equivalent at the given sqrtPriceX96. */
|
|
178
178
|
function convert0to1$2(amount, sqrtPriceX96) {
|
|
179
179
|
assertPositivePrice(sqrtPriceX96);
|
|
180
|
-
if (sqrtPriceX96 < Q128$
|
|
180
|
+
if (sqrtPriceX96 < Q128$2) 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
185
|
function convert1to0$2(amount, sqrtPriceX96) {
|
|
186
186
|
assertPositivePrice(sqrtPriceX96);
|
|
187
|
-
if (sqrtPriceX96 < Q128$
|
|
187
|
+
if (sqrtPriceX96 < Q128$2) {
|
|
188
188
|
const denom = sqrtPriceX96 * sqrtPriceX96;
|
|
189
189
|
return amount * (1n << 192n) / denom;
|
|
190
190
|
}
|
|
@@ -203,7 +203,7 @@ function convertToTokenIndex(amount, fromTokenIndex, toTokenIndex, sqrtPriceX96)
|
|
|
203
203
|
//#endregion
|
|
204
204
|
//#region src/panoptic/v2/reads/margin.ts
|
|
205
205
|
const FP96$1 = 1n << 96n;
|
|
206
|
-
const Q128$
|
|
206
|
+
const Q128$1 = 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;
|
|
@@ -215,7 +215,7 @@ const bigintMin = (a, b) => a < b ? a : b;
|
|
|
215
215
|
* overflow-safe branch when `sqrtPriceX96^2` would not fit in uint256.
|
|
216
216
|
*/
|
|
217
217
|
function convert0to1$1(amount, sqrtPriceX96) {
|
|
218
|
-
if (sqrtPriceX96 < Q128$
|
|
218
|
+
if (sqrtPriceX96 < Q128$1) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
|
|
219
219
|
const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
|
|
220
220
|
return amount * sp2Hi >> 128n;
|
|
221
221
|
}
|
|
@@ -223,7 +223,7 @@ function convert0to1$1(amount, sqrtPriceX96) {
|
|
|
223
223
|
* Convert a token1 amount to its token0-equivalent at the given sqrtPriceX96.
|
|
224
224
|
*/
|
|
225
225
|
function convert1to0$1(amount, sqrtPriceX96) {
|
|
226
|
-
if (sqrtPriceX96 < Q128$
|
|
226
|
+
if (sqrtPriceX96 < Q128$1) {
|
|
227
227
|
const denom = sqrtPriceX96 * sqrtPriceX96;
|
|
228
228
|
return amount * (1n << 192n) / denom;
|
|
229
229
|
}
|
|
@@ -3264,10 +3264,10 @@ async function getSafeMode(params) {
|
|
|
3264
3264
|
//#endregion
|
|
3265
3265
|
//#region src/panoptic/v2/reads/queryUtils.ts
|
|
3266
3266
|
/**
|
|
3267
|
-
* Get portfolio value (NAV) without
|
|
3267
|
+
* Get portfolio value (NAV) without streamia.
|
|
3268
3268
|
*
|
|
3269
3269
|
* This calculates the net asset value of the portfolio based on Uniswap liquidity
|
|
3270
|
-
* at a given tick, excluding accumulated
|
|
3270
|
+
* at a given tick, excluding accumulated streamia. Useful for PnL tracking separate
|
|
3271
3271
|
* from liquidation value.
|
|
3272
3272
|
*
|
|
3273
3273
|
* ## Same-Block Guarantee
|
|
@@ -3974,7 +3974,7 @@ async function getCollateralTotalAssetsBatch(client, collateralTrackerAddresses,
|
|
|
3974
3974
|
|
|
3975
3975
|
//#endregion
|
|
3976
3976
|
//#region src/panoptic/v2/reads/buyingPower.ts
|
|
3977
|
-
const Q128
|
|
3977
|
+
const Q128 = 1n << 128n;
|
|
3978
3978
|
/** Immutable collateral tracker addresses, suitable for a pool-scoped cache. */
|
|
3979
3979
|
async function getPoolCollateralAddresses(params) {
|
|
3980
3980
|
const [collateralToken0, collateralToken1] = await multicall(params.client, {
|
|
@@ -3996,12 +3996,12 @@ async function getPoolCollateralAddresses(params) {
|
|
|
3996
3996
|
};
|
|
3997
3997
|
}
|
|
3998
3998
|
function convert0to1(amount, sqrtPriceX96) {
|
|
3999
|
-
if (sqrtPriceX96 < Q128
|
|
3999
|
+
if (sqrtPriceX96 < Q128) return amount * sqrtPriceX96 * sqrtPriceX96 >> 192n;
|
|
4000
4000
|
const sp2Hi = sqrtPriceX96 * sqrtPriceX96 >> 64n;
|
|
4001
4001
|
return amount * sp2Hi >> 128n;
|
|
4002
4002
|
}
|
|
4003
4003
|
function convert1to0(amount, sqrtPriceX96) {
|
|
4004
|
-
if (sqrtPriceX96 < Q128
|
|
4004
|
+
if (sqrtPriceX96 < Q128) {
|
|
4005
4005
|
const denom = sqrtPriceX96 * sqrtPriceX96;
|
|
4006
4006
|
return amount * (1n << 192n) / denom;
|
|
4007
4007
|
}
|
|
@@ -4400,7 +4400,7 @@ function computeUniswapFeesForBlock(blockData, legs) {
|
|
|
4400
4400
|
total1
|
|
4401
4401
|
};
|
|
4402
4402
|
}
|
|
4403
|
-
const MAX_UINT256
|
|
4403
|
+
const MAX_UINT256 = 2n ** 256n - 1n;
|
|
4404
4404
|
/**
|
|
4405
4405
|
* Fee growth per unit of liquidity inside `[lowerTick, upperTick)` at one block,
|
|
4406
4406
|
* wrapped to uint256 as the pool computes it. Diff two snapshots with
|
|
@@ -4414,7 +4414,7 @@ function feeGrowthInsideX128(blockData, lowerTick, upperTick) {
|
|
|
4414
4414
|
const inside = (global, lowerOutside, upperOutside) => {
|
|
4415
4415
|
const below = currentTick >= lowerTick ? lowerOutside : global - lowerOutside;
|
|
4416
4416
|
const above = currentTick < upperTick ? upperOutside : global - upperOutside;
|
|
4417
|
-
return global - below - above & MAX_UINT256
|
|
4417
|
+
return global - below - above & MAX_UINT256;
|
|
4418
4418
|
};
|
|
4419
4419
|
return {
|
|
4420
4420
|
feeGrowthInside0X128: inside(blockData.feeGrowthGlobal0, lower.feeGrowthOutside0, upper.feeGrowthOutside0),
|
|
@@ -4534,7 +4534,7 @@ const MASK_128 = (1n << 128n) - 1n;
|
|
|
4534
4534
|
* Get historical streamia data for a position across multiple blocks.
|
|
4535
4535
|
*
|
|
4536
4536
|
* @param params - The parameters
|
|
4537
|
-
* @returns Snapshots of Panoptic
|
|
4537
|
+
* @returns Snapshots of Panoptic streamia and Uniswap fee deltas at each block
|
|
4538
4538
|
*/
|
|
4539
4539
|
async function getStreamiaHistory(params) {
|
|
4540
4540
|
const { client, panopticPoolAddress, account, tokenId, blockNumbers, legs, poolConfig, includeUniswapFees = true, settledEvents } = params;
|
|
@@ -5046,293 +5046,6 @@ async function getUniswapV4PoolLiquidities(params) {
|
|
|
5046
5046
|
};
|
|
5047
5047
|
}
|
|
5048
5048
|
|
|
5049
|
-
//#endregion
|
|
5050
|
-
//#region src/panoptic/v2/reads/uniswapLpPosition.ts
|
|
5051
|
-
const nfpmAbi = [{
|
|
5052
|
-
type: "function",
|
|
5053
|
-
name: "positions",
|
|
5054
|
-
inputs: [{
|
|
5055
|
-
name: "tokenId",
|
|
5056
|
-
type: "uint256"
|
|
5057
|
-
}],
|
|
5058
|
-
outputs: [
|
|
5059
|
-
{
|
|
5060
|
-
name: "nonce",
|
|
5061
|
-
type: "uint96"
|
|
5062
|
-
},
|
|
5063
|
-
{
|
|
5064
|
-
name: "operator",
|
|
5065
|
-
type: "address"
|
|
5066
|
-
},
|
|
5067
|
-
{
|
|
5068
|
-
name: "token0",
|
|
5069
|
-
type: "address"
|
|
5070
|
-
},
|
|
5071
|
-
{
|
|
5072
|
-
name: "token1",
|
|
5073
|
-
type: "address"
|
|
5074
|
-
},
|
|
5075
|
-
{
|
|
5076
|
-
name: "fee",
|
|
5077
|
-
type: "uint24"
|
|
5078
|
-
},
|
|
5079
|
-
{
|
|
5080
|
-
name: "tickLower",
|
|
5081
|
-
type: "int24"
|
|
5082
|
-
},
|
|
5083
|
-
{
|
|
5084
|
-
name: "tickUpper",
|
|
5085
|
-
type: "int24"
|
|
5086
|
-
},
|
|
5087
|
-
{
|
|
5088
|
-
name: "liquidity",
|
|
5089
|
-
type: "uint128"
|
|
5090
|
-
},
|
|
5091
|
-
{
|
|
5092
|
-
name: "feeGrowthInside0LastX128",
|
|
5093
|
-
type: "uint256"
|
|
5094
|
-
},
|
|
5095
|
-
{
|
|
5096
|
-
name: "feeGrowthInside1LastX128",
|
|
5097
|
-
type: "uint256"
|
|
5098
|
-
},
|
|
5099
|
-
{
|
|
5100
|
-
name: "tokensOwed0",
|
|
5101
|
-
type: "uint128"
|
|
5102
|
-
},
|
|
5103
|
-
{
|
|
5104
|
-
name: "tokensOwed1",
|
|
5105
|
-
type: "uint128"
|
|
5106
|
-
}
|
|
5107
|
-
],
|
|
5108
|
-
stateMutability: "view"
|
|
5109
|
-
}, {
|
|
5110
|
-
type: "function",
|
|
5111
|
-
name: "collect",
|
|
5112
|
-
inputs: [{
|
|
5113
|
-
name: "params",
|
|
5114
|
-
type: "tuple",
|
|
5115
|
-
components: [
|
|
5116
|
-
{
|
|
5117
|
-
name: "tokenId",
|
|
5118
|
-
type: "uint256"
|
|
5119
|
-
},
|
|
5120
|
-
{
|
|
5121
|
-
name: "recipient",
|
|
5122
|
-
type: "address"
|
|
5123
|
-
},
|
|
5124
|
-
{
|
|
5125
|
-
name: "amount0Max",
|
|
5126
|
-
type: "uint128"
|
|
5127
|
-
},
|
|
5128
|
-
{
|
|
5129
|
-
name: "amount1Max",
|
|
5130
|
-
type: "uint128"
|
|
5131
|
-
}
|
|
5132
|
-
]
|
|
5133
|
-
}],
|
|
5134
|
-
outputs: [{
|
|
5135
|
-
name: "amount0",
|
|
5136
|
-
type: "uint256"
|
|
5137
|
-
}, {
|
|
5138
|
-
name: "amount1",
|
|
5139
|
-
type: "uint256"
|
|
5140
|
-
}],
|
|
5141
|
-
stateMutability: "payable"
|
|
5142
|
-
}];
|
|
5143
|
-
const MAX_UINT128$1 = 2n ** 128n - 1n;
|
|
5144
|
-
const MAX_UINT256 = 2n ** 256n - 1n;
|
|
5145
|
-
const Q128 = 2n ** 128n;
|
|
5146
|
-
/**
|
|
5147
|
-
* Whether an error thrown by a viem contract call is an on-chain revert (as
|
|
5148
|
-
* opposed to a transport/RPC failure such as a timeout or rate limit).
|
|
5149
|
-
*/
|
|
5150
|
-
function isContractRevert(error) {
|
|
5151
|
-
return error instanceof BaseError && error.walk((err) => err instanceof ContractFunctionRevertedError || err instanceof ExecutionRevertedError) != null;
|
|
5152
|
-
}
|
|
5153
|
-
/**
|
|
5154
|
-
* Fetch a Uniswap V3 LP position's state and uncollected fees.
|
|
5155
|
-
*
|
|
5156
|
-
* Fees come from simulating `collect` with max amounts as the owner — one
|
|
5157
|
-
* eth_call returning the exact claimable amounts (tokensOwed + fee growth
|
|
5158
|
-
* since the last poke). The simulation is best-effort: if it reverts (e.g.
|
|
5159
|
-
* an empty position), fees fall back to 0.
|
|
5160
|
-
*/
|
|
5161
|
-
async function getUniswapV3LpPositionState(params) {
|
|
5162
|
-
const { client, nfpmAddress, tokenId, owner, blockNumber } = params;
|
|
5163
|
-
const _meta = await getBlockMeta({
|
|
5164
|
-
client,
|
|
5165
|
-
blockNumber
|
|
5166
|
-
});
|
|
5167
|
-
const position = await client.readContract({
|
|
5168
|
-
address: nfpmAddress,
|
|
5169
|
-
abi: nfpmAbi,
|
|
5170
|
-
functionName: "positions",
|
|
5171
|
-
args: [tokenId],
|
|
5172
|
-
blockNumber: _meta.blockNumber
|
|
5173
|
-
});
|
|
5174
|
-
const [, , token0, token1, fee, tickLower, tickUpper, liquidity] = position;
|
|
5175
|
-
let fees0 = 0n;
|
|
5176
|
-
let fees1 = 0n;
|
|
5177
|
-
try {
|
|
5178
|
-
const { result } = await client.simulateContract({
|
|
5179
|
-
address: nfpmAddress,
|
|
5180
|
-
abi: nfpmAbi,
|
|
5181
|
-
functionName: "collect",
|
|
5182
|
-
args: [{
|
|
5183
|
-
tokenId,
|
|
5184
|
-
recipient: owner,
|
|
5185
|
-
amount0Max: MAX_UINT128$1,
|
|
5186
|
-
amount1Max: MAX_UINT128$1
|
|
5187
|
-
}],
|
|
5188
|
-
account: owner,
|
|
5189
|
-
blockNumber: _meta.blockNumber
|
|
5190
|
-
});
|
|
5191
|
-
[fees0, fees1] = result;
|
|
5192
|
-
} catch (error) {
|
|
5193
|
-
if (!isContractRevert(error)) throw error;
|
|
5194
|
-
}
|
|
5195
|
-
return {
|
|
5196
|
-
token0,
|
|
5197
|
-
token1,
|
|
5198
|
-
fee: Number(fee),
|
|
5199
|
-
tickLower: Number(tickLower),
|
|
5200
|
-
tickUpper: Number(tickUpper),
|
|
5201
|
-
liquidity,
|
|
5202
|
-
fees0,
|
|
5203
|
-
fees1,
|
|
5204
|
-
_meta
|
|
5205
|
-
};
|
|
5206
|
-
}
|
|
5207
|
-
/**
|
|
5208
|
-
* Uncollected fees from a feeGrowthInside delta, mirroring v4-core's
|
|
5209
|
-
* `Position.calculatePositionFeesAccrued`: the subtraction wraps around
|
|
5210
|
-
* uint256 (feeGrowthInside can legitimately underflow in-protocol).
|
|
5211
|
-
*/
|
|
5212
|
-
function feesFromFeeGrowthDelta(feeGrowthInsideCurrentX128, feeGrowthInsideLastX128, liquidity) {
|
|
5213
|
-
const delta = feeGrowthInsideCurrentX128 - feeGrowthInsideLastX128 & MAX_UINT256;
|
|
5214
|
-
return delta * liquidity / Q128;
|
|
5215
|
-
}
|
|
5216
|
-
/**
|
|
5217
|
-
* Fetch a Uniswap V4 LP position's state and uncollected fees via StateView.
|
|
5218
|
-
*
|
|
5219
|
-
* The position inside PoolManager is keyed by (positionManager, tickLower,
|
|
5220
|
-
* tickUpper, salt) where posm uses `bytes32(tokenId)` as the salt. Fees on
|
|
5221
|
-
* pools with fee-taking hooks may be approximate.
|
|
5222
|
-
*/
|
|
5223
|
-
async function getUniswapV4LpPositionState(params) {
|
|
5224
|
-
const { client, stateViewAddress, positionManagerAddress, poolId, tokenId, tickLower, tickUpper, blockNumber } = params;
|
|
5225
|
-
const salt = toHex(tokenId, { size: 32 });
|
|
5226
|
-
const _meta = await getBlockMeta({
|
|
5227
|
-
client,
|
|
5228
|
-
blockNumber
|
|
5229
|
-
});
|
|
5230
|
-
const [positionInfo, feeGrowthInside] = await client.multicall({
|
|
5231
|
-
allowFailure: false,
|
|
5232
|
-
blockNumber: _meta.blockNumber,
|
|
5233
|
-
contracts: [{
|
|
5234
|
-
address: stateViewAddress,
|
|
5235
|
-
abi: StateViewAbi,
|
|
5236
|
-
functionName: "getPositionInfo",
|
|
5237
|
-
args: [
|
|
5238
|
-
poolId,
|
|
5239
|
-
positionManagerAddress,
|
|
5240
|
-
tickLower,
|
|
5241
|
-
tickUpper,
|
|
5242
|
-
salt
|
|
5243
|
-
]
|
|
5244
|
-
}, {
|
|
5245
|
-
address: stateViewAddress,
|
|
5246
|
-
abi: StateViewAbi,
|
|
5247
|
-
functionName: "getFeeGrowthInside",
|
|
5248
|
-
args: [
|
|
5249
|
-
poolId,
|
|
5250
|
-
tickLower,
|
|
5251
|
-
tickUpper
|
|
5252
|
-
]
|
|
5253
|
-
}]
|
|
5254
|
-
});
|
|
5255
|
-
const [liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128] = positionInfo;
|
|
5256
|
-
const [feeGrowthInside0X128, feeGrowthInside1X128] = feeGrowthInside;
|
|
5257
|
-
return {
|
|
5258
|
-
liquidity,
|
|
5259
|
-
tickLower,
|
|
5260
|
-
tickUpper,
|
|
5261
|
-
fees0: feesFromFeeGrowthDelta(feeGrowthInside0X128, feeGrowthInside0LastX128, liquidity),
|
|
5262
|
-
fees1: feesFromFeeGrowthDelta(feeGrowthInside1X128, feeGrowthInside1LastX128, liquidity),
|
|
5263
|
-
_meta
|
|
5264
|
-
};
|
|
5265
|
-
}
|
|
5266
|
-
|
|
5267
|
-
//#endregion
|
|
5268
|
-
//#region src/panoptic/v2/reads/priceHistory.ts
|
|
5269
|
-
/**
|
|
5270
|
-
* Get historical price data (tick + sqrtPriceX96) for a pool across multiple blocks.
|
|
5271
|
-
*
|
|
5272
|
-
* @param params - The parameters
|
|
5273
|
-
* @returns Price snapshots at each block
|
|
5274
|
-
*
|
|
5275
|
-
* @example
|
|
5276
|
-
* ```typescript
|
|
5277
|
-
* const { snapshots } = await getPriceHistory({
|
|
5278
|
-
* client,
|
|
5279
|
-
* blockNumbers: [18000000n, 18000100n, 18000200n],
|
|
5280
|
-
* poolConfig: { version: 'v3', poolAddress: '0x...' },
|
|
5281
|
-
* })
|
|
5282
|
-
*
|
|
5283
|
-
* for (const snap of snapshots) {
|
|
5284
|
-
* console.log(`Block ${snap.blockNumber}: tick=${snap.tick}`)
|
|
5285
|
-
* }
|
|
5286
|
-
* ```
|
|
5287
|
-
*/
|
|
5288
|
-
async function getPriceHistory(params) {
|
|
5289
|
-
const { client, blockNumbers, poolConfig } = params;
|
|
5290
|
-
if (blockNumbers.length === 0) {
|
|
5291
|
-
const _meta$1 = params._meta ?? await getBlockMeta({ client });
|
|
5292
|
-
return {
|
|
5293
|
-
snapshots: [],
|
|
5294
|
-
_meta: _meta$1
|
|
5295
|
-
};
|
|
5296
|
-
}
|
|
5297
|
-
const slot0Requests = blockNumbers.map((bn) => fetchSlot0(client, bn, poolConfig));
|
|
5298
|
-
const [slot0Results, _meta] = await Promise.all([Promise.all(slot0Requests), params._meta ? Promise.resolve(params._meta) : getBlockMeta({ client })]);
|
|
5299
|
-
const snapshots = slot0Results.map((result, i) => ({
|
|
5300
|
-
blockNumber: blockNumbers[i],
|
|
5301
|
-
tick: result.tick,
|
|
5302
|
-
sqrtPriceX96: result.sqrtPriceX96
|
|
5303
|
-
}));
|
|
5304
|
-
return {
|
|
5305
|
-
snapshots,
|
|
5306
|
-
_meta
|
|
5307
|
-
};
|
|
5308
|
-
}
|
|
5309
|
-
async function fetchSlot0(client, blockNumber, poolConfig) {
|
|
5310
|
-
if (poolConfig.version === "v3") {
|
|
5311
|
-
const result = await client.readContract({
|
|
5312
|
-
address: poolConfig.poolAddress,
|
|
5313
|
-
abi: uniswapV3PoolAbi,
|
|
5314
|
-
functionName: "slot0",
|
|
5315
|
-
blockNumber
|
|
5316
|
-
});
|
|
5317
|
-
return {
|
|
5318
|
-
sqrtPriceX96: result[0],
|
|
5319
|
-
tick: result[1]
|
|
5320
|
-
};
|
|
5321
|
-
} else {
|
|
5322
|
-
const result = await client.readContract({
|
|
5323
|
-
address: poolConfig.stateViewAddress,
|
|
5324
|
-
abi: stateViewAbi,
|
|
5325
|
-
functionName: "getSlot0",
|
|
5326
|
-
args: [poolConfig.poolId],
|
|
5327
|
-
blockNumber
|
|
5328
|
-
});
|
|
5329
|
-
return {
|
|
5330
|
-
sqrtPriceX96: result[0],
|
|
5331
|
-
tick: result[1]
|
|
5332
|
-
};
|
|
5333
|
-
}
|
|
5334
|
-
}
|
|
5335
|
-
|
|
5336
5049
|
//#endregion
|
|
5337
5050
|
//#region src/panoptic/v2/reads/enrichment.ts
|
|
5338
5051
|
/**
|
|
@@ -5350,17 +5063,17 @@ var EnrichmentCallError = class extends PanopticError {
|
|
|
5350
5063
|
}
|
|
5351
5064
|
};
|
|
5352
5065
|
/**
|
|
5353
|
-
* Fetch enrichment data (
|
|
5066
|
+
* Fetch enrichment data (streamia, portfolio values, collateral requirements) for a set of positions.
|
|
5354
5067
|
*
|
|
5355
5068
|
* Batches all needed contract reads into efficient multicalls:
|
|
5356
5069
|
* - **Open positions**: 3 calls per position in a single multicall at current block:
|
|
5357
|
-
* 1. `getFullPositionsData` →
|
|
5070
|
+
* 1. `getFullPositionsData` → streamia + collateral requirements
|
|
5358
5071
|
* 2. `getPortfolioValue` at currentTick → current portfolio value
|
|
5359
5072
|
* 3. `getPortfolioValue` at mintTick → portfolio value at mint
|
|
5360
5073
|
* - **Closed positions**: 2 calls per position at `burnBlockNumber - 1`:
|
|
5361
5074
|
* 1. `getPortfolioValue` at burnTick → portfolio value at close
|
|
5362
5075
|
* 2. `getPortfolioValue` at mintTick → portfolio value at mint
|
|
5363
|
-
* (
|
|
5076
|
+
* (streamia come from subgraph `burnPremium0/1`)
|
|
5364
5077
|
*
|
|
5365
5078
|
* ## Same-Block Guarantee
|
|
5366
5079
|
* Open position data is fetched at a single block number.
|
|
@@ -9871,7 +9584,7 @@ function netLiquidationValueInQuote(value0, value1, tick, isAssetToken0) {
|
|
|
9871
9584
|
const price = new Decimal("1.0001").pow(tick.toString());
|
|
9872
9585
|
return isAssetToken0 ? new Decimal(value1.toString()).plus(new Decimal(value0.toString()).mul(price)) : new Decimal(value0.toString()).plus(new Decimal(value1.toString()).div(price));
|
|
9873
9586
|
}
|
|
9874
|
-
/** Apply the accrued-
|
|
9587
|
+
/** Apply the accrued-streamia offset and optional asset collateral to a relative NLV curve. */
|
|
9875
9588
|
function marketPnlInQuote({ relativeValue, premium, assetBalance = 0n, price, baselinePrice }) {
|
|
9876
9589
|
return new Decimal(relativeValue).plus(premium).plus(new Decimal(assetBalance.toString()).mul(new Decimal(price).minus(baselinePrice)));
|
|
9877
9590
|
}
|
|
@@ -10020,7 +9733,7 @@ async function getCollateralCurve({ client, poolAddress, account, queryAddress,
|
|
|
10020
9733
|
//#endregion
|
|
10021
9734
|
//#region src/panoptic/v2/reads/positionValueCurve.ts
|
|
10022
9735
|
const abi = parseAbi(["function computeNetLiquidationValue(uint256[] positionIdList, uint256 shortPremium, uint256 longPremium, uint256[] positionBalanceArray, int24[] atTicks) pure returns (int256[] value0, int256[] value1)"]);
|
|
10023
|
-
/** Stable identity for a position-dependent curve;
|
|
9736
|
+
/** Stable identity for a position-dependent curve; streamia and spot are separate inputs. */
|
|
10024
9737
|
function positionValueKey(positions) {
|
|
10025
9738
|
return [...positions].sort((a, b) => a.tokenId < b.tokenId ? -1 : a.tokenId > b.tokenId ? 1 : 0).map(({ tokenId, positionSize }) => `${tokenId}:${positionSize}`).join(",");
|
|
10026
9739
|
}
|
|
@@ -10206,7 +9919,7 @@ async function getPositionVolatilityHistory({ client, poolAddress, account, toke
|
|
|
10206
9919
|
logs: receipt.logs.filter((log) => log.address.toLowerCase() === poolAddress.toLowerCase()),
|
|
10207
9920
|
eventName: "AccountLiquidated"
|
|
10208
9921
|
});
|
|
10209
|
-
if (liquidations.some((event) => event.args.liquidatee.toLowerCase() === account.toLowerCase())) throw new Error("Liquidation
|
|
9922
|
+
if (liquidations.some((event) => event.args.liquidatee.toLowerCase() === account.toLowerCase())) throw new Error("Liquidation streamia requires haircut reconciliation");
|
|
10210
9923
|
for (const packed of close.args.premiaByLeg) {
|
|
10211
9924
|
const amounts = unpack(packed);
|
|
10212
9925
|
settled.push({
|
|
@@ -10251,7 +9964,7 @@ async function getPositionVolatilityHistory({ client, poolAddress, account, toke
|
|
|
10251
9964
|
})
|
|
10252
9965
|
});
|
|
10253
9966
|
const openingAccrual = premium[0];
|
|
10254
|
-
if (!openingAccrual || openingAccrual.timestamp !== start.blockTimestamp) throw new Error("Opening
|
|
9967
|
+
if (!openingAccrual || openingAccrual.timestamp !== start.blockTimestamp) throw new Error("Opening streamia snapshot missing");
|
|
10255
9968
|
premium = premium.map((snapshot) => ({
|
|
10256
9969
|
timestamp: snapshot.timestamp,
|
|
10257
9970
|
token0: snapshot.token0 - openingAccrual.token0,
|
|
@@ -10259,7 +9972,7 @@ async function getPositionVolatilityHistory({ client, poolAddress, account, toke
|
|
|
10259
9972
|
}));
|
|
10260
9973
|
} catch (error) {
|
|
10261
9974
|
premium = null;
|
|
10262
|
-
premiumError = error instanceof Error ? error.message : "
|
|
9975
|
+
premiumError = error instanceof Error ? error.message : "Streamia history unavailable";
|
|
10263
9976
|
}
|
|
10264
9977
|
if (includeBaseFees) try {
|
|
10265
9978
|
const feeBlocks = close ? blockNumbers.filter((block) => block < finalBlock) : blockNumbers;
|
|
@@ -10311,4 +10024,4 @@ async function getPositionVolatilityHistory({ client, poolAddress, account, toke
|
|
|
10311
10024
|
}
|
|
10312
10025
|
|
|
10313
10026
|
//#endregion
|
|
10314
|
-
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, feeGrowthInsideX128,
|
|
10027
|
+
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, feeGrowthInsideX128, fetchSfpmV3PoolId, fetchUniswapFeeData, 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, 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, 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, simulateForceExercise, simulateLiquidate, simulateSFPMBurn, simulateSFPMMint, simulateSwapExactIn, simulateSwapExactOut, simulateWithdraw, slippageBpsToTickDistance, watchEvents };
|