@panoptic-eng/sdk 1.0.72 → 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,4 +1,4 @@
1
- import { BatchValidationError, DEFAULT_VEGOID, InputListFailError, InvalidTickLimitsError, InvalidTokenIdParameterError, LEG_BITS, LEG_LIMITS, LEG_MASKS, LoanSlotExhaustedError, MaxRetriesExceededError, MissingPositionIdsError, NoLoanPositionsError, OracleRateLimitedError, PanopticError, PanopticValidationError, PositionSnapshotNotFoundError, ProviderLagError, STANDARD_TICK_WIDTHS, STRIKE_CONVERSION_FACTOR, SwapTokenMismatchError, SyncTimeoutError, TOKEN_ID_BITS, UnsafePremiumSettlementError, collateralTrackerV2Abi, createTxResult, decodeLeftRightUnsigned, decodeOracleTiming, decodePosition, decodeTickSpacing, formatTokenAmount, getBlockMeta, getOpenPositionIds, getPool, getPoolMetaKey, getPoolMetadata, getPositionMetaKey, getPositions, getPositionsKey, getSyncCheckpointKey, getTrackedPositionIds, jsonSerializer, oracleEpochAt, panopticErrorsAbi, panopticFactoryV3Abi, panopticFactoryV4Abi, panopticPoolV2Abi, parsePanopticError, parseTokenAmount, submitWrite } from "./rates-BOGkyjVy.js";
1
+ import { BatchValidationError, InputListFailError, InvalidTickLimitsError, InvalidTokenIdParameterError, LEG_LIMITS, LoanSlotExhaustedError, MaxRetriesExceededError, MissingPositionIdsError, NoLoanPositionsError, OracleRateLimitedError, PanopticError, PanopticValidationError, PositionSnapshotNotFoundError, ProviderLagError, STANDARD_TICK_WIDTHS, SwapTokenMismatchError, SyncTimeoutError, TOKEN_ID_BITS, UnsafePremiumSettlementError, addLegToTokenId, collateralTrackerV2Abi, countLegs, createTxResult, decodeAllLegs, decodeLeftRightUnsigned, decodeLeg, decodeOracleTiming, decodeTickSpacing, decodeTokenId, formatTokenAmount, getBlockMeta, getForfeitablePremium, getOpenPositionIds, getPool, getPoolMetaKey, getPoolMetadata, getPositionMetaKey, getPositions, getPositionsKey, getSyncCheckpointKey, getTrackedPositionIds, isLoan, jsonSerializer, oracleEpochAt, panopticErrorsAbi, panopticFactoryV3Abi, panopticFactoryV4Abi, panopticPoolV2Abi, parsePanopticError, parseTokenAmount, submitWrite } from "./rates-c9XVKm3m.js";
2
2
  import { MAX_TICK, MIN_TICK, REORG_DEPTH, calculatePositionGreeks, priceToTick, roundToTickSpacing, sqrtPriceX96ToTick, tickLimits, tickToPrice, tickToPriceDecimalScaled, tickToSqrtPriceX96 } from "./greeks-CEv-Uex1.js";
3
3
  import { decodeFunctionResult, encodeFunctionData, erc20Abi, getAbiItem } from "viem";
4
4
 
@@ -2093,200 +2093,6 @@ function formatGwei(wei, precision) {
2093
2093
  return `${formatTokenAmount(wei, 9n, precision)} gwei`;
2094
2094
  }
2095
2095
 
