@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488

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 (156) hide show
  1. package/CHANGELOG.md +105 -9
  2. package/dist/PerpsController-method-action-types.d.ts +149 -3
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +125 -3
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +787 -31
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +69 -9
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +82 -11
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +15 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +14 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/perpsConfig.d.ts +10 -2
  18. package/dist/constants/perpsConfig.d.ts.map +1 -1
  19. package/dist/constants/perpsConfig.js +11 -3
  20. package/dist/constants/perpsConfig.js.map +1 -1
  21. package/dist/index.d.ts +10 -8
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal/accountReturnOnEquity.d.ts +12 -0
  26. package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
  27. package/dist/internal/accountReturnOnEquity.js +18 -0
  28. package/dist/internal/accountReturnOnEquity.js.map +1 -0
  29. package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
  30. package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
  31. package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
  32. package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
  33. package/dist/internal/marketNumericValues.d.ts +10 -0
  34. package/dist/internal/marketNumericValues.d.ts.map +1 -0
  35. package/dist/internal/marketNumericValues.js +9 -0
  36. package/dist/internal/marketNumericValues.js.map +1 -0
  37. package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
  38. package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
  39. package/dist/internal/perpsDisplaySymbol.js +21 -0
  40. package/dist/internal/perpsDisplaySymbol.js.map +1 -0
  41. package/dist/perpsErrorCodes.d.ts +1 -0
  42. package/dist/perpsErrorCodes.d.ts.map +1 -1
  43. package/dist/perpsErrorCodes.js +1 -0
  44. package/dist/perpsErrorCodes.js.map +1 -1
  45. package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
  46. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  47. package/dist/providers/AggregatedPerpsProvider.js +140 -0
  48. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  49. package/dist/providers/HyperLiquidProvider.d.ts +72 -4
  50. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  51. package/dist/providers/HyperLiquidProvider.js +751 -159
  52. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  53. package/dist/providers/LighterProvider.d.ts +2 -1
  54. package/dist/providers/LighterProvider.d.ts.map +1 -1
  55. package/dist/providers/LighterProvider.js +11 -6
  56. package/dist/providers/LighterProvider.js.map +1 -1
  57. package/dist/selectors.d.ts +15 -5
  58. package/dist/selectors.d.ts.map +1 -1
  59. package/dist/selectors.js +23 -5
  60. package/dist/selectors.js.map +1 -1
  61. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
  62. package/dist/services/AggregatedOrderBookConnection.js +8 -10
  63. package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
  64. package/dist/services/HyperLiquidClientService.d.ts +8 -0
  65. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  66. package/dist/services/HyperLiquidClientService.js +65 -0
  67. package/dist/services/HyperLiquidClientService.js.map +1 -1
  68. package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
  69. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  70. package/dist/services/HyperLiquidSubscriptionService.js +117 -30
  71. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  72. package/dist/services/MarketDataService.d.ts +20 -3
  73. package/dist/services/MarketDataService.d.ts.map +1 -1
  74. package/dist/services/MarketDataService.js +55 -3
  75. package/dist/services/MarketDataService.js.map +1 -1
  76. package/dist/services/StreamChannelManager.d.ts +139 -0
  77. package/dist/services/StreamChannelManager.d.ts.map +1 -0
  78. package/dist/services/StreamChannelManager.js +475 -0
  79. package/dist/services/StreamChannelManager.js.map +1 -0
  80. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  81. package/dist/services/TerminalMarketService.js +7 -0
  82. package/dist/services/TerminalMarketService.js.map +1 -1
  83. package/dist/services/agentSigner.d.ts +8 -0
  84. package/dist/services/agentSigner.d.ts.map +1 -1
  85. package/dist/services/agentSigner.js +13 -0
  86. package/dist/services/agentSigner.js.map +1 -1
  87. package/dist/types/hyperliquid-types.d.ts +9 -1
  88. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  89. package/dist/types/hyperliquid-types.js +10 -0
  90. package/dist/types/hyperliquid-types.js.map +1 -1
  91. package/dist/types/index.d.ts +434 -17
  92. package/dist/types/index.d.ts.map +1 -1
  93. package/dist/types/index.js.map +1 -1
  94. package/dist/utils/accountAggregation.d.ts +17 -0
  95. package/dist/utils/accountAggregation.d.ts.map +1 -1
  96. package/dist/utils/accountAggregation.js +21 -5
  97. package/dist/utils/accountAggregation.js.map +1 -1
  98. package/dist/utils/accountUtils.d.ts +31 -10
  99. package/dist/utils/accountUtils.d.ts.map +1 -1
  100. package/dist/utils/accountUtils.js +68 -28
  101. package/dist/utils/accountUtils.js.map +1 -1
  102. package/dist/utils/closeCalculations.d.ts +17 -4
  103. package/dist/utils/closeCalculations.d.ts.map +1 -1
  104. package/dist/utils/closeCalculations.js +23 -7
  105. package/dist/utils/closeCalculations.js.map +1 -1
  106. package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
  107. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  108. package/dist/utils/hyperLiquidAdapter.js +17 -1
  109. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  110. package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
  111. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  112. package/dist/utils/hyperLiquidPositionPreview.js +264 -29
  113. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  114. package/dist/utils/index.d.ts +4 -2
  115. package/dist/utils/index.d.ts.map +1 -1
  116. package/dist/utils/index.js +1 -0
  117. package/dist/utils/index.js.map +1 -1
  118. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  119. package/dist/utils/lighterAdapter.js +46 -9
  120. package/dist/utils/lighterAdapter.js.map +1 -1
  121. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  122. package/dist/utils/marketDataTransform.js +13 -8
  123. package/dist/utils/marketDataTransform.js.map +1 -1
  124. package/dist/utils/marketUtils.d.ts +1 -2
  125. package/dist/utils/marketUtils.d.ts.map +1 -1
  126. package/dist/utils/marketUtils.js +7 -17
  127. package/dist/utils/marketUtils.js.map +1 -1
  128. package/dist/utils/orderBookGrouping.d.ts +35 -5
  129. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  130. package/dist/utils/orderBookGrouping.js +62 -6
  131. package/dist/utils/orderBookGrouping.js.map +1 -1
  132. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  133. package/dist/utils/perpsClientCopy.js +4 -0
  134. package/dist/utils/perpsClientCopy.js.map +1 -1
  135. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
  136. package/dist/utils/perpsDiskPersistence.js +10 -0
  137. package/dist/utils/perpsDiskPersistence.js.map +1 -1
  138. package/dist/utils/perpsFormatters.d.ts +31 -0
  139. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  140. package/dist/utils/perpsFormatters.js +26 -0
  141. package/dist/utils/perpsFormatters.js.map +1 -1
  142. package/dist/utils/priceDeviation.d.ts +9 -6
  143. package/dist/utils/priceDeviation.d.ts.map +1 -1
  144. package/dist/utils/priceDeviation.js +17 -26
  145. package/dist/utils/priceDeviation.js.map +1 -1
  146. package/dist/utils/sortMarkets.d.ts +13 -5
  147. package/dist/utils/sortMarkets.d.ts.map +1 -1
  148. package/dist/utils/sortMarkets.js +60 -38
  149. package/dist/utils/sortMarkets.js.map +1 -1
  150. package/docs/architecture.md +54 -24
  151. package/docs/client-contract.md +52 -27
  152. package/docs/contracts/events.md +38 -32
  153. package/docs/contracts/feature-flags.md +4 -4
  154. package/docs/formatting.md +2 -0
  155. package/docs/venues/lighter/capabilities.md +18 -15
  156. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"lighterAdapter.js","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,qCAAqC,EACrC,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAyBvC,OAAO,EACL,gBAAgB,EAChB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,KAAa,EAAE,KAAa;IAC7D,MAAM,MAAM,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,GAAG,6BAA6B,IAAI,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,YAAY,CACnB,MAAc,EACd,UAAgC;IA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CAAC,KAAK,CAAC,MAAM,CAAC;QACtC,0EAA0E;QAC1E,qEAAqE;QACrE,SAAS,EACP,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS;QACnE,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;QACrC,UAAU,EAAE,SAAS;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Lighter API Adapter Utilities\n *\n * Adapters transforming zkLighter REST payloads into the MetaMask Perps API\n * canonical types. Portable: no mobile-specific imports; formatters are\n * injected via the MarketDataFormatters interface.\n *\n * Key differences from HyperLiquid:\n * - Prices/sizes are human-readable decimal strings in REST responses, but\n * integers scaled by `supported_*_decimals` on the signing path.\n * - Position side is a `sign` field (1 = long, -1 = short).\n * - USDC collateral, single margin mode per account in the POC (cross).\n */\n\nimport {\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MARGIN_MODE_ISOLATED,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketDataFormatters,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n PriceUpdate,\n PublicTrade,\n TriggerOrderType,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterOrderBookDetail,\n LighterOrderBookMeta,\n LighterRestTrade,\n LighterWsTrade,\n LighterSubAccount,\n LighterWsMarketStat,\n LighterWsUserStats,\n} from '../types/lighter-types.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\n\n/**\n * Parse an account-state number at the untrusted venue boundary. Account\n * balances feed trading availability and must never accept prefix parses or\n * propagate NaN/Infinity into canonical state.\n *\n * @param value - Raw venue decimal string.\n * @param field - Field identity for the integrity error.\n * @returns A finite, fully parsed number.\n */\nfunction parseStrictAccountDecimal(value: string, field: string): number {\n const parsed = parseLighterStrictDecimal(value);\n if (parsed === null || !Number.isFinite(parsed)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} ${field} '${String(value)}'`,\n );\n }\n return parsed;\n}\n\n/**\n * Format a price change value with sign prefix.\n *\n * @param change - The price change value to format.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns The formatted change string with sign and dollar symbol.\n */\nfunction formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change) || change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n\n// ============================================================================\n// Market Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter order book meta entry into canonical MarketInfo.\n *\n * @param market - Market metadata from `GET /api/v1/orderBooks`.\n * @param maxLeverage - Verified per-market leverage from margin metadata.\n * @returns MetaMask Perps API market info object.\n */\nexport function adaptMarketFromLighter(\n market: LighterOrderBookMeta,\n maxLeverage: number,\n): MarketInfo {\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n return {\n name: market.symbol,\n szDecimals: market.supportedSizeDecimals,\n priceDecimals: market.supportedPriceDecimals,\n maxLeverage,\n marginTableId: 0, // Lighter does not use margin tables\n minimumOrderSize: parseFloat(market.minQuoteAmount),\n providerId: 'lighter',\n ...(market.status === 'active' ? {} : { isDelisted: true as const }),\n };\n}\n\n/**\n * Transform a Lighter order book detail into UI-ready PerpsMarketData.\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns MetaMask Perps API market data object.\n */\nexport function adaptMarketDataFromLighter(\n detail: LighterOrderBookDetail,\n formatters: MarketDataFormatters,\n): PerpsMarketData {\n const { minInitialMarginFraction } = detail;\n if (\n !Number.isFinite(minInitialMarginFraction) ||\n minInitialMarginFraction === undefined ||\n minInitialMarginFraction <= 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${detail.symbol}`,\n );\n }\n const price = detail.lastTradePrice ?? 0;\n const changePercent = detail.dailyPriceChange ?? 0;\n // dailyPriceChange is a percentage; recover the absolute change.\n const changeAbs =\n changePercent === 0 ? 0 : (price * changePercent) / (100 + changePercent);\n\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid authoritative leverage for ${detail.symbol}`,\n );\n }\n return {\n symbol: detail.symbol,\n name: detail.symbol,\n maxLeverage: `${maxLeverage}x`,\n price: formatters.formatPerpsFiat(price, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: formatChange(changeAbs, formatters),\n change24hPercent: `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`,\n volume: formatters.formatVolume(detail.dailyQuoteTokenVolume ?? 0),\n openInterest: formatters.formatVolume(detail.openInterest ?? 0),\n };\n}\n\n/**\n * Transform a Lighter order book detail into a canonical PriceUpdate for\n * price-stream subscribers (REST polling stands in for a WS feed in the POC).\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighter(\n detail: LighterOrderBookDetail,\n timestamp: number,\n): PriceUpdate {\n return {\n symbol: detail.symbol,\n price: String(detail.lastTradePrice ?? 0),\n timestamp,\n percentChange24h: String(detail.dailyPriceChange ?? 0),\n volume24h: detail.dailyQuoteTokenVolume ?? 0,\n openInterest: detail.openInterest ?? 0,\n isTradable: detail.status === 'active',\n };\n}\n\n/**\n * Transform a `market_stats` WebSocket entry into a canonical PriceUpdate.\n * Richer than the REST fallback: carries mid/bid/ask, mark price, and funding.\n *\n * @param stat - Market stats entry from the `market_stats/all` WS channel.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighterWsStat(\n stat: LighterWsMarketStat,\n timestamp: number,\n): PriceUpdate {\n const bestBid = parseFloat(stat.bestBidPrice);\n const bestAsk = parseFloat(stat.bestAskPrice);\n const spread =\n Number.isFinite(bestBid) && Number.isFinite(bestAsk)\n ? String(bestAsk - bestBid)\n : undefined;\n return {\n symbol: stat.symbol,\n price: stat.midPrice,\n timestamp,\n percentChange24h: String(stat.dailyPriceChange ?? 0),\n bestBid: stat.bestBidPrice,\n bestAsk: stat.bestAskPrice,\n spread,\n markPrice: stat.markPrice,\n funding: parseFloat(stat.currentFundingRate ?? stat.fundingRate ?? '0'),\n openInterest: parseFloat(stat.openInterest ?? '0'),\n volume24h: stat.dailyQuoteTokenVolume ?? 0,\n isTradable: true,\n };\n}\n\n/**\n * Transform a `user_stats` WebSocket stats block into canonical AccountState.\n *\n * @param stats - Stats block from the `user_stats/{account_index}` channel.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighterUserStats(\n stats: LighterWsUserStats,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n stats.collateral,\n 'WebSocket collateral',\n );\n const available = parseStrictAccountDecimal(\n stats.availableBalance,\n 'WebSocket available balance',\n );\n const portfolioValue = parseStrictAccountDecimal(\n stats.portfolioValue,\n 'WebSocket portfolio value',\n );\n return {\n totalBalance: String(portfolioValue),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n // Lighter collateral is already the account value. There is no separate\n // spot USDC to add, and this read is a known account, so the amount is 0\n // rather than unknown.\n spotCollateral: '0',\n marginUsed: String(Math.max(collateral - available, 0)),\n unrealizedPnl: String(portfolioValue - collateral),\n returnOnEquity:\n collateral > 0\n ? String(((portfolioValue - collateral) / collateral) * 100)\n : '0',\n };\n}\n\n/**\n * Transform a Lighter trade (REST `/trades` or WS `account_all_trades`) into\n * a canonical OrderFill from the perspective of `accountIndex`.\n *\n * @param trade - Trade entry (post-camelization).\n * @param symbol - Market symbol resolved from the market id.\n * @param accountIndex - The account whose perspective determines the side.\n * @returns MetaMask Perps API order fill object.\n */\n/**\n * Derive the lifecycle direction of a fill from the venue's\n * position-before context, in the vocabulary client transforms consume\n * (`Open Long`, `Close Short`, `Long > Short`, ...).\n *\n * The venue reports the side's ABSOLUTE position size before the trade and\n * whether its sign changed. Combined with the trade side that is enough:\n * buying reduces shorts and opens longs; selling reduces longs and opens\n * shorts. A partial fill with no sign change is disambiguated by realized\n * pnl (closing realizes pnl, opening does not). Without position context\n * the side-only `Buy`/`Sell` vocabulary is used.\n *\n * @param context - Trade side, size, and position-before data.\n * @param context.isBuy - Whether our side bought.\n * @param context.size - Trade size (base units, absolute).\n * @param context.positionBefore - Our side's absolute position size before.\n * @param context.signChanged - Whether our side's position sign changed.\n * @param context.pnl - Realized pnl for our side, or undefined when omitted.\n * @returns Client-facing direction string.\n */\nexport function deriveLighterFillDirection(context: {\n isBuy: boolean;\n size: number;\n positionBefore: number;\n signChanged: boolean | undefined;\n pnl: number | undefined;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n // A flat baseline proves an open. On an existing position, nonzero\n // realized PnL proves reduction; otherwise an omitted flag is ambiguous.\n if (signChanged === undefined && (pnl === undefined || pnl === 0)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (\n signChanged ||\n (signChanged === undefined && pnl !== undefined && pnl !== 0)\n ) {\n // Crossed past zero → flipped; landed exactly on zero → full close.\n if (size > positionBefore * 1.000001) {\n return isBuy ? 'Short > Long' : 'Long > Short';\n }\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Partial fill on an existing position: realized pnl proves it reduced.\n if (pnl !== undefined && pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero or unknown pnl with no sign change is ambiguous from this\n // payload (a break-even partial close and an add both fit): fall back to\n // the side-only vocabulary instead of asserting Open without evidence.\n return isBuy ? 'Buy' : 'Sell';\n}\n\n/**\n * Parse one optional venue fee without treating malformed supplied values as\n * an omitted zero.\n *\n * @param value - Raw maker or taker fee.\n * @param tradeId - Trade identity for error context.\n * @param role - Fee role for error context.\n * @returns The finite nonnegative fee, with undefined mapped to venue-zero.\n */\nfunction parseLighterTradeFee(\n value: unknown,\n tradeId: number,\n role: 'maker' | 'taker',\n): number {\n let parsed: number | null;\n if (value === undefined) {\n parsed = 0;\n } else if (typeof value === 'number') {\n parsed = value;\n } else if (typeof value === 'string') {\n parsed = parseLighterStrictDecimal(value);\n } else {\n parsed = null;\n }\n if (parsed === null || !Number.isFinite(parsed) || parsed < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${tradeId} has invalid ${role} fee`,\n );\n }\n return parsed;\n}\n\n/**\n * Adapt Lighter public trades (REST `recentTrades` or the `trade/{market_id}`\n * channel, camelized) to {@link PublicTrade}, newest first. Trades for\n * another market and malformed trades are dropped. A maker ask means the\n * taker (aggressor) bought.\n *\n * @param trades - Camelized venue trades.\n * @param marketId - Requested market; other markets are dropped.\n * @param symbol - Symbol to stamp on each trade.\n * @returns The trades for the market, newest first.\n */\nexport function adaptPublicTradesFromLighter(\n trades: readonly unknown[],\n marketId: number,\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const raw of trades) {\n if (raw === null || typeof raw !== 'object') {\n continue;\n }\n const trade = raw as Partial<Record<string, unknown>>;\n if (trade.marketId !== marketId || typeof trade.isMakerAsk !== 'boolean') {\n continue;\n }\n let id: string | undefined;\n if (typeof trade.tradeIdStr === 'string') {\n id = trade.tradeIdStr;\n } else if (\n typeof trade.tradeId === 'number' &&\n Number.isSafeInteger(trade.tradeId) &&\n trade.tradeId >= 0\n ) {\n id = String(trade.tradeId);\n }\n const publicTrade = buildPublicTrade({\n id,\n symbol,\n price: trade.price,\n size: trade.size,\n side: trade.isMakerAsk ? 'buy' : 'sell',\n timestamp: trade.timestamp,\n txHash: typeof trade.txHash === 'string' ? trade.txHash : undefined,\n providerId: 'lighter',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\n}\n\nexport function adaptFillFromLighterTrade(\n trade: LighterRestTrade | LighterWsTrade,\n symbol: string,\n accountIndex: number,\n): OrderFill {\n const identifiers = [\n ['trade id', trade.tradeId],\n ['market id', trade.marketId],\n ['ask id', trade.askId],\n ['bid id', trade.bidId],\n ['ask account id', trade.askAccountId],\n ['bid account id', trade.bidAccountId],\n ] as const;\n for (const [field, value] of identifiers) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${String(trade.tradeId)} has invalid ${field}`,\n );\n }\n }\n const accountIsAsk = trade.askAccountId === accountIndex;\n const accountIsBid = trade.bidAccountId === accountIndex;\n if (accountIsAsk === accountIsBid) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} account ${accountIndex} is not an unambiguous participant in trade ${trade.tradeId}`,\n );\n }\n const size = parseLighterStrictDecimal(trade.size);\n const price = parseLighterStrictDecimal(trade.price);\n if (size === null || !Number.isFinite(size) || size <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid size`,\n );\n }\n if (price === null || !Number.isFinite(price) || price <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid price`,\n );\n }\n if (!Number.isSafeInteger(trade.timestamp) || trade.timestamp < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid timestamp`,\n );\n }\n if (typeof trade.isMakerAsk !== 'boolean') {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing maker-role context`,\n );\n }\n // Our side's role decides which fee applies; the venue includes the fee\n // fields only when nonzero (zero is the current standard-account truth).\n const accountIsMaker = accountIsAsk === trade.isMakerAsk;\n // Standard accounts (the only supported type — the provider gates\n // Premium at account resolution) pay zero fees, so zero is venue truth.\n // A PRESENT nonzero fee ON OUR SIDE contradicts that gate and its wire\n // unit is unverified: refusing loudly beats silently coercing a real fee\n // to $0. A valid nonzero counterparty fee is allowed, but malformed\n // supplied counterparty data still invalidates the venue row.\n const makerFee = parseLighterTradeFee(trade.makerFee, trade.tradeId, 'maker');\n const takerFee = parseLighterTradeFee(trade.takerFee, trade.tradeId, 'taker');\n const ourFeeNumeric = accountIsMaker ? makerFee : takerFee;\n if (ourFeeNumeric !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} nonzero fee in trade ${trade.tradeId}: fee unit is unverified`,\n );\n }\n const fee = '0';\n const isBuy = !accountIsAsk;\n // The account's maker/taker role selects the matching pre-trade position\n // context. Omitted sign-change flags retain an unknown direction for\n // existing positions; malformed supplied context still fails closed.\n const positionBeforeRaw = accountIsMaker\n ? trade.makerPositionSizeBefore\n : trade.takerPositionSizeBefore;\n const positionBefore = parseLighterStrictDecimal(positionBeforeRaw);\n const signChanged = accountIsMaker\n ? trade.makerPositionSignChanged\n : trade.takerPositionSignChanged;\n if (\n positionBefore === null ||\n !Number.isFinite(positionBefore) ||\n positionBefore < 0 ||\n (signChanged !== undefined && typeof signChanged !== 'boolean')\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid position context`,\n );\n }\n const pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n // Omitted amounts remain unknown, including closes and flips. Position\n // context can establish direction without establishing the realized amount.\n const parsedPnl =\n pnl === undefined ? undefined : parseLighterStrictDecimal(pnl);\n if (\n parsedPnl === null ||\n (pnl !== undefined &&\n (typeof pnl !== 'string' || !Number.isFinite(parsedPnl)))\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`,\n );\n }\n const direction = deriveLighterFillDirection({\n isBuy,\n size,\n positionBefore,\n signChanged,\n pnl: parsedPnl,\n });\n // Signed pre-trade position, derivable whenever the direction proved the\n // orientation: closing/flipping a long means it was +before, a short\n // -before; opens start from zero. Clients size flip displays from this.\n let startPosition: string | undefined;\n if (direction.startsWith('Open')) {\n startPosition = '0';\n } else if (direction === 'Close Long' || direction === 'Long > Short') {\n startPosition = String(positionBefore);\n } else if (direction === 'Close Short' || direction === 'Short > Long') {\n startPosition = String(-positionBefore);\n }\n return {\n orderId: String(accountIsAsk ? trade.askId : trade.bidId),\n // Lighter's unique execution id, validated as a safe non-negative\n // integer above. Order id alone cannot separate two fills of one order.\n fillId: String(trade.tradeId),\n symbol,\n side: accountIsAsk ? 'sell' : 'buy',\n size: trade.size,\n price: trade.price,\n // The venue reports realized pnl per side of the trade.\n ...(pnl === undefined ? {} : { pnl }),\n direction,\n ...(startPosition === undefined ? {} : { startPosition }),\n fee,\n feeToken: 'USDC',\n timestamp: trade.timestamp,\n // Lets clients apply venue-specific presentation rules (e.g. the\n // ambiguous side-only vocabulary) without guessing the source.\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Position Transformation\n// ============================================================================\n\n/**\n * Margin a Lighter position uses: its value times the initial margin\n * fraction, a percentage (e.g. \"20\" => 5x leverage).\n *\n * @param positionValue - Position value in USDC.\n * @param initialMarginFraction - Initial margin fraction, in percent.\n * @returns Margin used in USDC, or undefined without a positive fraction.\n */\nfunction deriveLighterPositionMarginUsed(\n positionValue: number,\n initialMarginFraction: number,\n): number | undefined {\n return Number.isFinite(initialMarginFraction) && initialMarginFraction > 0\n ? (positionValue * initialMarginFraction) / 100\n : undefined;\n}\n\n/**\n * Transform a Lighter account position into canonical Position.\n *\n * @param position - Position entry from an account payload.\n * @param maxLeverage - Per-market max leverage (venue margin fractions).\n * @returns MetaMask Perps API position object.\n */\nexport function adaptPositionFromLighter(\n position: LighterApiPosition,\n maxLeverage: number = LIGHTER_MAX_LEVERAGE,\n): Position {\n // Venue-input integrity boundary: the REST layer type-casts JSON without\n // runtime validation, and a prefix-parsed '0.1oops' would become a\n // canonical '0.1' that TP/SL cover-sizing and close paths then SIGN.\n // The documented representation is a NONNEGATIVE magnitude with sign\n // exactly 1 or -1: a negative magnitude with sign 1 would flip the\n // canonical direction and make close/TPSL act opposite the real\n // position; sign 0/2/'1' would be silently coerced by a > 0 ternary.\n const magnitude = parseLighterStrictDecimal(position.position);\n if (magnitude === null || !Number.isFinite(magnitude) || magnitude < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position size '${position.position}' for ${position.symbol}`,\n );\n }\n // The documented contract is sign EXACTLY 1 or -1, including for flat\n // positions (zero magnitudes are filtered downstream); anything else is\n // malformed venue data, never something to coerce.\n if (position.sign !== 1 && position.sign !== -1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position sign '${String(position.sign)}' for ${position.symbol}`,\n );\n }\n const size = magnitude * position.sign;\n // Malformed values must not turn into NaN margin or RoE.\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n const marginFraction =\n parseLighterStrictDecimal(position.initialMarginFraction) ?? Number.NaN;\n // initialMarginFraction is a percentage (e.g. \"20\" => 5x leverage).\n // Without a usable fraction leverage, margin and RoE are unknown, not 1x.\n const derivedMargin = deriveLighterPositionMarginUsed(\n positionValue,\n marginFraction,\n );\n if (derivedMargin === undefined && size !== 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} initial margin fraction '${String(position.initialMarginFraction)}' for open position ${position.symbol}`,\n );\n }\n const leverageValue =\n derivedMargin === undefined ? undefined : Math.round(100 / marginFraction);\n // A flat row (filtered downstream) uses no margin.\n const marginUsed = derivedMargin ?? 0;\n const liquidationPrice = parseFloat(position.liquidationPrice);\n\n return {\n symbol: position.symbol,\n size: String(size),\n entryPrice: position.avgEntryPrice,\n positionValue: position.positionValue,\n unrealizedPnl: position.unrealizedPnl,\n marginUsed: String(marginUsed),\n leverage: {\n // Older venue captures omit marginMode and therefore retain the\n // historical cross default. Current payloads use 1 for isolated.\n type: position.marginMode === 1 ? 'isolated' : 'cross',\n value: leverageValue,\n },\n liquidationPrice:\n isNaN(liquidationPrice) || liquidationPrice === 0\n ? null\n : position.liquidationPrice,\n maxLeverage,\n // A fraction (0.1 = 10%), the unit Hyperliquid positions use.\n returnOnEquity: marginUsed > 0 ? String(unrealizedPnl / marginUsed) : '0',\n // The account payload carries no funding, so cumulativeFunding is\n // omitted (unknown) rather than reported as zero.\n takeProfitCount: 0,\n stopLossCount: 0,\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Account Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter sub-account into canonical AccountState.\n *\n * @param account - Sub-account payload from `account`/`accountsByL1Address`.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighter(\n account: LighterSubAccount,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n account.collateral,\n 'REST collateral',\n );\n const available = parseStrictAccountDecimal(\n account.availableBalance,\n 'REST available balance',\n );\n const { positions } = account;\n if (!positions) {\n // Without positions, unrealized PnL and the total balance are unknown.\n throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} REST positions missing`);\n }\n const unrealizedPnl = positions.reduce(\n (sum, position) =>\n sum +\n parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n ),\n 0,\n );\n const marginUsed = Math.max(collateral - available, 0);\n const totalBalance = collateral + unrealizedPnl;\n\n return {\n totalBalance: String(totalBalance),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n // Lighter collateral is already the account value. There is no separate\n // spot USDC to add, and this read is a known account, so the amount is 0\n // rather than unknown.\n spotCollateral: '0',\n marginUsed: String(marginUsed),\n unrealizedPnl: String(unrealizedPnl),\n returnOnEquity:\n marginUsed > 0 ? String((unrealizedPnl / marginUsed) * 100) : '0',\n providerId: 'lighter',\n };\n}\n\n/**\n * Build the cross-margin summary from a Lighter sub-account's positions.\n *\n * Open cross positions contribute their value to notional, their margin to\n * margin used and value times the market's maintenance fraction to\n * maintenance margin. Account value is the total balance less isolated\n * positions' unrealized PnL.\n *\n * @param account - Sub-account payload from `account`.\n * @param totalBalance - The account's adapted total balance.\n * @param getMaintenanceFraction - Maintenance margin fraction (0.024 = 2.4%)\n * for a market symbol, or undefined when the market has none.\n * @returns The cross-margin summary, or undefined when the payload omits\n * positions or an open cross position has no maintenance or initial margin\n * fraction.\n */\nexport function adaptCrossMarginSummaryFromLighter(\n account: LighterSubAccount,\n totalBalance: string,\n getMaintenanceFraction: (symbol: string) => number | undefined,\n): CrossMarginSummary | undefined {\n // Omitted positions are not evidence of zero exposure.\n if (!account.positions) {\n return undefined;\n }\n let isolatedUnrealizedPnl = 0;\n let notional = 0;\n let marginUsed = 0;\n let maintenanceMargin = 0;\n for (const position of account.positions) {\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n if (position.marginMode === LIGHTER_MARGIN_MODE_ISOLATED) {\n isolatedUnrealizedPnl += unrealizedPnl;\n continue;\n }\n const size = parseStrictAccountDecimal(\n position.position,\n `REST position size for ${position.symbol}`,\n );\n if (size === 0) {\n continue;\n }\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n if (position.initialMarginFraction === undefined) {\n return undefined;\n }\n const initialMarginFraction = parseStrictAccountDecimal(\n position.initialMarginFraction,\n `REST initial margin fraction for ${position.symbol}`,\n );\n const maintenanceFraction = getMaintenanceFraction(position.symbol);\n if (maintenanceFraction === undefined) {\n return undefined;\n }\n const positionMargin = deriveLighterPositionMarginUsed(\n positionValue,\n initialMarginFraction,\n );\n if (positionMargin === undefined) {\n return undefined;\n }\n notional += positionValue;\n marginUsed += positionMargin;\n maintenanceMargin += positionValue * maintenanceFraction;\n }\n return {\n accountValue: String(\n parseStrictAccountDecimal(totalBalance, 'total balance') -\n isolatedUnrealizedPnl,\n ),\n maintenanceMargin: String(maintenanceMargin),\n marginUsed: String(marginUsed),\n notional: String(notional),\n };\n}\n\n// ============================================================================\n// Order Transformation\n// ============================================================================\n\n/**\n * Map a Lighter order status string onto the canonical status union.\n *\n * @param status - Raw status from the Lighter API.\n * @returns Canonical order status.\n */\nexport function adaptOrderStatus(status: string): Order['status'] {\n switch (status) {\n case 'open':\n case 'pending':\n case 'in-progress':\n return 'open';\n case 'filled':\n return 'filled';\n case 'canceled':\n case 'cancelled':\n case 'canceled-post-only':\n case 'canceled-reduce-only':\n case 'canceled-position-not-allowed':\n case 'canceled-margin-not-allowed':\n case 'canceled-too-much-slippage':\n case 'canceled-not-enough-liquidity':\n case 'canceled-self-trade':\n case 'canceled-expired':\n case 'canceled-oco':\n case 'canceled-child':\n case 'canceled-liquidation':\n case 'canceled-invalid-balance':\n return 'canceled';\n default:\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown order status '${status}'`,\n );\n }\n}\n\n/**\n * Transform a Lighter active order into canonical Order.\n *\n * @param order - Order entry from `GET /api/v1/accountActiveOrders`.\n * @param symbol - Market symbol for the order's `marketIndex`.\n * @returns MetaMask Perps API order object.\n */\nexport function adaptOrderFromLighter(\n order: LighterApiOrder,\n symbol: string,\n): Order {\n const original = parseFloat(order.initialBaseAmount);\n const remaining = parseFloat(order.remainingBaseAmount);\n // Canceled orders have zero remaining size even when nothing filled.\n const filled =\n order.filledBaseAmount === undefined\n ? Math.max(original - remaining, 0)\n : parseFloat(order.filledBaseAmount);\n\n const isTrigger = !['market', 'limit'].includes(order.type);\n const triggerPrice =\n order.triggerPrice !== undefined && parseFloat(order.triggerPrice) > 0\n ? order.triggerPrice\n : undefined;\n // Semantic trigger typing: without it, a TP/SL renders as a generic\n // Limit order in clients. Venue trigger orders execute market-on-trigger\n // (IOC with a protection price), the -limit variants rest at a price.\n const triggerTypeMeta: Record<\n string,\n {\n orderType: 'market' | 'limit';\n triggerOrderType: TriggerOrderType;\n detailed: string;\n }\n > = {\n 'take-profit': {\n orderType: 'market',\n triggerOrderType: 'take_profit_market',\n detailed: 'Take Profit Market',\n },\n 'stop-loss': {\n orderType: 'market',\n triggerOrderType: 'stop_market',\n detailed: 'Stop Market',\n },\n 'take-profit-limit': {\n orderType: 'limit',\n triggerOrderType: 'take_profit_limit',\n detailed: 'Take Profit Limit',\n },\n 'stop-loss-limit': {\n orderType: 'limit',\n triggerOrderType: 'stop_limit',\n detailed: 'Stop Limit',\n },\n };\n const triggerMeta = triggerTypeMeta[order.type];\n\n return {\n orderId: String(order.orderIndex),\n symbol,\n side: order.isAsk ? 'sell' : 'buy',\n orderType:\n triggerMeta?.orderType ?? (order.type === 'market' ? 'market' : 'limit'),\n ...(triggerMeta\n ? {\n triggerOrderType: triggerMeta.triggerOrderType,\n detailedOrderType: triggerMeta.detailed,\n }\n : {}),\n isTrigger,\n size: order.remainingBaseAmount,\n originalSize: order.initialBaseAmount,\n // On trigger orders `price` is the ±5% protection EXECUTION price;\n // the user-facing TP/SL level is `triggerPrice`.\n price: order.price,\n ...(triggerPrice === undefined ? {} : { triggerPrice }),\n filledSize: String(filled),\n remainingSize: order.remainingBaseAmount,\n status: adaptOrderStatus(order.status),\n // Order endpoints report seconds; preserve already-normalized millisecond\n // inputs. Trade timestamps are a separate millisecond wire contract.\n timestamp:\n order.timestamp < 1e12 ? order.timestamp * 1000 : order.timestamp,\n reduceOnly: Boolean(order.reduceOnly),\n providerId: 'lighter',\n };\n}\n"]}
