@panoptic-eng/sdk 1.0.37 → 1.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/cow/index.d.ts +804 -6
  2. package/dist/cow/index.d.ts.map +1 -0
  3. package/dist/cow/index.js +5268 -5
  4. package/dist/cow/index.js.map +1 -0
  5. package/dist/{cow-aX6of9TS.js → cow-tRUtAUZy.js} +2 -3
  6. package/dist/deployments.d.ts +3 -2
  7. package/dist/deployments.d.ts.map +1 -1
  8. package/dist/deployments.js +4 -0
  9. package/dist/deployments.js.map +1 -1
  10. package/dist/{position-C8rkkKhi.js → getTrackedPositionIds-ms3W9dYB.js} +1085 -34
  11. package/dist/greeks-GysWXct-.js +1 -2
  12. package/dist/index.d.ts +5907 -39
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +12192 -2117
  15. package/dist/index.js.map +1 -1
  16. package/dist/{irm-DnM96-X4.js → irm-SPC2KxLA.js} +6 -3
  17. package/dist/panoptic/v2/greeks/index.d.ts +277 -3
  18. package/dist/panoptic/v2/greeks/index.d.ts.map +1 -0
  19. package/dist/panoptic/v2/greeks/index.js +620 -2
  20. package/dist/panoptic/v2/greeks/index.js.map +1 -0
  21. package/dist/panoptic/v2/index.d.ts +14633 -8
  22. package/dist/panoptic/v2/index.d.ts.map +1 -0
  23. package/dist/panoptic/v2/index.js +27875 -8
  24. package/dist/panoptic/v2/index.js.map +1 -0
  25. package/dist/panoptic/v2/react-public.d.ts +14797 -17
  26. package/dist/panoptic/v2/react-public.d.ts.map +1 -1
  27. package/dist/panoptic/v2/react-public.js +29503 -89
  28. package/dist/panoptic/v2/react-public.js.map +1 -1
  29. package/dist/{router-DcoU2KmV.js → router-BTfbaRfg.js} +2 -3
  30. package/dist/{router-CS86ptMu.js → router-mLWy0MD9.js} +3 -4
  31. package/dist/test/index.d.ts +1 -1
  32. package/dist/test/index.js +2 -2
  33. package/dist/transactionFees-C_Qx07mx.js +174 -0
  34. package/dist/uniswap/index.d.ts +813 -79
  35. package/dist/uniswap/index.d.ts.map +1 -1
  36. package/dist/uniswap/index.js +5884 -13
  37. package/dist/uniswap/index.js.map +1 -1
  38. package/dist/{v2-D0dEatKb.js → v2-DG7qG6di.js} +3266 -2675
  39. package/dist/vault-transaction-fees.d.ts +63 -0
  40. package/dist/vault-transaction-fees.d.ts.map +1 -0
  41. package/dist/vault-transaction-fees.js +175 -0
  42. package/dist/vault-transaction-fees.js.map +1 -0
  43. package/dist/{writes-AupZCK4M.js → writes-Xp9Wa8GQ.js} +325 -1292
  44. package/package.json +8 -3
  45. package/dist/cow/types.d.ts +0 -3
  46. package/dist/cow/types.js +0 -0
  47. package/dist/cow-aX6of9TS.js.map +0 -1
  48. package/dist/greeks-GysWXct-.js.map +0 -1
  49. package/dist/index-CURXeKNy.d.ts +0 -9706
  50. package/dist/index-CURXeKNy.d.ts.map +0 -1
  51. package/dist/index-Cp-nCeV2.d.ts +0 -276
  52. package/dist/index-Cp-nCeV2.d.ts.map +0 -1
  53. package/dist/index-Zvu-rJpV.d.ts +0 -261
  54. package/dist/index-Zvu-rJpV.d.ts.map +0 -1
  55. package/dist/irm-CmgC1Mqi.d.ts +0 -5694
  56. package/dist/irm-CmgC1Mqi.d.ts.map +0 -1
  57. package/dist/irm-DnM96-X4.js.map +0 -1
  58. package/dist/position-BqIgubs5.d.ts +0 -199
  59. package/dist/position-BqIgubs5.d.ts.map +0 -1
  60. package/dist/position-C8rkkKhi.js.map +0 -1
  61. package/dist/quote-BxQkPBRg.d.ts +0 -718
  62. package/dist/quote-BxQkPBRg.d.ts.map +0 -1
  63. package/dist/router-CS86ptMu.js.map +0 -1
  64. package/dist/router-DcoU2KmV.js.map +0 -1
  65. package/dist/simulation-zM6-YUaw.d.ts +0 -258
  66. package/dist/simulation-zM6-YUaw.d.ts.map +0 -1
  67. package/dist/tx-CbDQ58Io.d.ts +0 -367
  68. package/dist/tx-CbDQ58Io.d.ts.map +0 -1
  69. package/dist/types-BHdnurYr.d.ts +0 -128
  70. package/dist/types-BHdnurYr.d.ts.map +0 -1
  71. package/dist/types-D_jcYss-.d.ts +0 -248
  72. package/dist/types-D_jcYss-.d.ts.map +0 -1
  73. package/dist/v2-D0dEatKb.js.map +0 -1
  74. package/dist/writes-AupZCK4M.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panoptic-eng/sdk",
