@metamask-previews/perps-controller 8.0.0-preview-51b287c55 → 8.1.0-preview-3af52b79c

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 (78) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/dist/constants/hyperLiquidConfig.cjs +166 -1
  3. package/dist/constants/hyperLiquidConfig.cjs.map +1 -1
  4. package/dist/constants/hyperLiquidConfig.d.cts +33 -0
  5. package/dist/constants/hyperLiquidConfig.d.cts.map +1 -1
  6. package/dist/constants/hyperLiquidConfig.d.mts +33 -0
  7. package/dist/constants/hyperLiquidConfig.d.mts.map +1 -1
  8. package/dist/constants/hyperLiquidConfig.mjs +163 -0
  9. package/dist/constants/hyperLiquidConfig.mjs.map +1 -1
  10. package/dist/constants/perpsConfig.cjs +2 -0
  11. package/dist/constants/perpsConfig.cjs.map +1 -1
  12. package/dist/constants/perpsConfig.d.cts +1 -0
  13. package/dist/constants/perpsConfig.d.cts.map +1 -1
  14. package/dist/constants/perpsConfig.d.mts +1 -0
  15. package/dist/constants/perpsConfig.d.mts.map +1 -1
  16. package/dist/constants/perpsConfig.mjs +2 -0
  17. package/dist/constants/perpsConfig.mjs.map +1 -1
  18. package/dist/index.cjs +48 -44
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +2 -1
  21. package/dist/index.d.cts.map +1 -1
  22. package/dist/index.d.mts +2 -1
  23. package/dist/index.d.mts.map +1 -1
  24. package/dist/index.mjs +2 -1
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/providers/HyperLiquidProvider.cjs +2 -2
  27. package/dist/providers/HyperLiquidProvider.cjs.map +1 -1
  28. package/dist/providers/HyperLiquidProvider.d.cts +1 -1
  29. package/dist/providers/HyperLiquidProvider.d.cts.map +1 -1
  30. package/dist/providers/HyperLiquidProvider.d.mts +1 -1
  31. package/dist/providers/HyperLiquidProvider.d.mts.map +1 -1
  32. package/dist/providers/HyperLiquidProvider.mjs +3 -3
  33. package/dist/providers/HyperLiquidProvider.mjs.map +1 -1
  34. package/dist/services/HyperLiquidSubscriptionService.cjs +109 -185
  35. package/dist/services/HyperLiquidSubscriptionService.cjs.map +1 -1
  36. package/dist/services/HyperLiquidSubscriptionService.d.cts +3 -3
  37. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +1 -1
  38. package/dist/services/HyperLiquidSubscriptionService.d.mts +3 -3
  39. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +1 -1
  40. package/dist/services/HyperLiquidSubscriptionService.mjs +109 -185
  41. package/dist/services/HyperLiquidSubscriptionService.mjs.map +1 -1
  42. package/dist/services/TradingService.cjs +50 -3
  43. package/dist/services/TradingService.cjs.map +1 -1
  44. package/dist/services/TradingService.d.cts.map +1 -1
  45. package/dist/services/TradingService.d.mts.map +1 -1
  46. package/dist/services/TradingService.mjs +50 -3
  47. package/dist/services/TradingService.mjs.map +1 -1
  48. package/dist/types/index.cjs.map +1 -1
  49. package/dist/types/index.d.cts +1 -1
  50. package/dist/types/index.d.cts.map +1 -1
  51. package/dist/types/index.d.mts +1 -1
  52. package/dist/types/index.d.mts.map +1 -1
  53. package/dist/types/index.mjs.map +1 -1
  54. package/dist/utils/index.cjs +1 -0
  55. package/dist/utils/index.cjs.map +1 -1
  56. package/dist/utils/index.d.cts +1 -0
  57. package/dist/utils/index.d.cts.map +1 -1
  58. package/dist/utils/index.d.mts +1 -0
  59. package/dist/utils/index.d.mts.map +1 -1
  60. package/dist/utils/index.mjs +1 -0
  61. package/dist/utils/index.mjs.map +1 -1
  62. package/dist/utils/marketDataTransform.cjs +5 -2
  63. package/dist/utils/marketDataTransform.cjs.map +1 -1
  64. package/dist/utils/marketDataTransform.d.cts +4 -1
  65. package/dist/utils/marketDataTransform.d.cts.map +1 -1
  66. package/dist/utils/marketDataTransform.d.mts +4 -1
  67. package/dist/utils/marketDataTransform.d.mts.map +1 -1
  68. package/dist/utils/marketDataTransform.mjs +6 -3
  69. package/dist/utils/marketDataTransform.mjs.map +1 -1
  70. package/dist/utils/marketSearch.cjs +85 -0
  71. package/dist/utils/marketSearch.cjs.map +1 -0
  72. package/dist/utils/marketSearch.d.cts +47 -0
  73. package/dist/utils/marketSearch.d.cts.map +1 -0
  74. package/dist/utils/marketSearch.d.mts +47 -0
  75. package/dist/utils/marketSearch.d.mts.map +1 -0
  76. package/dist/utils/marketSearch.mjs +80 -0
  77. package/dist/utils/marketSearch.mjs.map +1 -0
  78. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,mCAA+B;AAC/B,iCAA6B;AAC7B,mGAAmG;AACnG,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,EAC9C,iCAA6B;AAC9B,oDAAgD;AAChD,4CAAwC;AACxC,8BAA0B;AAC1B,0CAAsC;AACtC,kCAA8B;AAC9B,wCAAoC;AACpC,2CAAuC;AACvC,mCAA+B;AAC/B,yCAAqC;AACrC,kCAA8B;AAC9B,2CAAuC;AACvC,uCAAmC;AACnC,mCAA+B;AAC/B,2BAAuB;AAEvB,qFAAqF;AACrF,MAAM,CAAC,MAAM,cAAc,GAAG,GAAmB,EAAE;IACjD,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,QAAQ,IAAI,YAAY,CAAC;IAC9D,OAAO,GAAG,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;AAC/C,CAAC,CAAC;AACF,sCAAkC","sourcesContent":["/**\n * Barrel re-export for all portable utilities in controllers/utils/\n *\n * Note: hyperLiquidAdapter and orderCalculations both export calculatePositionSize.\n * We use selective exports to avoid the name collision.\n */\nexport * from './accountUtils';\nexport * from './errorUtils';\n// hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations\nexport {\n adaptOrderToSDK,\n adaptPositionFromSDK,\n adaptOrderFromSDK,\n adaptMarketFromSDK,\n adaptAccountStateFromSDK,\n buildAssetMapping,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n calculateHip3AssetId,\n parseAssetName,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n} from './hyperLiquidAdapter';\nexport * from './hyperLiquidOrderBookProcessor';\nexport * from './hyperLiquidValidation';\nexport * from './idUtils';\nexport * from './marketDataTransform';\nexport * from './marketUtils';\nexport * from './orderCalculations';\nexport * from './perpsDiskPersistence';\nexport * from './rewardsUtils';\nexport * from './significantFigures';\nexport * from './sortMarkets';\nexport * from './standaloneInfoClient';\nexport * from './stringParseUtils';\nexport * from './transferData';\nexport * from './wait';\n\n// Inline from former utils.ts (getEnvironment was previously at perps/utils.ts root)\nexport const getEnvironment = (): 'DEV' | 'PROD' => {\n const env = globalThis.process?.env?.NODE_ENV ?? 'production';\n return env === 'production' ? 'PROD' : 'DEV';\n};\nexport * from './perpsFormatters';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,mCAA+B;AAC/B,iCAA6B;AAC7B,mGAAmG;AACnG,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,EAC9C,iCAA6B;AAC9B,oDAAgD;AAChD,4CAAwC;AACxC,8BAA0B;AAC1B,0CAAsC;AACtC,mCAA+B;AAC/B,kCAA8B;AAC9B,wCAAoC;AACpC,2CAAuC;AACvC,mCAA+B;AAC/B,yCAAqC;AACrC,kCAA8B;AAC9B,2CAAuC;AACvC,uCAAmC;AACnC,mCAA+B;AAC/B,2BAAuB;AAEvB,qFAAqF;AACrF,MAAM,CAAC,MAAM,cAAc,GAAG,GAAmB,EAAE;IACjD,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,QAAQ,IAAI,YAAY,CAAC;IAC9D,OAAO,GAAG,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;AAC/C,CAAC,CAAC;AACF,sCAAkC","sourcesContent":["/**\n * Barrel re-export for all portable utilities in controllers/utils/\n *\n * Note: hyperLiquidAdapter and orderCalculations both export calculatePositionSize.\n * We use selective exports to avoid the name collision.\n */\nexport * from './accountUtils';\nexport * from './errorUtils';\n// hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations\nexport {\n adaptOrderToSDK,\n adaptPositionFromSDK,\n adaptOrderFromSDK,\n adaptMarketFromSDK,\n adaptAccountStateFromSDK,\n buildAssetMapping,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n calculateHip3AssetId,\n parseAssetName,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n} from './hyperLiquidAdapter';\nexport * from './hyperLiquidOrderBookProcessor';\nexport * from './hyperLiquidValidation';\nexport * from './idUtils';\nexport * from './marketDataTransform';\nexport * from './marketSearch';\nexport * from './marketUtils';\nexport * from './orderCalculations';\nexport * from './perpsDiskPersistence';\nexport * from './rewardsUtils';\nexport * from './significantFigures';\nexport * from './sortMarkets';\nexport * from './standaloneInfoClient';\nexport * from './stringParseUtils';\nexport * from './transferData';\nexport * from './wait';\n\n// Inline from former utils.ts (getEnvironment was previously at perps/utils.ts root)\nexport const getEnvironment = (): 'DEV' | 'PROD' => {\n const env = globalThis.process?.env?.NODE_ENV ?? 'production';\n return env === 'production' ? 'PROD' : 'DEV';\n};\nexport * from './perpsFormatters';\n"]}