2096
- //#endregion
2097
- //#region src/panoptic/v2/tokenId/encoding.ts
2098
- /**
2099
- * Convert a signed strike tick to unsigned representation for encoding.
2100
- *
2101
- * @param strike - The signed strike tick
2102
- * @returns The unsigned representation
2103
- */
2104
- function convertStrikeToUnsigned(strike) {
2105
- if (strike < 0n) return STRIKE_CONVERSION_FACTOR + strike;
2106
- return strike;
2107
- }
2108
- /**
2109
- * Convert an unsigned encoded strike back to signed representation.
2110
- *
2111
- * @param encodedStrike - The unsigned encoded strike
2112
- * @returns The signed strike tick
2113
- */
2114
- function convertStrikeToSigned(encodedStrike) {
2115
- if (encodedStrike > 2n ** 23n - 1n) return encodedStrike - STRIKE_CONVERSION_FACTOR;
2116
- return encodedStrike;
2117
- }
2118
- /**
2119
- * Get the bit offset for a leg at the given index.
2120
- *
2121
- * @param legIndex - The leg index (0-3)
2122
- * @returns The bit offset from the start of the legs section
2123
- */
2124
- function getLegOffset(legIndex) {
2125
- return legIndex * TOKEN_ID_BITS.LEG_SIZE;
2126
- }
2127
- /**
2128
- * Encode a pool ID from a Uniswap V3 pool address.
2129
- *
2130
- * The encoded PoolId structure: [16-bit tickSpacing][8-bit vegoid][40-bit pool address]
2131
- *
2132
- * @param address - The Uniswap V3 pool address
2133
- * @param tickSpacing - The tick spacing of the pool
2134
- * @param vegoid - The vegoid value (defaults to 4)
2135
- * @returns The encoded pool ID
2136
- */
2137
- function encodePoolId(address, tickSpacing, vegoid = DEFAULT_VEGOID) {
2138
- const addressHex = address.slice(2, 12).toLowerCase();
2139
- const bytes = [];
2140
- for (let i = 0; i < 10; i += 2) bytes.push(parseInt(addressHex.slice(i, i + 2), 16));
2141
- bytes.reverse();
2142
- let poolId = 0n;
2143
- for (let i = 0; i < bytes.length; i++) poolId |= BigInt(bytes[i]) << BigInt(i * 8);
2144
- poolId |= (vegoid & 0xffn) << TOKEN_ID_BITS.VEGOID_STARTING_BIT;
2145
- poolId |= (tickSpacing & 0xffffn) << TOKEN_ID_BITS.TICK_SPACING_STARTING_BIT;
2146
- return poolId;
2147
- }
2148
- /**
2149
- * Encode a pool ID from a Uniswap V4 pool ID (bytes32).
2150
- *
2151
- * @param poolIdHex - The V4 pool ID (bytes32 hex string)
2152
- * @param tickSpacing - The tick spacing of the pool
2153
- * @param vegoid - The vegoid value (defaults to 4)
2154
- * @returns The encoded pool ID
2155
- */
2156
- function encodeV4PoolId(poolIdHex, tickSpacing, vegoid = DEFAULT_VEGOID) {
2157
- const hex = poolIdHex.slice(2);
2158
- const last5BytesHex = hex.slice(-10).toLowerCase();
2159
- const bytes = [];
2160
- for (let i = 0; i < 10; i += 2) bytes.push(parseInt(last5BytesHex.slice(i, i + 2), 16));
2161
- bytes.reverse();
2162
- let encodedPoolId = 0n;
2163
- for (let i = 0; i < bytes.length; i++) encodedPoolId |= BigInt(bytes[i]) << BigInt(i * 8);
2164
- encodedPoolId |= (vegoid & 0xffn) << TOKEN_ID_BITS.VEGOID_STARTING_BIT;
2165
- encodedPoolId |= (tickSpacing & 0xffffn) << TOKEN_ID_BITS.TICK_SPACING_STARTING_BIT;
2166
- return encodedPoolId;
2167
- }
2168
- /**
2169
- * Decode the vegoid from a TokenId.
2170
- *
2171
- * @param tokenId - The TokenId to decode
2172
- * @returns The vegoid value
2173
- */
2174
- function decodeVegoid(tokenId) {
2175
- const poolId = tokenId & (1n << TOKEN_ID_BITS.POOL_ID_SIZE) - 1n;
2176
- return poolId >> TOKEN_ID_BITS.VEGOID_STARTING_BIT & (1n << TOKEN_ID_BITS.VEGOID_SIZE) - 1n;
2177
- }
2178
- /**
2179
- * Decode the tick spacing from a TokenId.
2180
- *
2181
- * @param tokenId - The TokenId to decode
2182
- * @returns The tick spacing
2183
- */
2184
- function decodeTickSpacing$1(tokenId) {
2185
- const poolId = tokenId & (1n << TOKEN_ID_BITS.POOL_ID_SIZE) - 1n;
2186
- return poolId >> TOKEN_ID_BITS.TICK_SPACING_STARTING_BIT;
2187
- }
2188
- /**
2189
- * Decode the pool ID portion from a TokenId.
2190
- *
2191
- * @param tokenId - The TokenId to decode
2192
- * @returns The pool ID as a hex string
2193
- */
2194
- function decodePoolId(tokenId) {
2195
- const poolId = tokenId & (1n << TOKEN_ID_BITS.POOL_ID_SIZE) - 1n;
2196
- let hex = poolId.toString(16);
2197
- while (hex.length < 16) hex = "0" + hex;
2198
- return `0x${hex}`;
2199
- }
2200
- /**
2201
- * Encode a single leg field.
2202
- *
2203
- * @param value - The value to encode
2204
- * @param bitPosition - The bit position within the leg
2205
- * @param legIndex - The leg index
2206
- * @returns The encoded value shifted to the correct position
2207
- */
2208
- function encodeLegField(value, bitPosition, legIndex) {
2209
- return value << getLegOffset(legIndex) + bitPosition + TOKEN_ID_BITS.POOL_ID_SIZE;
2210
- }
2211
- /**
2212
- * Encode a single leg into a TokenId.
2213
- *
2214
- * @param leg - The leg parameters
2215
- * @returns The encoded leg value (to be ORed with existing TokenId)
2216
- */
2217
- function encodeLeg(leg) {
2218
- const { index, asset, optionRatio, isLong, tokenType, riskPartner, strike, width } = leg;
2219
- return encodeLegField(asset & LEG_MASKS.ASSET, LEG_BITS.ASSET_BIT, index) | encodeLegField(optionRatio & LEG_MASKS.RATIO, LEG_BITS.RATIO_BIT, index) | encodeLegField(isLong & LEG_MASKS.IS_LONG, LEG_BITS.IS_LONG_BIT, index) | encodeLegField(tokenType & LEG_MASKS.TOKEN_TYPE, LEG_BITS.TOKEN_TYPE_BIT, index) | encodeLegField(riskPartner & LEG_MASKS.RISK_PARTNER, LEG_BITS.RISK_PARTNER_BIT, index) | encodeLegField(convertStrikeToUnsigned(strike) & LEG_MASKS.STRIKE, LEG_BITS.STRIKE_BIT, index) | encodeLegField(width & LEG_MASKS.WIDTH, LEG_BITS.WIDTH_BIT, index);
2220
- }
2221
- /**
2222
- * Add a leg to an existing TokenId.
2223
- *
2224
- * @param tokenId - The existing TokenId (can be just poolId or partial TokenId)
2225
- * @param leg - The leg parameters to add
2226
- * @returns The TokenId with the leg added
2227
- */
2228
- function addLegToTokenId(tokenId, leg) {
2229
- return tokenId | encodeLeg(leg);
2230
- }
2231
- /**
2232
- * Decode a single leg from a TokenId.
2233
- *
2234
- * @param tokenId - The TokenId to decode
2235
- * @param legIndex - The leg index (0-3)
2236
- * @returns The decoded leg data
2237
- */
2238
- function decodeLeg(tokenId, legIndex) {
2239
- const offset = getLegOffset(legIndex) + TOKEN_ID_BITS.POOL_ID_SIZE;
2240
- const leg = tokenId >> offset & LEG_MASKS.LEG;
2241
- const asset = leg & LEG_MASKS.ASSET;
2242
- const optionRatio = leg >> LEG_BITS.RATIO_BIT & LEG_MASKS.RATIO;
2243
- const isLong = (leg >> LEG_BITS.IS_LONG_BIT & LEG_MASKS.IS_LONG) === 1n;
2244
- const tokenType = leg >> LEG_BITS.TOKEN_TYPE_BIT & LEG_MASKS.TOKEN_TYPE;
2245
- const riskPartner = leg >> LEG_BITS.RISK_PARTNER_BIT & LEG_MASKS.RISK_PARTNER;
2246
- const encodedStrike = leg >> LEG_BITS.STRIKE_BIT & LEG_MASKS.STRIKE;
2247
- const strike = convertStrikeToSigned(encodedStrike);
2248
- const width = leg >> LEG_BITS.WIDTH_BIT & LEG_MASKS.WIDTH;
2249
- return {
2250
- index: legIndex,
2251
- asset,
2252
- optionRatio,
2253
- isLong,
2254
- tokenType,
2255
- riskPartner,
2256
- strike,
2257
- width
2258
- };
2259
- }
2260
- /**
2261
- * Count the number of active legs in a TokenId.
2262
- * A leg is active if its optionRatio > 0.
2263
- *
2264
- * @param tokenId - The TokenId to check
2265
- * @returns The number of active legs
2266
- */
2267
- function countLegs(tokenId) {
2268
- let count = 0n;
2269
- for (let i = 0n; i < TOKEN_ID_BITS.MAX_LEGS; i++) {
2270
- const leg = decodeLeg(tokenId, i);
2271
- if (leg.optionRatio > 0n) count++;
2272
- }
2273
- return count;
2274
- }
2275
- /**
2276
- * Decode all active legs from a TokenId.
2277
- *
2278
- * @param tokenId - The TokenId to decode
2279
- * @returns Array of decoded legs (only active legs with optionRatio > 0)
2280
- */
2281
- function decodeAllLegs(tokenId) {
2282
- const legs = [];
2283
- for (let i = 0n; i < TOKEN_ID_BITS.MAX_LEGS; i++) {
2284
- const leg = decodeLeg(tokenId, i);
2285
- if (leg.optionRatio > 0n) legs.push(leg);
2286
- }
2287
- return legs;
2288
- }
2289
-
2290
2096
  //#endregion