3
- "version": "1.0.37",
3
+ "version": "1.0.39",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/panoptic-labs/panoptic-sdk.git"
@@ -39,6 +39,10 @@
39
39
  "types": "./dist/zodiac/index.d.ts",
40
40
  "import": "./dist/zodiac/index.js"
41
41
  },
42
+ "./vault-transaction-fees": {
43
+ "types": "./dist/vault-transaction-fees.d.ts",
44
+ "import": "./dist/vault-transaction-fees.js"
45
+ },
42
46
  "./test": {
43
47
  "types": "./dist/test/index.d.ts",
44
48
  "import": "./dist/test/index.js"
@@ -50,8 +54,9 @@
50
54
  "scripts": {
51
55
  "check:no-src-dts": "node ./scripts/check-no-src-dts.mjs",
52
56
  "clean:tsbuildinfo": "node -e \"require('fs').rmSync('tsconfig.tsbuildinfo',{force:true})\"",
53
- "build": "pnpm run check:no-src-dts && pnpm run clean:tsbuildinfo && pnpm run codegen:graphql && node ./scripts/tsdown-with-retry.mjs && pnpm run build:deployments-dts",
54
- "build:ci": "pnpm run check:no-src-dts && pnpm run clean:tsbuildinfo && pnpm run codegen && pnpm tsdown && pnpm run build:deployments-dts",
57
+ "build": "pnpm run check:no-src-dts && pnpm run clean:tsbuildinfo && pnpm run codegen:graphql && pnpm tsdown && pnpm run build:dts && pnpm run build:deployments-dts",
58
+ "build:ci": "pnpm run check:no-src-dts && pnpm run clean:tsbuildinfo && pnpm run codegen && pnpm tsdown && pnpm run build:dts && pnpm run build:deployments-dts",
59
+ "build:dts": "node ./scripts/build-dts.mjs",
55
60
  "build:deployments-dts": "pnpm tsdown -c tsdown.deployments.config.ts && node ./scripts/inline-deployments-dts.mjs",
56
61
  "dev": "pnpm concurrently \"pnpm run codegen:graphql --watch\" \"pnpm tsdown --watch\"",
57
62
  "typecheck": "tsc --noEmit -p tsconfig.build.json",
@@ -1,3 +0,0 @@
1
- import "../tx-CbDQ58Io.js";
2
- import { ApproveErc20ForCowParams, CancelCowOrderParams, CheckCowApprovalParams, CowApprovalStatus, CowOrderKind, CowOrderResult, CowOrderState, CowOrderStatus, CowQuote, GetCowOrderStatusParams, QuoteCowSwapParams, SignAndSubmitCowOrderParams } from "../types-BHdnurYr.js";
3
- export { ApproveErc20ForCowParams, CancelCowOrderParams, CheckCowApprovalParams, CowApprovalStatus, CowOrderKind, CowOrderResult, CowOrderState, CowOrderStatus, CowQuote, GetCowOrderStatusParams, QuoteCowSwapParams, SignAndSubmitCowOrderParams };
package/dist/cow/types.js DELETED
File without changes
@@ -1 +0,0 @@
1
- {"version":3,"file":"cow-aX6of9TS.js","names":["COW_SETTLEMENT: Address","COW_VAULT_RELAYER: Address","COW_NATIVE_ETH: Address","COW_API_URLS: Partial<Record<number, string>>","chainId: bigint | number","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/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 * 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;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,aAAa,IAAI;AAKvB,SAAS,SAASC,SAAiB;CACjC,IAAI,MAAM,WAAW,IAAI,QAAQ;AACjC,MAAK,KAAK;EACR,MAAM,eAAe,IAAI;EACzB,MAAM,YAAY,IAAI;AACtB,OAAK,MAAM,SAAS,gBAAgB,YAAY,CAAE,GAAE;AAClD,gBAAa,IAAI,MAAM,WAAW,aAAa,EAAE,MAAM;AACvD,aAAU,IAAI,MAAM,QAAQ,aAAa,EAAE,MAAM;EAClD;AACD,QAAM;GAAE;GAAc;EAAW;AACjC,aAAW,IAAI,SAAS,IAAI;CAC7B;AACD,QAAO;AACR;;;;;AAMD,SAAgB,iBACdA,SACAC,YAC+B;AAC/B,QAAO,SAAS,QAAQ,CAAC,aAAa,IAAI,WAAW,aAAa,CAAC;AACpE;;;;;AAMD,SAAgB,oBACdD,SACAE,SAC+B;AAC/B,QAAO,SAAS,QAAQ,CAAC,UAAU,IAAI,QAAQ,aAAa,CAAC;AAC9D;;AAGD,SAAgB,mBAAmBF,SAAiBG,SAA2B;AAC7E,QAAO,iBAAiB,SAAS,QAAQ;AAC1C;;AAGD,SAAgB,gBAAgBH,SAAiBG,SAA2B;AAC1E,QAAO,oBAAoB,SAAS,QAAQ;AAC7C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"greeks-GysWXct-.js","names":["Q192","exponent: bigint","value: bigint","value: string","numerator: bigint","denominator: bigint","precision: bigint","leftNumerator: bigint","leftDenominator: bigint","rightNumerator: bigint","rightDenominator: bigint","tick: bigint","sqrtPriceX96: bigint","decimals0: bigint","decimals1: bigint","price: string","tickLower: bigint","tickUpper: bigint","feeBps: bigint","tickSpacing: bigint","currentTick: bigint","toleranceBps: bigint","tick: bigint","isAssetToken0: boolean","numerator: bigint","denominator: bigint","leg: Pick<TokenIdLeg, 'asset'>","assetIndex?: bigint","leg: TokenIdLeg","m: bigint","qCurrentTick: bigint","qStrikeTick: bigint","qMintTick: bigint","_definedRisk: boolean","swapAtMint: boolean","itmOffsetNotional: bigint","halfWidthTick: bigint","isPut: boolean","sqrtK","sqrtPm","sqrtR","rX192","diff","diffSqX192","tokenType: bigint","legs: Pick<TokenIdLeg, 'tokenType' | 'isLong'>[]","currentTick: bigint","mintTick: bigint","positionSize: bigint","poolTickSpacing: bigint","definedRisk: boolean","swapAtMint?: boolean","v: bigint","mintTick: bigint | undefined","vDelta","isPut","debtDelta","itmDelta","vDelta: bigint","delta: bigint","fromAsset: bigint","vaultAssetIndex: 0n | 1n","input: PositionGreeksInput","sum","input: Omit<PositionGreeksInput, 'assetIndex' | 'swapAtMint'> & {\n assetIndex: 0n | 1n\n }","positions: PositionGreeksInput[]","input: PositionGreeksInput & { swapAtMint: boolean }"],"sources":["../src/panoptic/v2/utils/constants.ts","../src/panoptic/v2/formatters/tick.ts","../src/panoptic/v2/greeks/index.ts"],"sourcesContent":["/**\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 * 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 * 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","/**\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"],"mappings":";;;;;;;;;AASA,MAAa,MAAM,OAAO;;;;;AAM1B,MAAa,kBAAkB;CAC7B,QAAQ;EACN,QAAQ;EACR,QAAQ;EACR,iBAAiB;EACjB,cAAc;CACf;CACD,QAAQ;EACN,QAAQ;EACR,QAAQ;EACR,iBAAiB;EACjB,cAAc;CACf;AACF;;;;;AAMD,MAAa,iBAAiB;CAC5B,sBAAsB;CACtB,sBAAsB;CACtB,oBAAoB;CACpB,oBAAoB;CACpB,eAAe;CACf,eAAe;AAChB;;;;;AAMD,MAAa,iBAAiB;;;;AAK9B,MAAa,iBAAiB;;;;;AAM9B,MAAa,qBAAqB;;;;;AAMlC,MAAa,cAAc;;;;AAK3B,MAAa,uBAAuB;;;;AAKpC,MAAa,YAAY;;;;AAKzB,MAAa,WAAW;;;;AAKxB,MAAa,kBAAkB;;;;AAK/B,MAAa,0BAA0B;;;;AC/EvC,MAAMA,SAAO,MAAM;AACnB,MAAM,sBAAsB;AAE5B,SAAS,MAAMC,UAA0B;AACvC,KAAI,WAAW,GACb,OAAM,IAAI,WAAW;AAEvB,QAAO,OAAO;AACf;AAED,SAAS,UAAUC,OAAuB;AACxC,QAAO,QAAQ,MAAM,QAAQ;AAC9B;AAED,SAAS,kBAAkBC,OAAuB;CAChD,MAAM,WAAW,MAAM,QAAQ,IAAI;AACnC,KAAI,aAAa,GAAI,QAAO;C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