@panoptic-eng/sdk 1.0.46 → 1.0.48

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 +1 @@
1
- {"version":3,"file":"index.js","names":["COW_SETTLEMENT: Address","COW_VAULT_RELAYER: Address","COW_NATIVE_ETH: Address","COW_API_URLS: Partial<Record<number, string>>","chainId: bigint | number","balanceData: bigint","value: bigint","logs: Log[]","events: PanopticEvent[]","client: PublicClient","hash: Hash","confirmations?: bigint","params: SubmitWriteParams","hash","gasOverrides: Record<string, unknown>","message: string","cause?: Error","Q192","tick: bigint","params: CheckCowApprovalParams","params: ApproveErc20ForCowParams","BPS_DENOMINATOR","params: PickBestVenueParams","chainId: bigint | number","chainId: bigint","cause?: Error","errorType: string","message: string","status: number","chainId: bigint","apiUrl?: string","baseUrl: string","path: string","init?: RequestInit","body: CowApiErrorBody","params: SignAndSubmitCowOrderParams","params: CancelCowOrderParams","slippageBps: bigint","params: QuoteCowSwapParams","params: GetCowOrderStatusParams","settlementTxHash: Hex | undefined","COINGECKO_CHAIN_SLUGS: Partial<Record<number, string>>","chainId: number","url: string","params: FindCowTokenParams","address: Address","XSTOCK_WRAPPERS: XstockWrapperRegistry","chainId: number","underlying: Address","wrapper: Address","address: Address"],"sources":["../../src/cow/addresses.ts","../../src/generated.ts","../../src/panoptic/v2/writes/utils.ts","../../src/panoptic/v2/errors/base.ts","../../src/panoptic/v2/errors/errorsAbi.ts","../../src/panoptic/v2/errors/parser.ts","../../src/panoptic/v2/utils/constants.ts","../../src/panoptic/v2/sync/snapshotRecovery.ts","../../src/panoptic/v2/formatters/tick.ts","../../src/panoptic/v2/utils/oraclePack.ts","../../src/panoptic/v2/utils/oracleSafeMode.ts","../../src/panoptic/v2/greeks/index.ts","../../src/panoptic/v2/tokenId/constants.ts","../../src/panoptic/v2/utils/option-encoding-v2.ts","../../src/panoptic/v2/sync/eventReconstruction.ts","../../src/panoptic/v2/reads/positionSizes.ts","../../src/panoptic/v2/simulations/tokenFlow.ts","../../src/cow/approval.ts","../../src/cow/compare.ts","../../src/cow/eip712.ts","../../src/cow/errors.ts","../../src/cow/api.ts","../../src/cow/order.ts","../../src/cow/quote.ts","../../src/cow/status.ts","../../src/cow/tokens.ts","../../src/cow/xstockWrappers.generated.ts","../../src/cow/xstockWrappers.ts"],"sourcesContent":["/**\n * CoW Protocol contract addresses and order-book API endpoints.\n *\n * Both contracts are deployed deterministically (CREATE2) and share the same\n * address on every supported chain.\n *\n * @module cow/addresses\n */\n\nimport type { Address } from 'viem'\n\n/** GPv2Settlement — EIP-712 verifying contract for signed orders. */\nexport const COW_SETTLEMENT: Address = '0x9008D19f58AAbD9eD0D60971565AA8510560ab41'\n\n/** GPv2VaultRelayer — the ERC20 approval target (NOT the settlement contract). */\nexport const COW_VAULT_RELAYER: Address = '0xC92E8bdf79f0507f65a392b0ab4667716BFE0110'\n\n/**\n * Buy-token marker for native ETH. Orders buying this sentinel settle in\n * native ETH (the settlement contract unwraps WETH). Only valid on the buy\n * side — selling native ETH requires the eth-flow contract (unsupported here).\n */\nexport const COW_NATIVE_ETH: Address = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\n\n/** Order-book API base URL per chain. */\nexport const COW_API_URLS: Partial<Record<number, string>> = {\n 1: 'https://api.cow.fi/mainnet',\n 11155111: 'https://api.cow.fi/sepolia',\n}\n\n/** Whether CoW Protocol has an order book for the chain. */\nexport function isCowSupportedChain(chainId: bigint | number): boolean {\n return COW_API_URLS[Number(chainId)] !== undefined\n}\n","//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// CollateralTrackerV2\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const collateralTrackerV2Abi = [\n { type: 'constructor', inputs: [], stateMutability: 'nonpayable' },\n {\n type: 'function',\n inputs: [],\n name: 'accrueInterest',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'spender', internalType: 'address', type: 'address' },\n ],\n name: 'allowance',\n outputs: [{ name: 'allowance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'asset',\n outputs: [{ name: 'assetTokenAddress', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'assetsAndInterest',\n outputs: [\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'assetsOf',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'account', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'borrowIndex',\n outputs: [{ name: '', internalType: 'uint80', type: 'uint80' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'convertToAssets',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'convertToShares',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'decimals',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'delegatee', internalType: 'address', type: 'address' }],\n name: 'delegate',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n ],\n name: 'deposit',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getPoolData',\n outputs: [\n { name: 'depositedAssets', internalType: 'uint256', type: 'uint256' },\n { name: 'insideAMM', internalType: 'uint256', type: 'uint256' },\n { name: 'creditedShares', internalType: 'uint256', type: 'uint256' },\n {\n name: 'currentPoolUtilization',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'interestRate',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'user', internalType: 'address', type: 'address' }],\n name: 'interestState',\n outputs: [\n { name: 'userBorrowIndex', internalType: 'int128', type: 'int128' },\n { name: 'netBorrows', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'lastInteractionTimestamp',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'maxDeposit',\n outputs: [{ name: 'maxAssets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'maxMint',\n outputs: [{ name: 'maxShares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'maxRedeem',\n outputs: [{ name: 'maxShares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'maxWithdraw',\n outputs: [{ name: 'maxAssets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'shares', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n ],\n name: 'mint',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'owedInterest',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'panopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolFee',\n outputs: [{ name: '_poolFee', internalType: 'uint24', type: 'uint24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolManager',\n outputs: [{ name: '', internalType: 'contract IPoolManager', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'previewDeposit',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'previewMint',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'previewOwedInterest',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'previewRedeem',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'previewWithdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'rateAtTarget',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'shares', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n ],\n name: 'redeem',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'refunder', internalType: 'address', type: 'address' },\n { name: 'refundee', internalType: 'address', type: 'address' },\n { name: 'assets', internalType: 'int256', type: 'int256' },\n ],\n name: 'refund',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'delegatee', internalType: 'address', type: 'address' }],\n name: 'revoke',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'riskEngine',\n outputs: [{ name: '', internalType: 'contract IRiskEngine', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'optionOwner', internalType: 'address', type: 'address' },\n { name: 'longAmount', internalType: 'int128', type: 'int128' },\n { name: 'shortAmount', internalType: 'int128', type: 'int128' },\n { name: 'ammDeltaAmount', internalType: 'int128', type: 'int128' },\n { name: 'realizedPremium', internalType: 'int128', type: 'int128' },\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n ],\n name: 'settleBurn',\n outputs: [{ name: '', internalType: 'int128', type: 'int128' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'liquidator', internalType: 'address', type: 'address' },\n { name: 'liquidatee', internalType: 'address', type: 'address' },\n { name: 'bonus', internalType: 'int256', type: 'int256' },\n ],\n name: 'settleLiquidation',\n outputs: [],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'optionOwner', internalType: 'address', type: 'address' },\n { name: 'longAmount', internalType: 'int128', type: 'int128' },\n { name: 'shortAmount', internalType: 'int128', type: 'int128' },\n { name: 'ammDeltaAmount', internalType: 'int128', type: 'int128' },\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n ],\n name: 'settleMint',\n outputs: [\n { name: '', internalType: 'uint32', type: 'uint32' },\n { name: '', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'token0',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'token1',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'totalAssets',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'totalSupply',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transfer',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'underlyingIsToken0',\n outputs: [{ name: '_underlyingIsToken0', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'underlyingToken',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes', type: 'bytes' }],\n name: 'unlockCallback',\n outputs: [{ name: '', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'unrealizedGlobalInterest',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n ],\n name: 'withdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n ],\n name: 'withdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'builder',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'commissionPaidProtocol',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n {\n name: 'commissionPaidBuilder',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'CommissionPaid',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'sender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'assets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'shares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Deposit',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'interestOwed',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'interestPaid',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'sharesBurned',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'InsolvencyPenaltyApplied',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'liquidatee',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'liquidator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'protocolLossAssets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'protocolLossShares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'ProtocolLossRealized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Transfer',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'sender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'receiver',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'assets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'shares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Withdraw',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'BelowMinimumRedemption' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'DepositTooLarge' },\n { type: 'error', inputs: [], name: 'ExceedsMaximumRedemption' },\n {\n type: 'error',\n inputs: [\n { name: 'tokenAddress', internalType: 'address', type: 'address' },\n { name: 'assetsRequested', internalType: 'uint256', type: 'uint256' },\n { name: 'assetBalance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'NotEnoughTokens',\n },\n { type: 'error', inputs: [], name: 'NotPanopticPool' },\n { type: 'error', inputs: [], name: 'PositionCountNotZero' },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnauthorizedUniswapCallback' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticFactoryV3\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticFactoryV3Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_SFPM',\n internalType: 'contract SemiFungiblePositionManagerV3',\n type: 'address',\n },\n {\n name: '_univ3Factory',\n internalType: 'contract IUniswapV3Factory',\n type: 'address',\n },\n { name: '_poolReference', internalType: 'address', type: 'address' },\n {\n name: '_collateralReference',\n internalType: 'address',\n type: 'address',\n },\n { name: 'properties', internalType: 'bytes32[]', type: 'bytes32[]' },\n { name: 'indices', internalType: 'uint256[][]', type: 'uint256[][]' },\n { name: 'pointers', internalType: 'Pointer[][]', type: 'uint256[][]' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'panopticPool', internalType: 'address', type: 'address' },\n { name: 'symbol0', internalType: 'string', type: 'string' },\n { name: 'symbol1', internalType: 'string', type: 'string' },\n { name: 'fee', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'constructMetadata',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token0', internalType: 'address', type: 'address' },\n { name: 'token1', internalType: 'address', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n ],\n name: 'deployNewPool',\n outputs: [\n {\n name: 'newPoolContract',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n name: 'getApproved',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'univ3pool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n ],\n name: 'getPanopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'deployerAddress', internalType: 'address', type: 'address' },\n { name: 'v3Pool', internalType: 'address', type: 'address' },\n { name: 'riskEngine', internalType: 'address', type: 'address' },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n { name: 'loops', internalType: 'uint256', type: 'uint256' },\n { name: 'minTargetRarity', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'minePoolAddress',\n outputs: [\n { name: 'bestSalt', internalType: 'uint96', type: 'uint96' },\n { name: 'highestRarity', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'id', internalType: 'uint256', type: 'uint256' }],\n name: 'ownerOf',\n outputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'tokenId', internalType: 'uint256', type: 'uint256' }],\n name: 'tokenURI',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolAddress',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n {\n name: 'uniswapPool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n indexed: true,\n },\n {\n name: 'collateralTracker0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'collateralTracker1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n indexed: false,\n },\n ],\n name: 'PoolDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Transfer',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CreateFail' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticFactoryV4\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticFactoryV4Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_SFPM',\n internalType: 'contract SemiFungiblePositionManagerV4',\n type: 'address',\n },\n {\n name: '_manager',\n internalType: 'contract IPoolManager',\n type: 'address',\n },\n { name: '_poolReference', internalType: 'address', type: 'address' },\n {\n name: '_collateralReference',\n internalType: 'address',\n type: 'address',\n },\n { name: 'properties', internalType: 'bytes32[]', type: 'bytes32[]' },\n { name: 'indices', internalType: 'uint256[][]', type: 'uint256[][]' },\n { name: 'pointers', internalType: 'Pointer[][]', type: 'uint256[][]' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'panopticPool', internalType: 'address', type: 'address' },\n { name: 'symbol0', internalType: 'string', type: 'string' },\n { name: 'symbol1', internalType: 'string', type: 'string' },\n { name: 'fee', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'constructMetadata',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n ],\n name: 'deployNewPool',\n outputs: [\n {\n name: 'newPoolContract',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n name: 'getApproved',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'keyV4',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n ],\n name: 'getPanopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'deployerAddress', internalType: 'address', type: 'address' },\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n { name: 'riskEngine', internalType: 'address', type: 'address' },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n { name: 'loops', internalType: 'uint256', type: 'uint256' },\n { name: 'minTargetRarity', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'minePoolAddress',\n outputs: [\n { name: 'bestSalt', internalType: 'uint96', type: 'uint96' },\n { name: 'highestRarity', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'id', internalType: 'uint256', type: 'uint256' }],\n name: 'ownerOf',\n outputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'tokenId', internalType: 'uint256', type: 'uint256' }],\n name: 'tokenURI',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolAddress',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'collateralTracker0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'collateralTracker1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n indexed: false,\n },\n ],\n name: 'PoolDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Transfer',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CreateFail' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticGuardian\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticGuardianAbi = [\n {\n type: 'constructor',\n inputs: [\n { name: 'guardianAdmin', internalType: 'address', type: 'address' },\n { name: 'treasurer', internalType: 'address', type: 'address' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'GUARDIAN_ADMIN',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TREASURER',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'UNLOCK_DELAY',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'builderAdminRevoked',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'cancelUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n { name: 'builderAdmin', internalType: 'address', type: 'address' },\n {\n name: 'builderFactory',\n internalType: 'contract BuilderFactory',\n type: 'address',\n },\n ],\n name: 'deployBuilder',\n outputs: [{ name: 'wallet', internalType: 'address', type: 'address' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'executeUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'isBuilderAdmin',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'isPoolUnlockReady',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'lockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'lockPoolAsBuilder',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'requestUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'admin', internalType: 'address', type: 'address' },\n { name: 'revoked', internalType: 'bool', type: 'bool' },\n ],\n name: 'setBuilderAdminRevoked',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n name: 'unlockEta',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'admin',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderAdminRestored',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'admin',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderAdminRevoked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'builderCode',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'wallet',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n {\n name: 'locker',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'PoolLocked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'PoolUnlocked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'token',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TokensCollected',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'UnlockCancelled',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n { name: 'eta', internalType: 'uint256', type: 'uint256', indexed: false },\n ],\n name: 'UnlockRequested',\n },\n { type: 'error', inputs: [], name: 'InvalidBuilderCode' },\n { type: 'error', inputs: [], name: 'NoPendingUnlock' },\n { type: 'error', inputs: [], name: 'NotAuthorizedBuilder' },\n { type: 'error', inputs: [], name: 'NotFactoryAdmin' },\n { type: 'error', inputs: [], name: 'NotGuardianAdmin' },\n { type: 'error', inputs: [], name: 'NotTreasurer' },\n { type: 'error', inputs: [], name: 'UnlockAlreadyPending' },\n {\n type: 'error',\n inputs: [{ name: 'eta', internalType: 'uint256', type: 'uint256' }],\n name: 'UnlockNotReady',\n },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticPoolV2\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticPoolV2Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_sfpm',\n internalType: 'contract ISemiFungiblePositionManager',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SFPM',\n outputs: [\n {\n name: '',\n internalType: 'contract ISemiFungiblePositionManager',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'minValue0', internalType: 'uint256', type: 'uint256' },\n { name: 'minValue1', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'assertMinCollateralValues',\n outputs: [],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'collateralToken0',\n outputs: [\n {\n name: '',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'collateralToken1',\n outputs: [\n {\n name: '',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'finalPositionIdList',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'positionSizes', internalType: 'uint128[]', type: 'uint128[]' },\n {\n name: 'tickAndSpreadLimits',\n internalType: 'int24[3][]',\n type: 'int24[3][]',\n },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'dispatch',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionIdListFrom',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'account', internalType: 'address', type: 'address' },\n {\n name: 'positionIdListTo',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n {\n name: 'positionIdListToFinal',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n {\n name: 'usePremiaAsCollateral',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n name: 'dispatchFrom',\n outputs: [],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'account', internalType: 'address', type: 'address' }],\n name: 'getAssetsOf',\n outputs: [\n { name: 'assets0', internalType: 'uint256', type: 'uint256' },\n { name: 'assets1', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getChunkData',\n outputs: [\n {\n name: 'liquidities0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'liquidities1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n { name: 'settled0', internalType: 'LeftRightUnsigned', type: 'uint256' },\n { name: 'settled1', internalType: 'LeftRightUnsigned', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'includePendingPremium', internalType: 'bool', type: 'bool' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getFullPositionsData',\n outputs: [\n {\n name: 'shortPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'positionBalances',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n {\n name: 'collateralRequirements',\n internalType: 'LeftRightUnsigned[]',\n type: 'uint256[]',\n },\n {\n name: 'netPremiaPerPosition',\n internalType: 'LeftRightSigned[]',\n type: 'int256[]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getOracleTicks',\n outputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'spotTick', internalType: 'int24', type: 'int24' },\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n { name: 'latestTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'builderCode', internalType: 'uint256', type: 'uint256' }],\n name: 'getRiskParameters',\n outputs: [\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getTWAP',\n outputs: [{ name: 'twapTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'isSafeMode',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'lockSafeMode',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'user', internalType: 'address', type: 'address' }],\n name: 'numberOfLegs',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'onERC1155Received',\n outputs: [{ name: '', internalType: 'bytes4', type: 'bytes4' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'pokeOracle',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolId',\n outputs: [{ name: '', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolKey',\n outputs: [{ name: 'key', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolManager',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'riskEngine',\n outputs: [{ name: '', internalType: 'contract IRiskEngine', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'tickSpacing',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'unlockSafeMode',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n ],\n name: 'validateCollateralWithdrawable',\n outputs: [],\n stateMutability: 'view',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'liquidator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'liquidatee',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'bonusAmounts',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'AccountLiquidated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'exercisor',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'user', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'exerciseFee',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'ForcedExercised',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'premiaByLeg',\n internalType: 'LeftRightSigned[4]',\n type: 'int256[4]',\n indexed: false,\n },\n ],\n name: 'OptionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'balanceData',\n internalType: 'PositionBalance',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'OptionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'user', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'legIndex',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'settledAmounts',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'PremiumSettled',\n },\n {\n type: 'error',\n inputs: [\n { name: 'solvent', internalType: 'uint256', type: 'uint256' },\n { name: 'numberOfTicks', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'AccountInsolvent',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'DuplicateTokenId' },\n { type: 'error', inputs: [], name: 'EffectiveLiquidityAboveThreshold' },\n { type: 'error', inputs: [], name: 'InputListFail' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NetLiquidityZero' },\n { type: 'error', inputs: [], name: 'NoLegsExercisable' },\n { type: 'error', inputs: [], name: 'NotGuardian' },\n { type: 'error', inputs: [], name: 'NotMarginCalled' },\n { type: 'error', inputs: [], name: 'PositionNotOwned' },\n { type: 'error', inputs: [], name: 'PriceImpactTooLarge' },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n { type: 'error', inputs: [], name: 'StaleOracle' },\n { type: 'error', inputs: [], name: 'TokenIdHasZeroLegs' },\n { type: 'error', inputs: [], name: 'TooManyLegsOpen' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'WrongPoolId' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticQuery\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticQueryAbi = [\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'checkCollateral',\n outputs: [\n {\n name: 'collateralBalances0',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'requiredCollaterals0',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'collateralBalances1',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'requiredCollaterals1',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'checkCollateral',\n outputs: [\n {\n name: 'balancesAndRequired',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'checkCollateralListOutput',\n outputs: [\n { name: '', internalType: 'uint256[4][]', type: 'uint256[4][]' },\n { name: '', internalType: 'int256[]', type: 'int256[]' },\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getChunkData',\n outputs: [{ name: '', internalType: 'uint256[2][4][]', type: 'uint256[2][4][]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getLiquidationPrices',\n outputs: [\n { name: 'liquidationPriceDown', internalType: 'int24', type: 'int24' },\n { name: 'liquidationPriceUp', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n ],\n name: 'getItmAmounts',\n outputs: [\n { name: 'itm0', internalType: 'int256', type: 'int256' },\n { name: 'itm1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n {\n name: 'existingPositionIds',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n ],\n name: 'getMaxPositionSizeBounds',\n outputs: [\n { name: 'maxSizeAtMinUtil', internalType: 'uint128', type: 'uint128' },\n { name: 'maxSizeAtMaxUtil', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'includePendingPremium', internalType: 'bool', type: 'bool' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getNetLiquidationValue',\n outputs: [\n { name: 'value0', internalType: 'int256', type: 'int256' },\n { name: 'value1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getPortfolioValue',\n outputs: [\n { name: 'value0', internalType: 'int256', type: 'int256' },\n { name: 'value1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'atTicks', internalType: 'int24[]', type: 'int24[]' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getPortfolioValueAtTicks',\n outputs: [\n { name: 'value0', internalType: 'int256[]', type: 'int256[]' },\n { name: 'value1', internalType: 'int256[]', type: 'int256[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getRequiredBase',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'startTick', internalType: 'int24', type: 'int24' },\n { name: 'nTicks', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getTickNets',\n outputs: [\n { name: 'tickData', internalType: 'int256[]', type: 'int256[]' },\n { name: 'liquidityNets', internalType: 'int256[]', type: 'int256[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'isAccountSolvent',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n ],\n name: 'optimizeRiskPartners',\n outputs: [{ name: '', internalType: 'TokenId', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'width', internalType: 'int24', type: 'int24' },\n ],\n name: 'scanChunks',\n outputs: [\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n { name: '', internalType: 'uint128[2][]', type: 'uint128[2][]' },\n { name: '', internalType: 'uint128[2][]', type: 'uint128[2][]' },\n {\n name: '',\n internalType: 'LeftRightUnsigned[2][]',\n type: 'uint256[2][]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'self', internalType: 'TokenId', type: 'uint256' }],\n name: 'validateTokenId',\n outputs: [],\n stateMutability: 'pure',\n },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// RiskEngine\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const riskEngineAbi = [\n {\n type: 'constructor',\n inputs: [\n { name: '_crossBuffer0', internalType: 'uint256', type: 'uint256' },\n { name: '_crossBuffer1', internalType: 'uint256', type: 'uint256' },\n { name: '_guardian', internalType: 'address', type: 'address' },\n { name: '_builderFactory', internalType: 'address', type: 'address' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'ADJUSTMENT_SPEED',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BP_DECREASE_BUFFER',\n outputs: [{ name: '', internalType: 'uint32', type: 'uint32' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUILDER_FACTORY',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUILDER_SPLIT',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUYER_COLLATERAL_RATIO',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CROSS_BUFFER_0',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CROSS_BUFFER_1',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CURVE_STEEPNESS',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'DECIMALS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'EMA_PERIODS',\n outputs: [{ name: '', internalType: 'uint96', type: 'uint96' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'FORCE_EXERCISE_COST',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'GUARDIAN',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'INITIAL_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'IRM_MAX_ELAPSED_TIME',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAINT_MARGIN_RATE',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_BONUS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_CLAMP_DELTA',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_OPEN_LEGS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_SPREAD',\n outputs: [{ name: '', internalType: 'uint24', type: 'uint24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_TICKS_DELTA',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_TWAP_DELTA_DISPATCH',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MIN_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'NOTIONAL_FEE',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'PREMIUM_FEE',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'PROTOCOL_SPLIT',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SATURATED_POOL_UTIL',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SELLER_COLLATERAL_RATIO',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TARGET_POOL_UTIL',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TARGET_UTILIZATION',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'VEGOID',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'computeInternalMedian',\n outputs: [\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n {\n name: 'updatedOraclePack',\n internalType: 'OraclePack',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'int256', type: 'int256' },\n { name: 'crossBuffer', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'crossBufferRatio',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oracleTick', internalType: 'int24', type: 'int24' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n {\n name: 'positionBalance',\n internalType: 'PositionBalance',\n type: 'uint256',\n },\n ],\n name: 'exerciseCost',\n outputs: [{ name: 'exerciseFees', internalType: 'LeftRightSigned', type: 'int256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'builderCode', internalType: 'uint256', type: 'uint256' }],\n name: 'getFeeRecipient',\n outputs: [{ name: 'feeRecipient', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'tokenData0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'tokenData1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n { name: 'atSqrtPriceX96', internalType: 'uint160', type: 'uint160' },\n { name: 'netPaid', internalType: 'LeftRightSigned', type: 'int256' },\n {\n name: 'shortPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'loanAmounts',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n name: 'getLiquidationBonus',\n outputs: [\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'shortPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n name: 'getMargin',\n outputs: [\n {\n name: 'tokenData0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'tokenData1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'globalUtilizations',\n internalType: 'PositionBalance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: '_oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n name: 'getOracleTicks',\n outputs: [\n { name: 'spotTick', internalType: 'int24', type: 'int24' },\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n { name: 'latestTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getPerPositionCollateralRequirements',\n outputs: [\n {\n name: 'collateralRequirements',\n internalType: 'LeftRightUnsigned[]',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'payor', internalType: 'address', type: 'address' },\n { name: 'fees', internalType: 'LeftRightSigned', type: 'int256' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n name: 'getRefundAmounts',\n outputs: [{ name: '', internalType: 'LeftRightSigned', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getRiskParameters',\n outputs: [{ name: '', internalType: 'RiskParameters', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: '_oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'safeMode', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getSolvencyTicks',\n outputs: [\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n { name: '', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'premiasByLeg',\n internalType: 'LeftRightSigned[4][]',\n type: 'int256[4][]',\n },\n {\n name: 'collateralRemaining',\n internalType: 'LeftRightSigned',\n type: 'int256',\n },\n { name: 'atSqrtPriceX96', internalType: 'uint160', type: 'uint160' },\n ],\n name: 'haircutPremia',\n outputs: [\n { name: 'bonusDeltas', internalType: 'LeftRightSigned', type: 'int256' },\n {\n name: 'haircutTotal',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'haircutPerLeg',\n internalType: 'LeftRightSigned[4][]',\n type: 'int256[4][]',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'uint256', type: 'uint256' },\n {\n name: 'interestRateAccumulator',\n internalType: 'MarketState',\n type: 'uint256',\n },\n ],\n name: 'interestRate',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'user', internalType: 'address', type: 'address' },\n {\n name: 'shortPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n { name: 'buffer', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'isAccountSolvent',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n name: 'isSafeMode',\n outputs: [{ name: 'safeMode', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'lockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' }],\n name: 'twapEMA',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'unlockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'uint256', type: 'uint256' },\n {\n name: 'interestRateAccumulator',\n internalType: 'MarketState',\n type: 'uint256',\n },\n ],\n name: 'updateInterestRate',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'vegoid',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'pure',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'collateralToken',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'avgBorrowRate',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'rateAtTarget',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'BorrowRateUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [{ name: 'lockMode', internalType: 'bool', type: 'bool', indexed: false }],\n name: 'GuardianSafeModeUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'token',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TokensCollected',\n },\n { type: 'error', inputs: [], name: 'BelowMinimumRedemption' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'InvalidBuilderCode' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'LengthMismatch' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotGuardian' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// SemiFungiblePositionManagerV3\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const semiFungiblePositionManagerV3Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_factory',\n internalType: 'contract IUniswapV3Factory',\n type: 'address',\n },\n {\n name: '_minEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_supplyMultiplierTickFill',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owners', internalType: 'address[]', type: 'address[]' },\n { name: 'ids', internalType: 'uint256[]', type: 'uint256[]' },\n ],\n name: 'balanceOfBatch',\n outputs: [{ name: 'balances', internalType: 'uint256[]', type: 'uint256[]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'burnTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'expandEnforcedTickRange',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountFeesBase',\n outputs: [\n { name: 'feesBase0', internalType: 'int128', type: 'int128' },\n { name: 'feesBase1', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountLiquidity',\n outputs: [\n {\n name: 'accountLiquidities',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'isLong', internalType: 'uint256', type: 'uint256' },\n { name: 'vegoid', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getAccountPremium',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolKey', internalType: 'bytes', type: 'bytes' }],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getEnforcedTickLimits',\n outputs: [\n { name: '', internalType: 'int24', type: 'int24' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'id', internalType: 'bytes', type: 'bytes' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getPoolId',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getUniswapV3PoolFromId',\n outputs: [\n {\n name: 'uniswapV3Pool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token0', internalType: 'address', type: 'address' },\n { name: 'token1', internalType: 'address', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'initializeAMMPool',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'operator', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: 'approvedForAll', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'mintTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'amount0Owed', internalType: 'uint256', type: 'uint256' },\n { name: 'amount1Owed', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'uniswapV3MintCallback',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'amount0Delta', internalType: 'int256', type: 'int256' },\n { name: 'amount1Delta', internalType: 'int256', type: 'int256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'uniswapV3SwapCallback',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'uniswapPool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'EnforcedTicksUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'univ3pool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenType',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'tickLower',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'tickUpper',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'liquidityDelta',\n internalType: 'int128',\n type: 'int128',\n indexed: false,\n },\n ],\n name: 'LiquidityChunkUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'uniswapPool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'poolId',\n internalType: 'uint64',\n type: 'uint64',\n indexed: false,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'PoolInitialized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'caller',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'ids',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n {\n name: 'amounts',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n ],\n name: 'TransferBatch',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: false },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TransferSingle',\n },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'ChunkHasZeroLiquidity' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'InvalidUniswapCallback' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotAuthorized' },\n { type: 'error', inputs: [], name: 'NotEnoughLiquidityInChunk' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'PositionTooLarge' },\n {\n type: 'error',\n inputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n name: 'PriceBoundFail',\n },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'UnsafeRecipient' },\n { type: 'error', inputs: [], name: 'WrongUniswapPool' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// SemiFungiblePositionManagerV4\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const semiFungiblePositionManagerV4Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: 'poolManager',\n internalType: 'contract IPoolManager',\n type: 'address',\n },\n {\n name: '_minEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_nativeEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_supplyMultiplierTickFill',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owners', internalType: 'address[]', type: 'address[]' },\n { name: 'ids', internalType: 'uint256[]', type: 'uint256[]' },\n ],\n name: 'balanceOfBatch',\n outputs: [{ name: 'balances', internalType: 'uint256[]', type: 'uint256[]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'burnTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'expandEnforcedTickRange',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountLiquidity',\n outputs: [\n {\n name: 'accountLiquidities',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'isLong', internalType: 'uint256', type: 'uint256' },\n { name: 'vegoid', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getAccountPremium',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolKey', internalType: 'bytes', type: 'bytes' }],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getEnforcedTickLimits',\n outputs: [\n { name: '', internalType: 'int24', type: 'int24' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'id', internalType: 'bytes', type: 'bytes' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getPoolId',\n outputs: [{ name: '', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getUniswapV4PoolKeyFromId',\n outputs: [\n {\n name: '',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'initializeAMMPool',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'operator', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: 'approvedForAll', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'mintTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes', type: 'bytes' }],\n name: 'unlockCallback',\n outputs: [{ name: '', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'EnforcedTicksUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolId',\n internalType: 'PoolId',\n type: 'bytes32',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenType',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'tickLower',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'tickUpper',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'liquidityDelta',\n internalType: 'int128',\n type: 'int128',\n indexed: false,\n },\n ],\n name: 'LiquidityChunkUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'poolId',\n internalType: 'uint64',\n type: 'uint64',\n indexed: false,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'PoolInitialized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'caller',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'ids',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n {\n name: 'amounts',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n ],\n name: 'TransferBatch',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: false },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TransferSingle',\n },\n { type: 'error', inputs: [], name: 'ChunkHasZeroLiquidity' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotAuthorized' },\n { type: 'error', inputs: [], name: 'NotEnoughLiquidityInChunk' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'PositionTooLarge' },\n {\n type: 'error',\n inputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n name: 'PriceBoundFail',\n },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n { type: 'error', inputs: [], name: 'UnauthorizedUniswapCallback' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'UnsafeRecipient' },\n { type: 'error', inputs: [], name: 'WrongUniswapPool' },\n] as const\n","/**\n * Write utilities for the Panoptic v2 SDK.\n * @module v2/writes/utils\n */\n\nimport type { Abi, Address, Hash, Log, PublicClient, WalletClient } from 'viem'\nimport { decodeEventLog, encodeFunctionData } from 'viem'\n\nimport { collateralTrackerV2Abi, panopticPoolV2Abi } from '../../../generated'\nimport type { PanopticEvent, TxOverrides, TxReceipt, TxResult } from '../types'\n\n/**\n * Decode PositionBalance packed data.\n *\n * Layout (from LSB to MSB):\n * - positionSize: bits 0-127 (uint128)\n * - poolUtilization0: bits 128-143 (uint16)\n * - poolUtilization1: bits 144-159 (uint16)\n * - tickAtMint: bits 160-183 (int24)\n * - timestampAtMint: bits 184-215 (uint32)\n * - blockAtMint: bits 216-254 (uint39)\n * - swapAtMint: bit 255 (bool)\n */\nexport function decodePositionBalance(balanceData: bigint): {\n positionSize: bigint\n poolUtilization0: bigint\n poolUtilization1: bigint\n tickAtMint: bigint\n timestampAtMint: bigint\n blockAtMint: bigint\n swapAtMint: boolean\n} {\n const positionSize = balanceData & ((1n << 128n) - 1n)\n const poolUtilization0 = (balanceData >> 128n) & 0xffffn\n const poolUtilization1 = (balanceData >> 144n) & 0xffffn\n\n // tickAtMint is int24 at bits 160-183\n let tickAtMint = (balanceData >> 160n) & 0xffffffn\n // Sign extend if negative (int24)\n if (tickAtMint > 0x7fffffn) {\n tickAtMint = tickAtMint - 0x1000000n\n }\n\n // timestampAtMint is uint32 at bits 184-215\n const timestampAtMint = (balanceData >> 184n) & 0xffffffffn\n\n // blockAtMint is uint39 at bits 216-254\n const blockAtMint = (balanceData >> 216n) & ((1n << 39n) - 1n)\n\n // swapAtMint is bool at bit 255\n const swapAtMint = balanceData >> 255n === 1n\n\n return {\n positionSize,\n poolUtilization0,\n poolUtilization1,\n tickAtMint,\n timestampAtMint,\n blockAtMint,\n swapAtMint,\n }\n}\n\n/**\n * Decode LeftRightSigned packed value.\n */\nexport function decodeLeftRightSigned(value: bigint): { right: bigint; left: bigint } {\n // Right is bits 0-127 (token0), Left is bits 128-255 (token1)\n // Both are signed int128\n let right = value & ((1n << 128n) - 1n)\n let left = value >> 128n\n\n // Sign extend right if needed\n if (right >= 1n << 127n) {\n right = right - (1n << 128n)\n }\n // Sign extend left if needed\n if (left >= 1n << 127n) {\n left = left - (1n << 128n)\n }\n\n return { right, left }\n}\n\n/**\n * Decode LeftRightUnsigned packed value.\n */\nexport function decodeLeftRightUnsigned(value: bigint): { right: bigint; left: bigint } {\n // Right is bits 0-127 (token0), Left is bits 128-255 (token1)\n // Both are unsigned uint128\n const right = value & ((1n << 128n) - 1n)\n const left = value >> 128n\n\n return { right, left }\n}\n\n/**\n * Parse Panoptic events from transaction logs.\n *\n * @param logs - The transaction logs\n * @returns Parsed Panoptic events\n */\nexport function parsePanopticEvents(logs: Log[]): PanopticEvent[] {\n const events: PanopticEvent[] = []\n\n // Try to decode each log with known ABIs\n for (const log of logs) {\n const baseEvent = {\n blockNumber: log.blockNumber ?? 0n,\n blockHash: (log.blockHash ??\n '0x0000000000000000000000000000000000000000000000000000000000000000') as Hash,\n transactionHash: log.transactionHash ?? ('0x' as Hash),\n logIndex: BigInt(log.logIndex ?? 0),\n }\n\n try {\n // Try PanopticPool events\n const poolEvent = decodeEventLog({\n abi: panopticPoolV2Abi,\n data: log.data,\n topics: log.topics,\n })\n\n if (poolEvent.eventName === 'OptionMinted') {\n const args = poolEvent.args as {\n recipient: `0x${string}`\n tokenId: bigint\n balanceData: bigint\n }\n const balance = decodePositionBalance(args.balanceData)\n events.push({\n type: 'OptionMinted',\n ...baseEvent,\n recipient: args.recipient,\n tokenId: args.tokenId,\n positionSize: balance.positionSize,\n poolUtilization0: balance.poolUtilization0,\n poolUtilization1: balance.poolUtilization1,\n tickAtMint: balance.tickAtMint,\n timestampAtMint: balance.timestampAtMint,\n blockAtMint: balance.blockAtMint,\n swapAtMint: balance.swapAtMint,\n })\n } else if (poolEvent.eventName === 'OptionBurnt') {\n const args = poolEvent.args as {\n recipient: `0x${string}`\n tokenId: bigint\n positionSize: bigint\n premiaByLeg: readonly bigint[]\n }\n events.push({\n type: 'OptionBurnt',\n ...baseEvent,\n recipient: args.recipient,\n tokenId: args.tokenId,\n positionSize: args.positionSize,\n premiaByLeg: [\n args.premiaByLeg[0] ?? 0n,\n args.premiaByLeg[1] ?? 0n,\n args.premiaByLeg[2] ?? 0n,\n args.premiaByLeg[3] ?? 0n,\n ] as const,\n })\n } else if (poolEvent.eventName === 'AccountLiquidated') {\n const args = poolEvent.args as {\n liquidator: `0x${string}`\n liquidatee: `0x${string}`\n bonusAmounts: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.bonusAmounts)\n events.push({\n type: 'AccountLiquidated',\n ...baseEvent,\n liquidator: args.liquidator,\n liquidatee: args.liquidatee,\n bonusAmount0: right,\n bonusAmount1: left,\n })\n } else if (poolEvent.eventName === 'ForcedExercised') {\n const args = poolEvent.args as {\n exercisor: `0x${string}`\n user: `0x${string}`\n tokenId: bigint\n exerciseFee: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.exerciseFee)\n events.push({\n type: 'ForcedExercised',\n ...baseEvent,\n exercisor: args.exercisor,\n user: args.user,\n tokenId: args.tokenId,\n exerciseFee0: right,\n exerciseFee1: left,\n })\n } else if (poolEvent.eventName === 'PremiumSettled') {\n const args = poolEvent.args as {\n user: `0x${string}`\n tokenId: bigint\n legIndex: bigint\n settledAmounts: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.settledAmounts)\n events.push({\n type: 'PremiumSettled',\n ...baseEvent,\n user: args.user,\n tokenId: args.tokenId,\n legIndex: args.legIndex,\n settledAmount0: right,\n settledAmount1: left,\n })\n }\n } catch {\n // Not a PanopticPool event, try CollateralTracker\n try {\n const collateralEvent = decodeEventLog({\n abi: collateralTrackerV2Abi,\n data: log.data,\n topics: log.topics,\n })\n\n if (collateralEvent.eventName === 'Deposit') {\n const args = collateralEvent.args as {\n sender: `0x${string}`\n owner: `0x${string}`\n assets: bigint\n shares: bigint\n }\n events.push({\n type: 'Deposit',\n ...baseEvent,\n sender: args.sender,\n owner: args.owner,\n assets: args.assets,\n shares: args.shares,\n })\n } else if (collateralEvent.eventName === 'Withdraw') {\n const args = collateralEvent.args as {\n sender: `0x${string}`\n receiver: `0x${string}`\n owner: `0x${string}`\n assets: bigint\n shares: bigint\n }\n events.push({\n type: 'Withdraw',\n ...baseEvent,\n sender: args.sender,\n receiver: args.receiver,\n owner: args.owner,\n assets: args.assets,\n shares: args.shares,\n })\n }\n } catch {\n // Unknown event, skip\n }\n }\n }\n\n return events\n}\n\n/**\n * Create a TxResult from a transaction hash.\n *\n * @param client - The public client\n * @param hash - The transaction hash\n * @returns TxResult with wait function\n */\nexport function createTxResult(client: PublicClient, hash: Hash): TxResult {\n return {\n hash,\n wait: async (confirmations?: bigint): Promise<TxReceipt> => {\n const receipt = await client.waitForTransactionReceipt({\n hash,\n confirmations: confirmations !== undefined ? Number(confirmations) : undefined,\n })\n\n const events = parsePanopticEvents(receipt.logs)\n\n return {\n hash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n blockHash: receipt.blockHash,\n gasUsed: receipt.gasUsed,\n status: receipt.status === 'success' ? 'success' : 'reverted',\n events,\n }\n },\n }\n}\n\n/**\n * Execute a write operation and return TxResult.\n *\n * @param client - The public client\n * @param hashPromise - Promise that resolves to transaction hash\n * @returns TxResult\n */\nexport async function executeWrite(\n client: PublicClient,\n hashPromise: Promise<Hash>,\n): Promise<TxResult> {\n const hash = await hashPromise\n return createTxResult(client, hash)\n}\n\n/**\n * Execute a write operation and wait for receipt.\n *\n * @param client - The public client\n * @param hashPromise - Promise that resolves to transaction hash\n * @param confirmations - Number of confirmations to wait for\n * @returns TxReceipt\n */\nexport async function executeWriteAndWait(\n client: PublicClient,\n hashPromise: Promise<Hash>,\n confirmations?: bigint,\n): Promise<TxReceipt> {\n const result = await executeWrite(client, hashPromise)\n return result.wait(confirmations)\n}\n\n/**\n * Parameters for the submitWrite helper.\n */\nexport interface SubmitWriteParams {\n /** Public client */\n client: PublicClient\n /** Wallet client */\n walletClient: WalletClient\n /** Account address */\n account: Address\n /** Contract address */\n address: Address\n /** Contract ABI */\n abi: Abi\n /** Function name to call */\n functionName: string\n /** Function arguments */\n args: readonly unknown[]\n /** ETH value to send with the transaction (for native ETH deposits) */\n value?: bigint\n /** Optional gas and transaction overrides */\n txOverrides?: TxOverrides\n}\n\n/**\n * Submit a write operation, supporting both direct wallet submission\n * and custom broadcaster paths with gas overrides.\n *\n * Normal path (no broadcaster): calls walletClient.writeContract() with gas overrides.\n * Broadcaster path: prepareTransactionRequest → apply overrides → signTransaction → broadcast.\n *\n * @param params - Submit write parameters\n * @returns TxResult\n */\nexport async function submitWrite(params: SubmitWriteParams): Promise<TxResult> {\n const { client, walletClient, account, address, abi, functionName, args, value, txOverrides } =\n params\n\n const broadcaster = txOverrides?.broadcaster\n\n if (broadcaster) {\n // Encode contract calldata before request preparation so gas/tx params\n // are derived from the exact call being signed and broadcast.\n const data = encodeFunctionData({ abi, functionName, args })\n\n // Broadcaster path: prepare → sign → broadcast\n const broadcastAccount = walletClient.account ?? account\n const request = await walletClient.prepareTransactionRequest({\n account: broadcastAccount,\n to: address,\n chain: walletClient.chain,\n data,\n ...(value !== undefined && { value }),\n ...(txOverrides?.maxFeePerGas !== undefined && { maxFeePerGas: txOverrides.maxFeePerGas }),\n ...(txOverrides?.maxPriorityFeePerGas !== undefined && {\n maxPriorityFeePerGas: txOverrides.maxPriorityFeePerGas,\n }),\n ...(txOverrides?.gas !== undefined && { gas: txOverrides.gas }),\n ...(txOverrides?.nonce !== undefined && { nonce: Number(txOverrides.nonce) }),\n })\n\n const signedTx = await walletClient.signTransaction({\n ...request,\n account: broadcastAccount,\n } as unknown as Parameters<WalletClient['signTransaction']>[0])\n\n const hash = await broadcaster.broadcast(signedTx)\n return createTxResult(client, hash)\n }\n\n // Normal path: direct writeContract with gas overrides\n const gasOverrides: Record<string, unknown> = {}\n if (txOverrides?.maxFeePerGas !== undefined) {\n gasOverrides.maxFeePerGas = txOverrides.maxFeePerGas\n }\n if (txOverrides?.maxPriorityFeePerGas !== undefined) {\n gasOverrides.maxPriorityFeePerGas = txOverrides.maxPriorityFeePerGas\n }\n if (txOverrides?.nonce !== undefined) {\n gasOverrides.nonce = Number(txOverrides.nonce)\n }\n\n // Use the walletClient's local account (if available) for local signing.\n // Passing a string address triggers eth_sendTransaction (remote signing),\n // which fails with hosted RPC providers like Alchemy/Infura.\n const resolvedAccount = walletClient.account ?? account\n\n // If no explicit gas override, estimate with a 20% buffer.\n // Panoptic dispatch calls are gas-heavy and viem's default estimate can be tight.\n if (txOverrides?.gas !== undefined) {\n gasOverrides.gas = txOverrides.gas\n } else {\n const estimated = await client.estimateContractGas({\n address,\n abi,\n functionName,\n args,\n account: resolvedAccount,\n ...(value !== undefined && { value }),\n } as Parameters<typeof client.estimateContractGas>[0])\n gasOverrides.gas = (estimated * 120n) / 100n\n }\n\n const hash = await walletClient.writeContract({\n address,\n abi,\n functionName,\n args,\n account: resolvedAccount,\n chain: walletClient.chain,\n ...(value !== undefined && { value }),\n ...gasOverrides,\n })\n\n return createTxResult(client, hash)\n}\n\n/**\n * Parameters required for all write operations.\n */\nexport interface BaseWriteParams {\n /** Public client for reading state */\n client: PublicClient\n}\n","/**\n * Base error class for the Panoptic v2 SDK.\n * @module v2/errors/base\n */\n\n/**\n * Base error class for all Panoptic SDK errors.\n * All errors thrown by the SDK extend this class.\n *\n * @example\n * ```typescript\n * try {\n * await openPosition(config, params)\n * } catch (error) {\n * if (error instanceof PanopticError) {\n * console.log('Panoptic error:', error.name, error.message)\n * console.log('Original cause:', error.cause)\n * }\n * }\n * ```\n */\nexport class PanopticError extends Error {\n override readonly name: string = 'PanopticError'\n\n /** The Solidity error name (e.g. 'PriceBoundFail', 'InputListFail'). Set by the parser. */\n errorName?: string\n\n /**\n * Creates a new PanopticError.\n *\n * @param message - Human-readable error message\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n message: string,\n public readonly cause?: Error,\n ) {\n super(message)\n\n // Maintains proper stack trace for where error was thrown (V8 only)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // Ensure prototype chain is correctly set up\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Custom error ABI definitions for Panoptic v2 contracts.\n *\n * Contains all custom errors from Errors.sol with their signatures.\n * Used for decoding contract revert data.\n *\n * Selectors sourced from `forge selectors list` output.\n *\n * @module v2/errors/errorsAbi\n */\n\n/**\n * All custom errors from Panoptic Errors.sol\n *\n * Selector computation: keccak256(errorSignature)[:4]\n */\nexport const panopticErrorsAbi = [\n // AccountInsolvent(uint256 solvent, uint256 numberOfTicks) - 0xcdef092d\n {\n type: 'error',\n name: 'AccountInsolvent',\n inputs: [\n { name: 'solvent', type: 'uint256' },\n { name: 'numberOfTicks', type: 'uint256' },\n ],\n },\n\n // AlreadyInitialized() - 0x0dc149f0\n {\n type: 'error',\n name: 'AlreadyInitialized',\n inputs: [],\n },\n\n // BelowMinimumRedemption() - 0x13185bd7\n {\n type: 'error',\n name: 'BelowMinimumRedemption',\n inputs: [],\n },\n\n // CastingError() - 0xb6680045\n {\n type: 'error',\n name: 'CastingError',\n inputs: [],\n },\n\n // ChunkHasZeroLiquidity() - 0x126ae3af\n {\n type: 'error',\n name: 'ChunkHasZeroLiquidity',\n inputs: [],\n },\n\n // CreateFail() - 0xebfef188\n {\n type: 'error',\n name: 'CreateFail',\n inputs: [],\n },\n\n // DepositTooLarge() - 0xc56d46d3\n {\n type: 'error',\n name: 'DepositTooLarge',\n inputs: [],\n },\n\n // DuplicateTokenId() - 0x2bd1a05a\n {\n type: 'error',\n name: 'DuplicateTokenId',\n inputs: [],\n },\n\n // EffectiveLiquidityAboveThreshold() - 0x3a8795c2\n {\n type: 'error',\n name: 'EffectiveLiquidityAboveThreshold',\n inputs: [],\n },\n\n // ExceedsMaximumRedemption() - 0x20adf2ea\n {\n type: 'error',\n name: 'ExceedsMaximumRedemption',\n inputs: [],\n },\n\n // InputListFail() - 0x99e877ce\n {\n type: 'error',\n name: 'InputListFail',\n inputs: [],\n },\n\n // InsufficientCreditLiquidity() - 0x7a70c281\n {\n type: 'error',\n name: 'InsufficientCreditLiquidity',\n inputs: [],\n },\n\n // InvalidBuilderCode() - 0x15b3fb46\n {\n type: 'error',\n name: 'InvalidBuilderCode',\n inputs: [],\n },\n\n // InvalidTick() - 0xce8ef7fc\n {\n type: 'error',\n name: 'InvalidTick',\n inputs: [],\n },\n\n // InvalidTickBound() - 0x1577d966\n {\n type: 'error',\n name: 'InvalidTickBound',\n inputs: [],\n },\n\n // InvalidTokenIdParameter(uint256 parameterType) - 0x93db0263\n {\n type: 'error',\n name: 'InvalidTokenIdParameter',\n inputs: [{ name: 'parameterType', type: 'uint256' }],\n },\n\n // InvalidUniswapCallback() - 0x3a94c705\n {\n type: 'error',\n name: 'InvalidUniswapCallback',\n inputs: [],\n },\n\n // LengthMismatch() - 0xff633a38\n {\n type: 'error',\n name: 'LengthMismatch',\n inputs: [],\n },\n\n // LiquidityTooHigh() - 0xa500e7ea\n {\n type: 'error',\n name: 'LiquidityTooHigh',\n inputs: [],\n },\n\n // NetLiquidityZero() - 0x73582ea0\n {\n type: 'error',\n name: 'NetLiquidityZero',\n inputs: [],\n },\n\n // NoLegsExercisable() - 0x7721f7da\n {\n type: 'error',\n name: 'NoLegsExercisable',\n inputs: [],\n },\n\n // NotALongLeg() - 0xb7d44f76\n {\n type: 'error',\n name: 'NotALongLeg',\n inputs: [],\n },\n\n // NotBuilder() - 0x0404714e\n {\n type: 'error',\n name: 'NotBuilder',\n inputs: [],\n },\n\n // NotEnoughLiquidityInChunk() - 0xc56d518e\n {\n type: 'error',\n name: 'NotEnoughLiquidityInChunk',\n inputs: [],\n },\n\n // NotEnoughTokens(address tokenAddress, uint256 assetsRequested, uint256 assetBalance) - 0x71c3730b\n {\n type: 'error',\n name: 'NotEnoughTokens',\n inputs: [\n { name: 'tokenAddress', type: 'address' },\n { name: 'assetsRequested', type: 'uint256' },\n { name: 'assetBalance', type: 'uint256' },\n ],\n },\n\n // NotGuardian() - 0xef6d0f02\n {\n type: 'error',\n name: 'NotGuardian',\n inputs: [],\n },\n\n // NotMarginCalled() - 0x2a23f1ad\n {\n type: 'error',\n name: 'NotMarginCalled',\n inputs: [],\n },\n\n // NotPanopticPool() - 0x2dd1912a\n {\n type: 'error',\n name: 'NotPanopticPool',\n inputs: [],\n },\n\n // PoolNotInitialized() - 0x486aa307\n {\n type: 'error',\n name: 'PoolNotInitialized',\n inputs: [],\n },\n\n // PositionCountNotZero() - 0x2501f81e\n {\n type: 'error',\n name: 'PositionCountNotZero',\n inputs: [],\n },\n\n // PositionNotOwned() - 0x00bd51c8\n {\n type: 'error',\n name: 'PositionNotOwned',\n inputs: [],\n },\n\n // PositionTooLarge() - 0x543a6e10\n {\n type: 'error',\n name: 'PositionTooLarge',\n inputs: [],\n },\n\n // PriceBoundFail(int24 currentTick) - 0x618ea40c\n {\n type: 'error',\n name: 'PriceBoundFail',\n inputs: [{ name: 'currentTick', type: 'int24' }],\n },\n\n // PriceImpactTooLarge() - 0xcbe5b9a6\n {\n type: 'error',\n name: 'PriceImpactTooLarge',\n inputs: [],\n },\n\n // Reentrancy() - 0xab143c06\n {\n type: 'error',\n name: 'Reentrancy',\n inputs: [],\n },\n\n // StaleOracle() - 0x88cce429\n {\n type: 'error',\n name: 'StaleOracle',\n inputs: [],\n },\n\n // TokenIdHasZeroLegs() - 0x9cd92fb2\n {\n type: 'error',\n name: 'TokenIdHasZeroLegs',\n inputs: [],\n },\n\n // TooManyLegsOpen() - 0x0ed7e777\n {\n type: 'error',\n name: 'TooManyLegsOpen',\n inputs: [],\n },\n\n // TransferFailed(address token, address from, uint256 amount, uint256 balance) - 0x81f20f86\n {\n type: 'error',\n name: 'TransferFailed',\n inputs: [\n { name: 'token', type: 'address' },\n { name: 'from', type: 'address' },\n { name: 'amount', type: 'uint256' },\n { name: 'balance', type: 'uint256' },\n ],\n },\n\n // UnauthorizedUniswapCallback() - 0x3e30718a\n {\n type: 'error',\n name: 'UnauthorizedUniswapCallback',\n inputs: [],\n },\n\n // UnderOverFlow() - 0xd2190174\n {\n type: 'error',\n name: 'UnderOverFlow',\n inputs: [],\n },\n\n // WrongPoolId() - 0xcfa4bfa2\n {\n type: 'error',\n name: 'WrongPoolId',\n inputs: [],\n },\n\n // WrongUniswapPool() - 0x768778de\n {\n type: 'error',\n name: 'WrongUniswapPool',\n inputs: [],\n },\n\n // ZeroAddress() - 0xd92e233d\n {\n type: 'error',\n name: 'ZeroAddress',\n inputs: [],\n },\n\n // ZeroCollateralRequirement() - 0x5b8edb4a\n {\n type: 'error',\n name: 'ZeroCollateralRequirement',\n inputs: [],\n },\n] as const\n","/**\n * Error parsing utilities for the Panoptic v2 SDK.\n *\n * Converts raw contract errors into typed SDK error classes.\n *\n * @module v2/errors/parser\n */\n\nimport { type Abi, BaseError, decodeErrorResult, toFunctionSelector } from 'viem'\n\nimport { collateralTrackerV2Abi, panopticPoolV2Abi, riskEngineAbi } from '../../../generated'\nimport { PanopticError } from './base'\nimport {\n // Solvency & Margin\n AccountInsolventError,\n AlreadyInitializedError,\n BelowMinimumRedemptionError,\n CastingError,\n // Liquidity\n ChunkHasZeroLiquidityError,\n CreateFailError,\n DepositTooLargeError,\n DuplicateTokenIdError,\n EffectiveLiquidityAboveThresholdError,\n ExceedsMaximumRedemptionError,\n InputListFailError,\n InsufficientCreditLiquidityError,\n InvalidBuilderCodeError,\n InvalidTickBoundError,\n // Tick & Price\n InvalidTickError,\n // Position & TokenId\n InvalidTokenIdParameterError,\n InvalidUniswapCallbackError,\n LengthMismatchError,\n LiquidityTooHighError,\n NetLiquidityZeroError,\n // Exercise\n NoLegsExercisableError,\n NotALongLegError,\n NotBuilderError,\n NotEnoughLiquidityInChunkError,\n // Token & Collateral\n NotEnoughTokensError,\n NotGuardianError,\n NotMarginCalledError,\n // Authorization\n NotPanopticPoolError,\n // Pool & Initialization\n PoolNotInitializedError,\n PositionCountNotZeroError,\n PositionNotOwnedError,\n PositionTooLargeError,\n PriceBoundFailError,\n PriceImpactTooLargeError,\n // Reentrancy\n ReentrancyError,\n // Oracle & Safe Mode\n StaleOracleError,\n TokenIdHasZeroLegsError,\n TooManyLegsOpenError,\n // Transfer & Casting\n TransferFailedError,\n UnauthorizedUniswapCallbackError,\n UnderOverFlowError,\n WrongPoolIdError,\n WrongUniswapPoolError,\n // Other\n ZeroAddressError,\n ZeroCollateralRequirementError,\n} from './contract'\nimport { panopticErrorsAbi } from './errorsAbi'\n\n/**\n * Result of parsing a Panoptic error.\n */\nexport interface ParsedError {\n /** The parsed error instance */\n error: PanopticError\n /** The original error name from the contract */\n errorName: string\n /** The decoded error arguments */\n args: readonly unknown[]\n}\n\n/**\n * Combined ABI for error decoding.\n * Includes the dedicated errors ABI for complete coverage.\n */\nconst combinedAbi = [\n ...panopticPoolV2Abi,\n ...collateralTrackerV2Abi,\n ...riskEngineAbi,\n ...panopticErrorsAbi,\n] as Abi\n\n/**\n * Map of error names to error constructors.\n */\nconst errorConstructors: Record<\n string,\n (args: readonly unknown[], cause?: Error) => PanopticError\n> = {\n // Solvency & Margin\n AccountInsolvent: (args, cause) =>\n new AccountInsolventError(args[0] as bigint, args[1] as bigint, cause),\n NotMarginCalled: (_args, cause) => new NotMarginCalledError(cause),\n\n // Factory\n CreateFail: (_args, cause) => new CreateFailError(cause),\n\n // Token & Collateral\n NotEnoughTokens: (args, cause) =>\n new NotEnoughTokensError(args[0] as `0x${string}`, args[1] as bigint, args[2] as bigint, cause),\n NotEnoughLiquidityInChunk: (_args, cause) => new NotEnoughLiquidityInChunkError(cause),\n InsufficientCreditLiquidity: (_args, cause) => new InsufficientCreditLiquidityError(cause),\n DepositTooLarge: (_args, cause) => new DepositTooLargeError(cause),\n BelowMinimumRedemption: (_args, cause) => new BelowMinimumRedemptionError(cause),\n ExceedsMaximumRedemption: (_args, cause) => new ExceedsMaximumRedemptionError(cause),\n ZeroCollateralRequirement: (_args, cause) => new ZeroCollateralRequirementError(cause),\n\n // Position & TokenId\n InvalidTokenIdParameter: (args, cause) =>\n new InvalidTokenIdParameterError(args[0] as bigint, cause),\n PositionNotOwned: (_args, cause) => new PositionNotOwnedError(cause),\n PositionTooLarge: (_args, cause) => new PositionTooLargeError(cause),\n PositionCountNotZero: (_args, cause) => new PositionCountNotZeroError(cause),\n DuplicateTokenId: (_args, cause) => new DuplicateTokenIdError(cause),\n TokenIdHasZeroLegs: (_args, cause) => new TokenIdHasZeroLegsError(cause),\n TooManyLegsOpen: (_args, cause) => new TooManyLegsOpenError(cause),\n InputListFail: (_args, cause) => new InputListFailError(cause),\n\n // Tick & Price\n InvalidTick: (_args, cause) => new InvalidTickError(cause),\n InvalidTickBound: (_args, cause) => new InvalidTickBoundError(cause),\n PriceBoundFail: (args, cause) => new PriceBoundFailError(args[0] as bigint, cause),\n PriceImpactTooLarge: (_args, cause) => new PriceImpactTooLargeError(cause),\n\n // Liquidity\n ChunkHasZeroLiquidity: (_args, cause) => new ChunkHasZeroLiquidityError(cause),\n LiquidityTooHigh: (_args, cause) => new LiquidityTooHighError(cause),\n NetLiquidityZero: (_args, cause) => new NetLiquidityZeroError(cause),\n EffectiveLiquidityAboveThreshold: (_args, cause) =>\n new EffectiveLiquidityAboveThresholdError(cause),\n\n // Oracle & Safe Mode\n StaleOracle: (_args, cause) => new StaleOracleError(cause),\n\n // Exercise\n NoLegsExercisable: (_args, cause) => new NoLegsExercisableError(cause),\n NotALongLeg: (_args, cause) => new NotALongLegError(cause),\n\n // Pool & Initialization\n PoolNotInitialized: (_args, cause) => new PoolNotInitializedError(cause),\n AlreadyInitialized: (_args, cause) => new AlreadyInitializedError(cause),\n WrongPoolId: (_args, cause) => new WrongPoolIdError(cause),\n WrongUniswapPool: (_args, cause) => new WrongUniswapPoolError(cause),\n\n // Authorization\n NotPanopticPool: (_args, cause) => new NotPanopticPoolError(cause),\n NotGuardian: (_args, cause) => new NotGuardianError(cause),\n NotBuilder: (_args, cause) => new NotBuilderError(cause),\n InvalidBuilderCode: (_args, cause) => new InvalidBuilderCodeError(cause),\n InvalidUniswapCallback: (_args, cause) => new InvalidUniswapCallbackError(cause),\n UnauthorizedUniswapCallback: (_args, cause) => new UnauthorizedUniswapCallbackError(cause),\n\n // Transfer & Casting\n TransferFailed: (args, cause) =>\n new TransferFailedError(\n args[0] as `0x${string}`,\n args[1] as `0x${string}`,\n args[2] as bigint,\n args[3] as bigint,\n cause,\n ),\n CastingError: (_args, cause) => new CastingError(cause),\n UnderOverFlow: (_args, cause) => new UnderOverFlowError(cause),\n\n // Reentrancy\n Reentrancy: (_args, cause) => new ReentrancyError(cause),\n\n // Other\n ZeroAddress: (_args, cause) => new ZeroAddressError(cause),\n LengthMismatch: (_args, cause) => new LengthMismatchError(cause),\n}\n\n/**\n * Parse a raw contract error into a typed SDK error.\n *\n * This function attempts to decode the error data from a failed contract call\n * and return a typed error instance with extracted parameters.\n *\n * @param error - The raw error from a failed contract call\n * @returns Parsed error with typed error instance, or null if parsing fails\n *\n * @example\n * ```typescript\n * try {\n * await contract.openPosition(...)\n * } catch (rawError) {\n * const parsed = parsePanopticError(rawError)\n * if (parsed) {\n * console.log('Error:', parsed.errorName)\n * if (parsed.error instanceof AccountInsolventError) {\n * console.log('Solvent value:', parsed.error.solvent)\n * }\n * }\n * }\n * ```\n */\nexport function parsePanopticError(error: unknown): ParsedError | null {\n // Strategy 1: Check if viem already decoded the error (ContractFunctionRevertedError.data)\n const viemDecoded = extractViemDecodedError(error)\n if (viemDecoded) {\n return buildParsedError(viemDecoded.errorName, viemDecoded.args, error)\n }\n\n // Strategy 2: Extract raw hex data and decode ourselves\n const errorData = extractErrorData(error)\n if (!errorData) return null\n\n try {\n const decoded = decodeErrorResult({\n abi: combinedAbi,\n data: errorData,\n })\n\n return buildParsedError(decoded.errorName, decoded.args ?? [], error)\n } catch {\n // decodeErrorResult failed — possibly we only have the 4-byte selector\n // (e.g. from a multicall error message). Try matching the selector manually.\n if (errorData.length >= 10) {\n const selector = errorData.slice(0, 10) as `0x${string}`\n const match = matchSelectorToErrorName(selector)\n if (match) {\n return buildParsedError(match, [], error)\n }\n }\n return null\n }\n}\n\n/**\n * Walk the cause chain looking for a viem ContractFunctionRevertedError\n * that already has decoded `.data` (an object with `errorName` and `args`).\n * This happens when the ABI passed to simulateContract includes the error definitions.\n */\nfunction extractViemDecodedError(\n error: unknown,\n): { errorName: string; args: readonly unknown[] } | null {\n if (!error || typeof error !== 'object') return null\n\n // Use BaseError.walk if available\n if (error instanceof BaseError) {\n let found: { errorName: string; args: readonly unknown[] } | null = null\n error.walk((e) => {\n if (found) return false\n const node = e as Record<string, unknown>\n if (\n node.data &&\n typeof node.data === 'object' &&\n 'errorName' in (node.data as object) &&\n typeof (node.data as Record<string, unknown>).errorName === 'string'\n ) {\n const data = node.data as { errorName: string; args?: readonly unknown[] }\n found = { errorName: data.errorName, args: data.args ?? [] }\n return true\n }\n return false\n })\n return found\n }\n\n // Manual walk for non-viem errors\n let current: Record<string, unknown> | null = error as Record<string, unknown>\n for (let i = 0; i < 10 && current; i++) {\n if (\n current.data &&\n typeof current.data === 'object' &&\n 'errorName' in (current.data as object) &&\n typeof (current.data as Record<string, unknown>).errorName === 'string'\n ) {\n const data = current.data as { errorName: string; args?: readonly unknown[] }\n return { errorName: data.errorName, args: data.args ?? [] }\n }\n current =\n current.cause && typeof current.cause === 'object'\n ? (current.cause as Record<string, unknown>)\n : null\n }\n\n return null\n}\n\n/**\n * Build a ParsedError from a decoded error name and args.\n */\nfunction buildParsedError(\n errorName: string,\n args: readonly unknown[],\n originalError: unknown,\n): ParsedError {\n const constructor = errorConstructors[errorName]\n const cause = originalError instanceof Error ? originalError : undefined\n\n if (!constructor) {\n const unknownError = new PanopticError(`Unknown contract error: ${errorName}`)\n unknownError.errorName = errorName\n return { error: unknownError, errorName, args }\n }\n\n const typedError = constructor(args, cause)\n typedError.errorName = errorName\n return { error: typedError, errorName, args }\n}\n\n/**\n * Match a 4-byte selector against the panoptic errors ABI.\n * Used as fallback when we only have the selector (no encoded args).\n */\nfunction matchSelectorToErrorName(selector: `0x${string}`): string | null {\n for (const item of panopticErrorsAbi) {\n if (item.type !== 'error') continue\n const computed = toFunctionSelector(\n `${item.name}(${item.inputs.map((i: { type: string }) => i.type).join(',')})`,\n )\n if (computed === selector) {\n return item.name\n }\n }\n return null\n}\n\n/**\n * Extract error data from various error formats.\n *\n * Strategy:\n * 1. Use viem's BaseError.walk() to traverse the full cause chain and find\n * hex data on any node (handles arbitrary nesting depth for multicall etc.)\n * 2. Fall back to manual cause-chain walk for non-viem errors\n * 3. Last resort: extract selector from error message (loses args)\n */\nfunction extractErrorData(error: unknown): `0x${string}` | null {\n if (!error) return null\n\n // Direct hex data\n if (typeof error === 'string' && error.startsWith('0x')) {\n return error as `0x${string}`\n }\n\n if (typeof error !== 'object') return null\n\n // Strategy 1: Use viem's BaseError.walk() — traverses the full cause chain\n if (error instanceof BaseError) {\n let foundData: `0x${string}` | null = null\n\n error.walk((e) => {\n if (foundData) return false\n const node = e as Record<string, unknown>\n\n // Check .data as hex string (full revert bytes on RPC errors)\n if (node.data && typeof node.data === 'string' && node.data.startsWith('0x')) {\n foundData = node.data as `0x${string}`\n return true\n }\n\n // Check .data.data (some RPC providers nest: { data: { data: '0x...' } })\n if (node.data && typeof node.data === 'object') {\n const nested = node.data as Record<string, unknown>\n if (nested.data && typeof nested.data === 'string' && nested.data.startsWith('0x')) {\n foundData = nested.data as `0x${string}`\n return true\n }\n }\n\n return false\n })\n\n if (foundData) return foundData\n\n // Also check .signature on walked nodes (viem stores raw selector here\n // when it can't decode against the provided ABI)\n error.walk((e) => {\n if (foundData) return false\n const node = e as Record<string, unknown>\n if (node.signature && typeof node.signature === 'string' && node.signature.startsWith('0x')) {\n foundData = node.signature as `0x${string}`\n return true\n }\n return false\n })\n\n if (foundData) return foundData\n }\n\n // Strategy 2: Manual cause-chain walk for non-viem errors\n let current: Record<string, unknown> | null = error as Record<string, unknown>\n const maxDepth = 10\n for (let i = 0; i < maxDepth && current; i++) {\n if (current.data && typeof current.data === 'string' && current.data.startsWith('0x')) {\n return current.data as `0x${string}`\n }\n\n if (current.data && typeof current.data === 'object') {\n const nested = current.data as Record<string, unknown>\n if (nested.data && typeof nested.data === 'string' && nested.data.startsWith('0x')) {\n return nested.data as `0x${string}`\n }\n }\n\n if (current.error && typeof current.error === 'object') {\n const rpcError = current.error as Record<string, unknown>\n if (rpcError.data && typeof rpcError.data === 'string' && rpcError.data.startsWith('0x')) {\n return rpcError.data as `0x${string}`\n }\n }\n\n current =\n current.cause && typeof current.cause === 'object'\n ? (current.cause as Record<string, unknown>)\n : null\n }\n\n // Strategy 3: Extract from error message (last resort — may only have 4-byte selector)\n const obj = error as Record<string, unknown>\n if (obj.message && typeof obj.message === 'string') {\n const signatureMatch = obj.message.match(/signature:\\s*(0x[a-fA-F0-9]{8,})/i)\n if (signatureMatch) {\n return signatureMatch[1] as `0x${string}`\n }\n }\n\n return null\n}\n\n/**\n * Check if an error is a specific Panoptic error type.\n *\n * @param error - The error to check\n * @param errorClass - The error class to check against\n * @returns True if the error is an instance of the specified class\n *\n * @example\n * ```typescript\n * const parsed = parsePanopticError(error)\n * if (parsed && isPanopticErrorType(parsed.error, AccountInsolventError)) {\n * console.log('Account is insolvent!')\n * }\n * ```\n */\nexport function isPanopticErrorType<T extends PanopticError>(\n error: PanopticError,\n errorClass: new (...args: unknown[]) => T,\n): error is T {\n return error instanceof errorClass\n}\n","/**\n * Constants for the Panoptic v2 SDK.\n * @module v2/utils/constants\n */\n\n/**\n * WAD constant (10^18) used for fixed-point arithmetic.\n * Commonly used for spread calculations and other WAD-scaled values.\n */\nexport const WAD = 10n ** 18n\n\n/**\n * Zero collateral object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_COLLATERAL = {\n token0: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n token1: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n} as const\n\n/**\n * Zero valuation object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_VALUATION = {\n netLiquidationValue0: 0n,\n netLiquidationValue1: 0n,\n maintenanceMargin0: 0n,\n maintenanceMargin1: 0n,\n marginExcess0: 0n,\n marginExcess1: 0n,\n} as const\n\n/**\n * Storage schema version for the SDK.\n * Increment when storage format changes (triggers migration or clear).\n */\nexport const SCHEMA_VERSION = 1\n\n/**\n * Storage key prefix for all SDK data.\n */\nexport const STORAGE_PREFIX = 'panoptic-v2-sdk'\n\n/**\n * Maximum number of chunks that can be tracked per pool.\n * Exceeding this limit throws ChunkLimitError.\n */\nexport const MAX_TRACKED_CHUNKS = 1000\n\n/**\n * Default reorg depth for chain reorganization handling.\n * On reorg detection, rollback this many blocks and re-sync.\n */\nexport const REORG_DEPTH = 128n\n\n/**\n * Oracle epoch duration in seconds (64 seconds per epoch).\n */\nexport const ORACLE_EPOCH_SECONDS = 64n\n\n/**\n * Minimum tick value for Uniswap v3/v4 pools.\n */\nexport const MIN_TICK = -887272n\n\n/**\n * Maximum tick value for Uniswap v3/v4 pools.\n */\nexport const MAX_TICK = 887272n\n\n/**\n * PanopticQuery sentinel indicating that no lower liquidation boundary exists.\n * This is int24.min, not Uniswap's minimum usable tick.\n */\nexport const NO_LOWER_LIQUIDATION_TICK = -(1n << 23n)\n\n/**\n * PanopticQuery sentinel indicating that no upper liquidation boundary exists.\n * This is int24.max, not Uniswap's maximum usable tick.\n */\nexport const NO_UPPER_LIQUIDATION_TICK = (1n << 23n) - 1n\n\n/**\n * Basis points denominator (100% = 10000 bps).\n */\nexport const BPS_DENOMINATOR = 10000n\n\n/**\n * Utilization denominator (100% = 10000).\n */\nexport const UTILIZATION_DENOMINATOR = 10000n\n","/**\n * Snapshot recovery from dispatch calldata.\n * @module v2/sync/snapshotRecovery\n */\n\nimport type { AbiFunction, Address, Hash, Hex, PublicClient } from 'viem'\nimport { decodeFunctionData, getAddress, parseAbi, toFunctionSelector } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\n\nconst LOG_SCAN_WINDOW = 10_000n\nconst rolesExecutionAbi = parseAbi([\n 'function execTransactionWithRole(address to, uint256 value, bytes data, uint8 operation, bytes32 roleKey, bool shouldRevert)',\n])\n\ntype SnapshotEventLog = Awaited<ReturnType<PublicClient['getLogs']>>[number]\ntype SnapshotCandidateEvent = SnapshotEventLog & {\n transactionHash: Hash\n blockNumber: bigint\n logIndex: number\n}\n\n/**\n * Parameters for recovering position snapshot from dispatch calldata.\n */\nexport interface RecoverSnapshotParams {\n /** viem public client */\n client: PublicClient\n /** Pool address */\n poolAddress: Address\n /** Account to recover positions for */\n account: Address\n /** Starting block for transaction search (defaults to 0) */\n fromBlock?: bigint\n /** Ending block for transaction search (defaults to latest) */\n toBlock?: bigint\n}\n\n/**\n * Snapshot recovery result.\n */\nexport interface SnapshotRecoveryResult {\n /** Whether recovery was successful */\n success: boolean\n /** Position IDs from the final position list */\n positionIds: bigint[]\n /** Block number of the recovery transaction */\n blockNumber: bigint\n /** Block hash of the recovery transaction */\n blockHash: Hash\n /** Transaction hash used for recovery */\n transactionHash: Hash\n}\n\n/**\n * Recover position snapshot from the last dispatch transaction.\n * This is the primary recovery method - it finds the most recent dispatch()\n * call and extracts the finalPositionIdList from the calldata.\n *\n * @param params - Recovery parameters\n * @returns Snapshot recovery result\n */\nexport async function recoverSnapshot(\n params: RecoverSnapshotParams,\n): Promise<SnapshotRecoveryResult | null> {\n const { client, poolAddress, account, toBlock } = params\n\n // Get the latest block if not specified\n const latestBlock = toBlock ?? (await client.getBlockNumber())\n\n // Search for transactions from the account to the pool\n // We need to find dispatch() or dispatchFrom() calls\n // Note: This requires the account to have sent transactions directly,\n // or we need to look at internal transactions\n\n // Strategy: Look for OptionMinted or OptionBurnt events to find transactions,\n // then decode the transaction input to get the full position list\n\n const searchFromBlock = params.fromBlock ?? 0n\n if (latestBlock < searchFromBlock) return null\n\n // Fast path: a single getLogs per event type over the entire\n // [searchFromBlock, latest] range. The queries are filtered by `address` and\n // an indexed account topic, so providers like Alchemy impose no block-range\n // cap on them (only a result-count cap) — one call per event type is enough\n // and the returned set is already complete, so there are no older windows to\n // scan. This avoids walking the whole chain in 10k-block chunks (4 getLogs\n // per chunk), which for accounts with no history is thousands of empty calls.\n try {\n const events = await getSnapshotEventsForWindow({\n client,\n poolAddress,\n account,\n fromBlock: searchFromBlock,\n toBlock: latestBlock,\n })\n return await recoverSnapshotFromEvents({ client, account, events })\n } catch (error) {\n // Only fall back to windowed scanning when the provider rejected the wide\n // range. Any other error (e.g. transport failure) should propagate.\n if (!isRangeLimitError(error)) throw error\n }\n\n // Fallback for providers that cap getLogs block range: scan newest-to-oldest\n // in 10k-block windows and stop at the first window that yields a snapshot.\n let windowToBlock = latestBlock\n while (true) {\n const windowFromBlock =\n windowToBlock - searchFromBlock + 1n > LOG_SCAN_WINDOW\n ? windowToBlock - LOG_SCAN_WINDOW + 1n\n : searchFromBlock\n\n const events = await getSnapshotEventsForWindow({\n client,\n poolAddress,\n account,\n fromBlock: windowFromBlock,\n toBlock: windowToBlock,\n })\n const snapshot = await recoverSnapshotFromEvents({ client, account, events })\n if (snapshot) return snapshot\n\n if (windowFromBlock === searchFromBlock) break\n windowToBlock = windowFromBlock - 1n\n }\n\n // No snapshot found\n return null\n}\n\n/**\n * Detect provider errors that indicate the requested getLogs block range was\n * too wide (so the caller should retry with smaller windows). Covers the common\n * phrasings used by Alchemy, Infura, and other JSON-RPC providers.\n */\nfunction isRangeLimitError(error: unknown): boolean {\n const parts: string[] = []\n let current: unknown = error\n let depth = 0\n while (current && typeof current === 'object' && depth < 5) {\n const obj = current as Record<string, unknown>\n if (typeof obj.message === 'string') parts.push(obj.message)\n if (typeof obj.details === 'string') parts.push(obj.details)\n current = obj.cause\n depth += 1\n }\n if (typeof error === 'string') parts.push(error)\n\n const message = parts.join(' ').toLowerCase()\n if (!message) return false\n\n return (\n message.includes('block range') ||\n message.includes('range is too large') ||\n message.includes('range too large') ||\n message.includes('query returned more than') ||\n message.includes('too many results') ||\n message.includes('log response size exceeded') ||\n message.includes('exceeds the limit') ||\n (message.includes('range') && message.includes('limit'))\n )\n}\n\nasync function getSnapshotEventsForWindow(params: {\n client: PublicClient\n poolAddress: Address\n account: Address\n fromBlock: bigint\n toBlock: bigint\n}): Promise<SnapshotEventLog[]> {\n const { client, poolAddress, account, fromBlock, toBlock } = params\n\n // OptionMinted/OptionBurnt cover the account's own dispatches.\n // ForcedExercised/AccountLiquidated cover third-party dispatchFrom calls\n // where the tx sender is not the account but calldata contains the final list.\n const [mintEvents, burnEvents, forceExerciseEvents, liquidationEvents] = await Promise.all([\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'OptionMinted',\n inputs: [\n { type: 'address', name: 'recipient', indexed: true },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'uint256', name: 'balanceData', indexed: false },\n ],\n },\n args: {\n recipient: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'OptionBurnt',\n inputs: [\n { type: 'address', name: 'recipient', indexed: true },\n { type: 'uint128', name: 'positionSize', indexed: false },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'int256[4]', name: 'premiaByLeg', indexed: false },\n ],\n },\n args: {\n recipient: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'ForcedExercised',\n inputs: [\n { type: 'address', name: 'exercisor', indexed: true },\n { type: 'address', name: 'user', indexed: true },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'int256', name: 'exerciseFee', indexed: false },\n ],\n },\n args: {\n user: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'AccountLiquidated',\n inputs: [\n { type: 'address', name: 'liquidator', indexed: true },\n { type: 'address', name: 'liquidatee', indexed: true },\n { type: 'int256', name: 'bonusAmounts', indexed: false },\n ],\n },\n args: {\n liquidatee: account,\n },\n fromBlock,\n toBlock,\n }),\n ])\n\n return [...mintEvents, ...burnEvents, ...forceExerciseEvents, ...liquidationEvents]\n}\n\nasync function recoverSnapshotFromEvents(params: {\n client: PublicClient\n account: Address\n events: SnapshotEventLog[]\n}): Promise<SnapshotRecoveryResult | null> {\n const { client, account, events } = params\n\n // Combine and sort by block number (descending) to get most recent first\n const allEvents = events.filter(isSnapshotCandidateEvent).sort((a, b) => {\n const blockDiff = Number(b.blockNumber - a.blockNumber)\n if (blockDiff !== 0) return blockDiff\n return Number(b.logIndex - a.logIndex)\n })\n\n // Deduplicate by transaction hash — multiple events from the same tx\n // (e.g. OptionMinted for each leg) would produce duplicate entries\n const seen = new Set<string>()\n const uniqueEvents = allEvents.filter((e) => {\n if (seen.has(e.transactionHash)) return false\n seen.add(e.transactionHash)\n return true\n })\n\n // Find the most recent transaction with position data\n for (const event of uniqueEvents) {\n try {\n const [tx, block] = await Promise.all([\n client.getTransaction({ hash: event.transactionHash }),\n client.getBlock({ blockNumber: event.blockNumber }),\n ])\n\n // A single tx (e.g. a force-exercise multicall) can embed several\n // dispatch/dispatchFrom calls — the exercisor's own dispatch alongside the\n // victim's dispatchFrom. Select a strict account match first, then allow a\n // plain dispatch only because this tx came from an account-indexed event.\n const candidates = decodeAllDispatchCalldata(tx.input)\n const decoded =\n selectDispatchForAccount(candidates, account, tx.from) ??\n selectDispatchProvenByAccountEvent(candidates)\n if (!decoded) {\n continue\n }\n\n return {\n success: true,\n positionIds: decoded.positionIds,\n blockNumber: event.blockNumber,\n blockHash: block.hash,\n transactionHash: event.transactionHash,\n }\n } catch {\n // Transaction fetch failed, continue\n }\n }\n\n return null\n}\n\nfunction isSnapshotCandidateEvent(event: SnapshotEventLog): event is SnapshotCandidateEvent {\n return event.transactionHash !== null && event.blockNumber !== null && event.logIndex !== null\n}\n\n/**\n * Parameters for recovering a snapshot from a known transaction hash.\n */\nexport interface RecoverSnapshotFromTxParams {\n /** viem public client */\n client: PublicClient\n /** Transaction hash of a known dispatch() call */\n transactionHash: Hash\n /** Account to verify. When set, rejects transactions not sent by (or targeting) this account. */\n account?: Address\n /** Pool address to validate against. When set, rejects transactions not sent to this pool. */\n pool?: Address\n /** Expected Zodiac Roles wrapper for bot-originated Safe dispatches. */\n rolesContext?: {\n modifier: Address\n member: Address\n roleKey: Hash\n }\n}\n\nexport interface RolesSnapshotContext {\n modifier: Address\n member: Address\n roleKey: Hash\n}\n\nexport function decodeSnapshotTransaction(params: {\n input: Hex\n from: Address\n to: Address | null\n account?: Address\n pool?: Address\n rolesContext?: RolesSnapshotContext\n}): DispatchCalldata | null {\n const { account, pool, rolesContext } = params\n let dispatchInput = params.input\n let dispatchSender = params.from\n\n if (rolesContext) {\n if (\n params.to === null ||\n getAddress(params.to) !== getAddress(rolesContext.modifier) ||\n getAddress(params.from) !== getAddress(rolesContext.member)\n ) {\n return null\n }\n try {\n const decodedRoleCall = decodeFunctionData({ abi: rolesExecutionAbi, data: params.input })\n const [target, value, data, operation, roleKey, shouldRevert] = decodedRoleCall.args\n if (\n !pool ||\n getAddress(target) !== getAddress(pool) ||\n value !== 0n ||\n operation !== 0 ||\n roleKey.toLowerCase() !== rolesContext.roleKey.toLowerCase() ||\n !shouldRevert\n ) {\n return null\n }\n dispatchInput = data\n if (!account) return null\n dispatchSender = account\n } catch {\n return null\n }\n } else if (pool && (params.to === null || getAddress(params.to) !== getAddress(pool))) {\n return null\n }\n\n const candidates = decodeAllDispatchCalldata(dispatchInput)\n if (candidates.length === 0) return null\n return account\n ? selectDispatchForAccount(candidates, account, dispatchSender)\n : candidates[candidates.length - 1]\n}\n\n/**\n * Recover position snapshot from a specific dispatch transaction hash.\n *\n * This is an O(1) alternative to {@link recoverSnapshot} when you already\n * know the tx hash of the most recent dispatch. It fetches the transaction,\n * decodes the `finalPositionIdList` from the calldata, and returns the result\n * — no event scanning required.\n *\n * @param params - Recovery parameters including the transaction hash\n * @returns Snapshot recovery result, or null if the tx is not a dispatch call\n *\n * @example\n * ```typescript\n * const snapshot = await recoverSnapshotFromTx({\n * client,\n * transactionHash: '0xabc...',\n * })\n * if (snapshot) {\n * console.log('Open positions:', snapshot.positionIds)\n * }\n * ```\n */\nexport async function recoverSnapshotFromTx(\n params: RecoverSnapshotFromTxParams,\n): Promise<SnapshotRecoveryResult | null> {\n const { client, transactionHash, account, pool, rolesContext } = params\n\n const tx = await client.getTransaction({ hash: transactionHash })\n\n // Pending transactions have no block number — cannot recover snapshot\n if (tx.blockNumber == null) return null\n\n const decoded = decodeSnapshotTransaction({\n input: tx.input,\n from: tx.from,\n to: tx.to,\n account,\n pool,\n rolesContext,\n })\n if (!decoded) return null\n\n const blockNumber = tx.blockNumber\n const block = await client.getBlock({ blockNumber })\n\n return {\n success: true,\n positionIds: decoded.positionIds,\n blockNumber,\n blockHash: block.hash,\n transactionHash,\n }\n}\n\n/**\n * Decoded dispatch calldata result.\n */\nexport interface DispatchCalldata {\n /** Final position ID list after the dispatch */\n positionIds: bigint[]\n /** Target account (only set for dispatchFrom) */\n targetAccount?: Address\n}\n\n/**\n * Decode position IDs from dispatch calldata.\n *\n * When the tx embeds multiple dispatch/dispatchFrom calls (e.g. a force-exercise\n * multicall), this returns the last one — prefer {@link decodeAllDispatchCalldata}\n * plus {@link selectDispatchForAccount} when the account context matters.\n *\n * @param input - Transaction input data\n * @returns Decoded dispatch data or null if not a dispatch call\n */\nexport function decodeDispatchCalldata(input: `0x${string}`): DispatchCalldata | null {\n const all = decodeAllDispatchCalldata(input)\n return all.length > 0 ? all[all.length - 1] : null\n}\n\n/**\n * Decode every dispatch/dispatchFrom call embedded in transaction calldata.\n *\n * A single tx can carry more than one such call — most importantly a force-exercise\n * `multicall` that bundles the exercisor's own `dispatch` together with the victim's\n * `dispatchFrom`. Returning all candidates lets the caller select the one attributable\n * to the relevant account ({@link selectDispatchForAccount}).\n *\n * @param input - Transaction input data\n * @returns All decoded dispatch calls, in calldata order (may be empty)\n */\nexport function decodeAllDispatchCalldata(input: `0x${string}`): DispatchCalldata[] {\n // Try direct dispatch/dispatchFrom first\n const direct = decodeDirectDispatch(input)\n if (direct) return [direct]\n\n // Try unwrapping smart contract wallet wrappers (executeBatch, execute, multicall)\n return decodeWrappedDispatch(input)\n}\n\n/**\n * Select the dispatch call attributable to `account` from a set of candidates.\n *\n * - `dispatchFrom`: matches when `targetAccount === account` (builder/exercisor acting\n * on behalf of the account).\n * - `dispatch` (no `targetAccount`): matches only when the tx sender is the account.\n *\n * Returns the LAST matching candidate (in calldata order), or null when none are\n * attributable to `account`. The last dispatch reflects the final post-transaction\n * state when a single tx contains multiple dispatches for the same account (e.g. a\n * multicall). Matching also prevents accepting a third party's `dispatch` (e.g. the\n * exercisor's own, bundled in a force-exercise multicall) as the account's snapshot.\n *\n * @param candidates - Decoded dispatch calls from a single tx, in calldata order\n * @param account - Account whose position list we are recovering\n * @param txFrom - The transaction sender (`tx.from`)\n */\nexport function selectDispatchForAccount(\n candidates: DispatchCalldata[],\n account: Address,\n txFrom: Address,\n): DispatchCalldata | null {\n const acct = account.toLowerCase()\n let match: DispatchCalldata | null = null\n for (const candidate of candidates) {\n if (candidate.targetAccount) {\n if (candidate.targetAccount.toLowerCase() === acct) match = candidate\n } else if (txFrom.toLowerCase() === acct) {\n match = candidate\n }\n }\n return match\n}\n\nfunction selectDispatchProvenByAccountEvent(\n candidates: DispatchCalldata[],\n): DispatchCalldata | null {\n let match: DispatchCalldata | null = null\n for (const candidate of candidates) {\n if (candidate.targetAccount === undefined) match = candidate\n }\n return match\n}\n\n/**\n * Try to decode input as a direct dispatch or dispatchFrom call.\n */\nfunction decodeDirectDispatch(input: `0x${string}`): DispatchCalldata | null {\n try {\n const decoded = decodeFunctionData({\n abi: panopticPoolV2Abi,\n data: input,\n })\n\n if (decoded.functionName === 'dispatch') {\n const args = decoded.args as readonly [\n bigint[],\n bigint[],\n bigint[],\n readonly [number, number, number][],\n boolean,\n bigint,\n ]\n return { positionIds: [...args[1]] } // finalPositionIdList\n }\n\n if (decoded.functionName === 'dispatchFrom') {\n const args = decoded.args as readonly [bigint[], Address, bigint[], bigint[], bigint]\n return {\n positionIds: [...args[3]], // positionIdListToFinal\n targetAccount: args[1],\n }\n }\n\n return null\n } catch {\n return null\n }\n}\n\n/**\n * 4-byte function selectors for dispatch/dispatchFrom, derived from the generated ABI.\n * Used for scanning raw calldata inside smart contract wallet wrappers.\n */\nconst DISPATCH_SELECTOR = toFunctionSelector(\n panopticPoolV2Abi.find((e) => e.type === 'function' && e.name === 'dispatch') as AbiFunction,\n).slice(2) // strip 0x prefix for hex scanning\n\nconst DISPATCH_FROM_SELECTOR = toFunctionSelector(\n panopticPoolV2Abi.find((e) => e.type === 'function' && e.name === 'dispatchFrom') as AbiFunction,\n).slice(2)\n\n/**\n * Scan raw transaction input for embedded dispatch calldata.\n *\n * Smart contract wallets (Safe, Turnkey, ERC-4337) and vault managers\n * wrap dispatch calls inside executeBatch → manage → dispatch chains.\n * Instead of decoding each wrapper layer, we scan the raw hex for the\n * dispatch function selector and attempt to decode from that offset.\n *\n * This handles arbitrary nesting depth without knowing wrapper ABIs.\n */\nfunction decodeWrappedDispatch(input: `0x${string}`): DispatchCalldata[] {\n const hex = input.slice(2).toLowerCase()\n const selectors = [DISPATCH_SELECTOR, DISPATCH_FROM_SELECTOR]\n\n // Single left-to-right pass: find the earliest selector match at each offset and\n // collect every successful decode, in calldata order. The caller selects the call\n // attributable to the relevant account rather than blindly taking one.\n const results: DispatchCalldata[] = []\n let offset = 0\n\n while (offset < hex.length) {\n // Find the nearest selector match from current offset\n let earliestIdx = -1\n for (const selector of selectors) {\n const idx = hex.indexOf(selector, offset)\n if (idx !== -1 && (earliestIdx === -1 || idx < earliestIdx)) {\n earliestIdx = idx\n }\n }\n if (earliestIdx === -1) break\n\n const candidate = `0x${hex.slice(earliestIdx)}` as `0x${string}`\n const result = decodeDirectDispatch(candidate)\n if (result) results.push(result)\n\n offset = earliestIdx + 8 // Move past this selector\n }\n\n return results\n}\n","/**\n * Tick and price formatters for Uniswap V3/V4 pools.\n *\n * Ticks represent logarithmic prices where: price = 1.0001^tick\n *\n * @module v2/formatters/tick\n */\n\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\n\nconst Q192 = 1n << 192n\nconst RAW_PRICE_PRECISION = 40n\n\nfunction pow10(exponent: bigint): bigint {\n if (exponent < 0n) {\n throw new RangeError('Exponent must be non-negative')\n }\n return 10n ** exponent\n}\n\nfunction absBigint(value: bigint): bigint {\n return value < 0n ? -value : value\n}\n\nfunction trimTrailingZeros(value: string): string {\n const dotIndex = value.indexOf('.')\n if (dotIndex === -1) return value\n\n let end = value.length\n while (end > dotIndex && value[end - 1] === '0') {\n end -= 1\n }\n\n if (end === dotIndex + 1) {\n end = dotIndex\n }\n\n return value.slice(0, end)\n}\n\nfunction formatRatio(numerator: bigint, denominator: bigint, precision: bigint): string {\n if (precision < 0n) {\n throw new RangeError('Precision must be non-negative')\n }\n\n const sign = numerator < 0n ? '-' : ''\n const absNumerator = numerator < 0n ? -numerator : numerator\n\n const scale = pow10(precision)\n const scaled = (absNumerator * scale + denominator / 2n) / denominator\n const integerPart = scaled / scale\n const fractionalPart = scaled % scale\n\n if (precision === 0n) {\n return `${sign}${integerPart}`\n }\n\n return `${sign}${integerPart}.${fractionalPart.toString().padStart(Number(precision), '0')}`\n}\n\nfunction parseDecimalToFraction(value: string): { numerator: bigint; denominator: bigint } {\n const trimmed = value.trim()\n if (trimmed.length === 0) {\n throw new Error('Price must be a number')\n }\n\n const isNegative = trimmed.startsWith('-')\n const unsigned = isNegative || trimmed.startsWith('+') ? trimmed.slice(1) : trimmed\n\n const [basePart, exponentPart] = unsigned.toLowerCase().split('e')\n const [integerStr, fractionalStr = ''] = basePart.split('.')\n\n if (integerStr === '' && fractionalStr === '') {\n throw new Error('Price must be a number')\n }\n\n const integerDigits = integerStr === '' ? '0' : integerStr\n const digits = `${integerDigits}${fractionalStr}`\n\n let numerator = BigInt(digits === '' ? '0' : digits)\n let denominator = pow10(BigInt(fractionalStr.length))\n\n if (exponentPart !== undefined && exponentPart !== '') {\n const exponent = BigInt(exponentPart)\n if (exponent > 0n) {\n numerator *= pow10(exponent)\n } else if (exponent < 0n) {\n denominator *= pow10(-exponent)\n }\n }\n\n if (isNegative) {\n numerator = -numerator\n }\n\n return { numerator, denominator }\n}\n\nfunction compareRatios(\n leftNumerator: bigint,\n leftDenominator: bigint,\n rightNumerator: bigint,\n rightDenominator: bigint,\n): -1 | 0 | 1 {\n const left = leftNumerator * rightDenominator\n const right = rightNumerator * leftDenominator\n\n if (left === right) return 0\n return left < right ? -1 : 1\n}\n\nexport function tickToSqrtPriceX96(tick: bigint): bigint {\n if (tick < MIN_TICK || tick > MAX_TICK) {\n throw new RangeError('Tick out of bounds')\n }\n\n const absTick = tick < 0n ? -tick : tick\n\n let ratio =\n (absTick & 0x1n) !== 0n\n ? 0xfffcb933bd6fad37aa2d162d1a594001n\n : 0x100000000000000000000000000000000n\n if ((absTick & 0x2n) !== 0n) ratio = (ratio * 0xfff97272373d413259a46990580e213an) >> 128n\n if ((absTick & 0x4n) !== 0n) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn) >> 128n\n if ((absTick & 0x8n) !== 0n) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n) >> 128n\n if ((absTick & 0x10n) !== 0n) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n) >> 128n\n if ((absTick & 0x20n) !== 0n) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n) >> 128n\n if ((absTick & 0x40n) !== 0n) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n) >> 128n\n if ((absTick & 0x80n) !== 0n) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n) >> 128n\n if ((absTick & 0x100n) !== 0n) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n) >> 128n\n if ((absTick & 0x200n) !== 0n) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n) >> 128n\n if ((absTick & 0x400n) !== 0n) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n) >> 128n\n if ((absTick & 0x800n) !== 0n) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n) >> 128n\n if ((absTick & 0x1000n) !== 0n) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n) >> 128n\n if ((absTick & 0x2000n) !== 0n) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n) >> 128n\n if ((absTick & 0x4000n) !== 0n) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n) >> 128n\n if ((absTick & 0x8000n) !== 0n) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n) >> 128n\n if ((absTick & 0x10000n) !== 0n) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n) >> 128n\n if ((absTick & 0x20000n) !== 0n) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n) >> 128n\n if ((absTick & 0x40000n) !== 0n) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n) >> 128n\n if ((absTick & 0x80000n) !== 0n) ratio = (ratio * 0x48a170391f7dc42444e8fa2n) >> 128n\n\n if (tick > 0n) {\n ratio = ((1n << 256n) - 1n) / ratio\n }\n\n const remainderMask = (1n << 32n) - 1n\n const sqrtPriceX96 = (ratio >> 32n) + ((ratio & remainderMask) === 0n ? 0n : 1n)\n\n return sqrtPriceX96\n}\n\nconst MIN_SQRT_PRICE_X96 = tickToSqrtPriceX96(MIN_TICK)\nconst MAX_SQRT_PRICE_X96 = tickToSqrtPriceX96(MAX_TICK)\n\nfunction getPriceRatioFromSqrtPriceX96(sqrtPriceX96: bigint): {\n numerator: bigint\n denominator: bigint\n} {\n return {\n numerator: sqrtPriceX96 * sqrtPriceX96,\n denominator: Q192,\n }\n}\n\nfunction getRawPriceRatio(tick: bigint): { numerator: bigint; denominator: bigint } {\n return getPriceRatioFromSqrtPriceX96(tickToSqrtPriceX96(tick))\n}\n\nfunction adjustRatioForDecimals(\n numerator: bigint,\n denominator: bigint,\n decimals0: bigint,\n decimals1: bigint,\n): { numerator: bigint; denominator: bigint } {\n const diff = decimals0 - decimals1\n if (diff === 0n) {\n return { numerator, denominator }\n }\n\n if (diff > 0n) {\n return { numerator: numerator * pow10(diff), denominator }\n }\n\n return { numerator, denominator: denominator * pow10(-diff) }\n}\n\n/**\n * Convert a tick to a raw price string (no decimal adjustment).\n * Uses the formula: price = 1.0001^tick\n *\n * This returns the raw price ratio, not adjusted for token decimals.\n * A fixed internal precision is used and trailing zeros are trimmed.\n *\n * @param tick - The tick value\n * @returns Price string\n *\n * @example\n * ```typescript\n * tickToPrice(0n) // \"1\"\n * tickToPrice(1000n) // \"1.105...\" (approximately)\n * tickToPrice(-1000n) // \"0.904...\" (approximately)\n * tickToPrice(200000n) // Very large number\n * ```\n */\nexport function tickToPrice(tick: bigint): string {\n const { numerator, denominator } = getRawPriceRatio(tick)\n const price = formatRatio(numerator, denominator, RAW_PRICE_PRECISION)\n return trimTrailingZeros(price)\n}\n\n/**\n * Convert a tick to a human-readable price with decimal scaling.\n * Uses the formula: price = 1.0001^tick * 10^(decimals0-decimals1)\n *\n * This adjusts for the different decimals of the two tokens in the pair.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * // WETH/USDC pool (18 decimals / 6 decimals)\n * // At tick ~200000, price is roughly $2000 per ETH\n * tickToPriceDecimalScaled(200000n, 18n, 6n, 2n) // \"2000.00\" (approximately)\n *\n * // For token1/token0 price, swap the decimals\n * tickToPriceDecimalScaled(200000n, 6n, 18n, 6n) // \"0.000500\" (approximately)\n * ```\n */\nexport function tickToPriceDecimalScaled(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getRawPriceRatio(tick)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a sqrtPriceX96 to a human-readable price with decimal scaling.\n *\n * Uses the formula: price = (sqrtPriceX96^2 / 2^192) * 10^(decimals0-decimals1)\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * sqrtPriceX96ToPriceDecimalScaled(2n ** 96n, 18n, 18n, 2n) // \"1.00\"\n * ```\n */\nexport function sqrtPriceX96ToPriceDecimalScaled(\n sqrtPriceX96: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getPriceRatioFromSqrtPriceX96(sqrtPriceX96)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a price to a tick value.\n *\n * @param price - The price string\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * // WETH/USDC: What tick for $2000 per ETH?\n * priceToTick(\"2000\", 18n, 6n) // ~200000n\n *\n * // Inverse: What tick for 0.0005 ETH per USDC?\n * priceToTick(\"0.0005\", 6n, 18n) // ~200000n\n * ```\n */\nexport function priceToTick(price: string, decimals0: bigint, decimals1: bigint): bigint {\n const parsed = parseDecimalToFraction(price)\n if (parsed.numerator <= 0n) {\n throw new Error('Price must be positive')\n }\n\n let targetNumerator = parsed.numerator\n let targetDenominator = parsed.denominator\n\n const diff = decimals0 - decimals1\n if (diff > 0n) {\n targetDenominator *= pow10(diff)\n } else if (diff < 0n) {\n targetNumerator *= pow10(-diff)\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const { numerator, denominator } = getRawPriceRatio(mid)\n const cmp = compareRatios(numerator, denominator, targetNumerator, targetDenominator)\n\n if (cmp === 0) {\n return mid\n }\n\n if (cmp < 0) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorRatio = getRawPriceRatio(floorTick)\n const ceilRatio = getRawPriceRatio(ceilTick)\n\n const floorDiffNumerator = absBigint(\n targetNumerator * floorRatio.denominator - floorRatio.numerator * targetDenominator,\n )\n const ceilDiffNumerator = absBigint(\n targetNumerator * ceilRatio.denominator - ceilRatio.numerator * targetDenominator,\n )\n const floorDiffDenominator = targetDenominator * floorRatio.denominator\n const ceilDiffDenominator = targetDenominator * ceilRatio.denominator\n\n return floorDiffNumerator * ceilDiffDenominator <= ceilDiffNumerator * floorDiffDenominator\n ? floorTick\n : ceilTick\n}\n\n/**\n * Convert a sqrtPriceX96 value to the nearest tick.\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * const tick = sqrtPriceX96ToTick(2n ** 96n) // 0n\n * ```\n */\nexport function sqrtPriceX96ToTick(sqrtPriceX96: bigint): bigint {\n if (sqrtPriceX96 <= 0n) {\n throw new Error('Sqrt price must be positive')\n }\n\n if (sqrtPriceX96 < MIN_SQRT_PRICE_X96 || sqrtPriceX96 > MAX_SQRT_PRICE_X96) {\n throw new RangeError('Sqrt price out of bounds')\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const midSqrt = tickToSqrtPriceX96(mid)\n\n if (midSqrt === sqrtPriceX96) {\n return mid\n }\n\n if (midSqrt < sqrtPriceX96) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorSqrt = tickToSqrtPriceX96(floorTick)\n const ceilSqrt = tickToSqrtPriceX96(ceilTick)\n\n const floorDiff = absBigint(sqrtPriceX96 - floorSqrt)\n const ceilDiff = absBigint(ceilSqrt - sqrtPriceX96)\n\n return floorDiff <= ceilDiff ? floorTick : ceilTick\n}\n\n/**\n * Format a tick value for display.\n *\n * @param tick - The tick value\n * @returns Formatted tick string\n *\n * @example\n * ```typescript\n * formatTick(200000n) // \"200000\"\n * formatTick(-50000n) // \"-50000\"\n * ```\n */\nexport function formatTick(tick: bigint): string {\n return tick.toString()\n}\n\n/**\n * Get the price at a specific tick, returning both token0/token1 and token1/token0 prices.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Object with both price directions\n *\n * @example\n * ```typescript\n * const prices = getPricesAtTick(200000n, 18n, 6n, 2n)\n * // prices.token0PerToken1 = \"0.00\" (very small)\n * // prices.token1PerToken0 = \"2000.00\" (USDC per ETH)\n * ```\n */\nexport function getPricesAtTick(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): { token0PerToken1: string; token1PerToken0: string } {\n const rawRatio = getRawPriceRatio(tick)\n const adjustedRatio = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return {\n token0PerToken1: formatRatio(adjustedRatio.denominator, adjustedRatio.numerator, precision),\n token1PerToken0: formatRatio(adjustedRatio.numerator, adjustedRatio.denominator, precision),\n }\n}\n\n/**\n * Format a tick range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @returns Formatted tick range string\n *\n * @example\n * ```typescript\n * formatTickRange(-50000n, 200000n) // \"-50000 - 200000\"\n * ```\n */\nexport function formatTickRange(tickLower: bigint, tickUpper: bigint): string {\n return `${tickLower} - ${tickUpper}`\n}\n\n/**\n * Format a price range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price range string\n *\n * @example\n * ```typescript\n * formatPriceRange(0n, 0n, 18n, 18n, 2n) // \"1.00 - 1.00\"\n * ```\n */\nexport function formatPriceRange(\n tickLower: bigint,\n tickUpper: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const lower = tickToPriceDecimalScaled(tickLower, decimals0, decimals1, precision)\n const upper = tickToPriceDecimalScaled(tickUpper, decimals0, decimals1, precision)\n return `${lower} - ${upper}`\n}\n\n/**\n * Calculate the tick spacing for a given fee tier.\n *\n * @param feeBps - Fee in basis points (e.g., 500n for 0.05%)\n * @returns Tick spacing\n *\n * @example\n * ```typescript\n * getTickSpacing(100n) // 1n (0.01% fee tier)\n * getTickSpacing(500n) // 10n (0.05% fee tier)\n * getTickSpacing(3000n) // 60n (0.30% fee tier)\n * getTickSpacing(10000n) // 200n (1.00% fee tier)\n * ```\n */\nexport function getTickSpacing(feeBps: bigint): bigint {\n // Standard Uniswap V3 tick spacings\n switch (feeBps) {\n case 100n:\n return 1n\n case 500n:\n return 10n\n case 3000n:\n return 60n\n case 10000n:\n return 200n\n default: {\n const spacing = feeBps / 50n\n return spacing > 1n ? spacing : 1n\n }\n }\n}\n\n/**\n * Round a tick to the nearest valid tick for a given tick spacing.\n *\n * @param tick - The tick to round\n * @param tickSpacing - The tick spacing\n * @returns Rounded tick\n *\n * @example\n * ```typescript\n * roundToTickSpacing(12345n, 10n) // 12340n\n * roundToTickSpacing(12345n, 60n) // 12360n\n * roundToTickSpacing(-12345n, 10n) // -12350n\n * ```\n */\nexport function roundToTickSpacing(tick: bigint, tickSpacing: bigint): bigint {\n const remainder = tick % tickSpacing\n if (remainder === 0n) {\n return tick\n }\n // Round to nearest\n if (tick >= 0n) {\n return remainder >= tickSpacing / 2n ? tick + (tickSpacing - remainder) : tick - remainder\n }\n\n const absRemainder = -remainder\n return absRemainder >= tickSpacing / 2n\n ? tick - (tickSpacing - absRemainder)\n : tick + absRemainder\n}\n\n/**\n * Result of {@link tickLimits}.\n */\nexport interface TickLimitsResult {\n /** Lower tick limit (clamped to MIN_TICK). */\n low: bigint\n /** Upper tick limit (clamped to MAX_TICK). */\n high: bigint\n}\n\n/**\n * Compute slippage-bounded tick limits around the current tick.\n *\n * 1 tick ≈ 1 basis point (0.01 %) of price change, so a `toleranceBps`\n * of 500 allows roughly 5 % price movement. The result is clamped to\n * the protocol's `[MIN_TICK, MAX_TICK]` range.\n *\n * Useful for setting `tickLimitLow` / `tickLimitHigh` on `openPosition`\n * and `closePosition` to protect against MEV sandwiches and volatile\n * tick moves.\n *\n * @param currentTick - The current pool tick (must be within [MIN_TICK, MAX_TICK]).\n * @param toleranceBps - Slippage tolerance in basis points (≈ ticks). Must be non-negative.\n * @returns Clamped `{ low, high }` tick limits.\n * @throws {RangeError} If `toleranceBps` is negative or `currentTick` is out of bounds.\n *\n * @example\n * ```typescript\n * const { low, high } = tickLimits(200_000n, 500n)\n * // low = 199_500n\n * // high = 200_500n\n *\n * await openPosition({ ..., tickLimitLow: low, tickLimitHigh: high })\n * ```\n */\nexport function tickLimits(currentTick: bigint, toleranceBps: bigint): TickLimitsResult {\n if (toleranceBps < 0n) {\n throw new RangeError(`toleranceBps must be non-negative, got ${toleranceBps}`)\n }\n if (currentTick < MIN_TICK || currentTick > MAX_TICK) {\n throw new RangeError(`currentTick ${currentTick} is out of bounds [${MIN_TICK}, ${MAX_TICK}]`)\n }\n\n const rawLow = currentTick - toleranceBps\n const rawHigh = currentTick + toleranceBps\n const low = rawLow < MIN_TICK ? MIN_TICK : rawLow\n const high = rawHigh > MAX_TICK ? MAX_TICK : rawHigh\n\n if (low > high) {\n throw new RangeError(\n `Computed tick limits are inverted: low ${low} > high ${high} (currentTick=${currentTick}, toleranceBps=${toleranceBps})`,\n )\n }\n\n return { low, high }\n}\n","import { ORACLE_EPOCH_SECONDS } from './constants'\n\nconst ORACLE_EPOCH_SHIFT = 232n\nconst ORACLE_EPOCH_MASK = (1n << 24n) - 1n\nconst ORACLE_TICK_MASK = (1n << 22n) - 1n\n\nfunction decodeSigned22(value: bigint): bigint {\n const signBit = 1n << 21n\n const truncated = value & ORACLE_TICK_MASK\n return (truncated & signBit) === 0n ? truncated : truncated - (1n << 22n)\n}\n\n/** Timing decoded from an OraclePack and resolved against a specific block. */\nexport interface OracleTiming {\n /** Modulo-2^24 oracle epoch stored on-chain. */\n epoch: bigint\n /** Absolute epoch-boundary timestamp reconstructed at or before the supplied block. */\n timestamp: bigint\n}\n\n/** Fixed-width oracle state decoded from an OraclePack. */\nexport interface DecodedOraclePack {\n referenceTick: bigint\n lockMode: bigint\n spotEMA: bigint\n fastEMA: bigint\n slowEMA: bigint\n eonsEMA: bigint\n epoch: bigint\n timestamp: bigint\n}\n\n/**\n * Decode the 24-bit epoch stored at bits 232..255 of OraclePack.\n *\n * The packed timestamp is modulo 2^30 seconds and only identifies an absolute\n * Unix timestamp within the wrap window containing `blockTimestamp`. Supplying\n * the relevant block timestamp resolves it to the latest matching epoch at or\n * before that block, including across the epoch counter wraparound.\n */\nexport function decodeOracleTiming(oraclePack: bigint, blockTimestamp: bigint): OracleTiming {\n const epoch = (oraclePack >> ORACLE_EPOCH_SHIFT) & ORACLE_EPOCH_MASK\n const currentEpoch = oracleEpochAt(blockTimestamp)\n const elapsedEpochs = (currentEpoch - epoch) & ORACLE_EPOCH_MASK\n const currentEpochTimestamp = blockTimestamp - (blockTimestamp % ORACLE_EPOCH_SECONDS)\n return { epoch, timestamp: currentEpochTimestamp - elapsedEpochs * ORACLE_EPOCH_SECONDS }\n}\n\n/** Decode the fixed-width ticks and guardian state stored in OraclePack. */\nexport function decodeOraclePack(oraclePack: bigint, blockTimestamp: bigint): DecodedOraclePack {\n const timing = decodeOracleTiming(oraclePack, blockTimestamp)\n return {\n referenceTick: decodeSigned22(oraclePack >> 96n),\n lockMode: (oraclePack >> 118n) & 3n,\n spotEMA: decodeSigned22(oraclePack >> 120n),\n fastEMA: decodeSigned22(oraclePack >> 142n),\n slowEMA: decodeSigned22(oraclePack >> 164n),\n eonsEMA: decodeSigned22(oraclePack >> 186n),\n ...timing,\n }\n}\n\n/** Return the contract's modulo-2^24 64-second epoch for a block timestamp. */\nexport function oracleEpochAt(timestamp: bigint): bigint {\n return (timestamp / ORACLE_EPOCH_SECONDS) & ORACLE_EPOCH_MASK\n}\n","import { PanopticValidationError } from '../errors'\nimport type { OracleState } from '../types'\nimport { ORACLE_EPOCH_SECONDS } from './constants'\n\nconst UINT24_MASK = (1n << 24n) - 1n\n\nexport interface OracleEmaPeriods {\n spot: bigint\n fast: bigint\n slow: bigint\n eons: bigint\n}\n\nexport interface OracleRiskParameters {\n emaPeriods: OracleEmaPeriods\n maxTicksDelta: bigint\n /** Informational observation clamp; not used by SafeMode diagnosis. May be zero. */\n maxClampDelta: bigint\n}\n\nexport type OracleSafeModeCause =\n | 'externalShock'\n | 'internalDisagreement'\n | 'highDivergence'\n | 'guardianLock'\n | 'unknown'\n\nexport interface OracleSafeModeDiagnosis {\n /** Authoritative value returned by PanopticPool.isSafeMode(). */\n level: bigint\n /** Value reproduced using the known RiskEngine formula and live constants. */\n reproducedLevel: bigint\n matchesOnchain: boolean\n causes: readonly OracleSafeModeCause[]\n externalShockDelta: bigint\n internalDisagreementDelta: bigint\n highDivergenceDelta: bigint\n guardianLocked: boolean\n /** Minimum whole 64-second oracle epochs to wait after the last observation. */\n minimumPokeEpochs: bigint\n shouldPoke: boolean\n}\n\ntype DiagnosticOracleState = Pick<\n OracleState,\n 'currentTick' | 'spotEMA' | 'fastEMA' | 'slowEMA' | 'medianTick' | 'lockMode'\n>\n\nfunction absoluteDelta(left: bigint, right: bigint): bigint {\n return left >= right ? left - right : right - left\n}\n\nfunction epochsForPeriod(period: bigint): bigint {\n return (period + ORACLE_EPOCH_SECONDS - 1n) / ORACLE_EPOCH_SECONDS\n}\n\n/** Decode the four uint24 periods packed by RiskEngine.EMA_PERIODS(). */\nexport function decodeOracleRiskParameters(\n emaPeriods: bigint,\n maxTicksDelta: bigint,\n maxClampDelta: bigint,\n): OracleRiskParameters {\n const decodedPeriods = {\n spot: emaPeriods & UINT24_MASK,\n fast: (emaPeriods >> 24n) & UINT24_MASK,\n slow: (emaPeriods >> 48n) & UINT24_MASK,\n eons: (emaPeriods >> 72n) & UINT24_MASK,\n }\n if (\n decodedPeriods.spot === 0n ||\n decodedPeriods.fast === 0n ||\n decodedPeriods.slow === 0n ||\n decodedPeriods.eons === 0n ||\n maxTicksDelta <= 0n ||\n maxClampDelta < 0n\n ) {\n throw new PanopticValidationError(\n `RiskEngine returned invalid oracle parameters: EMA_PERIODS=${emaPeriods}, ` +\n `MAX_TICKS_DELTA=${maxTicksDelta}, MAX_CLAMP_DELTA=${maxClampDelta}`,\n )\n }\n return { emaPeriods: decodedPeriods, maxTicksDelta, maxClampDelta }\n}\n\n/** Explain the on-chain SafeMode level using this deployment's RiskEngine constants. */\nexport function diagnoseOracleSafeMode(\n state: DiagnosticOracleState,\n parameters: OracleRiskParameters,\n onchainLevel: bigint,\n): OracleSafeModeDiagnosis {\n const externalShockDelta = absoluteDelta(state.currentTick, state.spotEMA)\n const internalDisagreementDelta = absoluteDelta(state.spotEMA, state.fastEMA)\n const highDivergenceDelta = absoluteDelta(state.medianTick, state.slowEMA)\n const internalThreshold = parameters.maxTicksDelta / 2n\n const externalShock = externalShockDelta > parameters.maxTicksDelta\n const internalDisagreement = internalDisagreementDelta > internalThreshold\n const highDivergence = highDivergenceDelta > internalThreshold\n const guardianLocked = state.lockMode !== 0n\n\n const algorithmicLevel =\n (externalShock ? 1n : 0n) + (internalDisagreement ? 1n : 0n) + (highDivergence ? 1n : 0n)\n const reproducedLevel = algorithmicLevel + state.lockMode\n const matchesOnchain = reproducedLevel === onchainLevel\n const causes: OracleSafeModeCause[] = []\n if (matchesOnchain) {\n if (externalShock) causes.push('externalShock')\n if (internalDisagreement) causes.push('internalDisagreement')\n if (highDivergence) causes.push('highDivergence')\n } else {\n causes.push('unknown')\n }\n if (guardianLocked) causes.push('guardianLock')\n\n const candidateEpochs: bigint[] = []\n if (!matchesOnchain) candidateEpochs.push(1n)\n if (highDivergence) candidateEpochs.push(1n)\n if (externalShock) candidateEpochs.push(epochsForPeriod(parameters.emaPeriods.spot))\n if (internalDisagreement) candidateEpochs.push(epochsForPeriod(parameters.emaPeriods.fast))\n const minimumPokeEpochs = candidateEpochs.reduce(\n (minimum, epochs) => (minimum === 0n || epochs < minimum ? epochs : minimum),\n 0n,\n )\n\n return {\n level: onchainLevel,\n reproducedLevel,\n matchesOnchain,\n causes,\n externalShockDelta,\n internalDisagreementDelta,\n highDivergenceDelta,\n guardianLocked,\n minimumPokeEpochs,\n shouldPoke: onchainLevel > 0n && !guardianLocked,\n }\n}\n","/**\n * Client-side greeks for the Panoptic v2 SDK.\n *\n * All functions accept bigint inputs (ticks, sizes) and return bigint values\n * in the natural token units — no artificial WAD scaling. The tick-based price\n * (1.0001^tick) naturally encodes the decimal conversion between tokens.\n *\n * Uses pure sqrtPriceX96 arithmetic for exact on-chain fidelity with PanopticQuery.\n * All intermediate calculations keep X96/X192 precision until final scaling.\n *\n * - Value: in numeraire token smallest units (e.g., USDC wei if numeraire is USDC)\n * - Delta: in asset token smallest units (e.g., WETH wei if asset is WETH)\n * - Gamma (dollar-gamma): in numeraire token smallest units\n *\n * @module v2/greeks\n */\n\nimport { tickToSqrtPriceX96 } from '../formatters/tick'\nimport type { TokenIdLeg } from '../types'\n\n// --- Internal Helpers ---\n\n/** Fixed-point scale constants for sqrtPriceX96 arithmetic */\nconst Q96 = 1n << 96n\nconst Q192 = 1n << 192n\n\n/**\n * Convert tick to quote-denominated tick based on asset direction.\n *\n * When isAssetToken0 = true (asset is token0, numeraire is token1):\n * - Tick already encodes price as token1/token0 (numeraire per asset)\n * - Return tick unchanged\n *\n * When isAssetToken0 = false (asset is token1, numeraire is token0):\n * - Tick encodes price as token1/token0, but we need token0/token1 (numeraire per asset)\n * - Invert by negating: 1/price = 1.0001^(-tick)\n */\nfunction quoteTick(tick: bigint, isAssetToken0: boolean): bigint {\n return isAssetToken0 ? tick : -tick\n}\n\n/**\n * Divide with truncation toward zero (matches Solidity division behavior).\n *\n * JavaScript bigint division uses floor (toward negative infinity), but Solidity\n * truncates toward zero. For on-chain fidelity, we must match Solidity.\n *\n * Example:\n * - Solidity: -7 / 2 = -3 (truncate toward zero)\n * - JS bigint: -7n / 2n = -4n (floor toward -∞)\n * - This function: divTrunc(-7n, 2n) = -3n ✓\n */\nfunction divTrunc(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) return 0n\n\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n\n // If signs differ and there's a remainder, JS floored when we need to truncate\n // Add 1 to move toward zero\n if (numerator < 0n !== denominator < 0n && remainder !== 0n) {\n return quotient + 1n\n }\n\n return quotient\n}\n\n/** Resolve isAssetToken0: optional assetIndex overrides leg.asset */\nfunction resolveAssetDirection(leg: Pick<TokenIdLeg, 'asset'>, assetIndex?: bigint): boolean {\n return assetIndex !== undefined ? assetIndex === 0n : leg.asset === 0n\n}\n\n/**\n * Compute the tokenType-denominated notional of a width=0 (loan/credit) leg.\n *\n * When leg.asset !== leg.tokenType, positionSize is in leg.asset units and\n * the borrowed notional is encoded via leg.strike: notional_tokenType_raw =\n * positionSize_raw × 1.0001^strike (a raw-to-raw ratio, unquoted by pool direction).\n * When leg.asset === leg.tokenType, m is already the notional (old convention).\n *\n * `m > 0` for loans (isLong=false), `m < 0` for credits (isLong=true), so the\n * returned notional is signed the same way.\n */\nfunction computeWidth0Notional(leg: TokenIdLeg, m: bigint): bigint {\n const scaleByStrike = leg.asset !== leg.tokenType\n if (!scaleByStrike) return m\n // The UI stores strike with a sign that depends on leg.asset:\n // priceTokenTypePerAsset = 1.0001^(leg.asset === 0 ? strike : -strike)\n // Mirror that here so K_raw matches the intended notional scaling.\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n return divTrunc(m * KrawX192, Q192)\n}\n\n/**\n * Calculate value for a width=0 (loan/credit) leg.\n * Width=0 means the range is a single tick (the strike), so there's no meaningful\n * \"in range\" — we use the below/above formulas which avoid division by (r-1)=0.\n *\n * This is the DEBT-ONLY value (the borrowed/lent obligation), used by delta/greeks\n * aggregation where the held-collateral side lives in a separate wallet/CT term. For\n * a standalone payoff chart that must reflect the net user-experienced payoff (which\n * depends on Zap vs Cover-at-mint), use `getLegNetValueWidth0`.\n */\nfunction getLegValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n _definedRisk: boolean,\n): bigint {\n // For loan/credit legs (width=0), value depends on the borrowed token.\n // m > 0 for loans (isLong=false), m < 0 for credits (isLong=true).\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n const notional = computeWidth0Notional(leg, m)\n\n if (borrowsAsset) {\n // Asset loan/credit: debt PnL = -notional*(P - Pm); crosses y=0 at mint price, delta=-notional.\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n } else {\n // Numeraire loan/credit: the obligation is a constant amount of the numeraire token,\n // so its value doesn't change with price. getLegValue is mint-relative PnL (option\n // legs cancel the mint baseline via `itm`; the asset branch above returns\n // -notional*(P - Pm), which is 0 at mint), so the numeraire branch's mint-relative PnL\n // is value(P) - value(Pm) = const - const = 0. Returning a nonzero constant here would\n // shift the whole PnL curve/baseline by the notional (double-counting the credit).\n return 0n\n }\n}\n\n/**\n * Calculate the NET (user-experienced) payoff value for a width=0 (loan/credit) leg.\n *\n * Unlike `getLegValueWidth0` (debt-only), this includes the collateral/holding side and\n * therefore depends on how the position was opened:\n *\n * - **Cover at mint** (`swapAtMint = false`): the collateral is sourced in the SAME token as\n * the debt/credit, so the holding side exactly offsets it → net PnL is FLAT (0 everywhere,\n * mint-relative), regardless of which token the leg is denominated in.\n * - **Zap** (`swapAtMint = true`): the collateral is sourced in the OTHER token, leaving a\n * ±1-delta line in the asset (ETH), anchored to 0 at the mint price:\n * - USDC loan → zap to ETH: +1 (long ETH)\n * - ETH loan → zap to USDC: −1 (short ETH)\n * - USDC credit ← zap from ETH: −1 (short ETH)\n * - ETH credit ← zap from USDC: +1 (long ETH)\n *\n * @returns Net leg value in numeraire token smallest units (mint-relative PnL).\n */\nexport function getLegNetValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n swapAtMint: boolean,\n itmOffsetNotional: bigint = 0n,\n): bigint {\n // Cover at mint: collateral in the same token as the debt/credit cancels it → flat.\n if (!swapAtMint) return 0n\n\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n // ITM-neutralizing credits/loans are sized to offset an option leg's mint-time ITM,\n // which was zapped into the other token under swapAtMint and therefore carries the same\n // ±delta line this leg would otherwise add. Net the leg's notional against that ITM\n // (`itmOffsetNotional`, same token side, opposite sign) so a correctly-sized credit\n // cancels to flat and only the residual (over/under-sizing) contributes a swap line.\n const notional = computeWidth0Notional(leg, m) + itmOffsetNotional\n\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n\n if (borrowsAsset) {\n // Debt/credit is in the asset (ETH); zapping the collateral into the numeraire leaves the\n // debt-only asset exposure -notional*(P - Pm). (Loan → short ETH; credit → long ETH.)\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n }\n\n // Debt/credit is in the numeraire (USDC); zapping sources/spends the asset (ETH). We hold\n // notional/Pm units of ETH, worth (notional/Pm)*(P - Pm) = notional*(P/Pm) - notional in\n // numeraire. (Loan → long ETH; credit → short ETH.) Zero at mint by construction.\n return divTrunc(notional * PX192, PmX192) - notional\n}\n\n/**\n * Compute the mint-time ITM (in-the-money) adjustment for an option leg.\n *\n * This is the `itm` baseline used by {@link getLegValue}: the amount by which the\n * position was already ITM at mint, expressed in the leg's natural units:\n * - Puts: numeraire units (added directly to the put's `debt*K + v` value).\n * - Calls: asset-ratio units (the call value multiplies it by price: `itm*P`/`itm*Pm`).\n *\n * Extracted so callers (e.g. {@link calculatePositionValue}) can build a per-side ITM\n * notional pool to net width=0 credit/loan legs against — an ITM-neutralizing credit\n * was sized to offset exactly this amount, so it should not add a spurious swap line.\n */\nfunction computeOptionItm(\n m: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n halfWidthTick: bigint,\n isPut: boolean,\n): bigint {\n if (isPut) {\n // Put ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = (K - Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (KX192 - PmX192), Q192)\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = 0\n return 0n\n }\n // In range: itm = m * (sqrt(K*r) - sqrt(Pm))^2 / (r - 1)\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const rX192 = sqrtR * sqrtR\n const diff = sqrtKR - sqrtPm // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n\n // Call ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = (1 - K/Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (PmX192 - KX192), PmX192)\n }\n // In range: itm = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const rX192 = sqrtR * sqrtR\n // sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = divTrunc(sqrtK * Q96, sqrtPm)\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n}\n\n// --- Public Helpers ---\n\n/**\n * Check if leg is a call option (vs put).\n *\n * A call is when the leg moves the asset token:\n * - If asset is token0: call when tokenType=0\n * - If asset is token1: call when tokenType=1\n */\nexport function isCall(tokenType: bigint, isAssetToken0: boolean): boolean {\n return isAssetToken0 ? tokenType === 0n : tokenType === 1n\n}\n\n/**\n * Check if position has defined risk (is a spread).\n *\n * A position is defined risk if it has 2+ legs of the same tokenType\n * with both long and short exposure.\n */\nexport function isDefinedRisk(legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]): boolean {\n if (legs.length < 2) return false\n\n for (const tt of [0n, 1n]) {\n const group = legs.filter((l) => l.tokenType === tt)\n if (group.length >= 2 && group.some((l) => l.isLong) && group.some((l) => !l.isLong)) {\n return true\n }\n }\n return false\n}\n\n// --- Per-Leg Greeks ---\n\n/**\n * Calculate the value of a single leg.\n *\n * Value represents the current P&L of the position in numeraire token units.\n * Combines base value (from Panoptic's piecewise formula), debt, and ITM adjustment.\n *\n * Uses sqrtPriceX96 for all calculations to maintain precision and on-chain fidelity.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param mintTick - Tick at position mint\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg value in numeraire token smallest units\n */\nexport function getLegValue(\n leg: TokenIdLeg,\n currentTick: bigint,\n mintTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n definedRisk: boolean,\n assetIndex?: bigint,\n swapAtMint?: boolean,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit (leg.width === 0n): when the caller specifies how the position was\n // opened (swapAtMint), return the NET user-experienced payoff (Zap vs Cover) instead of\n // the debt-only value. Narrow options whose halfWidth rounds to 0 are excluded.\n if (leg.width === 0n && swapAtMint !== undefined) {\n return getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint)\n }\n\n // Width=0 (loans/credits): single-tick position, no range to integrate over.\n if (halfWidthTick === 0n) {\n return getLegValueWidth0(\n leg,\n m,\n qCurrentTick,\n qStrikeTick,\n qMintTick,\n isAssetToken0,\n definedRisk,\n )\n }\n\n // Compute base value: v = f(P, K, r) from Panoptic's piecewise formula\n let v: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: v = m * P\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n v = divTrunc(m * PX192, Q192)\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: v = m * K\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n v = divTrunc(m * KX192, Q192)\n } else {\n // In range: v = m * (2*sqrt(P*K*r) - P - K) / (r - 1)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPKR = tickToSqrtPriceX96(qCurrentTick + qStrikeTick + halfWidthTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n\n const PX192 = sqrtP * sqrtP\n const KX192 = sqrtK * sqrtK\n const rX192 = sqrtR * sqrtR\n\n // v = m * (2*sqrtPKR/2^96 - PX192/2^192 - KX192/2^192) / ((rX192 - 2^192)/2^192)\n // = m * (2*sqrtPKR*2^96 - PX192 - KX192) / (rX192 - 2^192)\n const numerator = m * (2n * sqrtPKR * Q96 - PX192 - KX192)\n const denominator = rX192 - Q192\n v = divTrunc(numerator, denominator)\n }\n\n const debt = -m\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n // Compute ITM adjustment (differs for puts vs calls)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n\n // Compute final result based on option type\n if (isPut) {\n // Put: result = debt * K + v + itm\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n const debtK = divTrunc(debt * KX192, Q192)\n return debtK + v + itm\n } else {\n // Call: result = debt*P + v + itm*Pm (if defined risk) or debt*P + v + itm*P (if not)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n const debtP = divTrunc(debt * PX192, Q192)\n\n if (definedRisk) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PmX192 = sqrtPm * sqrtPm\n const itmPm = divTrunc(itm * PmX192, Q192)\n return debtP + v + itmPm\n } else {\n const itmP = divTrunc(itm * PX192, Q192)\n return debtP + v + itmP\n }\n }\n}\n\n/**\n * Calculate the delta of a single leg.\n *\n * Delta is the rate of change of position value with respect to price.\n * For puts: delta = vDelta\n * For calls: delta = debtDelta + vDelta + itmDelta (if not defined risk)\n *\n * Uses sqrtPriceX96 for all price calculations to maintain precision.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param mintTick - Tick at mint (optional, for ITM adjustment)\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg delta in asset token smallest units\n */\nexport function getLegDelta(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit: leg.width === 0n (not just halfWidth rounding to 0).\n // Debt-side exposure only — no option-like piecewise formula.\n if (leg.width === 0n) {\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n if (!borrowsAsset) return 0n\n // See getLegValueWidth0 for the notional-scaling rationale.\n if (leg.asset === leg.tokenType) return -m\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n const notional = divTrunc(m * KrawX192, Q192)\n return -notional\n }\n\n // Narrow option whose halfWidth rounds to 0: use option-like width=0 branch\n if (halfWidthTick === 0n) {\n const vDelta = qCurrentTick <= qStrikeTick ? m : 0n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n if (isPut) return vDelta\n\n // Call: add debt delta and ITM delta (same as normal path but no in-range branch)\n const debtDelta = -m\n let itmDelta = 0n\n if (mintTick !== undefined && !definedRisk) {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n if (qMintTick > qStrikeTick) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const PmX192 = sqrtPm * sqrtPm\n const KX192 = sqrtK * sqrtK\n itmDelta = divTrunc((PmX192 - KX192) * m, PmX192)\n }\n }\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n }\n\n // Compute vDelta: derivative of value with respect to price\n // vDelta = P < lo ? m : P > hi ? 0 : (m * (sqrt(K*r)/sqrt(P) - 1)) / (r - 1)\n let vDelta: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: vDelta = m\n vDelta = m\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: vDelta = 0\n vDelta = 0n\n } else {\n // In range: vDelta = m * (sqrt(K*r) - sqrt(P)) / (sqrt(P) * (r - 1))\n const sqrtP = tickToSqrtPriceX96(qCurrentTick) // X96\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick) // sqrt(K*r) in X96\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // vDelta = m * (sqrtKR - sqrtP)/2^96 / (sqrtP/2^96 * (rX192 - 2^192)/2^192)\n // = m * (sqrtKR - sqrtP) * 2^192 / (sqrtP * (rX192 - 2^192))\n const numerator = m * (sqrtKR - sqrtP) * Q192\n const denominator = sqrtP * (rX192 - Q192)\n vDelta = divTrunc(numerator, denominator)\n }\n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n if (isPut) {\n return vDelta\n }\n\n // Call: add debt delta and ITM delta\n const debtDelta = -m\n\n const itmDelta =\n mintTick === undefined\n ? 0n\n : (() => {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itmDelta = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itmDelta = (1 - K/Pm) * m = (Pm - K) * m / Pm\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const PmX192 = sqrtPm * sqrtPm // X192\n const KX192 = sqrtK * sqrtK // X192\n\n // itmDelta = (1 - K/Pm) * m = (PmX192 - KX192) * m / PmX192\n return divTrunc((PmX192 - KX192) * m, PmX192)\n } else {\n // In range: itmDelta = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // sqrt(K/Pm) = sqrtK / sqrtPm (both X96, so scale cancels)\n // But we need (sqrt(r) - sqrt(K/Pm))^2, so work in X96:\n // sqrtKPm = sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = (sqrtK * Q96) / sqrtPm // X96\n\n // (sqrt(r) - sqrt(K/Pm))^2 = (sqrtR - sqrtKPmX96)^2 / 2^192\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n\n // itmDelta = m * diffSqX192 / 2^192 / (rX192 / 2^192 - 1)\n // = m * diffSqX192 / (rX192 - 2^192)\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n })()\n\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n}\n\n/** Convert a delta between token frames at the current pool tick. */\nexport function toVaultFrameAtTick(\n delta: bigint,\n fromAsset: bigint,\n vaultAssetIndex: 0n | 1n,\n currentTick: bigint,\n flipSignOnAssetInversion = false,\n): bigint {\n if (fromAsset === vaultAssetIndex) return delta\n const sqrtPriceX96 = tickToSqrtPriceX96(currentTick)\n const converted =\n vaultAssetIndex === 0n\n ? (delta * Q192) / (sqrtPriceX96 * sqrtPriceX96)\n : (delta * sqrtPriceX96 * sqrtPriceX96) / Q192\n return flipSignOnAssetInversion ? -converted : converted\n}\n\n/**\n * Calculate one leg's wallet-aware delta in the vault asset frame.\n *\n * Width-zero loans and credits must be evaluated directly in the vault frame.\n * Option legs remain in their natural leg frame until converted at the mark tick.\n */\nexport function getLegDeltaInVaultFrame(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n vaultAssetIndex: 0n | 1n,\n): bigint {\n if (leg.width === 0n) {\n return getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n vaultAssetIndex,\n )\n }\n\n const legDelta = getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n )\n return toVaultFrameAtTick(legDelta, leg.asset, vaultAssetIndex, currentTick, true)\n}\n\n/**\n * Calculate the gamma (dollar gamma) of a single leg.\n *\n * Formula: gamma = (m * sqrt(K * P * r)) / (2 * (r - 1))\n * where:\n * - m = positionSize * optionRatio (with sign based on long/short)\n * - K = strike price (numeraire/asset)\n * - P = current price (numeraire/asset)\n * - r = 1.0001^(width*tickSpacing/2) ≈ 1 (dimensionless ratio)\n *\n * Uses sqrtPriceX96 arithmetic:\n * - sqrt(K*P*r) = tickToSqrtPriceX96(strikeₜ + currentₜ + widthₜ/2)\n * - Keeps X96/X192 precision until final division\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg gamma in numeraire token smallest units\n */\nexport function getLegGamma(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n\n // Convert to quote-denominated ticks (negate if asset is token0)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n // True loan: no gamma\n if (leg.width === 0n) return 0n\n\n // Narrow option whose halfWidth rounds to 0: no curvature (denominator 2*(r-1)=0)\n if (halfWidthTick === 0n) return 0n\n\n // Range check: gamma is zero outside [strike - halfWidth, strike + halfWidth]\n // This works in both normal and inverted tick space\n if (qCurrentTick < qStrikeTick - halfWidthTick || qCurrentTick > qStrikeTick + halfWidthTick) {\n return 0n\n }\n\n // Position size with sign: gamma uses inverted multiplier (long = positive, short = negative)\n const m = leg.isLong ? positionSize * leg.optionRatio : -(positionSize * leg.optionRatio)\n\n // sqrt(K * P * r) using tick addition: sqrt(K*P*r) = sqrt(1.0001^(K_tick + P_tick + r_tick))\n const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick) // X96 scale\n\n // r = 1.0001^(halfWidthTick), compute as (sqrtR)^2 to maintain precision\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96 scale\n const rX192 = sqrtR * sqrtR // X192 scale: r * 2^192\n\n // gamma = m * sqrt(K*P*r) / (2 * (r - 1))\n // = m * (sqrtKPR / 2^96) / (2 * (rX192/2^192 - 1))\n // = m * sqrtKPR * 2^192 / (2^96 * 2 * (rX192 - 2^192))\n // = m * sqrtKPR * 2^96 / (2 * (rX192 - 2^192))\n const numerator = m * sqrtKPR * Q96 // [asset] * [numeraire/asset * 2^96] * 2^96 = [numeraire * 2^192]\n const denominator = 2n * (rX192 - Q192) // 2 * (r - 1) in X192 scale\n\n return divTrunc(numerator, denominator) // [numeraire]\n}\n\n// --- Position-Level Aggregates ---\n\n/**\n * Parameters for position-level greek calculations.\n */\nexport interface PositionGreeksInput {\n /** Position legs */\n legs: TokenIdLeg[]\n /** Current pool tick */\n currentTick: bigint\n /** Tick at position mint */\n mintTick: bigint\n /** Position size in asset token smallest units */\n positionSize: bigint\n /** Pool tick spacing */\n poolTickSpacing: bigint\n /** Optional override for leg.asset on all legs (0n = token0 is asset, 1n = token1) */\n assetIndex?: bigint\n /**\n * How width=0 (loan/credit) legs were opened. When provided, `calculatePositionValue`\n * returns the NET user-experienced payoff for those legs (Zap = ±1 line, Cover = flat)\n * instead of the debt-only value. Leave undefined for delta/greeks aggregation, which\n * accounts for the held collateral separately.\n */\n swapAtMint?: boolean\n}\n\n/**\n * Calculate total value across all legs.\n */\nexport function calculatePositionValue(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const definedRisk = isDefinedRisk(legs)\n\n // Fast path: without swapAtMint there is no width=0 net-payoff (delta/greeks aggregation),\n // so no ITM netting is needed — value each leg independently.\n if (swapAtMint === undefined) {\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n ),\n 0n,\n )\n }\n\n // Pass 1: accumulate each option leg's mint-time ITM into a per-side notional pool. Under\n // swapAtMint the ITM was zapped into the other token, so a width=0 credit/loan that was\n // created to neutralize it (see getLegNetValueWidth0) should net against this pool instead\n // of adding a duplicate swap line. Puts contribute numeraire ITM; calls contribute asset ITM.\n let numeraireItmPool = 0n\n let assetItmPool = 0n\n for (const leg of legs) {\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n if (leg.width === 0n || halfWidthTick === 0n) continue // not a valued option leg\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n if (isPut) numeraireItmPool += itm\n else assetItmPool += itm\n }\n\n // Pass 2: sum leg values, netting width=0 legs against the matching ITM pool (consumed once).\n let sum = 0n\n for (const leg of legs) {\n if (leg.width === 0n) {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n const offset = borrowsAsset ? assetItmPool : numeraireItmPool\n if (borrowsAsset) assetItmPool = 0n\n else numeraireItmPool = 0n\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n sum += getLegNetValueWidth0(\n leg,\n m,\n qCurrentTick,\n qMintTick,\n isAssetToken0,\n swapAtMint,\n offset,\n )\n } else {\n sum += getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n )\n }\n }\n return sum\n}\n\n/**\n * Calculate total delta across all legs.\n */\nexport function calculatePositionDelta(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate debt-only position delta in a single target asset frame.\n *\n * Option legs are first valued in their natural `leg.asset` frame, then\n * converted into `assetIndex` using the current pool price. Width-zero legs\n * are evaluated directly in the target frame.\n *\n * Width=0 loan/credit legs include only their debt obligation. The held-token\n * side must be added separately from account collateral balances, preventing a\n * zap from being counted once in the position and again in collateral.\n */\nexport function calculatePositionDeltaDebtOnly(\n input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDeltaInVaultFrame(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate total gamma across all legs.\n */\nexport function calculatePositionGamma(input: PositionGreeksInput): bigint {\n const { legs, currentTick, positionSize, poolTickSpacing, assetIndex } = input\n\n return legs.reduce(\n (sum, leg) => sum + getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex),\n 0n,\n )\n}\n\n/**\n * Position greeks result.\n */\nexport interface PositionGreeksResult {\n /** Position value in numeraire token smallest units */\n value: bigint\n /** Position delta in asset token smallest units */\n delta: bigint\n /** Position gamma in numeraire token smallest units */\n gamma: bigint\n}\n\n/**\n * Calculate all greeks for a position.\n */\nexport function calculatePositionGreeks(input: PositionGreeksInput): PositionGreeksResult {\n return {\n value: calculatePositionValue(input),\n delta: calculatePositionDelta(input),\n gamma: calculatePositionGamma(input),\n }\n}\n\n// --- Portfolio (Multi-Position) Aggregates ---\n\n/**\n * Aggregate value across multiple independent positions.\n *\n * Each entry is valued with its OWN `positionSize`, `mintTick`, and legs, then\n * summed. Do NOT collapse multiple positions into one synthetic `PositionGreeksInput`\n * with a shared `positionSize` — `m = positionSize * optionRatio` is per-position, so a\n * shared size double-counts (and integer `optionRatio` cannot encode fractional shares).\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total value in numeraire token smallest units\n */\nexport function calculatePortfolioValue(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionValue(input), 0n)\n}\n\n/**\n * Aggregate delta across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePortfolioDelta(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionDelta(input), 0n)\n}\n\n/**\n * Aggregate gamma across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total gamma in numeraire token smallest units\n */\nexport function calculatePortfolioGamma(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionGamma(input), 0n)\n}\n\n/**\n * Calculate all greeks aggregated across multiple independent positions.\n */\nexport function calculatePortfolioGreeks(positions: PositionGreeksInput[]): PositionGreeksResult {\n return {\n value: calculatePortfolioValue(positions),\n delta: calculatePortfolioDelta(positions),\n gamma: calculatePortfolioGamma(positions),\n }\n}\n\n// --- Loan/Credit Swap-Aware Delta ---\n\n/**\n * Calculate the effective delta of a loan leg accounting for swapAtMint.\n *\n * A loan borrows one token and (optionally) swaps it for the other at mint.\n * The net delta depends on whether the swap occurred:\n *\n * | Scenario | Result |\n * |-----------------------|-------------------------------------------------|\n * | No swap | 0n (hold what you owe, net zero) |\n * | Swap + borrows asset | -m (hold numeraire, owe asset → short exposure) |\n * | Swap + borrows numer. | +m (hold asset, owe numeraire → long exposure) |\n *\n * Only meaningful for legs with `width === 0n`. For options, use `getLegDelta`.\n *\n * @param leg - The loan leg\n * @param positionSize - Position size in asset token smallest units\n * @param swapAtMint - Whether the borrowed tokens were swapped at mint\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset)\n * @returns Effective delta in asset token smallest units\n */\nexport function getLoanEffectiveDelta(\n leg: TokenIdLeg,\n positionSize: bigint,\n swapAtMint: boolean,\n assetIndex?: bigint,\n): bigint {\n if (!swapAtMint) return 0n\n\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n\n return borrowsAsset ? -m : m\n}\n\n/**\n * Calculate total delta for a position, using swap-aware delta for loan legs.\n *\n * For legs with `width === 0n` (loans/credits), uses `getLoanEffectiveDelta`\n * which accounts for the swapAtMint flag. For option legs (`width > 0n`),\n * uses the standard `getLegDelta`.\n *\n * @param input - Position greeks input plus swapAtMint flag\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePositionDeltaWithSwap(\n input: PositionGreeksInput & { swapAtMint: boolean },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const optionLegs = legs.filter((l) => l.width !== 0n)\n const definedRisk = isDefinedRisk(optionLegs)\n\n return legs.reduce((sum, leg) => {\n if (leg.width === 0n) {\n return sum + getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex)\n }\n return (\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n )\n )\n }, 0n)\n}\n","/**\n * TokenId constants for the Panoptic v2 SDK.\n * @module v2/tokenId/constants\n */\n\n/**\n * Default vegoid value used in pool ID encoding.\n */\nexport const DEFAULT_VEGOID = 8n\n\n/**\n * Default MAX_SPREAD value (90_000 = 9 * 10_000).\n * On-chain: removed/net ratio cap, in units of 1/10_000.\n */\nexport const DEFAULT_MAX_SPREAD = 90_000n\n\n/**\n * Standard tick widths matching DTE gamma profiles.\n *\n * These represent the position width in ticks for each timescale.\n * Width = tickUpper - tickLower.\n */\nexport const STANDARD_TICK_WIDTHS = {\n /** 1-hour expiry profile (240 ticks) */\n '1H': 240n,\n /** 1-day expiry profile (720 ticks) */\n '1D': 720n,\n /** 1-week expiry profile (2400 ticks) */\n '1W': 2400n,\n /** 1-month expiry profile (4800 ticks) */\n '1M': 4800n,\n /** 1-year expiry profile (15000 ticks) */\n '1Y': 15000n,\n} as const\n\n/**\n * Timescale key type for STANDARD_TICK_WIDTHS.\n */\nexport type Timescale = keyof typeof STANDARD_TICK_WIDTHS\n\n/**\n * Bit positions and sizes for TokenId encoding.\n */\nexport const TOKEN_ID_BITS = {\n /** Pool ID occupies bits 0-63 */\n POOL_ID_SIZE: 64n,\n /** Vegoid starts at bit 40 within pool ID */\n VEGOID_STARTING_BIT: 40n,\n /** Vegoid is 8 bits */\n VEGOID_SIZE: 8n,\n /** Tick spacing starts at bit 48 within pool ID */\n TICK_SPACING_STARTING_BIT: 48n,\n /** Tick spacing is 16 bits */\n TICK_SPACING_SIZE: 16n,\n /** Each leg is 48 bits */\n LEG_SIZE: 48n,\n /** Maximum number of legs per TokenId */\n MAX_LEGS: 4n,\n} as const\n\n/**\n * Bit positions within a leg (relative to leg start).\n */\nexport const LEG_BITS = {\n /** Asset bit position */\n ASSET_BIT: 0n,\n /** Asset size in bits */\n ASSET_SIZE: 1n,\n /** Option ratio starting bit */\n RATIO_BIT: 1n,\n /** Option ratio size in bits */\n RATIO_SIZE: 7n,\n /** Is long starting bit */\n IS_LONG_BIT: 8n,\n /** Is long size in bits */\n IS_LONG_SIZE: 1n,\n /** Token type starting bit */\n TOKEN_TYPE_BIT: 9n,\n /** Token type size in bits */\n TOKEN_TYPE_SIZE: 1n,\n /** Risk partner starting bit */\n RISK_PARTNER_BIT: 10n,\n /** Risk partner size in bits */\n RISK_PARTNER_SIZE: 2n,\n /** Strike starting bit */\n STRIKE_BIT: 12n,\n /** Strike size in bits (24 bits, signed int24) */\n STRIKE_SIZE: 24n,\n /** Width starting bit */\n WIDTH_BIT: 36n,\n /** Width size in bits */\n WIDTH_SIZE: 12n,\n} as const\n\n/**\n * Masks for extracting/encoding leg fields.\n */\nexport const LEG_MASKS = {\n /** Mask for asset (1 bit) */\n ASSET: (1n << LEG_BITS.ASSET_SIZE) - 1n,\n /** Mask for option ratio (7 bits) */\n RATIO: (1n << LEG_BITS.RATIO_SIZE) - 1n,\n /** Mask for is long (1 bit) */\n IS_LONG: (1n << LEG_BITS.IS_LONG_SIZE) - 1n,\n /** Mask for token type (1 bit) */\n TOKEN_TYPE: (1n << LEG_BITS.TOKEN_TYPE_SIZE) - 1n,\n /** Mask for risk partner (2 bits) */\n RISK_PARTNER: (1n << LEG_BITS.RISK_PARTNER_SIZE) - 1n,\n /** Mask for strike (24 bits) */\n STRIKE: (1n << LEG_BITS.STRIKE_SIZE) - 1n,\n /** Mask for width (12 bits) */\n WIDTH: (1n << LEG_BITS.WIDTH_SIZE) - 1n,\n /** Mask for entire leg (48 bits) */\n LEG: (1n << TOKEN_ID_BITS.LEG_SIZE) - 1n,\n} as const\n\n/**\n * Maximum and minimum values for leg fields.\n */\nexport const LEG_LIMITS = {\n /** Maximum option ratio (127) */\n MAX_RATIO: 127n,\n /** Maximum width (4095) */\n MAX_WIDTH: 4095n,\n /** Maximum strike (8388607, max int24 positive) */\n MAX_STRIKE: 8388607n,\n /** Minimum strike (-8388608, min int24) */\n MIN_STRIKE: -8388608n,\n} as const\n\n/**\n * Value used to convert negative strike to unsigned representation.\n * Strike is stored as int24, so we use 2^24 for conversion.\n */\nexport const STRIKE_CONVERSION_FACTOR = 16777216n\n","import type { Address, Hex } from 'viem'\n\nimport { DEFAULT_VEGOID } from '../tokenId/constants'\n\nexport const vegoid = Number(DEFAULT_VEGOID)\n\nexport interface LegParams {\n index: number\n width: bigint\n optionRatio: bigint\n asset: bigint\n strike: bigint\n isLong: bigint // 0 if short, 1 if long\n tokenType: bigint // Which token (0|1 in underlying pool) is being moved\n riskPartner: bigint\n}\n\nexport const areLegsEqual = (leg1: LegParams, leg2: LegParams): boolean => {\n return (\n leg1.width === leg2.width &&\n leg1.optionRatio === leg2.optionRatio &&\n leg1.asset === leg2.asset &&\n leg1.strike === leg2.strike &&\n leg1.isLong === leg2.isLong &&\n leg1.tokenType === leg2.tokenType &&\n leg1.riskPartner === leg2.riskPartner\n )\n}\n\nexport const stringifyLeg = (leg: LegParams): string => {\n return `Index: ${leg.index} | Width: ${leg.width.toString()} | OptionRatio: ${leg.optionRatio.toString()} | Asset: ${leg.asset.toString()} | Strike: ${leg.strike.toString()} | IsLong?: ${leg.isLong.toString()} | Token Type: ${leg.tokenType.toString()} | Risk Partner: ${leg.riskPartner.toString()}`\n}\n\n// Synthetic TokenIds padding constant\nexport const SYNTH_TOKENID_PADDING = BigInt(\n '115792089237316195423570985007226406215939081747436879206741300988257197096960',\n)\n\nconst POOL_ID_SIZE = 64n\nconst VEGOID_STARTING_BIT = 40n\nconst VEGOID_SIZE = 8n\nconst TICK_SPACING_STARTING_BIT = 48n\nconst ASSET_STARTING_BIT = 0n\nconst ASSET_SIZE = 1n\nconst RATIO_STARTING_BIT = ASSET_STARTING_BIT + ASSET_SIZE // 0 + 1\nconst RATIO_SIZE = 7n\nconst IS_LONG_STARTING_BIT = RATIO_STARTING_BIT + RATIO_SIZE // 1 + 7\nconst IS_LONG_SIZE = 1n\nconst TOKEN_TYPE_STARTING_BIT = IS_LONG_STARTING_BIT + IS_LONG_SIZE // 8 + 1\nconst TOKEN_TYPE_SIZE = 1n\nconst RISK_PARTNER_STARTING_BIT = TOKEN_TYPE_STARTING_BIT + TOKEN_TYPE_SIZE // 9 + 1\nconst RISK_PARTNER_SIZE = 2n\nconst STRIKE_STARTING_BIT = RISK_PARTNER_STARTING_BIT + RISK_PARTNER_SIZE // 10 + 2\nconst STRIKE_SIZE = 24n\nconst WIDTH_STARTING_BIT = STRIKE_STARTING_BIT + STRIKE_SIZE // 12 + 24\nconst WIDTH_SIZE = 12n\nconst LEG_SIZE = WIDTH_STARTING_BIT + WIDTH_SIZE // 36 + 12 = 48\n\n// converts unsigned strike to signed for encoding\nexport const convertStrike = (n: bigint): bigint => {\n if (n < 0n) {\n // 3 bytes because strike is int24\n return 16777216n + n\n } else {\n return n\n }\n}\n\n// converts encoded (unsigned) strike back to signed\nexport const signStrike = (encodedStrike: bigint): bigint => {\n if (encodedStrike > 2n ** 23n) {\n return encodedStrike - 16777216n\n }\n return encodedStrike\n}\n\nconst getLegOffsetByIndex = (index: bigint): bigint => index * LEG_SIZE\n\nconst encodeAsset = (asset: bigint, legIndex: bigint): bigint =>\n asset << (getLegOffsetByIndex(legIndex) + ASSET_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeRatio = (optionRatio: bigint, legIndex: bigint): bigint =>\n optionRatio << (getLegOffsetByIndex(legIndex) + RATIO_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeIsLong = (isLong: bigint, legIndex: bigint): bigint =>\n isLong << (getLegOffsetByIndex(legIndex) + IS_LONG_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeTokenType = (tokenType: bigint, legIndex: bigint): bigint =>\n tokenType << (getLegOffsetByIndex(legIndex) + TOKEN_TYPE_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeRiskPartner = (riskPartner: bigint, legIndex: bigint): bigint =>\n riskPartner << (getLegOffsetByIndex(legIndex) + RISK_PARTNER_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeStrike = (strike: bigint, legIndex: bigint): bigint =>\n convertStrike(strike) << (getLegOffsetByIndex(legIndex) + STRIKE_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeWidth = (width: bigint, legIndex: bigint): bigint =>\n width << (getLegOffsetByIndex(legIndex) + WIDTH_STARTING_BIT + POOL_ID_SIZE)\n\nconst decodeAsset = (leg: bigint): bigint => leg % (1n << ASSET_SIZE)\n\nconst decodeRatio = (leg: bigint): bigint => (leg >> RATIO_STARTING_BIT) % (1n << RATIO_SIZE)\n\nconst decodeIsLong = (leg: bigint): bigint => (leg >> IS_LONG_STARTING_BIT) % (1n << IS_LONG_SIZE)\n\nconst decodeTokenType = (leg: bigint): bigint =>\n (leg >> TOKEN_TYPE_STARTING_BIT) % (1n << TOKEN_TYPE_SIZE)\n\nconst decodeRiskPartner = (leg: bigint): bigint =>\n (leg >> RISK_PARTNER_STARTING_BIT) % (1n << RISK_PARTNER_SIZE)\n\nconst decodeStrike = (leg: bigint): bigint =>\n signStrike((leg >> STRIKE_STARTING_BIT) % (1n << STRIKE_SIZE))\n\nconst decodeWidth = (leg: bigint): bigint => (leg >> WIDTH_STARTING_BIT) % (1n << WIDTH_SIZE)\n\n/**\n * Extract vegoid from a TokenId\n * Vegoid is stored in bits 40-47 (8 bits) of the poolId\n */\nexport const decodeVegoid = (tokenId: bigint): bigint => {\n return ((tokenId % (1n << POOL_ID_SIZE)) >> VEGOID_STARTING_BIT) % (1n << VEGOID_SIZE)\n}\n\n/**\n * Extract vegoid from a poolId\n * Vegoid is stored in bits 40-47 (8 bits) of the poolId\n */\nexport const decodeVegoidFromPoolId = (poolId: bigint): bigint => {\n return (poolId >> VEGOID_STARTING_BIT) % (1n << VEGOID_SIZE)\n}\n\n/**\n * Extract tickSpacing from a TokenId\n * TickSpacing is stored in bits 48-63 (16 bits) of the poolId\n */\nexport const decodeTickSpacing = (tokenId: bigint): bigint => {\n return (tokenId % (1n << POOL_ID_SIZE)) >> TICK_SPACING_STARTING_BIT\n}\n\n/**\n * Encode poolId with vegoid support\n * The encoded PoolId structure: [16-bit tickSpacing][8-bit vegoid][40-bit pool address]\n * @param address The Uniswap V3 pool address (hex string)\n * @param tickSpacing The tick spacing of the pool\n * @param vegoidValue The vegoid value (defaults to 4 if not provided)\n * @return The encoded poolId as bigint\n */\nexport const encodePoolId = (\n address: Address,\n tickSpacing: bigint,\n vegoidValue: bigint = BigInt(vegoid),\n): bigint => {\n // Remove 0x prefix and get first 10 hex chars (5 bytes = 40 bits)\n const addressHex = address.slice(2, 12).toLowerCase()\n\n // Convert to bytes array (big-endian), then reverse to little-endian\n const bytes: number[] = []\n for (let i = 0; i < 10; i += 2) {\n bytes.push(parseInt(addressHex.slice(i, i + 2), 16))\n }\n bytes.reverse()\n\n // Build poolId: pool address (5 bytes) + vegoid (1 byte) + tickSpacing (2 bytes) = 8 bytes\n // All in little-endian format\n let poolId = 0n\n for (let i = 0; i < bytes.length; i++) {\n poolId |= BigInt(bytes[i]) << BigInt(i * 8)\n }\n\n // Add vegoid at bit 40\n poolId |= (vegoidValue % 256n) << 40n\n\n // Add tickSpacing at bit 48\n poolId |= (tickSpacing % 65536n) << 48n\n\n return poolId\n}\n\n/**\n * Encode V4 poolId with vegoid support\n * The encoded PoolId structure: [16-bit tickSpacing][8-bit vegoid][40-bit pool pattern]\n * @param poolId The V4 pool ID (bytes32 hex string)\n * @param tickSpacing The tick spacing of the pool\n * @param vegoidValue The vegoid value (defaults to 4 if not provided)\n * @return The encoded poolId as bigint\n */\nexport const encodeV4PoolId = (\n poolId: Hex,\n tickSpacing: bigint,\n vegoidValue: bigint = BigInt(vegoid),\n): bigint => {\n // Remove 0x prefix and get last 10 hex chars (5 bytes = 40 bits)\n const poolIdHex = poolId.slice(2)\n const last5BytesHex = poolIdHex.slice(-10).toLowerCase()\n\n // Convert to bytes array (big-endian), then reverse to little-endian\n const bytes: number[] = []\n for (let i = 0; i < 10; i += 2) {\n bytes.push(parseInt(last5BytesHex.slice(i, i + 2), 16))\n }\n bytes.reverse()\n\n // Build encoded poolId: pool pattern (5 bytes) + vegoid (1 byte) + tickSpacing (2 bytes) = 8 bytes\n let encodedPoolId = 0n\n for (let i = 0; i < bytes.length; i++) {\n encodedPoolId |= BigInt(bytes[i]) << BigInt(i * 8)\n }\n\n // Add vegoid at bit 40\n encodedPoolId |= (vegoidValue % 256n) << 40n\n\n // Add tickSpacing at bit 48\n encodedPoolId |= (tickSpacing % 65536n) << 48n\n\n return encodedPoolId\n}\n\n// Can be (ab)used to create a leg id by passing in a tokenId of 0\nexport const addLeg = (tokenId: bigint, leg: LegParams): bigint => {\n const legIndex = BigInt(leg.index)\n const width = leg.width\n const strike = leg.strike\n const riskPartner = leg.riskPartner\n const tokenType = leg.tokenType\n const isLong = leg.isLong\n const optionRatio = leg.optionRatio\n const asset = leg.asset\n\n return (\n tokenId +\n encodeWidth(width, legIndex) +\n encodeStrike(strike, legIndex) +\n (encodeRiskPartner(riskPartner, legIndex) |\n encodeTokenType(tokenType, legIndex) |\n encodeIsLong(isLong, legIndex) |\n encodeRatio(optionRatio, legIndex) |\n encodeAsset(asset, legIndex))\n )\n}\n\nexport const encodePosition = (poolId: bigint, legs: LegParams[]): bigint => {\n return legs.reduce((acc, leg) => addLeg(acc, leg), poolId)\n}\n\nexport interface Position {\n poolId: string\n legs: LegParams[]\n}\n\nexport const decodePosition = (encodedPosition: bigint): Position => {\n const leg4 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(3n))) % (1n << LEG_SIZE)\n\n const leg3 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(2n))) % (1n << LEG_SIZE)\n\n const leg2 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(1n))) % (1n << LEG_SIZE)\n\n const leg1 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(0n))) % (1n << LEG_SIZE)\n\n let poolId = (encodedPosition % (1n << POOL_ID_SIZE)).toString(16)\n\n const poolIdLength = 16 // poolId is 64 bits => 16 hex characters\n if (poolId.length < poolIdLength) {\n poolId = padHexWithZeros('0x' + poolId, poolIdLength + 2) // +2 for 0x prefix\n } else {\n poolId = '0x' + poolId\n }\n\n const encodedLegs = [leg1, leg2, leg3, leg4].filter((leg) => decodeRatio(leg) > 0n)\n\n const legs: LegParams[] = encodedLegs.map((leg, index) => ({\n index: index,\n width: decodeWidth(leg),\n strike: decodeStrike(leg),\n riskPartner: decodeRiskPartner(leg),\n tokenType: decodeTokenType(leg),\n isLong: decodeIsLong(leg),\n optionRatio: decodeRatio(leg),\n asset: decodeAsset(leg),\n }))\n\n return {\n poolId,\n legs,\n }\n}\n\nexport function padHexWithZeros(hex: string, length: number): string {\n // Check if the hex starts with \"0x\"\n if (hex.startsWith('0x')) {\n // Remove the \"0x\" prefix\n hex = hex.substring(2)\n } else {\n throw new Error('do not use padHexWithZeros on non-hex strings')\n }\n\n // Subtract 2 from length to account for the substring(2) call to remove the leading 0x\n while (hex.length < length - 2) {\n hex = '0' + hex\n }\n\n // Add back the \"0x\" prefix\n return '0x' + hex\n}\n","/**\n * Event reconstruction for full position history scan.\n * @module v2/sync/eventReconstruction\n */\n\nimport type { Address, Hash, PublicClient } from 'viem'\nimport { getAbiItem } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\nimport type { SyncEvent } from '../types'\n\ntype EventReconstructionClient = Pick<PublicClient, 'getBlock' | 'getLogs'>\n\n/**\n * Parameters for event reconstruction.\n */\nexport interface EventReconstructionParams {\n /** viem public client */\n client: EventReconstructionClient\n /** Pool address */\n poolAddress: Address\n /** Account to reconstruct positions for */\n account: Address\n /** Starting block for event scan */\n fromBlock: bigint\n /** Ending block for event scan */\n toBlock: bigint\n /** Batch size for log queries (default: 10000) */\n batchSize?: bigint\n /** Progress callback */\n onProgress?: (event: SyncEvent) => void\n}\n\n/**\n * Event reconstruction result.\n */\nexport interface EventReconstructionResult {\n /** Position IDs that are currently open */\n openPositions: bigint[]\n /** Position IDs that have been closed */\n closedPositions: bigint[]\n /** Number of blocks scanned */\n blocksScanned: bigint\n /** Last scanned block number */\n lastBlock: bigint\n /** Last scanned block hash */\n lastBlockHash: Hash\n}\n\n/**\n * Mint event from reconstruction.\n */\ninterface MintEvent {\n tokenId: bigint\n positionSize: bigint\n blockNumber: bigint\n blockHash: Hash\n transactionHash: Hash\n logIndex: number\n}\n\n/**\n * Burn event from reconstruction.\n */\ninterface BurnEvent {\n tokenId: bigint\n positionSize: bigint\n blockNumber: bigint\n blockHash: Hash\n transactionHash: Hash\n logIndex: number\n}\n\n/**\n * Reconstruct position history from events.\n * This is the fallback method when snapshot recovery fails.\n * It scans all OptionMinted and OptionBurnt events to build the position set.\n *\n * @param params - Reconstruction parameters\n * @returns Reconstruction result with open and closed positions\n */\nexport async function reconstructFromEvents(\n params: EventReconstructionParams,\n): Promise<EventReconstructionResult> {\n const {\n client,\n poolAddress,\n account,\n fromBlock,\n toBlock,\n batchSize = 10000n,\n onProgress,\n } = params\n\n const mintEvents: MintEvent[] = []\n const burnEvents: BurnEvent[] = []\n const totalBlocks = toBlock - fromBlock + 1n\n const safeBatchSize = batchSize > 0n ? batchSize : 10000n\n\n const scanRange = async (rangeFromBlock: bigint, rangeToBlock: bigint) => {\n const [mints, burns] = await Promise.all([\n client.getLogs({\n address: poolAddress,\n event: OPTION_MINTED_EVENT,\n args: { recipient: account },\n fromBlock: rangeFromBlock,\n toBlock: rangeToBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: OPTION_BURNT_EVENT,\n args: { recipient: account },\n fromBlock: rangeFromBlock,\n toBlock: rangeToBlock,\n }),\n ])\n\n // Process mint events\n for (const mint of mints) {\n // Decode position size from balanceData (first 128 bits)\n const balanceData = mint.args.balanceData as bigint\n const positionSize = balanceData & ((1n << 128n) - 1n)\n\n mintEvents.push({\n tokenId: mint.args.tokenId as bigint,\n positionSize,\n blockNumber: mint.blockNumber,\n blockHash: mint.blockHash,\n transactionHash: mint.transactionHash,\n logIndex: mint.logIndex,\n })\n }\n\n // Process burn events\n for (const burn of burns) {\n burnEvents.push({\n tokenId: burn.args.tokenId as bigint,\n positionSize: burn.args.positionSize as bigint,\n blockNumber: burn.blockNumber,\n blockHash: burn.blockHash,\n transactionHash: burn.transactionHash,\n logIndex: burn.logIndex,\n })\n }\n\n const blocksProcessed = rangeToBlock - fromBlock + 1n\n const progress = totalBlocks > 0n ? (blocksProcessed * 100n) / totalBlocks : 100n\n onProgress?.({\n currentBlock: rangeToBlock,\n targetBlock: toBlock,\n positionsFound: BigInt(mintEvents.length),\n progress: progress > 100n ? 100n : progress,\n })\n }\n\n // Account and pool topics make this query selective enough for providers that\n // permit wide eth_getLogs ranges. This keeps the fallback practical on mainnet.\n // Providers with an explicit range cap fall back to bounded requests.\n try {\n await scanRange(fromBlock, toBlock)\n } catch (error) {\n if (!isRangeLimitError(error)) throw error\n\n let currentBlock = fromBlock\n while (currentBlock <= toBlock) {\n const endBlock =\n currentBlock + safeBatchSize - 1n > toBlock ? toBlock : currentBlock + safeBatchSize - 1n\n await scanRange(currentBlock, endBlock)\n currentBlock = endBlock + 1n\n }\n }\n\n // Build position map: tokenId -> net position size\n const positionMap = new Map<bigint, bigint>()\n\n // Sort all events by block and log index\n const allEvents = [\n ...mintEvents.map((e) => ({ ...e, type: 'mint' as const })),\n ...burnEvents.map((e) => ({ ...e, type: 'burn' as const })),\n ].sort((a, b) => {\n const blockDiff = Number(a.blockNumber - b.blockNumber)\n if (blockDiff !== 0) return blockDiff\n return a.logIndex - b.logIndex\n })\n\n // Process events in order\n for (const event of allEvents) {\n const current = positionMap.get(event.tokenId) ?? 0n\n\n if (event.type === 'mint') {\n positionMap.set(event.tokenId, current + event.positionSize)\n } else {\n positionMap.set(event.tokenId, current - event.positionSize)\n }\n }\n\n // Separate open and closed positions\n const openPositions: bigint[] = []\n const closedPositions: bigint[] = []\n\n for (const [tokenId, size] of positionMap) {\n if (size > 0n) {\n openPositions.push(tokenId)\n } else {\n closedPositions.push(tokenId)\n }\n }\n\n // Get the last block hash\n const lastBlock = await client.getBlock({ blockNumber: toBlock })\n\n return {\n openPositions,\n closedPositions,\n blocksScanned: toBlock - fromBlock + 1n,\n lastBlock: toBlock,\n lastBlockHash: lastBlock.hash,\n }\n}\n\nconst OPTION_MINTED_EVENT = getAbiItem({ abi: panopticPoolV2Abi, name: 'OptionMinted' })\nconst OPTION_BURNT_EVENT = getAbiItem({ abi: panopticPoolV2Abi, name: 'OptionBurnt' })\n\nfunction isRangeLimitError(error: unknown): boolean {\n const messages: string[] = []\n let current: unknown = error\n for (let depth = 0; current && typeof current === 'object' && depth < 5; depth += 1) {\n if ('message' in current && typeof current.message === 'string') {\n messages.push(current.message)\n }\n if ('details' in current && typeof current.details === 'string') {\n messages.push(current.details)\n }\n current = 'cause' in current ? current.cause : undefined\n }\n if (typeof error === 'string') messages.push(error)\n\n const message = messages.join(' ').toLowerCase()\n return (\n message.includes('block range') ||\n message.includes('range is too large') ||\n message.includes('range too large') ||\n message.includes('query returned more than') ||\n message.includes('too many results') ||\n message.includes('log response size exceeded') ||\n message.includes('exceeds the limit') ||\n (message.includes('range') && message.includes('limit'))\n )\n}\n\n/**\n * Get the deployment block for a pool.\n * This searches for the first PoolInitialized event.\n *\n * @param client - viem public client\n * @param poolAddress - Pool address\n * @returns Deployment block number or null if not found\n */\nexport async function getPoolDeploymentBlock(\n client: PublicClient,\n poolAddress: Address,\n): Promise<bigint | null> {\n // Search for the first event from this pool\n // We use a binary search approach to find the deployment block\n\n const currentBlock = await client.getBlockNumber()\n let low = 0n\n let high = currentBlock\n let foundBlock: bigint | null = null\n\n // Binary search with scan windows to find the deployment block.\n // Each iteration checks [mid, mid + scanRange] for logs.\n const scanRange = 10000n\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const rangeEnd = mid + scanRange > high ? high : mid + scanRange\n\n try {\n const logs = await client.getLogs({\n address: poolAddress,\n fromBlock: mid,\n toBlock: rangeEnd,\n })\n\n if (logs.length > 0) {\n // Found logs — record earliest and search before it\n const earliest = logs[0].blockNumber\n if (foundBlock === null || earliest < foundBlock) {\n foundBlock = earliest\n }\n high = earliest - 1n\n } else {\n // No logs in [mid, rangeEnd] — skip the entire checked range\n low = rangeEnd + 1n\n }\n } catch {\n // Range too large for RPC — halve the search space\n high = mid + (rangeEnd - mid) / 2n\n }\n }\n\n return foundBlock\n}\n","/**\n * Read current on-chain positionSize for a list of tokenIds.\n *\n * PanopticPool.dispatch() treats `positionSizes[i] == storedSize` as a\n * settlePremium self-call and any mismatch (including 0) as a burn. Callers\n * that want to trigger settle without changing size must pass the CURRENT\n * stored size for each held tokenId — hence this helper.\n *\n * @module v2/reads/positionSizes\n */\n\nimport type { Address, PublicClient } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\n\nconst BIT_MASK_128 = (1n << 128n) - 1n\n\nexport interface GetCurrentPositionSizesParams {\n client: PublicClient\n poolAddress: Address\n account: Address\n positionIdList: bigint[]\n blockNumber?: bigint\n}\n\n/**\n * Returns the current stored positionSize for each tokenId, in the same order\n * as the input `positionIdList`. Reverts (via the contract) if any tokenId is\n * not held by `account`.\n */\nexport async function getCurrentPositionSizes(\n params: GetCurrentPositionSizesParams,\n): Promise<bigint[]> {\n const { client, poolAddress, account, positionIdList, blockNumber } = params\n\n if (positionIdList.length === 0) return []\n\n const [, , positionBalances] = await client.readContract({\n address: poolAddress,\n abi: panopticPoolV2Abi,\n functionName: 'getFullPositionsData',\n args: [account, false, positionIdList],\n blockNumber,\n })\n\n return positionBalances.map((packed) => packed & BIT_MASK_128)\n}\n","/**\n * Token flow simulation utility using PanopticPool.multicall.\n *\n * Uses getAssetsOf-dispatch-getAssetsOf pattern within a single eth_call\n * to measure exact collateral asset movements from any dispatch call.\n *\n * @module v2/simulations/tokenFlow\n */\n\nimport {\n type Address,\n type Hex,\n type PublicClient,\n decodeFunctionResult,\n encodeFunctionData,\n} from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\nimport { panopticErrorsAbi } from '../errors/errorsAbi'\n\n/**\n * PanopticPool getAssetsOf ABI.\n * Returns collateral assets (shares converted to underlying) for an account.\n */\nconst getAssetsOfAbi = [\n {\n type: 'function',\n name: 'getAssetsOf',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [\n { name: 'assets0', type: 'uint256' },\n { name: 'assets1', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n] as const\n\n/**\n * PanopticPool multicall ABI (inherited from Uniswap).\n * Uses delegatecall, preserving msg.sender throughout the chain.\n */\nconst multicallAbi = [\n {\n type: 'function',\n name: 'multicall',\n inputs: [{ name: 'data', type: 'bytes[]' }],\n outputs: [{ name: 'results', type: 'bytes[]' }],\n stateMutability: 'nonpayable',\n },\n // Include error definitions so viem can decode revert data with full args\n ...panopticErrorsAbi,\n] as const\n\n/**\n * Token flow result from simulation.\n * Measures collateral asset changes via getAssetsOf-dispatch-getAssetsOf pattern.\n */\nexport interface TokenFlow {\n /** Token 0 collateral change (negative = user deposits, positive = user receives) */\n delta0: bigint\n /** Token 1 collateral change (negative = user deposits, positive = user receives) */\n delta1: bigint\n /** Collateral assets in token 0 before the call */\n balanceBefore0: bigint\n /** Collateral assets in token 1 before the call */\n balanceBefore1: bigint\n /** Collateral assets in token 0 after the call */\n balanceAfter0: bigint\n /** Collateral assets in token 1 after the call */\n balanceAfter1: bigint\n /** Pool tick before the operation */\n tickBefore: bigint | null\n /** Pool tick after the operation */\n tickAfter: bigint | null\n}\n\n/**\n * Parameters for simulateWithTokenFlow.\n */\nexport interface SimulateWithTokenFlowParams {\n /** viem public client */\n client: PublicClient\n /** PanopticPool address */\n poolAddress: Address\n /** User address whose collateral changes we're measuring */\n user: Address\n /** Encoded call data (typically dispatch) */\n callData: Hex\n /** Optional block number for simulation */\n blockNumber?: bigint\n /**\n * Optional additional encoded calls to append after the 5-call pattern.\n * These execute post-dispatch within the same multicall (same state).\n * Raw encoded bytes are returned in `postCallResults`.\n */\n postCallData?: Hex[]\n /**\n * Optional additional encoded calls to insert between the pre-dispatch\n * `getAssetsOf` / `getCurrentTick` and the target call. These execute\n * pre-dispatch within the same multicall — useful for reading per-position\n * data (e.g. `getFullPositionsData`) against the original `positionIdList`\n * before state mutates. Raw encoded bytes are returned in `preCallResults`.\n */\n preCallData?: Hex[]\n}\n\n/**\n * Result of simulateWithTokenFlow.\n */\nexport interface SimulateWithTokenFlowResult {\n /** Whether the simulation succeeded */\n success: boolean\n /** Token flow data (only if success) */\n tokenFlow?: TokenFlow\n /** Error message (only if failed) */\n error?: string\n /** Raw error object preserving viem cause chain and revert data */\n rawError?: Error\n /** Gas estimate for the inner call */\n gasEstimate: bigint\n /** Raw results from postCallData entries (only if success and postCallData was provided) */\n postCallResults?: Hex[]\n /** Raw results from preCallData entries (only if success and preCallData was provided) */\n preCallResults?: Hex[]\n}\n\n/**\n * Simulate a contract call and measure token flow using PanopticPool.multicall.\n *\n * This function uses PanopticPool's inherited multicall (delegatecall-based) to chain:\n * 1. getAssetsOf(user) - read collateral assets before\n * 2. getCurrentTick() - read pool tick before\n * 3. Execute the target call (e.g., dispatch)\n * 4. getCurrentTick() - read pool tick after\n * 5. getAssetsOf(user) - read collateral assets after\n *\n * ## Why PanopticPool.multicall instead of Multicall3?\n * - Measures **collateral assets** (shares → underlying), not raw wallet balances\n * - Uses **delegatecall**, preserving msg.sender throughout the chain\n * - Single contract interaction with PanopticPool\n * - Correctly reflects what happens during position operations\n *\n * ## Same-Block Guarantee\n * All operations execute within a single eth_call, ensuring atomic consistency.\n *\n * @param params - Simulation parameters\n * @returns Token flow result\n *\n * @example\n * ```typescript\n * const callData = encodeFunctionData({\n * abi: panopticPoolV2Abi,\n * functionName: 'dispatch',\n * args: [positionIdList, finalPositionIdList, positionSizes, tickAndSpreadLimits, false, 0n],\n * })\n *\n * const result = await simulateWithTokenFlow({\n * client,\n * poolAddress,\n * user: userAddress,\n * callData,\n * })\n *\n * if (result.success) {\n * console.log('Token 0 change:', result.tokenFlow.delta0)\n * console.log('Token 1 change:', result.tokenFlow.delta1)\n * }\n * ```\n */\nexport async function simulateWithTokenFlow(\n params: SimulateWithTokenFlowParams,\n): Promise<SimulateWithTokenFlowResult> {\n const { client, poolAddress, user, callData, blockNumber, postCallData, preCallData } = params\n\n // Encode getAssetsOf call\n const getAssetsOfCallData = encodeFunctionData({\n abi: getAssetsOfAbi,\n functionName: 'getAssetsOf',\n args: [user],\n })\n\n // Encode getCurrentTick call\n const getCurrentTickCallData = encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'getCurrentTick',\n })\n\n const preLen = preCallData?.length ?? 0\n\n // Build multicall: [getAssetsOf, getCurrentTick, ...preCallData, targetCall, getCurrentTick, getAssetsOf, ...postCallData]\n const multicallData: Hex[] = [\n getAssetsOfCallData,\n getCurrentTickCallData,\n ...(preCallData ?? []),\n callData,\n getCurrentTickCallData,\n getAssetsOfCallData,\n ...(postCallData ?? []),\n ]\n\n try {\n // Execute via simulateContract on PanopticPool's multicall\n const { result } = await client.simulateContract({\n address: poolAddress,\n abi: multicallAbi,\n functionName: 'multicall',\n args: [multicallData],\n account: user,\n blockNumber,\n })\n\n // Decode getAssetsOf results\n const decodeAssets = (data: Hex): { assets0: bigint; assets1: bigint } => {\n const decoded = decodeFunctionResult({\n abi: getAssetsOfAbi,\n functionName: 'getAssetsOf',\n data,\n })\n return { assets0: decoded[0], assets1: decoded[1] }\n }\n\n // Decode getCurrentTick result (int24 decodes as number, convert to bigint)\n const decodeTick = (data: Hex): bigint => {\n return BigInt(\n decodeFunctionResult({\n abi: panopticPoolV2Abi,\n functionName: 'getCurrentTick',\n data,\n }),\n )\n }\n\n const assetsBefore = decodeAssets(result[0])\n const tickBefore = decodeTick(result[1])\n // result[2..2+preLen-1] are preCallData results\n // result[2+preLen] is the target call result (dispatch)\n const tickAfter = decodeTick(result[3 + preLen])\n const assetsAfter = decodeAssets(result[4 + preLen])\n\n const preCallResults = preLen > 0 ? (result.slice(2, 2 + preLen) as Hex[]) : undefined\n const postCallResults =\n postCallData && postCallData.length > 0 ? (result.slice(5 + preLen) as Hex[]) : undefined\n\n const delta0 = assetsAfter.assets0 - assetsBefore.assets0\n const delta1 = assetsAfter.assets1 - assetsBefore.assets1\n\n // Estimate gas for the target call directly\n let gasEstimate = 0n\n try {\n gasEstimate = await client.estimateGas({\n account: user,\n to: poolAddress,\n data: callData,\n blockNumber,\n })\n } catch {\n // Gas estimation may fail, use 0\n }\n\n return {\n success: true,\n tokenFlow: {\n delta0,\n delta1,\n balanceBefore0: assetsBefore.assets0,\n balanceBefore1: assetsBefore.assets1,\n balanceAfter0: assetsAfter.assets0,\n balanceAfter1: assetsAfter.assets1,\n tickBefore,\n tickAfter,\n },\n gasEstimate,\n postCallResults,\n preCallResults,\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Simulation failed',\n rawError: error instanceof Error ? error : undefined,\n gasEstimate: 0n,\n }\n }\n}\n\n/**\n * Parameters for getting pool tokens.\n */\nexport interface GetPoolTokensParams {\n /** viem public client */\n client: PublicClient\n /** Pool address */\n poolAddress: Address\n /** Optional block number */\n blockNumber?: bigint\n}\n\n/**\n * Pool token addresses result.\n */\nexport interface PoolTokens {\n /** Token 0 address */\n token0: Address\n /** Token 1 address */\n token1: Address\n /** Collateral tracker 0 address */\n collateralTracker0: Address\n /** Collateral tracker 1 address */\n collateralTracker1: Address\n}\n\n/**\n * Get pool token addresses for reference.\n *\n * @param params - Parameters\n * @returns Pool token addresses\n */\nexport async function getPoolTokensForSimulation(params: GetPoolTokensParams): Promise<PoolTokens> {\n const { client, poolAddress, blockNumber } = params\n\n // Minimal ABI for the calls we need\n const poolAbi = [\n {\n type: 'function',\n name: 'collateralToken0',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'collateralToken1',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n ] as const\n\n const collateralAbi = [\n {\n type: 'function',\n name: 'asset',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n ] as const\n\n // Get collateral tracker addresses\n const [ct0, ct1] = await client.multicall({\n contracts: [\n { address: poolAddress, abi: poolAbi, functionName: 'collateralToken0' },\n { address: poolAddress, abi: poolAbi, functionName: 'collateralToken1' },\n ],\n blockNumber,\n allowFailure: false,\n })\n\n // Get underlying token addresses from collateral trackers\n const [token0, token1] = await client.multicall({\n contracts: [\n { address: ct0, abi: collateralAbi, functionName: 'asset' },\n { address: ct1, abi: collateralAbi, functionName: 'asset' },\n ],\n blockNumber,\n allowFailure: false,\n })\n\n return {\n token0,\n token1,\n collateralTracker0: ct0,\n collateralTracker1: ct1,\n }\n}\n","/**\n * ERC20 approval to the CoW vault relayer.\n *\n * Single-step plain `approve` to GPv2VaultRelayer — CoW does not use Permit2.\n *\n * @module cow/approval\n */\n\nimport { erc20Abi, maxUint256 } from 'viem'\n\nimport type { TxResult } from '../panoptic/v2/types'\nimport { submitWrite } from '../panoptic/v2/writes'\nimport { COW_VAULT_RELAYER } from './addresses'\nimport type { ApproveErc20ForCowParams, CheckCowApprovalParams, CowApprovalStatus } from './types'\n\n/** Check whether the vault relayer can pull `amount` of the sell token. */\nexport async function checkCowApproval(params: CheckCowApprovalParams): Promise<CowApprovalStatus> {\n const { client, sellToken, owner, amount } = params\n\n const allowance = await client.readContract({\n address: sellToken,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [owner, COW_VAULT_RELAYER],\n })\n\n return { needsApproval: allowance < amount, allowance }\n}\n\n/** Approve the sell token to the vault relayer (defaults to unlimited). */\nexport async function approveErc20ForCow(params: ApproveErc20ForCowParams): Promise<TxResult> {\n const { client, walletClient, account, sellToken, amount = maxUint256, txOverrides } = params\n\n return submitWrite({\n client,\n walletClient,\n account,\n address: sellToken,\n abi: erc20Abi,\n functionName: 'approve',\n args: [COW_VAULT_RELAYER, amount],\n txOverrides,\n })\n}\n","/**\n * Venue selection between the Uniswap v4 router and CoW Swap.\n *\n * Pure amount comparison so it stays testable and reusable outside React.\n * Gas cost of the router tx is not factored in (CoW ERC20 sells are gasless);\n * TODO: optionally discount the Uniswap side by gasEstimate × gas price.\n *\n * @module cow/compare\n */\n\n/** Swap venues the UI can route through. */\nexport type SwapVenue = 'uniswap' | 'cow'\n\nconst BPS_DENOMINATOR = 10_000n\n\n/** Parameters for {@link pickBestVenue}. */\nexport interface PickBestVenueParams {\n /** 'sell' = exact-in (maximize output), 'buy' = exact-out (minimize input). */\n kind: 'sell' | 'buy'\n /** Uniswap quote amounts; omit when the quote failed or is unavailable. */\n uniswap?: {\n /** Quoted output (exact-in). */\n amountOut?: bigint\n /** Quoted input (exact-out). */\n amountIn?: bigint\n }\n /** CoW quote amounts; omit when the quote failed or is unavailable. */\n cow?: {\n /** Quoted net output (exact-in). */\n buyAmount?: bigint\n /** Quoted gross input including fee (exact-out). */\n sellAmountTotal?: bigint\n }\n}\n\n/** Result of {@link pickBestVenue}. */\nexport interface BestVenue {\n winner: SwapVenue\n /** Price advantage of the winner over the loser in bps (only when both quoted). */\n advantageBps?: bigint\n}\n\n/**\n * Pick the venue with the better effective price. Exact-in compares net\n * output (higher wins); exact-out compares gross input (lower wins). With a\n * single usable quote that venue wins; ties go to Uniswap (instant\n * settlement); with no usable quotes Uniswap wins by default.\n */\nexport function pickBestVenue(params: PickBestVenueParams): BestVenue {\n const { kind, uniswap, cow } = params\n\n const uniAmount = kind === 'sell' ? uniswap?.amountOut : uniswap?.amountIn\n const cowAmount = kind === 'sell' ? cow?.buyAmount : cow?.sellAmountTotal\n\n if (cowAmount === undefined || cowAmount <= 0n) return { winner: 'uniswap' }\n if (uniAmount === undefined || uniAmount <= 0n) return { winner: 'cow' }\n\n // 'sell': bigger output wins; 'buy': smaller input wins. Ties → Uniswap.\n const cowWins = kind === 'sell' ? cowAmount > uniAmount : cowAmount < uniAmount\n const [better, worse] = cowWins ? [cowAmount, uniAmount] : [uniAmount, cowAmount]\n const advantageBps =\n kind === 'sell'\n ? ((better - worse) * BPS_DENOMINATOR) / worse\n : ((worse - better) * BPS_DENOMINATOR) / better\n\n return { winner: cowWins ? 'cow' : 'uniswap', advantageBps }\n}\n","/**\n * EIP-712 typed-data definitions for GPv2 (CoW Protocol) orders.\n * @module cow/eip712\n */\n\nimport { type Address, keccak256, stringToHex } from 'viem'\n\nimport { COW_SETTLEMENT } from './addresses'\n\n/** GPv2 `Order` struct, in EIP-712 typed-data form. */\nexport const COW_ORDER_TYPES = {\n Order: [\n { name: 'sellToken', type: 'address' },\n { name: 'buyToken', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'sellAmount', type: 'uint256' },\n { name: 'buyAmount', type: 'uint256' },\n { name: 'validTo', type: 'uint32' },\n { name: 'appData', type: 'bytes32' },\n { name: 'feeAmount', type: 'uint256' },\n { name: 'kind', type: 'string' },\n { name: 'partiallyFillable', type: 'bool' },\n { name: 'sellTokenBalance', type: 'string' },\n { name: 'buyTokenBalance', type: 'string' },\n ],\n} as const\n\n/** GPv2 order-cancellation struct (batch of order UIDs). */\nexport const COW_CANCELLATION_TYPES = {\n OrderCancellations: [{ name: 'orderUids', type: 'bytes[]' }],\n} as const\n\n/** EIP-712 domain for GPv2Settlement on the given chain. */\nexport function cowDomain(chainId: bigint | number): {\n name: string\n version: string\n chainId: number\n verifyingContract: Address\n} {\n return {\n name: 'Gnosis Protocol',\n version: 'v2',\n chainId: Number(chainId),\n verifyingContract: COW_SETTLEMENT,\n }\n}\n\n/**\n * Full appData JSON document attached to orders. The order itself carries only\n * its keccak256 hash; the API stores the document when it accompanies the\n * order POST. Must stay byte-identical to {@link APP_DATA_HASH}.\n */\nexport const APP_DATA_DOC = '{\"appCode\":\"panoptic\",\"metadata\":{},\"version\":\"1.3.0\"}'\n\n/** keccak256 of {@link APP_DATA_DOC} — the `appData` field signed in the order. */\nexport const APP_DATA_HASH = keccak256(stringToHex(APP_DATA_DOC))\n","/**\n * Errors for the CoW Protocol swap module.\n *\n * All extend {@link PanopticError} so callers can keep a single\n * `instanceof PanopticError` check and so they satisfy `SimulationResult`'s\n * error type.\n *\n * @module cow/errors\n */\n\nimport { PanopticError } from '../panoptic/v2/errors'\n\n/** The chain has no CoW order book. */\nexport class CowUnsupportedChainError extends PanopticError {\n override readonly name = 'CowUnsupportedChainError'\n\n constructor(\n public readonly chainId: bigint,\n cause?: Error,\n ) {\n super(`CoW Protocol not available on chain ${chainId}`, cause)\n }\n}\n\n/** The order-book API rejected a request (non-2xx response). */\nexport class CowApiError extends PanopticError {\n override readonly name: string = 'CowApiError'\n\n constructor(\n /** Machine-readable API error type, e.g. 'SellAmountDoesNotCoverFee'. */\n public readonly errorType: string,\n message: string,\n public readonly status: number,\n cause?: Error,\n ) {\n super(message, cause)\n }\n}\n\n/** The sell amount is too small to cover the protocol fee (dust order). */\nexport class CowOrderTooSmallError extends CowApiError {\n override readonly name = 'CowOrderTooSmallError'\n\n constructor(message: string, status: number, cause?: Error) {\n super('SellAmountDoesNotCoverFee', message, status, cause)\n }\n}\n\n/** Selling native ETH requires the eth-flow contract (unsupported here); buying it is fine. */\nexport class CowNativeTokenError extends PanopticError {\n override readonly name = 'CowNativeTokenError'\n\n constructor(cause?: Error) {\n super('CoW orders cannot sell native ETH (eth-flow not supported)', cause)\n }\n}\n","/**\n * Minimal fetch wrapper for the CoW order-book REST API.\n * @module cow/api\n */\n\nimport { COW_API_URLS } from './addresses'\nimport { CowApiError, CowOrderTooSmallError, CowUnsupportedChainError } from './errors'\n\n/** Resolve the order-book base URL for a chain (override wins). */\nexport function resolveCowApiUrl(chainId: bigint, apiUrl?: string): string {\n const url = apiUrl ?? COW_API_URLS[Number(chainId)]\n if (!url) throw new CowUnsupportedChainError(chainId)\n return url\n}\n\n/** Shape of order-book error payloads. */\ninterface CowApiErrorBody {\n errorType?: string\n description?: string\n}\n\n/**\n * Call the order book and parse JSON, mapping non-2xx responses to\n * {@link CowApiError} (dust orders to {@link CowOrderTooSmallError}).\n */\nexport async function cowApiRequest<T>(\n baseUrl: string,\n path: string,\n init?: RequestInit,\n): Promise<T> {\n // Normalize headers so a Headers instance / tuple array passed by the caller\n // is preserved (a spread would drop those), only defaulting Content-Type.\n const headers = new Headers(init?.headers)\n if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json')\n const response = await fetch(`${baseUrl}/api/v1${path}`, { ...init, headers })\n\n if (!response.ok) {\n let body: CowApiErrorBody = {}\n try {\n body = (await response.json()) as CowApiErrorBody\n } catch {\n // Non-JSON error body — fall through with the status text.\n }\n const errorType = body.errorType ?? 'UnknownError'\n const message = body.description ?? `CoW API request failed (${response.status})`\n if (errorType === 'SellAmountDoesNotCoverFee') {\n throw new CowOrderTooSmallError(message, response.status)\n }\n throw new CowApiError(errorType, message, response.status)\n }\n\n // Tolerate empty / non-JSON success bodies (e.g. DELETE /orders for a\n // cancellation, which callers type as void): return undefined rather than\n // throwing inside response.json().\n if (response.status === 204) return undefined as T\n const text = await response.text()\n if (text === '') return undefined as T\n return JSON.parse(text) as T\n}\n","/**\n * Sign and submit CoW orders (and signed cancellations) to the order book.\n *\n * Orders are EIP-712 intents — submission returns an order UID, not a tx\n * hash. Settlement happens later when a solver includes the order in a batch;\n * track it via {@link getCowOrderStatus}.\n *\n * @module cow/order\n */\n\nimport type { Hex } from 'viem'\n\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport {\n APP_DATA_DOC,\n APP_DATA_HASH,\n COW_CANCELLATION_TYPES,\n COW_ORDER_TYPES,\n cowDomain,\n} from './eip712'\nimport type { CancelCowOrderParams, CowOrderResult, SignAndSubmitCowOrderParams } from './types'\n\n/**\n * Build the final order from a quote, sign it (EIP-712) and POST it to the\n * order book. The signed `feeAmount` is 0 — the fee is already folded into the\n * quote's `orderSellAmount`.\n */\nexport async function signAndSubmitCowOrder(\n params: SignAndSubmitCowOrderParams,\n): Promise<CowOrderResult> {\n const { walletClient, account, chainId, quote, receiver = account, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const order = {\n sellToken: quote.sellToken,\n buyToken: quote.buyToken,\n receiver,\n sellAmount: quote.orderSellAmount,\n buyAmount: quote.orderBuyAmount,\n validTo: Number(quote.validTo),\n appData: APP_DATA_HASH,\n feeAmount: 0n,\n kind: quote.kind,\n partiallyFillable: false,\n sellTokenBalance: 'erc20',\n buyTokenBalance: 'erc20',\n } as const\n\n const signature = await walletClient.signTypedData({\n account,\n domain: cowDomain(chainId),\n types: COW_ORDER_TYPES,\n primaryType: 'Order',\n message: order,\n })\n\n const orderUid = await cowApiRequest<Hex>(baseUrl, '/orders', {\n method: 'POST',\n body: JSON.stringify({\n ...order,\n sellAmount: order.sellAmount.toString(),\n buyAmount: order.buyAmount.toString(),\n feeAmount: '0',\n // Full appData document so the API can verify it against the signed hash.\n appData: APP_DATA_DOC,\n appDataHash: APP_DATA_HASH,\n signingScheme: 'eip712',\n signature,\n from: account,\n quoteId: quote.quoteId ?? undefined,\n }),\n })\n\n return { orderUid }\n}\n\n/**\n * Cancel an open order off-chain (free, signed cancellation). Cancellation is\n * best-effort: an order already committed to a solver batch can still settle.\n */\nexport async function cancelCowOrder(params: CancelCowOrderParams): Promise<void> {\n const { walletClient, account, chainId, orderUid, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const signature = await walletClient.signTypedData({\n account,\n domain: cowDomain(chainId),\n types: COW_CANCELLATION_TYPES,\n primaryType: 'OrderCancellations',\n message: { orderUids: [orderUid] },\n })\n\n await cowApiRequest<void>(baseUrl, '/orders', {\n method: 'DELETE',\n body: JSON.stringify({ orderUids: [orderUid], signature, signingScheme: 'eip712' }),\n })\n}\n","/**\n * Quote swaps via the CoW order-book API.\n *\n * Unlike the Uniswap quoter this is an off-chain HTTP call; results still come\n * back as a `SimulationResult` so UI error handling matches the router path.\n *\n * @module cow/quote\n */\n\nimport { zeroAddress } from 'viem'\n\nimport { PanopticError } from '../panoptic/v2/errors'\nimport type { SimulationResult } from '../panoptic/v2/types'\nimport { COW_NATIVE_ETH } from './addresses'\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport { APP_DATA_DOC } from './eip712'\nimport { CowNativeTokenError } from './errors'\nimport type { CowQuote, QuoteCowSwapParams } from './types'\n\nconst BPS_DENOMINATOR = 10_000n\n/** Default order validity window (30 minutes). */\nexport const DEFAULT_VALID_FOR_SECONDS = 1800n\n\n/** No block context for off-chain quotes. */\nconst OFFCHAIN_META = {\n blockNumber: 0n,\n blockTimestamp: 0n,\n blockHash: '0x0' as `0x${string}`,\n}\n\n/**\n * Reject out-of-range slippage so the limit-amount math can't underflow/overflow.\n * 100% (BPS_DENOMINATOR) is forbidden too: on the exact-in path it would reduce\n * `orderBuyAmount` to 0, signing an order that accepts any fill.\n */\nfunction assertSlippageBps(slippageBps: bigint): void {\n if (slippageBps < 0n || slippageBps >= BPS_DENOMINATOR) {\n throw new PanopticError(`invalid slippageBps ${slippageBps}, must be 0..9999`)\n }\n}\n\n/** Raw order-book quote response (amounts are decimal strings). */\ninterface CowQuoteResponse {\n quote: {\n sellToken: string\n buyToken: string\n sellAmount: string\n buyAmount: string\n feeAmount: string\n validTo: number\n kind: 'sell' | 'buy'\n }\n id: number | null\n}\n\n/**\n * Quote a swap via the CoW order book.\n *\n * For `kind: 'sell'` (exact-in) `amount` is the sell amount before fee; for\n * `kind: 'buy'` (exact-out) it is the exact buy amount. The returned\n * `orderSellAmount`/`orderBuyAmount` are ready to sign: the fee is folded into\n * the sell side (orders are placed with `feeAmount: 0` under the current fee\n * model) and `slippageBps` is applied to the non-exact side.\n */\nexport async function quoteCowSwap(\n params: QuoteCowSwapParams,\n): Promise<SimulationResult<CowQuote>> {\n const {\n chainId,\n sellToken,\n buyToken,\n kind,\n amount,\n from,\n slippageBps,\n validForSeconds = DEFAULT_VALID_FOR_SECONDS,\n apiUrl,\n } = params\n\n try {\n assertSlippageBps(slippageBps)\n // Selling native ETH would need the eth-flow contract; buying it is fine —\n // orders use the buy-token sentinel and settle in native ETH.\n if (sellToken === zeroAddress) {\n throw new CowNativeTokenError()\n }\n const resolvedBuyToken = buyToken === zeroAddress ? COW_NATIVE_ETH : buyToken\n if (amount <= 0n) {\n throw new PanopticError(`amount ${amount} must be positive`)\n }\n\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n const response = await cowApiRequest<CowQuoteResponse>(baseUrl, '/quote', {\n method: 'POST',\n body: JSON.stringify({\n sellToken,\n buyToken: resolvedBuyToken,\n from,\n receiver: from,\n validFor: Number(validForSeconds),\n appData: APP_DATA_DOC,\n partiallyFillable: false,\n sellTokenBalance: 'erc20',\n buyTokenBalance: 'erc20',\n signingScheme: 'eip712',\n ...(kind === 'sell'\n ? { kind: 'sell', sellAmountBeforeFee: amount.toString() }\n : { kind: 'buy', buyAmountAfterFee: amount.toString() }),\n }),\n })\n\n const sellAmount = BigInt(response.quote.sellAmount)\n const buyAmount = BigInt(response.quote.buyAmount)\n const feeAmount = BigInt(response.quote.feeAmount)\n const sellAmountTotal = sellAmount + feeAmount\n\n // Fold the fee into the signed sell amount (feeAmount signs as 0), then\n // apply slippage to the side the user did not fix. Buy-order sell cap uses\n // ceiling division so the buffer never rounds down.\n const orderSellAmount =\n kind === 'sell'\n ? sellAmountTotal\n : (sellAmountTotal * (BPS_DENOMINATOR + slippageBps) + BPS_DENOMINATOR - 1n) /\n BPS_DENOMINATOR\n const orderBuyAmount =\n kind === 'sell' ? (buyAmount * (BPS_DENOMINATOR - slippageBps)) / BPS_DENOMINATOR : buyAmount\n\n return {\n success: true,\n data: {\n kind,\n sellToken,\n // The signed order must carry the resolved (sentinel) buy token.\n buyToken: resolvedBuyToken,\n sellAmount,\n buyAmount,\n feeAmount,\n sellAmountTotal,\n orderSellAmount,\n orderBuyAmount,\n validTo: BigInt(response.quote.validTo),\n quoteId: response.id,\n },\n gasEstimate: 0n,\n _meta: OFFCHAIN_META,\n }\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof PanopticError\n ? error\n : new PanopticError(\n error instanceof Error ? error.message : 'CoW quote failed',\n error instanceof Error ? error : undefined,\n ),\n _meta: OFFCHAIN_META,\n }\n }\n}\n","/**\n * Poll order state from the CoW order book.\n * @module cow/status\n */\n\nimport type { Hex } from 'viem'\n\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport type { CowOrderState, CowOrderStatus, GetCowOrderStatusParams } from './types'\n\n/** Raw `GET /orders/{uid}` fields we consume. */\ninterface CowOrderResponse {\n status: CowOrderStatus\n executedSellAmount: string\n executedBuyAmount: string\n}\n\n/** Raw `GET /trades` entry fields we consume. */\ninterface CowTradeResponse {\n txHash: Hex | null\n}\n\n/**\n * Fetch an order's lifecycle state. Once any trade has executed, the\n * settlement tx hash is included (fetched from the trades endpoint).\n */\nexport async function getCowOrderStatus(params: GetCowOrderStatusParams): Promise<CowOrderState> {\n const { chainId, orderUid, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const order = await cowApiRequest<CowOrderResponse>(baseUrl, `/orders/${orderUid}`)\n\n const executedSellAmount = BigInt(order.executedSellAmount ?? '0')\n const executedBuyAmount = BigInt(order.executedBuyAmount ?? '0')\n\n let settlementTxHash: Hex | undefined\n if (executedBuyAmount > 0n) {\n const trades = await cowApiRequest<CowTradeResponse[]>(baseUrl, `/trades?orderUid=${orderUid}`)\n settlementTxHash = trades.find((t) => t.txHash)?.txHash ?? undefined\n }\n\n return { status: order.status, executedSellAmount, executedBuyAmount, settlementTxHash }\n}\n","/**\n * Resolve token symbols to addresses using the token lists CoW Swap trades\n * from. Lets a UI route any listed token (e.g. xStocks like NVDAx) to the\n * order book without maintaining a static registry.\n *\n * Sources, in priority order:\n * 1. CoW's curated list (canonical entries for blue-chip symbols like UNI)\n * 2. CoinGecko's full per-chain list (carries the long tail, incl. xStocks)\n *\n * Lists are fetched lazily and cached in-module for an hour.\n *\n * @module cow/tokens\n */\n\nimport { type Address, getAddress } from 'viem'\n\n/** Resolved token-list entry. */\nexport interface CowTokenInfo {\n chainId: number\n address: Address\n symbol: string\n name: string\n decimals: number\n logoURI?: string\n}\n\n/** Parameters for {@link findCowToken}. */\nexport interface FindCowTokenParams {\n /** Chain to resolve on. */\n chainId: bigint\n /** Token symbol, case-insensitive (e.g. 'nvdax'). */\n symbol: string\n /** Override the token-list URLs (e.g. tests). */\n listUrls?: string[]\n}\n\n/** CoinGecko per-chain list slugs for the chains CoW supports here. */\nconst COINGECKO_CHAIN_SLUGS: Partial<Record<number, string>> = {\n 1: 'ethereum',\n}\n\nfunction tokenListUrls(chainId: number): string[] {\n const urls = ['https://files.cow.fi/tokens/CowSwap.json']\n const slug = COINGECKO_CHAIN_SLUGS[chainId]\n if (slug) urls.push(`https://tokens.coingecko.com/${slug}/all.json`)\n return urls\n}\n\ninterface RawTokenList {\n tokens: {\n chainId?: number\n address: string\n symbol: string\n name: string\n decimals: number\n logoURI?: string\n }[]\n}\n\nconst LIST_CACHE_TTL_MS = 3_600_000\nconst listCache = new Map<string, { fetchedAt: number; list: Promise<RawTokenList | null> }>()\n\n/** Fetch a token list with an in-module 1h cache; resolves null on any failure. */\nfunction fetchTokenList(url: string): Promise<RawTokenList | null> {\n const cached = listCache.get(url)\n if (cached && Date.now() - cached.fetchedAt < LIST_CACHE_TTL_MS) return cached.list\n\n const list = fetch(url)\n .then((res) => (res.ok ? (res.json() as Promise<RawTokenList>) : null))\n .catch(() => null)\n .then((parsed) => {\n // Drop failures from the cache so the next call retries.\n if (parsed === null || !Array.isArray(parsed.tokens)) {\n listCache.delete(url)\n return null\n }\n return parsed\n })\n listCache.set(url, { fetchedAt: Date.now(), list })\n return list\n}\n\n/**\n * Find a token by symbol on the given chain across CoW's token lists. The\n * first list containing a (case-insensitive) symbol match wins; within a\n * list the first match wins, which favors canonical entries on collisions.\n * Returns null when no list resolves the symbol (or all fetches fail).\n *\n * Resolution only proves the token is listed — whether solvers can actually\n * fill a given pair/size is answered by `quoteCowSwap`.\n */\nexport async function findCowToken(params: FindCowTokenParams): Promise<CowTokenInfo | null> {\n const { chainId, symbol, listUrls } = params\n const chain = Number(chainId)\n const wanted = symbol.toUpperCase()\n\n for (const url of listUrls ?? tokenListUrls(chain)) {\n const list = await fetchTokenList(url)\n if (!list) continue\n const match = list.tokens.find(\n // CoW's own list omits chainId on some entries (single-chain lists).\n (t) => (t.chainId === undefined || t.chainId === chain) && t.symbol.toUpperCase() === wanted,\n )\n if (match) {\n // Validate/checksum the external address; skip a malformed entry rather\n // than leak a non-Address string to callers.\n let address: Address\n try {\n address = getAddress(match.address)\n } catch {\n continue\n }\n return {\n chainId: chain,\n address,\n symbol: match.symbol,\n name: match.name,\n decimals: match.decimals,\n logoURI: match.logoURI,\n }\n }\n }\n return null\n}\n","/**\n * Generated registry of Backed xStock ERC4626 wrappers on Ethereum mainnet.\n *\n * DO NOT EDIT BY HAND. Regenerate with `pnpm --filter panoptic-v2-sdk gen:xstock-wrappers`\n * (scripts/gen-xstock-wrappers.ts), which scans the WrappedBackedTokenFactory\n * `NewToken` events and reads each wrapper's ERC4626 `asset()` as the underlying.\n *\n * @module cow/xstockWrappers.generated\n */\n\nimport type { XstockWrapperRegistry } from './xstockWrappers'\n\nexport const XSTOCK_WRAPPERS: XstockWrapperRegistry = {\n 1: [\n {\n wrapper: '0x5AA7649fdbDa47De64A07aC81D64B682AF9C0724',\n underlying: '0x9d275685dC284C8eB1C79f6ABA7a63Dc75ec890a',\n symbol: 'wAAPLx',\n name: 'Wrapped Apple xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5CC079963Fb70C0f987F65F539E3B61a6EBdf6Db',\n underlying: '0xfBF2398dF672cEE4aFcC2A4A733222331c742a6A',\n symbol: 'wABBVx',\n name: 'Wrapped AbbVie xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD812B37181Ae89801e4BB3F49E4C1FAF11fC0b57',\n underlying: '0x89233399708C18Ac6887F90A2B4Cd8Ba5fEdD06e',\n symbol: 'wABTx',\n name: 'Wrapped Abbott xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc262Bea18cb810Cc7715EE48fe3cbD3D79B4aFe1',\n underlying: '0x03183Ce31b1656B72A55fa6056e287f50C35BbEB',\n symbol: 'wACNx',\n name: 'Wrapped Accenture xStock',\n decimals: 18,\n },\n {\n wrapper: '0x444DE06b76C9a1417A21A877038F49A1f0D8A1cD',\n underlying: '0x16E0B579be45bAaE54cEddd52e742B6457A7fE12',\n symbol: 'wADBEx',\n name: 'Wrapped Adobe xStock',\n decimals: 18,\n },\n {\n wrapper: '0x36d2fe6e6e4136C6BF286588391FAD6d45422350',\n underlying: '0x2f9a35aB5dDFBc49927BFdEab98A86c53DC6E763',\n symbol: 'wAMBRx',\n name: 'Wrapped Amber xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1eb8909B5C46A24F005A76C469912f5518F448eF',\n underlying: '0x3522513E5F146a2006e2901b05f16B2821485E19',\n symbol: 'wAMDx',\n name: 'Wrapped AMD xStock',\n decimals: 18,\n },\n {\n wrapper: '0xac85d37acbadCa37545E21ab0fB991bcE8c1187C',\n underlying: '0x3557Ba345B01EFa20A1bdDC61F573BFD87195081',\n symbol: 'wAMZNx',\n name: 'Wrapped Amazon.com xStock',\n decimals: 18,\n },\n {\n wrapper: '0xd17E483364D849e3B3A52464bb2CA56626EDfc31',\n underlying: '0x50a1291F69D9d3853Def8209cFb1AF0b46927BE1',\n symbol: 'wAPPx',\n name: 'Wrapped AppLovin xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD0798d3c30F4408350C8448d75DA1c7721227dBa',\n underlying: '0xC0B417e7F83db438631Eb5E096684dd742E5294F',\n symbol: 'wASMLx',\n name: 'Wrapped ASML xStock',\n decimals: 18,\n },\n {\n wrapper: '0x720347faf9D745B841541De0d7B2abc8A4b87531',\n underlying: '0x89b2607878ae19baB8020b8140eD550Ef3E953bb',\n symbol: 'wASTSx',\n name: 'Wrapped AST SpaceMobile xStock',\n decimals: 18,\n },\n {\n wrapper: '0x8DEb752aAA807E0258afd5cCFFe2b5A804026f28',\n underlying: '0x38BAC69cbBd28156796e4163B2B6dcb81E336565',\n symbol: 'wAVGOx',\n name: 'Wrapped Broadcom xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0b306951161b856Ad02c8566B4eF184c6BB08564',\n underlying: '0xb23767492D0Ca6dC7221CBeA45689a0410f388c4',\n symbol: 'wAXPx',\n name: 'Wrapped American Express xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB908FEAeab7E671dB697d77c3acFD8859E92a4e2',\n underlying: '0x5D642505FE1a28897eb3BaBA665F454755D8daA2',\n symbol: 'wAZNx',\n name: 'Wrapped AstraZeneca xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA2b1335256cd663Da89F650180508dd1f0DC3BAa',\n underlying: '0x314938c596F5ce31C3f75307d2979338C346D7F2',\n symbol: 'wBACx',\n name: 'Wrapped Bank of America xStock',\n decimals: 18,\n },\n {\n wrapper: '0xDEc933e2392AD908263e70A386fbF34e703Ffe8F',\n underlying: '0xbbcb0356bB9e6B3Faa5CbF9E5F36185d53403Ac9',\n symbol: 'wbCOIN',\n name: 'Wrapped Backed Coinbase Global',\n decimals: 18,\n },\n {\n wrapper: '0x277f724d12DD0249b48CBD7eB2623c5e5042b970',\n underlying: '0xa8A25DB6Cf17Fa097f1DBbc9c841892456898fF3',\n symbol: 'wBKNGx',\n name: 'Wrapped Booking xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE5365A5A16A7D1DD37b33e6F8D78aeB89847398B',\n underlying: '0x5A6a0742cA689E7E8a91A38F5255589CB2191646',\n symbol: 'wBLKx',\n name: 'Wrapped BlackRock xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7a1d054e09eAe0294D53959674EE9DE14a1f70B1',\n underlying: '0x38DE7b9FC733DeF81525E65C1Bf99722026489e2',\n symbol: 'wBLSHx',\n name: 'Wrapped Bullish xStock',\n decimals: 18,\n },\n {\n wrapper: '0xBFd29b7F395d30932033c2F45ab792024E71AA94',\n underlying: '0xaeB681B69E5094E04d11BCeF51A71358A374C3ED',\n symbol: 'wBMNRx',\n name: 'Wrapped Bitmine xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1a4F71B0Ff3C22540887bcf83b50054a213c673d',\n underlying: '0xaC28C9178ACc8BA4A11A29E013a3A2627086e422',\n symbol: 'wbMSTR',\n name: 'Wrapped Backed MicroStrategy Inc',\n decimals: 18,\n },\n {\n wrapper: '0x7E8101A1C322D394b3961498c7D40d2DFA94C392',\n underlying: '0xA34C5e0AbE843E10461E2C9586Ea03E55Dbcc495',\n symbol: 'wbNVDA',\n name: 'Wrapped Backed NVIDIA Corp',\n decimals: 18,\n },\n {\n wrapper: '0xa150245f155778e749185C9446e9e59E406674eF',\n underlying: '0x12992613fDd35aBe95DEc5a4964331b1ee23B50d',\n symbol: 'wBRK.Bx',\n name: 'Wrapped Berkshire Hathaway xStock',\n decimals: 18,\n },\n {\n wrapper: '0x88E437dbebdDe3D75Ff7c0cb830F54dd834538f0',\n underlying: '0x22E1991e5f82736A2a990322a46aac0e95826c5B',\n symbol: 'wBTBTx',\n name: 'Wrapped Bit Digital xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1f82284C1658Ad71C576f7230E6C2DEE7901c1FA',\n underlying: '0x14A5f2872396802C3Cc8942A39Ab3E4118EE5038',\n symbol: 'wbTSLA',\n name: 'Wrapped Backed Tesla Inc',\n decimals: 18,\n },\n {\n wrapper: '0xdCE0CA61bC9F95b771e0764dc4C553288b7F2f13',\n underlying: '0xD0194F0f077968DA8ca59811e9407f54AE6c9432',\n symbol: 'wCLSKx',\n name: 'Wrapped CleanSpark xStock',\n decimals: 18,\n },\n {\n wrapper: '0xd1A01e3F9c7565e88b1CF2413ba0a0E671e57b33',\n underlying: '0xBC7170a1280Be28513B4e940C681537EB25e39f4',\n symbol: 'wCMCSAx',\n name: 'Wrapped Comcast xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3a98E79cDc7D8B2716A8696E25af028E429f11dA',\n underlying: '0x364f210f430eC2448Fc68A49203040F6124096F0',\n symbol: 'wCOINx',\n name: 'Wrapped Coinbase xStock',\n decimals: 18,\n },\n {\n wrapper: '0x89E2B6cA78DBee629544679780963b85Ba76fe2a',\n underlying: '0x51eD5b74A05F256DbD9Ebb4e4f68Bb41ba10160b',\n symbol: 'wCORZx',\n name: 'Wrapped Core Scientific xStock',\n decimals: 18,\n },\n {\n wrapper: '0xFa48FeE923600Fecaa7af0DfB4a66E3109Ad51bf',\n underlying: '0x4720B5e6421e6879132aED52040d56Bb6e5CFeeF',\n symbol: 'wCOSTx',\n name: 'Wrapped Costco xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA90872ACa656eBE47bDEBF3B19Ec9Dd9C5ADC7f8',\n underlying: '0xfEbDEd1B0986a8ee107f5AB1a1c5a813491DeCEB',\n symbol: 'wCRCLx',\n name: 'Wrapped Circle xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc6B6B8D50A6673C04C495e30B411da5A7adF39f5',\n underlying: '0x4A4073f2EAF299A1be22254DCD2C41727F6F54a2',\n symbol: 'wCRMx',\n name: 'Wrapped Salesforce xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD71a6aDBc40c2674591CDB11B8C7ae03A880b06E',\n underlying: '0x214151022C2a5E380aB80CdaC31f23Ae554a7345',\n symbol: 'wCRWDx',\n name: 'Wrapped CrowdStrike xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCFa485bc42c2492917351F89F5cf5c7b2C5a66aa',\n underlying: '0x053C784cD87B74f42e0c089f98643E79c1A3ff16',\n symbol: 'wCSCOx',\n name: 'Wrapped Cisco xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7F88888b7A81546a036554Aa67a289Ea428b20d4',\n underlying: '0xad5cdc3340904285B8159089974A99a1A09EB4C0',\n symbol: 'wCVXx',\n name: 'Wrapped Chevron xStock',\n decimals: 18,\n },\n {\n wrapper: '0xce41bF7482E86fFF0Ab0A971dD425496BB58E4FD',\n underlying: '0x521860bB5dF5468358875266B89BFE90d990C6e7',\n symbol: 'wDFDVx',\n name: 'Wrapped DFDV xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6c7AD1886a6Da37766fED060d5F08fF43285DcdD',\n underlying: '0xdbA228936F4079DaF9Aa906fd48a87f2300405F4',\n symbol: 'wDHRx',\n name: 'Wrapped Danaher xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3E5ceeA6D6399Ac1a1FEE67C1644fc7F616aD9fD',\n underlying: '0x03D44b9bB0398E2Be3C89417D51E615C3D461F5a',\n symbol: 'wDUOLx',\n name: 'Wrapped Duolingo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0c4F0256FB31cC71666Fee3f0cE1De3B1abE347B',\n underlying: '0x4c7610990cb63cdca174ce61822F7693B49FCe93',\n symbol: 'wEBAYx',\n name: 'Wrapped eBay xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5230C4b621bd2d1f22933903F9a4fA82a9F17fcf',\n underlying: '0xd1be5bA0c293997C7F69da707D14EB4ABCB13ddD',\n symbol: 'wEXPEx',\n name: 'Wrapped Expedia xStock',\n decimals: 18,\n },\n {\n wrapper: '0x91049e9586301c54B2eF410C2b7e9040Ffb02182',\n underlying: '0x3C313D234D0C6C876F6c21ba2EC1F26823247Be2',\n symbol: 'wFIGx',\n name: 'Wrapped Figma xStock',\n decimals: 18,\n },\n {\n wrapper: '0xdeAE051463CD8C457e7e9D97A398c575E8629c18',\n underlying: '0x3AE27479E6e52f6ddB6EA8AA567e6Cc92C78d93a',\n symbol: 'wFUFUx',\n name: 'Wrapped BitFuFu xStock',\n decimals: 18,\n },\n {\n wrapper: '0x61532Ce3f1DF7fBf5fFb7B891d184226e85B37c6',\n underlying: '0x2380F2673C640fB67E2d6B55B44C62F0E0e69DA9',\n symbol: 'wGLDx',\n name: 'Wrapped Gold xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4c79D4A1a863830EF845431578FB40E31bD51f4A',\n underlying: '0xf7F4fAC56f012dE7Dd6adFF54C761986B9E0655a',\n symbol: 'wGLXYx',\n name: 'Wrapped Galaxy Digital xStock',\n decimals: 18,\n },\n {\n wrapper: '0xb2f6ED0ED3eEb22bEF7A648794FFC19b8aF3761C',\n underlying: '0xE5f6d3b2405ABdfE6F660e63202B25D23763160d',\n symbol: 'wGMEx',\n name: 'Wrapped Gamestop xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1630F08370917E79df0B7572395a5e907508bBBc',\n underlying: '0xe92f673Ca36C5E2Efd2DE7628f815f84807e803F',\n symbol: 'wGOOGLx',\n name: 'Wrapped Alphabet xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6eEd78e2780d82BE4E37d9937C27Bcf32C8DA072',\n underlying: '0x3Ee7E9B3A992fD23CD1C363B0e296856B04ab149',\n symbol: 'wGSx',\n name: 'Wrapped Goldman Sachs xStock',\n decimals: 18,\n },\n {\n wrapper: '0xC641E2eBF6E076e2AE53477C2E725b3c67C0fd94',\n underlying: '0x766b0CD6ED6D90B5d49d2c36a3761E9728501BA9',\n symbol: 'wHDx',\n name: 'Wrapped Home Depot xStock',\n decimals: 18,\n },\n {\n wrapper: '0xBd1B73b2E89967e83507B500D798998200A53380',\n underlying: '0x62a48560861B0b451654bFffdb5be6E47aa8ff1B',\n symbol: 'wHONx',\n name: 'Wrapped Honeywell xStock',\n decimals: 18,\n },\n {\n wrapper: '0x953707d7A1cB30cc5C636bDA8EaeBe410341eB14',\n underlying: '0xE1385FDd5ffB10081Cd52C56584F25EFa9084015',\n symbol: 'wHOODx',\n name: 'Wrapped Robinhood xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6Ec2763859C5b04F5598017880744081aFeFa3Bb',\n underlying: '0xd457b379801433EA5c3A8542b61902023AE39DcD',\n symbol: 'wHSDTx',\n name: 'Wrapped Helius Medical Technologies xStock',\n decimals: 18,\n },\n {\n wrapper: '0x154f25Cfd146d2DF6420ec1f575C3c46D45f4Db7',\n underlying: '0x560deb3D70Ac90064fF809349cDf9A771a06fd36',\n symbol: 'wHUTx',\n name: 'Wrapped Hut 8 xStock',\n decimals: 18,\n },\n {\n wrapper: '0xa8F31436FFE4E71f51B2D65b7D5a5c457AE2000f',\n underlying: '0xd9913208647671Fe0F48F7F260076B2C6F310Aac',\n symbol: 'wIBMx',\n name: 'Wrapped International Business Machines xStock',\n decimals: 18,\n },\n {\n wrapper: '0x59361E881b186e48D71EC61E969dCF50a4dbC75b',\n underlying: '0x6a668332825450ACD2e449372057d31b3de16a1E',\n symbol: 'wIEMGx',\n name: 'Wrapped Core MSCI Emerging Markets xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3ab20fd7c57146AF128E8565261CBdaDa0F015E6',\n underlying: '0xAA28cB97D7f7E172f54deE950743886D2d65447d',\n symbol: 'wIJRx',\n name: 'Wrapped S&P Small Cap xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6A2a68Ca7FC793D8CEa36326a6Ec1eF7AC3D9742',\n underlying: '0xf8A80D1cb9cFD70D03D655D9dF42339846F3B3C8',\n symbol: 'wINTCx',\n name: 'Wrapped Intel xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5A47DE111D731Fd2Df90E4A2d7a9b459b31Bd643',\n underlying: '0xdadfb355c6110eda0908740d52c834d6C2BCDDc7',\n symbol: 'wIWMx',\n name: 'Wrapped Russell 2000 xStock',\n decimals: 18,\n },\n {\n wrapper: '0xcdB53A7cBa9Ec6d55dfE8f58bd6772826722D7BD',\n underlying: '0xdb0482cfaD4789798623E64b15eebA01b16e917C',\n symbol: 'wJNJx',\n name: 'Wrapped Johnson & Johnson xStock',\n decimals: 18,\n },\n {\n wrapper: '0xaB635f839f81A12dC8Db8Ab31006af14E26292fE',\n underlying: '0xD9FC3E075d45254a1D834fEa18AF8041207DeA0A',\n symbol: 'wJPMx',\n name: 'Wrapped JPMorgan Chase xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9a2486fbe7bC17C9100be65c31aBE7c9Bf84C23c',\n underlying: '0xdCC1a2699441079dA889B1F49e12B69cC791129b',\n symbol: 'wKOx',\n name: 'Wrapped Coca-Cola xStock',\n decimals: 18,\n },\n {\n wrapper: '0x316fFEa434348c2cB72024e62Ae845770315351E',\n underlying: '0x15059c599C16Fd8f70B633Ade165502D6402CD49',\n symbol: 'wLINx',\n name: 'Wrapped Linde xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3644971A7E971f60e707F7E8716cCaC5a0461290',\n underlying: '0x19c41EA77b34BbDEe61c3A87A75D1ABDA2ED0be4',\n symbol: 'wLLYx',\n name: 'Wrapped Eli Lilly xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD395C4dAd12eb071714d2b86cB5bC16acE9996B6',\n underlying: '0x847dEB9c78fb00319bC7A006dFF729c11428E537',\n symbol: 'wLULUx',\n name: 'Wrapped lululemon xStock',\n decimals: 18,\n },\n {\n wrapper: '0x34f5273693C880a9B2d9B6cfc8e13A2f3B8C0F06',\n underlying: '0x9D692bffEf6f6BedF4274053ff9998EFE3B2539E',\n symbol: 'wMARAx',\n name: 'Wrapped MARA xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5b32624f352d2FC6cC70889967A143ba1814f82b',\n underlying: '0xb365Cd2588065F522D379AD19e903304f6B622C6',\n symbol: 'wMAx',\n name: 'Wrapped Mastercard xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1717D8Be2Bcb27f4E8f36c817088Fa6a2c0b3B30',\n underlying: '0x80A77a372c1e12AcCdA84299492f404902E2DA67',\n symbol: 'wMCDx',\n name: \"Wrapped McDonald's xStock\",\n decimals: 18,\n },\n {\n wrapper: '0x02C1b10e5329c4502469396B2ce9f200E60b4a77',\n underlying: '0x0588e851ec0418d660BeE81230d6c678dAF21d46',\n symbol: 'wMDTx',\n name: 'Wrapped Medtronic xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4E41a262cAA93C6575d336E0a4eb79f3c67caa06',\n underlying: '0x96702be57Cd9777f835117a809C7124fe4ec989A',\n symbol: 'wMETAx',\n name: 'Wrapped Meta xStock',\n decimals: 18,\n },\n {\n wrapper: '0x61a6Cd11f658D1b418e1082b564678983b71Fb7F',\n underlying: '0x8499b26BBfC8c3830a37b92E47DF2d7cBc0154e9',\n symbol: 'wMNSTx',\n name: 'Wrapped Monster xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4728E48c2C201E32fe210AaB68A71E419FEAc74a',\n underlying: '0x17D8186Ed8F68059124190D147174D0f6697dc40',\n symbol: 'wMRKx',\n name: 'Wrapped Merck xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0d6fce45796D5c00689c0916b976645a0FF1F0cE',\n underlying: '0xeAAd46F4146Ded5a47B55AA7F6c48c191dEAEC88',\n symbol: 'wMRVLx',\n name: 'Wrapped Marvell xStock',\n decimals: 18,\n },\n {\n wrapper: '0x63Ad27614231767C8C489745B9145272De50D09b',\n underlying: '0x5621737f42dAE558b81269FcB9E9E70c19Aa6b35',\n symbol: 'wMSFTx',\n name: 'Wrapped Microsoft xStock',\n decimals: 18,\n },\n {\n wrapper: '0x266E5923F6118F8b340cA5a23AE7f71897361476',\n underlying: '0xAE2f842EF90C0d5213259Ab82639D5BBF649b08E',\n symbol: 'wMSTRx',\n name: 'Wrapped MicroStrategy xStock',\n decimals: 18,\n },\n {\n wrapper: '0x529E286229963bE57F0EC6F57d2D70A2F3E29935',\n underlying: '0xf6a873BAe4Ba1B304e45dF52A4b7D176E1C6a8c4',\n symbol: 'wMUx',\n name: 'Wrapped Micron Technology xStock',\n decimals: 18,\n },\n {\n wrapper: '0xfE0D2545f9E7f3678CB35Ed3CDf70488C5570D11',\n underlying: '0xA6a65AC27E76cD53cB790473E4345c46e5eBf961',\n symbol: 'wNFLXx',\n name: 'Wrapped Netflix xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93E62845C1DD5822EbC807ab71A5Fb750DecD15A',\n underlying: '0xc845b2894dBddd03858fd2D643B4eF725fE0849d',\n symbol: 'wNVDAx',\n name: 'Wrapped NVIDIA xStock',\n decimals: 18,\n },\n {\n wrapper: '0x16E443AEbc83E2089AA90431A1C0d311854EEC69',\n underlying: '0xF9523E369c5f55ad72DbAA75B0a9b92B3D8b147e',\n symbol: 'wNVOx',\n name: 'Wrapped Novo Nordisk xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9608a6eB064dd1C35eC9A4332bD9F8b05D1dE66C',\n underlying: '0x4b0eE7C047D43cA403239f28f42115bEdB7c0076',\n symbol: 'wOKLOx',\n name: 'Wrapped Oklo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9836479c80823f5f8B60FD0171F8D96301185714',\n underlying: '0xbEe6b69345F376598Fe16AbD5592c6F844825E66',\n symbol: 'wOPENx',\n name: 'Wrapped OPEN xStock',\n decimals: 18,\n },\n {\n wrapper: '0x54f34Ceb15313Caaee838F77c1c3C2Fe2E94526A',\n underlying: '0x548308E91ec9F285C7bFf05295baDBD56a6e4971',\n symbol: 'wORCLx',\n name: 'Wrapped Oracle xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7FbE0E7ACB47DCb053BF6146cCA6Bfb81A5D1319',\n underlying: '0xe12BB32D77BE4DB10DDC82088b230D35d097E9C5',\n symbol: 'wPANWx',\n name: 'Wrapped Palo Alto Networks xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA00A5538708b5aca7045F2ca15104707965bac94',\n underlying: '0x36c424a6EC0e264b1616102Ad63eD2aD7857413e',\n symbol: 'wPEPx',\n name: 'Wrapped PepsiCo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4E6894c3481B3A45393ce8ac9552945Ad50A3758',\n underlying: '0x1Ac765B5BEa23184802C7d2d497f7c33f1444A9e',\n symbol: 'wPFEx',\n name: 'Wrapped Pfizer xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0afC19943fA98E9E9E90Fc4ab4d4D3c13E162232',\n underlying: '0xa90424D5D3E770e8644103AB503ed775dD1318FD',\n symbol: 'wPGx',\n name: 'Wrapped Procter & Gamble xStock',\n decimals: 18,\n },\n {\n wrapper: '0xa3B6Fe1a923585bb828fCFAa460B78EeFD5aE2EC',\n underlying: '0x6d482CeC5f9dd1f05CCee9Fd3ff79B246170F8e2',\n symbol: 'wPLTRx',\n name: 'Wrapped Palantir xStock',\n decimals: 18,\n },\n {\n wrapper: '0xF429759BBf687118efd6B3713303006C356b8765',\n underlying: '0x536825370F1159cBA953055f5c2F16DDc7B5a348',\n symbol: 'wPLx',\n name: 'Wrapped Planet Labs xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7C2e00e6b0d519a8C492d20c2524342A4398FF34',\n underlying: '0x02a6c1789c3B4FDb1a7a3DfA39F90e5d3c94F4F9',\n symbol: 'wPMx',\n name: 'Wrapped Philip Morris xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCf4953c617CD1306A1f9236084204fBc67FDA2Ac',\n underlying: '0xf706585e7e8900bE0267bEE3B9A2F70835EC6628',\n symbol: 'wPYPLx',\n name: 'Wrapped PayPal xStock',\n decimals: 18,\n },\n {\n wrapper: '0xdbD9232fee15351068Fe02F0683146e16D9f2cEa',\n underlying: '0xa753A7395cAe905Cd615Da0B82A53E0560f250af',\n symbol: 'wQQQx',\n name: 'Wrapped Nasdaq xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc1de0BA489E6a5df9ebbA3911e382b455DeDF8c3',\n underlying: '0x5d8dA1417E3565eb02C9ca8cC588bE5D8F65b1c5',\n symbol: 'wRBLXx',\n name: 'Wrapped Roblox xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE99c177Bcb254bE2A0333c3B7071c696400Df1cF',\n underlying: '0x6Ac47387f0a2798dF4C4eE5bb31ab9517ac97cb8',\n symbol: 'wRIOTx',\n name: 'Wrapped Riot Platforms xStock',\n decimals: 18,\n },\n {\n wrapper: '0xf3f249dBaA9E3e9C9B78b1784cECd954e829aC81',\n underlying: '0xE17ce7dD2afb6Da3488fD9ef2558523D569e17B4',\n symbol: 'wRKLBx',\n name: 'Wrapped Rocket Lab xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4329d7C2Fa1De1c7218cd0c68587e2225C8C53fB',\n underlying: '0x7c7445A40926152B8d24aBDb9020e219d3D3380a',\n symbol: 'wSATAx',\n name: 'Wrapped Strive, Inc. Series A Preferred xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9Fd163B1020535C24A3140DB9BB1153E6dEf8fCd',\n underlying: '0x338791c58fdED314b81EAb139A1A2Fb7967D90d6',\n symbol: 'wSBETx',\n name: 'Wrapped SharpLink Gaming xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB9FCE7dcDfa1962EB53B3e2000554A77F0c10E8b',\n underlying: '0xF6D87E523512704C29E9b7cA3e9e6226bDCE3EA1',\n symbol: 'wSCHFx',\n name: 'Wrapped Schwab International Equity xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93bd84EE978b60f37df0639f70EAC621e542AD4b',\n underlying: '0x4833e7f4f0460f4B72A3a5879A6C9841bCC5B58B',\n symbol: 'wSLVx',\n name: 'Wrapped iShares Silver Trust xStock',\n decimals: 18,\n },\n {\n wrapper: '0x382567e5D72eca3eD2Bb97a4e42918107E09fab0',\n underlying: '0x7F8ba411ECBC0A135d669d5EaE5D15b0Ca0b0ea1',\n symbol: 'wSPCEx',\n name: 'Wrapped Virgin Galactic xStock',\n decimals: 18,\n },\n {\n wrapper: '0x8e2eeD8b8B5E13Ea7BF38e50d7821d2C57309072',\n underlying: '0x68fa48B1C2FE52b3D776E1953e0E782b5044Ce28',\n symbol: 'wSPCXx',\n name: 'Wrapped SpaceX xStock',\n decimals: 18,\n },\n {\n wrapper: '0x2f5a59Dd87C57fBfA10a5Ab12fD902C8AFdA2dfD',\n underlying: '0xD3c5Af6B2F0F754b2141f368cFc5ea99C3594d3a',\n symbol: 'wSPGIx',\n name: 'Wrapped S&P Global xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc88FcD8B874fDb3256E8B55b3decB8c24EAb4c02',\n underlying: '0x90A2a4c76b5D8c0bc892A69EA28Aa775a8f2dD48',\n symbol: 'wSPYx',\n name: 'Wrapped SP500 xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0B2456017C5Df2dFc0289740C4b352049892780C',\n underlying: '0x1Aad217B8F78dbA5E6693460e8470F8b1A3977f3',\n symbol: 'wSTRCx',\n name: 'Wrapped Strategy PP Variable xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB038B3b1f999897035AD4Ea65A9d6F59E2e86588',\n underlying: '0x38E0445308E7FcD5230F2DF6b52B36DD4FF313b6',\n symbol: 'wSTRKx',\n name: 'Wrapped Strategy PP Fixed xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCd932bF1c895B7143ec34Df5Ae7889D3853904D8',\n underlying: '0x4cbf89ED7Bb30b8a860fa86d3c96E9c72931299b',\n symbol: 'wTBLLx',\n name: 'Wrapped TBLL xStock',\n decimals: 18,\n },\n {\n wrapper: '0xfa4fFDbf6D53E1539B03823D72886Ab9510250E7',\n underlying: '0x61AeE4f4e6B62806c26eafF921e7F41782cA2E03',\n symbol: 'wTEMx',\n name: 'Wrapped Tempus AI xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0420112790C619Fbbd44106bC72ce217b515269A',\n underlying: '0xAB6a44AD34D083f463fa6F64d0619F11eB2cb48D',\n symbol: 'wTGTx',\n name: 'Wrapped Target xStock',\n decimals: 18,\n },\n {\n wrapper: '0x89EA0284308dEEF33a22abd7ea33888b4349108C',\n underlying: '0xAF072F109A2C173D822a4fe9af311A1B18F83d19',\n symbol: 'wTMOx',\n name: 'Wrapped Thermo Fisher xStock',\n decimals: 18,\n },\n {\n wrapper: '0xF940Fd9D8B80412C47691442075848cc05cD6732',\n underlying: '0x68F3DDEE8BAE33691E7CD0372984fD857E842760',\n symbol: 'wTMUSx',\n name: 'Wrapped T-Mobile xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4b12EB39418e30fC0e86E36CDac0545c1d9edAc9',\n underlying: '0xe95ab205e333443D7970336D5fD827eF9eD97608',\n symbol: 'wTONXx',\n name: 'Wrapped TON xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3D843414E617CBb9D2328c7eCF155d7C18139D6A',\n underlying: '0xfDDDb57878eF9D6f681Ec4381DCB626b9E69AC86',\n symbol: 'wTQQQx',\n name: 'Wrapped TQQQ xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93730D679190e831caea5e4ce46a5701D555e0F2',\n underlying: '0xeCF59a3FD0224D33429920f8fa6dE493abc4EFC0',\n symbol: 'wTRONx',\n name: 'Wrapped Tron xStock',\n decimals: 18,\n },\n {\n wrapper: '0x43680aBF18cf54898Be84C6eF78237CFBD441883',\n underlying: '0x8aD3c73F833d3F9A523aB01476625F269aEB7Cf0',\n symbol: 'wTSLAx',\n name: 'Wrapped Tesla xStock',\n decimals: 18,\n },\n {\n wrapper: '0x083283FAfD9CEC6145ce6a4A50F020A01737De52',\n underlying: '0x9e3bf4Ecfc44EeDD624F26656B6736a3F093b073',\n symbol: 'wTSMx',\n name: 'Wrapped TSMC xStock',\n decimals: 18,\n },\n {\n wrapper: '0xb10F7AA3BC0ad9FcE5Fc99702C2022d47BA93827',\n underlying: '0x75639aE3A05079873D7189DcbDBc455898cAe904',\n symbol: 'wTx',\n name: 'Wrapped AT&T xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4BEa51f138A30329b8855bf0DaE85EA5644Ada82',\n underlying: '0xdb9783Ca04bBD64fe2c6d7B9503A979b3DE30729',\n symbol: 'wUBERx',\n name: 'Wrapped Uber xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA0412CE46fE877b7f174B82aCD95E70063BbaF2a',\n underlying: '0x167A6375DA1eFc4a5BE0f470E73eCEfd66245048',\n symbol: 'wUNHx',\n name: 'Wrapped UnitedHealth xStock',\n decimals: 18,\n },\n {\n wrapper: '0x92DB84B2358E97976DAD16f91E6aeb9B2A757e76',\n underlying: '0x7AB6C97f65e4227adc5090Bd31a376D1F36f39fa',\n symbol: 'wVSTx',\n name: 'Wrapped Vistra xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE9161F111c55Bdd67525C1d4F9bbca07750aaAb7',\n underlying: '0xbD730E618bcD88C82dDeE52e10275CF2f88A4777',\n symbol: 'wVTIx',\n name: 'Wrapped Vanguard xStock',\n decimals: 18,\n },\n {\n wrapper: '0x48Da55D8FE70A4E3ec421736369BACB8D62Fa089',\n underlying: '0x6d5edEEbBc6A4099Eb8bb289EB3b80D799f7b28C',\n symbol: 'wVTx',\n name: 'Wrapped Vanguard Total World xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3cf193acf378Ec224a0209Be888b4b0B963E1896',\n underlying: '0x2363FD1235C1B6d3A5088DdF8dF3A0b3A30C5293',\n symbol: 'wVx',\n name: 'Wrapped Visa xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4cA269239B760787bB2A54C055c383FD2DADE779',\n underlying: '0xc435b3C41AE56d9Bc57b8525F4d522C978F168e8',\n symbol: 'wWBDx',\n name: 'Wrapped Warner Bros. Discovery xStock',\n decimals: 18,\n },\n {\n wrapper: '0x97C4C1704111B7c2304B177C37858B7169c667f9',\n underlying: '0xfEEE18422F8F1cD6193C12aAfad7123DbfF15517',\n symbol: 'wWENx',\n name: \"Wrapped Wendy's xStock\",\n decimals: 18,\n },\n {\n wrapper: '0xa24D9c43D64c76aCD962003647FD43a85eb44Db8',\n underlying: '0x7AEfc9965699fBea943e03264d96e50CD4A97b21',\n symbol: 'wWMTx',\n name: 'Wrapped Walmart xStock',\n decimals: 18,\n },\n {\n wrapper: '0xf068165CFf011A56562F855b44CF690e371232C8',\n underlying: '0xC0c2150cf0870E2d7aBc7cDe17C20A542faFBB9B',\n symbol: 'wWULFx',\n name: 'Wrapped TeraWulf xStock',\n decimals: 18,\n },\n {\n wrapper: '0x448bC811F60eac772775dD53421380E8D4DC4338',\n underlying: '0xEEdb0273c5Af792745180e9fF568cD01550fFA13',\n symbol: 'wXOMx',\n name: 'Wrapped Exxon Mobil xStock',\n decimals: 18,\n },\n ],\n}\n","/**\n * Resolve xStocks (tokenized equities) to their Backed ERC4626 wrapper, and\n * back.\n *\n * xStocks are rebasing, so they can't be used directly in AMMs / Panoptic\n * pools — those are built on the non-rebasing **wrapped** version minted by the\n * Backed `WrappedBackedTokenFactory`. CoW Swap, by contrast, trades the\n * unwrapped xStock. A user who buys e.g. NVDAx on CoW therefore holds the\n * unwrapped token and must wrap it before lending it or selling it through the\n * Uniswap/Panoptic venue.\n *\n * The factory exposes no underlying→wrapper lookup and its `NewToken` event\n * omits the underlying, so this mapping is generated offline (see\n * `scripts/gen-xstock-wrappers.ts`) into {@link XSTOCK_WRAPPERS} and resolved\n * statically here — no runtime fetch.\n *\n * Each wrapper is a standard ERC4626 vault: `asset()` is the underlying xStock,\n * `deposit` wraps, `redeem` unwraps, and `convertToShares`/`convertToAssets`\n * (or `previewDeposit`/`previewRedeem`) convert amounts.\n *\n * @module cow/xstockWrappers\n */\n\nimport type { Address } from 'viem'\n\nimport { XSTOCK_WRAPPERS } from './xstockWrappers.generated'\n\nexport { XSTOCK_WRAPPERS }\n\n/** A single xStock → wrapper mapping entry. */\nexport interface XstockWrapperInfo {\n /** ERC4626 wrapper (the token Panoptic/Uniswap pools trade). */\n wrapper: Address\n /** Underlying rebasing xStock (`asset()` of the wrapper; the CoW-traded token). */\n underlying: Address\n /** Wrapper symbol, e.g. `wNVDAx`. */\n symbol: string\n /** Wrapper name, e.g. `Wrapped NVIDIA xStock`. */\n name: string\n /** Wrapper (and underlying) ERC20 decimals. */\n decimals: number\n}\n\n/** Generated registry keyed by chainId. */\nexport type XstockWrapperRegistry = Partial<Record<number, XstockWrapperInfo[]>>\n\n/**\n * Per-chain lookup indices, built lazily from the static registry. Keys are\n * lowercased addresses for case-insensitive matching. Caching static config is\n * safe (it carries no dynamic on-chain data).\n */\nconst indexCache = new Map<\n number,\n { byUnderlying: Map<string, XstockWrapperInfo>; byWrapper: Map<string, XstockWrapperInfo> }\n>()\n\nfunction getIndex(chainId: number) {\n let idx = indexCache.get(chainId)\n if (!idx) {\n const byUnderlying = new Map<string, XstockWrapperInfo>()\n const byWrapper = new Map<string, XstockWrapperInfo>()\n for (const entry of XSTOCK_WRAPPERS[chainId] ?? []) {\n byUnderlying.set(entry.underlying.toLowerCase(), entry)\n byWrapper.set(entry.wrapper.toLowerCase(), entry)\n }\n idx = { byUnderlying, byWrapper }\n indexCache.set(chainId, idx)\n }\n return idx\n}\n\n/**\n * Resolve the wrapper for an unwrapped xStock. Returns `undefined` when the\n * address isn't a known xStock underlying on this chain.\n */\nexport function getXstockWrapper(\n chainId: number,\n underlying: Address,\n): XstockWrapperInfo | undefined {\n return getIndex(chainId).byUnderlying.get(underlying.toLowerCase())\n}\n\n/**\n * Resolve the underlying xStock for a wrapper address. Returns `undefined` when\n * the address isn't a known xStock wrapper on this chain.\n */\nexport function getXstockUnderlying(\n chainId: number,\n wrapper: Address,\n): XstockWrapperInfo | undefined {\n return getIndex(chainId).byWrapper.get(wrapper.toLowerCase())\n}\n\n/** True if `address` is a known unwrapped xStock on this chain. */\nexport function isXstockUnderlying(chainId: number, address: Address): boolean {\n return getXstockWrapper(chainId, address) !== undefined\n}\n\n/** True if `address` is a known xStock wrapper on this chain. */\nexport function isXstockWrapper(chainId: number, address: Address): boolean {\n return getXstockUnderlying(chainId, address) !== undefined\n}\n"],"mappings":";;;;AAYA,MAAaA,iBAA0B;;AAGvC,MAAaC,oBAA6B;;;;;;AAO1C,MAAaC,iBAA0B;;AAGvC,MAAaC,eAAgD;CAC3D,GAAG;CACH,UAAU;AACX;;AAGD,SAAgB,oBAAoBC,SAAmC;AACrE,QAAO,aAAa,OAAO,QAAQ;AACpC;;;;AC7BD,MAAa,yBAAyB;CACpC;EAAE,MAAM;EAAe,QAAQ,CAAE;EAAE,iBAAiB;CAAc;CAClE;EACE,MAAM;EACN,QAAQ,CAAE;EACV,MAAM;EACN,SAAS,CAAE;EACX,iBAAiB;CAClB;CACD;EACE,MAAM;EACN,QAAQ,CACN;GAAE,MAAM;GAA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AE,MAAM;IAAY,cAAc;IAAW,MAAM;GAAW;GAC9D;IAAE,MAAM;IAAS,cAAc;IAAW,MAAM;GAAW;GAC3D;IAAE,MAAM;IAAkB,cAAc;IAAa,MAAM;GAAa;GACxE;IAAE,MAAM;IAAyB,cAAc;IAAQ,MAAM;GAAQ;EACtE;EACD,MAAM;EACN,SAAS,CAAC;GAAE,MAAM;GAAU,cAAc;GAAW,MAAM;EAAW,CAAC;EACvE,iBAAiB;CAClB;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAA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M;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IAAE,MAAM;IAAQ,cAAc;IAAW,MAAM;IAAW,SAAS;GAAM;GACzE;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IAAE,MAAM;IAAQ,cAAc;IAAW,MAAM;IAAW,SAAS;GAAM;GACzE;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,QAAQ,CACN;GAAE,MAAM;GAAW,cAAc;GAAW,MAAM;EAAW,GAC7D;GAAE,MAAM;GAAiB,cAAc;GAAW,MAAM;EAAW,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SAAgB,gBAAgBH,SAAiBG,SAA2B;AAC1E,QAAO,oBAAoB,SAAS,QAAQ;AAC7C"}
1
+ {"version":3,"file":"index.js","names":["COW_SETTLEMENT: Address","COW_VAULT_RELAYER: Address","COW_NATIVE_ETH: Address","COW_API_URLS: Partial<Record<number, string>>","chainId: bigint | number","balanceData: bigint","value: bigint","logs: Log[]","events: PanopticEvent[]","client: PublicClient","hash: Hash","confirmations?: bigint","params: SubmitWriteParams","hash","gasOverrides: Record<string, unknown>","message: string","cause?: Error","Q192","tick: bigint","Q96","Q192","POOL_ID_MASK","Q192","MAX_UINT128","POOL_ID_MASK","MAX_UINT128","BIT_MASK_128","params: CheckCowApprovalParams","params: ApproveErc20ForCowParams","BPS_DENOMINATOR","params: PickBestVenueParams","chainId: bigint | number","chainId: bigint","cause?: Error","errorType: string","message: string","status: number","chainId: bigint","apiUrl?: string","baseUrl: string","path: string","init?: RequestInit","body: CowApiErrorBody","params: SignAndSubmitCowOrderParams","params: CancelCowOrderParams","slippageBps: bigint","params: QuoteCowSwapParams","params: GetCowOrderStatusParams","settlementTxHash: Hex | undefined","COINGECKO_CHAIN_SLUGS: Partial<Record<number, string>>","chainId: number","url: string","params: FindCowTokenParams","address: Address","XSTOCK_WRAPPERS: XstockWrapperRegistry","chainId: number","underlying: Address","wrapper: Address","address: Address"],"sources":["../../src/cow/addresses.ts","../../src/generated.ts","../../src/panoptic/v2/writes/utils.ts","../../src/panoptic/v2/errors/base.ts","../../src/panoptic/v2/errors/errorsAbi.ts","../../src/panoptic/v2/errors/parser.ts","../../src/panoptic/v2/utils/constants.ts","../../src/panoptic/v2/sync/snapshotRecovery.ts","../../src/panoptic/v2/formatters/tick.ts","../../src/panoptic/v2/utils/oraclePack.ts","../../src/panoptic/v2/utils/oracleSafeMode.ts","../../src/panoptic/v2/greeks/index.ts","../../src/panoptic/v2/tokenId/constants.ts","../../src/panoptic/v2/utils/option-encoding-v2.ts","../../src/panoptic/v2/sync/eventReconstruction.ts","../../src/panoptic/v2/formatters/rates.ts","../../src/panoptic/v2/tokenId/deriveUniqueTokenId.ts","../../src/panoptic/v2/tokenId/generateOverlapping.ts","../../src/panoptic/v2/tokenId/split.ts","../../src/panoptic/v2/writes/protectedSettle.ts","../../src/panoptic/v2/reads/positionSizes.ts","../../src/panoptic/v2/simulations/tokenFlow.ts","../../src/panoptic/v2/simulations/simulateSettle.ts","../../src/cow/approval.ts","../../src/cow/compare.ts","../../src/cow/eip712.ts","../../src/cow/errors.ts","../../src/cow/api.ts","../../src/cow/order.ts","../../src/cow/quote.ts","../../src/cow/status.ts","../../src/cow/tokens.ts","../../src/cow/xstockWrappers.generated.ts","../../src/cow/xstockWrappers.ts"],"sourcesContent":["/**\n * CoW Protocol contract addresses and order-book API endpoints.\n *\n * Both contracts are deployed deterministically (CREATE2) and share the same\n * address on every supported chain.\n *\n * @module cow/addresses\n */\n\nimport type { Address } from 'viem'\n\n/** GPv2Settlement — EIP-712 verifying contract for signed orders. */\nexport const COW_SETTLEMENT: Address = '0x9008D19f58AAbD9eD0D60971565AA8510560ab41'\n\n/** GPv2VaultRelayer — the ERC20 approval target (NOT the settlement contract). */\nexport const COW_VAULT_RELAYER: Address = '0xC92E8bdf79f0507f65a392b0ab4667716BFE0110'\n\n/**\n * Buy-token marker for native ETH. Orders buying this sentinel settle in\n * native ETH (the settlement contract unwraps WETH). Only valid on the buy\n * side — selling native ETH requires the eth-flow contract (unsupported here).\n */\nexport const COW_NATIVE_ETH: Address = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\n\n/** Order-book API base URL per chain. */\nexport const COW_API_URLS: Partial<Record<number, string>> = {\n 1: 'https://api.cow.fi/mainnet',\n 11155111: 'https://api.cow.fi/sepolia',\n}\n\n/** Whether CoW Protocol has an order book for the chain. */\nexport function isCowSupportedChain(chainId: bigint | number): boolean {\n return COW_API_URLS[Number(chainId)] !== undefined\n}\n","//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// CollateralTrackerV2\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const collateralTrackerV2Abi = [\n { type: 'constructor', inputs: [], stateMutability: 'nonpayable' },\n {\n type: 'function',\n inputs: [],\n name: 'accrueInterest',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'spender', internalType: 'address', type: 'address' },\n ],\n name: 'allowance',\n outputs: [{ name: 'allowance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'asset',\n outputs: [{ name: 'assetTokenAddress', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'assetsAndInterest',\n outputs: [\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'assetsOf',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'account', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'borrowIndex',\n outputs: [{ name: '', internalType: 'uint80', type: 'uint80' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'convertToAssets',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'convertToShares',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'decimals',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'delegatee', internalType: 'address', type: 'address' }],\n name: 'delegate',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n ],\n name: 'deposit',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getPoolData',\n outputs: [\n { name: 'depositedAssets', internalType: 'uint256', type: 'uint256' },\n { name: 'insideAMM', internalType: 'uint256', type: 'uint256' },\n { name: 'creditedShares', internalType: 'uint256', type: 'uint256' },\n {\n name: 'currentPoolUtilization',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'interestRate',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'user', internalType: 'address', type: 'address' }],\n name: 'interestState',\n outputs: [\n { name: 'userBorrowIndex', internalType: 'int128', type: 'int128' },\n { name: 'netBorrows', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'lastInteractionTimestamp',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'maxDeposit',\n outputs: [{ name: 'maxAssets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'maxMint',\n outputs: [{ name: 'maxShares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'maxRedeem',\n outputs: [{ name: 'maxShares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'maxWithdraw',\n outputs: [{ name: 'maxAssets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'shares', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n ],\n name: 'mint',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'owedInterest',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'panopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolFee',\n outputs: [{ name: '_poolFee', internalType: 'uint24', type: 'uint24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolManager',\n outputs: [{ name: '', internalType: 'contract IPoolManager', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'previewDeposit',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'previewMint',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'previewOwedInterest',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n name: 'previewRedeem',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n name: 'previewWithdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'rateAtTarget',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'shares', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n ],\n name: 'redeem',\n outputs: [{ name: 'assets', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'refunder', internalType: 'address', type: 'address' },\n { name: 'refundee', internalType: 'address', type: 'address' },\n { name: 'assets', internalType: 'int256', type: 'int256' },\n ],\n name: 'refund',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'delegatee', internalType: 'address', type: 'address' }],\n name: 'revoke',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'riskEngine',\n outputs: [{ name: '', internalType: 'contract IRiskEngine', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'optionOwner', internalType: 'address', type: 'address' },\n { name: 'longAmount', internalType: 'int128', type: 'int128' },\n { name: 'shortAmount', internalType: 'int128', type: 'int128' },\n { name: 'ammDeltaAmount', internalType: 'int128', type: 'int128' },\n { name: 'realizedPremium', internalType: 'int128', type: 'int128' },\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n ],\n name: 'settleBurn',\n outputs: [{ name: '', internalType: 'int128', type: 'int128' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'liquidator', internalType: 'address', type: 'address' },\n { name: 'liquidatee', internalType: 'address', type: 'address' },\n { name: 'bonus', internalType: 'int256', type: 'int256' },\n ],\n name: 'settleLiquidation',\n outputs: [],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'optionOwner', internalType: 'address', type: 'address' },\n { name: 'longAmount', internalType: 'int128', type: 'int128' },\n { name: 'shortAmount', internalType: 'int128', type: 'int128' },\n { name: 'ammDeltaAmount', internalType: 'int128', type: 'int128' },\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n ],\n name: 'settleMint',\n outputs: [\n { name: '', internalType: 'uint32', type: 'uint32' },\n { name: '', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'token0',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'token1',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'totalAssets',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'totalSupply',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transfer',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'underlyingIsToken0',\n outputs: [{ name: '_underlyingIsToken0', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'underlyingToken',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes', type: 'bytes' }],\n name: 'unlockCallback',\n outputs: [{ name: '', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'unrealizedGlobalInterest',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n ],\n name: 'withdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'assets', internalType: 'uint256', type: 'uint256' },\n { name: 'receiver', internalType: 'address', type: 'address' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n ],\n name: 'withdraw',\n outputs: [{ name: 'shares', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'builder',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'commissionPaidProtocol',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n {\n name: 'commissionPaidBuilder',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'CommissionPaid',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'sender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'assets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'shares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Deposit',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'interestOwed',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'interestPaid',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'sharesBurned',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'InsolvencyPenaltyApplied',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'liquidatee',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'liquidator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'protocolLossAssets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'protocolLossShares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'ProtocolLossRealized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Transfer',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'sender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'receiver',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'assets',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'shares',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'Withdraw',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'BelowMinimumRedemption' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'DepositTooLarge' },\n { type: 'error', inputs: [], name: 'ExceedsMaximumRedemption' },\n {\n type: 'error',\n inputs: [\n { name: 'tokenAddress', internalType: 'address', type: 'address' },\n { name: 'assetsRequested', internalType: 'uint256', type: 'uint256' },\n { name: 'assetBalance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'NotEnoughTokens',\n },\n { type: 'error', inputs: [], name: 'NotPanopticPool' },\n { type: 'error', inputs: [], name: 'PositionCountNotZero' },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnauthorizedUniswapCallback' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticFactoryV3\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticFactoryV3Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_SFPM',\n internalType: 'contract SemiFungiblePositionManagerV3',\n type: 'address',\n },\n {\n name: '_univ3Factory',\n internalType: 'contract IUniswapV3Factory',\n type: 'address',\n },\n { name: '_poolReference', internalType: 'address', type: 'address' },\n {\n name: '_collateralReference',\n internalType: 'address',\n type: 'address',\n },\n { name: 'properties', internalType: 'bytes32[]', type: 'bytes32[]' },\n { name: 'indices', internalType: 'uint256[][]', type: 'uint256[][]' },\n { name: 'pointers', internalType: 'Pointer[][]', type: 'uint256[][]' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'panopticPool', internalType: 'address', type: 'address' },\n { name: 'symbol0', internalType: 'string', type: 'string' },\n { name: 'symbol1', internalType: 'string', type: 'string' },\n { name: 'fee', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'constructMetadata',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token0', internalType: 'address', type: 'address' },\n { name: 'token1', internalType: 'address', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n ],\n name: 'deployNewPool',\n outputs: [\n {\n name: 'newPoolContract',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n name: 'getApproved',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'univ3pool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n ],\n name: 'getPanopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'deployerAddress', internalType: 'address', type: 'address' },\n { name: 'v3Pool', internalType: 'address', type: 'address' },\n { name: 'riskEngine', internalType: 'address', type: 'address' },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n { name: 'loops', internalType: 'uint256', type: 'uint256' },\n { name: 'minTargetRarity', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'minePoolAddress',\n outputs: [\n { name: 'bestSalt', internalType: 'uint96', type: 'uint96' },\n { name: 'highestRarity', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'id', internalType: 'uint256', type: 'uint256' }],\n name: 'ownerOf',\n outputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'tokenId', internalType: 'uint256', type: 'uint256' }],\n name: 'tokenURI',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolAddress',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n {\n name: 'uniswapPool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n indexed: true,\n },\n {\n name: 'collateralTracker0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'collateralTracker1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n indexed: false,\n },\n ],\n name: 'PoolDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Transfer',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CreateFail' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticFactoryV4\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticFactoryV4Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_SFPM',\n internalType: 'contract SemiFungiblePositionManagerV4',\n type: 'address',\n },\n {\n name: '_manager',\n internalType: 'contract IPoolManager',\n type: 'address',\n },\n { name: '_poolReference', internalType: 'address', type: 'address' },\n {\n name: '_collateralReference',\n internalType: 'address',\n type: 'address',\n },\n { name: 'properties', internalType: 'bytes32[]', type: 'bytes32[]' },\n { name: 'indices', internalType: 'uint256[][]', type: 'uint256[][]' },\n { name: 'pointers', internalType: 'Pointer[][]', type: 'uint256[][]' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'spender', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'panopticPool', internalType: 'address', type: 'address' },\n { name: 'symbol0', internalType: 'string', type: 'string' },\n { name: 'symbol1', internalType: 'string', type: 'string' },\n { name: 'fee', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'constructMetadata',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n ],\n name: 'deployNewPool',\n outputs: [\n {\n name: 'newPoolContract',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n name: 'getApproved',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'keyV4',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n ],\n name: 'getPanopticPool',\n outputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'deployerAddress', internalType: 'address', type: 'address' },\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n { name: 'riskEngine', internalType: 'address', type: 'address' },\n { name: 'salt', internalType: 'uint96', type: 'uint96' },\n { name: 'loops', internalType: 'uint256', type: 'uint256' },\n { name: 'minTargetRarity', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'minePoolAddress',\n outputs: [\n { name: 'bestSalt', internalType: 'uint96', type: 'uint96' },\n { name: 'highestRarity', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'name',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'id', internalType: 'uint256', type: 'uint256' }],\n name: 'ownerOf',\n outputs: [{ name: 'owner', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'tokenId', internalType: 'uint256', type: 'uint256' }],\n name: 'tokenURI',\n outputs: [{ name: '', internalType: 'string', type: 'string' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'to', internalType: 'address', type: 'address' },\n { name: 'id', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'spender',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Approval',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolAddress',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'collateralTracker0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'collateralTracker1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n indexed: false,\n },\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n indexed: false,\n },\n ],\n name: 'PoolDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: true },\n ],\n name: 'Transfer',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CreateFail' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticGuardian\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticGuardianAbi = [\n {\n type: 'constructor',\n inputs: [\n { name: 'guardianAdmin', internalType: 'address', type: 'address' },\n { name: 'treasurer', internalType: 'address', type: 'address' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'GUARDIAN_ADMIN',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TREASURER',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'UNLOCK_DELAY',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'address', type: 'address' }],\n name: 'builderAdminRevoked',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'cancelUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'riskEngine',\n internalType: 'contract IRiskEngine',\n type: 'address',\n },\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n { name: 'builderAdmin', internalType: 'address', type: 'address' },\n {\n name: 'builderFactory',\n internalType: 'contract BuilderFactory',\n type: 'address',\n },\n ],\n name: 'deployBuilder',\n outputs: [{ name: 'wallet', internalType: 'address', type: 'address' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'executeUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'isBuilderAdmin',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'isPoolUnlockReady',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'lockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'lockPoolAsBuilder',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'requestUnlock',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'admin', internalType: 'address', type: 'address' },\n { name: 'revoked', internalType: 'bool', type: 'bool' },\n ],\n name: 'setBuilderAdminRevoked',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: '', internalType: 'contract PanopticPoolV2', type: 'address' }],\n name: 'unlockEta',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'admin',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderAdminRestored',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'admin',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderAdminRevoked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'builderCode',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'wallet',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'BuilderDeployed',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n {\n name: 'locker',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'PoolLocked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'PoolUnlocked',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'token',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TokensCollected',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n ],\n name: 'UnlockCancelled',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n indexed: true,\n },\n { name: 'eta', internalType: 'uint256', type: 'uint256', indexed: false },\n ],\n name: 'UnlockRequested',\n },\n { type: 'error', inputs: [], name: 'InvalidBuilderCode' },\n { type: 'error', inputs: [], name: 'NoPendingUnlock' },\n { type: 'error', inputs: [], name: 'NotAuthorizedBuilder' },\n { type: 'error', inputs: [], name: 'NotFactoryAdmin' },\n { type: 'error', inputs: [], name: 'NotGuardianAdmin' },\n { type: 'error', inputs: [], name: 'NotTreasurer' },\n { type: 'error', inputs: [], name: 'UnlockAlreadyPending' },\n {\n type: 'error',\n inputs: [{ name: 'eta', internalType: 'uint256', type: 'uint256' }],\n name: 'UnlockNotReady',\n },\n { type: 'error', inputs: [], name: 'ZeroAddress' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticPoolV2\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticPoolV2Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_sfpm',\n internalType: 'contract ISemiFungiblePositionManager',\n type: 'address',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SFPM',\n outputs: [\n {\n name: '',\n internalType: 'contract ISemiFungiblePositionManager',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'minValue0', internalType: 'uint256', type: 'uint256' },\n { name: 'minValue1', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'assertMinCollateralValues',\n outputs: [],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'collateralToken0',\n outputs: [\n {\n name: '',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'collateralToken1',\n outputs: [\n {\n name: '',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'finalPositionIdList',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'positionSizes', internalType: 'uint128[]', type: 'uint128[]' },\n {\n name: 'tickAndSpreadLimits',\n internalType: 'int24[3][]',\n type: 'int24[3][]',\n },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'dispatch',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionIdListFrom',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'account', internalType: 'address', type: 'address' },\n {\n name: 'positionIdListTo',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n {\n name: 'positionIdListToFinal',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n {\n name: 'usePremiaAsCollateral',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n name: 'dispatchFrom',\n outputs: [],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'account', internalType: 'address', type: 'address' }],\n name: 'getAssetsOf',\n outputs: [\n { name: 'assets0', internalType: 'uint256', type: 'uint256' },\n { name: 'assets1', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getChunkData',\n outputs: [\n {\n name: 'liquidities0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'liquidities1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n { name: 'settled0', internalType: 'LeftRightUnsigned', type: 'uint256' },\n { name: 'settled1', internalType: 'LeftRightUnsigned', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'includePendingPremium', internalType: 'bool', type: 'bool' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getFullPositionsData',\n outputs: [\n {\n name: 'shortPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'positionBalances',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n {\n name: 'collateralRequirements',\n internalType: 'LeftRightUnsigned[]',\n type: 'uint256[]',\n },\n {\n name: 'netPremiaPerPosition',\n internalType: 'LeftRightSigned[]',\n type: 'int256[]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getOracleTicks',\n outputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'spotTick', internalType: 'int24', type: 'int24' },\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n { name: 'latestTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'builderCode', internalType: 'uint256', type: 'uint256' }],\n name: 'getRiskParameters',\n outputs: [\n {\n name: 'riskParameters',\n internalType: 'RiskParameters',\n type: 'uint256',\n },\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'getTWAP',\n outputs: [{ name: 'twapTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'isSafeMode',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'lockSafeMode',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [{ name: 'user', internalType: 'address', type: 'address' }],\n name: 'numberOfLegs',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'onERC1155Received',\n outputs: [{ name: '', internalType: 'bytes4', type: 'bytes4' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'pokeOracle',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolId',\n outputs: [{ name: '', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolKey',\n outputs: [{ name: 'key', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'poolManager',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'riskEngine',\n outputs: [{ name: '', internalType: 'contract IRiskEngine', type: 'address' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'tickSpacing',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [],\n name: 'unlockSafeMode',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'usePremiaAsCollateral', internalType: 'bool', type: 'bool' },\n ],\n name: 'validateCollateralWithdrawable',\n outputs: [],\n stateMutability: 'view',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'liquidator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'liquidatee',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'bonusAmounts',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'AccountLiquidated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'exercisor',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'user', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'exerciseFee',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'ForcedExercised',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'premiaByLeg',\n internalType: 'LeftRightSigned[4]',\n type: 'int256[4]',\n indexed: false,\n },\n ],\n name: 'OptionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'balanceData',\n internalType: 'PositionBalance',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'OptionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'user', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'legIndex',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'settledAmounts',\n internalType: 'LeftRightSigned',\n type: 'int256',\n indexed: false,\n },\n ],\n name: 'PremiumSettled',\n },\n {\n type: 'error',\n inputs: [\n { name: 'solvent', internalType: 'uint256', type: 'uint256' },\n { name: 'numberOfTicks', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'AccountInsolvent',\n },\n { type: 'error', inputs: [], name: 'AlreadyInitialized' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'DuplicateTokenId' },\n { type: 'error', inputs: [], name: 'EffectiveLiquidityAboveThreshold' },\n { type: 'error', inputs: [], name: 'InputListFail' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NetLiquidityZero' },\n { type: 'error', inputs: [], name: 'NoLegsExercisable' },\n { type: 'error', inputs: [], name: 'NotGuardian' },\n { type: 'error', inputs: [], name: 'NotMarginCalled' },\n { type: 'error', inputs: [], name: 'PositionNotOwned' },\n { type: 'error', inputs: [], name: 'PriceImpactTooLarge' },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n { type: 'error', inputs: [], name: 'StaleOracle' },\n { type: 'error', inputs: [], name: 'TokenIdHasZeroLegs' },\n { type: 'error', inputs: [], name: 'TooManyLegsOpen' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'WrongPoolId' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// PanopticQuery\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const panopticQueryAbi = [\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'checkCollateral',\n outputs: [\n {\n name: 'collateralBalances0',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'requiredCollaterals0',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'collateralBalances1',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n {\n name: 'requiredCollaterals1',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'checkCollateral',\n outputs: [\n {\n name: 'balancesAndRequired',\n internalType: 'uint256[4]',\n type: 'uint256[4]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'checkCollateralListOutput',\n outputs: [\n { name: '', internalType: 'uint256[4][]', type: 'uint256[4][]' },\n { name: '', internalType: 'int256[]', type: 'int256[]' },\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getChunkData',\n outputs: [{ name: '', internalType: 'uint256[2][4][]', type: 'uint256[2][4][]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getLiquidationPrices',\n outputs: [\n { name: 'liquidationPriceDown', internalType: 'int24', type: 'int24' },\n { name: 'liquidationPriceUp', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n ],\n name: 'getItmAmounts',\n outputs: [\n { name: 'itm0', internalType: 'int256', type: 'int256' },\n { name: 'itm1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n {\n name: 'existingPositionIds',\n internalType: 'TokenId[]',\n type: 'uint256[]',\n },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n ],\n name: 'getMaxPositionSizeBounds',\n outputs: [\n { name: 'maxSizeAtMinUtil', internalType: 'uint128', type: 'uint128' },\n { name: 'maxSizeAtMaxUtil', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'includePendingPremium', internalType: 'bool', type: 'bool' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getNetLiquidationValue',\n outputs: [\n { name: 'value0', internalType: 'int256', type: 'int256' },\n { name: 'value1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getPortfolioValue',\n outputs: [\n { name: 'value0', internalType: 'int256', type: 'int256' },\n { name: 'value1', internalType: 'int256', type: 'int256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'atTicks', internalType: 'int24[]', type: 'int24[]' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n ],\n name: 'getPortfolioValueAtTicks',\n outputs: [\n { name: 'value0', internalType: 'int256[]', type: 'int256[]' },\n { name: 'value1', internalType: 'int256[]', type: 'int256[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getRequiredBase',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'startTick', internalType: 'int24', type: 'int24' },\n { name: 'nTicks', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getTickNets',\n outputs: [\n { name: 'tickData', internalType: 'int256[]', type: 'int256[]' },\n { name: 'liquidityNets', internalType: 'int256[]', type: 'int256[]' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'isAccountSolvent',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n ],\n name: 'optimizeRiskPartners',\n outputs: [{ name: '', internalType: 'TokenId', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'pool', internalType: 'contract PanopticPool', type: 'address' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'width', internalType: 'int24', type: 'int24' },\n ],\n name: 'scanChunks',\n outputs: [\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n { name: '', internalType: 'uint128[2][]', type: 'uint128[2][]' },\n { name: '', internalType: 'uint128[2][]', type: 'uint128[2][]' },\n {\n name: '',\n internalType: 'LeftRightUnsigned[2][]',\n type: 'uint256[2][]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'self', internalType: 'TokenId', type: 'uint256' }],\n name: 'validateTokenId',\n outputs: [],\n stateMutability: 'pure',\n },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// RiskEngine\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const riskEngineAbi = [\n {\n type: 'constructor',\n inputs: [\n { name: '_crossBuffer0', internalType: 'uint256', type: 'uint256' },\n { name: '_crossBuffer1', internalType: 'uint256', type: 'uint256' },\n { name: '_guardian', internalType: 'address', type: 'address' },\n { name: '_builderFactory', internalType: 'address', type: 'address' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'ADJUSTMENT_SPEED',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BP_DECREASE_BUFFER',\n outputs: [{ name: '', internalType: 'uint32', type: 'uint32' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUILDER_FACTORY',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUILDER_SPLIT',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'BUYER_COLLATERAL_RATIO',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CROSS_BUFFER_0',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CROSS_BUFFER_1',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'CURVE_STEEPNESS',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'DECIMALS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'EMA_PERIODS',\n outputs: [{ name: '', internalType: 'uint96', type: 'uint96' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'FORCE_EXERCISE_COST',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'GUARDIAN',\n outputs: [{ name: '', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'INITIAL_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'IRM_MAX_ELAPSED_TIME',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAINT_MARGIN_RATE',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_BONUS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_CLAMP_DELTA',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_OPEN_LEGS',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_SPREAD',\n outputs: [{ name: '', internalType: 'uint24', type: 'uint24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_TICKS_DELTA',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MAX_TWAP_DELTA_DISPATCH',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'MIN_RATE_AT_TARGET',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'NOTIONAL_FEE',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'PREMIUM_FEE',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'PROTOCOL_SPLIT',\n outputs: [{ name: '', internalType: 'uint16', type: 'uint16' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SATURATED_POOL_UTIL',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'SELLER_COLLATERAL_RATIO',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TARGET_POOL_UTIL',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'TARGET_UTILIZATION',\n outputs: [{ name: '', internalType: 'int256', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'VEGOID',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'recipient', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'collect',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'computeInternalMedian',\n outputs: [\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n {\n name: 'updatedOraclePack',\n internalType: 'OraclePack',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'int256', type: 'int256' },\n { name: 'crossBuffer', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'crossBufferRatio',\n outputs: [{ name: '', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oracleTick', internalType: 'int24', type: 'int24' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n {\n name: 'positionBalance',\n internalType: 'PositionBalance',\n type: 'uint256',\n },\n ],\n name: 'exerciseCost',\n outputs: [{ name: 'exerciseFees', internalType: 'LeftRightSigned', type: 'int256' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'builderCode', internalType: 'uint256', type: 'uint256' }],\n name: 'getFeeRecipient',\n outputs: [{ name: 'feeRecipient', internalType: 'address', type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'tokenData0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'tokenData1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n { name: 'atSqrtPriceX96', internalType: 'uint160', type: 'uint160' },\n { name: 'netPaid', internalType: 'LeftRightSigned', type: 'int256' },\n {\n name: 'shortPremium',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'loanAmounts',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n name: 'getLiquidationBonus',\n outputs: [\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'user', internalType: 'address', type: 'address' },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'shortPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n name: 'getMargin',\n outputs: [\n {\n name: 'tokenData0',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'tokenData1',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'globalUtilizations',\n internalType: 'PositionBalance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: '_oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n name: 'getOracleTicks',\n outputs: [\n { name: 'spotTick', internalType: 'int24', type: 'int24' },\n { name: 'medianTick', internalType: 'int24', type: 'int24' },\n { name: 'latestTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n ],\n name: 'getPerPositionCollateralRequirements',\n outputs: [\n {\n name: 'collateralRequirements',\n internalType: 'LeftRightUnsigned[]',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'payor', internalType: 'address', type: 'address' },\n { name: 'fees', internalType: 'LeftRightSigned', type: 'int256' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n ],\n name: 'getRefundAmounts',\n outputs: [{ name: '', internalType: 'LeftRightSigned', type: 'int256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'builderCode', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getRiskParameters',\n outputs: [{ name: '', internalType: 'RiskParameters', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: '_oraclePack', internalType: 'OraclePack', type: 'uint256' },\n { name: 'safeMode', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getSolvencyTicks',\n outputs: [\n { name: '', internalType: 'int24[]', type: 'int24[]' },\n { name: '', internalType: 'OraclePack', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n {\n name: 'premiasByLeg',\n internalType: 'LeftRightSigned[4][]',\n type: 'int256[4][]',\n },\n {\n name: 'collateralRemaining',\n internalType: 'LeftRightSigned',\n type: 'int256',\n },\n { name: 'atSqrtPriceX96', internalType: 'uint160', type: 'uint160' },\n ],\n name: 'haircutPremia',\n outputs: [\n { name: 'bonusDeltas', internalType: 'LeftRightSigned', type: 'int256' },\n {\n name: 'haircutTotal',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'haircutPerLeg',\n internalType: 'LeftRightSigned[4][]',\n type: 'int256[4][]',\n },\n ],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'uint256', type: 'uint256' },\n {\n name: 'interestRateAccumulator',\n internalType: 'MarketState',\n type: 'uint256',\n },\n ],\n name: 'interestRate',\n outputs: [{ name: '', internalType: 'uint128', type: 'uint128' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'positionBalanceArray',\n internalType: 'PositionBalance[]',\n type: 'uint256[]',\n },\n { name: 'positionIdList', internalType: 'TokenId[]', type: 'uint256[]' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'user', internalType: 'address', type: 'address' },\n {\n name: 'shortPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'longPremia',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n {\n name: 'ct0',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n {\n name: 'ct1',\n internalType: 'contract CollateralTrackerV2',\n type: 'address',\n },\n { name: 'buffer', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'isAccountSolvent',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'currentTick', internalType: 'int24', type: 'int24' },\n { name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' },\n ],\n name: 'isSafeMode',\n outputs: [{ name: 'safeMode', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'lockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'oraclePack', internalType: 'OraclePack', type: 'uint256' }],\n name: 'twapEMA',\n outputs: [{ name: '', internalType: 'int24', type: 'int24' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'pool',\n internalType: 'contract PanopticPoolV2',\n type: 'address',\n },\n ],\n name: 'unlockPool',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'utilization', internalType: 'uint256', type: 'uint256' },\n {\n name: 'interestRateAccumulator',\n internalType: 'MarketState',\n type: 'uint256',\n },\n ],\n name: 'updateInterestRate',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [],\n name: 'vegoid',\n outputs: [{ name: '', internalType: 'uint8', type: 'uint8' }],\n stateMutability: 'pure',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'collateralToken',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'avgBorrowRate',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n {\n name: 'rateAtTarget',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'BorrowRateUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [{ name: 'lockMode', internalType: 'bool', type: 'bool', indexed: false }],\n name: 'GuardianSafeModeUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'token',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TokensCollected',\n },\n { type: 'error', inputs: [], name: 'BelowMinimumRedemption' },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'InvalidBuilderCode' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'LengthMismatch' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotGuardian' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// SemiFungiblePositionManagerV3\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const semiFungiblePositionManagerV3Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: '_factory',\n internalType: 'contract IUniswapV3Factory',\n type: 'address',\n },\n {\n name: '_minEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_supplyMultiplierTickFill',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owners', internalType: 'address[]', type: 'address[]' },\n { name: 'ids', internalType: 'uint256[]', type: 'uint256[]' },\n ],\n name: 'balanceOfBatch',\n outputs: [{ name: 'balances', internalType: 'uint256[]', type: 'uint256[]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'burnTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'expandEnforcedTickRange',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountFeesBase',\n outputs: [\n { name: 'feesBase0', internalType: 'int128', type: 'int128' },\n { name: 'feesBase1', internalType: 'int128', type: 'int128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountLiquidity',\n outputs: [\n {\n name: 'accountLiquidities',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'isLong', internalType: 'uint256', type: 'uint256' },\n { name: 'vegoid', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getAccountPremium',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolKey', internalType: 'bytes', type: 'bytes' }],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getEnforcedTickLimits',\n outputs: [\n { name: '', internalType: 'int24', type: 'int24' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'id', internalType: 'bytes', type: 'bytes' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getPoolId',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getUniswapV3PoolFromId',\n outputs: [\n {\n name: 'uniswapV3Pool',\n internalType: 'contract IUniswapV3Pool',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'token0', internalType: 'address', type: 'address' },\n { name: 'token1', internalType: 'address', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'initializeAMMPool',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'operator', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: 'approvedForAll', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'mintTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'amount0Owed', internalType: 'uint256', type: 'uint256' },\n { name: 'amount1Owed', internalType: 'uint256', type: 'uint256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'uniswapV3MintCallback',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'amount0Delta', internalType: 'int256', type: 'int256' },\n { name: 'amount1Delta', internalType: 'int256', type: 'int256' },\n { name: 'data', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'uniswapV3SwapCallback',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'uniswapPool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'EnforcedTicksUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'univ3pool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenType',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'tickLower',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'tickUpper',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'liquidityDelta',\n internalType: 'int128',\n type: 'int128',\n indexed: false,\n },\n ],\n name: 'LiquidityChunkUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'uniswapPool',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'poolId',\n internalType: 'uint64',\n type: 'uint64',\n indexed: false,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'PoolInitialized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'caller',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'ids',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n {\n name: 'amounts',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n ],\n name: 'TransferBatch',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: false },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TransferSingle',\n },\n { type: 'error', inputs: [], name: 'CastingError' },\n { type: 'error', inputs: [], name: 'ChunkHasZeroLiquidity' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'InvalidUniswapCallback' },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotAuthorized' },\n { type: 'error', inputs: [], name: 'NotEnoughLiquidityInChunk' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'PositionTooLarge' },\n {\n type: 'error',\n inputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n name: 'PriceBoundFail',\n },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n {\n type: 'error',\n inputs: [\n { name: 'token', internalType: 'address', type: 'address' },\n { name: 'from', internalType: 'address', type: 'address' },\n { name: 'amount', internalType: 'uint256', type: 'uint256' },\n { name: 'balance', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'TransferFailed',\n },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'UnsafeRecipient' },\n { type: 'error', inputs: [], name: 'WrongUniswapPool' },\n] as const\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// SemiFungiblePositionManagerV4\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport const semiFungiblePositionManagerV4Abi = [\n {\n type: 'constructor',\n inputs: [\n {\n name: 'poolManager',\n internalType: 'contract IPoolManager',\n type: 'address',\n },\n {\n name: '_minEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_nativeEnforcedTickFillCost',\n internalType: 'uint256',\n type: 'uint256',\n },\n {\n name: '_supplyMultiplierTickFill',\n internalType: 'uint256',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'account', internalType: 'address', type: 'address' },\n { name: 'tokenId', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'balanceOf',\n outputs: [{ name: 'balance', internalType: 'uint256', type: 'uint256' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owners', internalType: 'address[]', type: 'address[]' },\n { name: 'ids', internalType: 'uint256[]', type: 'uint256[]' },\n ],\n name: 'balanceOfBatch',\n outputs: [{ name: 'balances', internalType: 'uint256[]', type: 'uint256[]' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'burnTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'expandEnforcedTickRange',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n ],\n name: 'getAccountLiquidity',\n outputs: [\n {\n name: 'accountLiquidities',\n internalType: 'LeftRightUnsigned',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'tokenType', internalType: 'uint256', type: 'uint256' },\n { name: 'tickLower', internalType: 'int24', type: 'int24' },\n { name: 'tickUpper', internalType: 'int24', type: 'int24' },\n { name: 'atTick', internalType: 'int24', type: 'int24' },\n { name: 'isLong', internalType: 'uint256', type: 'uint256' },\n { name: 'vegoid', internalType: 'uint256', type: 'uint256' },\n ],\n name: 'getAccountPremium',\n outputs: [\n { name: '', internalType: 'uint128', type: 'uint128' },\n { name: '', internalType: 'uint128', type: 'uint128' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolKey', internalType: 'bytes', type: 'bytes' }],\n name: 'getCurrentTick',\n outputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getEnforcedTickLimits',\n outputs: [\n { name: '', internalType: 'int24', type: 'int24' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'id', internalType: 'bytes', type: 'bytes' },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'getPoolId',\n outputs: [{ name: '', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n name: 'getUniswapV4PoolKeyFromId',\n outputs: [\n {\n name: '',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n {\n name: 'key',\n internalType: 'struct PoolKey',\n type: 'tuple',\n components: [\n { name: 'currency0', internalType: 'Currency', type: 'address' },\n { name: 'currency1', internalType: 'Currency', type: 'address' },\n { name: 'fee', internalType: 'uint24', type: 'uint24' },\n { name: 'tickSpacing', internalType: 'int24', type: 'int24' },\n { name: 'hooks', internalType: 'contract IHooks', type: 'address' },\n ],\n },\n { name: 'vegoid', internalType: 'uint8', type: 'uint8' },\n ],\n name: 'initializeAMMPool',\n outputs: [{ name: 'poolId', internalType: 'uint64', type: 'uint64' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [\n { name: 'owner', internalType: 'address', type: 'address' },\n { name: 'operator', internalType: 'address', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: 'approvedForAll', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: 'poolKey', internalType: 'bytes', type: 'bytes' },\n { name: 'tokenId', internalType: 'TokenId', type: 'uint256' },\n { name: 'positionSize', internalType: 'uint128', type: 'uint128' },\n { name: 'tickLimitLow', internalType: 'int24', type: 'int24' },\n { name: 'tickLimitHigh', internalType: 'int24', type: 'int24' },\n ],\n name: 'mintTokenizedPosition',\n outputs: [\n { name: '', internalType: 'LeftRightUnsigned[4]', type: 'uint256[4]' },\n { name: '', internalType: 'LeftRightSigned', type: 'int256' },\n { name: '', internalType: 'int24', type: 'int24' },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes[]', type: 'bytes[]' }],\n name: 'multicall',\n outputs: [{ name: 'results', internalType: 'bytes[]', type: 'bytes[]' }],\n stateMutability: 'payable',\n },\n {\n type: 'function',\n inputs: [],\n name: 'reentrancyGuardEntered',\n outputs: [{ name: 'entered', internalType: 'bool', type: 'bool' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'uint256[]', type: 'uint256[]' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'address', type: 'address' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'uint256', type: 'uint256' },\n { name: '', internalType: 'bytes', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [\n { name: 'operator', internalType: 'address', type: 'address' },\n { name: 'approved', internalType: 'bool', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n inputs: [{ name: 'interfaceId', internalType: 'bytes4', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', internalType: 'bool', type: 'bool' }],\n stateMutability: 'pure',\n },\n {\n type: 'function',\n inputs: [{ name: 'data', internalType: 'bytes', type: 'bytes' }],\n name: 'unlockCallback',\n outputs: [{ name: '', internalType: 'bytes', type: 'bytes' }],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'approved', internalType: 'bool', type: 'bool', indexed: false },\n ],\n name: 'ApprovalForAll',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'EnforcedTicksUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'poolId',\n internalType: 'PoolId',\n type: 'bytes32',\n indexed: true,\n },\n {\n name: 'owner',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenType',\n internalType: 'uint256',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'tickLower',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'tickUpper',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'liquidityDelta',\n internalType: 'int128',\n type: 'int128',\n indexed: false,\n },\n ],\n name: 'LiquidityChunkUpdated',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n { name: 'idV4', internalType: 'PoolId', type: 'bytes32', indexed: true },\n {\n name: 'poolId',\n internalType: 'uint64',\n type: 'uint64',\n indexed: false,\n },\n {\n name: 'minEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n {\n name: 'maxEnforcedTick',\n internalType: 'int24',\n type: 'int24',\n indexed: false,\n },\n ],\n name: 'PoolInitialized',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'recipient',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionBurnt',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'caller',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n {\n name: 'tokenId',\n internalType: 'TokenId',\n type: 'uint256',\n indexed: true,\n },\n {\n name: 'positionSize',\n internalType: 'uint128',\n type: 'uint128',\n indexed: false,\n },\n ],\n name: 'TokenizedPositionMinted',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n {\n name: 'ids',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n {\n name: 'amounts',\n internalType: 'uint256[]',\n type: 'uint256[]',\n indexed: false,\n },\n ],\n name: 'TransferBatch',\n },\n {\n type: 'event',\n anonymous: false,\n inputs: [\n {\n name: 'operator',\n internalType: 'address',\n type: 'address',\n indexed: true,\n },\n { name: 'from', internalType: 'address', type: 'address', indexed: true },\n { name: 'to', internalType: 'address', type: 'address', indexed: true },\n { name: 'id', internalType: 'uint256', type: 'uint256', indexed: false },\n {\n name: 'amount',\n internalType: 'uint256',\n type: 'uint256',\n indexed: false,\n },\n ],\n name: 'TransferSingle',\n },\n { type: 'error', inputs: [], name: 'ChunkHasZeroLiquidity' },\n { type: 'error', inputs: [], name: 'InvalidTick' },\n { type: 'error', inputs: [], name: 'InvalidTickBound' },\n {\n type: 'error',\n inputs: [{ name: 'parameterType', internalType: 'uint256', type: 'uint256' }],\n name: 'InvalidTokenIdParameter',\n },\n { type: 'error', inputs: [], name: 'LiquidityTooHigh' },\n { type: 'error', inputs: [], name: 'NotAuthorized' },\n { type: 'error', inputs: [], name: 'NotEnoughLiquidityInChunk' },\n { type: 'error', inputs: [], name: 'PoolNotInitialized' },\n { type: 'error', inputs: [], name: 'PositionTooLarge' },\n {\n type: 'error',\n inputs: [{ name: 'currentTick', internalType: 'int24', type: 'int24' }],\n name: 'PriceBoundFail',\n },\n { type: 'error', inputs: [], name: 'Reentrancy' },\n { type: 'error', inputs: [], name: 'UnauthorizedUniswapCallback' },\n { type: 'error', inputs: [], name: 'UnderOverFlow' },\n { type: 'error', inputs: [], name: 'UnsafeRecipient' },\n { type: 'error', inputs: [], name: 'WrongUniswapPool' },\n] as const\n","/**\n * Write utilities for the Panoptic v2 SDK.\n * @module v2/writes/utils\n */\n\nimport type { Abi, Address, Hash, Log, PublicClient, WalletClient } from 'viem'\nimport { decodeEventLog, encodeFunctionData } from 'viem'\n\nimport { collateralTrackerV2Abi, panopticPoolV2Abi } from '../../../generated'\nimport type { PanopticEvent, TxOverrides, TxReceipt, TxResult } from '../types'\n\n/**\n * Decode PositionBalance packed data.\n *\n * Layout (from LSB to MSB):\n * - positionSize: bits 0-127 (uint128)\n * - poolUtilization0: bits 128-143 (uint16)\n * - poolUtilization1: bits 144-159 (uint16)\n * - tickAtMint: bits 160-183 (int24)\n * - timestampAtMint: bits 184-215 (uint32)\n * - blockAtMint: bits 216-254 (uint39)\n * - swapAtMint: bit 255 (bool)\n */\nexport function decodePositionBalance(balanceData: bigint): {\n positionSize: bigint\n poolUtilization0: bigint\n poolUtilization1: bigint\n tickAtMint: bigint\n timestampAtMint: bigint\n blockAtMint: bigint\n swapAtMint: boolean\n} {\n const positionSize = balanceData & ((1n << 128n) - 1n)\n const poolUtilization0 = (balanceData >> 128n) & 0xffffn\n const poolUtilization1 = (balanceData >> 144n) & 0xffffn\n\n // tickAtMint is int24 at bits 160-183\n let tickAtMint = (balanceData >> 160n) & 0xffffffn\n // Sign extend if negative (int24)\n if (tickAtMint > 0x7fffffn) {\n tickAtMint = tickAtMint - 0x1000000n\n }\n\n // timestampAtMint is uint32 at bits 184-215\n const timestampAtMint = (balanceData >> 184n) & 0xffffffffn\n\n // blockAtMint is uint39 at bits 216-254\n const blockAtMint = (balanceData >> 216n) & ((1n << 39n) - 1n)\n\n // swapAtMint is bool at bit 255\n const swapAtMint = balanceData >> 255n === 1n\n\n return {\n positionSize,\n poolUtilization0,\n poolUtilization1,\n tickAtMint,\n timestampAtMint,\n blockAtMint,\n swapAtMint,\n }\n}\n\n/**\n * Decode LeftRightSigned packed value.\n */\nexport function decodeLeftRightSigned(value: bigint): { right: bigint; left: bigint } {\n // Right is bits 0-127 (token0), Left is bits 128-255 (token1)\n // Both are signed int128\n let right = value & ((1n << 128n) - 1n)\n let left = value >> 128n\n\n // Sign extend right if needed\n if (right >= 1n << 127n) {\n right = right - (1n << 128n)\n }\n // Sign extend left if needed\n if (left >= 1n << 127n) {\n left = left - (1n << 128n)\n }\n\n return { right, left }\n}\n\n/**\n * Decode LeftRightUnsigned packed value.\n */\nexport function decodeLeftRightUnsigned(value: bigint): { right: bigint; left: bigint } {\n // Right is bits 0-127 (token0), Left is bits 128-255 (token1)\n // Both are unsigned uint128\n const right = value & ((1n << 128n) - 1n)\n const left = value >> 128n\n\n return { right, left }\n}\n\n/**\n * Parse Panoptic events from transaction logs.\n *\n * @param logs - The transaction logs\n * @returns Parsed Panoptic events\n */\nexport function parsePanopticEvents(logs: Log[]): PanopticEvent[] {\n const events: PanopticEvent[] = []\n\n // Try to decode each log with known ABIs\n for (const log of logs) {\n const baseEvent = {\n blockNumber: log.blockNumber ?? 0n,\n blockHash: (log.blockHash ??\n '0x0000000000000000000000000000000000000000000000000000000000000000') as Hash,\n transactionHash: log.transactionHash ?? ('0x' as Hash),\n logIndex: BigInt(log.logIndex ?? 0),\n }\n\n try {\n // Try PanopticPool events\n const poolEvent = decodeEventLog({\n abi: panopticPoolV2Abi,\n data: log.data,\n topics: log.topics,\n })\n\n if (poolEvent.eventName === 'OptionMinted') {\n const args = poolEvent.args as {\n recipient: `0x${string}`\n tokenId: bigint\n balanceData: bigint\n }\n const balance = decodePositionBalance(args.balanceData)\n events.push({\n type: 'OptionMinted',\n ...baseEvent,\n recipient: args.recipient,\n tokenId: args.tokenId,\n positionSize: balance.positionSize,\n poolUtilization0: balance.poolUtilization0,\n poolUtilization1: balance.poolUtilization1,\n tickAtMint: balance.tickAtMint,\n timestampAtMint: balance.timestampAtMint,\n blockAtMint: balance.blockAtMint,\n swapAtMint: balance.swapAtMint,\n })\n } else if (poolEvent.eventName === 'OptionBurnt') {\n const args = poolEvent.args as {\n recipient: `0x${string}`\n tokenId: bigint\n positionSize: bigint\n premiaByLeg: readonly bigint[]\n }\n events.push({\n type: 'OptionBurnt',\n ...baseEvent,\n recipient: args.recipient,\n tokenId: args.tokenId,\n positionSize: args.positionSize,\n premiaByLeg: [\n args.premiaByLeg[0] ?? 0n,\n args.premiaByLeg[1] ?? 0n,\n args.premiaByLeg[2] ?? 0n,\n args.premiaByLeg[3] ?? 0n,\n ] as const,\n })\n } else if (poolEvent.eventName === 'AccountLiquidated') {\n const args = poolEvent.args as {\n liquidator: `0x${string}`\n liquidatee: `0x${string}`\n bonusAmounts: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.bonusAmounts)\n events.push({\n type: 'AccountLiquidated',\n ...baseEvent,\n liquidator: args.liquidator,\n liquidatee: args.liquidatee,\n bonusAmount0: right,\n bonusAmount1: left,\n })\n } else if (poolEvent.eventName === 'ForcedExercised') {\n const args = poolEvent.args as {\n exercisor: `0x${string}`\n user: `0x${string}`\n tokenId: bigint\n exerciseFee: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.exerciseFee)\n events.push({\n type: 'ForcedExercised',\n ...baseEvent,\n exercisor: args.exercisor,\n user: args.user,\n tokenId: args.tokenId,\n exerciseFee0: right,\n exerciseFee1: left,\n })\n } else if (poolEvent.eventName === 'PremiumSettled') {\n const args = poolEvent.args as {\n user: `0x${string}`\n tokenId: bigint\n legIndex: bigint\n settledAmounts: bigint\n }\n const { right, left } = decodeLeftRightSigned(args.settledAmounts)\n events.push({\n type: 'PremiumSettled',\n ...baseEvent,\n user: args.user,\n tokenId: args.tokenId,\n legIndex: args.legIndex,\n settledAmount0: right,\n settledAmount1: left,\n })\n }\n } catch {\n // Not a PanopticPool event, try CollateralTracker\n try {\n const collateralEvent = decodeEventLog({\n abi: collateralTrackerV2Abi,\n data: log.data,\n topics: log.topics,\n })\n\n if (collateralEvent.eventName === 'Deposit') {\n const args = collateralEvent.args as {\n sender: `0x${string}`\n owner: `0x${string}`\n assets: bigint\n shares: bigint\n }\n events.push({\n type: 'Deposit',\n ...baseEvent,\n sender: args.sender,\n owner: args.owner,\n assets: args.assets,\n shares: args.shares,\n })\n } else if (collateralEvent.eventName === 'Withdraw') {\n const args = collateralEvent.args as {\n sender: `0x${string}`\n receiver: `0x${string}`\n owner: `0x${string}`\n assets: bigint\n shares: bigint\n }\n events.push({\n type: 'Withdraw',\n ...baseEvent,\n sender: args.sender,\n receiver: args.receiver,\n owner: args.owner,\n assets: args.assets,\n shares: args.shares,\n })\n }\n } catch {\n // Unknown event, skip\n }\n }\n }\n\n return events\n}\n\n/**\n * Create a TxResult from a transaction hash.\n *\n * @param client - The public client\n * @param hash - The transaction hash\n * @returns TxResult with wait function\n */\nexport function createTxResult(client: PublicClient, hash: Hash): TxResult {\n return {\n hash,\n wait: async (confirmations?: bigint): Promise<TxReceipt> => {\n const receipt = await client.waitForTransactionReceipt({\n hash,\n confirmations: confirmations !== undefined ? Number(confirmations) : undefined,\n })\n\n const events = parsePanopticEvents(receipt.logs)\n\n return {\n hash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n blockHash: receipt.blockHash,\n gasUsed: receipt.gasUsed,\n status: receipt.status === 'success' ? 'success' : 'reverted',\n events,\n }\n },\n }\n}\n\n/**\n * Execute a write operation and return TxResult.\n *\n * @param client - The public client\n * @param hashPromise - Promise that resolves to transaction hash\n * @returns TxResult\n */\nexport async function executeWrite(\n client: PublicClient,\n hashPromise: Promise<Hash>,\n): Promise<TxResult> {\n const hash = await hashPromise\n return createTxResult(client, hash)\n}\n\n/**\n * Execute a write operation and wait for receipt.\n *\n * @param client - The public client\n * @param hashPromise - Promise that resolves to transaction hash\n * @param confirmations - Number of confirmations to wait for\n * @returns TxReceipt\n */\nexport async function executeWriteAndWait(\n client: PublicClient,\n hashPromise: Promise<Hash>,\n confirmations?: bigint,\n): Promise<TxReceipt> {\n const result = await executeWrite(client, hashPromise)\n return result.wait(confirmations)\n}\n\n/**\n * Parameters for the submitWrite helper.\n */\nexport interface SubmitWriteParams {\n /** Public client */\n client: PublicClient\n /** Wallet client */\n walletClient: WalletClient\n /** Account address */\n account: Address\n /** Contract address */\n address: Address\n /** Contract ABI */\n abi: Abi\n /** Function name to call */\n functionName: string\n /** Function arguments */\n args: readonly unknown[]\n /** ETH value to send with the transaction (for native ETH deposits) */\n value?: bigint\n /** Optional gas and transaction overrides */\n txOverrides?: TxOverrides\n}\n\n/**\n * Submit a write operation, supporting both direct wallet submission\n * and custom broadcaster paths with gas overrides.\n *\n * Normal path (no broadcaster): calls walletClient.writeContract() with gas overrides.\n * Broadcaster path: prepareTransactionRequest → apply overrides → signTransaction → broadcast.\n *\n * @param params - Submit write parameters\n * @returns TxResult\n */\nexport async function submitWrite(params: SubmitWriteParams): Promise<TxResult> {\n const { client, walletClient, account, address, abi, functionName, args, value, txOverrides } =\n params\n\n const broadcaster = txOverrides?.broadcaster\n\n if (broadcaster) {\n // Encode contract calldata before request preparation so gas/tx params\n // are derived from the exact call being signed and broadcast.\n const data = encodeFunctionData({ abi, functionName, args })\n\n // Broadcaster path: prepare → sign → broadcast\n const broadcastAccount = walletClient.account ?? account\n const request = await walletClient.prepareTransactionRequest({\n account: broadcastAccount,\n to: address,\n chain: walletClient.chain,\n data,\n ...(value !== undefined && { value }),\n ...(txOverrides?.maxFeePerGas !== undefined && { maxFeePerGas: txOverrides.maxFeePerGas }),\n ...(txOverrides?.maxPriorityFeePerGas !== undefined && {\n maxPriorityFeePerGas: txOverrides.maxPriorityFeePerGas,\n }),\n ...(txOverrides?.gas !== undefined && { gas: txOverrides.gas }),\n ...(txOverrides?.nonce !== undefined && { nonce: Number(txOverrides.nonce) }),\n })\n\n const signedTx = await walletClient.signTransaction({\n ...request,\n account: broadcastAccount,\n } as unknown as Parameters<WalletClient['signTransaction']>[0])\n\n const hash = await broadcaster.broadcast(signedTx)\n return createTxResult(client, hash)\n }\n\n // Normal path: direct writeContract with gas overrides\n const gasOverrides: Record<string, unknown> = {}\n if (txOverrides?.maxFeePerGas !== undefined) {\n gasOverrides.maxFeePerGas = txOverrides.maxFeePerGas\n }\n if (txOverrides?.maxPriorityFeePerGas !== undefined) {\n gasOverrides.maxPriorityFeePerGas = txOverrides.maxPriorityFeePerGas\n }\n if (txOverrides?.nonce !== undefined) {\n gasOverrides.nonce = Number(txOverrides.nonce)\n }\n\n // Use the walletClient's local account (if available) for local signing.\n // Passing a string address triggers eth_sendTransaction (remote signing),\n // which fails with hosted RPC providers like Alchemy/Infura.\n const resolvedAccount = walletClient.account ?? account\n\n // If no explicit gas override, estimate with a 20% buffer.\n // Panoptic dispatch calls are gas-heavy and viem's default estimate can be tight.\n if (txOverrides?.gas !== undefined) {\n gasOverrides.gas = txOverrides.gas\n } else {\n const estimated = await client.estimateContractGas({\n address,\n abi,\n functionName,\n args,\n account: resolvedAccount,\n ...(value !== undefined && { value }),\n } as Parameters<typeof client.estimateContractGas>[0])\n gasOverrides.gas = (estimated * 120n) / 100n\n }\n\n const hash = await walletClient.writeContract({\n address,\n abi,\n functionName,\n args,\n account: resolvedAccount,\n chain: walletClient.chain,\n ...(value !== undefined && { value }),\n ...gasOverrides,\n })\n\n return createTxResult(client, hash)\n}\n\n/**\n * Parameters required for all write operations.\n */\nexport interface BaseWriteParams {\n /** Public client for reading state */\n client: PublicClient\n}\n","/**\n * Base error class for the Panoptic v2 SDK.\n * @module v2/errors/base\n */\n\n/**\n * Base error class for all Panoptic SDK errors.\n * All errors thrown by the SDK extend this class.\n *\n * @example\n * ```typescript\n * try {\n * await openPosition(config, params)\n * } catch (error) {\n * if (error instanceof PanopticError) {\n * console.log('Panoptic error:', error.name, error.message)\n * console.log('Original cause:', error.cause)\n * }\n * }\n * ```\n */\nexport class PanopticError extends Error {\n override readonly name: string = 'PanopticError'\n\n /** The Solidity error name (e.g. 'PriceBoundFail', 'InputListFail'). Set by the parser. */\n errorName?: string\n\n /**\n * Creates a new PanopticError.\n *\n * @param message - Human-readable error message\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n message: string,\n public readonly cause?: Error,\n ) {\n super(message)\n\n // Maintains proper stack trace for where error was thrown (V8 only)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // Ensure prototype chain is correctly set up\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Custom error ABI definitions for Panoptic v2 contracts.\n *\n * Contains all custom errors from Errors.sol with their signatures.\n * Used for decoding contract revert data.\n *\n * Selectors sourced from `forge selectors list` output.\n *\n * @module v2/errors/errorsAbi\n */\n\n/**\n * All custom errors from Panoptic Errors.sol\n *\n * Selector computation: keccak256(errorSignature)[:4]\n */\nexport const panopticErrorsAbi = [\n // AccountInsolvent(uint256 solvent, uint256 numberOfTicks) - 0xcdef092d\n {\n type: 'error',\n name: 'AccountInsolvent',\n inputs: [\n { name: 'solvent', type: 'uint256' },\n { name: 'numberOfTicks', type: 'uint256' },\n ],\n },\n\n // AlreadyInitialized() - 0x0dc149f0\n {\n type: 'error',\n name: 'AlreadyInitialized',\n inputs: [],\n },\n\n // BelowMinimumRedemption() - 0x13185bd7\n {\n type: 'error',\n name: 'BelowMinimumRedemption',\n inputs: [],\n },\n\n // CastingError() - 0xb6680045\n {\n type: 'error',\n name: 'CastingError',\n inputs: [],\n },\n\n // ChunkHasZeroLiquidity() - 0x126ae3af\n {\n type: 'error',\n name: 'ChunkHasZeroLiquidity',\n inputs: [],\n },\n\n // CreateFail() - 0xebfef188\n {\n type: 'error',\n name: 'CreateFail',\n inputs: [],\n },\n\n // DepositTooLarge() - 0xc56d46d3\n {\n type: 'error',\n name: 'DepositTooLarge',\n inputs: [],\n },\n\n // DuplicateTokenId() - 0x2bd1a05a\n {\n type: 'error',\n name: 'DuplicateTokenId',\n inputs: [],\n },\n\n // EffectiveLiquidityAboveThreshold() - 0x3a8795c2\n {\n type: 'error',\n name: 'EffectiveLiquidityAboveThreshold',\n inputs: [],\n },\n\n // ExceedsMaximumRedemption() - 0x20adf2ea\n {\n type: 'error',\n name: 'ExceedsMaximumRedemption',\n inputs: [],\n },\n\n // InputListFail() - 0x99e877ce\n {\n type: 'error',\n name: 'InputListFail',\n inputs: [],\n },\n\n // InsufficientCreditLiquidity() - 0x7a70c281\n {\n type: 'error',\n name: 'InsufficientCreditLiquidity',\n inputs: [],\n },\n\n // InvalidBuilderCode() - 0x15b3fb46\n {\n type: 'error',\n name: 'InvalidBuilderCode',\n inputs: [],\n },\n\n // InvalidTick() - 0xce8ef7fc\n {\n type: 'error',\n name: 'InvalidTick',\n inputs: [],\n },\n\n // InvalidTickBound() - 0x1577d966\n {\n type: 'error',\n name: 'InvalidTickBound',\n inputs: [],\n },\n\n // InvalidTokenIdParameter(uint256 parameterType) - 0x93db0263\n {\n type: 'error',\n name: 'InvalidTokenIdParameter',\n inputs: [{ name: 'parameterType', type: 'uint256' }],\n },\n\n // InvalidUniswapCallback() - 0x3a94c705\n {\n type: 'error',\n name: 'InvalidUniswapCallback',\n inputs: [],\n },\n\n // LengthMismatch() - 0xff633a38\n {\n type: 'error',\n name: 'LengthMismatch',\n inputs: [],\n },\n\n // LiquidityTooHigh() - 0xa500e7ea\n {\n type: 'error',\n name: 'LiquidityTooHigh',\n inputs: [],\n },\n\n // NetLiquidityZero() - 0x73582ea0\n {\n type: 'error',\n name: 'NetLiquidityZero',\n inputs: [],\n },\n\n // NoLegsExercisable() - 0x7721f7da\n {\n type: 'error',\n name: 'NoLegsExercisable',\n inputs: [],\n },\n\n // NotALongLeg() - 0xb7d44f76\n {\n type: 'error',\n name: 'NotALongLeg',\n inputs: [],\n },\n\n // NotBuilder() - 0x0404714e\n {\n type: 'error',\n name: 'NotBuilder',\n inputs: [],\n },\n\n // NotEnoughLiquidityInChunk() - 0xc56d518e\n {\n type: 'error',\n name: 'NotEnoughLiquidityInChunk',\n inputs: [],\n },\n\n // NotEnoughTokens(address tokenAddress, uint256 assetsRequested, uint256 assetBalance) - 0x71c3730b\n {\n type: 'error',\n name: 'NotEnoughTokens',\n inputs: [\n { name: 'tokenAddress', type: 'address' },\n { name: 'assetsRequested', type: 'uint256' },\n { name: 'assetBalance', type: 'uint256' },\n ],\n },\n\n // NotGuardian() - 0xef6d0f02\n {\n type: 'error',\n name: 'NotGuardian',\n inputs: [],\n },\n\n // NotMarginCalled() - 0x2a23f1ad\n {\n type: 'error',\n name: 'NotMarginCalled',\n inputs: [],\n },\n\n // NotPanopticPool() - 0x2dd1912a\n {\n type: 'error',\n name: 'NotPanopticPool',\n inputs: [],\n },\n\n // PoolNotInitialized() - 0x486aa307\n {\n type: 'error',\n name: 'PoolNotInitialized',\n inputs: [],\n },\n\n // PositionCountNotZero() - 0x2501f81e\n {\n type: 'error',\n name: 'PositionCountNotZero',\n inputs: [],\n },\n\n // PositionNotOwned() - 0x00bd51c8\n {\n type: 'error',\n name: 'PositionNotOwned',\n inputs: [],\n },\n\n // PositionTooLarge() - 0x543a6e10\n {\n type: 'error',\n name: 'PositionTooLarge',\n inputs: [],\n },\n\n // PriceBoundFail(int24 currentTick) - 0x618ea40c\n {\n type: 'error',\n name: 'PriceBoundFail',\n inputs: [{ name: 'currentTick', type: 'int24' }],\n },\n\n // PriceImpactTooLarge() - 0xcbe5b9a6\n {\n type: 'error',\n name: 'PriceImpactTooLarge',\n inputs: [],\n },\n\n // Reentrancy() - 0xab143c06\n {\n type: 'error',\n name: 'Reentrancy',\n inputs: [],\n },\n\n // StaleOracle() - 0x88cce429\n {\n type: 'error',\n name: 'StaleOracle',\n inputs: [],\n },\n\n // TokenIdHasZeroLegs() - 0x9cd92fb2\n {\n type: 'error',\n name: 'TokenIdHasZeroLegs',\n inputs: [],\n },\n\n // TooManyLegsOpen() - 0x0ed7e777\n {\n type: 'error',\n name: 'TooManyLegsOpen',\n inputs: [],\n },\n\n // TransferFailed(address token, address from, uint256 amount, uint256 balance) - 0x81f20f86\n {\n type: 'error',\n name: 'TransferFailed',\n inputs: [\n { name: 'token', type: 'address' },\n { name: 'from', type: 'address' },\n { name: 'amount', type: 'uint256' },\n { name: 'balance', type: 'uint256' },\n ],\n },\n\n // UnauthorizedUniswapCallback() - 0x3e30718a\n {\n type: 'error',\n name: 'UnauthorizedUniswapCallback',\n inputs: [],\n },\n\n // UnderOverFlow() - 0xd2190174\n {\n type: 'error',\n name: 'UnderOverFlow',\n inputs: [],\n },\n\n // WrongPoolId() - 0xcfa4bfa2\n {\n type: 'error',\n name: 'WrongPoolId',\n inputs: [],\n },\n\n // WrongUniswapPool() - 0x768778de\n {\n type: 'error',\n name: 'WrongUniswapPool',\n inputs: [],\n },\n\n // ZeroAddress() - 0xd92e233d\n {\n type: 'error',\n name: 'ZeroAddress',\n inputs: [],\n },\n\n // ZeroCollateralRequirement() - 0x5b8edb4a\n {\n type: 'error',\n name: 'ZeroCollateralRequirement',\n inputs: [],\n },\n] as const\n","/**\n * Error parsing utilities for the Panoptic v2 SDK.\n *\n * Converts raw contract errors into typed SDK error classes.\n *\n * @module v2/errors/parser\n */\n\nimport { type Abi, BaseError, decodeErrorResult, toFunctionSelector } from 'viem'\n\nimport { collateralTrackerV2Abi, panopticPoolV2Abi, riskEngineAbi } from '../../../generated'\nimport { PanopticError } from './base'\nimport {\n // Solvency & Margin\n AccountInsolventError,\n AlreadyInitializedError,\n BelowMinimumRedemptionError,\n CastingError,\n // Liquidity\n ChunkHasZeroLiquidityError,\n CreateFailError,\n DepositTooLargeError,\n DuplicateTokenIdError,\n EffectiveLiquidityAboveThresholdError,\n ExceedsMaximumRedemptionError,\n InputListFailError,\n InsufficientCreditLiquidityError,\n InvalidBuilderCodeError,\n InvalidTickBoundError,\n // Tick & Price\n InvalidTickError,\n // Position & TokenId\n InvalidTokenIdParameterError,\n InvalidUniswapCallbackError,\n LengthMismatchError,\n LiquidityTooHighError,\n NetLiquidityZeroError,\n // Exercise\n NoLegsExercisableError,\n NotALongLegError,\n NotBuilderError,\n NotEnoughLiquidityInChunkError,\n // Token & Collateral\n NotEnoughTokensError,\n NotGuardianError,\n NotMarginCalledError,\n // Authorization\n NotPanopticPoolError,\n // Pool & Initialization\n PoolNotInitializedError,\n PositionCountNotZeroError,\n PositionNotOwnedError,\n PositionTooLargeError,\n PriceBoundFailError,\n PriceImpactTooLargeError,\n // Reentrancy\n ReentrancyError,\n // Oracle & Safe Mode\n StaleOracleError,\n TokenIdHasZeroLegsError,\n TooManyLegsOpenError,\n // Transfer & Casting\n TransferFailedError,\n UnauthorizedUniswapCallbackError,\n UnderOverFlowError,\n WrongPoolIdError,\n WrongUniswapPoolError,\n // Other\n ZeroAddressError,\n ZeroCollateralRequirementError,\n} from './contract'\nimport { panopticErrorsAbi } from './errorsAbi'\n\n/**\n * Result of parsing a Panoptic error.\n */\nexport interface ParsedError {\n /** The parsed error instance */\n error: PanopticError\n /** The original error name from the contract */\n errorName: string\n /** The decoded error arguments */\n args: readonly unknown[]\n}\n\n/**\n * Combined ABI for error decoding.\n * Includes the dedicated errors ABI for complete coverage.\n */\nconst combinedAbi = [\n ...panopticPoolV2Abi,\n ...collateralTrackerV2Abi,\n ...riskEngineAbi,\n ...panopticErrorsAbi,\n] as Abi\n\n/**\n * Map of error names to error constructors.\n */\nconst errorConstructors: Record<\n string,\n (args: readonly unknown[], cause?: Error) => PanopticError\n> = {\n // Solvency & Margin\n AccountInsolvent: (args, cause) =>\n new AccountInsolventError(args[0] as bigint, args[1] as bigint, cause),\n NotMarginCalled: (_args, cause) => new NotMarginCalledError(cause),\n\n // Factory\n CreateFail: (_args, cause) => new CreateFailError(cause),\n\n // Token & Collateral\n NotEnoughTokens: (args, cause) =>\n new NotEnoughTokensError(args[0] as `0x${string}`, args[1] as bigint, args[2] as bigint, cause),\n NotEnoughLiquidityInChunk: (_args, cause) => new NotEnoughLiquidityInChunkError(cause),\n InsufficientCreditLiquidity: (_args, cause) => new InsufficientCreditLiquidityError(cause),\n DepositTooLarge: (_args, cause) => new DepositTooLargeError(cause),\n BelowMinimumRedemption: (_args, cause) => new BelowMinimumRedemptionError(cause),\n ExceedsMaximumRedemption: (_args, cause) => new ExceedsMaximumRedemptionError(cause),\n ZeroCollateralRequirement: (_args, cause) => new ZeroCollateralRequirementError(cause),\n\n // Position & TokenId\n InvalidTokenIdParameter: (args, cause) =>\n new InvalidTokenIdParameterError(args[0] as bigint, cause),\n PositionNotOwned: (_args, cause) => new PositionNotOwnedError(cause),\n PositionTooLarge: (_args, cause) => new PositionTooLargeError(cause),\n PositionCountNotZero: (_args, cause) => new PositionCountNotZeroError(cause),\n DuplicateTokenId: (_args, cause) => new DuplicateTokenIdError(cause),\n TokenIdHasZeroLegs: (_args, cause) => new TokenIdHasZeroLegsError(cause),\n TooManyLegsOpen: (_args, cause) => new TooManyLegsOpenError(cause),\n InputListFail: (_args, cause) => new InputListFailError(cause),\n\n // Tick & Price\n InvalidTick: (_args, cause) => new InvalidTickError(cause),\n InvalidTickBound: (_args, cause) => new InvalidTickBoundError(cause),\n PriceBoundFail: (args, cause) => new PriceBoundFailError(args[0] as bigint, cause),\n PriceImpactTooLarge: (_args, cause) => new PriceImpactTooLargeError(cause),\n\n // Liquidity\n ChunkHasZeroLiquidity: (_args, cause) => new ChunkHasZeroLiquidityError(cause),\n LiquidityTooHigh: (_args, cause) => new LiquidityTooHighError(cause),\n NetLiquidityZero: (_args, cause) => new NetLiquidityZeroError(cause),\n EffectiveLiquidityAboveThreshold: (_args, cause) =>\n new EffectiveLiquidityAboveThresholdError(cause),\n\n // Oracle & Safe Mode\n StaleOracle: (_args, cause) => new StaleOracleError(cause),\n\n // Exercise\n NoLegsExercisable: (_args, cause) => new NoLegsExercisableError(cause),\n NotALongLeg: (_args, cause) => new NotALongLegError(cause),\n\n // Pool & Initialization\n PoolNotInitialized: (_args, cause) => new PoolNotInitializedError(cause),\n AlreadyInitialized: (_args, cause) => new AlreadyInitializedError(cause),\n WrongPoolId: (_args, cause) => new WrongPoolIdError(cause),\n WrongUniswapPool: (_args, cause) => new WrongUniswapPoolError(cause),\n\n // Authorization\n NotPanopticPool: (_args, cause) => new NotPanopticPoolError(cause),\n NotGuardian: (_args, cause) => new NotGuardianError(cause),\n NotBuilder: (_args, cause) => new NotBuilderError(cause),\n InvalidBuilderCode: (_args, cause) => new InvalidBuilderCodeError(cause),\n InvalidUniswapCallback: (_args, cause) => new InvalidUniswapCallbackError(cause),\n UnauthorizedUniswapCallback: (_args, cause) => new UnauthorizedUniswapCallbackError(cause),\n\n // Transfer & Casting\n TransferFailed: (args, cause) =>\n new TransferFailedError(\n args[0] as `0x${string}`,\n args[1] as `0x${string}`,\n args[2] as bigint,\n args[3] as bigint,\n cause,\n ),\n CastingError: (_args, cause) => new CastingError(cause),\n UnderOverFlow: (_args, cause) => new UnderOverFlowError(cause),\n\n // Reentrancy\n Reentrancy: (_args, cause) => new ReentrancyError(cause),\n\n // Other\n ZeroAddress: (_args, cause) => new ZeroAddressError(cause),\n LengthMismatch: (_args, cause) => new LengthMismatchError(cause),\n}\n\n/**\n * Parse a raw contract error into a typed SDK error.\n *\n * This function attempts to decode the error data from a failed contract call\n * and return a typed error instance with extracted parameters.\n *\n * @param error - The raw error from a failed contract call\n * @returns Parsed error with typed error instance, or null if parsing fails\n *\n * @example\n * ```typescript\n * try {\n * await contract.openPosition(...)\n * } catch (rawError) {\n * const parsed = parsePanopticError(rawError)\n * if (parsed) {\n * console.log('Error:', parsed.errorName)\n * if (parsed.error instanceof AccountInsolventError) {\n * console.log('Solvent value:', parsed.error.solvent)\n * }\n * }\n * }\n * ```\n */\nexport function parsePanopticError(error: unknown): ParsedError | null {\n // Strategy 1: Check if viem already decoded the error (ContractFunctionRevertedError.data)\n const viemDecoded = extractViemDecodedError(error)\n if (viemDecoded) {\n return buildParsedError(viemDecoded.errorName, viemDecoded.args, error)\n }\n\n // Strategy 2: Extract raw hex data and decode ourselves\n const errorData = extractErrorData(error)\n if (!errorData) return null\n\n try {\n const decoded = decodeErrorResult({\n abi: combinedAbi,\n data: errorData,\n })\n\n return buildParsedError(decoded.errorName, decoded.args ?? [], error)\n } catch {\n // decodeErrorResult failed — possibly we only have the 4-byte selector\n // (e.g. from a multicall error message). Try matching the selector manually.\n if (errorData.length >= 10) {\n const selector = errorData.slice(0, 10) as `0x${string}`\n const match = matchSelectorToErrorName(selector)\n if (match) {\n return buildParsedError(match, [], error)\n }\n }\n return null\n }\n}\n\n/**\n * Walk the cause chain looking for a viem ContractFunctionRevertedError\n * that already has decoded `.data` (an object with `errorName` and `args`).\n * This happens when the ABI passed to simulateContract includes the error definitions.\n */\nfunction extractViemDecodedError(\n error: unknown,\n): { errorName: string; args: readonly unknown[] } | null {\n if (!error || typeof error !== 'object') return null\n\n // Use BaseError.walk if available\n if (error instanceof BaseError) {\n let found: { errorName: string; args: readonly unknown[] } | null = null\n error.walk((e) => {\n if (found) return false\n const node = e as Record<string, unknown>\n if (\n node.data &&\n typeof node.data === 'object' &&\n 'errorName' in (node.data as object) &&\n typeof (node.data as Record<string, unknown>).errorName === 'string'\n ) {\n const data = node.data as { errorName: string; args?: readonly unknown[] }\n found = { errorName: data.errorName, args: data.args ?? [] }\n return true\n }\n return false\n })\n return found\n }\n\n // Manual walk for non-viem errors\n let current: Record<string, unknown> | null = error as Record<string, unknown>\n for (let i = 0; i < 10 && current; i++) {\n if (\n current.data &&\n typeof current.data === 'object' &&\n 'errorName' in (current.data as object) &&\n typeof (current.data as Record<string, unknown>).errorName === 'string'\n ) {\n const data = current.data as { errorName: string; args?: readonly unknown[] }\n return { errorName: data.errorName, args: data.args ?? [] }\n }\n current =\n current.cause && typeof current.cause === 'object'\n ? (current.cause as Record<string, unknown>)\n : null\n }\n\n return null\n}\n\n/**\n * Build a ParsedError from a decoded error name and args.\n */\nfunction buildParsedError(\n errorName: string,\n args: readonly unknown[],\n originalError: unknown,\n): ParsedError {\n const constructor = errorConstructors[errorName]\n const cause = originalError instanceof Error ? originalError : undefined\n\n if (!constructor) {\n const unknownError = new PanopticError(`Unknown contract error: ${errorName}`)\n unknownError.errorName = errorName\n return { error: unknownError, errorName, args }\n }\n\n const typedError = constructor(args, cause)\n typedError.errorName = errorName\n return { error: typedError, errorName, args }\n}\n\n/**\n * Match a 4-byte selector against the panoptic errors ABI.\n * Used as fallback when we only have the selector (no encoded args).\n */\nfunction matchSelectorToErrorName(selector: `0x${string}`): string | null {\n for (const item of panopticErrorsAbi) {\n if (item.type !== 'error') continue\n const computed = toFunctionSelector(\n `${item.name}(${item.inputs.map((i: { type: string }) => i.type).join(',')})`,\n )\n if (computed === selector) {\n return item.name\n }\n }\n return null\n}\n\n/**\n * Extract error data from various error formats.\n *\n * Strategy:\n * 1. Use viem's BaseError.walk() to traverse the full cause chain and find\n * hex data on any node (handles arbitrary nesting depth for multicall etc.)\n * 2. Fall back to manual cause-chain walk for non-viem errors\n * 3. Last resort: extract selector from error message (loses args)\n */\nfunction extractErrorData(error: unknown): `0x${string}` | null {\n if (!error) return null\n\n // Direct hex data\n if (typeof error === 'string' && error.startsWith('0x')) {\n return error as `0x${string}`\n }\n\n if (typeof error !== 'object') return null\n\n // Strategy 1: Use viem's BaseError.walk() — traverses the full cause chain\n if (error instanceof BaseError) {\n let foundData: `0x${string}` | null = null\n\n error.walk((e) => {\n if (foundData) return false\n const node = e as Record<string, unknown>\n\n // Check .data as hex string (full revert bytes on RPC errors)\n if (node.data && typeof node.data === 'string' && node.data.startsWith('0x')) {\n foundData = node.data as `0x${string}`\n return true\n }\n\n // Check .data.data (some RPC providers nest: { data: { data: '0x...' } })\n if (node.data && typeof node.data === 'object') {\n const nested = node.data as Record<string, unknown>\n if (nested.data && typeof nested.data === 'string' && nested.data.startsWith('0x')) {\n foundData = nested.data as `0x${string}`\n return true\n }\n }\n\n return false\n })\n\n if (foundData) return foundData\n\n // Also check .signature on walked nodes (viem stores raw selector here\n // when it can't decode against the provided ABI)\n error.walk((e) => {\n if (foundData) return false\n const node = e as Record<string, unknown>\n if (node.signature && typeof node.signature === 'string' && node.signature.startsWith('0x')) {\n foundData = node.signature as `0x${string}`\n return true\n }\n return false\n })\n\n if (foundData) return foundData\n }\n\n // Strategy 2: Manual cause-chain walk for non-viem errors\n let current: Record<string, unknown> | null = error as Record<string, unknown>\n const maxDepth = 10\n for (let i = 0; i < maxDepth && current; i++) {\n if (current.data && typeof current.data === 'string' && current.data.startsWith('0x')) {\n return current.data as `0x${string}`\n }\n\n if (current.data && typeof current.data === 'object') {\n const nested = current.data as Record<string, unknown>\n if (nested.data && typeof nested.data === 'string' && nested.data.startsWith('0x')) {\n return nested.data as `0x${string}`\n }\n }\n\n if (current.error && typeof current.error === 'object') {\n const rpcError = current.error as Record<string, unknown>\n if (rpcError.data && typeof rpcError.data === 'string' && rpcError.data.startsWith('0x')) {\n return rpcError.data as `0x${string}`\n }\n }\n\n current =\n current.cause && typeof current.cause === 'object'\n ? (current.cause as Record<string, unknown>)\n : null\n }\n\n // Strategy 3: Extract from error message (last resort — may only have 4-byte selector)\n const obj = error as Record<string, unknown>\n if (obj.message && typeof obj.message === 'string') {\n const signatureMatch = obj.message.match(/signature:\\s*(0x[a-fA-F0-9]{8,})/i)\n if (signatureMatch) {\n return signatureMatch[1] as `0x${string}`\n }\n }\n\n return null\n}\n\n/**\n * Check if an error is a specific Panoptic error type.\n *\n * @param error - The error to check\n * @param errorClass - The error class to check against\n * @returns True if the error is an instance of the specified class\n *\n * @example\n * ```typescript\n * const parsed = parsePanopticError(error)\n * if (parsed && isPanopticErrorType(parsed.error, AccountInsolventError)) {\n * console.log('Account is insolvent!')\n * }\n * ```\n */\nexport function isPanopticErrorType<T extends PanopticError>(\n error: PanopticError,\n errorClass: new (...args: unknown[]) => T,\n): error is T {\n return error instanceof errorClass\n}\n","/**\n * Constants for the Panoptic v2 SDK.\n * @module v2/utils/constants\n */\n\n/**\n * WAD constant (10^18) used for fixed-point arithmetic.\n * Commonly used for spread calculations and other WAD-scaled values.\n */\nexport const WAD = 10n ** 18n\n\n/**\n * Zero collateral object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_COLLATERAL = {\n token0: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n token1: {\n assets: 0n,\n shares: 0n,\n availableAssets: 0n,\n lockedAssets: 0n,\n },\n} as const\n\n/**\n * Zero valuation object for guest mode.\n * Returns safe defaults when no wallet is connected.\n */\nexport const ZERO_VALUATION = {\n netLiquidationValue0: 0n,\n netLiquidationValue1: 0n,\n maintenanceMargin0: 0n,\n maintenanceMargin1: 0n,\n marginExcess0: 0n,\n marginExcess1: 0n,\n} as const\n\n/**\n * Storage schema version for the SDK.\n * Increment when storage format changes (triggers migration or clear).\n */\nexport const SCHEMA_VERSION = 1\n\n/**\n * Storage key prefix for all SDK data.\n */\nexport const STORAGE_PREFIX = 'panoptic-v2-sdk'\n\n/**\n * Maximum number of chunks that can be tracked per pool.\n * Exceeding this limit throws ChunkLimitError.\n */\nexport const MAX_TRACKED_CHUNKS = 1000\n\n/**\n * Default reorg depth for chain reorganization handling.\n * On reorg detection, rollback this many blocks and re-sync.\n */\nexport const REORG_DEPTH = 128n\n\n/**\n * Oracle epoch duration in seconds (64 seconds per epoch).\n */\nexport const ORACLE_EPOCH_SECONDS = 64n\n\n/**\n * Minimum tick value for Uniswap v3/v4 pools.\n */\nexport const MIN_TICK = -887272n\n\n/**\n * Maximum tick value for Uniswap v3/v4 pools.\n */\nexport const MAX_TICK = 887272n\n\n/**\n * PanopticQuery sentinel indicating that no lower liquidation boundary exists.\n * This is int24.min, not Uniswap's minimum usable tick.\n */\nexport const NO_LOWER_LIQUIDATION_TICK = -(1n << 23n)\n\n/**\n * PanopticQuery sentinel indicating that no upper liquidation boundary exists.\n * This is int24.max, not Uniswap's maximum usable tick.\n */\nexport const NO_UPPER_LIQUIDATION_TICK = (1n << 23n) - 1n\n\n/**\n * Basis points denominator (100% = 10000 bps).\n */\nexport const BPS_DENOMINATOR = 10000n\n\n/**\n * Utilization denominator (100% = 10000).\n */\nexport const UTILIZATION_DENOMINATOR = 10000n\n","/**\n * Snapshot recovery from dispatch calldata.\n * @module v2/sync/snapshotRecovery\n */\n\nimport type { AbiFunction, Address, Hash, Hex, PublicClient } from 'viem'\nimport { decodeFunctionData, getAddress, parseAbi, toFunctionSelector } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\n\nconst LOG_SCAN_WINDOW = 10_000n\nconst rolesExecutionAbi = parseAbi([\n 'function execTransactionWithRole(address to, uint256 value, bytes data, uint8 operation, bytes32 roleKey, bool shouldRevert)',\n])\n\ntype SnapshotEventLog = Awaited<ReturnType<PublicClient['getLogs']>>[number]\ntype SnapshotCandidateEvent = SnapshotEventLog & {\n transactionHash: Hash\n blockNumber: bigint\n logIndex: number\n}\n\n/**\n * Parameters for recovering position snapshot from dispatch calldata.\n */\nexport interface RecoverSnapshotParams {\n /** viem public client */\n client: PublicClient\n /** Pool address */\n poolAddress: Address\n /** Account to recover positions for */\n account: Address\n /** Starting block for transaction search (defaults to 0) */\n fromBlock?: bigint\n /** Ending block for transaction search (defaults to latest) */\n toBlock?: bigint\n}\n\n/**\n * Snapshot recovery result.\n */\nexport interface SnapshotRecoveryResult {\n /** Whether recovery was successful */\n success: boolean\n /** Position IDs from the final position list */\n positionIds: bigint[]\n /** Block number of the recovery transaction */\n blockNumber: bigint\n /** Block hash of the recovery transaction */\n blockHash: Hash\n /** Transaction hash used for recovery */\n transactionHash: Hash\n}\n\n/**\n * Recover position snapshot from the last dispatch transaction.\n * This is the primary recovery method - it finds the most recent dispatch()\n * call and extracts the finalPositionIdList from the calldata.\n *\n * @param params - Recovery parameters\n * @returns Snapshot recovery result\n */\nexport async function recoverSnapshot(\n params: RecoverSnapshotParams,\n): Promise<SnapshotRecoveryResult | null> {\n const { client, poolAddress, account, toBlock } = params\n\n // Get the latest block if not specified\n const latestBlock = toBlock ?? (await client.getBlockNumber())\n\n // Search for transactions from the account to the pool\n // We need to find dispatch() or dispatchFrom() calls\n // Note: This requires the account to have sent transactions directly,\n // or we need to look at internal transactions\n\n // Strategy: Look for OptionMinted or OptionBurnt events to find transactions,\n // then decode the transaction input to get the full position list\n\n const searchFromBlock = params.fromBlock ?? 0n\n if (latestBlock < searchFromBlock) return null\n\n // Fast path: a single getLogs per event type over the entire\n // [searchFromBlock, latest] range. The queries are filtered by `address` and\n // an indexed account topic, so providers like Alchemy impose no block-range\n // cap on them (only a result-count cap) — one call per event type is enough\n // and the returned set is already complete, so there are no older windows to\n // scan. This avoids walking the whole chain in 10k-block chunks (4 getLogs\n // per chunk), which for accounts with no history is thousands of empty calls.\n try {\n const events = await getSnapshotEventsForWindow({\n client,\n poolAddress,\n account,\n fromBlock: searchFromBlock,\n toBlock: latestBlock,\n })\n return await recoverSnapshotFromEvents({ client, account, events })\n } catch (error) {\n // Only fall back to windowed scanning when the provider rejected the wide\n // range. Any other error (e.g. transport failure) should propagate.\n if (!isRangeLimitError(error)) throw error\n }\n\n // Fallback for providers that cap getLogs block range: scan newest-to-oldest\n // in 10k-block windows and stop at the first window that yields a snapshot.\n let windowToBlock = latestBlock\n while (true) {\n const windowFromBlock =\n windowToBlock - searchFromBlock + 1n > LOG_SCAN_WINDOW\n ? windowToBlock - LOG_SCAN_WINDOW + 1n\n : searchFromBlock\n\n const events = await getSnapshotEventsForWindow({\n client,\n poolAddress,\n account,\n fromBlock: windowFromBlock,\n toBlock: windowToBlock,\n })\n const snapshot = await recoverSnapshotFromEvents({ client, account, events })\n if (snapshot) return snapshot\n\n if (windowFromBlock === searchFromBlock) break\n windowToBlock = windowFromBlock - 1n\n }\n\n // No snapshot found\n return null\n}\n\n/**\n * Detect provider errors that indicate the requested getLogs block range was\n * too wide (so the caller should retry with smaller windows). Covers the common\n * phrasings used by Alchemy, Infura, and other JSON-RPC providers.\n */\nfunction isRangeLimitError(error: unknown): boolean {\n const parts: string[] = []\n let current: unknown = error\n let depth = 0\n while (current && typeof current === 'object' && depth < 5) {\n const obj = current as Record<string, unknown>\n if (typeof obj.message === 'string') parts.push(obj.message)\n if (typeof obj.details === 'string') parts.push(obj.details)\n current = obj.cause\n depth += 1\n }\n if (typeof error === 'string') parts.push(error)\n\n const message = parts.join(' ').toLowerCase()\n if (!message) return false\n\n return (\n message.includes('block range') ||\n message.includes('range is too large') ||\n message.includes('range too large') ||\n message.includes('query returned more than') ||\n message.includes('too many results') ||\n message.includes('log response size exceeded') ||\n message.includes('exceeds the limit') ||\n (message.includes('range') && message.includes('limit'))\n )\n}\n\nasync function getSnapshotEventsForWindow(params: {\n client: PublicClient\n poolAddress: Address\n account: Address\n fromBlock: bigint\n toBlock: bigint\n}): Promise<SnapshotEventLog[]> {\n const { client, poolAddress, account, fromBlock, toBlock } = params\n\n // OptionMinted/OptionBurnt cover the account's own dispatches.\n // ForcedExercised/AccountLiquidated cover third-party dispatchFrom calls\n // where the tx sender is not the account but calldata contains the final list.\n const [mintEvents, burnEvents, forceExerciseEvents, liquidationEvents] = await Promise.all([\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'OptionMinted',\n inputs: [\n { type: 'address', name: 'recipient', indexed: true },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'uint256', name: 'balanceData', indexed: false },\n ],\n },\n args: {\n recipient: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'OptionBurnt',\n inputs: [\n { type: 'address', name: 'recipient', indexed: true },\n { type: 'uint128', name: 'positionSize', indexed: false },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'int256[4]', name: 'premiaByLeg', indexed: false },\n ],\n },\n args: {\n recipient: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'ForcedExercised',\n inputs: [\n { type: 'address', name: 'exercisor', indexed: true },\n { type: 'address', name: 'user', indexed: true },\n { type: 'uint256', name: 'tokenId', indexed: true },\n { type: 'int256', name: 'exerciseFee', indexed: false },\n ],\n },\n args: {\n user: account,\n },\n fromBlock,\n toBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: {\n type: 'event',\n name: 'AccountLiquidated',\n inputs: [\n { type: 'address', name: 'liquidator', indexed: true },\n { type: 'address', name: 'liquidatee', indexed: true },\n { type: 'int256', name: 'bonusAmounts', indexed: false },\n ],\n },\n args: {\n liquidatee: account,\n },\n fromBlock,\n toBlock,\n }),\n ])\n\n return [...mintEvents, ...burnEvents, ...forceExerciseEvents, ...liquidationEvents]\n}\n\nasync function recoverSnapshotFromEvents(params: {\n client: PublicClient\n account: Address\n events: SnapshotEventLog[]\n}): Promise<SnapshotRecoveryResult | null> {\n const { client, account, events } = params\n\n // Combine and sort by block number (descending) to get most recent first\n const allEvents = events.filter(isSnapshotCandidateEvent).sort((a, b) => {\n const blockDiff = Number(b.blockNumber - a.blockNumber)\n if (blockDiff !== 0) return blockDiff\n return Number(b.logIndex - a.logIndex)\n })\n\n // Deduplicate by transaction hash — multiple events from the same tx\n // (e.g. OptionMinted for each leg) would produce duplicate entries\n const seen = new Set<string>()\n const uniqueEvents = allEvents.filter((e) => {\n if (seen.has(e.transactionHash)) return false\n seen.add(e.transactionHash)\n return true\n })\n\n // Find the most recent transaction with position data\n for (const event of uniqueEvents) {\n try {\n const [tx, block] = await Promise.all([\n client.getTransaction({ hash: event.transactionHash }),\n client.getBlock({ blockNumber: event.blockNumber }),\n ])\n\n // A single tx (e.g. a force-exercise multicall) can embed several\n // dispatch/dispatchFrom calls — the exercisor's own dispatch alongside the\n // victim's dispatchFrom. Select a strict account match first, then allow a\n // plain dispatch only because this tx came from an account-indexed event.\n const candidates = decodeAllDispatchCalldata(tx.input)\n const decoded =\n selectDispatchForAccount(candidates, account, tx.from) ??\n selectDispatchProvenByAccountEvent(candidates)\n if (!decoded) {\n continue\n }\n\n return {\n success: true,\n positionIds: decoded.positionIds,\n blockNumber: event.blockNumber,\n blockHash: block.hash,\n transactionHash: event.transactionHash,\n }\n } catch {\n // Transaction fetch failed, continue\n }\n }\n\n return null\n}\n\nfunction isSnapshotCandidateEvent(event: SnapshotEventLog): event is SnapshotCandidateEvent {\n return event.transactionHash !== null && event.blockNumber !== null && event.logIndex !== null\n}\n\n/**\n * Parameters for recovering a snapshot from a known transaction hash.\n */\nexport interface RecoverSnapshotFromTxParams {\n /** viem public client */\n client: PublicClient\n /** Transaction hash of a known dispatch() call */\n transactionHash: Hash\n /** Account to verify. When set, rejects transactions not sent by (or targeting) this account. */\n account?: Address\n /** Pool address to validate against. When set, rejects transactions not sent to this pool. */\n pool?: Address\n /** Expected Zodiac Roles wrapper for bot-originated Safe dispatches. */\n rolesContext?: {\n modifier: Address\n member: Address\n roleKey: Hash\n }\n}\n\nexport interface RolesSnapshotContext {\n modifier: Address\n member: Address\n roleKey: Hash\n}\n\nexport function decodeSnapshotTransaction(params: {\n input: Hex\n from: Address\n to: Address | null\n account?: Address\n pool?: Address\n rolesContext?: RolesSnapshotContext\n}): DispatchCalldata | null {\n const { account, pool, rolesContext } = params\n let dispatchInput = params.input\n let dispatchSender = params.from\n\n if (rolesContext) {\n if (\n params.to === null ||\n getAddress(params.to) !== getAddress(rolesContext.modifier) ||\n getAddress(params.from) !== getAddress(rolesContext.member)\n ) {\n return null\n }\n try {\n const decodedRoleCall = decodeFunctionData({ abi: rolesExecutionAbi, data: params.input })\n const [target, value, data, operation, roleKey, shouldRevert] = decodedRoleCall.args\n if (\n !pool ||\n getAddress(target) !== getAddress(pool) ||\n value !== 0n ||\n operation !== 0 ||\n roleKey.toLowerCase() !== rolesContext.roleKey.toLowerCase() ||\n !shouldRevert\n ) {\n return null\n }\n dispatchInput = data\n if (!account) return null\n dispatchSender = account\n } catch {\n return null\n }\n } else if (pool && (params.to === null || getAddress(params.to) !== getAddress(pool))) {\n return null\n }\n\n const candidates = decodeAllDispatchCalldata(dispatchInput)\n if (candidates.length === 0) return null\n return account\n ? selectDispatchForAccount(candidates, account, dispatchSender)\n : candidates[candidates.length - 1]\n}\n\n/**\n * Recover position snapshot from a specific dispatch transaction hash.\n *\n * This is an O(1) alternative to {@link recoverSnapshot} when you already\n * know the tx hash of the most recent dispatch. It fetches the transaction,\n * decodes the `finalPositionIdList` from the calldata, and returns the result\n * — no event scanning required.\n *\n * @param params - Recovery parameters including the transaction hash\n * @returns Snapshot recovery result, or null if the tx is not a dispatch call\n *\n * @example\n * ```typescript\n * const snapshot = await recoverSnapshotFromTx({\n * client,\n * transactionHash: '0xabc...',\n * })\n * if (snapshot) {\n * console.log('Open positions:', snapshot.positionIds)\n * }\n * ```\n */\nexport async function recoverSnapshotFromTx(\n params: RecoverSnapshotFromTxParams,\n): Promise<SnapshotRecoveryResult | null> {\n const { client, transactionHash, account, pool, rolesContext } = params\n\n const tx = await client.getTransaction({ hash: transactionHash })\n\n // Pending transactions have no block number — cannot recover snapshot\n if (tx.blockNumber == null) return null\n\n const decoded = decodeSnapshotTransaction({\n input: tx.input,\n from: tx.from,\n to: tx.to,\n account,\n pool,\n rolesContext,\n })\n if (!decoded) return null\n\n const blockNumber = tx.blockNumber\n const block = await client.getBlock({ blockNumber })\n\n return {\n success: true,\n positionIds: decoded.positionIds,\n blockNumber,\n blockHash: block.hash,\n transactionHash,\n }\n}\n\n/**\n * Decoded dispatch calldata result.\n */\nexport interface DispatchCalldata {\n /** Final position ID list after the dispatch */\n positionIds: bigint[]\n /** Target account (only set for dispatchFrom) */\n targetAccount?: Address\n}\n\n/**\n * Decode position IDs from dispatch calldata.\n *\n * When the tx embeds multiple dispatch/dispatchFrom calls (e.g. a force-exercise\n * multicall), this returns the last one — prefer {@link decodeAllDispatchCalldata}\n * plus {@link selectDispatchForAccount} when the account context matters.\n *\n * @param input - Transaction input data\n * @returns Decoded dispatch data or null if not a dispatch call\n */\nexport function decodeDispatchCalldata(input: `0x${string}`): DispatchCalldata | null {\n const all = decodeAllDispatchCalldata(input)\n return all.length > 0 ? all[all.length - 1] : null\n}\n\n/**\n * Decode every dispatch/dispatchFrom call embedded in transaction calldata.\n *\n * A single tx can carry more than one such call — most importantly a force-exercise\n * `multicall` that bundles the exercisor's own `dispatch` together with the victim's\n * `dispatchFrom`. Returning all candidates lets the caller select the one attributable\n * to the relevant account ({@link selectDispatchForAccount}).\n *\n * @param input - Transaction input data\n * @returns All decoded dispatch calls, in calldata order (may be empty)\n */\nexport function decodeAllDispatchCalldata(input: `0x${string}`): DispatchCalldata[] {\n // Try direct dispatch/dispatchFrom first\n const direct = decodeDirectDispatch(input)\n if (direct) return [direct]\n\n // Try unwrapping smart contract wallet wrappers (executeBatch, execute, multicall)\n return decodeWrappedDispatch(input)\n}\n\n/**\n * Select the dispatch call attributable to `account` from a set of candidates.\n *\n * - `dispatchFrom`: matches when `targetAccount === account` (builder/exercisor acting\n * on behalf of the account).\n * - `dispatch` (no `targetAccount`): matches only when the tx sender is the account.\n *\n * Returns the LAST matching candidate (in calldata order), or null when none are\n * attributable to `account`. The last dispatch reflects the final post-transaction\n * state when a single tx contains multiple dispatches for the same account (e.g. a\n * multicall). Matching also prevents accepting a third party's `dispatch` (e.g. the\n * exercisor's own, bundled in a force-exercise multicall) as the account's snapshot.\n *\n * @param candidates - Decoded dispatch calls from a single tx, in calldata order\n * @param account - Account whose position list we are recovering\n * @param txFrom - The transaction sender (`tx.from`)\n */\nexport function selectDispatchForAccount(\n candidates: DispatchCalldata[],\n account: Address,\n txFrom: Address,\n): DispatchCalldata | null {\n const acct = account.toLowerCase()\n let match: DispatchCalldata | null = null\n for (const candidate of candidates) {\n if (candidate.targetAccount) {\n if (candidate.targetAccount.toLowerCase() === acct) match = candidate\n } else if (txFrom.toLowerCase() === acct) {\n match = candidate\n }\n }\n return match\n}\n\nfunction selectDispatchProvenByAccountEvent(\n candidates: DispatchCalldata[],\n): DispatchCalldata | null {\n let match: DispatchCalldata | null = null\n for (const candidate of candidates) {\n if (candidate.targetAccount === undefined) match = candidate\n }\n return match\n}\n\n/**\n * Try to decode input as a direct dispatch or dispatchFrom call.\n */\nfunction decodeDirectDispatch(input: `0x${string}`): DispatchCalldata | null {\n try {\n const decoded = decodeFunctionData({\n abi: panopticPoolV2Abi,\n data: input,\n })\n\n if (decoded.functionName === 'dispatch') {\n const args = decoded.args as readonly [\n bigint[],\n bigint[],\n bigint[],\n readonly [number, number, number][],\n boolean,\n bigint,\n ]\n return { positionIds: [...args[1]] } // finalPositionIdList\n }\n\n if (decoded.functionName === 'dispatchFrom') {\n const args = decoded.args as readonly [bigint[], Address, bigint[], bigint[], bigint]\n return {\n positionIds: [...args[3]], // positionIdListToFinal\n targetAccount: args[1],\n }\n }\n\n return null\n } catch {\n return null\n }\n}\n\n/**\n * 4-byte function selectors for dispatch/dispatchFrom, derived from the generated ABI.\n * Used for scanning raw calldata inside smart contract wallet wrappers.\n */\nconst DISPATCH_SELECTOR = toFunctionSelector(\n panopticPoolV2Abi.find((e) => e.type === 'function' && e.name === 'dispatch') as AbiFunction,\n).slice(2) // strip 0x prefix for hex scanning\n\nconst DISPATCH_FROM_SELECTOR = toFunctionSelector(\n panopticPoolV2Abi.find((e) => e.type === 'function' && e.name === 'dispatchFrom') as AbiFunction,\n).slice(2)\n\n/**\n * Scan raw transaction input for embedded dispatch calldata.\n *\n * Smart contract wallets (Safe, Turnkey, ERC-4337) and vault managers\n * wrap dispatch calls inside executeBatch → manage → dispatch chains.\n * Instead of decoding each wrapper layer, we scan the raw hex for the\n * dispatch function selector and attempt to decode from that offset.\n *\n * This handles arbitrary nesting depth without knowing wrapper ABIs.\n */\nfunction decodeWrappedDispatch(input: `0x${string}`): DispatchCalldata[] {\n const hex = input.slice(2).toLowerCase()\n const selectors = [DISPATCH_SELECTOR, DISPATCH_FROM_SELECTOR]\n\n // Single left-to-right pass: find the earliest selector match at each offset and\n // collect every successful decode, in calldata order. The caller selects the call\n // attributable to the relevant account rather than blindly taking one.\n const results: DispatchCalldata[] = []\n let offset = 0\n\n while (offset < hex.length) {\n // Find the nearest selector match from current offset\n let earliestIdx = -1\n for (const selector of selectors) {\n const idx = hex.indexOf(selector, offset)\n if (idx !== -1 && (earliestIdx === -1 || idx < earliestIdx)) {\n earliestIdx = idx\n }\n }\n if (earliestIdx === -1) break\n\n const candidate = `0x${hex.slice(earliestIdx)}` as `0x${string}`\n const result = decodeDirectDispatch(candidate)\n if (result) results.push(result)\n\n offset = earliestIdx + 8 // Move past this selector\n }\n\n return results\n}\n","/**\n * Tick and price formatters for Uniswap V3/V4 pools.\n *\n * Ticks represent logarithmic prices where: price = 1.0001^tick\n *\n * @module v2/formatters/tick\n */\n\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\n\nconst Q192 = 1n << 192n\nconst RAW_PRICE_PRECISION = 40n\n\nfunction pow10(exponent: bigint): bigint {\n if (exponent < 0n) {\n throw new RangeError('Exponent must be non-negative')\n }\n return 10n ** exponent\n}\n\nfunction absBigint(value: bigint): bigint {\n return value < 0n ? -value : value\n}\n\nfunction trimTrailingZeros(value: string): string {\n const dotIndex = value.indexOf('.')\n if (dotIndex === -1) return value\n\n let end = value.length\n while (end > dotIndex && value[end - 1] === '0') {\n end -= 1\n }\n\n if (end === dotIndex + 1) {\n end = dotIndex\n }\n\n return value.slice(0, end)\n}\n\nfunction formatRatio(numerator: bigint, denominator: bigint, precision: bigint): string {\n if (precision < 0n) {\n throw new RangeError('Precision must be non-negative')\n }\n\n const sign = numerator < 0n ? '-' : ''\n const absNumerator = numerator < 0n ? -numerator : numerator\n\n const scale = pow10(precision)\n const scaled = (absNumerator * scale + denominator / 2n) / denominator\n const integerPart = scaled / scale\n const fractionalPart = scaled % scale\n\n if (precision === 0n) {\n return `${sign}${integerPart}`\n }\n\n return `${sign}${integerPart}.${fractionalPart.toString().padStart(Number(precision), '0')}`\n}\n\nfunction parseDecimalToFraction(value: string): { numerator: bigint; denominator: bigint } {\n const trimmed = value.trim()\n if (trimmed.length === 0) {\n throw new Error('Price must be a number')\n }\n\n const isNegative = trimmed.startsWith('-')\n const unsigned = isNegative || trimmed.startsWith('+') ? trimmed.slice(1) : trimmed\n\n const [basePart, exponentPart] = unsigned.toLowerCase().split('e')\n const [integerStr, fractionalStr = ''] = basePart.split('.')\n\n if (integerStr === '' && fractionalStr === '') {\n throw new Error('Price must be a number')\n }\n\n const integerDigits = integerStr === '' ? '0' : integerStr\n const digits = `${integerDigits}${fractionalStr}`\n\n let numerator = BigInt(digits === '' ? '0' : digits)\n let denominator = pow10(BigInt(fractionalStr.length))\n\n if (exponentPart !== undefined && exponentPart !== '') {\n const exponent = BigInt(exponentPart)\n if (exponent > 0n) {\n numerator *= pow10(exponent)\n } else if (exponent < 0n) {\n denominator *= pow10(-exponent)\n }\n }\n\n if (isNegative) {\n numerator = -numerator\n }\n\n return { numerator, denominator }\n}\n\nfunction compareRatios(\n leftNumerator: bigint,\n leftDenominator: bigint,\n rightNumerator: bigint,\n rightDenominator: bigint,\n): -1 | 0 | 1 {\n const left = leftNumerator * rightDenominator\n const right = rightNumerator * leftDenominator\n\n if (left === right) return 0\n return left < right ? -1 : 1\n}\n\nexport function tickToSqrtPriceX96(tick: bigint): bigint {\n if (tick < MIN_TICK || tick > MAX_TICK) {\n throw new RangeError('Tick out of bounds')\n }\n\n const absTick = tick < 0n ? -tick : tick\n\n let ratio =\n (absTick & 0x1n) !== 0n\n ? 0xfffcb933bd6fad37aa2d162d1a594001n\n : 0x100000000000000000000000000000000n\n if ((absTick & 0x2n) !== 0n) ratio = (ratio * 0xfff97272373d413259a46990580e213an) >> 128n\n if ((absTick & 0x4n) !== 0n) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn) >> 128n\n if ((absTick & 0x8n) !== 0n) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n) >> 128n\n if ((absTick & 0x10n) !== 0n) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n) >> 128n\n if ((absTick & 0x20n) !== 0n) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n) >> 128n\n if ((absTick & 0x40n) !== 0n) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n) >> 128n\n if ((absTick & 0x80n) !== 0n) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n) >> 128n\n if ((absTick & 0x100n) !== 0n) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n) >> 128n\n if ((absTick & 0x200n) !== 0n) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n) >> 128n\n if ((absTick & 0x400n) !== 0n) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n) >> 128n\n if ((absTick & 0x800n) !== 0n) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n) >> 128n\n if ((absTick & 0x1000n) !== 0n) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n) >> 128n\n if ((absTick & 0x2000n) !== 0n) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n) >> 128n\n if ((absTick & 0x4000n) !== 0n) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n) >> 128n\n if ((absTick & 0x8000n) !== 0n) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n) >> 128n\n if ((absTick & 0x10000n) !== 0n) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n) >> 128n\n if ((absTick & 0x20000n) !== 0n) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n) >> 128n\n if ((absTick & 0x40000n) !== 0n) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n) >> 128n\n if ((absTick & 0x80000n) !== 0n) ratio = (ratio * 0x48a170391f7dc42444e8fa2n) >> 128n\n\n if (tick > 0n) {\n ratio = ((1n << 256n) - 1n) / ratio\n }\n\n const remainderMask = (1n << 32n) - 1n\n const sqrtPriceX96 = (ratio >> 32n) + ((ratio & remainderMask) === 0n ? 0n : 1n)\n\n return sqrtPriceX96\n}\n\nconst MIN_SQRT_PRICE_X96 = tickToSqrtPriceX96(MIN_TICK)\nconst MAX_SQRT_PRICE_X96 = tickToSqrtPriceX96(MAX_TICK)\n\nfunction getPriceRatioFromSqrtPriceX96(sqrtPriceX96: bigint): {\n numerator: bigint\n denominator: bigint\n} {\n return {\n numerator: sqrtPriceX96 * sqrtPriceX96,\n denominator: Q192,\n }\n}\n\nfunction getRawPriceRatio(tick: bigint): { numerator: bigint; denominator: bigint } {\n return getPriceRatioFromSqrtPriceX96(tickToSqrtPriceX96(tick))\n}\n\nfunction adjustRatioForDecimals(\n numerator: bigint,\n denominator: bigint,\n decimals0: bigint,\n decimals1: bigint,\n): { numerator: bigint; denominator: bigint } {\n const diff = decimals0 - decimals1\n if (diff === 0n) {\n return { numerator, denominator }\n }\n\n if (diff > 0n) {\n return { numerator: numerator * pow10(diff), denominator }\n }\n\n return { numerator, denominator: denominator * pow10(-diff) }\n}\n\n/**\n * Convert a tick to a raw price string (no decimal adjustment).\n * Uses the formula: price = 1.0001^tick\n *\n * This returns the raw price ratio, not adjusted for token decimals.\n * A fixed internal precision is used and trailing zeros are trimmed.\n *\n * @param tick - The tick value\n * @returns Price string\n *\n * @example\n * ```typescript\n * tickToPrice(0n) // \"1\"\n * tickToPrice(1000n) // \"1.105...\" (approximately)\n * tickToPrice(-1000n) // \"0.904...\" (approximately)\n * tickToPrice(200000n) // Very large number\n * ```\n */\nexport function tickToPrice(tick: bigint): string {\n const { numerator, denominator } = getRawPriceRatio(tick)\n const price = formatRatio(numerator, denominator, RAW_PRICE_PRECISION)\n return trimTrailingZeros(price)\n}\n\n/**\n * Convert a tick to a human-readable price with decimal scaling.\n * Uses the formula: price = 1.0001^tick * 10^(decimals0-decimals1)\n *\n * This adjusts for the different decimals of the two tokens in the pair.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * // WETH/USDC pool (18 decimals / 6 decimals)\n * // At tick ~200000, price is roughly $2000 per ETH\n * tickToPriceDecimalScaled(200000n, 18n, 6n, 2n) // \"2000.00\" (approximately)\n *\n * // For token1/token0 price, swap the decimals\n * tickToPriceDecimalScaled(200000n, 6n, 18n, 6n) // \"0.000500\" (approximately)\n * ```\n */\nexport function tickToPriceDecimalScaled(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getRawPriceRatio(tick)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a sqrtPriceX96 to a human-readable price with decimal scaling.\n *\n * Uses the formula: price = (sqrtPriceX96^2 / 2^192) * 10^(decimals0-decimals1)\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price string\n *\n * @example\n * ```typescript\n * sqrtPriceX96ToPriceDecimalScaled(2n ** 96n, 18n, 18n, 2n) // \"1.00\"\n * ```\n */\nexport function sqrtPriceX96ToPriceDecimalScaled(\n sqrtPriceX96: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const rawRatio = getPriceRatioFromSqrtPriceX96(sqrtPriceX96)\n const { numerator, denominator } = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return formatRatio(numerator, denominator, precision)\n}\n\n/**\n * Convert a price to a tick value.\n *\n * @param price - The price string\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * // WETH/USDC: What tick for $2000 per ETH?\n * priceToTick(\"2000\", 18n, 6n) // ~200000n\n *\n * // Inverse: What tick for 0.0005 ETH per USDC?\n * priceToTick(\"0.0005\", 6n, 18n) // ~200000n\n * ```\n */\nexport function priceToTick(price: string, decimals0: bigint, decimals1: bigint): bigint {\n const parsed = parseDecimalToFraction(price)\n if (parsed.numerator <= 0n) {\n throw new Error('Price must be positive')\n }\n\n let targetNumerator = parsed.numerator\n let targetDenominator = parsed.denominator\n\n const diff = decimals0 - decimals1\n if (diff > 0n) {\n targetDenominator *= pow10(diff)\n } else if (diff < 0n) {\n targetNumerator *= pow10(-diff)\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const { numerator, denominator } = getRawPriceRatio(mid)\n const cmp = compareRatios(numerator, denominator, targetNumerator, targetDenominator)\n\n if (cmp === 0) {\n return mid\n }\n\n if (cmp < 0) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorRatio = getRawPriceRatio(floorTick)\n const ceilRatio = getRawPriceRatio(ceilTick)\n\n const floorDiffNumerator = absBigint(\n targetNumerator * floorRatio.denominator - floorRatio.numerator * targetDenominator,\n )\n const ceilDiffNumerator = absBigint(\n targetNumerator * ceilRatio.denominator - ceilRatio.numerator * targetDenominator,\n )\n const floorDiffDenominator = targetDenominator * floorRatio.denominator\n const ceilDiffDenominator = targetDenominator * ceilRatio.denominator\n\n return floorDiffNumerator * ceilDiffDenominator <= ceilDiffNumerator * floorDiffDenominator\n ? floorTick\n : ceilTick\n}\n\n/**\n * Convert a sqrtPriceX96 value to the nearest tick.\n *\n * @param sqrtPriceX96 - The sqrt price in Q64.96 format\n * @returns The tick value (rounded to nearest integer)\n *\n * @example\n * ```typescript\n * const tick = sqrtPriceX96ToTick(2n ** 96n) // 0n\n * ```\n */\nexport function sqrtPriceX96ToTick(sqrtPriceX96: bigint): bigint {\n if (sqrtPriceX96 <= 0n) {\n throw new Error('Sqrt price must be positive')\n }\n\n if (sqrtPriceX96 < MIN_SQRT_PRICE_X96 || sqrtPriceX96 > MAX_SQRT_PRICE_X96) {\n throw new RangeError('Sqrt price out of bounds')\n }\n\n let low = MIN_TICK\n let high = MAX_TICK\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const midSqrt = tickToSqrtPriceX96(mid)\n\n if (midSqrt === sqrtPriceX96) {\n return mid\n }\n\n if (midSqrt < sqrtPriceX96) {\n low = mid + 1n\n } else {\n high = mid - 1n\n }\n }\n\n const floorTick = high\n const ceilTick = low\n\n if (floorTick < MIN_TICK) return MIN_TICK\n if (ceilTick > MAX_TICK) return MAX_TICK\n\n const floorSqrt = tickToSqrtPriceX96(floorTick)\n const ceilSqrt = tickToSqrtPriceX96(ceilTick)\n\n const floorDiff = absBigint(sqrtPriceX96 - floorSqrt)\n const ceilDiff = absBigint(ceilSqrt - sqrtPriceX96)\n\n return floorDiff <= ceilDiff ? floorTick : ceilTick\n}\n\n/**\n * Format a tick value for display.\n *\n * @param tick - The tick value\n * @returns Formatted tick string\n *\n * @example\n * ```typescript\n * formatTick(200000n) // \"200000\"\n * formatTick(-50000n) // \"-50000\"\n * ```\n */\nexport function formatTick(tick: bigint): string {\n return tick.toString()\n}\n\n/**\n * Get the price at a specific tick, returning both token0/token1 and token1/token0 prices.\n *\n * @param tick - The tick value\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Object with both price directions\n *\n * @example\n * ```typescript\n * const prices = getPricesAtTick(200000n, 18n, 6n, 2n)\n * // prices.token0PerToken1 = \"0.00\" (very small)\n * // prices.token1PerToken0 = \"2000.00\" (USDC per ETH)\n * ```\n */\nexport function getPricesAtTick(\n tick: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): { token0PerToken1: string; token1PerToken0: string } {\n const rawRatio = getRawPriceRatio(tick)\n const adjustedRatio = adjustRatioForDecimals(\n rawRatio.numerator,\n rawRatio.denominator,\n decimals0,\n decimals1,\n )\n\n return {\n token0PerToken1: formatRatio(adjustedRatio.denominator, adjustedRatio.numerator, precision),\n token1PerToken0: formatRatio(adjustedRatio.numerator, adjustedRatio.denominator, precision),\n }\n}\n\n/**\n * Format a tick range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @returns Formatted tick range string\n *\n * @example\n * ```typescript\n * formatTickRange(-50000n, 200000n) // \"-50000 - 200000\"\n * ```\n */\nexport function formatTickRange(tickLower: bigint, tickUpper: bigint): string {\n return `${tickLower} - ${tickUpper}`\n}\n\n/**\n * Format a price range for display.\n *\n * @param tickLower - Lower tick\n * @param tickUpper - Upper tick\n * @param decimals0 - Decimals of token0\n * @param decimals1 - Decimals of token1\n * @param precision - Number of decimal places to display\n * @returns Formatted price range string\n *\n * @example\n * ```typescript\n * formatPriceRange(0n, 0n, 18n, 18n, 2n) // \"1.00 - 1.00\"\n * ```\n */\nexport function formatPriceRange(\n tickLower: bigint,\n tickUpper: bigint,\n decimals0: bigint,\n decimals1: bigint,\n precision: bigint,\n): string {\n const lower = tickToPriceDecimalScaled(tickLower, decimals0, decimals1, precision)\n const upper = tickToPriceDecimalScaled(tickUpper, decimals0, decimals1, precision)\n return `${lower} - ${upper}`\n}\n\n/**\n * Calculate the tick spacing for a given fee tier.\n *\n * @param feeBps - Fee in basis points (e.g., 500n for 0.05%)\n * @returns Tick spacing\n *\n * @example\n * ```typescript\n * getTickSpacing(100n) // 1n (0.01% fee tier)\n * getTickSpacing(500n) // 10n (0.05% fee tier)\n * getTickSpacing(3000n) // 60n (0.30% fee tier)\n * getTickSpacing(10000n) // 200n (1.00% fee tier)\n * ```\n */\nexport function getTickSpacing(feeBps: bigint): bigint {\n // Standard Uniswap V3 tick spacings\n switch (feeBps) {\n case 100n:\n return 1n\n case 500n:\n return 10n\n case 3000n:\n return 60n\n case 10000n:\n return 200n\n default: {\n const spacing = feeBps / 50n\n return spacing > 1n ? spacing : 1n\n }\n }\n}\n\n/**\n * Round a tick to the nearest valid tick for a given tick spacing.\n *\n * @param tick - The tick to round\n * @param tickSpacing - The tick spacing\n * @returns Rounded tick\n *\n * @example\n * ```typescript\n * roundToTickSpacing(12345n, 10n) // 12340n\n * roundToTickSpacing(12345n, 60n) // 12360n\n * roundToTickSpacing(-12345n, 10n) // -12350n\n * ```\n */\nexport function roundToTickSpacing(tick: bigint, tickSpacing: bigint): bigint {\n const remainder = tick % tickSpacing\n if (remainder === 0n) {\n return tick\n }\n // Round to nearest\n if (tick >= 0n) {\n return remainder >= tickSpacing / 2n ? tick + (tickSpacing - remainder) : tick - remainder\n }\n\n const absRemainder = -remainder\n return absRemainder >= tickSpacing / 2n\n ? tick - (tickSpacing - absRemainder)\n : tick + absRemainder\n}\n\n/**\n * Result of {@link tickLimits}.\n */\nexport interface TickLimitsResult {\n /** Lower tick limit (clamped to MIN_TICK). */\n low: bigint\n /** Upper tick limit (clamped to MAX_TICK). */\n high: bigint\n}\n\n/**\n * Compute slippage-bounded tick limits around the current tick.\n *\n * 1 tick ≈ 1 basis point (0.01 %) of price change, so a `toleranceBps`\n * of 500 allows roughly 5 % price movement. The result is clamped to\n * the protocol's `[MIN_TICK, MAX_TICK]` range.\n *\n * Useful for setting `tickLimitLow` / `tickLimitHigh` on `openPosition`\n * and `closePosition` to protect against MEV sandwiches and volatile\n * tick moves.\n *\n * @param currentTick - The current pool tick (must be within [MIN_TICK, MAX_TICK]).\n * @param toleranceBps - Slippage tolerance in basis points (≈ ticks). Must be non-negative.\n * @returns Clamped `{ low, high }` tick limits.\n * @throws {RangeError} If `toleranceBps` is negative or `currentTick` is out of bounds.\n *\n * @example\n * ```typescript\n * const { low, high } = tickLimits(200_000n, 500n)\n * // low = 199_500n\n * // high = 200_500n\n *\n * await openPosition({ ..., tickLimitLow: low, tickLimitHigh: high })\n * ```\n */\nexport function tickLimits(currentTick: bigint, toleranceBps: bigint): TickLimitsResult {\n if (toleranceBps < 0n) {\n throw new RangeError(`toleranceBps must be non-negative, got ${toleranceBps}`)\n }\n if (currentTick < MIN_TICK || currentTick > MAX_TICK) {\n throw new RangeError(`currentTick ${currentTick} is out of bounds [${MIN_TICK}, ${MAX_TICK}]`)\n }\n\n const rawLow = currentTick - toleranceBps\n const rawHigh = currentTick + toleranceBps\n const low = rawLow < MIN_TICK ? MIN_TICK : rawLow\n const high = rawHigh > MAX_TICK ? MAX_TICK : rawHigh\n\n if (low > high) {\n throw new RangeError(\n `Computed tick limits are inverted: low ${low} > high ${high} (currentTick=${currentTick}, toleranceBps=${toleranceBps})`,\n )\n }\n\n return { low, high }\n}\n","import { ORACLE_EPOCH_SECONDS } from './constants'\n\nconst ORACLE_EPOCH_SHIFT = 232n\nconst ORACLE_EPOCH_MASK = (1n << 24n) - 1n\nconst ORACLE_TICK_MASK = (1n << 22n) - 1n\n\nfunction decodeSigned22(value: bigint): bigint {\n const signBit = 1n << 21n\n const truncated = value & ORACLE_TICK_MASK\n return (truncated & signBit) === 0n ? truncated : truncated - (1n << 22n)\n}\n\n/** Timing decoded from an OraclePack and resolved against a specific block. */\nexport interface OracleTiming {\n /** Modulo-2^24 oracle epoch stored on-chain. */\n epoch: bigint\n /** Absolute epoch-boundary timestamp reconstructed at or before the supplied block. */\n timestamp: bigint\n}\n\n/** Fixed-width oracle state decoded from an OraclePack. */\nexport interface DecodedOraclePack {\n referenceTick: bigint\n lockMode: bigint\n spotEMA: bigint\n fastEMA: bigint\n slowEMA: bigint\n eonsEMA: bigint\n epoch: bigint\n timestamp: bigint\n}\n\n/**\n * Decode the 24-bit epoch stored at bits 232..255 of OraclePack.\n *\n * The packed timestamp is modulo 2^30 seconds and only identifies an absolute\n * Unix timestamp within the wrap window containing `blockTimestamp`. Supplying\n * the relevant block timestamp resolves it to the latest matching epoch at or\n * before that block, including across the epoch counter wraparound.\n */\nexport function decodeOracleTiming(oraclePack: bigint, blockTimestamp: bigint): OracleTiming {\n const epoch = (oraclePack >> ORACLE_EPOCH_SHIFT) & ORACLE_EPOCH_MASK\n const currentEpoch = oracleEpochAt(blockTimestamp)\n const elapsedEpochs = (currentEpoch - epoch) & ORACLE_EPOCH_MASK\n const currentEpochTimestamp = blockTimestamp - (blockTimestamp % ORACLE_EPOCH_SECONDS)\n return { epoch, timestamp: currentEpochTimestamp - elapsedEpochs * ORACLE_EPOCH_SECONDS }\n}\n\n/** Decode the fixed-width ticks and guardian state stored in OraclePack. */\nexport function decodeOraclePack(oraclePack: bigint, blockTimestamp: bigint): DecodedOraclePack {\n const timing = decodeOracleTiming(oraclePack, blockTimestamp)\n return {\n referenceTick: decodeSigned22(oraclePack >> 96n),\n lockMode: (oraclePack >> 118n) & 3n,\n spotEMA: decodeSigned22(oraclePack >> 120n),\n fastEMA: decodeSigned22(oraclePack >> 142n),\n slowEMA: decodeSigned22(oraclePack >> 164n),\n eonsEMA: decodeSigned22(oraclePack >> 186n),\n ...timing,\n }\n}\n\n/** Return the contract's modulo-2^24 64-second epoch for a block timestamp. */\nexport function oracleEpochAt(timestamp: bigint): bigint {\n return (timestamp / ORACLE_EPOCH_SECONDS) & ORACLE_EPOCH_MASK\n}\n","import { PanopticValidationError } from '../errors'\nimport type { OracleState } from '../types'\nimport { ORACLE_EPOCH_SECONDS } from './constants'\n\nconst UINT24_MASK = (1n << 24n) - 1n\n\nexport interface OracleEmaPeriods {\n spot: bigint\n fast: bigint\n slow: bigint\n eons: bigint\n}\n\nexport interface OracleRiskParameters {\n emaPeriods: OracleEmaPeriods\n maxTicksDelta: bigint\n /** Informational observation clamp; not used by SafeMode diagnosis. May be zero. */\n maxClampDelta: bigint\n}\n\nexport type OracleSafeModeCause =\n | 'externalShock'\n | 'internalDisagreement'\n | 'highDivergence'\n | 'guardianLock'\n | 'unknown'\n\nexport interface OracleSafeModeDiagnosis {\n /** Authoritative value returned by PanopticPool.isSafeMode(). */\n level: bigint\n /** Value reproduced using the known RiskEngine formula and live constants. */\n reproducedLevel: bigint\n matchesOnchain: boolean\n causes: readonly OracleSafeModeCause[]\n externalShockDelta: bigint\n internalDisagreementDelta: bigint\n highDivergenceDelta: bigint\n guardianLocked: boolean\n /** Minimum whole 64-second oracle epochs to wait after the last observation. */\n minimumPokeEpochs: bigint\n shouldPoke: boolean\n}\n\ntype DiagnosticOracleState = Pick<\n OracleState,\n 'currentTick' | 'spotEMA' | 'fastEMA' | 'slowEMA' | 'medianTick' | 'lockMode'\n>\n\nfunction absoluteDelta(left: bigint, right: bigint): bigint {\n return left >= right ? left - right : right - left\n}\n\nfunction epochsForPeriod(period: bigint): bigint {\n return (period + ORACLE_EPOCH_SECONDS - 1n) / ORACLE_EPOCH_SECONDS\n}\n\n/** Decode the four uint24 periods packed by RiskEngine.EMA_PERIODS(). */\nexport function decodeOracleRiskParameters(\n emaPeriods: bigint,\n maxTicksDelta: bigint,\n maxClampDelta: bigint,\n): OracleRiskParameters {\n const decodedPeriods = {\n spot: emaPeriods & UINT24_MASK,\n fast: (emaPeriods >> 24n) & UINT24_MASK,\n slow: (emaPeriods >> 48n) & UINT24_MASK,\n eons: (emaPeriods >> 72n) & UINT24_MASK,\n }\n if (\n decodedPeriods.spot === 0n ||\n decodedPeriods.fast === 0n ||\n decodedPeriods.slow === 0n ||\n decodedPeriods.eons === 0n ||\n maxTicksDelta <= 0n ||\n maxClampDelta < 0n\n ) {\n throw new PanopticValidationError(\n `RiskEngine returned invalid oracle parameters: EMA_PERIODS=${emaPeriods}, ` +\n `MAX_TICKS_DELTA=${maxTicksDelta}, MAX_CLAMP_DELTA=${maxClampDelta}`,\n )\n }\n return { emaPeriods: decodedPeriods, maxTicksDelta, maxClampDelta }\n}\n\n/** Explain the on-chain SafeMode level using this deployment's RiskEngine constants. */\nexport function diagnoseOracleSafeMode(\n state: DiagnosticOracleState,\n parameters: OracleRiskParameters,\n onchainLevel: bigint,\n): OracleSafeModeDiagnosis {\n const externalShockDelta = absoluteDelta(state.currentTick, state.spotEMA)\n const internalDisagreementDelta = absoluteDelta(state.spotEMA, state.fastEMA)\n const highDivergenceDelta = absoluteDelta(state.medianTick, state.slowEMA)\n const internalThreshold = parameters.maxTicksDelta / 2n\n const externalShock = externalShockDelta > parameters.maxTicksDelta\n const internalDisagreement = internalDisagreementDelta > internalThreshold\n const highDivergence = highDivergenceDelta > internalThreshold\n const guardianLocked = state.lockMode !== 0n\n\n const algorithmicLevel =\n (externalShock ? 1n : 0n) + (internalDisagreement ? 1n : 0n) + (highDivergence ? 1n : 0n)\n const reproducedLevel = algorithmicLevel + state.lockMode\n const matchesOnchain = reproducedLevel === onchainLevel\n const causes: OracleSafeModeCause[] = []\n if (matchesOnchain) {\n if (externalShock) causes.push('externalShock')\n if (internalDisagreement) causes.push('internalDisagreement')\n if (highDivergence) causes.push('highDivergence')\n } else {\n causes.push('unknown')\n }\n if (guardianLocked) causes.push('guardianLock')\n\n const candidateEpochs: bigint[] = []\n if (!matchesOnchain) candidateEpochs.push(1n)\n if (highDivergence) candidateEpochs.push(1n)\n if (externalShock) candidateEpochs.push(epochsForPeriod(parameters.emaPeriods.spot))\n if (internalDisagreement) candidateEpochs.push(epochsForPeriod(parameters.emaPeriods.fast))\n const minimumPokeEpochs = candidateEpochs.reduce(\n (minimum, epochs) => (minimum === 0n || epochs < minimum ? epochs : minimum),\n 0n,\n )\n\n return {\n level: onchainLevel,\n reproducedLevel,\n matchesOnchain,\n causes,\n externalShockDelta,\n internalDisagreementDelta,\n highDivergenceDelta,\n guardianLocked,\n minimumPokeEpochs,\n shouldPoke: onchainLevel > 0n && !guardianLocked,\n }\n}\n","/**\n * Client-side greeks for the Panoptic v2 SDK.\n *\n * All functions accept bigint inputs (ticks, sizes) and return bigint values\n * in the natural token units — no artificial WAD scaling. The tick-based price\n * (1.0001^tick) naturally encodes the decimal conversion between tokens.\n *\n * Uses pure sqrtPriceX96 arithmetic for exact on-chain fidelity with PanopticQuery.\n * All intermediate calculations keep X96/X192 precision until final scaling.\n *\n * - Value: in numeraire token smallest units (e.g., USDC wei if numeraire is USDC)\n * - Delta: in asset token smallest units (e.g., WETH wei if asset is WETH)\n * - Gamma (dollar-gamma): in numeraire token smallest units\n *\n * @module v2/greeks\n */\n\nimport { tickToSqrtPriceX96 } from '../formatters/tick'\nimport type { TokenIdLeg } from '../types'\n\n// --- Internal Helpers ---\n\n/** Fixed-point scale constants for sqrtPriceX96 arithmetic */\nconst Q96 = 1n << 96n\nconst Q192 = 1n << 192n\n\n/**\n * Convert tick to quote-denominated tick based on asset direction.\n *\n * When isAssetToken0 = true (asset is token0, numeraire is token1):\n * - Tick already encodes price as token1/token0 (numeraire per asset)\n * - Return tick unchanged\n *\n * When isAssetToken0 = false (asset is token1, numeraire is token0):\n * - Tick encodes price as token1/token0, but we need token0/token1 (numeraire per asset)\n * - Invert by negating: 1/price = 1.0001^(-tick)\n */\nfunction quoteTick(tick: bigint, isAssetToken0: boolean): bigint {\n return isAssetToken0 ? tick : -tick\n}\n\n/**\n * Divide with truncation toward zero (matches Solidity division behavior).\n *\n * JavaScript bigint division uses floor (toward negative infinity), but Solidity\n * truncates toward zero. For on-chain fidelity, we must match Solidity.\n *\n * Example:\n * - Solidity: -7 / 2 = -3 (truncate toward zero)\n * - JS bigint: -7n / 2n = -4n (floor toward -∞)\n * - This function: divTrunc(-7n, 2n) = -3n ✓\n */\nfunction divTrunc(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) return 0n\n\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n\n // If signs differ and there's a remainder, JS floored when we need to truncate\n // Add 1 to move toward zero\n if (numerator < 0n !== denominator < 0n && remainder !== 0n) {\n return quotient + 1n\n }\n\n return quotient\n}\n\n/** Resolve isAssetToken0: optional assetIndex overrides leg.asset */\nfunction resolveAssetDirection(leg: Pick<TokenIdLeg, 'asset'>, assetIndex?: bigint): boolean {\n return assetIndex !== undefined ? assetIndex === 0n : leg.asset === 0n\n}\n\n/**\n * Compute the tokenType-denominated notional of a width=0 (loan/credit) leg.\n *\n * When leg.asset !== leg.tokenType, positionSize is in leg.asset units and\n * the borrowed notional is encoded via leg.strike: notional_tokenType_raw =\n * positionSize_raw × 1.0001^strike (a raw-to-raw ratio, unquoted by pool direction).\n * When leg.asset === leg.tokenType, m is already the notional (old convention).\n *\n * `m > 0` for loans (isLong=false), `m < 0` for credits (isLong=true), so the\n * returned notional is signed the same way.\n */\nfunction computeWidth0Notional(leg: TokenIdLeg, m: bigint): bigint {\n const scaleByStrike = leg.asset !== leg.tokenType\n if (!scaleByStrike) return m\n // The UI stores strike with a sign that depends on leg.asset:\n // priceTokenTypePerAsset = 1.0001^(leg.asset === 0 ? strike : -strike)\n // Mirror that here so K_raw matches the intended notional scaling.\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n return divTrunc(m * KrawX192, Q192)\n}\n\n/**\n * Calculate value for a width=0 (loan/credit) leg.\n * Width=0 means the range is a single tick (the strike), so there's no meaningful\n * \"in range\" — we use the below/above formulas which avoid division by (r-1)=0.\n *\n * This is the DEBT-ONLY value (the borrowed/lent obligation), used by delta/greeks\n * aggregation where the held-collateral side lives in a separate wallet/CT term. For\n * a standalone payoff chart that must reflect the net user-experienced payoff (which\n * depends on Zap vs Cover-at-mint), use `getLegNetValueWidth0`.\n */\nfunction getLegValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n _definedRisk: boolean,\n): bigint {\n // For loan/credit legs (width=0), value depends on the borrowed token.\n // m > 0 for loans (isLong=false), m < 0 for credits (isLong=true).\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n const notional = computeWidth0Notional(leg, m)\n\n if (borrowsAsset) {\n // Asset loan/credit: debt PnL = -notional*(P - Pm); crosses y=0 at mint price, delta=-notional.\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n } else {\n // Numeraire loan/credit: the obligation is a constant amount of the numeraire token,\n // so its value doesn't change with price. getLegValue is mint-relative PnL (option\n // legs cancel the mint baseline via `itm`; the asset branch above returns\n // -notional*(P - Pm), which is 0 at mint), so the numeraire branch's mint-relative PnL\n // is value(P) - value(Pm) = const - const = 0. Returning a nonzero constant here would\n // shift the whole PnL curve/baseline by the notional (double-counting the credit).\n return 0n\n }\n}\n\n/**\n * Calculate the NET (user-experienced) payoff value for a width=0 (loan/credit) leg.\n *\n * Unlike `getLegValueWidth0` (debt-only), this includes the collateral/holding side and\n * therefore depends on how the position was opened:\n *\n * - **Cover at mint** (`swapAtMint = false`): the collateral is sourced in the SAME token as\n * the debt/credit, so the holding side exactly offsets it → net PnL is FLAT (0 everywhere,\n * mint-relative), regardless of which token the leg is denominated in.\n * - **Zap** (`swapAtMint = true`): the collateral is sourced in the OTHER token, leaving a\n * ±1-delta line in the asset (ETH), anchored to 0 at the mint price:\n * - USDC loan → zap to ETH: +1 (long ETH)\n * - ETH loan → zap to USDC: −1 (short ETH)\n * - USDC credit ← zap from ETH: −1 (short ETH)\n * - ETH credit ← zap from USDC: +1 (long ETH)\n *\n * @returns Net leg value in numeraire token smallest units (mint-relative PnL).\n */\nexport function getLegNetValueWidth0(\n leg: TokenIdLeg,\n m: bigint,\n qCurrentTick: bigint,\n qMintTick: bigint,\n isAssetToken0: boolean,\n swapAtMint: boolean,\n itmOffsetNotional: bigint = 0n,\n): bigint {\n // Cover at mint: collateral in the same token as the debt/credit cancels it → flat.\n if (!swapAtMint) return 0n\n\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n\n // ITM-neutralizing credits/loans are sized to offset an option leg's mint-time ITM,\n // which was zapped into the other token under swapAtMint and therefore carries the same\n // ±delta line this leg would otherwise add. Net the leg's notional against that ITM\n // (`itmOffsetNotional`, same token side, opposite sign) so a correctly-sized credit\n // cancels to flat and only the residual (over/under-sizing) contributes a swap line.\n const notional = computeWidth0Notional(leg, m) + itmOffsetNotional\n\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PX192 = sqrtP * sqrtP\n const PmX192 = sqrtPm * sqrtPm\n\n if (borrowsAsset) {\n // Debt/credit is in the asset (ETH); zapping the collateral into the numeraire leaves the\n // debt-only asset exposure -notional*(P - Pm). (Loan → short ETH; credit → long ETH.)\n return divTrunc(-notional * (PX192 - PmX192), Q192)\n }\n\n // Debt/credit is in the numeraire (USDC); zapping sources/spends the asset (ETH). We hold\n // notional/Pm units of ETH, worth (notional/Pm)*(P - Pm) = notional*(P/Pm) - notional in\n // numeraire. (Loan → long ETH; credit → short ETH.) Zero at mint by construction.\n return divTrunc(notional * PX192, PmX192) - notional\n}\n\n/**\n * Compute the mint-time ITM (in-the-money) adjustment for an option leg.\n *\n * This is the `itm` baseline used by {@link getLegValue}: the amount by which the\n * position was already ITM at mint, expressed in the leg's natural units:\n * - Puts: numeraire units (added directly to the put's `debt*K + v` value).\n * - Calls: asset-ratio units (the call value multiplies it by price: `itm*P`/`itm*Pm`).\n *\n * Extracted so callers (e.g. {@link calculatePositionValue}) can build a per-side ITM\n * notional pool to net width=0 credit/loan legs against — an ITM-neutralizing credit\n * was sized to offset exactly this amount, so it should not add a spurious swap line.\n */\nfunction computeOptionItm(\n m: bigint,\n qStrikeTick: bigint,\n qMintTick: bigint,\n halfWidthTick: bigint,\n isPut: boolean,\n): bigint {\n if (isPut) {\n // Put ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = (K - Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (KX192 - PmX192), Q192)\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = 0\n return 0n\n }\n // In range: itm = m * (sqrt(K*r) - sqrt(Pm))^2 / (r - 1)\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const rX192 = sqrtR * sqrtR\n const diff = sqrtKR - sqrtPm // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n\n // Call ITM adjustment\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itm = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itm = (1 - K/Pm) * m\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const KX192 = sqrtK * sqrtK\n const PmX192 = sqrtPm * sqrtPm\n return divTrunc(m * (PmX192 - KX192), PmX192)\n }\n // In range: itm = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const rX192 = sqrtR * sqrtR\n // sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = divTrunc(sqrtK * Q96, sqrtPm)\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n return divTrunc(m * diffSqX192, rX192 - Q192)\n}\n\n// --- Public Helpers ---\n\n/**\n * Check if leg is a call option (vs put).\n *\n * A call is when the leg moves the asset token:\n * - If asset is token0: call when tokenType=0\n * - If asset is token1: call when tokenType=1\n */\nexport function isCall(tokenType: bigint, isAssetToken0: boolean): boolean {\n return isAssetToken0 ? tokenType === 0n : tokenType === 1n\n}\n\n/**\n * Check if position has defined risk (is a spread).\n *\n * A position is defined risk if it has 2+ legs of the same tokenType\n * with both long and short exposure.\n */\nexport function isDefinedRisk(legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]): boolean {\n if (legs.length < 2) return false\n\n for (const tt of [0n, 1n]) {\n const group = legs.filter((l) => l.tokenType === tt)\n if (group.length >= 2 && group.some((l) => l.isLong) && group.some((l) => !l.isLong)) {\n return true\n }\n }\n return false\n}\n\n// --- Per-Leg Greeks ---\n\n/**\n * Calculate the value of a single leg.\n *\n * Value represents the current P&L of the position in numeraire token units.\n * Combines base value (from Panoptic's piecewise formula), debt, and ITM adjustment.\n *\n * Uses sqrtPriceX96 for all calculations to maintain precision and on-chain fidelity.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param mintTick - Tick at position mint\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg value in numeraire token smallest units\n */\nexport function getLegValue(\n leg: TokenIdLeg,\n currentTick: bigint,\n mintTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n definedRisk: boolean,\n assetIndex?: bigint,\n swapAtMint?: boolean,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit (leg.width === 0n): when the caller specifies how the position was\n // opened (swapAtMint), return the NET user-experienced payoff (Zap vs Cover) instead of\n // the debt-only value. Narrow options whose halfWidth rounds to 0 are excluded.\n if (leg.width === 0n && swapAtMint !== undefined) {\n return getLegNetValueWidth0(leg, m, qCurrentTick, qMintTick, isAssetToken0, swapAtMint)\n }\n\n // Width=0 (loans/credits): single-tick position, no range to integrate over.\n if (halfWidthTick === 0n) {\n return getLegValueWidth0(\n leg,\n m,\n qCurrentTick,\n qStrikeTick,\n qMintTick,\n isAssetToken0,\n definedRisk,\n )\n }\n\n // Compute base value: v = f(P, K, r) from Panoptic's piecewise formula\n let v: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: v = m * P\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n v = divTrunc(m * PX192, Q192)\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: v = m * K\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n v = divTrunc(m * KX192, Q192)\n } else {\n // In range: v = m * (2*sqrt(P*K*r) - P - K) / (r - 1)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const sqrtPKR = tickToSqrtPriceX96(qCurrentTick + qStrikeTick + halfWidthTick)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick)\n\n const PX192 = sqrtP * sqrtP\n const KX192 = sqrtK * sqrtK\n const rX192 = sqrtR * sqrtR\n\n // v = m * (2*sqrtPKR/2^96 - PX192/2^192 - KX192/2^192) / ((rX192 - 2^192)/2^192)\n // = m * (2*sqrtPKR*2^96 - PX192 - KX192) / (rX192 - 2^192)\n const numerator = m * (2n * sqrtPKR * Q96 - PX192 - KX192)\n const denominator = rX192 - Q192\n v = divTrunc(numerator, denominator)\n }\n\n const debt = -m\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n // Compute ITM adjustment (differs for puts vs calls)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n\n // Compute final result based on option type\n if (isPut) {\n // Put: result = debt * K + v + itm\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const KX192 = sqrtK * sqrtK\n const debtK = divTrunc(debt * KX192, Q192)\n return debtK + v + itm\n } else {\n // Call: result = debt*P + v + itm*Pm (if defined risk) or debt*P + v + itm*P (if not)\n const sqrtP = tickToSqrtPriceX96(qCurrentTick)\n const PX192 = sqrtP * sqrtP\n const debtP = divTrunc(debt * PX192, Q192)\n\n if (definedRisk) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const PmX192 = sqrtPm * sqrtPm\n const itmPm = divTrunc(itm * PmX192, Q192)\n return debtP + v + itmPm\n } else {\n const itmP = divTrunc(itm * PX192, Q192)\n return debtP + v + itmP\n }\n }\n}\n\n/**\n * Calculate the delta of a single leg.\n *\n * Delta is the rate of change of position value with respect to price.\n * For puts: delta = vDelta\n * For calls: delta = debtDelta + vDelta + itmDelta (if not defined risk)\n *\n * Uses sqrtPriceX96 for all price calculations to maintain precision.\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param mintTick - Tick at mint (optional, for ITM adjustment)\n * @param definedRisk - Whether position is defined risk\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg delta in asset token smallest units\n */\nexport function getLegDelta(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n\n // True loan/credit: leg.width === 0n (not just halfWidth rounding to 0).\n // Debt-side exposure only — no option-like piecewise formula.\n if (leg.width === 0n) {\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n if (!borrowsAsset) return 0n\n // See getLegValueWidth0 for the notional-scaling rationale.\n if (leg.asset === leg.tokenType) return -m\n const signedStrike = leg.asset === 0n ? leg.strike : -leg.strike\n const sqrtKraw = tickToSqrtPriceX96(signedStrike)\n const KrawX192 = sqrtKraw * sqrtKraw\n const notional = divTrunc(m * KrawX192, Q192)\n return -notional\n }\n\n // Narrow option whose halfWidth rounds to 0: use option-like width=0 branch\n if (halfWidthTick === 0n) {\n const vDelta = qCurrentTick <= qStrikeTick ? m : 0n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n if (isPut) return vDelta\n\n // Call: add debt delta and ITM delta (same as normal path but no in-range branch)\n const debtDelta = -m\n let itmDelta = 0n\n if (mintTick !== undefined && !definedRisk) {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n if (qMintTick > qStrikeTick) {\n const sqrtPm = tickToSqrtPriceX96(qMintTick)\n const sqrtK = tickToSqrtPriceX96(qStrikeTick)\n const PmX192 = sqrtPm * sqrtPm\n const KX192 = sqrtK * sqrtK\n itmDelta = divTrunc((PmX192 - KX192) * m, PmX192)\n }\n }\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n }\n\n // Compute vDelta: derivative of value with respect to price\n // vDelta = P < lo ? m : P > hi ? 0 : (m * (sqrt(K*r)/sqrt(P) - 1)) / (r - 1)\n let vDelta: bigint\n\n if (qCurrentTick < qStrikeTick - halfWidthTick) {\n // Below range: vDelta = m\n vDelta = m\n } else if (qCurrentTick > qStrikeTick + halfWidthTick) {\n // Above range: vDelta = 0\n vDelta = 0n\n } else {\n // In range: vDelta = m * (sqrt(K*r) - sqrt(P)) / (sqrt(P) * (r - 1))\n const sqrtP = tickToSqrtPriceX96(qCurrentTick) // X96\n const sqrtKR = tickToSqrtPriceX96(qStrikeTick + halfWidthTick) // sqrt(K*r) in X96\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // vDelta = m * (sqrtKR - sqrtP)/2^96 / (sqrtP/2^96 * (rX192 - 2^192)/2^192)\n // = m * (sqrtKR - sqrtP) * 2^192 / (sqrtP * (rX192 - 2^192))\n const numerator = m * (sqrtKR - sqrtP) * Q192\n const denominator = sqrtP * (rX192 - Q192)\n vDelta = divTrunc(numerator, denominator)\n }\n\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n\n if (isPut) {\n return vDelta\n }\n\n // Call: add debt delta and ITM delta\n const debtDelta = -m\n\n const itmDelta =\n mintTick === undefined\n ? 0n\n : (() => {\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n\n if (qMintTick < qStrikeTick - halfWidthTick) {\n // Below range: itmDelta = 0\n return 0n\n } else if (qMintTick > qStrikeTick + halfWidthTick) {\n // Above range: itmDelta = (1 - K/Pm) * m = (Pm - K) * m / Pm\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const PmX192 = sqrtPm * sqrtPm // X192\n const KX192 = sqrtK * sqrtK // X192\n\n // itmDelta = (1 - K/Pm) * m = (PmX192 - KX192) * m / PmX192\n return divTrunc((PmX192 - KX192) * m, PmX192)\n } else {\n // In range: itmDelta = m * (sqrt(r) - sqrt(K/Pm))^2 / (r - 1)\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96\n const sqrtK = tickToSqrtPriceX96(qStrikeTick) // X96\n const sqrtPm = tickToSqrtPriceX96(qMintTick) // X96\n const rX192 = sqrtR * sqrtR // X192\n\n // sqrt(K/Pm) = sqrtK / sqrtPm (both X96, so scale cancels)\n // But we need (sqrt(r) - sqrt(K/Pm))^2, so work in X96:\n // sqrtKPm = sqrt(K/Pm) in X96 = sqrtK * 2^96 / sqrtPm\n const sqrtKPmX96 = (sqrtK * Q96) / sqrtPm // X96\n\n // (sqrt(r) - sqrt(K/Pm))^2 = (sqrtR - sqrtKPmX96)^2 / 2^192\n const diff = sqrtR - sqrtKPmX96 // X96\n const diffSqX192 = diff * diff // X192\n\n // itmDelta = m * diffSqX192 / 2^192 / (rX192 / 2^192 - 1)\n // = m * diffSqX192 / (rX192 - 2^192)\n return divTrunc(m * diffSqX192, rX192 - Q192)\n }\n })()\n\n return definedRisk ? debtDelta + vDelta : debtDelta + vDelta + itmDelta\n}\n\n/** Convert a delta between token frames at the current pool tick. */\nexport function toVaultFrameAtTick(\n delta: bigint,\n fromAsset: bigint,\n vaultAssetIndex: 0n | 1n,\n currentTick: bigint,\n flipSignOnAssetInversion = false,\n): bigint {\n if (fromAsset === vaultAssetIndex) return delta\n const sqrtPriceX96 = tickToSqrtPriceX96(currentTick)\n const converted =\n vaultAssetIndex === 0n\n ? (delta * Q192) / (sqrtPriceX96 * sqrtPriceX96)\n : (delta * sqrtPriceX96 * sqrtPriceX96) / Q192\n return flipSignOnAssetInversion ? -converted : converted\n}\n\n/**\n * Calculate one leg's wallet-aware delta in the vault asset frame.\n *\n * Width-zero loans and credits must be evaluated directly in the vault frame.\n * Option legs remain in their natural leg frame until converted at the mark tick.\n */\nexport function getLegDeltaInVaultFrame(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n mintTick: bigint | undefined,\n definedRisk: boolean,\n vaultAssetIndex: 0n | 1n,\n): bigint {\n if (leg.width === 0n) {\n return getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n vaultAssetIndex,\n )\n }\n\n const legDelta = getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n )\n return toVaultFrameAtTick(legDelta, leg.asset, vaultAssetIndex, currentTick, true)\n}\n\n/**\n * Calculate the gamma (dollar gamma) of a single leg.\n *\n * Formula: gamma = (m * sqrt(K * P * r)) / (2 * (r - 1))\n * where:\n * - m = positionSize * optionRatio (with sign based on long/short)\n * - K = strike price (numeraire/asset)\n * - P = current price (numeraire/asset)\n * - r = 1.0001^(width*tickSpacing/2) ≈ 1 (dimensionless ratio)\n *\n * Uses sqrtPriceX96 arithmetic:\n * - sqrt(K*P*r) = tickToSqrtPriceX96(strikeₜ + currentₜ + widthₜ/2)\n * - Keeps X96/X192 precision until final division\n *\n * @param leg - The leg to calculate\n * @param currentTick - Current pool tick\n * @param positionSize - Position size in asset token smallest units\n * @param poolTickSpacing - Pool tick spacing\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset, 1n = token1)\n * @returns Leg gamma in numeraire token smallest units\n */\nexport function getLegGamma(\n leg: TokenIdLeg,\n currentTick: bigint,\n positionSize: bigint,\n poolTickSpacing: bigint,\n assetIndex?: bigint,\n): bigint {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n\n // Convert to quote-denominated ticks (negate if asset is token0)\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n\n // True loan: no gamma\n if (leg.width === 0n) return 0n\n\n // Narrow option whose halfWidth rounds to 0: no curvature (denominator 2*(r-1)=0)\n if (halfWidthTick === 0n) return 0n\n\n // Range check: gamma is zero outside [strike - halfWidth, strike + halfWidth]\n // This works in both normal and inverted tick space\n if (qCurrentTick < qStrikeTick - halfWidthTick || qCurrentTick > qStrikeTick + halfWidthTick) {\n return 0n\n }\n\n // Position size with sign: gamma uses inverted multiplier (long = positive, short = negative)\n const m = leg.isLong ? positionSize * leg.optionRatio : -(positionSize * leg.optionRatio)\n\n // sqrt(K * P * r) using tick addition: sqrt(K*P*r) = sqrt(1.0001^(K_tick + P_tick + r_tick))\n const sqrtKPR = tickToSqrtPriceX96(qStrikeTick + qCurrentTick + halfWidthTick) // X96 scale\n\n // r = 1.0001^(halfWidthTick), compute as (sqrtR)^2 to maintain precision\n const sqrtR = tickToSqrtPriceX96(halfWidthTick) // X96 scale\n const rX192 = sqrtR * sqrtR // X192 scale: r * 2^192\n\n // gamma = m * sqrt(K*P*r) / (2 * (r - 1))\n // = m * (sqrtKPR / 2^96) / (2 * (rX192/2^192 - 1))\n // = m * sqrtKPR * 2^192 / (2^96 * 2 * (rX192 - 2^192))\n // = m * sqrtKPR * 2^96 / (2 * (rX192 - 2^192))\n const numerator = m * sqrtKPR * Q96 // [asset] * [numeraire/asset * 2^96] * 2^96 = [numeraire * 2^192]\n const denominator = 2n * (rX192 - Q192) // 2 * (r - 1) in X192 scale\n\n return divTrunc(numerator, denominator) // [numeraire]\n}\n\n// --- Position-Level Aggregates ---\n\n/**\n * Parameters for position-level greek calculations.\n */\nexport interface PositionGreeksInput {\n /** Position legs */\n legs: TokenIdLeg[]\n /** Current pool tick */\n currentTick: bigint\n /** Tick at position mint */\n mintTick: bigint\n /** Position size in asset token smallest units */\n positionSize: bigint\n /** Pool tick spacing */\n poolTickSpacing: bigint\n /** Optional override for leg.asset on all legs (0n = token0 is asset, 1n = token1) */\n assetIndex?: bigint\n /**\n * How width=0 (loan/credit) legs were opened. When provided, `calculatePositionValue`\n * returns the NET user-experienced payoff for those legs (Zap = ±1 line, Cover = flat)\n * instead of the debt-only value. Leave undefined for delta/greeks aggregation, which\n * accounts for the held collateral separately.\n */\n swapAtMint?: boolean\n}\n\n/**\n * Calculate total value across all legs.\n */\nexport function calculatePositionValue(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const definedRisk = isDefinedRisk(legs)\n\n // Fast path: without swapAtMint there is no width=0 net-payoff (delta/greeks aggregation),\n // so no ITM netting is needed — value each leg independently.\n if (swapAtMint === undefined) {\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n ),\n 0n,\n )\n }\n\n // Pass 1: accumulate each option leg's mint-time ITM into a per-side notional pool. Under\n // swapAtMint the ITM was zapped into the other token, so a width=0 credit/loan that was\n // created to neutralize it (see getLegNetValueWidth0) should net against this pool instead\n // of adding a duplicate swap line. Puts contribute numeraire ITM; calls contribute asset ITM.\n let numeraireItmPool = 0n\n let assetItmPool = 0n\n for (const leg of legs) {\n const halfWidthTick = (leg.width * poolTickSpacing) / 2n\n if (leg.width === 0n || halfWidthTick === 0n) continue // not a valued option leg\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const qStrikeTick = quoteTick(leg.strike, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const isPut = !isCall(leg.tokenType, isAssetToken0)\n const itm = computeOptionItm(m, qStrikeTick, qMintTick, halfWidthTick, isPut)\n if (isPut) numeraireItmPool += itm\n else assetItmPool += itm\n }\n\n // Pass 2: sum leg values, netting width=0 legs against the matching ITM pool (consumed once).\n let sum = 0n\n for (const leg of legs) {\n if (leg.width === 0n) {\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const borrowsAsset = isCall(leg.tokenType, isAssetToken0)\n const offset = borrowsAsset ? assetItmPool : numeraireItmPool\n if (borrowsAsset) assetItmPool = 0n\n else numeraireItmPool = 0n\n const qCurrentTick = quoteTick(currentTick, isAssetToken0)\n const qMintTick = quoteTick(mintTick, isAssetToken0)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n sum += getLegNetValueWidth0(\n leg,\n m,\n qCurrentTick,\n qMintTick,\n isAssetToken0,\n swapAtMint,\n offset,\n )\n } else {\n sum += getLegValue(\n leg,\n currentTick,\n mintTick,\n positionSize,\n poolTickSpacing,\n definedRisk,\n assetIndex,\n swapAtMint,\n )\n }\n }\n return sum\n}\n\n/**\n * Calculate total delta across all legs.\n */\nexport function calculatePositionDelta(input: PositionGreeksInput): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate debt-only position delta in a single target asset frame.\n *\n * Option legs are first valued in their natural `leg.asset` frame, then\n * converted into `assetIndex` using the current pool price. Width-zero legs\n * are evaluated directly in the target frame.\n *\n * Width=0 loan/credit legs include only their debt obligation. The held-token\n * side must be added separately from account collateral balances, preventing a\n * zap from being counted once in the position and again in collateral.\n */\nexport function calculatePositionDeltaDebtOnly(\n input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex } = input\n const definedRisk = isDefinedRisk(legs)\n\n return legs.reduce(\n (sum, leg) =>\n sum +\n getLegDeltaInVaultFrame(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n ),\n 0n,\n )\n}\n\n/**\n * Calculate total gamma across all legs.\n */\nexport function calculatePositionGamma(input: PositionGreeksInput): bigint {\n const { legs, currentTick, positionSize, poolTickSpacing, assetIndex } = input\n\n return legs.reduce(\n (sum, leg) => sum + getLegGamma(leg, currentTick, positionSize, poolTickSpacing, assetIndex),\n 0n,\n )\n}\n\n/**\n * Position greeks result.\n */\nexport interface PositionGreeksResult {\n /** Position value in numeraire token smallest units */\n value: bigint\n /** Position delta in asset token smallest units */\n delta: bigint\n /** Position gamma in numeraire token smallest units */\n gamma: bigint\n}\n\n/**\n * Calculate all greeks for a position.\n */\nexport function calculatePositionGreeks(input: PositionGreeksInput): PositionGreeksResult {\n return {\n value: calculatePositionValue(input),\n delta: calculatePositionDelta(input),\n gamma: calculatePositionGamma(input),\n }\n}\n\n// --- Portfolio (Multi-Position) Aggregates ---\n\n/**\n * Aggregate value across multiple independent positions.\n *\n * Each entry is valued with its OWN `positionSize`, `mintTick`, and legs, then\n * summed. Do NOT collapse multiple positions into one synthetic `PositionGreeksInput`\n * with a shared `positionSize` — `m = positionSize * optionRatio` is per-position, so a\n * shared size double-counts (and integer `optionRatio` cannot encode fractional shares).\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total value in numeraire token smallest units\n */\nexport function calculatePortfolioValue(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionValue(input), 0n)\n}\n\n/**\n * Aggregate delta across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePortfolioDelta(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionDelta(input), 0n)\n}\n\n/**\n * Aggregate gamma across multiple independent positions.\n *\n * See {@link calculatePortfolioValue} for why each position must keep its own\n * `positionSize` rather than being merged into one synthetic position.\n *\n * @param positions - One `PositionGreeksInput` per open position\n * @returns Total gamma in numeraire token smallest units\n */\nexport function calculatePortfolioGamma(positions: PositionGreeksInput[]): bigint {\n return positions.reduce((sum, input) => sum + calculatePositionGamma(input), 0n)\n}\n\n/**\n * Calculate all greeks aggregated across multiple independent positions.\n */\nexport function calculatePortfolioGreeks(positions: PositionGreeksInput[]): PositionGreeksResult {\n return {\n value: calculatePortfolioValue(positions),\n delta: calculatePortfolioDelta(positions),\n gamma: calculatePortfolioGamma(positions),\n }\n}\n\n// --- Loan/Credit Swap-Aware Delta ---\n\n/**\n * Calculate the effective delta of a loan leg accounting for swapAtMint.\n *\n * A loan borrows one token and (optionally) swaps it for the other at mint.\n * The net delta depends on whether the swap occurred:\n *\n * | Scenario | Result |\n * |-----------------------|-------------------------------------------------|\n * | No swap | 0n (hold what you owe, net zero) |\n * | Swap + borrows asset | -m (hold numeraire, owe asset → short exposure) |\n * | Swap + borrows numer. | +m (hold asset, owe numeraire → long exposure) |\n *\n * Only meaningful for legs with `width === 0n`. For options, use `getLegDelta`.\n *\n * @param leg - The loan leg\n * @param positionSize - Position size in asset token smallest units\n * @param swapAtMint - Whether the borrowed tokens were swapped at mint\n * @param assetIndex - Optional override for leg.asset (0n = token0 is asset)\n * @returns Effective delta in asset token smallest units\n */\nexport function getLoanEffectiveDelta(\n leg: TokenIdLeg,\n positionSize: bigint,\n swapAtMint: boolean,\n assetIndex?: bigint,\n): bigint {\n if (!swapAtMint) return 0n\n\n const isAssetToken0 = resolveAssetDirection(leg, assetIndex)\n const m = leg.isLong ? -(positionSize * leg.optionRatio) : positionSize * leg.optionRatio\n const borrowsAsset = isAssetToken0 ? leg.tokenType === 0n : leg.tokenType === 1n\n\n return borrowsAsset ? -m : m\n}\n\n/**\n * Calculate total delta for a position, using swap-aware delta for loan legs.\n *\n * For legs with `width === 0n` (loans/credits), uses `getLoanEffectiveDelta`\n * which accounts for the swapAtMint flag. For option legs (`width > 0n`),\n * uses the standard `getLegDelta`.\n *\n * @param input - Position greeks input plus swapAtMint flag\n * @returns Total delta in asset token smallest units\n */\nexport function calculatePositionDeltaWithSwap(\n input: PositionGreeksInput & { swapAtMint: boolean },\n): bigint {\n const { legs, currentTick, mintTick, positionSize, poolTickSpacing, assetIndex, swapAtMint } =\n input\n const optionLegs = legs.filter((l) => l.width !== 0n)\n const definedRisk = isDefinedRisk(optionLegs)\n\n return legs.reduce((sum, leg) => {\n if (leg.width === 0n) {\n return sum + getLoanEffectiveDelta(leg, positionSize, swapAtMint, assetIndex)\n }\n return (\n sum +\n getLegDelta(\n leg,\n currentTick,\n positionSize,\n poolTickSpacing,\n mintTick,\n definedRisk,\n assetIndex,\n )\n )\n }, 0n)\n}\n","/**\n * TokenId constants for the Panoptic v2 SDK.\n * @module v2/tokenId/constants\n */\n\n/**\n * Default vegoid value used in pool ID encoding.\n */\nexport const DEFAULT_VEGOID = 8n\n\n/**\n * Default MAX_SPREAD value (90_000 = 9 * 10_000).\n * On-chain: removed/net ratio cap, in units of 1/10_000.\n */\nexport const DEFAULT_MAX_SPREAD = 90_000n\n\n/**\n * Standard tick widths matching DTE gamma profiles.\n *\n * These represent the position width in ticks for each timescale.\n * Width = tickUpper - tickLower.\n */\nexport const STANDARD_TICK_WIDTHS = {\n /** 1-hour expiry profile (240 ticks) */\n '1H': 240n,\n /** 1-day expiry profile (720 ticks) */\n '1D': 720n,\n /** 1-week expiry profile (2400 ticks) */\n '1W': 2400n,\n /** 1-month expiry profile (4800 ticks) */\n '1M': 4800n,\n /** 1-year expiry profile (15000 ticks) */\n '1Y': 15000n,\n} as const\n\n/**\n * Timescale key type for STANDARD_TICK_WIDTHS.\n */\nexport type Timescale = keyof typeof STANDARD_TICK_WIDTHS\n\n/**\n * Bit positions and sizes for TokenId encoding.\n */\nexport const TOKEN_ID_BITS = {\n /** Pool ID occupies bits 0-63 */\n POOL_ID_SIZE: 64n,\n /** Vegoid starts at bit 40 within pool ID */\n VEGOID_STARTING_BIT: 40n,\n /** Vegoid is 8 bits */\n VEGOID_SIZE: 8n,\n /** Tick spacing starts at bit 48 within pool ID */\n TICK_SPACING_STARTING_BIT: 48n,\n /** Tick spacing is 16 bits */\n TICK_SPACING_SIZE: 16n,\n /** Each leg is 48 bits */\n LEG_SIZE: 48n,\n /** Maximum number of legs per TokenId */\n MAX_LEGS: 4n,\n} as const\n\n/**\n * Bit positions within a leg (relative to leg start).\n */\nexport const LEG_BITS = {\n /** Asset bit position */\n ASSET_BIT: 0n,\n /** Asset size in bits */\n ASSET_SIZE: 1n,\n /** Option ratio starting bit */\n RATIO_BIT: 1n,\n /** Option ratio size in bits */\n RATIO_SIZE: 7n,\n /** Is long starting bit */\n IS_LONG_BIT: 8n,\n /** Is long size in bits */\n IS_LONG_SIZE: 1n,\n /** Token type starting bit */\n TOKEN_TYPE_BIT: 9n,\n /** Token type size in bits */\n TOKEN_TYPE_SIZE: 1n,\n /** Risk partner starting bit */\n RISK_PARTNER_BIT: 10n,\n /** Risk partner size in bits */\n RISK_PARTNER_SIZE: 2n,\n /** Strike starting bit */\n STRIKE_BIT: 12n,\n /** Strike size in bits (24 bits, signed int24) */\n STRIKE_SIZE: 24n,\n /** Width starting bit */\n WIDTH_BIT: 36n,\n /** Width size in bits */\n WIDTH_SIZE: 12n,\n} as const\n\n/**\n * Masks for extracting/encoding leg fields.\n */\nexport const LEG_MASKS = {\n /** Mask for asset (1 bit) */\n ASSET: (1n << LEG_BITS.ASSET_SIZE) - 1n,\n /** Mask for option ratio (7 bits) */\n RATIO: (1n << LEG_BITS.RATIO_SIZE) - 1n,\n /** Mask for is long (1 bit) */\n IS_LONG: (1n << LEG_BITS.IS_LONG_SIZE) - 1n,\n /** Mask for token type (1 bit) */\n TOKEN_TYPE: (1n << LEG_BITS.TOKEN_TYPE_SIZE) - 1n,\n /** Mask for risk partner (2 bits) */\n RISK_PARTNER: (1n << LEG_BITS.RISK_PARTNER_SIZE) - 1n,\n /** Mask for strike (24 bits) */\n STRIKE: (1n << LEG_BITS.STRIKE_SIZE) - 1n,\n /** Mask for width (12 bits) */\n WIDTH: (1n << LEG_BITS.WIDTH_SIZE) - 1n,\n /** Mask for entire leg (48 bits) */\n LEG: (1n << TOKEN_ID_BITS.LEG_SIZE) - 1n,\n} as const\n\n/**\n * Maximum and minimum values for leg fields.\n */\nexport const LEG_LIMITS = {\n /** Maximum option ratio (127) */\n MAX_RATIO: 127n,\n /** Maximum width (4095) */\n MAX_WIDTH: 4095n,\n /** Maximum strike (8388607, max int24 positive) */\n MAX_STRIKE: 8388607n,\n /** Minimum strike (-8388608, min int24) */\n MIN_STRIKE: -8388608n,\n} as const\n\n/**\n * Value used to convert negative strike to unsigned representation.\n * Strike is stored as int24, so we use 2^24 for conversion.\n */\nexport const STRIKE_CONVERSION_FACTOR = 16777216n\n","import type { Address, Hex } from 'viem'\n\nimport { DEFAULT_VEGOID } from '../tokenId/constants'\n\nexport const vegoid = Number(DEFAULT_VEGOID)\n\nexport interface LegParams {\n index: number\n width: bigint\n optionRatio: bigint\n asset: bigint\n strike: bigint\n isLong: bigint // 0 if short, 1 if long\n tokenType: bigint // Which token (0|1 in underlying pool) is being moved\n riskPartner: bigint\n}\n\nexport const areLegsEqual = (leg1: LegParams, leg2: LegParams): boolean => {\n return (\n leg1.width === leg2.width &&\n leg1.optionRatio === leg2.optionRatio &&\n leg1.asset === leg2.asset &&\n leg1.strike === leg2.strike &&\n leg1.isLong === leg2.isLong &&\n leg1.tokenType === leg2.tokenType &&\n leg1.riskPartner === leg2.riskPartner\n )\n}\n\nexport const stringifyLeg = (leg: LegParams): string => {\n return `Index: ${leg.index} | Width: ${leg.width.toString()} | OptionRatio: ${leg.optionRatio.toString()} | Asset: ${leg.asset.toString()} | Strike: ${leg.strike.toString()} | IsLong?: ${leg.isLong.toString()} | Token Type: ${leg.tokenType.toString()} | Risk Partner: ${leg.riskPartner.toString()}`\n}\n\n// Synthetic TokenIds padding constant\nexport const SYNTH_TOKENID_PADDING = BigInt(\n '115792089237316195423570985007226406215939081747436879206741300988257197096960',\n)\n\nconst POOL_ID_SIZE = 64n\nconst VEGOID_STARTING_BIT = 40n\nconst VEGOID_SIZE = 8n\nconst TICK_SPACING_STARTING_BIT = 48n\nconst ASSET_STARTING_BIT = 0n\nconst ASSET_SIZE = 1n\nconst RATIO_STARTING_BIT = ASSET_STARTING_BIT + ASSET_SIZE // 0 + 1\nconst RATIO_SIZE = 7n\nconst IS_LONG_STARTING_BIT = RATIO_STARTING_BIT + RATIO_SIZE // 1 + 7\nconst IS_LONG_SIZE = 1n\nconst TOKEN_TYPE_STARTING_BIT = IS_LONG_STARTING_BIT + IS_LONG_SIZE // 8 + 1\nconst TOKEN_TYPE_SIZE = 1n\nconst RISK_PARTNER_STARTING_BIT = TOKEN_TYPE_STARTING_BIT + TOKEN_TYPE_SIZE // 9 + 1\nconst RISK_PARTNER_SIZE = 2n\nconst STRIKE_STARTING_BIT = RISK_PARTNER_STARTING_BIT + RISK_PARTNER_SIZE // 10 + 2\nconst STRIKE_SIZE = 24n\nconst WIDTH_STARTING_BIT = STRIKE_STARTING_BIT + STRIKE_SIZE // 12 + 24\nconst WIDTH_SIZE = 12n\nconst LEG_SIZE = WIDTH_STARTING_BIT + WIDTH_SIZE // 36 + 12 = 48\n\n// converts unsigned strike to signed for encoding\nexport const convertStrike = (n: bigint): bigint => {\n if (n < 0n) {\n // 3 bytes because strike is int24\n return 16777216n + n\n } else {\n return n\n }\n}\n\n// converts encoded (unsigned) strike back to signed\nexport const signStrike = (encodedStrike: bigint): bigint => {\n if (encodedStrike > 2n ** 23n) {\n return encodedStrike - 16777216n\n }\n return encodedStrike\n}\n\nconst getLegOffsetByIndex = (index: bigint): bigint => index * LEG_SIZE\n\nconst encodeAsset = (asset: bigint, legIndex: bigint): bigint =>\n asset << (getLegOffsetByIndex(legIndex) + ASSET_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeRatio = (optionRatio: bigint, legIndex: bigint): bigint =>\n optionRatio << (getLegOffsetByIndex(legIndex) + RATIO_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeIsLong = (isLong: bigint, legIndex: bigint): bigint =>\n isLong << (getLegOffsetByIndex(legIndex) + IS_LONG_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeTokenType = (tokenType: bigint, legIndex: bigint): bigint =>\n tokenType << (getLegOffsetByIndex(legIndex) + TOKEN_TYPE_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeRiskPartner = (riskPartner: bigint, legIndex: bigint): bigint =>\n riskPartner << (getLegOffsetByIndex(legIndex) + RISK_PARTNER_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeStrike = (strike: bigint, legIndex: bigint): bigint =>\n convertStrike(strike) << (getLegOffsetByIndex(legIndex) + STRIKE_STARTING_BIT + POOL_ID_SIZE)\n\nconst encodeWidth = (width: bigint, legIndex: bigint): bigint =>\n width << (getLegOffsetByIndex(legIndex) + WIDTH_STARTING_BIT + POOL_ID_SIZE)\n\nconst decodeAsset = (leg: bigint): bigint => leg % (1n << ASSET_SIZE)\n\nconst decodeRatio = (leg: bigint): bigint => (leg >> RATIO_STARTING_BIT) % (1n << RATIO_SIZE)\n\nconst decodeIsLong = (leg: bigint): bigint => (leg >> IS_LONG_STARTING_BIT) % (1n << IS_LONG_SIZE)\n\nconst decodeTokenType = (leg: bigint): bigint =>\n (leg >> TOKEN_TYPE_STARTING_BIT) % (1n << TOKEN_TYPE_SIZE)\n\nconst decodeRiskPartner = (leg: bigint): bigint =>\n (leg >> RISK_PARTNER_STARTING_BIT) % (1n << RISK_PARTNER_SIZE)\n\nconst decodeStrike = (leg: bigint): bigint =>\n signStrike((leg >> STRIKE_STARTING_BIT) % (1n << STRIKE_SIZE))\n\nconst decodeWidth = (leg: bigint): bigint => (leg >> WIDTH_STARTING_BIT) % (1n << WIDTH_SIZE)\n\n/**\n * Extract vegoid from a TokenId\n * Vegoid is stored in bits 40-47 (8 bits) of the poolId\n */\nexport const decodeVegoid = (tokenId: bigint): bigint => {\n return ((tokenId % (1n << POOL_ID_SIZE)) >> VEGOID_STARTING_BIT) % (1n << VEGOID_SIZE)\n}\n\n/**\n * Extract vegoid from a poolId\n * Vegoid is stored in bits 40-47 (8 bits) of the poolId\n */\nexport const decodeVegoidFromPoolId = (poolId: bigint): bigint => {\n return (poolId >> VEGOID_STARTING_BIT) % (1n << VEGOID_SIZE)\n}\n\n/**\n * Extract tickSpacing from a TokenId\n * TickSpacing is stored in bits 48-63 (16 bits) of the poolId\n */\nexport const decodeTickSpacing = (tokenId: bigint): bigint => {\n return (tokenId % (1n << POOL_ID_SIZE)) >> TICK_SPACING_STARTING_BIT\n}\n\n/**\n * Encode poolId with vegoid support\n * The encoded PoolId structure: [16-bit tickSpacing][8-bit vegoid][40-bit pool address]\n * @param address The Uniswap V3 pool address (hex string)\n * @param tickSpacing The tick spacing of the pool\n * @param vegoidValue The vegoid value (defaults to 4 if not provided)\n * @return The encoded poolId as bigint\n */\nexport const encodePoolId = (\n address: Address,\n tickSpacing: bigint,\n vegoidValue: bigint = BigInt(vegoid),\n): bigint => {\n // Remove 0x prefix and get first 10 hex chars (5 bytes = 40 bits)\n const addressHex = address.slice(2, 12).toLowerCase()\n\n // Convert to bytes array (big-endian), then reverse to little-endian\n const bytes: number[] = []\n for (let i = 0; i < 10; i += 2) {\n bytes.push(parseInt(addressHex.slice(i, i + 2), 16))\n }\n bytes.reverse()\n\n // Build poolId: pool address (5 bytes) + vegoid (1 byte) + tickSpacing (2 bytes) = 8 bytes\n // All in little-endian format\n let poolId = 0n\n for (let i = 0; i < bytes.length; i++) {\n poolId |= BigInt(bytes[i]) << BigInt(i * 8)\n }\n\n // Add vegoid at bit 40\n poolId |= (vegoidValue % 256n) << 40n\n\n // Add tickSpacing at bit 48\n poolId |= (tickSpacing % 65536n) << 48n\n\n return poolId\n}\n\n/**\n * Encode V4 poolId with vegoid support\n * The encoded PoolId structure: [16-bit tickSpacing][8-bit vegoid][40-bit pool pattern]\n * @param poolId The V4 pool ID (bytes32 hex string)\n * @param tickSpacing The tick spacing of the pool\n * @param vegoidValue The vegoid value (defaults to 4 if not provided)\n * @return The encoded poolId as bigint\n */\nexport const encodeV4PoolId = (\n poolId: Hex,\n tickSpacing: bigint,\n vegoidValue: bigint = BigInt(vegoid),\n): bigint => {\n // Remove 0x prefix and get last 10 hex chars (5 bytes = 40 bits)\n const poolIdHex = poolId.slice(2)\n const last5BytesHex = poolIdHex.slice(-10).toLowerCase()\n\n // Convert to bytes array (big-endian), then reverse to little-endian\n const bytes: number[] = []\n for (let i = 0; i < 10; i += 2) {\n bytes.push(parseInt(last5BytesHex.slice(i, i + 2), 16))\n }\n bytes.reverse()\n\n // Build encoded poolId: pool pattern (5 bytes) + vegoid (1 byte) + tickSpacing (2 bytes) = 8 bytes\n let encodedPoolId = 0n\n for (let i = 0; i < bytes.length; i++) {\n encodedPoolId |= BigInt(bytes[i]) << BigInt(i * 8)\n }\n\n // Add vegoid at bit 40\n encodedPoolId |= (vegoidValue % 256n) << 40n\n\n // Add tickSpacing at bit 48\n encodedPoolId |= (tickSpacing % 65536n) << 48n\n\n return encodedPoolId\n}\n\n// Can be (ab)used to create a leg id by passing in a tokenId of 0\nexport const addLeg = (tokenId: bigint, leg: LegParams): bigint => {\n const legIndex = BigInt(leg.index)\n const width = leg.width\n const strike = leg.strike\n const riskPartner = leg.riskPartner\n const tokenType = leg.tokenType\n const isLong = leg.isLong\n const optionRatio = leg.optionRatio\n const asset = leg.asset\n\n return (\n tokenId +\n encodeWidth(width, legIndex) +\n encodeStrike(strike, legIndex) +\n (encodeRiskPartner(riskPartner, legIndex) |\n encodeTokenType(tokenType, legIndex) |\n encodeIsLong(isLong, legIndex) |\n encodeRatio(optionRatio, legIndex) |\n encodeAsset(asset, legIndex))\n )\n}\n\nexport const encodePosition = (poolId: bigint, legs: LegParams[]): bigint => {\n return legs.reduce((acc, leg) => addLeg(acc, leg), poolId)\n}\n\nexport interface Position {\n poolId: string\n legs: LegParams[]\n}\n\nexport const decodePosition = (encodedPosition: bigint): Position => {\n const leg4 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(3n))) % (1n << LEG_SIZE)\n\n const leg3 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(2n))) % (1n << LEG_SIZE)\n\n const leg2 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(1n))) % (1n << LEG_SIZE)\n\n const leg1 = (encodedPosition >> (POOL_ID_SIZE + getLegOffsetByIndex(0n))) % (1n << LEG_SIZE)\n\n let poolId = (encodedPosition % (1n << POOL_ID_SIZE)).toString(16)\n\n const poolIdLength = 16 // poolId is 64 bits => 16 hex characters\n if (poolId.length < poolIdLength) {\n poolId = padHexWithZeros('0x' + poolId, poolIdLength + 2) // +2 for 0x prefix\n } else {\n poolId = '0x' + poolId\n }\n\n const encodedLegs = [leg1, leg2, leg3, leg4].filter((leg) => decodeRatio(leg) > 0n)\n\n const legs: LegParams[] = encodedLegs.map((leg, index) => ({\n index: index,\n width: decodeWidth(leg),\n strike: decodeStrike(leg),\n riskPartner: decodeRiskPartner(leg),\n tokenType: decodeTokenType(leg),\n isLong: decodeIsLong(leg),\n optionRatio: decodeRatio(leg),\n asset: decodeAsset(leg),\n }))\n\n return {\n poolId,\n legs,\n }\n}\n\nexport function padHexWithZeros(hex: string, length: number): string {\n // Check if the hex starts with \"0x\"\n if (hex.startsWith('0x')) {\n // Remove the \"0x\" prefix\n hex = hex.substring(2)\n } else {\n throw new Error('do not use padHexWithZeros on non-hex strings')\n }\n\n // Subtract 2 from length to account for the substring(2) call to remove the leading 0x\n while (hex.length < length - 2) {\n hex = '0' + hex\n }\n\n // Add back the \"0x\" prefix\n return '0x' + hex\n}\n","/**\n * Event reconstruction for full position history scan.\n * @module v2/sync/eventReconstruction\n */\n\nimport type { Address, Hash, PublicClient } from 'viem'\nimport { getAbiItem } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\nimport type { SyncEvent } from '../types'\n\ntype EventReconstructionClient = Pick<PublicClient, 'getBlock' | 'getLogs'>\n\n/**\n * Parameters for event reconstruction.\n */\nexport interface EventReconstructionParams {\n /** viem public client */\n client: EventReconstructionClient\n /** Pool address */\n poolAddress: Address\n /** Account to reconstruct positions for */\n account: Address\n /** Starting block for event scan */\n fromBlock: bigint\n /** Ending block for event scan */\n toBlock: bigint\n /** Batch size for log queries (default: 10000) */\n batchSize?: bigint\n /** Progress callback */\n onProgress?: (event: SyncEvent) => void\n}\n\n/**\n * Event reconstruction result.\n */\nexport interface EventReconstructionResult {\n /** Position IDs that are currently open */\n openPositions: bigint[]\n /** Position IDs that have been closed */\n closedPositions: bigint[]\n /** Number of blocks scanned */\n blocksScanned: bigint\n /** Last scanned block number */\n lastBlock: bigint\n /** Last scanned block hash */\n lastBlockHash: Hash\n}\n\n/**\n * Mint event from reconstruction.\n */\ninterface MintEvent {\n tokenId: bigint\n positionSize: bigint\n blockNumber: bigint\n blockHash: Hash\n transactionHash: Hash\n logIndex: number\n}\n\n/**\n * Burn event from reconstruction.\n */\ninterface BurnEvent {\n tokenId: bigint\n positionSize: bigint\n blockNumber: bigint\n blockHash: Hash\n transactionHash: Hash\n logIndex: number\n}\n\n/**\n * Reconstruct position history from events.\n * This is the fallback method when snapshot recovery fails.\n * It scans all OptionMinted and OptionBurnt events to build the position set.\n *\n * @param params - Reconstruction parameters\n * @returns Reconstruction result with open and closed positions\n */\nexport async function reconstructFromEvents(\n params: EventReconstructionParams,\n): Promise<EventReconstructionResult> {\n const {\n client,\n poolAddress,\n account,\n fromBlock,\n toBlock,\n batchSize = 10000n,\n onProgress,\n } = params\n\n const mintEvents: MintEvent[] = []\n const burnEvents: BurnEvent[] = []\n const totalBlocks = toBlock - fromBlock + 1n\n const safeBatchSize = batchSize > 0n ? batchSize : 10000n\n\n const scanRange = async (rangeFromBlock: bigint, rangeToBlock: bigint) => {\n const [mints, burns] = await Promise.all([\n client.getLogs({\n address: poolAddress,\n event: OPTION_MINTED_EVENT,\n args: { recipient: account },\n fromBlock: rangeFromBlock,\n toBlock: rangeToBlock,\n }),\n client.getLogs({\n address: poolAddress,\n event: OPTION_BURNT_EVENT,\n args: { recipient: account },\n fromBlock: rangeFromBlock,\n toBlock: rangeToBlock,\n }),\n ])\n\n // Process mint events\n for (const mint of mints) {\n // Decode position size from balanceData (first 128 bits)\n const balanceData = mint.args.balanceData as bigint\n const positionSize = balanceData & ((1n << 128n) - 1n)\n\n mintEvents.push({\n tokenId: mint.args.tokenId as bigint,\n positionSize,\n blockNumber: mint.blockNumber,\n blockHash: mint.blockHash,\n transactionHash: mint.transactionHash,\n logIndex: mint.logIndex,\n })\n }\n\n // Process burn events\n for (const burn of burns) {\n burnEvents.push({\n tokenId: burn.args.tokenId as bigint,\n positionSize: burn.args.positionSize as bigint,\n blockNumber: burn.blockNumber,\n blockHash: burn.blockHash,\n transactionHash: burn.transactionHash,\n logIndex: burn.logIndex,\n })\n }\n\n const blocksProcessed = rangeToBlock - fromBlock + 1n\n const progress = totalBlocks > 0n ? (blocksProcessed * 100n) / totalBlocks : 100n\n onProgress?.({\n currentBlock: rangeToBlock,\n targetBlock: toBlock,\n positionsFound: BigInt(mintEvents.length),\n progress: progress > 100n ? 100n : progress,\n })\n }\n\n // Account and pool topics make this query selective enough for providers that\n // permit wide eth_getLogs ranges. This keeps the fallback practical on mainnet.\n // Providers with an explicit range cap fall back to bounded requests.\n try {\n await scanRange(fromBlock, toBlock)\n } catch (error) {\n if (!isRangeLimitError(error)) throw error\n\n let currentBlock = fromBlock\n while (currentBlock <= toBlock) {\n const endBlock =\n currentBlock + safeBatchSize - 1n > toBlock ? toBlock : currentBlock + safeBatchSize - 1n\n await scanRange(currentBlock, endBlock)\n currentBlock = endBlock + 1n\n }\n }\n\n // Build position map: tokenId -> net position size\n const positionMap = new Map<bigint, bigint>()\n\n // Sort all events by block and log index\n const allEvents = [\n ...mintEvents.map((e) => ({ ...e, type: 'mint' as const })),\n ...burnEvents.map((e) => ({ ...e, type: 'burn' as const })),\n ].sort((a, b) => {\n const blockDiff = Number(a.blockNumber - b.blockNumber)\n if (blockDiff !== 0) return blockDiff\n return a.logIndex - b.logIndex\n })\n\n // Process events in order\n for (const event of allEvents) {\n const current = positionMap.get(event.tokenId) ?? 0n\n\n if (event.type === 'mint') {\n positionMap.set(event.tokenId, current + event.positionSize)\n } else {\n positionMap.set(event.tokenId, current - event.positionSize)\n }\n }\n\n // Separate open and closed positions\n const openPositions: bigint[] = []\n const closedPositions: bigint[] = []\n\n for (const [tokenId, size] of positionMap) {\n if (size > 0n) {\n openPositions.push(tokenId)\n } else {\n closedPositions.push(tokenId)\n }\n }\n\n // Get the last block hash\n const lastBlock = await client.getBlock({ blockNumber: toBlock })\n\n return {\n openPositions,\n closedPositions,\n blocksScanned: toBlock - fromBlock + 1n,\n lastBlock: toBlock,\n lastBlockHash: lastBlock.hash,\n }\n}\n\nconst OPTION_MINTED_EVENT = getAbiItem({ abi: panopticPoolV2Abi, name: 'OptionMinted' })\nconst OPTION_BURNT_EVENT = getAbiItem({ abi: panopticPoolV2Abi, name: 'OptionBurnt' })\n\nfunction isRangeLimitError(error: unknown): boolean {\n const messages: string[] = []\n let current: unknown = error\n for (let depth = 0; current && typeof current === 'object' && depth < 5; depth += 1) {\n if ('message' in current && typeof current.message === 'string') {\n messages.push(current.message)\n }\n if ('details' in current && typeof current.details === 'string') {\n messages.push(current.details)\n }\n current = 'cause' in current ? current.cause : undefined\n }\n if (typeof error === 'string') messages.push(error)\n\n const message = messages.join(' ').toLowerCase()\n return (\n message.includes('block range') ||\n message.includes('range is too large') ||\n message.includes('range too large') ||\n message.includes('query returned more than') ||\n message.includes('too many results') ||\n message.includes('log response size exceeded') ||\n message.includes('exceeds the limit') ||\n (message.includes('range') && message.includes('limit'))\n )\n}\n\n/**\n * Get the deployment block for a pool.\n * This searches for the first PoolInitialized event.\n *\n * @param client - viem public client\n * @param poolAddress - Pool address\n * @returns Deployment block number or null if not found\n */\nexport async function getPoolDeploymentBlock(\n client: PublicClient,\n poolAddress: Address,\n): Promise<bigint | null> {\n // Search for the first event from this pool\n // We use a binary search approach to find the deployment block\n\n const currentBlock = await client.getBlockNumber()\n let low = 0n\n let high = currentBlock\n let foundBlock: bigint | null = null\n\n // Binary search with scan windows to find the deployment block.\n // Each iteration checks [mid, mid + scanRange] for logs.\n const scanRange = 10000n\n\n while (low <= high) {\n const mid = (low + high) / 2n\n const rangeEnd = mid + scanRange > high ? high : mid + scanRange\n\n try {\n const logs = await client.getLogs({\n address: poolAddress,\n fromBlock: mid,\n toBlock: rangeEnd,\n })\n\n if (logs.length > 0) {\n // Found logs — record earliest and search before it\n const earliest = logs[0].blockNumber\n if (foundBlock === null || earliest < foundBlock) {\n foundBlock = earliest\n }\n high = earliest - 1n\n } else {\n // No logs in [mid, rangeEnd] — skip the entire checked range\n low = rangeEnd + 1n\n }\n } catch {\n // Range too large for RPC — halve the search space\n high = mid + (rangeEnd - mid) / 2n\n }\n }\n\n return foundBlock\n}\n","/**\n * Per-second rate helpers.\n *\n * Collateral tracker rates are returned as WAD-scaled per-second rates.\n * These helpers annualize them for display.\n *\n * @module v2/formatters/rates\n */\n\nimport { formatWadPercent } from './wad'\n\nconst SECONDS_PER_DAY = 86_400n\nconst DAYS_PER_YEAR = 365n\nconst SECONDS_PER_YEAR = SECONDS_PER_DAY * DAYS_PER_YEAR\n\n/**\n * Annualize a per-second WAD-scaled rate to annual WAD.\n *\n * @param ratePerSecondWad - Rate in WAD per second\n * @returns Annualized rate in WAD\n */\nexport function annualizePerSecondRateWad(ratePerSecondWad: bigint): bigint {\n return ratePerSecondWad * SECONDS_PER_YEAR\n}\n\n/**\n * Format a per-second WAD rate as APY percentage text.\n * Uses linear annualization, then formats as WAD percent.\n *\n * @param ratePerSecondWad - Rate in WAD per second\n * @param precision - Decimal places\n * @returns Percentage string, e.g. \"2.41%\"\n */\nexport function formatPerSecondRateWadAsApyPct(\n ratePerSecondWad: bigint,\n precision: bigint,\n): string {\n return formatWadPercent(annualizePerSecondRateWad(ratePerSecondWad), precision)\n}\n\n/**\n * Format a per-second WAD rate as APR percentage text.\n * For this rate model, APR presentation uses the same annualized output.\n *\n * @param ratePerSecondWad - Rate in WAD per second\n * @param precision - Decimal places\n * @returns Percentage string, e.g. \"2.41%\"\n */\nexport function formatPerSecondRateWadAsAprPct(\n ratePerSecondWad: bigint,\n precision: bigint,\n): string {\n return formatWadPercent(annualizePerSecondRateWad(ratePerSecondWad), precision)\n}\n","/**\n * Derive a unique tokenId to mint alongside a burn (position reduction / roll).\n *\n * dispatch() cannot partial-close a held tokenId — a same-tokenId size change\n * is interpreted as `settlePremium`. To reduce, we burn the old tokenId and\n * mint a DIFFERENT tokenId with the desired smaller size in one dispatch. The\n * new tokenId must merely be unique from the old one.\n *\n * Two derivation paths:\n * 1. **Tiny credit leg (default)** — when the base has a free leg slot\n * (< 4 legs), append a width=0 credit (isLong=1) leg with an extreme\n * strike so its token notional (`positionSize · 1.0001^strike`) rounds\n * down to ~1 wei — tokenId-uniquifying but economically negligible. New\n * positionSize can be any value ≤ current size; arbitrary reduction\n * amounts fall out.\n * 2. **Ratio scaling (fallback)** — only when all 4 leg slots are used:\n * multiply every leg's optionRatio by a factor `N` such that\n * `N · max(optionRatio) ≤ 127`, then set\n * `newPositionSize = ceil(targetSize / N)`. Per-leg preserved liquidity\n * is `newPositionSize · N`, so the reduce still satisfies the target.\n *\n * @module v2/tokenId/deriveUniqueTokenId\n */\n\nimport { PanopticError } from '../errors'\nimport { sqrtPriceX96ToTick } from '../formatters/tick'\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\nimport { LEG_LIMITS, TOKEN_ID_BITS } from './constants'\nimport { addLegToTokenId, countLegs, decodeAllLegs, decodeLeg } from './encoding'\n\nconst POOL_ID_MASK = (1n << 64n) - 1n\nconst MAX_LEGS = TOKEN_ID_BITS.MAX_LEGS\nconst MAX_OPTION_RATIO = LEG_LIMITS.MAX_RATIO\nconst Q192 = 1n << 192n\n\nexport type DeriveStrategy = 'tiny-credit' | 'ratio-scale'\n\nexport interface DeriveUniqueTokenIdParams {\n /** Base tokenId to derive a unique sibling from. */\n baseTokenId: bigint\n /**\n * Desired new positionSize. Must be > 0 and ≤ the CURRENT stored\n * positionSize on the tokenId being reduced.\n *\n * For `ratio-scale` the effective size (`newPositionSize · N`) may exceed\n * this by a rounding-up wei. `newPositionSize` in the result reflects\n * exactly what to pass to dispatch.\n */\n targetPositionSize: bigint\n /**\n * Pool tickSpacing. Used to keep the appended credit leg's tick range\n * (SFPM internally widens width=0 to a width-2 chunk: `strike ± tickSpacing`)\n * strictly inside `[MIN_POOL_TICK, MAX_POOL_TICK]`. Omit to use a\n * worst-case Uniswap-v3 default of 200.\n */\n tickSpacing?: bigint\n}\n\nexport interface DeriveUniqueTokenIdResult {\n newTokenId: bigint\n /** positionSize to pass to dispatch for the new tokenId. */\n newPositionSize: bigint\n /**\n * Real per-leg liquidity the new tokenId will hold, expressed in the\n * base-token positionSize frame. Equals `newPositionSize · N` for\n * `ratio-scale` (where N is the applied optionRatio multiplier) and\n * `newPositionSize` for `tiny-credit`. Consumers should compare this\n * against the base tokenId's current stored size to validate that a\n * reduction is actually smaller (or, for `ratio-scale`, that the ceiling\n * rounding did not push effective size above the stored size).\n */\n effectivePositionSize: bigint\n strategy: DeriveStrategy\n}\n\n/**\n * Floor integer square root for bigints (Newton's method). Mirrors the isqrt\n * used in reads/collateralEstimate.ts (buildNeutralLeg).\n */\nfunction isqrt(value: bigint): bigint {\n if (value < 0n) throw new PanopticError('isqrt of negative number')\n if (value < 2n) return value\n let x = value\n let y = (x + 1n) >> 1n\n while (y < x) {\n x = y\n y = (x + value / x) >> 1n\n }\n return x\n}\n\nconst DEFAULT_TICK_SPACING = 200n\n\n/**\n * Target notional (in wei of the tokenType-side asset) for the appended\n * tiny credit leg. Chosen at 10 wei — small enough to be economically\n * meaningless against any real position size, large enough to safely\n * clear rounding on the SFPM's width-2 internal chunk math without any\n * risk of underflowing to zero (which would revert ChunkHasZeroLiquidity).\n */\nconst TINY_CREDIT_TARGET_NOTIONAL_WEI = 10n\n\n/**\n * Pick a signedStrike for the appended width=0 credit leg such that:\n * 1. positionSize · 1.0001^signedStrike ≈ TINY_CREDIT_TARGET_NOTIONAL_WEI\n * (~10 wei — economically meaningless but comfortably above any\n * SFPM width-2 chunk rounding);\n * 2. the leg's tick range (SFPM internally treats width=0 as width=2, so\n * the range is `strike ± tickSpacing`) stays strictly inside\n * `[MIN_POOL_TICK, MAX_POOL_TICK]` — otherwise the getSqrtRatioAtTick\n * call reverts with `InvalidTick`.\n *\n * Closed form: `1.0001^signedStrike = target/positionSize`, so\n * `sqrtKrawX96 = isqrt(target · 2^192 / positionSize)` and\n * `signedStrike = sqrtPriceX96ToTick(sqrtKrawX96)`. If the notional-optimal\n * strike falls outside the safe range, we clamp inward. Clamping raises the\n * notional but keeps it << position size for any reasonable strike.\n */\nfunction computeTinyCreditSignedStrike(positionSize: bigint, tickSpacing: bigint): bigint {\n if (positionSize <= 0n) {\n throw new PanopticError('computeTinyCreditSignedStrike: positionSize must be > 0')\n }\n // Leave one tickSpacing of buffer on each side + 1 tick of headroom so the\n // width-2 chunk (strike ± tickSpacing) stays strictly inside the pool bounds.\n const minSafe = MIN_TICK + tickSpacing + 1n\n const maxSafe = MAX_TICK - tickSpacing - 1n\n\n let signedStrike: bigint\n try {\n const sqrtKrawX96 = isqrt((TINY_CREDIT_TARGET_NOTIONAL_WEI * Q192) / positionSize)\n signedStrike = sqrtPriceX96ToTick(sqrtKrawX96)\n } catch {\n // sqrtPriceX96ToTick rejects out-of-bounds sqrt prices; that only happens\n // for extreme (>> 2^128) or dust positionSizes. Fall back to the min-safe\n // edge, which still gives a tiny notional relative to any real position.\n signedStrike = minSafe\n }\n\n if (signedStrike < minSafe) return minSafe\n if (signedStrike > maxSafe) return maxSafe\n return signedStrike\n}\n\n/**\n * Assemble the tiny credit leg struct, picking a strike that avoids\n * colliding with any existing width=0 credit leg on the same (asset,\n * tokenType) pair.\n *\n * The encoded strike stored in the tokenId is\n * `asset === 0 ? signedStrike : -signedStrike` (mirrors\n * {@link buildNeutralLeg} in reads/collateralEstimate.ts).\n */\nfunction pickUniqueTinyCreditLeg(\n baseTokenId: bigint,\n legIndex: bigint,\n positionSize: bigint,\n tickSpacing: bigint,\n): {\n index: bigint\n asset: bigint\n tokenType: bigint\n optionRatio: bigint\n isLong: bigint\n riskPartner: bigint\n strike: bigint\n width: bigint\n} {\n const asset: bigint = 1n\n const tokenType: bigint = 0n\n\n const existingLegs = decodeAllLegs(baseTokenId)\n const maxSafe = MAX_TICK - tickSpacing - 1n\n\n let signedStrike = computeTinyCreditSignedStrike(positionSize, tickSpacing)\n while (signedStrike <= maxSafe) {\n const candidate = asset === 0n ? signedStrike : -signedStrike\n let collides = false\n for (const leg of existingLegs) {\n if (\n leg.width === 0n &&\n leg.isLong &&\n leg.asset === asset &&\n leg.tokenType === tokenType &&\n leg.strike === candidate\n ) {\n collides = true\n break\n }\n }\n if (!collides) break\n signedStrike += 1n\n }\n if (signedStrike > maxSafe) {\n throw new PanopticError(\n 'deriveUniqueTokenId: exhausted strike space picking a unique tiny credit leg',\n )\n }\n\n const encodedStrike = asset === 0n ? signedStrike : -signedStrike\n\n return {\n index: legIndex,\n asset,\n tokenType,\n optionRatio: 1n,\n isLong: 1n,\n riskPartner: legIndex,\n strike: encodedStrike,\n width: 0n,\n }\n}\n\nfunction appendTinyCreditLeg(\n baseTokenId: bigint,\n baseLegCount: bigint,\n positionSize: bigint,\n tickSpacing: bigint,\n): bigint {\n const newLeg = pickUniqueTinyCreditLeg(baseTokenId, baseLegCount, positionSize, tickSpacing)\n return addLegToTokenId(baseTokenId, newLeg)\n}\n\nfunction scaleRatios(baseTokenId: bigint, targetPositionSize: bigint): DeriveUniqueTokenIdResult {\n const legs = decodeAllLegs(baseTokenId)\n const maxRatio = legs.reduce<bigint>((m, leg) => (leg.optionRatio > m ? leg.optionRatio : m), 0n)\n const N = MAX_OPTION_RATIO / maxRatio\n if (N < 2n) {\n throw new PanopticError(\n 'deriveUniqueTokenId: cannot derive a unique tokenId — all 4 leg slots used and optionRatios already near the 127 ceiling',\n )\n }\n // Preserved per-leg liquidity = newSize · N. ceil ensures effective size ≥ target.\n const newPositionSize = (targetPositionSize + N - 1n) / N\n\n const poolId = baseTokenId & POOL_ID_MASK\n let out = poolId\n for (const leg of legs) {\n out = addLegToTokenId(out, {\n index: leg.index,\n asset: leg.asset,\n tokenType: leg.tokenType,\n optionRatio: leg.optionRatio * N,\n isLong: leg.isLong ? 1n : 0n,\n riskPartner: leg.riskPartner,\n strike: leg.strike,\n width: leg.width,\n })\n }\n return {\n newTokenId: out,\n newPositionSize,\n effectivePositionSize: newPositionSize * N,\n strategy: 'ratio-scale',\n }\n}\n\n/**\n * Derive a tokenId unique from `baseTokenId` for a partial reduction.\n *\n * Prefers a tiny-credit-leg extension (arbitrary new size). Falls back to\n * optionRatio scaling only when the base tokenId already occupies all 4 leg\n * slots.\n */\nexport function deriveUniqueTokenId(params: DeriveUniqueTokenIdParams): DeriveUniqueTokenIdResult {\n const { baseTokenId, targetPositionSize, tickSpacing = DEFAULT_TICK_SPACING } = params\n\n if (targetPositionSize <= 0n) {\n throw new PanopticError('deriveUniqueTokenId: targetPositionSize must be > 0')\n }\n\n const legCount = countLegs(baseTokenId)\n if (legCount === 0n) {\n throw new PanopticError('deriveUniqueTokenId: baseTokenId has no legs')\n }\n\n if (legCount < MAX_LEGS) {\n const newTokenId = appendTinyCreditLeg(baseTokenId, legCount, targetPositionSize, tickSpacing)\n return {\n newTokenId,\n newPositionSize: targetPositionSize,\n effectivePositionSize: targetPositionSize,\n strategy: 'tiny-credit',\n }\n }\n\n return scaleRatios(baseTokenId, targetPositionSize)\n}\n\n/**\n * Test hook: exposed only to make the tiny-credit leg strike inspectable.\n * @internal\n */\nexport function _pickUniqueTinyCreditLegForTests(\n baseTokenId: bigint,\n legIndex: bigint,\n positionSize: bigint = 10n ** 18n,\n tickSpacing: bigint = DEFAULT_TICK_SPACING,\n) {\n return pickUniqueTinyCreditLeg(baseTokenId, legIndex, positionSize, tickSpacing)\n}\n\n/**\n * Re-export decoded leg count so callers can gate UI on the strategy that\n * would be chosen (e.g. show a divisibility hint on ratio-scale positions).\n */\nexport function planDeriveStrategy(baseTokenId: bigint): DeriveStrategy {\n return countLegs(baseTokenId) < MAX_LEGS ? 'tiny-credit' : 'ratio-scale'\n}\n\n// Re-export used by consumers who only need the leg-count helper.\nexport { decodeLeg }\n","/**\n * Pure generation of fixed-price TokenId ladders overlapping the current tick.\n * @module v2/tokenId/generateOverlapping\n */\n\nimport { PanopticValidationError } from '../errors'\nimport { priceToTick, roundToTickSpacing, tickToSqrtPriceX96 } from '../formatters'\nimport { MAX_TICK, MIN_TICK } from '../utils/constants'\nimport { createTokenIdBuilder } from './builder'\nimport { type Timescale, LEG_LIMITS, STANDARD_TICK_WIDTHS, TOKEN_ID_BITS } from './constants'\nimport { decodeTickSpacing } from './encoding'\n\nconst MAX_UINT64 = (1n << 64n) - 1n\nconst MAX_UINT128 = (1n << 128n) - 1n\nconst Q192 = 1n << 192n\nconst MAX_TOKEN_DECIMALS = 255n\nconst MAX_DECIMAL_EXPONENT = 512n\n\nexport type OverlappingOptionType = 'call' | 'put'\n\n/** One option leg repeated at every generated strike. */\nexport interface OverlappingOptionLegConfig {\n optionType: OverlappingOptionType\n optionRatio: bigint\n isLong: boolean\n /** Defaults to this leg's index. */\n riskPartner?: bigint\n}\n\n/** Parameters for {@link generateOverlappingTokenIds}. */\nexport interface GenerateOverlappingTokenIdsParams {\n /** Encoded 64-bit Panoptic pool ID, including tick spacing. */\n poolId: bigint\n /** Current Uniswap pool tick. */\n currentTick: bigint\n /** Standard option timescale used to derive every leg's width. */\n timescale: Timescale\n /** Positive quote-token price interval, such as \"25\" or \"50\". */\n strikePriceSpacing: string\n /** Asset token index in the pool (0 or 1). */\n asset: bigint\n assetDecimals: bigint\n quoteDecimals: bigint\n /** One to four call/put legs sharing each generated strike. */\n legs: readonly OverlappingOptionLegConfig[]\n /** Total size divided across all generated TokenIds. */\n positionSize: bigint\n}\n\n/** TokenIds and sizes aligned with the corresponding `dispatch()` arguments. */\nexport interface GenerateOverlappingTokenIdsResult {\n positionIdList: bigint[]\n positionSizes: bigint[]\n}\n\ninterface ResolvedLegConfig extends OverlappingOptionLegConfig {\n riskPartner: bigint\n}\n\ninterface DecimalSpacing {\n units: bigint\n scale: bigint\n denominator: bigint\n}\n\ninterface Fraction {\n numerator: bigint\n denominator: bigint\n}\n\nfunction invalid(message: string): never {\n throw new PanopticValidationError(`generateOverlappingTokenIds: ${message}`)\n}\n\nfunction pow10(exponent: bigint): bigint {\n return 10n ** exponent\n}\n\nfunction parsePriceSpacing(value: string, quoteDecimals: bigint): DecimalSpacing {\n const match = /^\\+?(?:(\\d+)(?:\\.(\\d*))?|\\.(\\d+))(?:e([+-]?\\d+))?$/i.exec(value.trim())\n if (match === null) invalid('strikePriceSpacing must be a positive decimal string')\n\n const integerPart = match[1] ?? '0'\n const fractionalPart = match[2] ?? match[3] ?? ''\n const exponent = BigInt(match[4] ?? '0')\n if (exponent < -MAX_DECIMAL_EXPONENT || exponent > MAX_DECIMAL_EXPONENT) {\n invalid('strikePriceSpacing exponent is too large')\n }\n\n let units = BigInt(`${integerPart}${fractionalPart}`)\n let scale = BigInt(fractionalPart.length) - exponent\n if (scale < 0n) {\n units *= pow10(-scale)\n scale = 0n\n }\n\n while (scale > 0n && units % 10n === 0n) {\n units /= 10n\n scale -= 1n\n }\n\n if (units <= 0n) invalid('strikePriceSpacing must be positive')\n if (scale > quoteDecimals) {\n invalid('strikePriceSpacing exceeds the quote token decimal precision')\n }\n\n return { units, scale, denominator: pow10(scale) }\n}\n\nfunction formatGridPrice(multiple: bigint, spacing: DecimalSpacing): string {\n const scaledPrice = multiple * spacing.units\n if (spacing.scale === 0n) return scaledPrice.toString()\n\n const scale = Number(spacing.scale)\n const digits = scaledPrice.toString().padStart(scale + 1, '0')\n const decimalIndex = digits.length - scale\n return `${digits.slice(0, decimalIndex)}.${digits.slice(decimalIndex)}`\n}\n\nfunction quotePriceAtTick(\n tick: bigint,\n asset: bigint,\n assetDecimals: bigint,\n quoteDecimals: bigint,\n): Fraction {\n const orientedTick = asset === 0n ? tick : -tick\n const sqrtPriceX96 = tickToSqrtPriceX96(orientedTick)\n let numerator = sqrtPriceX96 * sqrtPriceX96\n let denominator = Q192\n const decimalDifference = assetDecimals - quoteDecimals\n\n if (decimalDifference > 0n) {\n numerator *= pow10(decimalDifference)\n } else if (decimalDifference < 0n) {\n denominator *= pow10(-decimalDifference)\n }\n\n return { numerator, denominator }\n}\n\nfunction isPriceGridStrike(\n strike: bigint,\n params: Pick<GenerateOverlappingTokenIdsParams, 'asset' | 'assetDecimals' | 'quoteDecimals'>,\n spacing: DecimalSpacing,\n tickSpacing: bigint,\n): boolean {\n const price = quotePriceAtTick(strike, params.asset, params.assetDecimals, params.quoteDecimals)\n const floorMultiple =\n (price.numerator * spacing.denominator) / (price.denominator * spacing.units)\n\n for (const multiple of [floorMultiple, floorMultiple + 1n]) {\n if (multiple <= 0n) continue\n\n const orientedTick = priceToTick(\n formatGridPrice(multiple, spacing),\n params.assetDecimals,\n params.quoteDecimals,\n )\n const poolTick = params.asset === 0n ? orientedTick : -orientedTick\n if (roundToTickSpacing(poolTick, tickSpacing) === strike) return true\n }\n\n return false\n}\n\nfunction ceilDiv(value: bigint, divisor: bigint): bigint {\n const quotient = value / divisor\n const remainder = value % divisor\n return remainder > 0n ? quotient + 1n : quotient\n}\n\nfunction floorDiv(value: bigint, divisor: bigint): bigint {\n const quotient = value / divisor\n const remainder = value % divisor\n return remainder < 0n ? quotient - 1n : quotient\n}\n\nfunction resolveLegs(legs: readonly OverlappingOptionLegConfig[]): ResolvedLegConfig[] {\n if (legs.length === 0 || legs.length > Number(TOKEN_ID_BITS.MAX_LEGS)) {\n invalid('legs must contain between 1 and 4 entries')\n }\n\n const resolved = legs.map((leg, index) => {\n if (leg.optionType !== 'call' && leg.optionType !== 'put') {\n invalid(`leg ${index} has an invalid optionType`)\n }\n if (typeof leg.isLong !== 'boolean') invalid(`leg ${index} has an invalid isLong value`)\n if (leg.optionRatio < 1n || leg.optionRatio > LEG_LIMITS.MAX_RATIO) {\n invalid(`leg ${index} optionRatio must be between 1 and ${LEG_LIMITS.MAX_RATIO}`)\n }\n\n const riskPartner = leg.riskPartner ?? BigInt(index)\n if (riskPartner < 0n || riskPartner >= BigInt(legs.length)) {\n invalid(`leg ${index} references an inactive risk partner`)\n }\n\n return { ...leg, riskPartner }\n })\n\n for (const [index, leg] of resolved.entries()) {\n if (leg.riskPartner === BigInt(index)) continue\n const partner = resolved[Number(leg.riskPartner)]\n if (partner === undefined || partner.riskPartner !== BigInt(index)) {\n invalid(`leg ${index} has a non-mutual risk partner`)\n }\n }\n\n return resolved\n}\n\nfunction getCandidateStrikes(\n params: GenerateOverlappingTokenIdsParams,\n spacing: DecimalSpacing,\n tickSpacing: bigint,\n halfWidth: bigint,\n): bigint[] {\n const lower =\n MIN_TICK + halfWidth > params.currentTick - halfWidth + 1n\n ? MIN_TICK + halfWidth\n : params.currentTick - halfWidth + 1n\n const upper =\n MAX_TICK - halfWidth < params.currentTick + halfWidth - 1n\n ? MAX_TICK - halfWidth\n : params.currentTick + halfWidth - 1n\n const firstStrike = ceilDiv(lower, tickSpacing) * tickSpacing\n const lastStrike = floorDiv(upper, tickSpacing) * tickSpacing\n const strikes: bigint[] = []\n\n for (let strike = firstStrike; strike <= lastStrike; strike += tickSpacing) {\n if (isPriceGridStrike(strike, params, spacing, tickSpacing)) strikes.push(strike)\n }\n\n if (params.asset === 1n) strikes.reverse()\n return strikes\n}\n\nfunction buildTokenId(\n poolId: bigint,\n strike: bigint,\n width: bigint,\n asset: bigint,\n legs: readonly ResolvedLegConfig[],\n): bigint {\n const builder = createTokenIdBuilder(poolId)\n for (const leg of legs) {\n const config = {\n strike,\n width,\n optionRatio: leg.optionRatio,\n isLong: leg.isLong,\n riskPartner: leg.riskPartner,\n asset,\n }\n if (leg.optionType === 'call') builder.addCall(config)\n else builder.addPut(config)\n }\n return builder.build()\n}\n\nfunction dividePositionSize(positionSize: bigint, count: bigint): bigint[] {\n if (positionSize < count) {\n invalid(`positionSize ${positionSize} is too small for ${count} nonzero positions`)\n }\n\n const quotient = positionSize / count\n const remainder = positionSize % count\n const sizes: bigint[] = []\n for (let index = 0n; index < count; index += 1n) {\n sizes.push(quotient + (index < remainder ? 1n : 0n))\n }\n return sizes\n}\n\n/**\n * Generate a fixed quote-price lattice of co-strike TokenIds whose liquidity\n * ranges strictly contain the current tick. Returned arrays are ordered by\n * ascending quote strike price and are ready for `dispatch()`.\n */\nexport function generateOverlappingTokenIds(\n params: GenerateOverlappingTokenIdsParams,\n): GenerateOverlappingTokenIdsResult {\n if (params.poolId < 0n || params.poolId > MAX_UINT64) invalid('poolId must fit in uint64')\n if (params.currentTick < MIN_TICK || params.currentTick > MAX_TICK) {\n invalid(`currentTick must be between ${MIN_TICK} and ${MAX_TICK}`)\n }\n if (params.asset !== 0n && params.asset !== 1n) invalid('asset must be 0 or 1')\n if (\n params.assetDecimals < 0n ||\n params.assetDecimals > MAX_TOKEN_DECIMALS ||\n params.quoteDecimals < 0n ||\n params.quoteDecimals > MAX_TOKEN_DECIMALS\n ) {\n invalid('assetDecimals and quoteDecimals must be between 0 and 255')\n }\n if (params.positionSize <= 0n || params.positionSize > MAX_UINT128) {\n invalid('positionSize must be between 1 and uint128.max')\n }\n\n const tickSpacing = decodeTickSpacing(params.poolId)\n if (tickSpacing <= 0n) invalid('poolId tick spacing must be positive')\n\n const standardTickWidth = STANDARD_TICK_WIDTHS[params.timescale]\n if (standardTickWidth === undefined) invalid(`unknown timescale ${String(params.timescale)}`)\n const width = (standardTickWidth + tickSpacing - 1n) / tickSpacing\n if (width <= 0n || width > LEG_LIMITS.MAX_WIDTH) {\n invalid(\n `timescale width does not fit in the TokenId width field for tick spacing ${tickSpacing}`,\n )\n }\n\n const halfWidth = (width * tickSpacing) / 2n\n if (halfWidth <= 0n) invalid('timescale width must span at least two ticks')\n\n const spacing = parsePriceSpacing(params.strikePriceSpacing, params.quoteDecimals)\n const legs = resolveLegs(params.legs)\n const strikes = getCandidateStrikes(params, spacing, tickSpacing, halfWidth)\n if (strikes.length === 0) invalid('no price-grid strikes overlap the current tick')\n\n return {\n positionIdList: strikes.map((strike) =>\n buildTokenId(params.poolId, strike, width, params.asset, legs),\n ),\n positionSizes: dividePositionSize(params.positionSize, BigInt(strikes.length)),\n }\n}\n","/**\n * Pure TokenId decomposition into shorter-timescale positions.\n * @module v2/tokenId/split\n */\n\nimport { PanopticValidationError } from '../errors'\nimport { type Timescale, LEG_LIMITS, STANDARD_TICK_WIDTHS, TOKEN_ID_BITS } from './constants'\nimport { type DecodedLeg, addLegToTokenId, decodeAllLegs, decodeTickSpacing } from './encoding'\n\nconst POOL_ID_MASK = (1n << TOKEN_ID_BITS.POOL_ID_SIZE) - 1n\nconst MAX_UINT128 = (1n << 128n) - 1n\nconst MAX_UINT256 = (1n << 256n) - 1n\n\n/** TokenIds and sizes aligned with the corresponding `dispatch()` arguments. */\nexport interface SplitTokenIdByTimescaleResult {\n positionIdList: bigint[]\n positionSizes: bigint[]\n}\n\ntype LegGroup = DecodedLeg[]\n\nfunction invalid(message: string): never {\n throw new PanopticValidationError(`splitTokenIdByTimescale: ${message}`)\n}\n\nfunction validateInput(tokenId: bigint, positionSize: bigint): DecodedLeg[] {\n if (tokenId < 0n || tokenId > MAX_UINT256) invalid('tokenId must fit in uint256')\n if (positionSize <= 0n || positionSize > MAX_UINT128) {\n invalid('positionSize must be between 1 and uint128.max')\n }\n\n const legs = decodeAllLegs(tokenId)\n if (legs.length === 0) invalid('tokenId must contain at least one active leg')\n\n for (const [index, leg] of legs.entries()) {\n if (leg.index !== BigInt(index)) invalid('active legs must be contiguous from index 0')\n }\n\n const firstUnusedBit = TOKEN_ID_BITS.POOL_ID_SIZE + BigInt(legs.length) * TOKEN_ID_BITS.LEG_SIZE\n if (tokenId >> firstUnusedBit !== 0n) invalid('inactive leg slots must be empty')\n\n const byIndex = new Map(legs.map((leg) => [leg.index, leg]))\n for (const leg of legs) {\n const partner = byIndex.get(leg.riskPartner)\n if (partner === undefined) invalid(`leg ${leg.index} references an inactive risk partner`)\n if (partner.index !== leg.index && partner.riskPartner !== leg.index) {\n invalid(`leg ${leg.index} has a non-mutual risk partner`)\n }\n }\n\n return legs\n}\n\nfunction isCall(leg: DecodedLeg): boolean {\n return leg.tokenType === leg.asset\n}\n\nfunction isEconomicStraddlePair(left: DecodedLeg, right: DecodedLeg): boolean {\n return (\n isCall(left) !== isCall(right) &&\n left.asset === right.asset &&\n left.optionRatio === right.optionRatio &&\n left.isLong === right.isLong &&\n left.strike === right.strike &&\n left.width === right.width\n )\n}\n\n/** Preserve mutual pairs, then pair self-partnered economic straddles in source order. */\nfunction groupOptionLegs(optionLegs: DecodedLeg[]): LegGroup[] {\n const byIndex = new Map(optionLegs.map((leg) => [leg.index, leg]))\n const consumed = new Set<bigint>()\n const groups: LegGroup[] = []\n\n for (const leg of optionLegs) {\n if (consumed.has(leg.index)) continue\n\n if (leg.riskPartner !== leg.index) {\n const riskPartner = byIndex.get(leg.riskPartner)\n if (riskPartner === undefined) {\n invalid(`mutual risk pair containing leg ${leg.index} cannot be separated`)\n }\n\n consumed.add(leg.index)\n consumed.add(riskPartner.index)\n groups.push([leg, riskPartner])\n continue\n }\n\n const partner = optionLegs.find(\n (candidate) =>\n candidate.index > leg.index &&\n !consumed.has(candidate.index) &&\n candidate.riskPartner === candidate.index &&\n isEconomicStraddlePair(leg, candidate),\n )\n\n consumed.add(leg.index)\n if (partner === undefined) {\n groups.push([leg])\n continue\n }\n\n consumed.add(partner.index)\n groups.push([leg, partner])\n }\n\n return groups\n}\n\nfunction remapRiskPartner(leg: DecodedLeg, indexBySource: ReadonlyMap<bigint, bigint>): bigint {\n const riskPartner = indexBySource.get(leg.riskPartner)\n if (riskPartner === undefined) {\n invalid(`risk partner for leg ${leg.index} is missing from its output group`)\n }\n return riskPartner\n}\n\nfunction buildTokenId(\n poolId: bigint,\n legs: LegGroup,\n transform: (leg: DecodedLeg) => Pick<DecodedLeg, 'strike' | 'width'>,\n): bigint {\n const indexBySource = new Map(legs.map((leg, index) => [leg.index, BigInt(index)]))\n let output = poolId\n\n for (const [index, leg] of legs.entries()) {\n const newIndex = BigInt(index)\n const { strike, width } = transform(leg)\n if (strike < LEG_LIMITS.MIN_STRIKE || strike > LEG_LIMITS.MAX_STRIKE) {\n invalid(`generated strike ${strike} does not fit in int24`)\n }\n if (width < 0n || width > LEG_LIMITS.MAX_WIDTH) {\n invalid(`generated width ${width} does not fit in the TokenId width field`)\n }\n\n output = addLegToTokenId(output, {\n index: newIndex,\n asset: leg.asset,\n optionRatio: leg.optionRatio,\n isLong: leg.isLong ? 1n : 0n,\n tokenType: leg.tokenType,\n riskPartner: remapRiskPartner(leg, indexBySource),\n strike,\n width,\n })\n }\n\n return output\n}\n\nfunction childWidths(sourceWidth: bigint, targetWidth: bigint): bigint[] {\n if (sourceWidth <= targetWidth) return [sourceWidth]\n\n const fullWidthCount = sourceWidth / targetWidth\n const remainder = sourceWidth % targetWidth\n const widths: bigint[] = []\n for (let remaining = fullWidthCount; remaining > 0n; remaining -= 1n) {\n widths.push(targetWidth)\n }\n if (remainder > 0n) widths.push(remainder)\n return widths\n}\n\nfunction dividePositionSize(positionSize: bigint, count: number): bigint[] {\n const countBigInt = BigInt(count)\n if (positionSize < countBigInt) {\n invalid(`positionSize ${positionSize} is too small for ${count} nonzero child positions`)\n }\n\n const quotient = positionSize / countBigInt\n const remainder = positionSize % countBigInt\n return Array.from(\n { length: count },\n (_, index) => quotient + (BigInt(index) < remainder ? 1n : 0n),\n )\n}\n\nfunction splitGroup(\n poolId: bigint,\n group: LegGroup,\n tickSpacing: bigint,\n targetWidth: bigint,\n positionSize: bigint,\n): SplitTokenIdByTimescaleResult {\n const sourceWidth = group[0]?.width\n if (sourceWidth === undefined || sourceWidth === 0n)\n invalid('option group must have nonzero width')\n if (group.some((leg) => leg.width !== sourceWidth)) {\n invalid('all legs in an option group must have the same width')\n }\n\n const widths = childWidths(sourceWidth, targetWidth)\n const positionSizes = dividePositionSize(positionSize, widths.length)\n let consumedWidth = 0n\n\n const positionIdList = widths.map((width) => {\n const offset = consumedWidth\n consumedWidth += width\n\n return buildTokenId(poolId, group, (leg) => {\n // PanopticMath.getTicks uses floor below the strike and ceil above it.\n const sourceLower = leg.strike - (sourceWidth * tickSpacing) / 2n\n const childLower = sourceLower + offset * tickSpacing\n const strike = childLower + (width * tickSpacing) / 2n\n return { strike, width }\n })\n })\n\n return { positionIdList, positionSizes }\n}\n\n/**\n * Split every standalone option, economic straddle, or mutual risk pair in a\n * TokenId into a shorter standard timescale. Width-zero credit/loan legs are\n * emitted together as one final position. Returned arrays are parallel and\n * ready for `dispatch()`.\n *\n * Each option group divides `positionSize` independently across its children.\n * Integer remainder units are assigned to the lower children first.\n */\nexport function splitTokenIdByTimescale(\n tokenId: bigint,\n positionSize: bigint,\n targetTimescale: Timescale,\n): SplitTokenIdByTimescaleResult {\n const legs = validateInput(tokenId, positionSize)\n const tickSpacing = decodeTickSpacing(tokenId)\n if (tickSpacing <= 0n) invalid('tokenId tick spacing must be positive')\n\n const targetTickWidth = STANDARD_TICK_WIDTHS[targetTimescale]\n if (targetTickWidth === undefined) invalid(`unknown target timescale ${String(targetTimescale)}`)\n const targetWidth = (targetTickWidth + tickSpacing - 1n) / tickSpacing\n\n const poolId = tokenId & POOL_ID_MASK\n const optionLegs = legs.filter((leg) => leg.width > 0n)\n const fundingLegs = legs.filter((leg) => leg.width === 0n)\n const positionIdList: bigint[] = []\n const positionSizes: bigint[] = []\n\n for (const group of groupOptionLegs(optionLegs)) {\n const split = splitGroup(poolId, group, tickSpacing, targetWidth, positionSize)\n positionIdList.push(...split.positionIdList)\n positionSizes.push(...split.positionSizes)\n }\n\n if (fundingLegs.length > 0) {\n positionIdList.push(\n buildTokenId(poolId, fundingLegs, (leg) => ({ strike: leg.strike, width: leg.width })),\n )\n positionSizes.push(positionSize)\n }\n\n return { positionIdList, positionSizes }\n}\n","/**\n * Construction of fee-protected self-settlement dispatches.\n *\n * A short position's displayed premium can include fees that still live in\n * Uniswap. Minting a temporary, minimal short over the same chunks collects\n * those fees into `settledTokens`; burning it after settlement leaves the\n * caller's position list unchanged.\n * @module v2/writes/protectedSettle\n */\n\nimport { PanopticError } from '../errors'\nimport { tickToSqrtPriceX96 } from '../formatters'\nimport type { DispatchIntent } from '../simulations/creditWrap'\nimport { addLegToTokenId, decodeAllLegs, decodeTickSpacing } from '../tokenId'\n\nconst POOL_ID_MASK = (1n << 64n) - 1n\nconst Q96 = 1n << 96n\nconst MAX_UINT128 = (1n << 128n) - 1n\nconst SETTLE_LIMITS = [-887272n, 887272n, 0n] as const\n\nexport interface BuildProtectedSettleDispatchParams {\n /** Positions whose premium should be settled. */\n positionIdList: bigint[]\n /** The caller's complete held list. A settlement does not change it. */\n finalPositionIdList: bigint[]\n /** Current stored size for every entry in `positionIdList`. */\n positionSizes: bigint[]\n usePremiaAsCollateral?: boolean\n builderCode?: bigint\n}\n\nexport interface ProtectedSettlePlan {\n /** Atomic poke/settle/poke dispatch submitted after buyer settlements. */\n dispatch: DispatchIntent\n /** Poke-only dispatch used to verify no displayed premium remains uncollected. */\n collectionDispatch?: DispatchIntent\n /** Temporary position IDs, one for each settled position containing short chunks. */\n pokingTokenIds: bigint[]\n}\n\nfunction ceilDiv(numerator: bigint, denominator: bigint): bigint {\n return (numerator + denominator - 1n) / denominator\n}\n\n/** Smallest position size that creates non-zero liquidity on every poke leg. */\nfunction minimumPokeSize(\n legs: ReturnType<typeof decodeAllLegs>,\n tickSpacing: bigint,\n): bigint | undefined {\n let requiredSize = 1n\n\n for (const leg of legs) {\n const widthInTicks = leg.width * tickSpacing\n const lowerTick = leg.strike - widthInTicks / 2n\n const upperTick = leg.strike + (widthInTicks + 1n) / 2n\n const sqrtLower = tickToSqrtPriceX96(lowerTick)\n const sqrtUpper = tickToSqrtPriceX96(upperTick)\n const delta = sqrtUpper - sqrtLower\n const liquidityFactor = leg.asset === 0n ? (sqrtLower * sqrtUpper) / Q96 : Q96\n if (liquidityFactor === 0n) return undefined\n const requiredAmount = ceilDiv(delta, liquidityFactor)\n const legSize = ceilDiv(requiredAmount, leg.optionRatio)\n if (legSize > requiredSize) requiredSize = legSize\n }\n\n if (requiredSize > MAX_UINT128) {\n return undefined\n }\n return requiredSize\n}\n\nfunction encodePokeToken(\n sourceTokenId: bigint,\n legs: ReturnType<typeof decodeAllLegs>,\n firstRatio: bigint,\n assetMask: bigint,\n): bigint {\n let tokenId = sourceTokenId & POOL_ID_MASK\n legs.forEach((leg, index) => {\n const encodedIndex = BigInt(index)\n tokenId = addLegToTokenId(tokenId, {\n index: encodedIndex,\n asset: (assetMask >> encodedIndex) & 1n,\n optionRatio: index === 0 ? firstRatio : leg.optionRatio,\n isLong: 0n,\n tokenType: leg.tokenType,\n riskPartner: encodedIndex,\n strike: leg.strike,\n width: leg.width,\n })\n })\n return tokenId\n}\n\nfunction buildUniquePoke(\n sourceTokenId: bigint,\n occupied: Set<bigint>,\n): { tokenId: bigint; size: bigint } | undefined {\n const seenChunks = new Set<string>()\n const shortChunkLegs = decodeAllLegs(sourceTokenId).filter((leg) => {\n if (leg.isLong || leg.width === 0n) return false\n const chunkKey = `${leg.strike}:${leg.width}:${leg.tokenType}`\n if (seenChunks.has(chunkKey)) return false\n seenChunks.add(chunkKey)\n return true\n })\n if (shortChunkLegs.length === 0) return undefined\n\n const originalRatio = shortChunkLegs[0].optionRatio\n for (let ratioOffset = 0n; ratioOffset < 127n; ratioOffset += 1n) {\n const firstRatio = ((originalRatio - 1n + ratioOffset) % 127n) + 1n\n const assetVariants = 1n << BigInt(shortChunkLegs.length)\n for (let assetMask = 0n; assetMask < assetVariants; assetMask += 1n) {\n const tokenId = encodePokeToken(sourceTokenId, shortChunkLegs, firstRatio, assetMask)\n if (!occupied.has(tokenId)) {\n const size = minimumPokeSize(decodeAllLegs(tokenId), decodeTickSpacing(sourceTokenId))\n if (size !== undefined) return { tokenId, size }\n }\n }\n }\n\n throw new PanopticError('Unable to derive a collision-free protected settlement poke')\n}\n\n/**\n * Build `[poke, settle, poke]` for every target containing a width>0 short.\n * Pure-long and width-zero positions are settled directly.\n */\nexport function buildProtectedSettlePlan(\n params: BuildProtectedSettleDispatchParams,\n): ProtectedSettlePlan {\n const {\n positionIdList,\n finalPositionIdList,\n positionSizes,\n usePremiaAsCollateral = false,\n builderCode = 0n,\n } = params\n if (positionIdList.length !== positionSizes.length) {\n throw new PanopticError('Protected settlement: positionSizes length must match positionIdList')\n }\n\n const occupied = new Set(finalPositionIdList)\n const actionIds: bigint[] = []\n const actionSizes: bigint[] = []\n const actionLimits: (readonly [bigint, bigint, bigint])[] = []\n const collectionIds: bigint[] = []\n const collectionSizes: bigint[] = []\n const collectionLimits: (readonly [bigint, bigint, bigint])[] = []\n const pokingTokenIds: bigint[] = []\n\n positionIdList.forEach((tokenId, index) => {\n const poke = buildUniquePoke(tokenId, occupied)\n if (poke === undefined) {\n actionIds.push(tokenId)\n actionSizes.push(positionSizes[index])\n actionLimits.push(SETTLE_LIMITS)\n return\n }\n\n occupied.add(poke.tokenId)\n pokingTokenIds.push(poke.tokenId)\n actionIds.push(poke.tokenId, tokenId, poke.tokenId)\n actionSizes.push(poke.size, positionSizes[index], 0n)\n actionLimits.push(SETTLE_LIMITS, SETTLE_LIMITS, SETTLE_LIMITS)\n collectionIds.push(poke.tokenId, poke.tokenId)\n collectionSizes.push(poke.size, 0n)\n collectionLimits.push(SETTLE_LIMITS, SETTLE_LIMITS)\n })\n\n const base = { finalPositionIdList: [...finalPositionIdList], usePremiaAsCollateral, builderCode }\n return {\n dispatch: {\n ...base,\n positionIdList: actionIds,\n positionSizes: actionSizes,\n tickAndSpreadLimits: actionLimits,\n },\n collectionDispatch:\n collectionIds.length === 0\n ? undefined\n : {\n ...base,\n positionIdList: collectionIds,\n positionSizes: collectionSizes,\n tickAndSpreadLimits: collectionLimits,\n },\n pokingTokenIds,\n }\n}\n\n/**\n * Build the atomic self-settlement dispatch that temporarily pokes each\n * affected short chunk before settling its source position.\n *\n * @param params - Positions, current sizes, and complete held-position list.\n * @returns A dispatch intent ready for simulation or submission.\n */\nexport function buildProtectedSettleDispatch(\n params: BuildProtectedSettleDispatchParams,\n): DispatchIntent {\n return buildProtectedSettlePlan(params).dispatch\n}\n","/**\n * Read current on-chain positionSize for a list of tokenIds.\n *\n * PanopticPool.dispatch() treats `positionSizes[i] == storedSize` as a\n * settlePremium self-call and any mismatch (including 0) as a burn. Callers\n * that want to trigger settle without changing size must pass the CURRENT\n * stored size for each held tokenId — hence this helper.\n *\n * @module v2/reads/positionSizes\n */\n\nimport type { Address, PublicClient } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\n\nconst BIT_MASK_128 = (1n << 128n) - 1n\n\nexport interface GetCurrentPositionSizesParams {\n client: PublicClient\n poolAddress: Address\n account: Address\n positionIdList: bigint[]\n blockNumber?: bigint\n}\n\n/**\n * Returns the current stored positionSize for each tokenId, in the same order\n * as the input `positionIdList`. Reverts (via the contract) if any tokenId is\n * not held by `account`.\n */\nexport async function getCurrentPositionSizes(\n params: GetCurrentPositionSizesParams,\n): Promise<bigint[]> {\n const { client, poolAddress, account, positionIdList, blockNumber } = params\n\n if (positionIdList.length === 0) return []\n\n const [, , positionBalances] = await client.readContract({\n address: poolAddress,\n abi: panopticPoolV2Abi,\n functionName: 'getFullPositionsData',\n args: [account, false, positionIdList],\n blockNumber,\n })\n\n return positionBalances.map((packed) => packed & BIT_MASK_128)\n}\n","/**\n * Token flow simulation utility using PanopticPool.multicall.\n *\n * Uses getAssetsOf-dispatch-getAssetsOf pattern within a single eth_call\n * to measure exact collateral asset movements from any dispatch call.\n *\n * @module v2/simulations/tokenFlow\n */\n\nimport {\n type Address,\n type Hex,\n type PublicClient,\n decodeFunctionResult,\n encodeFunctionData,\n} from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\nimport { panopticErrorsAbi } from '../errors/errorsAbi'\n\n/**\n * PanopticPool getAssetsOf ABI.\n * Returns collateral assets (shares converted to underlying) for an account.\n */\nconst getAssetsOfAbi = [\n {\n type: 'function',\n name: 'getAssetsOf',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [\n { name: 'assets0', type: 'uint256' },\n { name: 'assets1', type: 'uint256' },\n ],\n stateMutability: 'view',\n },\n] as const\n\n/**\n * PanopticPool multicall ABI (inherited from Uniswap).\n * Uses delegatecall, preserving msg.sender throughout the chain.\n */\nconst multicallAbi = [\n {\n type: 'function',\n name: 'multicall',\n inputs: [{ name: 'data', type: 'bytes[]' }],\n outputs: [{ name: 'results', type: 'bytes[]' }],\n stateMutability: 'nonpayable',\n },\n // Include error definitions so viem can decode revert data with full args\n ...panopticErrorsAbi,\n] as const\n\n/**\n * Token flow result from simulation.\n * Measures collateral asset changes via getAssetsOf-dispatch-getAssetsOf pattern.\n */\nexport interface TokenFlow {\n /** Token 0 collateral change (negative = user deposits, positive = user receives) */\n delta0: bigint\n /** Token 1 collateral change (negative = user deposits, positive = user receives) */\n delta1: bigint\n /** Collateral assets in token 0 before the call */\n balanceBefore0: bigint\n /** Collateral assets in token 1 before the call */\n balanceBefore1: bigint\n /** Collateral assets in token 0 after the call */\n balanceAfter0: bigint\n /** Collateral assets in token 1 after the call */\n balanceAfter1: bigint\n /** Pool tick before the operation */\n tickBefore: bigint | null\n /** Pool tick after the operation */\n tickAfter: bigint | null\n}\n\n/**\n * Parameters for simulateWithTokenFlow.\n */\nexport interface SimulateWithTokenFlowParams {\n /** viem public client */\n client: PublicClient\n /** PanopticPool address */\n poolAddress: Address\n /** User address whose collateral changes we're measuring */\n user: Address\n /** Encoded call data (typically dispatch) */\n callData: Hex\n /** Optional block number for simulation */\n blockNumber?: bigint\n /**\n * Optional additional encoded calls to append after the 5-call pattern.\n * These execute post-dispatch within the same multicall (same state).\n * Raw encoded bytes are returned in `postCallResults`.\n */\n postCallData?: Hex[]\n /**\n * Optional additional encoded calls to insert between the pre-dispatch\n * `getAssetsOf` / `getCurrentTick` and the target call. These execute\n * pre-dispatch within the same multicall — useful for reading per-position\n * data (e.g. `getFullPositionsData`) against the original `positionIdList`\n * before state mutates. Raw encoded bytes are returned in `preCallResults`.\n */\n preCallData?: Hex[]\n}\n\n/**\n * Result of simulateWithTokenFlow.\n */\nexport interface SimulateWithTokenFlowResult {\n /** Whether the simulation succeeded */\n success: boolean\n /** Token flow data (only if success) */\n tokenFlow?: TokenFlow\n /** Error message (only if failed) */\n error?: string\n /** Raw error object preserving viem cause chain and revert data */\n rawError?: Error\n /** Gas estimate for the inner call */\n gasEstimate: bigint\n /** Raw results from postCallData entries (only if success and postCallData was provided) */\n postCallResults?: Hex[]\n /** Raw results from preCallData entries (only if success and preCallData was provided) */\n preCallResults?: Hex[]\n}\n\n/**\n * Simulate a contract call and measure token flow using PanopticPool.multicall.\n *\n * This function uses PanopticPool's inherited multicall (delegatecall-based) to chain:\n * 1. getAssetsOf(user) - read collateral assets before\n * 2. getCurrentTick() - read pool tick before\n * 3. Execute the target call (e.g., dispatch)\n * 4. getCurrentTick() - read pool tick after\n * 5. getAssetsOf(user) - read collateral assets after\n *\n * ## Why PanopticPool.multicall instead of Multicall3?\n * - Measures **collateral assets** (shares → underlying), not raw wallet balances\n * - Uses **delegatecall**, preserving msg.sender throughout the chain\n * - Single contract interaction with PanopticPool\n * - Correctly reflects what happens during position operations\n *\n * ## Same-Block Guarantee\n * All operations execute within a single eth_call, ensuring atomic consistency.\n *\n * @param params - Simulation parameters\n * @returns Token flow result\n *\n * @example\n * ```typescript\n * const callData = encodeFunctionData({\n * abi: panopticPoolV2Abi,\n * functionName: 'dispatch',\n * args: [positionIdList, finalPositionIdList, positionSizes, tickAndSpreadLimits, false, 0n],\n * })\n *\n * const result = await simulateWithTokenFlow({\n * client,\n * poolAddress,\n * user: userAddress,\n * callData,\n * })\n *\n * if (result.success) {\n * console.log('Token 0 change:', result.tokenFlow.delta0)\n * console.log('Token 1 change:', result.tokenFlow.delta1)\n * }\n * ```\n */\nexport async function simulateWithTokenFlow(\n params: SimulateWithTokenFlowParams,\n): Promise<SimulateWithTokenFlowResult> {\n const { client, poolAddress, user, callData, blockNumber, postCallData, preCallData } = params\n\n // Encode getAssetsOf call\n const getAssetsOfCallData = encodeFunctionData({\n abi: getAssetsOfAbi,\n functionName: 'getAssetsOf',\n args: [user],\n })\n\n // Encode getCurrentTick call\n const getCurrentTickCallData = encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'getCurrentTick',\n })\n\n const preLen = preCallData?.length ?? 0\n\n // Build multicall: [getAssetsOf, getCurrentTick, ...preCallData, targetCall, getCurrentTick, getAssetsOf, ...postCallData]\n const multicallData: Hex[] = [\n getAssetsOfCallData,\n getCurrentTickCallData,\n ...(preCallData ?? []),\n callData,\n getCurrentTickCallData,\n getAssetsOfCallData,\n ...(postCallData ?? []),\n ]\n\n try {\n // Execute via simulateContract on PanopticPool's multicall\n const { result } = await client.simulateContract({\n address: poolAddress,\n abi: multicallAbi,\n functionName: 'multicall',\n args: [multicallData],\n account: user,\n blockNumber,\n })\n\n // Decode getAssetsOf results\n const decodeAssets = (data: Hex): { assets0: bigint; assets1: bigint } => {\n const decoded = decodeFunctionResult({\n abi: getAssetsOfAbi,\n functionName: 'getAssetsOf',\n data,\n })\n return { assets0: decoded[0], assets1: decoded[1] }\n }\n\n // Decode getCurrentTick result (int24 decodes as number, convert to bigint)\n const decodeTick = (data: Hex): bigint => {\n return BigInt(\n decodeFunctionResult({\n abi: panopticPoolV2Abi,\n functionName: 'getCurrentTick',\n data,\n }),\n )\n }\n\n const assetsBefore = decodeAssets(result[0])\n const tickBefore = decodeTick(result[1])\n // result[2..2+preLen-1] are preCallData results\n // result[2+preLen] is the target call result (dispatch)\n const tickAfter = decodeTick(result[3 + preLen])\n const assetsAfter = decodeAssets(result[4 + preLen])\n\n const preCallResults = preLen > 0 ? (result.slice(2, 2 + preLen) as Hex[]) : undefined\n const postCallResults =\n postCallData && postCallData.length > 0 ? (result.slice(5 + preLen) as Hex[]) : undefined\n\n const delta0 = assetsAfter.assets0 - assetsBefore.assets0\n const delta1 = assetsAfter.assets1 - assetsBefore.assets1\n\n // Estimate gas for the target call directly\n let gasEstimate = 0n\n try {\n gasEstimate = await client.estimateGas({\n account: user,\n to: poolAddress,\n data: callData,\n blockNumber,\n })\n } catch {\n // Gas estimation may fail, use 0\n }\n\n return {\n success: true,\n tokenFlow: {\n delta0,\n delta1,\n balanceBefore0: assetsBefore.assets0,\n balanceBefore1: assetsBefore.assets1,\n balanceAfter0: assetsAfter.assets0,\n balanceAfter1: assetsAfter.assets1,\n tickBefore,\n tickAfter,\n },\n gasEstimate,\n postCallResults,\n preCallResults,\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Simulation failed',\n rawError: error instanceof Error ? error : undefined,\n gasEstimate: 0n,\n }\n }\n}\n\n/**\n * Parameters for getting pool tokens.\n */\nexport interface GetPoolTokensParams {\n /** viem public client */\n client: PublicClient\n /** Pool address */\n poolAddress: Address\n /** Optional block number */\n blockNumber?: bigint\n}\n\n/**\n * Pool token addresses result.\n */\nexport interface PoolTokens {\n /** Token 0 address */\n token0: Address\n /** Token 1 address */\n token1: Address\n /** Collateral tracker 0 address */\n collateralTracker0: Address\n /** Collateral tracker 1 address */\n collateralTracker1: Address\n}\n\n/**\n * Get pool token addresses for reference.\n *\n * @param params - Parameters\n * @returns Pool token addresses\n */\nexport async function getPoolTokensForSimulation(params: GetPoolTokensParams): Promise<PoolTokens> {\n const { client, poolAddress, blockNumber } = params\n\n // Minimal ABI for the calls we need\n const poolAbi = [\n {\n type: 'function',\n name: 'collateralToken0',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'collateralToken1',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n ] as const\n\n const collateralAbi = [\n {\n type: 'function',\n name: 'asset',\n inputs: [],\n outputs: [{ type: 'address' }],\n stateMutability: 'view',\n },\n ] as const\n\n // Get collateral tracker addresses\n const [ct0, ct1] = await client.multicall({\n contracts: [\n { address: poolAddress, abi: poolAbi, functionName: 'collateralToken0' },\n { address: poolAddress, abi: poolAbi, functionName: 'collateralToken1' },\n ],\n blockNumber,\n allowFailure: false,\n })\n\n // Get underlying token addresses from collateral trackers\n const [token0, token1] = await client.multicall({\n contracts: [\n { address: ct0, abi: collateralAbi, functionName: 'asset' },\n { address: ct1, abi: collateralAbi, functionName: 'asset' },\n ],\n blockNumber,\n allowFailure: false,\n })\n\n return {\n token0,\n token1,\n collateralTracker0: ct0,\n collateralTracker1: ct1,\n }\n}\n","/** Fee-protected premium settlement simulation. @module v2/simulations/simulateSettle */\n\nimport type { Address, Hex, PublicClient } from 'viem'\nimport { decodeFunctionResult, encodeFunctionData } from 'viem'\n\nimport { panopticPoolV2Abi } from '../../../generated'\nimport { getBlockMeta } from '../clients'\nimport { PanopticError, UnsafePremiumSettlementError } from '../errors'\nimport { getCurrentPositionSizes } from '../reads/positionSizes'\nimport { getForfeitablePremium } from '../reads/premia'\nimport type { SettleSimulation, SimulationResult, TokenFlow } from '../types'\nimport { buildProtectedSettlePlan } from '../writes/protectedSettle'\nimport type { SettleSequenceTarget } from '../writes/settleSequence'\nimport { buildSettleSequenceCalls } from '../writes/settleSequence'\nimport { simulateSettlePremiumBatch } from './simulateSettlePremiumBatch'\nimport { simulateWithTokenFlow } from './tokenFlow'\n\nconst BIT_MASK_128 = (1n << 128n) - 1n\nconst multicallAbi = [\n {\n type: 'function',\n name: 'multicall',\n inputs: [{ name: 'data', type: 'bytes[]' }],\n outputs: [{ name: 'results', type: 'bytes[]' }],\n stateMutability: 'nonpayable',\n },\n] as const\n\nexport interface SimulateSettleParams {\n client: PublicClient\n poolAddress: Address\n account: Address\n positionIdList: bigint[]\n finalPositionIdList?: bigint[]\n positionSizes?: bigint[]\n /** Buyers holding longs against the short chunks being settled. */\n targets?: SettleSequenceTarget[]\n usePremiaAsCollateral?: boolean\n builderCode?: bigint\n /**\n * Allow settlement when premium remains but no buyer settlement or chunk\n * poke can collect it (for example, width-zero legs). Avoidable forfeiture\n * still fails closed. Default false.\n */\n allowForfeit?: boolean\n blockNumber?: bigint\n}\n\nfunction encodeDispatch(plan: ReturnType<typeof buildProtectedSettlePlan>): Hex {\n const dispatch = plan.dispatch\n return encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'dispatch',\n args: [\n dispatch.positionIdList,\n dispatch.finalPositionIdList,\n dispatch.positionSizes,\n dispatch.tickAndSpreadLimits.map(\n (limits) =>\n [Number(limits[0]), Number(limits[1]), Number(limits[2])] as readonly [\n number,\n number,\n number,\n ],\n ),\n dispatch.usePremiaAsCollateral,\n dispatch.builderCode,\n ],\n })\n}\n\nfunction decodeShortPremium(data: Hex): readonly [bigint, bigint] {\n const packed = decodeFunctionResult({\n abi: panopticPoolV2Abi,\n functionName: 'getFullPositionsData',\n data,\n })[0]\n return [packed & BIT_MASK_128, packed >> 128n]\n}\n\nasync function remainingForfeitAfterProtection(params: {\n client: PublicClient\n poolAddress: Address\n account: Address\n positionIdList: bigint[]\n finalPositionIdList: bigint[]\n targets: SettleSequenceTarget[]\n plan: ReturnType<typeof buildProtectedSettlePlan>\n blockNumber: bigint\n initial: readonly [bigint, bigint]\n}): Promise<[bigint, bigint]> {\n const { client, poolAddress, account, positionIdList, targets, plan, blockNumber, initial } =\n params\n if (targets.length === 0 && plan.collectionDispatch === undefined) return [...initial]\n\n const protectionCalls = buildSettleSequenceCalls({\n positionIdListFrom: params.finalPositionIdList,\n targets,\n dispatch: plan.collectionDispatch,\n })\n const availableCall = encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'getFullPositionsData',\n args: [account, false, positionIdList],\n })\n const totalCall = encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'getFullPositionsData',\n args: [account, true, positionIdList],\n })\n const { result } = await client.simulateContract({\n address: poolAddress,\n abi: multicallAbi,\n functionName: 'multicall',\n args: [[...protectionCalls, availableCall, totalCall]],\n account,\n blockNumber,\n })\n const available = decodeShortPremium(result[result.length - 2])\n const total = decodeShortPremium(result[result.length - 1])\n return [\n total[0] > available[0] ? total[0] - available[0] : 0n,\n total[1] > available[1] ? total[1] - available[1] : 0n,\n ]\n}\n\nexport async function simulateSettle(\n params: SimulateSettleParams,\n): Promise<SimulationResult<SettleSimulation>> {\n const {\n client,\n poolAddress,\n account,\n positionIdList,\n finalPositionIdList = positionIdList,\n positionSizes: providedSizes,\n targets = [],\n usePremiaAsCollateral = false,\n builderCode = 0n,\n allowForfeit = false,\n blockNumber,\n } = params\n const targetBlockNumber = blockNumber ?? (await client.getBlockNumber())\n const metaPromise = getBlockMeta({ client, blockNumber: targetBlockNumber })\n\n try {\n if (providedSizes && providedSizes.length !== positionIdList.length) {\n throw new PanopticError('simulateSettle: positionSizes length must match positionIdList')\n }\n const positionSizes =\n providedSizes ??\n (await getCurrentPositionSizes({\n client,\n poolAddress,\n account,\n positionIdList,\n blockNumber: targetBlockNumber,\n }))\n const plan = buildProtectedSettlePlan({\n positionIdList,\n finalPositionIdList,\n positionSizes,\n usePremiaAsCollateral,\n builderCode,\n })\n const initialForfeit = await getForfeitablePremium({\n client,\n poolAddress,\n account,\n tokenIds: positionIdList,\n blockNumber: targetBlockNumber,\n })\n const initial: [bigint, bigint] = [initialForfeit.forfeit0, initialForfeit.forfeit1]\n\n if (targets.length > 0) {\n const buyers = await simulateSettlePremiumBatch({\n client,\n poolAddress,\n account,\n positionIdListFrom: finalPositionIdList,\n targets,\n blockNumber: targetBlockNumber,\n })\n if (buyers.unsettleableCount > 0) {\n throw new UnsafePremiumSettlementError(initial, buyers.unsettleableCount)\n }\n }\n\n const remainingForfeit = await remainingForfeitAfterProtection({\n client,\n poolAddress,\n account,\n positionIdList,\n finalPositionIdList,\n targets,\n plan,\n blockNumber: targetBlockNumber,\n initial,\n })\n if ((remainingForfeit[0] > 0n || remainingForfeit[1] > 0n) && !allowForfeit) {\n throw new UnsafePremiumSettlementError(remainingForfeit, 0)\n }\n\n const callData =\n targets.length === 0\n ? encodeDispatch(plan)\n : encodeFunctionData({\n abi: panopticPoolV2Abi,\n functionName: 'multicall',\n args: [\n buildSettleSequenceCalls({\n positionIdListFrom: finalPositionIdList,\n targets,\n dispatch: plan.dispatch,\n }),\n ],\n })\n const flowResult = await simulateWithTokenFlow({\n client,\n poolAddress,\n user: account,\n callData,\n blockNumber: targetBlockNumber,\n })\n if (!flowResult.success || !flowResult.tokenFlow) {\n throw flowResult.rawError ?? new PanopticError(flowResult.error || 'Simulation failed')\n }\n\n const tokenFlow: TokenFlow = flowResult.tokenFlow\n return {\n success: true,\n data: {\n premiaReceived0: tokenFlow.delta0,\n premiaReceived1: tokenFlow.delta1,\n postCollateral0: tokenFlow.balanceAfter0,\n postCollateral1: tokenFlow.balanceAfter1,\n premiumProtected: [initial[0] - remainingForfeit[0], initial[1] - remainingForfeit[1]],\n remainingForfeit,\n usesPoke: plan.pokingTokenIds.length > 0,\n settledBuyerCount: targets.length,\n },\n gasEstimate: flowResult.gasEstimate,\n tokenFlow,\n _meta: await metaPromise,\n }\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof PanopticError\n ? error\n : new PanopticError(\n error instanceof Error ? error.message : 'Simulation failed',\n error instanceof Error ? error : undefined,\n ),\n _meta: await metaPromise,\n }\n }\n}\n","/**\n * ERC20 approval to the CoW vault relayer.\n *\n * Single-step plain `approve` to GPv2VaultRelayer — CoW does not use Permit2.\n *\n * @module cow/approval\n */\n\nimport { erc20Abi, maxUint256 } from 'viem'\n\nimport type { TxResult } from '../panoptic/v2/types'\nimport { submitWrite } from '../panoptic/v2/writes'\nimport { COW_VAULT_RELAYER } from './addresses'\nimport type { ApproveErc20ForCowParams, CheckCowApprovalParams, CowApprovalStatus } from './types'\n\n/** Check whether the vault relayer can pull `amount` of the sell token. */\nexport async function checkCowApproval(params: CheckCowApprovalParams): Promise<CowApprovalStatus> {\n const { client, sellToken, owner, amount } = params\n\n const allowance = await client.readContract({\n address: sellToken,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [owner, COW_VAULT_RELAYER],\n })\n\n return { needsApproval: allowance < amount, allowance }\n}\n\n/** Approve the sell token to the vault relayer (defaults to unlimited). */\nexport async function approveErc20ForCow(params: ApproveErc20ForCowParams): Promise<TxResult> {\n const { client, walletClient, account, sellToken, amount = maxUint256, txOverrides } = params\n\n return submitWrite({\n client,\n walletClient,\n account,\n address: sellToken,\n abi: erc20Abi,\n functionName: 'approve',\n args: [COW_VAULT_RELAYER, amount],\n txOverrides,\n })\n}\n","/**\n * Venue selection between the Uniswap v4 router and CoW Swap.\n *\n * Pure amount comparison so it stays testable and reusable outside React.\n * Gas cost of the router tx is not factored in (CoW ERC20 sells are gasless);\n * TODO: optionally discount the Uniswap side by gasEstimate × gas price.\n *\n * @module cow/compare\n */\n\n/** Swap venues the UI can route through. */\nexport type SwapVenue = 'uniswap' | 'cow'\n\nconst BPS_DENOMINATOR = 10_000n\n\n/** Parameters for {@link pickBestVenue}. */\nexport interface PickBestVenueParams {\n /** 'sell' = exact-in (maximize output), 'buy' = exact-out (minimize input). */\n kind: 'sell' | 'buy'\n /** Uniswap quote amounts; omit when the quote failed or is unavailable. */\n uniswap?: {\n /** Quoted output (exact-in). */\n amountOut?: bigint\n /** Quoted input (exact-out). */\n amountIn?: bigint\n }\n /** CoW quote amounts; omit when the quote failed or is unavailable. */\n cow?: {\n /** Quoted net output (exact-in). */\n buyAmount?: bigint\n /** Quoted gross input including fee (exact-out). */\n sellAmountTotal?: bigint\n }\n}\n\n/** Result of {@link pickBestVenue}. */\nexport interface BestVenue {\n winner: SwapVenue\n /** Price advantage of the winner over the loser in bps (only when both quoted). */\n advantageBps?: bigint\n}\n\n/**\n * Pick the venue with the better effective price. Exact-in compares net\n * output (higher wins); exact-out compares gross input (lower wins). With a\n * single usable quote that venue wins; ties go to Uniswap (instant\n * settlement); with no usable quotes Uniswap wins by default.\n */\nexport function pickBestVenue(params: PickBestVenueParams): BestVenue {\n const { kind, uniswap, cow } = params\n\n const uniAmount = kind === 'sell' ? uniswap?.amountOut : uniswap?.amountIn\n const cowAmount = kind === 'sell' ? cow?.buyAmount : cow?.sellAmountTotal\n\n if (cowAmount === undefined || cowAmount <= 0n) return { winner: 'uniswap' }\n if (uniAmount === undefined || uniAmount <= 0n) return { winner: 'cow' }\n\n // 'sell': bigger output wins; 'buy': smaller input wins. Ties → Uniswap.\n const cowWins = kind === 'sell' ? cowAmount > uniAmount : cowAmount < uniAmount\n const [better, worse] = cowWins ? [cowAmount, uniAmount] : [uniAmount, cowAmount]\n const advantageBps =\n kind === 'sell'\n ? ((better - worse) * BPS_DENOMINATOR) / worse\n : ((worse - better) * BPS_DENOMINATOR) / better\n\n return { winner: cowWins ? 'cow' : 'uniswap', advantageBps }\n}\n","/**\n * EIP-712 typed-data definitions for GPv2 (CoW Protocol) orders.\n * @module cow/eip712\n */\n\nimport { type Address, keccak256, stringToHex } from 'viem'\n\nimport { COW_SETTLEMENT } from './addresses'\n\n/** GPv2 `Order` struct, in EIP-712 typed-data form. */\nexport const COW_ORDER_TYPES = {\n Order: [\n { name: 'sellToken', type: 'address' },\n { name: 'buyToken', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'sellAmount', type: 'uint256' },\n { name: 'buyAmount', type: 'uint256' },\n { name: 'validTo', type: 'uint32' },\n { name: 'appData', type: 'bytes32' },\n { name: 'feeAmount', type: 'uint256' },\n { name: 'kind', type: 'string' },\n { name: 'partiallyFillable', type: 'bool' },\n { name: 'sellTokenBalance', type: 'string' },\n { name: 'buyTokenBalance', type: 'string' },\n ],\n} as const\n\n/** GPv2 order-cancellation struct (batch of order UIDs). */\nexport const COW_CANCELLATION_TYPES = {\n OrderCancellations: [{ name: 'orderUids', type: 'bytes[]' }],\n} as const\n\n/** EIP-712 domain for GPv2Settlement on the given chain. */\nexport function cowDomain(chainId: bigint | number): {\n name: string\n version: string\n chainId: number\n verifyingContract: Address\n} {\n return {\n name: 'Gnosis Protocol',\n version: 'v2',\n chainId: Number(chainId),\n verifyingContract: COW_SETTLEMENT,\n }\n}\n\n/**\n * Full appData JSON document attached to orders. The order itself carries only\n * its keccak256 hash; the API stores the document when it accompanies the\n * order POST. Must stay byte-identical to {@link APP_DATA_HASH}.\n */\nexport const APP_DATA_DOC = '{\"appCode\":\"panoptic\",\"metadata\":{},\"version\":\"1.3.0\"}'\n\n/** keccak256 of {@link APP_DATA_DOC} — the `appData` field signed in the order. */\nexport const APP_DATA_HASH = keccak256(stringToHex(APP_DATA_DOC))\n","/**\n * Errors for the CoW Protocol swap module.\n *\n * All extend {@link PanopticError} so callers can keep a single\n * `instanceof PanopticError` check and so they satisfy `SimulationResult`'s\n * error type.\n *\n * @module cow/errors\n */\n\nimport { PanopticError } from '../panoptic/v2/errors'\n\n/** The chain has no CoW order book. */\nexport class CowUnsupportedChainError extends PanopticError {\n override readonly name = 'CowUnsupportedChainError'\n\n constructor(\n public readonly chainId: bigint,\n cause?: Error,\n ) {\n super(`CoW Protocol not available on chain ${chainId}`, cause)\n }\n}\n\n/** The order-book API rejected a request (non-2xx response). */\nexport class CowApiError extends PanopticError {\n override readonly name: string = 'CowApiError'\n\n constructor(\n /** Machine-readable API error type, e.g. 'SellAmountDoesNotCoverFee'. */\n public readonly errorType: string,\n message: string,\n public readonly status: number,\n cause?: Error,\n ) {\n super(message, cause)\n }\n}\n\n/** The sell amount is too small to cover the protocol fee (dust order). */\nexport class CowOrderTooSmallError extends CowApiError {\n override readonly name = 'CowOrderTooSmallError'\n\n constructor(message: string, status: number, cause?: Error) {\n super('SellAmountDoesNotCoverFee', message, status, cause)\n }\n}\n\n/** Selling native ETH requires the eth-flow contract (unsupported here); buying it is fine. */\nexport class CowNativeTokenError extends PanopticError {\n override readonly name = 'CowNativeTokenError'\n\n constructor(cause?: Error) {\n super('CoW orders cannot sell native ETH (eth-flow not supported)', cause)\n }\n}\n","/**\n * Minimal fetch wrapper for the CoW order-book REST API.\n * @module cow/api\n */\n\nimport { COW_API_URLS } from './addresses'\nimport { CowApiError, CowOrderTooSmallError, CowUnsupportedChainError } from './errors'\n\n/** Resolve the order-book base URL for a chain (override wins). */\nexport function resolveCowApiUrl(chainId: bigint, apiUrl?: string): string {\n const url = apiUrl ?? COW_API_URLS[Number(chainId)]\n if (!url) throw new CowUnsupportedChainError(chainId)\n return url\n}\n\n/** Shape of order-book error payloads. */\ninterface CowApiErrorBody {\n errorType?: string\n description?: string\n}\n\n/**\n * Call the order book and parse JSON, mapping non-2xx responses to\n * {@link CowApiError} (dust orders to {@link CowOrderTooSmallError}).\n */\nexport async function cowApiRequest<T>(\n baseUrl: string,\n path: string,\n init?: RequestInit,\n): Promise<T> {\n // Normalize headers so a Headers instance / tuple array passed by the caller\n // is preserved (a spread would drop those), only defaulting Content-Type.\n const headers = new Headers(init?.headers)\n if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json')\n const response = await fetch(`${baseUrl}/api/v1${path}`, { ...init, headers })\n\n if (!response.ok) {\n let body: CowApiErrorBody = {}\n try {\n body = (await response.json()) as CowApiErrorBody\n } catch {\n // Non-JSON error body — fall through with the status text.\n }\n const errorType = body.errorType ?? 'UnknownError'\n const message = body.description ?? `CoW API request failed (${response.status})`\n if (errorType === 'SellAmountDoesNotCoverFee') {\n throw new CowOrderTooSmallError(message, response.status)\n }\n throw new CowApiError(errorType, message, response.status)\n }\n\n // Tolerate empty / non-JSON success bodies (e.g. DELETE /orders for a\n // cancellation, which callers type as void): return undefined rather than\n // throwing inside response.json().\n if (response.status === 204) return undefined as T\n const text = await response.text()\n if (text === '') return undefined as T\n return JSON.parse(text) as T\n}\n","/**\n * Sign and submit CoW orders (and signed cancellations) to the order book.\n *\n * Orders are EIP-712 intents — submission returns an order UID, not a tx\n * hash. Settlement happens later when a solver includes the order in a batch;\n * track it via {@link getCowOrderStatus}.\n *\n * @module cow/order\n */\n\nimport type { Hex } from 'viem'\n\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport {\n APP_DATA_DOC,\n APP_DATA_HASH,\n COW_CANCELLATION_TYPES,\n COW_ORDER_TYPES,\n cowDomain,\n} from './eip712'\nimport type { CancelCowOrderParams, CowOrderResult, SignAndSubmitCowOrderParams } from './types'\n\n/**\n * Build the final order from a quote, sign it (EIP-712) and POST it to the\n * order book. The signed `feeAmount` is 0 — the fee is already folded into the\n * quote's `orderSellAmount`.\n */\nexport async function signAndSubmitCowOrder(\n params: SignAndSubmitCowOrderParams,\n): Promise<CowOrderResult> {\n const { walletClient, account, chainId, quote, receiver = account, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const order = {\n sellToken: quote.sellToken,\n buyToken: quote.buyToken,\n receiver,\n sellAmount: quote.orderSellAmount,\n buyAmount: quote.orderBuyAmount,\n validTo: Number(quote.validTo),\n appData: APP_DATA_HASH,\n feeAmount: 0n,\n kind: quote.kind,\n partiallyFillable: false,\n sellTokenBalance: 'erc20',\n buyTokenBalance: 'erc20',\n } as const\n\n const signature = await walletClient.signTypedData({\n account,\n domain: cowDomain(chainId),\n types: COW_ORDER_TYPES,\n primaryType: 'Order',\n message: order,\n })\n\n const orderUid = await cowApiRequest<Hex>(baseUrl, '/orders', {\n method: 'POST',\n body: JSON.stringify({\n ...order,\n sellAmount: order.sellAmount.toString(),\n buyAmount: order.buyAmount.toString(),\n feeAmount: '0',\n // Full appData document so the API can verify it against the signed hash.\n appData: APP_DATA_DOC,\n appDataHash: APP_DATA_HASH,\n signingScheme: 'eip712',\n signature,\n from: account,\n quoteId: quote.quoteId ?? undefined,\n }),\n })\n\n return { orderUid }\n}\n\n/**\n * Cancel an open order off-chain (free, signed cancellation). Cancellation is\n * best-effort: an order already committed to a solver batch can still settle.\n */\nexport async function cancelCowOrder(params: CancelCowOrderParams): Promise<void> {\n const { walletClient, account, chainId, orderUid, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const signature = await walletClient.signTypedData({\n account,\n domain: cowDomain(chainId),\n types: COW_CANCELLATION_TYPES,\n primaryType: 'OrderCancellations',\n message: { orderUids: [orderUid] },\n })\n\n await cowApiRequest<void>(baseUrl, '/orders', {\n method: 'DELETE',\n body: JSON.stringify({ orderUids: [orderUid], signature, signingScheme: 'eip712' }),\n })\n}\n","/**\n * Quote swaps via the CoW order-book API.\n *\n * Unlike the Uniswap quoter this is an off-chain HTTP call; results still come\n * back as a `SimulationResult` so UI error handling matches the router path.\n *\n * @module cow/quote\n */\n\nimport { zeroAddress } from 'viem'\n\nimport { PanopticError } from '../panoptic/v2/errors'\nimport type { SimulationResult } from '../panoptic/v2/types'\nimport { COW_NATIVE_ETH } from './addresses'\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport { APP_DATA_DOC } from './eip712'\nimport { CowNativeTokenError } from './errors'\nimport type { CowQuote, QuoteCowSwapParams } from './types'\n\nconst BPS_DENOMINATOR = 10_000n\n/** Default order validity window (30 minutes). */\nexport const DEFAULT_VALID_FOR_SECONDS = 1800n\n\n/** No block context for off-chain quotes. */\nconst OFFCHAIN_META = {\n blockNumber: 0n,\n blockTimestamp: 0n,\n blockHash: '0x0' as `0x${string}`,\n}\n\n/**\n * Reject out-of-range slippage so the limit-amount math can't underflow/overflow.\n * 100% (BPS_DENOMINATOR) is forbidden too: on the exact-in path it would reduce\n * `orderBuyAmount` to 0, signing an order that accepts any fill.\n */\nfunction assertSlippageBps(slippageBps: bigint): void {\n if (slippageBps < 0n || slippageBps >= BPS_DENOMINATOR) {\n throw new PanopticError(`invalid slippageBps ${slippageBps}, must be 0..9999`)\n }\n}\n\n/** Raw order-book quote response (amounts are decimal strings). */\ninterface CowQuoteResponse {\n quote: {\n sellToken: string\n buyToken: string\n sellAmount: string\n buyAmount: string\n feeAmount: string\n validTo: number\n kind: 'sell' | 'buy'\n }\n id: number | null\n}\n\n/**\n * Quote a swap via the CoW order book.\n *\n * For `kind: 'sell'` (exact-in) `amount` is the sell amount before fee; for\n * `kind: 'buy'` (exact-out) it is the exact buy amount. The returned\n * `orderSellAmount`/`orderBuyAmount` are ready to sign: the fee is folded into\n * the sell side (orders are placed with `feeAmount: 0` under the current fee\n * model) and `slippageBps` is applied to the non-exact side.\n */\nexport async function quoteCowSwap(\n params: QuoteCowSwapParams,\n): Promise<SimulationResult<CowQuote>> {\n const {\n chainId,\n sellToken,\n buyToken,\n kind,\n amount,\n from,\n slippageBps,\n validForSeconds = DEFAULT_VALID_FOR_SECONDS,\n apiUrl,\n } = params\n\n try {\n assertSlippageBps(slippageBps)\n // Selling native ETH would need the eth-flow contract; buying it is fine —\n // orders use the buy-token sentinel and settle in native ETH.\n if (sellToken === zeroAddress) {\n throw new CowNativeTokenError()\n }\n const resolvedBuyToken = buyToken === zeroAddress ? COW_NATIVE_ETH : buyToken\n if (amount <= 0n) {\n throw new PanopticError(`amount ${amount} must be positive`)\n }\n\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n const response = await cowApiRequest<CowQuoteResponse>(baseUrl, '/quote', {\n method: 'POST',\n body: JSON.stringify({\n sellToken,\n buyToken: resolvedBuyToken,\n from,\n receiver: from,\n validFor: Number(validForSeconds),\n appData: APP_DATA_DOC,\n partiallyFillable: false,\n sellTokenBalance: 'erc20',\n buyTokenBalance: 'erc20',\n signingScheme: 'eip712',\n ...(kind === 'sell'\n ? { kind: 'sell', sellAmountBeforeFee: amount.toString() }\n : { kind: 'buy', buyAmountAfterFee: amount.toString() }),\n }),\n })\n\n const sellAmount = BigInt(response.quote.sellAmount)\n const buyAmount = BigInt(response.quote.buyAmount)\n const feeAmount = BigInt(response.quote.feeAmount)\n const sellAmountTotal = sellAmount + feeAmount\n\n // Fold the fee into the signed sell amount (feeAmount signs as 0), then\n // apply slippage to the side the user did not fix. Buy-order sell cap uses\n // ceiling division so the buffer never rounds down.\n const orderSellAmount =\n kind === 'sell'\n ? sellAmountTotal\n : (sellAmountTotal * (BPS_DENOMINATOR + slippageBps) + BPS_DENOMINATOR - 1n) /\n BPS_DENOMINATOR\n const orderBuyAmount =\n kind === 'sell' ? (buyAmount * (BPS_DENOMINATOR - slippageBps)) / BPS_DENOMINATOR : buyAmount\n\n return {\n success: true,\n data: {\n kind,\n sellToken,\n // The signed order must carry the resolved (sentinel) buy token.\n buyToken: resolvedBuyToken,\n sellAmount,\n buyAmount,\n feeAmount,\n sellAmountTotal,\n orderSellAmount,\n orderBuyAmount,\n validTo: BigInt(response.quote.validTo),\n quoteId: response.id,\n },\n gasEstimate: 0n,\n _meta: OFFCHAIN_META,\n }\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof PanopticError\n ? error\n : new PanopticError(\n error instanceof Error ? error.message : 'CoW quote failed',\n error instanceof Error ? error : undefined,\n ),\n _meta: OFFCHAIN_META,\n }\n }\n}\n","/**\n * Poll order state from the CoW order book.\n * @module cow/status\n */\n\nimport type { Hex } from 'viem'\n\nimport { cowApiRequest, resolveCowApiUrl } from './api'\nimport type { CowOrderState, CowOrderStatus, GetCowOrderStatusParams } from './types'\n\n/** Raw `GET /orders/{uid}` fields we consume. */\ninterface CowOrderResponse {\n status: CowOrderStatus\n executedSellAmount: string\n executedBuyAmount: string\n}\n\n/** Raw `GET /trades` entry fields we consume. */\ninterface CowTradeResponse {\n txHash: Hex | null\n}\n\n/**\n * Fetch an order's lifecycle state. Once any trade has executed, the\n * settlement tx hash is included (fetched from the trades endpoint).\n */\nexport async function getCowOrderStatus(params: GetCowOrderStatusParams): Promise<CowOrderState> {\n const { chainId, orderUid, apiUrl } = params\n const baseUrl = resolveCowApiUrl(chainId, apiUrl)\n\n const order = await cowApiRequest<CowOrderResponse>(baseUrl, `/orders/${orderUid}`)\n\n const executedSellAmount = BigInt(order.executedSellAmount ?? '0')\n const executedBuyAmount = BigInt(order.executedBuyAmount ?? '0')\n\n let settlementTxHash: Hex | undefined\n if (executedBuyAmount > 0n) {\n const trades = await cowApiRequest<CowTradeResponse[]>(baseUrl, `/trades?orderUid=${orderUid}`)\n settlementTxHash = trades.find((t) => t.txHash)?.txHash ?? undefined\n }\n\n return { status: order.status, executedSellAmount, executedBuyAmount, settlementTxHash }\n}\n","/**\n * Resolve token symbols to addresses using the token lists CoW Swap trades\n * from. Lets a UI route any listed token (e.g. xStocks like NVDAx) to the\n * order book without maintaining a static registry.\n *\n * Sources, in priority order:\n * 1. CoW's curated list (canonical entries for blue-chip symbols like UNI)\n * 2. CoinGecko's full per-chain list (carries the long tail, incl. xStocks)\n *\n * Lists are fetched lazily and cached in-module for an hour.\n *\n * @module cow/tokens\n */\n\nimport { type Address, getAddress } from 'viem'\n\n/** Resolved token-list entry. */\nexport interface CowTokenInfo {\n chainId: number\n address: Address\n symbol: string\n name: string\n decimals: number\n logoURI?: string\n}\n\n/** Parameters for {@link findCowToken}. */\nexport interface FindCowTokenParams {\n /** Chain to resolve on. */\n chainId: bigint\n /** Token symbol, case-insensitive (e.g. 'nvdax'). */\n symbol: string\n /** Override the token-list URLs (e.g. tests). */\n listUrls?: string[]\n}\n\n/** CoinGecko per-chain list slugs for the chains CoW supports here. */\nconst COINGECKO_CHAIN_SLUGS: Partial<Record<number, string>> = {\n 1: 'ethereum',\n}\n\nfunction tokenListUrls(chainId: number): string[] {\n const urls = ['https://files.cow.fi/tokens/CowSwap.json']\n const slug = COINGECKO_CHAIN_SLUGS[chainId]\n if (slug) urls.push(`https://tokens.coingecko.com/${slug}/all.json`)\n return urls\n}\n\ninterface RawTokenList {\n tokens: {\n chainId?: number\n address: string\n symbol: string\n name: string\n decimals: number\n logoURI?: string\n }[]\n}\n\nconst LIST_CACHE_TTL_MS = 3_600_000\nconst listCache = new Map<string, { fetchedAt: number; list: Promise<RawTokenList | null> }>()\n\n/** Fetch a token list with an in-module 1h cache; resolves null on any failure. */\nfunction fetchTokenList(url: string): Promise<RawTokenList | null> {\n const cached = listCache.get(url)\n if (cached && Date.now() - cached.fetchedAt < LIST_CACHE_TTL_MS) return cached.list\n\n const list = fetch(url)\n .then((res) => (res.ok ? (res.json() as Promise<RawTokenList>) : null))\n .catch(() => null)\n .then((parsed) => {\n // Drop failures from the cache so the next call retries.\n if (parsed === null || !Array.isArray(parsed.tokens)) {\n listCache.delete(url)\n return null\n }\n return parsed\n })\n listCache.set(url, { fetchedAt: Date.now(), list })\n return list\n}\n\n/**\n * Find a token by symbol on the given chain across CoW's token lists. The\n * first list containing a (case-insensitive) symbol match wins; within a\n * list the first match wins, which favors canonical entries on collisions.\n * Returns null when no list resolves the symbol (or all fetches fail).\n *\n * Resolution only proves the token is listed — whether solvers can actually\n * fill a given pair/size is answered by `quoteCowSwap`.\n */\nexport async function findCowToken(params: FindCowTokenParams): Promise<CowTokenInfo | null> {\n const { chainId, symbol, listUrls } = params\n const chain = Number(chainId)\n const wanted = symbol.toUpperCase()\n\n for (const url of listUrls ?? tokenListUrls(chain)) {\n const list = await fetchTokenList(url)\n if (!list) continue\n const match = list.tokens.find(\n // CoW's own list omits chainId on some entries (single-chain lists).\n (t) => (t.chainId === undefined || t.chainId === chain) && t.symbol.toUpperCase() === wanted,\n )\n if (match) {\n // Validate/checksum the external address; skip a malformed entry rather\n // than leak a non-Address string to callers.\n let address: Address\n try {\n address = getAddress(match.address)\n } catch {\n continue\n }\n return {\n chainId: chain,\n address,\n symbol: match.symbol,\n name: match.name,\n decimals: match.decimals,\n logoURI: match.logoURI,\n }\n }\n }\n return null\n}\n","/**\n * Generated registry of Backed xStock ERC4626 wrappers on Ethereum mainnet.\n *\n * DO NOT EDIT BY HAND. Regenerate with `pnpm --filter panoptic-v2-sdk gen:xstock-wrappers`\n * (scripts/gen-xstock-wrappers.ts), which scans the WrappedBackedTokenFactory\n * `NewToken` events and reads each wrapper's ERC4626 `asset()` as the underlying.\n *\n * @module cow/xstockWrappers.generated\n */\n\nimport type { XstockWrapperRegistry } from './xstockWrappers'\n\nexport const XSTOCK_WRAPPERS: XstockWrapperRegistry = {\n 1: [\n {\n wrapper: '0x5AA7649fdbDa47De64A07aC81D64B682AF9C0724',\n underlying: '0x9d275685dC284C8eB1C79f6ABA7a63Dc75ec890a',\n symbol: 'wAAPLx',\n name: 'Wrapped Apple xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5CC079963Fb70C0f987F65F539E3B61a6EBdf6Db',\n underlying: '0xfBF2398dF672cEE4aFcC2A4A733222331c742a6A',\n symbol: 'wABBVx',\n name: 'Wrapped AbbVie xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD812B37181Ae89801e4BB3F49E4C1FAF11fC0b57',\n underlying: '0x89233399708C18Ac6887F90A2B4Cd8Ba5fEdD06e',\n symbol: 'wABTx',\n name: 'Wrapped Abbott xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc262Bea18cb810Cc7715EE48fe3cbD3D79B4aFe1',\n underlying: '0x03183Ce31b1656B72A55fa6056e287f50C35BbEB',\n symbol: 'wACNx',\n name: 'Wrapped Accenture xStock',\n decimals: 18,\n },\n {\n wrapper: '0x444DE06b76C9a1417A21A877038F49A1f0D8A1cD',\n underlying: '0x16E0B579be45bAaE54cEddd52e742B6457A7fE12',\n symbol: 'wADBEx',\n name: 'Wrapped Adobe xStock',\n decimals: 18,\n },\n {\n wrapper: '0x36d2fe6e6e4136C6BF286588391FAD6d45422350',\n underlying: '0x2f9a35aB5dDFBc49927BFdEab98A86c53DC6E763',\n symbol: 'wAMBRx',\n name: 'Wrapped Amber xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1eb8909B5C46A24F005A76C469912f5518F448eF',\n underlying: '0x3522513E5F146a2006e2901b05f16B2821485E19',\n symbol: 'wAMDx',\n name: 'Wrapped AMD xStock',\n decimals: 18,\n },\n {\n wrapper: '0xac85d37acbadCa37545E21ab0fB991bcE8c1187C',\n underlying: '0x3557Ba345B01EFa20A1bdDC61F573BFD87195081',\n symbol: 'wAMZNx',\n name: 'Wrapped Amazon.com xStock',\n decimals: 18,\n },\n {\n wrapper: '0xd17E483364D849e3B3A52464bb2CA56626EDfc31',\n underlying: '0x50a1291F69D9d3853Def8209cFb1AF0b46927BE1',\n symbol: 'wAPPx',\n name: 'Wrapped AppLovin xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD0798d3c30F4408350C8448d75DA1c7721227dBa',\n underlying: '0xC0B417e7F83db438631Eb5E096684dd742E5294F',\n symbol: 'wASMLx',\n name: 'Wrapped ASML xStock',\n decimals: 18,\n },\n {\n wrapper: '0x720347faf9D745B841541De0d7B2abc8A4b87531',\n underlying: '0x89b2607878ae19baB8020b8140eD550Ef3E953bb',\n symbol: 'wASTSx',\n name: 'Wrapped AST SpaceMobile xStock',\n decimals: 18,\n },\n {\n wrapper: '0x8DEb752aAA807E0258afd5cCFFe2b5A804026f28',\n underlying: '0x38BAC69cbBd28156796e4163B2B6dcb81E336565',\n symbol: 'wAVGOx',\n name: 'Wrapped Broadcom xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0b306951161b856Ad02c8566B4eF184c6BB08564',\n underlying: '0xb23767492D0Ca6dC7221CBeA45689a0410f388c4',\n symbol: 'wAXPx',\n name: 'Wrapped American Express xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB908FEAeab7E671dB697d77c3acFD8859E92a4e2',\n underlying: '0x5D642505FE1a28897eb3BaBA665F454755D8daA2',\n symbol: 'wAZNx',\n name: 'Wrapped AstraZeneca xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA2b1335256cd663Da89F650180508dd1f0DC3BAa',\n underlying: '0x314938c596F5ce31C3f75307d2979338C346D7F2',\n symbol: 'wBACx',\n name: 'Wrapped Bank of America xStock',\n decimals: 18,\n },\n {\n wrapper: '0xDEc933e2392AD908263e70A386fbF34e703Ffe8F',\n underlying: '0xbbcb0356bB9e6B3Faa5CbF9E5F36185d53403Ac9',\n symbol: 'wbCOIN',\n name: 'Wrapped Backed Coinbase Global',\n decimals: 18,\n },\n {\n wrapper: '0x277f724d12DD0249b48CBD7eB2623c5e5042b970',\n underlying: '0xa8A25DB6Cf17Fa097f1DBbc9c841892456898fF3',\n symbol: 'wBKNGx',\n name: 'Wrapped Booking xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE5365A5A16A7D1DD37b33e6F8D78aeB89847398B',\n underlying: '0x5A6a0742cA689E7E8a91A38F5255589CB2191646',\n symbol: 'wBLKx',\n name: 'Wrapped BlackRock xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7a1d054e09eAe0294D53959674EE9DE14a1f70B1',\n underlying: '0x38DE7b9FC733DeF81525E65C1Bf99722026489e2',\n symbol: 'wBLSHx',\n name: 'Wrapped Bullish xStock',\n decimals: 18,\n },\n {\n wrapper: '0xBFd29b7F395d30932033c2F45ab792024E71AA94',\n underlying: '0xaeB681B69E5094E04d11BCeF51A71358A374C3ED',\n symbol: 'wBMNRx',\n name: 'Wrapped Bitmine xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1a4F71B0Ff3C22540887bcf83b50054a213c673d',\n underlying: '0xaC28C9178ACc8BA4A11A29E013a3A2627086e422',\n symbol: 'wbMSTR',\n name: 'Wrapped Backed MicroStrategy Inc',\n decimals: 18,\n },\n {\n wrapper: '0x7E8101A1C322D394b3961498c7D40d2DFA94C392',\n underlying: '0xA34C5e0AbE843E10461E2C9586Ea03E55Dbcc495',\n symbol: 'wbNVDA',\n name: 'Wrapped Backed NVIDIA Corp',\n decimals: 18,\n },\n {\n wrapper: '0xa150245f155778e749185C9446e9e59E406674eF',\n underlying: '0x12992613fDd35aBe95DEc5a4964331b1ee23B50d',\n symbol: 'wBRK.Bx',\n name: 'Wrapped Berkshire Hathaway xStock',\n decimals: 18,\n },\n {\n wrapper: '0x88E437dbebdDe3D75Ff7c0cb830F54dd834538f0',\n underlying: '0x22E1991e5f82736A2a990322a46aac0e95826c5B',\n symbol: 'wBTBTx',\n name: 'Wrapped Bit Digital xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1f82284C1658Ad71C576f7230E6C2DEE7901c1FA',\n underlying: '0x14A5f2872396802C3Cc8942A39Ab3E4118EE5038',\n symbol: 'wbTSLA',\n name: 'Wrapped Backed Tesla Inc',\n decimals: 18,\n },\n {\n wrapper: '0xdCE0CA61bC9F95b771e0764dc4C553288b7F2f13',\n underlying: '0xD0194F0f077968DA8ca59811e9407f54AE6c9432',\n symbol: 'wCLSKx',\n name: 'Wrapped CleanSpark xStock',\n decimals: 18,\n },\n {\n wrapper: '0xd1A01e3F9c7565e88b1CF2413ba0a0E671e57b33',\n underlying: '0xBC7170a1280Be28513B4e940C681537EB25e39f4',\n symbol: 'wCMCSAx',\n name: 'Wrapped Comcast xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3a98E79cDc7D8B2716A8696E25af028E429f11dA',\n underlying: '0x364f210f430eC2448Fc68A49203040F6124096F0',\n symbol: 'wCOINx',\n name: 'Wrapped Coinbase xStock',\n decimals: 18,\n },\n {\n wrapper: '0x89E2B6cA78DBee629544679780963b85Ba76fe2a',\n underlying: '0x51eD5b74A05F256DbD9Ebb4e4f68Bb41ba10160b',\n symbol: 'wCORZx',\n name: 'Wrapped Core Scientific xStock',\n decimals: 18,\n },\n {\n wrapper: '0xFa48FeE923600Fecaa7af0DfB4a66E3109Ad51bf',\n underlying: '0x4720B5e6421e6879132aED52040d56Bb6e5CFeeF',\n symbol: 'wCOSTx',\n name: 'Wrapped Costco xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA90872ACa656eBE47bDEBF3B19Ec9Dd9C5ADC7f8',\n underlying: '0xfEbDEd1B0986a8ee107f5AB1a1c5a813491DeCEB',\n symbol: 'wCRCLx',\n name: 'Wrapped Circle xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc6B6B8D50A6673C04C495e30B411da5A7adF39f5',\n underlying: '0x4A4073f2EAF299A1be22254DCD2C41727F6F54a2',\n symbol: 'wCRMx',\n name: 'Wrapped Salesforce xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD71a6aDBc40c2674591CDB11B8C7ae03A880b06E',\n underlying: '0x214151022C2a5E380aB80CdaC31f23Ae554a7345',\n symbol: 'wCRWDx',\n name: 'Wrapped CrowdStrike xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCFa485bc42c2492917351F89F5cf5c7b2C5a66aa',\n underlying: '0x053C784cD87B74f42e0c089f98643E79c1A3ff16',\n symbol: 'wCSCOx',\n name: 'Wrapped Cisco xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7F88888b7A81546a036554Aa67a289Ea428b20d4',\n underlying: '0xad5cdc3340904285B8159089974A99a1A09EB4C0',\n symbol: 'wCVXx',\n name: 'Wrapped Chevron xStock',\n decimals: 18,\n },\n {\n wrapper: '0xce41bF7482E86fFF0Ab0A971dD425496BB58E4FD',\n underlying: '0x521860bB5dF5468358875266B89BFE90d990C6e7',\n symbol: 'wDFDVx',\n name: 'Wrapped DFDV xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6c7AD1886a6Da37766fED060d5F08fF43285DcdD',\n underlying: '0xdbA228936F4079DaF9Aa906fd48a87f2300405F4',\n symbol: 'wDHRx',\n name: 'Wrapped Danaher xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3E5ceeA6D6399Ac1a1FEE67C1644fc7F616aD9fD',\n underlying: '0x03D44b9bB0398E2Be3C89417D51E615C3D461F5a',\n symbol: 'wDUOLx',\n name: 'Wrapped Duolingo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0c4F0256FB31cC71666Fee3f0cE1De3B1abE347B',\n underlying: '0x4c7610990cb63cdca174ce61822F7693B49FCe93',\n symbol: 'wEBAYx',\n name: 'Wrapped eBay xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5230C4b621bd2d1f22933903F9a4fA82a9F17fcf',\n underlying: '0xd1be5bA0c293997C7F69da707D14EB4ABCB13ddD',\n symbol: 'wEXPEx',\n name: 'Wrapped Expedia xStock',\n decimals: 18,\n },\n {\n wrapper: '0x91049e9586301c54B2eF410C2b7e9040Ffb02182',\n underlying: '0x3C313D234D0C6C876F6c21ba2EC1F26823247Be2',\n symbol: 'wFIGx',\n name: 'Wrapped Figma xStock',\n decimals: 18,\n },\n {\n wrapper: '0xdeAE051463CD8C457e7e9D97A398c575E8629c18',\n underlying: '0x3AE27479E6e52f6ddB6EA8AA567e6Cc92C78d93a',\n symbol: 'wFUFUx',\n name: 'Wrapped BitFuFu xStock',\n decimals: 18,\n },\n {\n wrapper: '0x61532Ce3f1DF7fBf5fFb7B891d184226e85B37c6',\n underlying: '0x2380F2673C640fB67E2d6B55B44C62F0E0e69DA9',\n symbol: 'wGLDx',\n name: 'Wrapped Gold xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4c79D4A1a863830EF845431578FB40E31bD51f4A',\n underlying: '0xf7F4fAC56f012dE7Dd6adFF54C761986B9E0655a',\n symbol: 'wGLXYx',\n name: 'Wrapped Galaxy Digital xStock',\n decimals: 18,\n },\n {\n wrapper: '0xb2f6ED0ED3eEb22bEF7A648794FFC19b8aF3761C',\n underlying: '0xE5f6d3b2405ABdfE6F660e63202B25D23763160d',\n symbol: 'wGMEx',\n name: 'Wrapped Gamestop xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1630F08370917E79df0B7572395a5e907508bBBc',\n underlying: '0xe92f673Ca36C5E2Efd2DE7628f815f84807e803F',\n symbol: 'wGOOGLx',\n name: 'Wrapped Alphabet xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6eEd78e2780d82BE4E37d9937C27Bcf32C8DA072',\n underlying: '0x3Ee7E9B3A992fD23CD1C363B0e296856B04ab149',\n symbol: 'wGSx',\n name: 'Wrapped Goldman Sachs xStock',\n decimals: 18,\n },\n {\n wrapper: '0xC641E2eBF6E076e2AE53477C2E725b3c67C0fd94',\n underlying: '0x766b0CD6ED6D90B5d49d2c36a3761E9728501BA9',\n symbol: 'wHDx',\n name: 'Wrapped Home Depot xStock',\n decimals: 18,\n },\n {\n wrapper: '0xBd1B73b2E89967e83507B500D798998200A53380',\n underlying: '0x62a48560861B0b451654bFffdb5be6E47aa8ff1B',\n symbol: 'wHONx',\n name: 'Wrapped Honeywell xStock',\n decimals: 18,\n },\n {\n wrapper: '0x953707d7A1cB30cc5C636bDA8EaeBe410341eB14',\n underlying: '0xE1385FDd5ffB10081Cd52C56584F25EFa9084015',\n symbol: 'wHOODx',\n name: 'Wrapped Robinhood xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6Ec2763859C5b04F5598017880744081aFeFa3Bb',\n underlying: '0xd457b379801433EA5c3A8542b61902023AE39DcD',\n symbol: 'wHSDTx',\n name: 'Wrapped Helius Medical Technologies xStock',\n decimals: 18,\n },\n {\n wrapper: '0x154f25Cfd146d2DF6420ec1f575C3c46D45f4Db7',\n underlying: '0x560deb3D70Ac90064fF809349cDf9A771a06fd36',\n symbol: 'wHUTx',\n name: 'Wrapped Hut 8 xStock',\n decimals: 18,\n },\n {\n wrapper: '0xa8F31436FFE4E71f51B2D65b7D5a5c457AE2000f',\n underlying: '0xd9913208647671Fe0F48F7F260076B2C6F310Aac',\n symbol: 'wIBMx',\n name: 'Wrapped International Business Machines xStock',\n decimals: 18,\n },\n {\n wrapper: '0x59361E881b186e48D71EC61E969dCF50a4dbC75b',\n underlying: '0x6a668332825450ACD2e449372057d31b3de16a1E',\n symbol: 'wIEMGx',\n name: 'Wrapped Core MSCI Emerging Markets xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3ab20fd7c57146AF128E8565261CBdaDa0F015E6',\n underlying: '0xAA28cB97D7f7E172f54deE950743886D2d65447d',\n symbol: 'wIJRx',\n name: 'Wrapped S&P Small Cap xStock',\n decimals: 18,\n },\n {\n wrapper: '0x6A2a68Ca7FC793D8CEa36326a6Ec1eF7AC3D9742',\n underlying: '0xf8A80D1cb9cFD70D03D655D9dF42339846F3B3C8',\n symbol: 'wINTCx',\n name: 'Wrapped Intel xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5A47DE111D731Fd2Df90E4A2d7a9b459b31Bd643',\n underlying: '0xdadfb355c6110eda0908740d52c834d6C2BCDDc7',\n symbol: 'wIWMx',\n name: 'Wrapped Russell 2000 xStock',\n decimals: 18,\n },\n {\n wrapper: '0xcdB53A7cBa9Ec6d55dfE8f58bd6772826722D7BD',\n underlying: '0xdb0482cfaD4789798623E64b15eebA01b16e917C',\n symbol: 'wJNJx',\n name: 'Wrapped Johnson & Johnson xStock',\n decimals: 18,\n },\n {\n wrapper: '0xaB635f839f81A12dC8Db8Ab31006af14E26292fE',\n underlying: '0xD9FC3E075d45254a1D834fEa18AF8041207DeA0A',\n symbol: 'wJPMx',\n name: 'Wrapped JPMorgan Chase xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9a2486fbe7bC17C9100be65c31aBE7c9Bf84C23c',\n underlying: '0xdCC1a2699441079dA889B1F49e12B69cC791129b',\n symbol: 'wKOx',\n name: 'Wrapped Coca-Cola xStock',\n decimals: 18,\n },\n {\n wrapper: '0x316fFEa434348c2cB72024e62Ae845770315351E',\n underlying: '0x15059c599C16Fd8f70B633Ade165502D6402CD49',\n symbol: 'wLINx',\n name: 'Wrapped Linde xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3644971A7E971f60e707F7E8716cCaC5a0461290',\n underlying: '0x19c41EA77b34BbDEe61c3A87A75D1ABDA2ED0be4',\n symbol: 'wLLYx',\n name: 'Wrapped Eli Lilly xStock',\n decimals: 18,\n },\n {\n wrapper: '0xD395C4dAd12eb071714d2b86cB5bC16acE9996B6',\n underlying: '0x847dEB9c78fb00319bC7A006dFF729c11428E537',\n symbol: 'wLULUx',\n name: 'Wrapped lululemon xStock',\n decimals: 18,\n },\n {\n wrapper: '0x34f5273693C880a9B2d9B6cfc8e13A2f3B8C0F06',\n underlying: '0x9D692bffEf6f6BedF4274053ff9998EFE3B2539E',\n symbol: 'wMARAx',\n name: 'Wrapped MARA xStock',\n decimals: 18,\n },\n {\n wrapper: '0x5b32624f352d2FC6cC70889967A143ba1814f82b',\n underlying: '0xb365Cd2588065F522D379AD19e903304f6B622C6',\n symbol: 'wMAx',\n name: 'Wrapped Mastercard xStock',\n decimals: 18,\n },\n {\n wrapper: '0x1717D8Be2Bcb27f4E8f36c817088Fa6a2c0b3B30',\n underlying: '0x80A77a372c1e12AcCdA84299492f404902E2DA67',\n symbol: 'wMCDx',\n name: \"Wrapped McDonald's xStock\",\n decimals: 18,\n },\n {\n wrapper: '0x02C1b10e5329c4502469396B2ce9f200E60b4a77',\n underlying: '0x0588e851ec0418d660BeE81230d6c678dAF21d46',\n symbol: 'wMDTx',\n name: 'Wrapped Medtronic xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4E41a262cAA93C6575d336E0a4eb79f3c67caa06',\n underlying: '0x96702be57Cd9777f835117a809C7124fe4ec989A',\n symbol: 'wMETAx',\n name: 'Wrapped Meta xStock',\n decimals: 18,\n },\n {\n wrapper: '0x61a6Cd11f658D1b418e1082b564678983b71Fb7F',\n underlying: '0x8499b26BBfC8c3830a37b92E47DF2d7cBc0154e9',\n symbol: 'wMNSTx',\n name: 'Wrapped Monster xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4728E48c2C201E32fe210AaB68A71E419FEAc74a',\n underlying: '0x17D8186Ed8F68059124190D147174D0f6697dc40',\n symbol: 'wMRKx',\n name: 'Wrapped Merck xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0d6fce45796D5c00689c0916b976645a0FF1F0cE',\n underlying: '0xeAAd46F4146Ded5a47B55AA7F6c48c191dEAEC88',\n symbol: 'wMRVLx',\n name: 'Wrapped Marvell xStock',\n decimals: 18,\n },\n {\n wrapper: '0x63Ad27614231767C8C489745B9145272De50D09b',\n underlying: '0x5621737f42dAE558b81269FcB9E9E70c19Aa6b35',\n symbol: 'wMSFTx',\n name: 'Wrapped Microsoft xStock',\n decimals: 18,\n },\n {\n wrapper: '0x266E5923F6118F8b340cA5a23AE7f71897361476',\n underlying: '0xAE2f842EF90C0d5213259Ab82639D5BBF649b08E',\n symbol: 'wMSTRx',\n name: 'Wrapped MicroStrategy xStock',\n decimals: 18,\n },\n {\n wrapper: '0x529E286229963bE57F0EC6F57d2D70A2F3E29935',\n underlying: '0xf6a873BAe4Ba1B304e45dF52A4b7D176E1C6a8c4',\n symbol: 'wMUx',\n name: 'Wrapped Micron Technology xStock',\n decimals: 18,\n },\n {\n wrapper: '0xfE0D2545f9E7f3678CB35Ed3CDf70488C5570D11',\n underlying: '0xA6a65AC27E76cD53cB790473E4345c46e5eBf961',\n symbol: 'wNFLXx',\n name: 'Wrapped Netflix xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93E62845C1DD5822EbC807ab71A5Fb750DecD15A',\n underlying: '0xc845b2894dBddd03858fd2D643B4eF725fE0849d',\n symbol: 'wNVDAx',\n name: 'Wrapped NVIDIA xStock',\n decimals: 18,\n },\n {\n wrapper: '0x16E443AEbc83E2089AA90431A1C0d311854EEC69',\n underlying: '0xF9523E369c5f55ad72DbAA75B0a9b92B3D8b147e',\n symbol: 'wNVOx',\n name: 'Wrapped Novo Nordisk xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9608a6eB064dd1C35eC9A4332bD9F8b05D1dE66C',\n underlying: '0x4b0eE7C047D43cA403239f28f42115bEdB7c0076',\n symbol: 'wOKLOx',\n name: 'Wrapped Oklo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9836479c80823f5f8B60FD0171F8D96301185714',\n underlying: '0xbEe6b69345F376598Fe16AbD5592c6F844825E66',\n symbol: 'wOPENx',\n name: 'Wrapped OPEN xStock',\n decimals: 18,\n },\n {\n wrapper: '0x54f34Ceb15313Caaee838F77c1c3C2Fe2E94526A',\n underlying: '0x548308E91ec9F285C7bFf05295baDBD56a6e4971',\n symbol: 'wORCLx',\n name: 'Wrapped Oracle xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7FbE0E7ACB47DCb053BF6146cCA6Bfb81A5D1319',\n underlying: '0xe12BB32D77BE4DB10DDC82088b230D35d097E9C5',\n symbol: 'wPANWx',\n name: 'Wrapped Palo Alto Networks xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA00A5538708b5aca7045F2ca15104707965bac94',\n underlying: '0x36c424a6EC0e264b1616102Ad63eD2aD7857413e',\n symbol: 'wPEPx',\n name: 'Wrapped PepsiCo xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4E6894c3481B3A45393ce8ac9552945Ad50A3758',\n underlying: '0x1Ac765B5BEa23184802C7d2d497f7c33f1444A9e',\n symbol: 'wPFEx',\n name: 'Wrapped Pfizer xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0afC19943fA98E9E9E90Fc4ab4d4D3c13E162232',\n underlying: '0xa90424D5D3E770e8644103AB503ed775dD1318FD',\n symbol: 'wPGx',\n name: 'Wrapped Procter & Gamble xStock',\n decimals: 18,\n },\n {\n wrapper: '0xa3B6Fe1a923585bb828fCFAa460B78EeFD5aE2EC',\n underlying: '0x6d482CeC5f9dd1f05CCee9Fd3ff79B246170F8e2',\n symbol: 'wPLTRx',\n name: 'Wrapped Palantir xStock',\n decimals: 18,\n },\n {\n wrapper: '0xF429759BBf687118efd6B3713303006C356b8765',\n underlying: '0x536825370F1159cBA953055f5c2F16DDc7B5a348',\n symbol: 'wPLx',\n name: 'Wrapped Planet Labs xStock',\n decimals: 18,\n },\n {\n wrapper: '0x7C2e00e6b0d519a8C492d20c2524342A4398FF34',\n underlying: '0x02a6c1789c3B4FDb1a7a3DfA39F90e5d3c94F4F9',\n symbol: 'wPMx',\n name: 'Wrapped Philip Morris xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCf4953c617CD1306A1f9236084204fBc67FDA2Ac',\n underlying: '0xf706585e7e8900bE0267bEE3B9A2F70835EC6628',\n symbol: 'wPYPLx',\n name: 'Wrapped PayPal xStock',\n decimals: 18,\n },\n {\n wrapper: '0xdbD9232fee15351068Fe02F0683146e16D9f2cEa',\n underlying: '0xa753A7395cAe905Cd615Da0B82A53E0560f250af',\n symbol: 'wQQQx',\n name: 'Wrapped Nasdaq xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc1de0BA489E6a5df9ebbA3911e382b455DeDF8c3',\n underlying: '0x5d8dA1417E3565eb02C9ca8cC588bE5D8F65b1c5',\n symbol: 'wRBLXx',\n name: 'Wrapped Roblox xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE99c177Bcb254bE2A0333c3B7071c696400Df1cF',\n underlying: '0x6Ac47387f0a2798dF4C4eE5bb31ab9517ac97cb8',\n symbol: 'wRIOTx',\n name: 'Wrapped Riot Platforms xStock',\n decimals: 18,\n },\n {\n wrapper: '0xf3f249dBaA9E3e9C9B78b1784cECd954e829aC81',\n underlying: '0xE17ce7dD2afb6Da3488fD9ef2558523D569e17B4',\n symbol: 'wRKLBx',\n name: 'Wrapped Rocket Lab xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4329d7C2Fa1De1c7218cd0c68587e2225C8C53fB',\n underlying: '0x7c7445A40926152B8d24aBDb9020e219d3D3380a',\n symbol: 'wSATAx',\n name: 'Wrapped Strive, Inc. Series A Preferred xStock',\n decimals: 18,\n },\n {\n wrapper: '0x9Fd163B1020535C24A3140DB9BB1153E6dEf8fCd',\n underlying: '0x338791c58fdED314b81EAb139A1A2Fb7967D90d6',\n symbol: 'wSBETx',\n name: 'Wrapped SharpLink Gaming xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB9FCE7dcDfa1962EB53B3e2000554A77F0c10E8b',\n underlying: '0xF6D87E523512704C29E9b7cA3e9e6226bDCE3EA1',\n symbol: 'wSCHFx',\n name: 'Wrapped Schwab International Equity xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93bd84EE978b60f37df0639f70EAC621e542AD4b',\n underlying: '0x4833e7f4f0460f4B72A3a5879A6C9841bCC5B58B',\n symbol: 'wSLVx',\n name: 'Wrapped iShares Silver Trust xStock',\n decimals: 18,\n },\n {\n wrapper: '0x382567e5D72eca3eD2Bb97a4e42918107E09fab0',\n underlying: '0x7F8ba411ECBC0A135d669d5EaE5D15b0Ca0b0ea1',\n symbol: 'wSPCEx',\n name: 'Wrapped Virgin Galactic xStock',\n decimals: 18,\n },\n {\n wrapper: '0x8e2eeD8b8B5E13Ea7BF38e50d7821d2C57309072',\n underlying: '0x68fa48B1C2FE52b3D776E1953e0E782b5044Ce28',\n symbol: 'wSPCXx',\n name: 'Wrapped SpaceX xStock',\n decimals: 18,\n },\n {\n wrapper: '0x2f5a59Dd87C57fBfA10a5Ab12fD902C8AFdA2dfD',\n underlying: '0xD3c5Af6B2F0F754b2141f368cFc5ea99C3594d3a',\n symbol: 'wSPGIx',\n name: 'Wrapped S&P Global xStock',\n decimals: 18,\n },\n {\n wrapper: '0xc88FcD8B874fDb3256E8B55b3decB8c24EAb4c02',\n underlying: '0x90A2a4c76b5D8c0bc892A69EA28Aa775a8f2dD48',\n symbol: 'wSPYx',\n name: 'Wrapped SP500 xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0B2456017C5Df2dFc0289740C4b352049892780C',\n underlying: '0x1Aad217B8F78dbA5E6693460e8470F8b1A3977f3',\n symbol: 'wSTRCx',\n name: 'Wrapped Strategy PP Variable xStock',\n decimals: 18,\n },\n {\n wrapper: '0xB038B3b1f999897035AD4Ea65A9d6F59E2e86588',\n underlying: '0x38E0445308E7FcD5230F2DF6b52B36DD4FF313b6',\n symbol: 'wSTRKx',\n name: 'Wrapped Strategy PP Fixed xStock',\n decimals: 18,\n },\n {\n wrapper: '0xCd932bF1c895B7143ec34Df5Ae7889D3853904D8',\n underlying: '0x4cbf89ED7Bb30b8a860fa86d3c96E9c72931299b',\n symbol: 'wTBLLx',\n name: 'Wrapped TBLL xStock',\n decimals: 18,\n },\n {\n wrapper: '0xfa4fFDbf6D53E1539B03823D72886Ab9510250E7',\n underlying: '0x61AeE4f4e6B62806c26eafF921e7F41782cA2E03',\n symbol: 'wTEMx',\n name: 'Wrapped Tempus AI xStock',\n decimals: 18,\n },\n {\n wrapper: '0x0420112790C619Fbbd44106bC72ce217b515269A',\n underlying: '0xAB6a44AD34D083f463fa6F64d0619F11eB2cb48D',\n symbol: 'wTGTx',\n name: 'Wrapped Target xStock',\n decimals: 18,\n },\n {\n wrapper: '0x89EA0284308dEEF33a22abd7ea33888b4349108C',\n underlying: '0xAF072F109A2C173D822a4fe9af311A1B18F83d19',\n symbol: 'wTMOx',\n name: 'Wrapped Thermo Fisher xStock',\n decimals: 18,\n },\n {\n wrapper: '0xF940Fd9D8B80412C47691442075848cc05cD6732',\n underlying: '0x68F3DDEE8BAE33691E7CD0372984fD857E842760',\n symbol: 'wTMUSx',\n name: 'Wrapped T-Mobile xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4b12EB39418e30fC0e86E36CDac0545c1d9edAc9',\n underlying: '0xe95ab205e333443D7970336D5fD827eF9eD97608',\n symbol: 'wTONXx',\n name: 'Wrapped TON xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3D843414E617CBb9D2328c7eCF155d7C18139D6A',\n underlying: '0xfDDDb57878eF9D6f681Ec4381DCB626b9E69AC86',\n symbol: 'wTQQQx',\n name: 'Wrapped TQQQ xStock',\n decimals: 18,\n },\n {\n wrapper: '0x93730D679190e831caea5e4ce46a5701D555e0F2',\n underlying: '0xeCF59a3FD0224D33429920f8fa6dE493abc4EFC0',\n symbol: 'wTRONx',\n name: 'Wrapped Tron xStock',\n decimals: 18,\n },\n {\n wrapper: '0x43680aBF18cf54898Be84C6eF78237CFBD441883',\n underlying: '0x8aD3c73F833d3F9A523aB01476625F269aEB7Cf0',\n symbol: 'wTSLAx',\n name: 'Wrapped Tesla xStock',\n decimals: 18,\n },\n {\n wrapper: '0x083283FAfD9CEC6145ce6a4A50F020A01737De52',\n underlying: '0x9e3bf4Ecfc44EeDD624F26656B6736a3F093b073',\n symbol: 'wTSMx',\n name: 'Wrapped TSMC xStock',\n decimals: 18,\n },\n {\n wrapper: '0xb10F7AA3BC0ad9FcE5Fc99702C2022d47BA93827',\n underlying: '0x75639aE3A05079873D7189DcbDBc455898cAe904',\n symbol: 'wTx',\n name: 'Wrapped AT&T xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4BEa51f138A30329b8855bf0DaE85EA5644Ada82',\n underlying: '0xdb9783Ca04bBD64fe2c6d7B9503A979b3DE30729',\n symbol: 'wUBERx',\n name: 'Wrapped Uber xStock',\n decimals: 18,\n },\n {\n wrapper: '0xA0412CE46fE877b7f174B82aCD95E70063BbaF2a',\n underlying: '0x167A6375DA1eFc4a5BE0f470E73eCEfd66245048',\n symbol: 'wUNHx',\n name: 'Wrapped UnitedHealth xStock',\n decimals: 18,\n },\n {\n wrapper: '0x92DB84B2358E97976DAD16f91E6aeb9B2A757e76',\n underlying: '0x7AB6C97f65e4227adc5090Bd31a376D1F36f39fa',\n symbol: 'wVSTx',\n name: 'Wrapped Vistra xStock',\n decimals: 18,\n },\n {\n wrapper: '0xE9161F111c55Bdd67525C1d4F9bbca07750aaAb7',\n underlying: '0xbD730E618bcD88C82dDeE52e10275CF2f88A4777',\n symbol: 'wVTIx',\n name: 'Wrapped Vanguard xStock',\n decimals: 18,\n },\n {\n wrapper: '0x48Da55D8FE70A4E3ec421736369BACB8D62Fa089',\n underlying: '0x6d5edEEbBc6A4099Eb8bb289EB3b80D799f7b28C',\n symbol: 'wVTx',\n name: 'Wrapped Vanguard Total World xStock',\n decimals: 18,\n },\n {\n wrapper: '0x3cf193acf378Ec224a0209Be888b4b0B963E1896',\n underlying: '0x2363FD1235C1B6d3A5088DdF8dF3A0b3A30C5293',\n symbol: 'wVx',\n name: 'Wrapped Visa xStock',\n decimals: 18,\n },\n {\n wrapper: '0x4cA269239B760787bB2A54C055c383FD2DADE779',\n underlying: '0xc435b3C41AE56d9Bc57b8525F4d522C978F168e8',\n symbol: 'wWBDx',\n name: 'Wrapped Warner Bros. Discovery xStock',\n decimals: 18,\n },\n {\n wrapper: '0x97C4C1704111B7c2304B177C37858B7169c667f9',\n underlying: '0xfEEE18422F8F1cD6193C12aAfad7123DbfF15517',\n symbol: 'wWENx',\n name: \"Wrapped Wendy's xStock\",\n decimals: 18,\n },\n {\n wrapper: '0xa24D9c43D64c76aCD962003647FD43a85eb44Db8',\n underlying: '0x7AEfc9965699fBea943e03264d96e50CD4A97b21',\n symbol: 'wWMTx',\n name: 'Wrapped Walmart xStock',\n decimals: 18,\n },\n {\n wrapper: '0xf068165CFf011A56562F855b44CF690e371232C8',\n underlying: '0xC0c2150cf0870E2d7aBc7cDe17C20A542faFBB9B',\n symbol: 'wWULFx',\n name: 'Wrapped TeraWulf xStock',\n decimals: 18,\n },\n {\n wrapper: '0x448bC811F60eac772775dD53421380E8D4DC4338',\n underlying: '0xEEdb0273c5Af792745180e9fF568cD01550fFA13',\n symbol: 'wXOMx',\n name: 'Wrapped Exxon Mobil xStock',\n decimals: 18,\n },\n ],\n}\n","/**\n * Resolve xStocks (tokenized equities) to their Backed ERC4626 wrapper, and\n * back.\n *\n * xStocks are rebasing, so they can't be used directly in AMMs / Panoptic\n * pools — those are built on the non-rebasing **wrapped** version minted by the\n * Backed `WrappedBackedTokenFactory`. CoW Swap, by contrast, trades the\n * unwrapped xStock. A user who buys e.g. NVDAx on CoW therefore holds the\n * unwrapped token and must wrap it before lending it or selling it through the\n * Uniswap/Panoptic venue.\n *\n * The factory exposes no underlying→wrapper lookup and its `NewToken` event\n * omits the underlying, so this mapping is generated offline (see\n * `scripts/gen-xstock-wrappers.ts`) into {@link XSTOCK_WRAPPERS} and resolved\n * statically here — no runtime fetch.\n *\n * Each wrapper is a standard ERC4626 vault: `asset()` is the underlying xStock,\n * `deposit` wraps, `redeem` unwraps, and `convertToShares`/`convertToAssets`\n * (or `previewDeposit`/`previewRedeem`) convert amounts.\n *\n * @module cow/xstockWrappers\n */\n\nimport type { Address } from 'viem'\n\nimport { XSTOCK_WRAPPERS } from './xstockWrappers.generated'\n\nexport { XSTOCK_WRAPPERS }\n\n/** A single xStock → wrapper mapping entry. */\nexport interface XstockWrapperInfo {\n /** ERC4626 wrapper (the token Panoptic/Uniswap pools trade). */\n wrapper: Address\n /** Underlying rebasing xStock (`asset()` of the wrapper; the CoW-traded token). */\n underlying: Address\n /** Wrapper symbol, e.g. `wNVDAx`. */\n symbol: string\n /** Wrapper name, e.g. `Wrapped NVIDIA xStock`. */\n name: string\n /** Wrapper (and underlying) ERC20 decimals. */\n decimals: number\n}\n\n/** Generated registry keyed by chainId. */\nexport type XstockWrapperRegistry = Partial<Record<number, XstockWrapperInfo[]>>\n\n/**\n * Per-chain lookup indices, built lazily from the static registry. Keys are\n * lowercased addresses for case-insensitive matching. Caching static config is\n * safe (it carries no dynamic on-chain data).\n */\nconst indexCache = new Map<\n number,\n { byUnderlying: Map<string, XstockWrapperInfo>; byWrapper: Map<string, XstockWrapperInfo> }\n>()\n\nfunction getIndex(chainId: number) {\n let idx = indexCache.get(chainId)\n if (!idx) {\n const byUnderlying = new Map<string, XstockWrapperInfo>()\n const byWrapper = new Map<string, XstockWrapperInfo>()\n for (const entry of XSTOCK_WRAPPERS[chainId] ?? []) {\n byUnderlying.set(entry.underlying.toLowerCase(), entry)\n byWrapper.set(entry.wrapper.toLowerCase(), entry)\n }\n idx = { byUnderlying, byWrapper }\n indexCache.set(chainId, idx)\n }\n return idx\n}\n\n/**\n * Resolve the wrapper for an unwrapped xStock. Returns `undefined` when the\n * address isn't a known xStock underlying on this chain.\n */\nexport function getXstockWrapper(\n chainId: number,\n underlying: Address,\n): XstockWrapperInfo | undefined {\n return getIndex(chainId).byUnderlying.get(underlying.toLowerCase())\n}\n\n/**\n * Resolve the underlying xStock for a wrapper address. Returns `undefined` when\n * the address isn't a known xStock wrapper on this chain.\n */\nexport function getXstockUnderlying(\n chainId: number,\n wrapper: Address,\n): XstockWrapperInfo | undefined {\n return getIndex(chainId).byWrapper.get(wrapper.toLowerCase())\n}\n\n/** True if `address` is a known unwrapped xStock on this chain. */\nexport function isXstockUnderlying(chainId: number, address: Address): boolean {\n return getXstockWrapper(chainId, address) !== undefined\n}\n\n/** True if `address` is a known xStock wrapper on this chain. */\nexport function isXstockWrapper(chainId: number, address: Address): boolean {\n return getXstockUnderlying(chainId, address) !== undefined\n}\n"],"mappings":";;;;AAYA,MAAaA,iBAA0B;;AAGvC,MAAaC,oBAA6B;;;;;;AAO1C,MAAaC,iBAA0B;;AAGvC,MAAaC,eAAgD;CA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V;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IAAE,MAAM;IAAQ,cAAc;IAAW,MAAM;IAAW,SAAS;GAAM;GACzE;IAAE,MAAM;IAAM,cAAc;IAAW,MAAM;IAAW,SAAS;GAAM;GACvE;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;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D;IAAE,MAAM;IAAkB,cAAc;IAAa,MAAM;GAAa;GACxE;IAAE,MAAM;IAAyB,cAAc;IAAQ,MAAM;GAAQ;EACtE;EACD,MAAM;EACN,SAAS,CAAE;EACX,iBAAiB;CAClB;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IAAE,MAAM;IAAQ,cAAc;IAAW,MAAM;IAAW,SAAS;GAAM;GACzE;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;GACD;IACE,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;GACV;EACF;EACD,MAAM;CACP;CACD;EACE,MAAM;EACN,WAAW;EACX,QAAQ;GACN;IAAE,MAAM;IAAQ,cAAc;IAAW,MAAM;IAAW,SAAS;GAA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