2291
2097
  //#region src/panoptic/v2/tokenId/builder.ts
2292
2098
  /**
@@ -2391,181 +2197,6 @@ function createTokenIdBuilder(poolId) {
2391
2197
  return builder;
2392
2198
  }
2393
2199
 
2394
- //#endregion
2395
- //#region src/panoptic/v2/tokenId/decode.ts
2396
- /**
2397
- * Convert a DecodedLeg to TokenIdLeg format.
2398
- *
2399
- * @param leg - The decoded leg from encoding utils
2400
- * @param tickSpacing - The tick spacing for calculating tick bounds
2401
- * @returns The TokenIdLeg format
2402
- */
2403
- function convertToTokenIdLeg(leg, tickSpacing) {
2404
- const halfWidth = leg.width * tickSpacing / 2n;
2405
- const tickLower = leg.strike - halfWidth;
2406
- const tickUpper = leg.strike + halfWidth;
2407
- return {
2408
- index: leg.index,
2409
- asset: leg.asset,
2410
- optionRatio: leg.optionRatio,
2411
- isLong: leg.isLong,
2412
- tokenType: leg.tokenType,
2413
- riskPartner: leg.riskPartner,
2414
- strike: leg.strike,
2415
- width: leg.width,
2416
- tickLower,
2417
- tickUpper
2418
- };
2419
- }
2420
- /**
2421
- * Decode a TokenId into its component parts.
2422
- *
2423
- * @param tokenId - The TokenId to decode
2424
- * @returns The decoded TokenId data
2425
- *
2426
- * @example
2427
- * ```typescript
2428
- * const decoded = decodeTokenId(tokenId)
2429
- * console.log(decoded.legs) // Array of legs
2430
- * console.log(decoded.tickSpacing) // Tick spacing
2431
- * ```
2432
- */
2433
- function decodeTokenId(tokenId) {
2434
- const poolId = decodePoolId(tokenId);
2435
- const vegoid = decodeVegoid(tokenId);
2436
- const tickSpacing = decodeTickSpacing$1(tokenId);
2437
- const rawLegs = decodeAllLegs(tokenId);
2438
- const numLegs = countLegs(tokenId);
2439
- const legs = rawLegs.map((leg) => convertToTokenIdLeg(leg, tickSpacing));
2440
- return {
2441
- tokenId,
2442
- poolId,
2443
- vegoid,
2444
- tickSpacing,
2445
- legs,
2446
- legCount: numLegs
2447
- };
2448
- }
2449
- /**
2450
- * Validate that a TokenId has the expected pool ID.
2451
- *
2452
- * @param tokenId - The TokenId to validate
2453
- * @param expectedPoolId - The expected pool ID
2454
- * @returns True if the pool IDs match
2455
- */
2456
- function validatePoolId(tokenId, expectedPoolId) {
2457
- const actualPoolId = tokenId & (1n << 64n) - 1n;
2458
- return actualPoolId === expectedPoolId;
2459
- }
2460
- /**
2461
- * Check if a TokenId represents a long position (any leg is long).
2462
- *
2463
- * @param tokenId - The TokenId to check
2464
- * @returns True if any leg is long
2465
- */
2466
- function hasLongLeg(tokenId) {
2467
- const legs = decodeAllLegs(tokenId);
2468
- return legs.some((leg) => leg.isLong);
2469
- }
2470
- /**
2471
- * Check if a TokenId represents a short-only position.
2472
- *
2473
- * @param tokenId - The TokenId to check
2474
- * @returns True if all legs are short
2475
- */
2476
- function isShortOnly(tokenId) {
2477
- const legs = decodeAllLegs(tokenId);
2478
- return legs.length > 0 && legs.every((leg) => !leg.isLong);
2479
- }
2480
- /**
2481
- * Check if a TokenId represents a spread (legs with different risk partners).
2482
- *
2483
- * @param tokenId - The TokenId to check
2484
- * @returns True if any leg has a different risk partner
2485
- */
2486
- function isSpread(tokenId) {
2487
- const legs = decodeAllLegs(tokenId);
2488
- return legs.some((leg) => leg.riskPartner !== leg.index);
2489
- }
2490
- /**
2491
- * Get the asset index for a TokenId (from the first leg).
2492
- *
2493
- * @param tokenId - The TokenId
2494
- * @returns The asset index (0 or 1), or undefined if no legs
2495
- */
2496
- function getAssetIndex(tokenId) {
2497
- const legs = decodeAllLegs(tokenId);
2498
- if (legs.length === 0) return void 0;
2499
- return legs[0].asset;
2500
- }
2501
- /**
2502
- * Check if a leg is a loan (width=0 and isLong=false).
2503
- *
2504
- * Loans borrow liquidity from the pool at a specific strike price.
2505
- *
2506
- * @param leg - The decoded leg to check
2507
- * @returns True if the leg is a loan
2508
- */
2509
- function isLoanLeg(leg) {
2510
- return leg.width === 0n && !leg.isLong;
2511
- }
2512
- /**
2513
- * Check if a leg is a credit (width=0 and isLong=true).
2514
- *
2515
- * Credits lend liquidity to the pool at a specific strike price.
2516
- *
2517
- * @param leg - The decoded leg to check
2518
- * @returns True if the leg is a credit
2519
- */
2520
- function isCreditLeg(leg) {
2521
- return leg.width === 0n && leg.isLong;
2522
- }
2523
- /**
2524
- * Check if a TokenId is a pure loan (all legs are loans).
2525
- *
2526
- * @param tokenId - The TokenId to check
2527
- * @returns True if all legs are loans
2528
- */
2529
- function isLoan(tokenId) {
2530
- const legs = decodeAllLegs(tokenId);
2531
- return legs.length > 0 && legs.every(isLoanLeg);
2532
- }
2533
- /**
2534
- * Index of the borrowed token when a TokenId is a single-leg loan.
2535
- *
2536
- * Returns undefined for credits, multi-leg loans, and positions mixing loans
2537
- * with options: closing those can move both tokens for reasons other than
2538
- * repaying one borrowed principal.
2539
- *
2540
- * @param tokenId - The TokenId to classify
2541
- * @returns The borrowed token index (the leg's tokenType), or undefined
2542
- */
2543
- function getSimpleLoanTokenIndex(tokenId) {
2544
- const legs = decodeAllLegs(tokenId);
2545
- if (legs.length !== 1 || !isLoanLeg(legs[0])) return void 0;
2546
- return legs[0].tokenType === 0n ? 0n : 1n;
2547
- }
2548
- /**
2549
- * Check if a TokenId is a pure credit (all legs are credits).
2550
- *
2551
- * @param tokenId - The TokenId to check
2552
- * @returns True if all legs are credits
2553
- */
2554
- function isCredit(tokenId) {
2555
- const legs = decodeAllLegs(tokenId);
2556
- return legs.length > 0 && legs.every(isCreditLeg);
2557
- }
2558
- /**
2559
- * Check if a TokenId contains loan or credit legs (width=0).
2560
- *
2561
- * @param tokenId - The TokenId to check
2562
- * @returns True if any leg has width=0 (loan or credit)
2563
- */
2564
- function hasLoanOrCredit(tokenId) {
2565
- const legs = decodeAllLegs(tokenId);
2566
- return legs.some((leg) => leg.width === 0n);
2567
- }
2568
-
2569
2200
  //#endregion