@@ -93,9 +93,12 @@ function extractFundingData(params) {
93
93
  * @param hyperLiquidData - Raw data from HyperLiquid API
94
94
  * @param formatters - Injectable formatters for platform-agnostic formatting
95
95
  * @param assetMarketTypes - Optional mapping of asset symbols to market types
96
+ * @param assetNames - Optional mapping of asset symbols to human-readable names.
97
+ * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to
98
+ * their ticker symbol.
96
99
  * @returns Transformed market data ready for UI consumption
97
100
  */
98
- function transformMarketData(hyperLiquidData, formatters, assetMarketTypes) {
101
+ function transformMarketData(hyperLiquidData, formatters, assetMarketTypes, assetNames) {
99
102
  const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;
100
103
  return universe.map((asset, index) => {
101
104
  const symbol = asset.name;
@@ -156,7 +159,7 @@ function transformMarketData(hyperLiquidData, formatters, assetMarketTypes) {
156
159
  const isNewMarket = isHip3 && !explicitMarketType;
157
160
  return {
158
161
  symbol,
159
- name: symbol,
162
+ name: (0, hyperLiquidConfig_1.getHyperLiquidAssetName)(symbol, assetNames),
160
163
  maxLeverage: `${asset.maxLeverage}x`,
161
164
  price: isNaN(currentPrice)
162
165
  ? perpsConfig_1.PERPS_CONSTANTS.FallbackPriceDisplay
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.cjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,2CAA8C;AAE9C,0EAAoE;AACpE,8DAA2D;AAY3D,iEAAsD;AAEtD;;;;;;;;GAQG;AACH,SAAgB,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,CAAC,CAAC,CAAC,Y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ACnB,CAAC,CAAC,6BAAe,CAAC,oBAAoB;gBACtC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;YACnC,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC;gBAC/B,CAAC,CAAC,6BAAe,CAAC,oBAAoB;gBACtC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,YAAY,CAAC;YACzC,eAAe,EAAE,WAAW,CAAC,eAAe;YAC5C,oBAAoB,EAAE,WAAW,CAAC,oBAAoB;YACtD,WAAW;YACX,YAAY;YACZ,UAAU;YACV,MAAM;YACN,WAAW;SACZ,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAjHD,kDAiHC;AAED;;;;;;;GAOG;AACH,SAAgB,YAAY,CAC1B,MAAc,EACd,UAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;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;AAlBD,oCAkBC","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 { HYPERLIQUID_CONFIG } from '../constants/hyperLiquidConfig';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\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 * 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 * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\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 mapping only\n // Only explicitly mapped HIP-3 markets get a marketType (e.g., 'xyz:GOLD' → 'commodity')\n // Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to \"New\" tab\n // Main DEX crypto also has no marketType\n const explicitMarketType = assetMarketTypes?.[symbol];\n const marketType: MarketType | undefined = explicitMarketType;\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n // New markets are always HIP-3 (non-crypto) that haven't been assigned a category yet\n const isNewMarket = isHip3 && !explicitMarketType;\n\n return {\n symbol,\n name: symbol,\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.cjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,2CAA8C;AAE9C,0EAGwC;AACxC,8DAA2D;AAY3D,iEAAsD;AAEtD;;;;;;;;GAQG;AACH,SAAgB,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,CAAC,CAAC,CAAC,YAAY,CAAC;IAE7E,IAAI,KAAK,CAAC,eAAe,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC9C,OAAO,GAAG,CAAC;IACb,CAAC;IAED,OAAO,eAAe,GAAG,QAAQ,CAAC;AACpC,CAAC;AAlBD,4DAkBC;AAqBD;;;;;;GAMG;AACH,SAAS,yBAAyB,CAChC,MAAuC;IAEvC,MAAM,EAAE,eAAe,EAAE,YAAY,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IAE/D,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,OAAO,YAAY,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAA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;SACZ,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAlHD,kDAkHC;AAED;;;;;;;GAOG;AACH,SAAgB,YAAY,CAC1B,MAAc,EACd,UAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;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;AAlBD,oCAkBC","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';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\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 * 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 mapping only\n // Only explicitly mapped HIP-3 markets get a marketType (e.g., 'xyz:GOLD' → 'commodity')\n // Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to \"New\" tab\n // Main DEX crypto also has no marketType\n const explicitMarketType = assetMarketTypes?.[symbol];\n const marketType: MarketType | undefined = explicitMarketType;\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n // New markets are always HIP-3 (non-crypto) that haven't been assigned a category yet\n const isNewMarket = isHip3 && !explicitMarketType;\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"]}
@@ -25,9 +25,12 @@ export type HyperLiquidMarketData = {
25
25
  * @param hyperLiquidData - Raw data from HyperLiquid API
26
26
  * @param formatters - Injectable formatters for platform-agnostic formatting
27
27
  * @param assetMarketTypes - Optional mapping of asset symbols to market types
28
+ * @param assetNames - Optional mapping of asset symbols to human-readable names.
29
+ * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to
30
+ * their ticker symbol.
28
31
  * @returns Transformed market data ready for UI consumption
29
32
  */
30
- export declare function transformMarketData(hyperLiquidData: HyperLiquidMarketData, formatters: MarketDataFormatters, assetMarketTypes?: Record<string, MarketType>): PerpsMarketData[];
33
+ export declare function transformMarketData(hyperLiquidData: HyperLiquidMarketData, formatters: MarketDataFormatters, assetMarketTypes?: Record<string, MarketType>, assetNames?: Record<string, string>): PerpsMarketData[];
31
34
  /**
32
35
  * Format 24h change with sign.
33
36
  * Uses more decimal places for smaller amounts to show meaningful precision.
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.d.cts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;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;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAC5C,eAAe,EAAE,CA6GnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
1
+ {"version":3,"file":"marketDataTransform.d.cts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;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,CA6GnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
@@ -25,9 +25,12 @@ export type HyperLiquidMarketData = {
25
25
  * @param hyperLiquidData - Raw data from HyperLiquid API
26
26
  * @param formatters - Injectable formatters for platform-agnostic formatting
27
27
  * @param assetMarketTypes - Optional mapping of asset symbols to market types
28
+ * @param assetNames - Optional mapping of asset symbols to human-readable names.
29
+ * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to
30
+ * their ticker symbol.
28
31
  * @returns Transformed market data ready for UI consumption
29
32
  */
30
- export declare function transformMarketData(hyperLiquidData: HyperLiquidMarketData, formatters: MarketDataFormatters, assetMarketTypes?: Record<string, MarketType>): PerpsMarketData[];
33
+ export declare function transformMarketData(hyperLiquidData: HyperLiquidMarketData, formatters: MarketDataFormatters, assetMarketTypes?: Record<string, MarketType>, assetNames?: Record<string, string>): PerpsMarketData[];
31
34
  /**
32
35
  * Format 24h change with sign.
33
36
  * Uses more decimal places for smaller amounts to show meaningful precision.
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.d.mts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;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;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAC5C,eAAe,EAAE,CA6GnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
1
+ {"version":3,"file":"marketDataTransform.d.mts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;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,CA6GnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
@@ -5,7 +5,7 @@
5
5
  * Formatters are injected via MarketDataFormatters interface.
6
6
  */
7
7
  import { hasProperty } from "@metamask/utils";
8
- import { HYPERLIQUID_CONFIG } from "../constants/hyperLiquidConfig.mjs";
8
+ import { HYPERLIQUID_CONFIG, getHyperLiquidAssetName } from "../constants/hyperLiquidConfig.mjs";
9
9
  import { PERPS_CONSTANTS } from "../constants/perpsConfig.mjs";
10
10
  import { parseAssetName } from "./hyperLiquidAdapter.mjs";
11
11
  /**
@@ -89,9 +89,12 @@ function extractFundingData(params) {
89
89
  * @param hyperLiquidData - Raw data from HyperLiquid API
90
90
  * @param formatters - Injectable formatters for platform-agnostic formatting
91
91
  * @param assetMarketTypes - Optional mapping of asset symbols to market types
92
+ * @param assetNames - Optional mapping of asset symbols to human-readable names.
93
+ * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to
94
+ * their ticker symbol.
92
95
  * @returns Transformed market data ready for UI consumption
93
96
  */
94
- export function transformMarketData(hyperLiquidData, formatters, assetMarketTypes) {
97
+ export function transformMarketData(hyperLiquidData, formatters, assetMarketTypes, assetNames) {
95
98
  const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;
96
99
  return universe.map((asset, index) => {
97
100
  const symbol = asset.name;
@@ -152,7 +155,7 @@ export function transformMarketData(hyperLiquidData, formatters, assetMarketType
152
155
  const isNewMarket = isHip3 && !explicitMarketType;
153
156
  return {
154
157
  symbol,
155
- name: symbol,
158
+ name: getHyperLiquidAssetName(symbol, assetNames),
156
159
  maxLeverage: `${asset.maxLeverage}x`,
157
160
  price: isNaN(currentPrice)
158
161
  ? PERPS_CONSTANTS.FallbackPriceDisplay
@@ -1 +1 @@
1
- {"version":3,"file":"marketDataTransform.mjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EAAE,kBAAkB,EAAE,2CAAuC;AACpE,OAAO,EAAE,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AU,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 { HYPERLIQUID_CONFIG } from '../constants/hyperLiquidConfig';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\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 * 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 * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\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 mapping only\n // Only explicitly mapped HIP-3 markets get a marketType (e.g., 'xyz:GOLD' → 'commodity')\n // Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to \"New\" tab\n // Main DEX crypto also has no marketType\n const explicitMarketType = assetMarketTypes?.[symbol];\n const marketType: MarketType | undefined = explicitMarketType;\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n // New markets are always HIP-3 (non-crypto) that haven't been assigned a category yet\n const isNewMarket = isHip3 && !explicitMarketType;\n\n return {\n symbol,\n name: symbol,\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.mjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACxB,2CAAuC;AACxC,OAAO,EAAE,eAAe,EAAE,qCAAiC;AAY3D,OAAO,EAAE,cAAc,EAAE,iCAA6B;AAEtD;;;;;;;;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,M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formatters are injected via MarketDataFormatters interface.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_CONFIG,\n getHyperLiquidAssetName,\n} from '../constants/hyperLiquidConfig';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\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 * 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 mapping only\n // Only explicitly mapped HIP-3 markets get a marketType (e.g., 'xyz:GOLD' → 'commodity')\n // Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to \"New\" tab\n // Main DEX crypto also has no marketType\n const explicitMarketType = assetMarketTypes?.[symbol];\n const marketType: MarketType | undefined = explicitMarketType;\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n // New markets are always HIP-3 (non-crypto) that haven't been assigned a category yet\n const isNewMarket = isHip3 && !explicitMarketType;\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"]}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rankMarketsByQuery = exports.getMarketMatchRank = exports.MarketMatchRank = void 0;
4
+ /**
5
+ * Relevance tier for a market/query match. Lower values sort first.
6
+ */
7
+ var MarketMatchRank;
8
+ (function (MarketMatchRank) {
9
+ MarketMatchRank[MarketMatchRank["Exact"] = 0] = "Exact";
10
+ MarketMatchRank[MarketMatchRank["Prefix"] = 1] = "Prefix";
11
+ MarketMatchRank[MarketMatchRank["Substring"] = 2] = "Substring";
12
+ })(MarketMatchRank || (exports.MarketMatchRank = MarketMatchRank = {}));
13
+ /**
14
+ * Rank a single field value against a normalized query.
15
+ *
16
+ * @param value - Field value (e.g. symbol or name); may be undefined.
17
+ * @param query - Already trimmed, lower-cased, non-empty query.
18
+ * @returns The match tier, or null when the field does not match.
19
+ */
20
+ function fieldRank(value, query) {
21
+ if (!value) {
22
+ return null;
23
+ }
24
+ const normalized = value.toLowerCase();
25
+ if (normalized === query) {
26
+ return MarketMatchRank.Exact;
27
+ }
28
+ if (normalized.startsWith(query)) {
29
+ return MarketMatchRank.Prefix;
30
+ }
31
+ if (normalized.includes(query)) {
32
+ return MarketMatchRank.Substring;
33
+ }
34
+ return null;
35
+ }
36
+ /**
37
+ * Compute the best (lowest) relevance rank for a market against a search query,
38
+ * considering both its ticker symbol and human-readable name.
39
+ *
40
+ * @param market - Market to score (uses `symbol` and `name`).
41
+ * @param searchQuery - User search text (trimmed/cased internally).
42
+ * @returns The match rank, or null when the market does not match (or the query
43
+ * is empty/whitespace).
44
+ */
45
+ function getMarketMatchRank(market, searchQuery) {
46
+ if (!searchQuery?.trim()) {
47
+ return null;
48
+ }
49
+ const query = searchQuery.toLowerCase().trim();
50
+ const ranks = [
51
+ fieldRank(market.symbol, query),
52
+ fieldRank(market.name, query),
53
+ ].filter((rank) => rank !== null);
54
+ return ranks.length > 0 ? Math.min(...ranks) : null;
55
+ }
56
+ exports.getMarketMatchRank = getMarketMatchRank;
57
+ /**
58
+ * Filter and rank markets by a search query, matching the human-readable name or
59
+ * ticker symbol. Exact matches sort first, then prefix, then substring; markets
60
+ * sharing a rank keep their input order (stable). An empty/whitespace query
61
+ * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.
62
+ *
63
+ * @param markets - Markets to search.
64
+ * @param searchQuery - User search text.
65
+ * @returns Matching markets ordered by relevance.
66
+ */
67
+ function rankMarketsByQuery(markets, searchQuery) {
68
+ if (!searchQuery?.trim()) {
69
+ return markets;
70
+ }
71
+ const query = searchQuery.toLowerCase().trim();
72
+ const matches = [];
73
+ markets.forEach((market) => {
74
+ const rank = getMarketMatchRank(market, query);
75
+ if (rank !== null) {
76
+ matches.push({ market, rank });
77
+ }
78
+ });
79
+ // Stable sort by rank only; Array.prototype.sort is stable in modern engines,
80
+ // so equal-rank markets retain their original relative order.
81
+ matches.sort((a, b) => a.rank - b.rank);
82
+ return matches.map((match) => match.market);
83
+ }
84
+ exports.rankMarketsByQuery = rankMarketsByQuery;
85
+ //# sourceMappingURL=marketSearch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marketSearch.cjs","sourceRoot":"","s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,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACtD,CAAC;AAdD,gDAcC;AAED;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAChC,OAA0B,EAC1B,WAAmB;IAEnB,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,MAAM,KAAK,GAAG,WAAW,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC;IAE/C,MAAM,OAAO,GAAyD,EAAE,CAAC;IACzE,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QACzB,MAAM,IAAI,GAAG,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC/C,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAClB,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,8EAA8E;IAC9E,8DAA8D;IAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9C,CAAC;AArBD,gDAqBC","sourcesContent":["/**\n * Market search ranking (TAT-2413).\n *\n * Provisional, standalone helper layered on the same match semantics as\n * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol\n * and human-readable name). It adds the one thing `filterMarketsByQuery` does\n * not: relevance ranking — exact matches first, then prefix, then substring;\n * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope\n * for v1).\n *\n * Kept in its own file so it can be promoted or relocated later without touching\n * the shared `marketUtils`. A market matches here (rank !== null) iff\n * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.\n *\n * Portable: no platform-specific imports.\n */\nimport type { PerpsMarketData } from '../types';\n\n/**\n * Relevance tier for a market/query match. Lower values sort first.\n */\nexport enum MarketMatchRank {\n Exact = 0,\n Prefix = 1,\n Substring = 2,\n}\n\n/**\n * Rank a single field value against a normalized query.\n *\n * @param value - Field value (e.g. symbol or name); may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The match tier, or null when the field does not match.\n */\nfunction fieldRank(\n value: string | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!value) {\n return null;\n }\n const normalized = value.toLowerCase();\n if (normalized === query) {\n return MarketMatchRank.Exact;\n }\n if (normalized.startsWith(query)) {\n return MarketMatchRank.Prefix;\n }\n if (normalized.includes(query)) {\n return MarketMatchRank.Substring;\n }\n return null;\n}\n\n/**\n * Compute the best (lowest) relevance rank for a market against a search query,\n * considering both its ticker symbol and human-readable name.\n *\n * @param market - Market to score (uses `symbol` and `name`).\n * @param searchQuery - User search text (trimmed/cased internally).\n * @returns The match rank, or null when the market does not match (or the query\n * is empty/whitespace).\n */\nexport function getMarketMatchRank(\n market: Pick<PerpsMarketData, 'symbol' | 'name'>,\n searchQuery: string,\n): MarketMatchRank | null {\n if (!searchQuery?.trim()) {\n return null;\n }\n const query = searchQuery.toLowerCase().trim();\n const ranks = [\n fieldRank(market.symbol, query),\n fieldRank(market.name, query),\n ].filter((rank): rank is MarketMatchRank => rank !== null);\n\n return ranks.length > 0 ? Math.min(...ranks) : null;\n}\n\n/**\n * Filter and rank markets by a search query, matching the human-readable name or\n * ticker symbol. Exact matches sort first, then prefix, then substring; markets\n * sharing a rank keep their input order (stable). An empty/whitespace query\n * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.\n *\n * @param markets - Markets to search.\n * @param searchQuery - User search text.\n * @returns Matching markets ordered by relevance.\n */\nexport function rankMarketsByQuery(\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] {\n if (!searchQuery?.trim()) {\n return markets;\n }\n const query = searchQuery.toLowerCase().trim();\n\n const matches: { market: PerpsMarketData; rank: MarketMatchRank }[] = [];\n markets.forEach((market) => {\n const rank = getMarketMatchRank(market, query);\n if (rank !== null) {\n matches.push({ market, rank });\n }\n });\n\n // Stable sort by rank only; Array.prototype.sort is stable in modern engines,\n // so equal-rank markets retain their original relative order.\n matches.sort((a, b) => a.rank - b.rank);\n return matches.map((match) => match.market);\n}\n"]}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Market search ranking (TAT-2413).
3
+ *
4
+ * Provisional, standalone helper layered on the same match semantics as
5
+ * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol
6
+ * and human-readable name). It adds the one thing `filterMarketsByQuery` does
7
+ * not: relevance ranking — exact matches first, then prefix, then substring;
8
+ * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope
9
+ * for v1).
10
+ *
11
+ * Kept in its own file so it can be promoted or relocated later without touching
12
+ * the shared `marketUtils`. A market matches here (rank !== null) iff
13
+ * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.
14
+ *
15
+ * Portable: no platform-specific imports.
16
+ */
17
+ import type { PerpsMarketData } from "../types/index.cjs";
18
+ /**
19
+ * Relevance tier for a market/query match. Lower values sort first.
20
+ */
21
+ export declare enum MarketMatchRank {
22
+ Exact = 0,
23
+ Prefix = 1,
24
+ Substring = 2
25
+ }
26
+ /**
27
+ * Compute the best (lowest) relevance rank for a market against a search query,
28
+ * considering both its ticker symbol and human-readable name.
29
+ *
30
+ * @param market - Market to score (uses `symbol` and `name`).
31
+ * @param searchQuery - User search text (trimmed/cased internally).
32
+ * @returns The match rank, or null when the market does not match (or the query
33
+ * is empty/whitespace).
34
+ */
35
+ export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name'>, searchQuery: string): MarketMatchRank | null;
36
+ /**
37
+ * Filter and rank markets by a search query, matching the human-readable name or
38
+ * ticker symbol. Exact matches sort first, then prefix, then substring; markets
39
+ * sharing a rank keep their input order (stable). An empty/whitespace query
40
+ * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.
41
+ *
42
+ * @param markets - Markets to search.
43
+ * @param searchQuery - User search text.
44
+ * @returns Matching markets ordered by relevance.
45
+ */
46
+ export declare function rankMarketsByQuery(markets: PerpsMarketData[], searchQuery: string): PerpsMarketData[];
47
+ //# sourceMappingURL=marketSearch.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marketSearch.d.cts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;AA6BD;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,MAAM,CAAC,EAChD,WAAW,EAAE,MAAM,GAClB,eAAe,GAAG,IAAI,CAWxB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,eAAe,EAAE,EAC1B,WAAW,EAAE,MAAM,GAClB,eAAe,EAAE,CAkBnB"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Market search ranking (TAT-2413).
3
+ *
4
+ * Provisional, standalone helper layered on the same match semantics as
5
+ * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol
6
+ * and human-readable name). It adds the one thing `filterMarketsByQuery` does
7
+ * not: relevance ranking — exact matches first, then prefix, then substring;
8
+ * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope
9
+ * for v1).
10
+ *
11
+ * Kept in its own file so it can be promoted or relocated later without touching
12
+ * the shared `marketUtils`. A market matches here (rank !== null) iff
13
+ * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.
14
+ *
15
+ * Portable: no platform-specific imports.
16
+ */
17
+ import type { PerpsMarketData } from "../types/index.mjs";
18
+ /**
19
+ * Relevance tier for a market/query match. Lower values sort first.
20
+ */
21
+ export declare enum MarketMatchRank {
22
+ Exact = 0,
23
+ Prefix = 1,
24
+ Substring = 2
25
+ }
26
+ /**
27
+ * Compute the best (lowest) relevance rank for a market against a search query,
28
+ * considering both its ticker symbol and human-readable name.
29
+ *
30
+ * @param market - Market to score (uses `symbol` and `name`).
31
+ * @param searchQuery - User search text (trimmed/cased internally).
32
+ * @returns The match rank, or null when the market does not match (or the query
33
+ * is empty/whitespace).
34
+ */
35
+ export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name'>, searchQuery: string): MarketMatchRank | null;
36
+ /**
37
+ * Filter and rank markets by a search query, matching the human-readable name or
38
+ * ticker symbol. Exact matches sort first, then prefix, then substring; markets
39
+ * sharing a rank keep their input order (stable). An empty/whitespace query
40
+ * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.
41
+ *
42
+ * @param markets - Markets to search.
43
+ * @param searchQuery - User search text.
44
+ * @returns Matching markets ordered by relevance.
45
+ */
46
+ export declare function rankMarketsByQuery(markets: PerpsMarketData[], searchQuery: string): PerpsMarketData[];
47
+ //# sourceMappingURL=marketSearch.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marketSearch.d.mts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;AA6BD;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,MAAM,CAAC,EAChD,WAAW,EAAE,MAAM,GAClB,eAAe,GAAG,IAAI,CAWxB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,eAAe,EAAE,EAC1B,WAAW,EAAE,MAAM,GAClB,eAAe,EAAE,CAkBnB"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Relevance tier for a market/query match. Lower values sort first.
3
+ */
4
+ export var MarketMatchRank;
5
+ (function (MarketMatchRank) {
6
+ MarketMatchRank[MarketMatchRank["Exact"] = 0] = "Exact";
7
+ MarketMatchRank[MarketMatchRank["Prefix"] = 1] = "Prefix";
8
+ MarketMatchRank[MarketMatchRank["Substring"] = 2] = "Substring";
9
+ })(MarketMatchRank || (MarketMatchRank = {}));
10
+ /**
11
+ * Rank a single field value against a normalized query.
12
+ *
13
+ * @param value - Field value (e.g. symbol or name); may be undefined.
14
+ * @param query - Already trimmed, lower-cased, non-empty query.
15
+ * @returns The match tier, or null when the field does not match.
16
+ */
17
+ function fieldRank(value, query) {
18
+ if (!value) {
19
+ return null;
20
+ }
21
+ const normalized = value.toLowerCase();
22
+ if (normalized === query) {
23
+ return MarketMatchRank.Exact;
24
+ }
25
+ if (normalized.startsWith(query)) {
26
+ return MarketMatchRank.Prefix;
27
+ }
28
+ if (normalized.includes(query)) {
29
+ return MarketMatchRank.Substring;
30
+ }
31
+ return null;
32
+ }
33
+ /**
34
+ * Compute the best (lowest) relevance rank for a market against a search query,
35
+ * considering both its ticker symbol and human-readable name.
36
+ *
37
+ * @param market - Market to score (uses `symbol` and `name`).
38
+ * @param searchQuery - User search text (trimmed/cased internally).
39
+ * @returns The match rank, or null when the market does not match (or the query
40
+ * is empty/whitespace).
41
+ */
42
+ export function getMarketMatchRank(market, searchQuery) {
43
+ if (!searchQuery?.trim()) {
44
+ return null;
45
+ }
46
+ const query = searchQuery.toLowerCase().trim();
47
+ const ranks = [
48
+ fieldRank(market.symbol, query),
49
+ fieldRank(market.name, query),
50
+ ].filter((rank) => rank !== null);
51
+ return ranks.length > 0 ? Math.min(...ranks) : null;
52
+ }
53
+ /**
54
+ * Filter and rank markets by a search query, matching the human-readable name or
55
+ * ticker symbol. Exact matches sort first, then prefix, then substring; markets
56
+ * sharing a rank keep their input order (stable). An empty/whitespace query
57
+ * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.
58
+ *
59
+ * @param markets - Markets to search.
60
+ * @param searchQuery - User search text.
61
+ * @returns Matching markets ordered by relevance.
62
+ */
63
+ export function rankMarketsByQuery(markets, searchQuery) {
64
+ if (!searchQuery?.trim()) {
65
+ return markets;
66
+ }
67
+ const query = searchQuery.toLowerCase().trim();
68
+ const matches = [];
69
+ markets.forEach((market) => {
70
+ const rank = getMarketMatchRank(market, query);
71
+ if (rank !== null) {
72
+ matches.push({ market, rank });
73
+ }
74
+ });
75
+ // Stable sort by rank only; Array.prototype.sort is stable in modern engines,
76
+ // so equal-rank markets retain their original relative order.
77
+ matches.sort((a, b) => a.rank - b.rank);
78
+ return matches.map((match) => match.market);
79
+ }
80
+ //# sourceMappingURL=marketSearch.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marketSearch.mjs","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,uDAAS,CAAA;IACT,yDAAU,CAAA;IACV,+DAAa,CAAA;AACf,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAChB,KAAyB,EACzB,KAAa;IAEb,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IACvC,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;QACzB,OAAO,eAAe,CAAC,KAAK,CAAC;IAC/B,CAAC;IACD,IAAI,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,eAAe,CAAC,MAAM,CAAC;IAChC,CAAC;IACD,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,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C;IAEH,8EAA8E;IAC9E,8DAA8D;IAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["/**\n * Market search ranking (TAT-2413).\n *\n * Provisional, standalone helper layered on the same match semantics as\n * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol\n * and human-readable name). It adds the one thing `filterMarketsByQuery` does\n * not: relevance ranking — exact matches first, then prefix, then substring;\n * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope\n * for v1).\n *\n * Kept in its own file so it can be promoted or relocated later without touching\n * the shared `marketUtils`. A market matches here (rank !== null) iff\n * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.\n *\n * Portable: no platform-specific imports.\n */\nimport type { PerpsMarketData } from '../types';\n\n/**\n * Relevance tier for a market/query match. Lower values sort first.\n */\nexport enum MarketMatchRank {\n Exact = 0,\n Prefix = 1,\n Substring = 2,\n}\n\n/**\n * Rank a single field value against a normalized query.\n *\n * @param value - Field value (e.g. symbol or name); may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The match tier, or null when the field does not match.\n */\nfunction fieldRank(\n value: string | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!value) {\n return null;\n }\n const normalized = value.toLowerCase();\n if (normalized === query) {\n return MarketMatchRank.Exact;\n }\n if (normalized.startsWith(query)) {\n return MarketMatchRank.Prefix;\n }\n if (normalized.includes(query)) {\n return MarketMatchRank.Substring;\n }\n return null;\n}\n\n/**\n * Compute the best (lowest) relevance rank for a market against a search query,\n * considering both its ticker symbol and human-readable name.\n *\n * @param market - Market to score (uses `symbol` and `name`).\n * @param searchQuery - User search text (trimmed/cased internally).\n * @returns The match rank, or null when the market does not match (or the query\n * is empty/whitespace).\n */\nexport function getMarketMatchRank(\n market: Pick<PerpsMarketData, 'symbol' | 'name'>,\n searchQuery: string,\n): MarketMatchRank | null {\n if (!searchQuery?.trim()) {\n return null;\n }\n const query = searchQuery.toLowerCase().trim();\n const ranks = [\n fieldRank(market.symbol, query),\n fieldRank(market.name, query),\n ].filter((rank): rank is MarketMatchRank => rank !== null);\n\n return ranks.length > 0 ? Math.min(...ranks) : null;\n}\n\n/**\n * Filter and rank markets by a search query, matching the human-readable name or\n * ticker symbol. Exact matches sort first, then prefix, then substring; markets\n * sharing a rank keep their input order (stable). An empty/whitespace query\n * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.\n *\n * @param markets - Markets to search.\n * @param searchQuery - User search text.\n * @returns Matching markets ordered by relevance.\n */\nexport function rankMarketsByQuery(\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] {\n if (!searchQuery?.trim()) {\n return markets;\n }\n const query = searchQuery.toLowerCase().trim();\n\n const matches: { market: PerpsMarketData; rank: MarketMatchRank }[] = [];\n markets.forEach((market) => {\n const rank = getMarketMatchRank(market, query);\n if (rank !== null) {\n matches.push({ market, rank });\n }\n });\n\n // Stable sort by rank only; Array.prototype.sort is stable in modern engines,\n // so equal-rank markets retain their original relative order.\n matches.sort((a, b) => a.rank - b.rank);\n return matches.map((match) => match.market);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/perps-controller",
3
- "version": "8.0.0-preview-51b287c55",
3
+ "version": "8.1.0-preview-3af52b79c",
4
4
  "description": "Controller for perpetual trading functionality in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -100,7 +100,7 @@
100
100
  "@metamask/base-controller": "^9.1.0",
101
101
  "@metamask/controller-utils": "^12.2.0",
102
102
  "@metamask/messenger": "^1.2.0",
103
- "@metamask/utils": "^11.9.0",
103
+ "@metamask/utils": "^11.11.0",
104
104
  "@nktkas/hyperliquid": "^0.32.2",
105
105
  "bignumber.js": "^9.1.2",
106
106
  "reselect": "^5.1.1",