1
+ {"version":3,"file":"lighterAdapter.js","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,qCAAqC,EACrC,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAyB9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EACL,gBAAgB,EAChB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,KAAa,EAAE,KAAa;IAC7D,MAAM,MAAM,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,GAAG,6BAA6B,IAAI,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,YAAY,CACnB,MAAc,EACd,UAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC;QACvD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;QAC7D,MAAM,EAAE,UAAU,CAAC,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CAAC,IAAI,CAAC,CAAC;IAEhD,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;QACjC,MAAM;QACN,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK;QAClC,SAAS,EACP,WAAW,EAAE,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1E,GAAG,CAAC,WAAW;YACb,CAAC,CAAC;gBACE,gBAAgB,EAAE,WAAW,CAAC,gBAAgB;gBAC9C,iBAAiB,EAAE,WAAW,CAAC,QAAQ;aACxC;YACH,CAAC,CAAC,EAAE,CAAC;QACP,SAAS;QACT,IAAI,EAAE,KAAK,CAAC,mBAAmB;QAC/B,YAAY,EAAE,KAAK,CAAC,iBAAiB;QACrC,mEAAmE;QACnE,iDAAiD;QACjD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,GAAG,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC;QACvD,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1B,aAAa,EAAE,KAAK,CAAC,mBAAmB;QACxC,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC;QACtC,0EAA0E;QAC1E,qEAAqE;QACrE,SAAS,EACP,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS;QACnE,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;QACrC,UAAU,EAAE,SAAS;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Lighter API Adapter Utilities\n *\n * Adapters transforming zkLighter REST payloads into the MetaMask Perps API\n * canonical types. Portable: no mobile-specific imports; formatters are\n * injected via the MarketDataFormatters interface.\n *\n * Key differences from HyperLiquid:\n * - Prices/sizes are human-readable decimal strings in REST responses, but\n * integers scaled by `supported_*_decimals` on the signing path.\n * - Position side is a `sign` field (1 = long, -1 = short).\n * - USDC collateral, single margin mode per account in the POC (cross).\n */\n\nimport {\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MARGIN_MODE_ISOLATED,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport { accountReturnOnEquity } from '../internal/accountReturnOnEquity.js';\nimport { buildMarketNumericValues } from '../internal/marketNumericValues.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketDataFormatters,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n PriceUpdate,\n PublicTrade,\n TriggerOrderType,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterOrderBookDetail,\n LighterOrderBookMeta,\n LighterRestTrade,\n LighterWsTrade,\n LighterSubAccount,\n LighterWsMarketStat,\n LighterWsUserStats,\n} from '../types/lighter-types.js';\nimport { calculateOpenInterestUSD } from './marketDataTransform.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\n\n/**\n * Parse an account-state number at the untrusted venue boundary. Account\n * balances feed trading availability and must never accept prefix parses or\n * propagate NaN/Infinity into canonical state.\n *\n * @param value - Raw venue decimal string.\n * @param field - Field identity for the integrity error.\n * @returns A finite, fully parsed number.\n */\nfunction parseStrictAccountDecimal(value: string, field: string): number {\n const parsed = parseLighterStrictDecimal(value);\n if (parsed === null || !Number.isFinite(parsed)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} ${field} '${String(value)}'`,\n );\n }\n return parsed;\n}\n\n/**\n * Format a price change value with sign prefix.\n *\n * @param change - The price change value to format.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns The formatted change string with sign and dollar symbol.\n */\nfunction formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change) || change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n\n// ============================================================================\n// Market Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter order book meta entry into canonical MarketInfo.\n *\n * @param market - Market metadata from `GET /api/v1/orderBooks`.\n * @param maxLeverage - Verified per-market leverage from margin metadata.\n * @returns MetaMask Perps API market info object.\n */\nexport function adaptMarketFromLighter(\n market: LighterOrderBookMeta,\n maxLeverage: number,\n): MarketInfo {\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n return {\n name: market.symbol,\n szDecimals: market.supportedSizeDecimals,\n priceDecimals: market.supportedPriceDecimals,\n maxLeverage,\n marginTableId: 0, // Lighter does not use margin tables\n minimumOrderSize: parseFloat(market.minQuoteAmount),\n providerId: 'lighter',\n ...(market.status === 'active' ? {} : { isDelisted: true as const }),\n };\n}\n\n/**\n * Lighter reports open interest in base units; convert it to USD with\n * `calculateOpenInterestUSD`, as Hyperliquid does.\n *\n * @param baseAmount - Open interest in base units.\n * @param price - Price to convert at.\n * @returns Open interest in USD, or undefined without a positive price or a\n * finite amount.\n */\nfunction toUsdOpenInterest(\n baseAmount: number | undefined,\n price: number,\n): number | undefined {\n if (!(price > 0)) {\n return undefined;\n }\n const usd = calculateOpenInterestUSD(baseAmount, price);\n return Number.isFinite(usd) ? usd : undefined;\n}\n\n/**\n * Transform a Lighter order book detail into UI-ready PerpsMarketData.\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns MetaMask Perps API market data object.\n */\nexport function adaptMarketDataFromLighter(\n detail: LighterOrderBookDetail,\n formatters: MarketDataFormatters,\n): PerpsMarketData {\n const { minInitialMarginFraction } = detail;\n if (\n !Number.isFinite(minInitialMarginFraction) ||\n minInitialMarginFraction === undefined ||\n minInitialMarginFraction <= 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${detail.symbol}`,\n );\n }\n const price = detail.lastTradePrice ?? 0;\n const changePercent = detail.dailyPriceChange ?? 0;\n // dailyPriceChange is a percentage; recover the absolute change.\n const changeAbs =\n changePercent === 0 ? 0 : (price * changePercent) / (100 + changePercent);\n\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid authoritative leverage for ${detail.symbol}`,\n );\n }\n // The detail has no mark price, so convert at the last trade price.\n const openInterestUsd = toUsdOpenInterest(detail.openInterest, price);\n return {\n symbol: detail.symbol,\n name: detail.symbol,\n maxLeverage: `${maxLeverage}x`,\n price: formatters.formatPerpsFiat(price, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: formatChange(changeAbs, formatters),\n change24hPercent: `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`,\n volume: formatters.formatVolume(detail.dailyQuoteTokenVolume ?? 0),\n openInterest:\n openInterestUsd === undefined\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(openInterestUsd),\n numericValues: buildMarketNumericValues({\n price: detail.lastTradePrice,\n change24hPercent: detail.dailyPriceChange,\n volume: detail.dailyQuoteTokenVolume,\n openInterest: openInterestUsd,\n }),\n };\n}\n\n/**\n * Transform a Lighter order book detail into a canonical PriceUpdate for\n * price-stream subscribers (REST polling stands in for a WS feed in the POC).\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighter(\n detail: LighterOrderBookDetail,\n timestamp: number,\n): PriceUpdate {\n // The detail has no mark price, so convert at the last trade price.\n const openInterest = toUsdOpenInterest(\n detail.openInterest,\n detail.lastTradePrice,\n );\n return {\n symbol: detail.symbol,\n price: String(detail.lastTradePrice ?? 0),\n timestamp,\n percentChange24h: String(detail.dailyPriceChange ?? 0),\n volume24h: detail.dailyQuoteTokenVolume ?? 0,\n ...(openInterest !== undefined && { openInterest }),\n isTradable: detail.status === 'active',\n };\n}\n\n/**\n * Transform a `market_stats` WebSocket entry into a canonical PriceUpdate.\n * Richer than the REST fallback: carries mid/bid/ask, mark price, and funding.\n *\n * @param stat - Market stats entry from the `market_stats/all` WS channel.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighterWsStat(\n stat: LighterWsMarketStat,\n timestamp: number,\n): PriceUpdate {\n const bestBid = parseFloat(stat.bestBidPrice);\n const bestAsk = parseFloat(stat.bestAskPrice);\n const spread =\n Number.isFinite(bestBid) && Number.isFinite(bestAsk)\n ? String(bestAsk - bestBid)\n : undefined;\n const markPrice = parseFloat(stat.markPrice);\n const openInterest = toUsdOpenInterest(\n parseFloat(stat.openInterest),\n markPrice > 0 ? markPrice : parseFloat(stat.lastTradePrice),\n );\n return {\n symbol: stat.symbol,\n price: stat.midPrice,\n timestamp,\n percentChange24h: String(stat.dailyPriceChange ?? 0),\n bestBid: stat.bestBidPrice,\n bestAsk: stat.bestAskPrice,\n spread,\n markPrice: stat.markPrice,\n oraclePrice: stat.indexPrice,\n funding: parseFloat(stat.currentFundingRate ?? stat.fundingRate ?? '0'),\n ...(openInterest !== undefined && { openInterest }),\n volume24h: stat.dailyQuoteTokenVolume ?? 0,\n isTradable: true,\n };\n}\n\n/**\n * Transform a `user_stats` WebSocket stats block into canonical AccountState.\n *\n * @param stats - Stats block from the `user_stats/{account_index}` channel.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighterUserStats(\n stats: LighterWsUserStats,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n stats.collateral,\n 'WebSocket collateral',\n );\n const available = parseStrictAccountDecimal(\n stats.availableBalance,\n 'WebSocket available balance',\n );\n const portfolioValue = parseStrictAccountDecimal(\n stats.portfolioValue,\n 'WebSocket portfolio value',\n );\n const marginUsed = Math.max(collateral - available, 0);\n const unrealizedPnl = portfolioValue - collateral;\n return {\n totalBalance: String(portfolioValue),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n // Lighter collateral is already the account value. There is no separate\n // spot USDC to add, and this read is a known account, so the amount is 0\n // rather than unknown.\n spotCollateral: '0',\n marginUsed: String(marginUsed),\n unrealizedPnl: String(unrealizedPnl),\n // Same rate as the REST account state: '0' only when no margin is used.\n returnOnEquity: String(\n accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber() ?? 0,\n ),\n };\n}\n\n/**\n * Transform a Lighter trade (REST `/trades` or WS `account_all_trades`) into\n * a canonical OrderFill from the perspective of `accountIndex`.\n *\n * @param trade - Trade entry (post-camelization).\n * @param symbol - Market symbol resolved from the market id.\n * @param accountIndex - The account whose perspective determines the side.\n * @returns MetaMask Perps API order fill object.\n */\n/**\n * Derive the lifecycle direction of a fill from the venue's\n * position-before context, in the vocabulary client transforms consume\n * (`Open Long`, `Close Short`, `Long > Short`, ...).\n *\n * The venue reports the side's ABSOLUTE position size before the trade and\n * whether its sign changed. Combined with the trade side that is enough:\n * buying reduces shorts and opens longs; selling reduces longs and opens\n * shorts. A partial fill with no sign change is disambiguated by realized\n * pnl (closing realizes pnl, opening does not). Without position context\n * the side-only `Buy`/`Sell` vocabulary is used.\n *\n * @param context - Trade side, size, and position-before data.\n * @param context.isBuy - Whether our side bought.\n * @param context.size - Trade size (base units, absolute).\n * @param context.positionBefore - Our side's absolute position size before.\n * @param context.signChanged - Whether our side's position sign changed.\n * @param context.pnl - Realized pnl for our side, or undefined when omitted.\n * @returns Client-facing direction string.\n */\nexport function deriveLighterFillDirection(context: {\n isBuy: boolean;\n size: number;\n positionBefore: number;\n signChanged: boolean | undefined;\n pnl: number | undefined;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n // A flat baseline proves an open. On an existing position, nonzero\n // realized PnL proves reduction; otherwise an omitted flag is ambiguous.\n if (signChanged === undefined && (pnl === undefined || pnl === 0)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (\n signChanged ||\n (signChanged === undefined && pnl !== undefined && pnl !== 0)\n ) {\n // Crossed past zero → flipped; landed exactly on zero → full close.\n if (size > positionBefore * 1.000001) {\n return isBuy ? 'Short > Long' : 'Long > Short';\n }\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Partial fill on an existing position: realized pnl proves it reduced.\n if (pnl !== undefined && pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero or unknown pnl with no sign change is ambiguous from this\n // payload (a break-even partial close and an add both fit): fall back to\n // the side-only vocabulary instead of asserting Open without evidence.\n return isBuy ? 'Buy' : 'Sell';\n}\n\n/**\n * Parse one optional venue fee without treating malformed supplied values as\n * an omitted zero.\n *\n * @param value - Raw maker or taker fee.\n * @param tradeId - Trade identity for error context.\n * @param role - Fee role for error context.\n * @returns The finite nonnegative fee, with undefined mapped to venue-zero.\n */\nfunction parseLighterTradeFee(\n value: unknown,\n tradeId: number,\n role: 'maker' | 'taker',\n): number {\n let parsed: number | null;\n if (value === undefined) {\n parsed = 0;\n } else if (typeof value === 'number') {\n parsed = value;\n } else if (typeof value === 'string') {\n parsed = parseLighterStrictDecimal(value);\n } else {\n parsed = null;\n }\n if (parsed === null || !Number.isFinite(parsed) || parsed < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${tradeId} has invalid ${role} fee`,\n );\n }\n return parsed;\n}\n\n/**\n * Adapt Lighter public trades (REST `recentTrades` or the `trade/{market_id}`\n * channel, camelized) to {@link PublicTrade}, newest first. Trades for\n * another market and malformed trades are dropped. A maker ask means the\n * taker (aggressor) bought.\n *\n * @param trades - Camelized venue trades.\n * @param marketId - Requested market; other markets are dropped.\n * @param symbol - Symbol to stamp on each trade.\n * @returns The trades for the market, newest first.\n */\nexport function adaptPublicTradesFromLighter(\n trades: readonly unknown[],\n marketId: number,\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const raw of trades) {\n if (raw === null || typeof raw !== 'object') {\n continue;\n }\n const trade = raw as Partial<Record<string, unknown>>;\n if (trade.marketId !== marketId || typeof trade.isMakerAsk !== 'boolean') {\n continue;\n }\n let id: string | undefined;\n if (typeof trade.tradeIdStr === 'string') {\n id = trade.tradeIdStr;\n } else if (\n typeof trade.tradeId === 'number' &&\n Number.isSafeInteger(trade.tradeId) &&\n trade.tradeId >= 0\n ) {\n id = String(trade.tradeId);\n }\n const publicTrade = buildPublicTrade({\n id,\n symbol,\n price: trade.price,\n size: trade.size,\n side: trade.isMakerAsk ? 'buy' : 'sell',\n timestamp: trade.timestamp,\n txHash: typeof trade.txHash === 'string' ? trade.txHash : undefined,\n providerId: 'lighter',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\n}\n\nexport function adaptFillFromLighterTrade(\n trade: LighterRestTrade | LighterWsTrade,\n symbol: string,\n accountIndex: number,\n): OrderFill {\n const identifiers = [\n ['trade id', trade.tradeId],\n ['market id', trade.marketId],\n ['ask id', trade.askId],\n ['bid id', trade.bidId],\n ['ask account id', trade.askAccountId],\n ['bid account id', trade.bidAccountId],\n ] as const;\n for (const [field, value] of identifiers) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${String(trade.tradeId)} has invalid ${field}`,\n );\n }\n }\n const accountIsAsk = trade.askAccountId === accountIndex;\n const accountIsBid = trade.bidAccountId === accountIndex;\n if (accountIsAsk === accountIsBid) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} account ${accountIndex} is not an unambiguous participant in trade ${trade.tradeId}`,\n );\n }\n const size = parseLighterStrictDecimal(trade.size);\n const price = parseLighterStrictDecimal(trade.price);\n if (size === null || !Number.isFinite(size) || size <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid size`,\n );\n }\n if (price === null || !Number.isFinite(price) || price <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid price`,\n );\n }\n if (!Number.isSafeInteger(trade.timestamp) || trade.timestamp < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid timestamp`,\n );\n }\n if (typeof trade.isMakerAsk !== 'boolean') {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing maker-role context`,\n );\n }\n // Our side's role decides which fee applies; the venue includes the fee\n // fields only when nonzero (zero is the current standard-account truth).\n const accountIsMaker = accountIsAsk === trade.isMakerAsk;\n // Standard accounts (the only supported type — the provider gates\n // Premium at account resolution) pay zero fees, so zero is venue truth.\n // A PRESENT nonzero fee ON OUR SIDE contradicts that gate and its wire\n // unit is unverified: refusing loudly beats silently coercing a real fee\n // to $0. A valid nonzero counterparty fee is allowed, but malformed\n // supplied counterparty data still invalidates the venue row.\n const makerFee = parseLighterTradeFee(trade.makerFee, trade.tradeId, 'maker');\n const takerFee = parseLighterTradeFee(trade.takerFee, trade.tradeId, 'taker');\n const ourFeeNumeric = accountIsMaker ? makerFee : takerFee;\n if (ourFeeNumeric !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} nonzero fee in trade ${trade.tradeId}: fee unit is unverified`,\n );\n }\n const fee = '0';\n const isBuy = !accountIsAsk;\n // The account's maker/taker role selects the matching pre-trade position\n // context. Omitted sign-change flags retain an unknown direction for\n // existing positions; malformed supplied context still fails closed.\n const positionBeforeRaw = accountIsMaker\n ? trade.makerPositionSizeBefore\n : trade.takerPositionSizeBefore;\n const positionBefore = parseLighterStrictDecimal(positionBeforeRaw);\n const signChanged = accountIsMaker\n ? trade.makerPositionSignChanged\n : trade.takerPositionSignChanged;\n if (\n positionBefore === null ||\n !Number.isFinite(positionBefore) ||\n positionBefore < 0 ||\n (signChanged !== undefined && typeof signChanged !== 'boolean')\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid position context`,\n );\n }\n const pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n // Omitted amounts remain unknown, including closes and flips. Position\n // context can establish direction without establishing the realized amount.\n const parsedPnl =\n pnl === undefined ? undefined : parseLighterStrictDecimal(pnl);\n if (\n parsedPnl === null ||\n (pnl !== undefined &&\n (typeof pnl !== 'string' || !Number.isFinite(parsedPnl)))\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`,\n );\n }\n const direction = deriveLighterFillDirection({\n isBuy,\n size,\n positionBefore,\n signChanged,\n pnl: parsedPnl,\n });\n // Signed pre-trade position, derivable whenever the direction proved the\n // orientation: closing/flipping a long means it was +before, a short\n // -before; opens start from zero. Clients size flip displays from this.\n let startPosition: string | undefined;\n if (direction.startsWith('Open')) {\n startPosition = '0';\n } else if (direction === 'Close Long' || direction === 'Long > Short') {\n startPosition = String(positionBefore);\n } else if (direction === 'Close Short' || direction === 'Short > Long') {\n startPosition = String(-positionBefore);\n }\n return {\n orderId: String(accountIsAsk ? trade.askId : trade.bidId),\n // Lighter's unique execution id, validated as a safe non-negative\n // integer above. Order id alone cannot separate two fills of one order.\n fillId: String(trade.tradeId),\n symbol,\n side: accountIsAsk ? 'sell' : 'buy',\n size: trade.size,\n price: trade.price,\n // The venue reports realized pnl per side of the trade.\n ...(pnl === undefined ? {} : { pnl }),\n direction,\n ...(startPosition === undefined ? {} : { startPosition }),\n fee,\n feeToken: 'USDC',\n timestamp: trade.timestamp,\n // Lets clients apply venue-specific presentation rules (e.g. the\n // ambiguous side-only vocabulary) without guessing the source.\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Position Transformation\n// ============================================================================\n\n/**\n * Margin a Lighter position uses: its value times the initial margin\n * fraction, a percentage (e.g. \"20\" => 5x leverage).\n *\n * @param positionValue - Position value in USDC.\n * @param initialMarginFraction - Initial margin fraction, in percent.\n * @returns Margin used in USDC, or undefined without a positive fraction.\n */\nfunction deriveLighterPositionMarginUsed(\n positionValue: number,\n initialMarginFraction: number,\n): number | undefined {\n return Number.isFinite(initialMarginFraction) && initialMarginFraction > 0\n ? (positionValue * initialMarginFraction) / 100\n : undefined;\n}\n\n/**\n * Transform a Lighter account position into canonical Position.\n *\n * @param position - Position entry from an account payload.\n * @param maxLeverage - Per-market max leverage (venue margin fractions).\n * @returns MetaMask Perps API position object.\n */\nexport function adaptPositionFromLighter(\n position: LighterApiPosition,\n maxLeverage: number = LIGHTER_MAX_LEVERAGE,\n): Position {\n // Venue-input integrity boundary: the REST layer type-casts JSON without\n // runtime validation, and a prefix-parsed '0.1oops' would become a\n // canonical '0.1' that TP/SL cover-sizing and close paths then SIGN.\n // The documented representation is a NONNEGATIVE magnitude with sign\n // exactly 1 or -1: a negative magnitude with sign 1 would flip the\n // canonical direction and make close/TPSL act opposite the real\n // position; sign 0/2/'1' would be silently coerced by a > 0 ternary.\n const magnitude = parseLighterStrictDecimal(position.position);\n if (magnitude === null || !Number.isFinite(magnitude) || magnitude < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position size '${position.position}' for ${position.symbol}`,\n );\n }\n // The documented contract is sign EXACTLY 1 or -1, including for flat\n // positions (zero magnitudes are filtered downstream); anything else is\n // malformed venue data, never something to coerce.\n if (position.sign !== 1 && position.sign !== -1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position sign '${String(position.sign)}' for ${position.symbol}`,\n );\n }\n const size = magnitude * position.sign;\n // Malformed values must not turn into NaN margin or RoE.\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n const marginFraction =\n parseLighterStrictDecimal(position.initialMarginFraction) ?? Number.NaN;\n // initialMarginFraction is a percentage (e.g. \"20\" => 5x leverage).\n // Without a usable fraction leverage, margin and RoE are unknown, not 1x.\n const derivedMargin = deriveLighterPositionMarginUsed(\n positionValue,\n marginFraction,\n );\n if (derivedMargin === undefined && size !== 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} initial margin fraction '${String(position.initialMarginFraction)}' for open position ${position.symbol}`,\n );\n }\n const leverageValue =\n derivedMargin === undefined ? undefined : Math.round(100 / marginFraction);\n // A flat row (filtered downstream) uses no margin.\n const marginUsed = derivedMargin ?? 0;\n const liquidationPrice = parseFloat(position.liquidationPrice);\n\n return {\n symbol: position.symbol,\n size: String(size),\n entryPrice: position.avgEntryPrice,\n positionValue: position.positionValue,\n unrealizedPnl: position.unrealizedPnl,\n marginUsed: String(marginUsed),\n leverage: {\n // Older venue captures omit marginMode and therefore retain the\n // historical cross default. Current payloads use 1 for isolated.\n type: position.marginMode === 1 ? 'isolated' : 'cross',\n value: leverageValue,\n },\n liquidationPrice:\n isNaN(liquidationPrice) || liquidationPrice === 0\n ? null\n : position.liquidationPrice,\n maxLeverage,\n // A fraction (0.1 = 10%), the unit Hyperliquid positions use.\n returnOnEquity: marginUsed > 0 ? String(unrealizedPnl / marginUsed) : '0',\n // The account payload carries no funding, so cumulativeFunding is\n // omitted (unknown) rather than reported as zero.\n takeProfitCount: 0,\n stopLossCount: 0,\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Account Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter sub-account into canonical AccountState.\n *\n * @param account - Sub-account payload from `account`/`accountsByL1Address`.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighter(\n account: LighterSubAccount,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n account.collateral,\n 'REST collateral',\n );\n const available = parseStrictAccountDecimal(\n account.availableBalance,\n 'REST available balance',\n );\n const { positions } = account;\n if (!positions) {\n // Without positions, unrealized PnL and the total balance are unknown.\n throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} REST positions missing`);\n }\n const unrealizedPnl = positions.reduce(\n (sum, position) =>\n sum +\n parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n ),\n 0,\n );\n const marginUsed = Math.max(collateral - available, 0);\n const totalBalance = collateral + unrealizedPnl;\n\n return {\n totalBalance: String(totalBalance),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n // Lighter collateral is already the account value. There is no separate\n // spot USDC to add, and this read is a known account, so the amount is 0\n // rather than unknown.\n spotCollateral: '0',\n marginUsed: String(marginUsed),\n unrealizedPnl: String(unrealizedPnl),\n // '0' only when no margin is used, as before.\n returnOnEquity: String(\n accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber() ?? 0,\n ),\n providerId: 'lighter',\n };\n}\n\n/**\n * Build the cross-margin summary from a Lighter sub-account's positions.\n *\n * Open cross positions contribute their value to notional, their margin to\n * margin used and value times the market's maintenance fraction to\n * maintenance margin. Account value is the total balance less isolated\n * positions' unrealized PnL.\n *\n * @param account - Sub-account payload from `account`.\n * @param totalBalance - The account's adapted total balance.\n * @param getMaintenanceFraction - Maintenance margin fraction (0.024 = 2.4%)\n * for a market symbol, or undefined when the market has none.\n * @returns The cross-margin summary, or undefined when the payload omits\n * positions or an open cross position has no maintenance or initial margin\n * fraction.\n */\nexport function adaptCrossMarginSummaryFromLighter(\n account: LighterSubAccount,\n totalBalance: string,\n getMaintenanceFraction: (symbol: string) => number | undefined,\n): CrossMarginSummary | undefined {\n // Omitted positions are not evidence of zero exposure.\n if (!account.positions) {\n return undefined;\n }\n let isolatedUnrealizedPnl = 0;\n let notional = 0;\n let marginUsed = 0;\n let maintenanceMargin = 0;\n for (const position of account.positions) {\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n if (position.marginMode === LIGHTER_MARGIN_MODE_ISOLATED) {\n isolatedUnrealizedPnl += unrealizedPnl;\n continue;\n }\n const size = parseStrictAccountDecimal(\n position.position,\n `REST position size for ${position.symbol}`,\n );\n if (size === 0) {\n continue;\n }\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n if (position.initialMarginFraction === undefined) {\n return undefined;\n }\n const initialMarginFraction = parseStrictAccountDecimal(\n position.initialMarginFraction,\n `REST initial margin fraction for ${position.symbol}`,\n );\n const maintenanceFraction = getMaintenanceFraction(position.symbol);\n if (maintenanceFraction === undefined) {\n return undefined;\n }\n const positionMargin = deriveLighterPositionMarginUsed(\n positionValue,\n initialMarginFraction,\n );\n if (positionMargin === undefined) {\n return undefined;\n }\n notional += positionValue;\n marginUsed += positionMargin;\n maintenanceMargin += positionValue * maintenanceFraction;\n }\n return {\n accountValue: String(\n parseStrictAccountDecimal(totalBalance, 'total balance') -\n isolatedUnrealizedPnl,\n ),\n maintenanceMargin: String(maintenanceMargin),\n marginUsed: String(marginUsed),\n notional: String(notional),\n };\n}\n\n// ============================================================================\n// Order Transformation\n// ============================================================================\n\n/**\n * Map a Lighter order status string onto the canonical status union.\n *\n * @param status - Raw status from the Lighter API.\n * @returns Canonical order status.\n */\nexport function adaptOrderStatus(status: string): Order['status'] {\n switch (status) {\n case 'open':\n case 'pending':\n case 'in-progress':\n return 'open';\n case 'filled':\n return 'filled';\n case 'canceled':\n case 'cancelled':\n case 'canceled-post-only':\n case 'canceled-reduce-only':\n case 'canceled-position-not-allowed':\n case 'canceled-margin-not-allowed':\n case 'canceled-too-much-slippage':\n case 'canceled-not-enough-liquidity':\n case 'canceled-self-trade':\n case 'canceled-expired':\n case 'canceled-oco':\n case 'canceled-child':\n case 'canceled-liquidation':\n case 'canceled-invalid-balance':\n return 'canceled';\n default:\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown order status '${status}'`,\n );\n }\n}\n\n/**\n * Transform a Lighter active order into canonical Order.\n *\n * @param order - Order entry from `GET /api/v1/accountActiveOrders`.\n * @param symbol - Market symbol for the order's `marketIndex`.\n * @returns MetaMask Perps API order object.\n */\nexport function adaptOrderFromLighter(\n order: LighterApiOrder,\n symbol: string,\n): Order {\n const original = parseFloat(order.initialBaseAmount);\n const remaining = parseFloat(order.remainingBaseAmount);\n // Canceled orders have zero remaining size even when nothing filled.\n const filled =\n order.filledBaseAmount === undefined\n ? Math.max(original - remaining, 0)\n : parseFloat(order.filledBaseAmount);\n\n const isTrigger = !['market', 'limit'].includes(order.type);\n const triggerPrice =\n order.triggerPrice !== undefined && parseFloat(order.triggerPrice) > 0\n ? order.triggerPrice\n : undefined;\n // Semantic trigger typing: without it, a TP/SL renders as a generic\n // Limit order in clients. Venue trigger orders execute market-on-trigger\n // (IOC with a protection price), the -limit variants rest at a price.\n const triggerTypeMeta: Record<\n string,\n {\n orderType: 'market' | 'limit';\n triggerOrderType: TriggerOrderType;\n detailed: string;\n }\n > = {\n 'take-profit': {\n orderType: 'market',\n triggerOrderType: 'take_profit_market',\n detailed: 'Take Profit Market',\n },\n 'stop-loss': {\n orderType: 'market',\n triggerOrderType: 'stop_market',\n detailed: 'Stop Market',\n },\n 'take-profit-limit': {\n orderType: 'limit',\n triggerOrderType: 'take_profit_limit',\n detailed: 'Take Profit Limit',\n },\n 'stop-loss-limit': {\n orderType: 'limit',\n triggerOrderType: 'stop_limit',\n detailed: 'Stop Limit',\n },\n };\n const triggerMeta = triggerTypeMeta[order.type];\n\n return {\n orderId: String(order.orderIndex),\n symbol,\n side: order.isAsk ? 'sell' : 'buy',\n orderType:\n triggerMeta?.orderType ?? (order.type === 'market' ? 'market' : 'limit'),\n ...(triggerMeta\n ? {\n triggerOrderType: triggerMeta.triggerOrderType,\n detailedOrderType: triggerMeta.detailed,\n }\n : {}),\n isTrigger,\n size: order.remainingBaseAmount,\n originalSize: order.initialBaseAmount,\n // On trigger orders `price` is the ±5% protection EXECUTION price;\n // the user-facing TP/SL level is `triggerPrice`.\n price: order.price,\n ...(triggerPrice === undefined ? {} : { triggerPrice }),\n filledSize: String(filled),\n remainingSize: order.remainingBaseAmount,\n status: adaptOrderStatus(order.status),\n // Order endpoints report seconds; preserve already-normalized millisecond\n // inputs. Trade timestamps are a separate millisecond wire contract.\n timestamp:\n order.timestamp < 1e12 ? order.timestamp * 1000 : order.timestamp,\n reduceOnly: Boolean(order.reduceOnly),\n providerId: 'lighter',\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.d.ts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,MAAM,mBAAmB,CAAC;AAG3B;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IACvC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,OAAO,CAuBV;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,SAAS,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,EAAE,eAAe,CAAC;IACzB,iBAAiB,CAAC,EAAE,gBAAgB,EAAE,CAAC;CACxC,CAAC;AA8GF;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAClC,eAAe,EAAE,CAwGnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
1
+ {"version":3,"file":"marketDataTransform.d.ts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,MAAM,mBAAmB,CAAC;AAI3B;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IACvC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,OAAO,CAgBV;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,SAAS,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,EAAE,eAAe,CAAC;IACzB,iBAAiB,CAAC,EAAE,gBAAgB,EAAE,CAAC;CACxC,CAAC;AA8GF;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAClC,eAAe,EAAE,CAgHnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
@@ -7,7 +7,9 @@
7
7
  import { hasProperty } from '@metamask/utils';
8
8
  import { HYPERLIQUID_CONFIG, getHyperLiquidAssetName, } from '../constants/hyperLiquidConfig.js';
9
9
  import { PERPS_CONSTANTS } from '../constants/perpsConfig.js';
10
+ import { buildMarketNumericValues } from '../internal/marketNumericValues.js';
10
11
  import { parseAssetName } from './hyperLiquidAdapter.js';
12
+ import { isPriceOutsideDeviationBand } from './priceDeviation.js';
11
13
  /**
12
14
  * Calculate open interest in USD
13
15
  * Open interest from HyperLiquid is in contracts/units, not USD
@@ -56,16 +58,12 @@ export function isMarketTradable(params) {
56
58
  // Without usable prices we cannot assess deviation — default to tradable so missing
57
59
  // data never blocks the user. A non-positive price means "no data" (e.g. the transient
58
60
  // zero price emitted before the first real tick), not an untradable market.
59
- if (midPrice === undefined ||
60
- oraclePrice === undefined ||
61
- isNaN(midPrice) ||
62
- isNaN(oraclePrice) ||
63
- midPrice <= 0 ||
64
- oraclePrice <= 0) {
61
+ if (midPrice === undefined || oraclePrice === undefined) {
65
62
  return true;
66
63
  }
67
- const deviation = Math.abs(midPrice - oraclePrice) / oraclePrice;
68
- return deviation <= deviationLimit;
64
+ // The same band clients use to check a limit price, so a market and an
65
+ // order at one price never disagree.
66
+ return !isPriceOutsideDeviationBand(midPrice, oraclePrice, deviationLimit);
69
67
  }
70
68
  /**
71
69
  * Calculate 24h percentage change
@@ -215,6 +213,13 @@ export function transformMarketData(hyperLiquidData, formatters, assetMarketType
215
213
  marketType,
216
214
  isHip3,
217
215
  isNewMarket,
216
+ numericValues: buildMarketNumericValues({
217
+ price: currentPrice,
218
+ // Unknown without both prices, not 0%.
219
+ change24hPercent: hasCurrentPrice && prevDayPrice > 0 ? change24hPercent : undefined,
220
+ volume,
221
+ openInterest,
222
+ }),
218
223
  };
219
224
  });
220
225
  }
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.js","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAY9D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CACtC,YAAyC,EACzC,YAAyC;IAEzC,IAAI,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAC7D,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,eAAe,GACnB,OAAO,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;IAC7E,MAAM,QAAQ,GACZ,OAAO,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,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C,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;QAC7D,MAAM,EAAE,UAAU,CAAC,oBAAoB;KACxC,CAAC,CAAC;IAEH,2DAA2D;IAC3D,MAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACtD,OAAO,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC;AAC5E,CAAC","sourcesContent":["/**\n * Market data transformation utilities.\n *\n * Portable: no mobile-specific imports.\n * Formatters are injected via MarketDataFormatters interface.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_CONFIG,\n getHyperLiquidAssetName,\n} from '../constants/hyperLiquidConfig.js';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types.js';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types/index.js';\nimport { parseAssetName } from './hyperLiquidAdapter.js';\n\n/**\n * Calculate open interest in USD\n * Open interest from HyperLiquid is in contracts/units, not USD\n * To get USD value, multiply by current price\n *\n * @param openInterest - Raw open interest value in contracts/units\n * @param currentPrice - Current price of the asset\n * @returns Open interest in USD, or NaN if invalid\n */\nexport function calculateOpenInterestUSD(\n openInterest: string | number | undefined,\n currentPrice: string | number | undefined,\n): number {\n if (openInterest === undefined || currentPrice === undefined) {\n return NaN;\n }\n\n const openInterestNum =\n typeof openInterest === 'string' ? parseFloat(openInterest) : openInterest;\n const priceNum =\n typeof currentPrice === 'string' ? parseFloat(currentPrice) : currentPrice;\n\n if (isNaN(openInterestNum) || isNaN(priceNum)) {\n return NaN;\n }\n\n return openInterestNum * priceNum;\n}\n\n/**\n * Determine whether a market is currently tradable based on how far its market\n * (mid) price has drifted from the oracle (reference) price.\n *\n * HyperLiquid rejects orders when the order price is more than 95% away from the\n * reference price (\"Order price cannot be more than 95% away from the reference\n * price\"). This most often affects HIP-3 builder-deployed markets, which can become\n * temporarily untradable when their mid price diverges far from the oracle price.\n * Clients use this signal to proactively warn the user (e.g. a \"trading unavailable\"\n * banner) instead of letting the order fail on submission.\n *\n * Note: the deviation limit is a HyperLiquid protocol rule. Other providers may have\n * different rules and should compute tradability accordingly.\n *\n * @param params - The parameters for the tradability check.\n * @param params.midPrice - Current market/mid price.\n * @param params.oraclePrice - Current oracle/reference price.\n * @param params.deviationLimit - Max allowed deviation as a decimal fraction\n * (defaults to HyperLiquid's 0.95). A market is untradable when\n * `abs(midPrice - oraclePrice) / oraclePrice > deviationLimit`.\n * @returns `true` when the market is tradable (or when prices are unavailable, so the\n * absence of data never blocks trading); `false` when the deviation exceeds the limit.\n */\nexport function isMarketTradable(params: {\n midPrice: number | undefined;\n oraclePrice: number | undefined;\n deviationLimit?: number;\n}): boolean {\n const {\n midPrice,\n oraclePrice,\n deviationLimit = HYPERLIQUID_CONFIG.OraclePriceDeviationLimit,\n } = params;\n\n // Without usable prices we cannot assess deviation — default to tradable so missing\n // data never blocks the user. A non-positive price means \"no data\" (e.g. the transient\n // zero price emitted before the first real tick), not an untradable market.\n if (\n midPrice === undefined ||\n oraclePrice === undefined ||\n isNaN(midPrice) ||\n isNaN(oraclePrice) ||\n midPrice <= 0 ||\n oraclePrice <= 0\n ) {\n return true;\n }\n\n const deviation = Math.abs(midPrice - oraclePrice) / oraclePrice;\n return deviation <= deviationLimit;\n}\n\n/**\n * HyperLiquid-specific market data structure\n */\nexport type HyperLiquidMarketData = {\n universe: PerpsUniverse[];\n assetCtxs: PerpsAssetCtx[];\n allMids: AllMidsResponse;\n predictedFundings?: PredictedFunding[];\n};\n\n/**\n * Parameters for calculating 24h percentage change\n */\ntype CalculateChange24hPercentParams = {\n hasCurrentPrice: boolean;\n currentPrice: number;\n prevDayPrice: number;\n};\n\n/**\n * Calculate 24h percentage change\n * Shows -100% when current price is missing but previous price exists\n *\n * @param params - The parameters for calculating the 24h change.\n * @returns The 24h percentage change value.\n */\nfunction calculateChange24hPercent(\n params: CalculateChange24hPercentParams,\n): number {\n const { hasCurrentPrice, currentPrice, prevDayPrice } = params;\n\n if (!hasCurrentPrice) {\n return prevDayPrice > 0 ? -100 : 0;\n }\n\n if (prevDayPrice <= 0) {\n return 0;\n }\n\n return ((currentPrice - prevDayPrice) / prevDayPrice) * 100;\n}\n\n/**\n * Funding data extracted from predicted fundings\n */\ntype FundingData = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n predictedFundingRate?: number;\n};\n\n/**\n * Parameters for extracting funding data\n */\ntype ExtractFundingDataParams = {\n predictedFundings?: PredictedFunding[];\n symbol: string;\n exchangeName?: string;\n};\n\n/**\n * Extract funding data for a symbol from predicted fundings.\n * Looks for specified exchange first, falls back to first available.\n *\n * @param params - Parameters for extracting funding data\n * @param params.predictedFundings - Array of predicted funding data\n * @param params.symbol - Asset symbol to extract funding for\n * @param params.exchangeName - Exchange to prioritize (defaults to HyperLiquid's 'HlPerp')\n * @returns Funding data including next funding time, interval, and predicted rate\n */\nfunction extractFundingData(params: ExtractFundingDataParams): FundingData {\n const {\n predictedFundings,\n symbol,\n exchangeName = HYPERLIQUID_CONFIG.ExchangeName,\n } = params;\n\n const result: FundingData = {};\n\n if (!predictedFundings) {\n return result;\n }\n\n const fundingData = predictedFundings.find(\n ([assetSymbol]) => assetSymbol === symbol,\n );\n\n if (\n !fundingData?.[1] ||\n !Array.isArray(fundingData[1]) ||\n fundingData[1].length === 0\n ) {\n return result;\n }\n\n // Look for specified exchange (e.g., 'HlPerp' for HyperLiquid)\n const targetExchange = fundingData[1].find(\n (exchange: unknown) =>\n Array.isArray(exchange) && exchange[0] === exchangeName,\n );\n\n if (targetExchange?.[1]) {\n result.nextFundingTime = targetExchange[1].nextFundingTime;\n result.fundingIntervalHours = targetExchange[1].fundingIntervalHours;\n result.predictedFundingRate = parseFloat(targetExchange[1].fundingRate);\n return result;\n }\n\n // Fallback to first exchange if target not found\n const firstExchange = fundingData[1][0];\n if (Array.isArray(firstExchange) && firstExchange[1]) {\n result.nextFundingTime = firstExchange[1].nextFundingTime;\n result.fundingIntervalHours = firstExchange[1].fundingIntervalHours;\n }\n\n return result;\n}\n\n/**\n * Transform raw HyperLiquid market data to UI-friendly format\n *\n * @param hyperLiquidData - Raw data from HyperLiquid API\n * @param formatters - Injectable formatters for platform-agnostic formatting\n * @param assetMarketTypes - Optional mapping of asset symbols to market types\n * @param assetNames - Optional mapping of asset symbols to human-readable names.\n * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to\n * their ticker symbol.\n * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\n assetNames?: Record<string, string>,\n): PerpsMarketData[] {\n const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;\n\n return universe.map((asset, index) => {\n const symbol = asset.name;\n const currentPrice = parseFloat(allMids[symbol]);\n\n // Find matching asset context for additional data\n // The assetCtxs array is aligned with universe array by index\n const assetCtx = assetCtxs[index];\n\n // Calculate 24h change\n const prevDayPrice = assetCtx ? parseFloat(assetCtx.prevDayPx) : 0;\n\n // Handle missing current price data\n const hasCurrentPrice = !isNaN(currentPrice);\n const effectiveCurrentPrice = hasCurrentPrice ? currentPrice : 0;\n\n // For dollar change: show $0.00 when current price is missing\n const change24h = hasCurrentPrice\n ? effectiveCurrentPrice - prevDayPrice\n : 0;\n\n // For percentage: show -100% when current price is missing but previous price exists\n const change24hPercent = calculateChange24hPercent({\n hasCurrentPrice,\n currentPrice: effectiveCurrentPrice,\n prevDayPrice,\n });\n\n // Format volume (dayNtlVlm is daily notional volume)\n // If assetCtx is missing or dayNtlVlm is not available, use NaN to indicate missing data\n const volume = assetCtx?.dayNtlVlm ? parseFloat(assetCtx.dayNtlVlm) : NaN;\n\n // Calculate open interest in USD\n const openInterest = calculateOpenInterestUSD(\n assetCtx?.openInterest,\n currentPrice,\n );\n\n // Get current funding rate from assetCtx - this is the actual current funding rate\n let fundingRate: number | undefined;\n\n if (assetCtx && hasProperty(assetCtx, 'funding')) {\n fundingRate = parseFloat(assetCtx.funding);\n }\n\n // Extract funding timing and predicted rate\n const fundingData = extractFundingData({\n predictedFundings,\n symbol,\n });\n\n // Use current funding rate from assetCtx, not predicted\n // The predicted rate is for the next funding period\n if (!fundingRate && fundingData.predictedFundingRate !== undefined) {\n fundingRate = fundingData.predictedFundingRate;\n }\n\n // Extract DEX and base symbol for display\n // e.g., \"flx:TSLA\" → { dex: \"flx\", symbol: \"TSLA\" }\n const { dex } = parseAssetName(symbol);\n const marketSource = dex ?? undefined;\n\n // HIP-3 markets have a DEX prefix (e.g., xyz:TSLA, flx:GOLD)\n // Crypto markets (HIP-2) don't have a prefix (e.g., BTC, ETH)\n const isHip3 = Boolean(dex);\n\n // Determine market type from explicit static mapping\n const marketType: MarketType | undefined = assetMarketTypes?.[symbol];\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n const isNewMarket = isHip3 && !marketType;\n\n return {\n symbol,\n name: getHyperLiquidAssetName(symbol, assetNames),\n maxLeverage: `${asset.maxLeverage}x`,\n price: isNaN(currentPrice)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatPerpsFiat(currentPrice, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: isNaN(change24h)\n ? PERPS_CONSTANTS.ZeroAmountDetailedDisplay\n : formatChange(change24h, formatters),\n change24hPercent: isNaN(change24hPercent)\n ? '0.00%'\n : formatters.formatPercentage(change24hPercent),\n volume: isNaN(volume)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(volume),\n openInterest: isNaN(openInterest)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(openInterest),\n nextFundingTime: fundingData.nextFundingTime,\n fundingIntervalHours: fundingData.fundingIntervalHours,\n fundingRate,\n marketSource,\n marketType,\n isHip3,\n isNewMarket,\n };\n });\n}\n\n/**\n * Format 24h change with sign.\n * Uses more decimal places for smaller amounts to show meaningful precision.\n *\n * @param change - The price change value to format\n * @param formatters - Injectable formatters\n * @returns Formatted change string with sign and dollar symbol\n */\nexport function formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change)) {\n return '$0.00';\n }\n if (change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n\n // Remove $ sign and add it back with proper sign placement\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n"]}
1
+ {"version":3,"file":"marketDataTransform.js","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAY9E,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAElE;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CACtC,YAAyC,EACzC,YAAyC;IAEzC,IAAI,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAC7D,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,eAAe,GACnB,OAAO,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;IAC7E,MAAM,QAA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QACvC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;QAC7D,MAAM,EAAE,UAAU,CAAC,oBAAoB;KACxC,CAAC,CAAC;IAEH,2DAA2D;IAC3D,MAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACtD,OAAO,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC;AAC5E,CAAC","sourcesContent":["/**\n * Market data transformation utilities.\n *\n * Portable: no mobile-specific imports.\n * Formatters are injected via MarketDataFormatters interface.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_CONFIG,\n getHyperLiquidAssetName,\n} from '../constants/hyperLiquidConfig.js';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport { buildMarketNumericValues } from '../internal/marketNumericValues.js';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types.js';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types/index.js';\nimport { parseAssetName } from './hyperLiquidAdapter.js';\nimport { isPriceOutsideDeviationBand } from './priceDeviation.js';\n\n/**\n * Calculate open interest in USD\n * Open interest from HyperLiquid is in contracts/units, not USD\n * To get USD value, multiply by current price\n *\n * @param openInterest - Raw open interest value in contracts/units\n * @param currentPrice - Current price of the asset\n * @returns Open interest in USD, or NaN if invalid\n */\nexport function calculateOpenInterestUSD(\n openInterest: string | number | undefined,\n currentPrice: string | number | undefined,\n): number {\n if (openInterest === undefined || currentPrice === undefined) {\n return NaN;\n }\n\n const openInterestNum =\n typeof openInterest === 'string' ? parseFloat(openInterest) : openInterest;\n const priceNum =\n typeof currentPrice === 'string' ? parseFloat(currentPrice) : currentPrice;\n\n if (isNaN(openInterestNum) || isNaN(priceNum)) {\n return NaN;\n }\n\n return openInterestNum * priceNum;\n}\n\n/**\n * Determine whether a market is currently tradable based on how far its market\n * (mid) price has drifted from the oracle (reference) price.\n *\n * HyperLiquid rejects orders when the order price is more than 95% away from the\n * reference price (\"Order price cannot be more than 95% away from the reference\n * price\"). This most often affects HIP-3 builder-deployed markets, which can become\n * temporarily untradable when their mid price diverges far from the oracle price.\n * Clients use this signal to proactively warn the user (e.g. a \"trading unavailable\"\n * banner) instead of letting the order fail on submission.\n *\n * Note: the deviation limit is a HyperLiquid protocol rule. Other providers may have\n * different rules and should compute tradability accordingly.\n *\n * @param params - The parameters for the tradability check.\n * @param params.midPrice - Current market/mid price.\n * @param params.oraclePrice - Current oracle/reference price.\n * @param params.deviationLimit - Max allowed deviation as a decimal fraction\n * (defaults to HyperLiquid's 0.95). A market is untradable when\n * `abs(midPrice - oraclePrice) / oraclePrice > deviationLimit`.\n * @returns `true` when the market is tradable (or when prices are unavailable, so the\n * absence of data never blocks trading); `false` when the deviation exceeds the limit.\n */\nexport function isMarketTradable(params: {\n midPrice: number | undefined;\n oraclePrice: number | undefined;\n deviationLimit?: number;\n}): boolean {\n const {\n midPrice,\n oraclePrice,\n deviationLimit = HYPERLIQUID_CONFIG.OraclePriceDeviationLimit,\n } = params;\n\n // Without usable prices we cannot assess deviation — default to tradable so missing\n // data never blocks the user. A non-positive price means \"no data\" (e.g. the transient\n // zero price emitted before the first real tick), not an untradable market.\n if (midPrice === undefined || oraclePrice === undefined) {\n return true;\n }\n // The same band clients use to check a limit price, so a market and an\n // order at one price never disagree.\n return !isPriceOutsideDeviationBand(midPrice, oraclePrice, deviationLimit);\n}\n\n/**\n * HyperLiquid-specific market data structure\n */\nexport type HyperLiquidMarketData = {\n universe: PerpsUniverse[];\n assetCtxs: PerpsAssetCtx[];\n allMids: AllMidsResponse;\n predictedFundings?: PredictedFunding[];\n};\n\n/**\n * Parameters for calculating 24h percentage change\n */\ntype CalculateChange24hPercentParams = {\n hasCurrentPrice: boolean;\n currentPrice: number;\n prevDayPrice: number;\n};\n\n/**\n * Calculate 24h percentage change\n * Shows -100% when current price is missing but previous price exists\n *\n * @param params - The parameters for calculating the 24h change.\n * @returns The 24h percentage change value.\n */\nfunction calculateChange24hPercent(\n params: CalculateChange24hPercentParams,\n): number {\n const { hasCurrentPrice, currentPrice, prevDayPrice } = params;\n\n if (!hasCurrentPrice) {\n return prevDayPrice > 0 ? -100 : 0;\n }\n\n if (prevDayPrice <= 0) {\n return 0;\n }\n\n return ((currentPrice - prevDayPrice) / prevDayPrice) * 100;\n}\n\n/**\n * Funding data extracted from predicted fundings\n */\ntype FundingData = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n predictedFundingRate?: number;\n};\n\n/**\n * Parameters for extracting funding data\n */\ntype ExtractFundingDataParams = {\n predictedFundings?: PredictedFunding[];\n symbol: string;\n exchangeName?: string;\n};\n\n/**\n * Extract funding data for a symbol from predicted fundings.\n * Looks for specified exchange first, falls back to first available.\n *\n * @param params - Parameters for extracting funding data\n * @param params.predictedFundings - Array of predicted funding data\n * @param params.symbol - Asset symbol to extract funding for\n * @param params.exchangeName - Exchange to prioritize (defaults to HyperLiquid's 'HlPerp')\n * @returns Funding data including next funding time, interval, and predicted rate\n */\nfunction extractFundingData(params: ExtractFundingDataParams): FundingData {\n const {\n predictedFundings,\n symbol,\n exchangeName = HYPERLIQUID_CONFIG.ExchangeName,\n } = params;\n\n const result: FundingData = {};\n\n if (!predictedFundings) {\n return result;\n }\n\n const fundingData = predictedFundings.find(\n ([assetSymbol]) => assetSymbol === symbol,\n );\n\n if (\n !fundingData?.[1] ||\n !Array.isArray(fundingData[1]) ||\n fundingData[1].length === 0\n ) {\n return result;\n }\n\n // Look for specified exchange (e.g., 'HlPerp' for HyperLiquid)\n const targetExchange = fundingData[1].find(\n (exchange: unknown) =>\n Array.isArray(exchange) && exchange[0] === exchangeName,\n );\n\n if (targetExchange?.[1]) {\n result.nextFundingTime = targetExchange[1].nextFundingTime;\n result.fundingIntervalHours = targetExchange[1].fundingIntervalHours;\n result.predictedFundingRate = parseFloat(targetExchange[1].fundingRate);\n return result;\n }\n\n // Fallback to first exchange if target not found\n const firstExchange = fundingData[1][0];\n if (Array.isArray(firstExchange) && firstExchange[1]) {\n result.nextFundingTime = firstExchange[1].nextFundingTime;\n result.fundingIntervalHours = firstExchange[1].fundingIntervalHours;\n }\n\n return result;\n}\n\n/**\n * Transform raw HyperLiquid market data to UI-friendly format\n *\n * @param hyperLiquidData - Raw data from HyperLiquid API\n * @param formatters - Injectable formatters for platform-agnostic formatting\n * @param assetMarketTypes - Optional mapping of asset symbols to market types\n * @param assetNames - Optional mapping of asset symbols to human-readable names.\n * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to\n * their ticker symbol.\n * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\n assetNames?: Record<string, string>,\n): PerpsMarketData[] {\n const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;\n\n return universe.map((asset, index) => {\n const symbol = asset.name;\n const currentPrice = parseFloat(allMids[symbol]);\n\n // Find matching asset context for additional data\n // The assetCtxs array is aligned with universe array by index\n const assetCtx = assetCtxs[index];\n\n // Calculate 24h change\n const prevDayPrice = assetCtx ? parseFloat(assetCtx.prevDayPx) : 0;\n\n // Handle missing current price data\n const hasCurrentPrice = !isNaN(currentPrice);\n const effectiveCurrentPrice = hasCurrentPrice ? currentPrice : 0;\n\n // For dollar change: show $0.00 when current price is missing\n const change24h = hasCurrentPrice\n ? effectiveCurrentPrice - prevDayPrice\n : 0;\n\n // For percentage: show -100% when current price is missing but previous price exists\n const change24hPercent = calculateChange24hPercent({\n hasCurrentPrice,\n currentPrice: effectiveCurrentPrice,\n prevDayPrice,\n });\n\n // Format volume (dayNtlVlm is daily notional volume)\n // If assetCtx is missing or dayNtlVlm is not available, use NaN to indicate missing data\n const volume = assetCtx?.dayNtlVlm ? parseFloat(assetCtx.dayNtlVlm) : NaN;\n\n // Calculate open interest in USD\n const openInterest = calculateOpenInterestUSD(\n assetCtx?.openInterest,\n currentPrice,\n );\n\n // Get current funding rate from assetCtx - this is the actual current funding rate\n let fundingRate: number | undefined;\n\n if (assetCtx && hasProperty(assetCtx, 'funding')) {\n fundingRate = parseFloat(assetCtx.funding);\n }\n\n // Extract funding timing and predicted rate\n const fundingData = extractFundingData({\n predictedFundings,\n symbol,\n });\n\n // Use current funding rate from assetCtx, not predicted\n // The predicted rate is for the next funding period\n if (!fundingRate && fundingData.predictedFundingRate !== undefined) {\n fundingRate = fundingData.predictedFundingRate;\n }\n\n // Extract DEX and base symbol for display\n // e.g., \"flx:TSLA\" → { dex: \"flx\", symbol: \"TSLA\" }\n const { dex } = parseAssetName(symbol);\n const marketSource = dex ?? undefined;\n\n // HIP-3 markets have a DEX prefix (e.g., xyz:TSLA, flx:GOLD)\n // Crypto markets (HIP-2) don't have a prefix (e.g., BTC, ETH)\n const isHip3 = Boolean(dex);\n\n // Determine market type from explicit static mapping\n const marketType: MarketType | undefined = assetMarketTypes?.[symbol];\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n const isNewMarket = isHip3 && !marketType;\n\n return {\n symbol,\n name: getHyperLiquidAssetName(symbol, assetNames),\n maxLeverage: `${asset.maxLeverage}x`,\n price: isNaN(currentPrice)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatPerpsFiat(currentPrice, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: isNaN(change24h)\n ? PERPS_CONSTANTS.ZeroAmountDetailedDisplay\n : formatChange(change24h, formatters),\n change24hPercent: isNaN(change24hPercent)\n ? '0.00%'\n : formatters.formatPercentage(change24hPercent),\n volume: isNaN(volume)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(volume),\n openInterest: isNaN(openInterest)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(openInterest),\n nextFundingTime: fundingData.nextFundingTime,\n fundingIntervalHours: fundingData.fundingIntervalHours,\n fundingRate,\n marketSource,\n marketType,\n isHip3,\n isNewMarket,\n numericValues: buildMarketNumericValues({\n price: currentPrice,\n // Unknown without both prices, not 0%.\n change24hPercent:\n hasCurrentPrice && prevDayPrice > 0 ? change24hPercent : undefined,\n volume,\n openInterest,\n }),\n };\n });\n}\n\n/**\n * Format 24h change with sign.\n * Uses more decimal places for smaller amounts to show meaningful precision.\n *\n * @param change - The price change value to format\n * @param formatters - Injectable formatters\n * @returns Formatted change string with sign and dollar symbol\n */\nexport function formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change)) {\n return '$0.00';\n }\n if (change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n\n // Remove $ sign and add it back with proper sign placement\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { GetMarketDataWithPricesParams, GroupedPerpsMarket, MarketInfo, MarketTypeFilter, PerpsMarketData, PerpsProviderType } from '../types/index.js';
2
2
  import type { CandleData } from '../types/perps-types.js';
3
+ export { getPerpsDisplaySymbol } from '../internal/perpsDisplaySymbol.js';
3
4
  type MarketIdentity = Pick<MarketInfo, 'marketKey' | 'priceScale'>;
4
5
  /**
5
6
  * Copy the optional cross-venue identity fields of a snapshot row.
@@ -125,7 +126,6 @@ export declare const validateMarketPattern: (pattern: string) => boolean;
125
126
  export declare const compileMarketPattern: (pattern: string) => MarketPatternMatcher;
126
127
  export declare const matchesMarketPattern: (symbol: string, matcher: MarketPatternMatcher) => boolean;
127
128
  export declare const shouldIncludeMarket: (symbol: string, dex: string | null, hip3Enabled: boolean, compiledEnabledPatterns: CompiledMarketPattern[], compiledBlockedPatterns: CompiledMarketPattern[]) => boolean;
128
- export declare const getPerpsDisplaySymbol: (symbol: string) => string;
129
129
  export declare const getPerpsDexFromSymbol: (symbol: string) => string | null;
130
130
  type FundingCountdownParams = {
131
131
  nextFundingTime?: number;
@@ -137,5 +137,4 @@ export declare const calculate24hHighLow: (candleData: CandleData | null) => {
137
137
  low: number;
138
138
  };
139
139
  export declare const filterMarketsByQuery: (markets: PerpsMarketData[], searchQuery: string) => PerpsMarketData[];
140
- export {};
141
140
  //# sourceMappingURL=marketUtils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"marketUtils.d.ts","sourceRoot":"","sources":["../../src/utils/marketUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,kBAAkB,EAClB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AAMvE,KAAK,cAAc,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,GAAG,YAAY,CAAC,CAAC;AAEnE;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE;IAClD,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,GAAG,cAAc,CAMjB;AAOD;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,SAAS,eAAe,EAAE,EACnC,eAAe,EAAE,iBAAiB,GACjC,kBAAkB,EAAE,CAmCtB;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB,MAAM,CAER;AAED;;;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KAC5B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CA2B7B,CAAC;AAEF,eAAO,MAAM,oBAAoB,YACtB,eAAe,EAAE,eACb,MAAM,KAClB,eAAe,EAYjB,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { sortMarkets } from './sortMarkets.js';
2
+ export { getPerpsDisplaySymbol } from '../internal/perpsDisplaySymbol.js';
2
3
  const SAVED_MARKET_KEY_PREFIX = 'market-key:';
3
4
  const SAVED_VENUE_PREFIX = 'venue:';
4
5
  /**
@@ -166,6 +167,7 @@ export function clonePerpsMarketData(markets) {
166
167
  ...(market.keywords && { keywords: [...market.keywords] }),
167
168
  ...(market.tags && { tags: [...market.tags] }),
168
169
  ...(market.categories && { categories: [...market.categories] }),
170
+ ...(market.numericValues && { numericValues: { ...market.numericValues } }),
169
171
  ...(market.trend && {
170
172
  trend: market.trend.map(([timestamp, price]) => [
171
173
  timestamp,
@@ -209,13 +211,11 @@ export function matchesCategory(market, category) {
209
211
  case 'crypto':
210
212
  return getMarketTypeFilter(market) === 'crypto';
211
213
  case 'memecoin':
212
- // Derived category: a crypto market that carries the 'memecoin' tag.
213
- // Aligned with the 'crypto' case above so tagged main-DEX markets
214
- // still match when their marketType is unset (the common
215
- // provider-sourced shape prior to Terminal enrichment). Overlaps
216
- // with 'crypto' by design — memecoins appear under both pills.
217
- return (getMarketTypeFilter(market) === 'crypto' &&
218
- (market.tags?.includes('memecoin') ?? false));
214
+ // Derived category, as Mobile's isMemecoinMarket: a main-DEX market
215
+ // that carries the 'memecoin' tag, whatever its marketType. A HIP-3
216
+ // market never matches. Overlaps with 'crypto' by design: memecoins
217
+ // appear under both pills.
218
+ return (!isHip3Market(market) && (market.tags?.includes('memecoin') ?? false));
219
219
  default:
220
220
  // Every other filter is a 1:1 data-model category match.
221
221
  return market.marketType !== undefined && market.marketType === category;
@@ -336,16 +336,6 @@ export const shouldIncludeMarket = (symbol, dex, hip3Enabled, compiledEnabledPat
336
336
  const blacklisted = compiledBlockedPatterns.some(({ matcher }) => matchesMarketPattern(symbol, matcher));
337
337
  return !blacklisted;
338
338
  };
339
- export const getPerpsDisplaySymbol = (symbol) => {
340
- if (!symbol || typeof symbol !== 'string') {
341
- return symbol;
342
- }
343
- const colonIndex = symbol.indexOf(':');
344
- if (colonIndex > 0 && colonIndex < symbol.length - 1) {
345
- return symbol.substring(colonIndex + 1);
346
- }
347
- return symbol;
348
- };
349
339
  export const getPerpsDexFromSymbol = (symbol) => {
350
340
  if (!symbol || typeof symbol !== 'string') {
351
341
  return null;