2570
2201
  //#region src/panoptic/v2/tokenId/deriveUniqueTokenId.ts
2571
2202
  const POOL_ID_MASK$2 = (1n << 64n) - 1n;
@@ -2870,7 +2501,7 @@ function generateOverlappingTokenIds(params) {
2870
2501
  if (params.asset !== 0n && params.asset !== 1n) invalid$1("asset must be 0 or 1");
2871
2502
  if (params.assetDecimals < 0n || params.assetDecimals > MAX_TOKEN_DECIMALS || params.quoteDecimals < 0n || params.quoteDecimals > MAX_TOKEN_DECIMALS) invalid$1("assetDecimals and quoteDecimals must be between 0 and 255");
2872
2503
  if (params.positionSize <= 0n || params.positionSize > MAX_UINT128$2) invalid$1("positionSize must be between 1 and uint128.max");
2873
- const tickSpacing = decodeTickSpacing$1(params.poolId);
2504
+ const tickSpacing = decodeTickSpacing(params.poolId);
2874
2505
  if (tickSpacing <= 0n) invalid$1("poolId tick spacing must be positive");
2875
2506
  const standardTickWidth = STANDARD_TICK_WIDTHS[params.timescale];
2876
2507
  if (standardTickWidth === void 0) invalid$1(`unknown timescale ${String(params.timescale)}`);
@@ -3022,7 +2653,7 @@ function splitGroup(poolId, group, tickSpacing, targetWidth, positionSize) {
3022
2653
  */
3023
2654
  function splitTokenIdByTimescale(tokenId, positionSize, targetTimescale) {
3024
2655
  const legs = validateInput(tokenId, positionSize);
3025
- const tickSpacing = decodeTickSpacing$1(tokenId);
2656
+ const tickSpacing = decodeTickSpacing(tokenId);
3026
2657
  if (tickSpacing <= 0n) invalid("tokenId tick spacing must be positive");
3027
2658
  const targetTickWidth = STANDARD_TICK_WIDTHS[targetTimescale];
3028
2659
  if (targetTickWidth === void 0) invalid(`unknown target timescale ${String(targetTimescale)}`);
@@ -3147,7 +2778,7 @@ function buildUniquePoke(sourceTokenId, occupied) {
3147
2778
  for (let assetMask = 0n; assetMask < assetVariants; assetMask += 1n) {
3148
2779
  const tokenId = encodePokeToken(sourceTokenId, shortChunkLegs, firstRatio, assetMask);
3149
2780
  if (!occupied.has(tokenId)) {
3150
- const size = minimumPokeSize(decodeAllLegs(tokenId), decodeTickSpacing$1(sourceTokenId));
2781
+ const size = minimumPokeSize(decodeAllLegs(tokenId), decodeTickSpacing(sourceTokenId));
3151
2782
  if (size !== void 0) return {
3152
2783
  tokenId,
3153
2784
  size
@@ -3246,261 +2877,6 @@ async function getCurrentPositionSizes(params) {
3246
2877
  return positionBalances.map((packed) => packed & BIT_MASK_128$1);
3247
2878
  }
3248
2879
 
3249
- //#endregion
3250
- //#region src/panoptic/v2/reads/premia.ts
3251
- /**
3252
- * Get streamia totals for an account.
3253
- *
3254
- * Returns the total short and long streamia across all positions.
3255
- * Short streamia is owed TO the account (earned from selling options).
3256
- * Long streamia is owed BY the account (paid for buying options).
3257
- *
3258
- * @param params - The parameters
3259
- * @returns Streamia totals with block metadata
3260
- *
3261
- * @example
3262
- * ```typescript
3263
- * const streamia = await getAccountPremia({
3264
- * client,
3265
- * poolAddress,
3266
- * account,
3267
- * tokenIds: [tokenId1, tokenId2],
3268
- * includePendingPremium: true,
3269
- * })
3270
- *
3271
- * console.log('Short streamia earned:', streamia.shortPremium0, streamia.shortPremium1)
3272
- * console.log('Long streamia owed:', streamia.longPremium0, streamia.longPremium1)
3273
- * ```
3274
- */
3275
- async function getAccountPremia(params) {
3276
- const { client, poolAddress, account, tokenIds, includePendingPremium = true, blockNumber } = params;
3277
- const targetBlockNumber = blockNumber ?? params._meta?.blockNumber ?? await client.getBlockNumber();
3278
- if (tokenIds.length === 0) {
3279
- const _meta$1 = params._meta ?? await getBlockMeta({
3280
- client,
3281
- blockNumber: targetBlockNumber
3282
- });
3283
- return {
3284
- shortPremium0: 0n,
3285
- shortPremium1: 0n,
3286
- longPremium0: 0n,
3287
- longPremium1: 0n,
3288
- includePendingPremium,
3289
- _meta: _meta$1
3290
- };
3291
- }
3292
- const [[shortPremiumPacked, longPremiumPacked], _meta] = await Promise.all([client.readContract({
3293
- address: poolAddress,
3294
- abi: panopticPoolV2Abi,
3295
- functionName: "getFullPositionsData",
3296
- args: [
3297
- account,
3298
- includePendingPremium,
3299
- tokenIds
3300
- ],
3301
- blockNumber: targetBlockNumber
3302
- }), params._meta ?? getBlockMeta({
3303
- client,
3304
- blockNumber: targetBlockNumber
3305
- })]);
3306
- const shortPremium = decodeLeftRightUnsigned(shortPremiumPacked);
3307
- const longPremium = decodeLeftRightUnsigned(longPremiumPacked);
3308
- return {
3309
- shortPremium0: shortPremium.right,
3310
- shortPremium1: shortPremium.left,
3311
- longPremium0: longPremium.right,
3312
- longPremium1: longPremium.left,
3313
- includePendingPremium,
3314
- _meta
3315
- };
3316
- }
3317
- /**
3318
- * Get positions with per-position streamia data.
3319
- *
3320
- * Uses multicall to batch individual getFullPositionsData calls
3321
- * for each position, giving us per-position streamia in a single RPC request.
3322
- *
3323
- * @param params - The parameters
3324
- * @returns Positions with streamia and totals with block metadata
3325
- *
3326
- * @example
3327
- * ```typescript
3328
- * const result = await getPositionsWithPremia({
3329
- * client,
3330
- * poolAddress,
3331
- * account,
3332
- * tokenIds: [tokenId1, tokenId2],
3333
- * })
3334
- *
3335
- * for (const position of result.positions) {
3336
- * console.log('Position:', position.tokenId)
3337
- * console.log('Streamia:', position.premiaOwed0, position.premiaOwed1)
3338
- * }
3339
- * console.log('Total short streamia:', result.shortPremium0, result.shortPremium1)
3340
- * ```
3341
- */
3342
- async function getPositionsWithPremia(params) {
3343
- const { client, poolAddress, account, tokenIds, includePendingPremium = true, blockNumber } = params;
3344
- const targetBlockNumber = blockNumber ?? params._meta?.blockNumber ?? await client.getBlockNumber();
3345
- if (tokenIds.length === 0) {
3346
- const _meta$1 = params._meta ?? await getBlockMeta({
3347
- client,
3348
- blockNumber: targetBlockNumber
3349
- });
3350
- return {
3351
- positions: [],
3352
- shortPremium0: 0n,
3353
- shortPremium1: 0n,
3354
- longPremium0: 0n,
3355
- longPremium1: 0n,
3356
- includePendingPremium,
3357
- _meta: _meta$1
3358
- };
3359
- }
3360
- const contracts = tokenIds.map((tokenId) => ({
3361
- address: poolAddress,
3362
- abi: panopticPoolV2Abi,
3363
- functionName: "getFullPositionsData",
3364
- args: [
3365
- account,
3366
- includePendingPremium,
3367
- [tokenId]
3368
- ]
3369
- }));
3370
- const [multicallResults, _meta] = await Promise.all([client.multicall({
3371
- contracts,
3372
- blockNumber: targetBlockNumber,
3373
- allowFailure: true
3374
- }), params._meta ?? getBlockMeta({
3375
- client,
3376
- blockNumber: targetBlockNumber
3377
- })]);
3378
- const positions = [];
3379
- let totalShortPremium0 = 0n;
3380
- let totalShortPremium1 = 0n;
3381
- let totalLongPremium0 = 0n;
3382
- let totalLongPremium1 = 0n;
3383
- for (let i = 0; i < tokenIds.length; i++) {
3384
- const tokenId = tokenIds[i];
3385
- const result = multicallResults[i];
3386
- if (result.status !== "success") continue;
3387
- const [shortPremiumPacked, longPremiumPacked, balances] = result.result;
3388
- const shortPremium = decodeLeftRightUnsigned(shortPremiumPacked);
3389
- const longPremium = decodeLeftRightUnsigned(longPremiumPacked);
3390
- totalShortPremium0 += shortPremium.right;
3391
- totalShortPremium1 += shortPremium.left;
3392
- totalLongPremium0 += longPremium.right;
3393
- totalLongPremium1 += longPremium.left;
3394
- const balanceData = balances[0];
3395
- if (balanceData === void 0) continue;
3396
- const positionSize = balanceData & (1n << 128n) - 1n;
3397
- if (positionSize === 0n) continue;
3398
- const poolUtilization0 = balanceData >> 128n & 0xffffn;
3399
- const poolUtilization1 = balanceData >> 144n & 0xffffn;
3400
- let tickAtMint = balanceData >> 160n & 0xffffffn;
3401
- if (tickAtMint > 0x7fffffn) tickAtMint = tickAtMint - 0x1000000n;
3402
- const timestampAtMint = balanceData >> 184n & 0xffffffffn;
3403
- const blockAtMint = balanceData >> 216n & (1n << 39n) - 1n;
3404
- const swapAtMint = balanceData >> 255n === 1n;
3405
- const decoded = decodePosition(tokenId);
3406
- const tickSpacing = decodeTickSpacing(tokenId);
3407
- const legs = decoded.legs.map((leg) => {
3408
- const width = leg.width;
3409
- const strike = leg.strike;
3410
- const tickLower = strike - width * tickSpacing / 2n;
3411
- const tickUpper = strike + width * tickSpacing / 2n;
3412
- return {
3413
- index: BigInt(leg.index),
3414
- asset: leg.asset,
3415
- optionRatio: leg.optionRatio,
3416
- isLong: leg.isLong === 1n,
3417
- tokenType: leg.tokenType,
3418
- riskPartner: leg.riskPartner,
3419
- strike,
3420
- width,
3421
- tickLower,
3422
- tickUpper
3423
- };
3424
- });
3425
- const premiaOwed0 = shortPremium.right - longPremium.right;
3426
- const premiaOwed1 = shortPremium.left - longPremium.left;
3427
- positions.push({
3428
- tokenId,
3429
- positionSize,
3430
- owner: account,
3431
- poolAddress,
3432
- legs,
3433
- poolUtilization0AtMint: poolUtilization0,
3434
- poolUtilization1AtMint: poolUtilization1,
3435
- tickAtMint,
3436
- timestampAtMint,
3437
- blockNumberAtMint: blockAtMint,
3438
- swapAtMint,
3439
- premiaOwed0,
3440
- premiaOwed1,
3441
- assetIndex: legs.length > 0 ? legs[0].asset : 0n,
3442
- _meta
3443
- });
3444
- }
3445
- return {
3446
- positions,
3447
- shortPremium0: totalShortPremium0,
3448
- shortPremium1: totalShortPremium1,
3449
- longPremium0: totalLongPremium0,
3450
- longPremium1: totalLongPremium1,
3451
- includePendingPremium,
3452
- _meta
3453
- };
3454
- }
3455
- /**
3456
- * Get the unsettled short streamia an account would forfeit by closing now.
3457
- *
3458
- * Calls `getFullPositionsData` twice in one multicall — once with
3459
- * `includePendingPremium = true` (everything owed to the short legs) and once
3460
- * with `false` (only what is available to collect). The difference is the
3461
- * streamia still owed by buyers that has not been settled; closing before it
3462
- * settles forfeits it. Settling buyers first (see `settlePremiumFrom`) moves
3463
- * that streamia into the available bucket.
3464
- *
3465
- * @param params - The parameters
3466
- * @returns Owed, available, and forfeitable streamia with block metadata
3467
- */
3468
- async function getForfeitablePremium(params) {
3469
- const { client, poolAddress, account, tokenIds, blockNumber } = params;
3470
- const targetBlockNumber = blockNumber ?? await client.getBlockNumber();
3471
- const contracts = [true, false].map((includePendingPremium) => ({
3472
- address: poolAddress,
3473
- abi: panopticPoolV2Abi,
3474
- functionName: "getFullPositionsData",
3475
- args: [
3476
- account,
3477
- includePendingPremium,
3478
- tokenIds
3479
- ]
3480
- }));
3481
- const [multicallResults, _meta] = await Promise.all([client.multicall({
3482
- contracts,
3483
- blockNumber: targetBlockNumber,
3484
- allowFailure: false
3485
- }), getBlockMeta({
3486
- client,
3487
- blockNumber: targetBlockNumber
3488
- })]);
3489
- const owed = decodeLeftRightUnsigned(multicallResults[0][0]);
3490
- const available = decodeLeftRightUnsigned(multicallResults[1][0]);
3491
- const forfeit0 = owed.right > available.right ? owed.right - available.right : 0n;
3492
- const forfeit1 = owed.left > available.left ? owed.left - available.left : 0n;
3493
- return {
3494
- owed0: owed.right,
3495
- owed1: owed.left,
3496
- available0: available.right,
3497
- available1: available.left,
3498
- forfeit0,
3499
- forfeit1,
3500
- _meta
3501
- };
3502
- }
3503
-
3504
2880
  //#endregion
3505
2881
  //#region src/panoptic/v2/simulations/tokenFlow.ts
3506
2882
  /**
@@ -5968,4 +5344,4 @@ async function smartRepayAndWait(params) {
5968
5344
  }
5969
5345
 
5970
5346
  //#endregion
5971
- export { addLegToTokenId, approve, approveAndWait, approvePool, borrow, borrowAndWait, buildBatchDispatchArgs, buildCreditSwapCall, buildOpenPositionCalldata, buildProtectedSettleDispatch, buildProtectedSettlePlan, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, buildUniqueWidthZeroLeg, calculateResyncBlock, cancelTransaction, checkApproval, clearCheckpoint, closePosition, closePositionAndWait, countLegs, createNonceManager, createPoolFormatters, createTokenIdBuilder, decodeAllLegs, decodeLeg, decodePoolId, decodeTickSpacing$1, decodeTokenId, decodeVegoid, deployNewPool, deployNewPoolAndWait, deposit, depositAndWait, deriveUniqueTokenId, detectReorg, dispatch, dispatchAndWait, encodeLeg, encodePoolId, encodeV4PoolId, executeBatchDispatch, executeBatchDispatchAndWait, executeSettleSequence, executeSettleSequenceAndWait, forceExercise, forceExerciseAndWait, formatBlockNumber, formatBps, formatCompact, formatDatetime, formatDuration, formatDurationSeconds, formatFeeTier, formatGas, formatGwei, formatPoolIdHex, formatRatioPercent, formatTimestamp, formatTimestampLocale, formatTokenIdHex, formatTokenIdShort, formatTxHash, formatUtilization, formatWei, generateOverlappingTokenIds, getAccountPremia, getAssetIndex, getCurrentPositionSizes, getForfeitablePremium, getPoolDeploymentBlock, getPoolDisplayId, getPoolTokensForSimulation, getPositionsWithPremia, getSimpleLoanTokenIndex, getTokenIdValidationError, getTokenListId, hasLoanOrCredit, hasLongLeg, isCredit, isCreditLeg, isInputListFailError, isLoan, isLoanLeg, isShortOnly, isSpread, liquidate, liquidateAndWait, loadCheckpoint, mint, mintAndWait, openPosition, openPositionAndWait, orderListForSettle, parseBps, parseTokenListId, planDeriveStrategy, pokeOracle, pokeOracleAndWait, previewBorrow, previewRepay, previewUnwrap, previewWrap, publicBroadcaster, reconstructFromEvents, redeem, redeemAndWait, repay, repayAndWait, resolveTokenIndex, rollPosition, rollPositionAndWait, saveCheckpoint, settleAccumulatedPremia, settleAccumulatedPremiaAndWait, settlePremiumFrom, settlePremiumFromAndWait, simulateDispatch, simulateOpenPosition, simulateSettle, simulateSettlePremiumBatch, simulateSettlePremiumFrom, simulateSettleSequence, simulateWithTokenFlow, smartRepay, smartRepayAndWait, speedUpTransaction, splitTokenIdByTimescale, supply, supplyAndWait, swapExactIn, swapExactInAndWait, swapExactOut, swapExactOutAndWait, syncPositions, truncateAddress, unsupply, unsupplyAndWait, unwrapWeth, unwrapWethAndWait, unwrapXstock, unwrapXstockAndWait, validateBatch, validatePoolId, verifyBlockContinuity, wethWrapAbi, withdraw, withdrawAndWait, withdrawWithPositions, withdrawWithPositionsAndWait, wrapEth, wrapEthAndWait, wrapXstock, wrapXstockAndWait, xstockWrapperAbi };
5347
+ export { approve, approveAndWait, approvePool, borrow, borrowAndWait, buildBatchDispatchArgs, buildCreditSwapCall, buildOpenPositionCalldata, buildProtectedSettleDispatch, buildProtectedSettlePlan, buildSettleSequenceCalls, buildUniqueCredit, buildUniqueLoan, buildUniqueWidthZeroLeg, calculateResyncBlock, cancelTransaction, checkApproval, clearCheckpoint, closePosition, closePositionAndWait, createNonceManager, createPoolFormatters, createTokenIdBuilder, deployNewPool, deployNewPoolAndWait, deposit, depositAndWait, deriveUniqueTokenId, detectReorg, dispatch, dispatchAndWait, executeBatchDispatch, executeBatchDispatchAndWait, executeSettleSequence, executeSettleSequenceAndWait, forceExercise, forceExerciseAndWait, formatBlockNumber, formatBps, formatCompact, formatDatetime, formatDuration, formatDurationSeconds, formatFeeTier, formatGas, formatGwei, formatPoolIdHex, formatRatioPercent, formatTimestamp, formatTimestampLocale, formatTokenIdHex, formatTokenIdShort, formatTxHash, formatUtilization, formatWei, generateOverlappingTokenIds, getCurrentPositionSizes, getPoolDeploymentBlock, getPoolDisplayId, getPoolTokensForSimulation, getTokenIdValidationError, getTokenListId, isInputListFailError, liquidate, liquidateAndWait, loadCheckpoint, mint, mintAndWait, openPosition, openPositionAndWait, orderListForSettle, parseBps, parseTokenListId, planDeriveStrategy, pokeOracle, pokeOracleAndWait, previewBorrow, previewRepay, previewUnwrap, previewWrap, publicBroadcaster, reconstructFromEvents, redeem, redeemAndWait, repay, repayAndWait, resolveTokenIndex, rollPosition, rollPositionAndWait, saveCheckpoint, settleAccumulatedPremia, settleAccumulatedPremiaAndWait, settlePremiumFrom, settlePremiumFromAndWait, simulateDispatch, simulateOpenPosition, simulateSettle, simulateSettlePremiumBatch, simulateSettlePremiumFrom, simulateSettleSequence, simulateWithTokenFlow, smartRepay, smartRepayAndWait, speedUpTransaction, splitTokenIdByTimescale, supply, supplyAndWait, swapExactIn, swapExactInAndWait, swapExactOut, swapExactOutAndWait, syncPositions, truncateAddress, unsupply, unsupplyAndWait, unwrapWeth, unwrapWethAndWait, unwrapXstock, unwrapXstockAndWait, validateBatch, verifyBlockContinuity, wethWrapAbi, withdraw, withdrawAndWait, withdrawWithPositions, withdrawWithPositionsAndWait, wrapEth, wrapEthAndWait, wrapXstock, wrapXstockAndWait, xstockWrapperAbi };