@metamask-previews/perps-controller 25.0.0-preview-2be370e → 25.0.0-preview-c785ff081

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 (64) hide show
  1. package/CHANGELOG.md +14 -6
  2. package/dist/PerpsController.d.ts.map +1 -1
  3. package/dist/PerpsController.js +71 -8
  4. package/dist/PerpsController.js.map +1 -1
  5. package/dist/constants/eventNames.d.ts +6 -9
  6. package/dist/constants/eventNames.d.ts.map +1 -1
  7. package/dist/constants/eventNames.js +9 -11
  8. package/dist/constants/eventNames.js.map +1 -1
  9. package/dist/constants/perpsConfig.d.ts +8 -1
  10. package/dist/constants/perpsConfig.d.ts.map +1 -1
  11. package/dist/constants/perpsConfig.js +8 -2
  12. package/dist/constants/perpsConfig.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  18. package/dist/providers/HyperLiquidProvider.js +2 -2
  19. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  20. package/dist/providers/LighterProvider.d.ts.map +1 -1
  21. package/dist/providers/LighterProvider.js +8 -6
  22. package/dist/providers/LighterProvider.js.map +1 -1
  23. package/dist/selectors.d.ts +15 -5
  24. package/dist/selectors.d.ts.map +1 -1
  25. package/dist/selectors.js +23 -5
  26. package/dist/selectors.js.map +1 -1
  27. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
  28. package/dist/services/AggregatedOrderBookConnection.js +8 -10
  29. package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
  30. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  31. package/dist/services/HyperLiquidSubscriptionService.js +20 -13
  32. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  33. package/dist/services/MarketDataService.d.ts +5 -2
  34. package/dist/services/MarketDataService.d.ts.map +1 -1
  35. package/dist/services/MarketDataService.js +12 -2
  36. package/dist/services/MarketDataService.js.map +1 -1
  37. package/dist/types/index.d.ts +4 -3
  38. package/dist/types/index.d.ts.map +1 -1
  39. package/dist/types/index.js.map +1 -1
  40. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  41. package/dist/utils/hyperLiquidAdapter.js +2 -13
  42. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  43. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  44. package/dist/utils/marketDataTransform.js +5 -8
  45. package/dist/utils/marketDataTransform.js.map +1 -1
  46. package/dist/utils/marketUtils.d.ts +9 -0
  47. package/dist/utils/marketUtils.d.ts.map +1 -1
  48. package/dist/utils/marketUtils.js +12 -0
  49. package/dist/utils/marketUtils.js.map +1 -1
  50. package/dist/utils/priceDeviation.d.ts +9 -6
  51. package/dist/utils/priceDeviation.d.ts.map +1 -1
  52. package/dist/utils/priceDeviation.js +17 -26
  53. package/dist/utils/priceDeviation.js.map +1 -1
  54. package/dist/utils/pricePrecision.d.ts +14 -2
  55. package/dist/utils/pricePrecision.d.ts.map +1 -1
  56. package/dist/utils/pricePrecision.js +31 -10
  57. package/dist/utils/pricePrecision.js.map +1 -1
  58. package/docs/architecture.md +17 -17
  59. package/docs/client-contract.md +14 -10
  60. package/docs/contracts/events.md +4 -2
  61. package/docs/contracts/feature-flags.md +4 -4
  62. package/docs/venues/hyperliquid/trading-rules.md +2 -2
  63. package/docs/venues/lighter/capabilities.md +1 -1
  64. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,0BAA0B,EAC1B,sBAAsB,EACtB,YAAY,EACZ,cAAc,EACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,YAAY,EAEZ,UAAU,EACV,KAAK,EACL,WAAW,I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AAE;IAC5C,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,MAAM,CAeT;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAC5C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,MAAM,CAGT;AAED,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,GAClB,MAAM,CASR;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,GAAG,MAAM,GAAG,SAAS,CAKrB;AAED,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG;IACjD,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB,CASA;AAED,wBAAgB,6CAA6C,CAC3D,gBAAgB,EAAE,eAAe,EAAE,GAClC,eAAe,EAAE,CAkDnB;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,SAAS,sBAAsB,EAAE,EACzC,MAAM,EAAE,MAAM,GACb,WAAW,EAAE,CA4Bf"}
@@ -4,8 +4,8 @@ import { BASIS_POINTS_DIVISOR, HIP3_ASSET_ID_CONFIG, isUnrestrictedMarginMode, }
4
4
  import { DECIMAL_PRECISION_CONFIG, ORDER_SLIPPAGE_CONFIG, } from '../constants/perpsConfig.js';
5
5
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
6
6
  import { buildTriggerOrderType, classifyTriggerDirection, getTriggerDirection, getTriggerExecution, isLimitExecutionOrderType, isTriggerOrderType, toSDKTimeInForce, } from './orderTypes.js';
7
+ import { roundToSignificantFiguresGrid } from './pricePrecision.js';
7
8
  import { buildPublicTrade, sortPublicTradesNewestFirst, } from './publicTrades.js';
8
- import { countSignificantFigures, roundToSignificantFigures, } from './significantFigures.js';
9
9
  import { parseFiniteDecimal } from './stringParseUtils.js';
10
10
  export const HYPERLIQUID_SCALE_CLOID_MARKER = '4d4d5343';
11
11
  /**
@@ -468,18 +468,7 @@ export function buildAssetMapping(params) {
468
468
  }
469
469
  export function formatHyperLiquidPrice(params) {
470
470
  const { price, szDecimals } = params;
471
- const priceNum = typeof price === 'string' ? parseFloat(price) : price;
472
- if (Number.isInteger(priceNum)) {
473
- return priceNum.toString();
474
- }
475
- const maxDecimalPlaces = DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals;
476
- let formattedPrice = priceNum.toFixed(maxDecimalPlaces);
477
- formattedPrice = parseFloat(formattedPrice).toString();
478
- const significantDigits = countSignificantFigures(formattedPrice);
479
- if (significantDigits > DECIMAL_PRECISION_CONFIG.MaxSignificantFigures) {
480
- formattedPrice = roundToSignificantFigures(formattedPrice);
481
- }
482
- return formattedPrice;
471
+ return roundToSignificantFiguresGrid(price, DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals, DECIMAL_PRECISION_CONFIG.MaxSignificantFigures);
483
472
  }
484
473
  export function formatHyperLiquidSize(params) {
485
474
  const { size, szDecimals } = params;
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidAdapter.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAO,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iB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AAQ;gBAC9B,CAAC,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;gBACrC,CAAC,CAAC,KAAK,CAAC,IAAI;gBACZ,CAAC,CAAC,SAAS;YACf,UAAU,EAAE,aAAa;SAC1B,CAAC,CAAC;QACH,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IACD,OAAO,2BAA2B,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { hasProperty, Hex, isHexString } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\n isUnrestrictedMarginMode,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n DECIMAL_PRECISION_CONFIG,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n AssetPosition,\n FrontendOrder,\n ClearinghouseStateResponse,\n HyperLiquidPublicTrade,\n MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\n PublicTrade,\n RawLedgerUpdate,\n UserHistoryItem,\n} from '../types/index.js';\nimport type { TpslLinkage, TriggerOrderType } from '../types/perps-types.js';\nimport {\n buildTriggerOrderType,\n classifyTriggerDirection,\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n toSDKTimeInForce,\n} from './orderTypes.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\nimport {\n countSignificantFigures,\n roundToSignificantFigures,\n} from './significantFigures.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\ntype FrontendOrderWithParentTpsl = FrontendOrder & {\n takeProfitPrice?: unknown;\n stopLossPrice?: unknown;\n takeProfitOrderId?: unknown;\n stopLossOrderId?: unknown;\n};\n\nexport const HYPERLIQUID_SCALE_CLOID_MARKER = '4d4d5343';\n\n/**\n * Recover the Scale group shared by MetaMask-generated rung CLOIDs.\n *\n * @param clientOrderId - HyperLiquid client order ID.\n * @returns The Scale handle, or undefined for an unrelated order.\n */\nexport const readScaleGroupId = (\n clientOrderId: string | null | undefined,\n): string | undefined => {\n const normalized = clientOrderId?.toLowerCase();\n if (\n normalized?.length !== 34 ||\n !normalized.startsWith(`0x${HYPERLIQUID_SCALE_CLOID_MARKER}`)\n ) {\n return undefined;\n }\n return `scale:${normalized.slice(2, -2)}`;\n};\n\nconst readOptionalString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst readOptionalOrderId = (value: unknown): string | undefined => {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value.toString();\n }\n\n return undefined;\n};\n\nconst getParentTpslMetadata = (\n rawOrder: FrontendOrderWithParentTpsl,\n): {\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitOrderId?: string;\n stopLossOrderId?: string;\n} => ({\n takeProfitPrice: readOptionalString(rawOrder.takeProfitPrice),\n stopLossPrice: readOptionalString(rawOrder.stopLossPrice),\n takeProfitOrderId: readOptionalOrderId(rawOrder.takeProfitOrderId),\n stopLossOrderId: readOptionalOrderId(rawOrder.stopLossOrderId),\n});\n\n/**\n * HyperLiquid SDK Adapter Utilities\n *\n * These functions transform between MetaMask Perps API types and HyperLiquid SDK types.\n * The SDK uses cryptic property names for efficiency, but our API uses descriptive names\n * to provide a consistent interface across different perps protocols.\n */\n\nexport function adaptOrderToSDK(\n order: PerpsOrderParams,\n symbolToAssetId: Map<string, number>,\n): SDKOrderParams {\n const assetId = symbolToAssetId.get(order.symbol);\n if (assetId === undefined) {\n const availableDexs = new Set<string>();\n symbolToAssetId.forEach((_, symbol) => {\n if (symbol.includes(':')) {\n const dex = symbol.split(':')[0];\n availableDexs.add(dex);\n }\n });\n\n const dexHint =\n availableDexs.size > 0\n ? ` Available HIP-3 DEXs: ${Array.from(availableDexs).join(', ')}`\n : ' No HIP-3 DEXs currently available.';\n\n throw new Error(\n `Asset ${order.symbol} not found in asset mapping.${dexHint} Check console logs for \"HyperLiquidProvider: Asset mapping built\" to see available assets.`,\n );\n }\n\n return {\n a: assetId,\n b: order.isBuy,\n p: order.price ?? resolveTriggerCapPrice(order) ?? '0',\n s: order.size,\n r: order.reduceOnly ?? false,\n t: adaptOrderTypeToSDK(order),\n c:\n order.clientOrderId && isHexString(order.clientOrderId)\n ? order.clientOrderId\n : undefined,\n };\n}\n\n/**\n * Derive the slippage cap a market-on-trigger order submits as its price.\n *\n * A `stop_market` / `take_profit_market` order legitimately carries no limit\n * price, but the SDK still requires a positive `p` — it is the cap the order\n * fills against once the trigger fires, not a resting price. Sending `'0'`\n * fails SDK validation before the request is ever made.\n *\n * The cap follows the order's own tolerance, matching `calculateOrderPriceAndSize`\n * on the `placeOrder` path, so the same order priced through either route gets\n * the same execution bound.\n *\n * @param order - Order params carrying the placement type, trigger price, and\n * slippage tolerance.\n * @returns The formatted cap price, or undefined when the order needs no cap.\n */\nfunction resolveTriggerCapPrice(order: PerpsOrderParams): string | undefined {\n if (\n !isTriggerOrderType(order.orderType) ||\n isLimitExecutionOrderType(order.orderType) ||\n !order.triggerPrice\n ) {\n return undefined;\n }\n\n const triggerPrice = parseFloat(order.triggerPrice);\n if (!Number.isFinite(triggerPrice)) {\n return undefined;\n }\n\n // Accept the deprecated decimal `slippage` too, normalizing it to bps the way\n // `placeOrder` does, so neither spelling silently falls back to the default.\n const effectiveBps =\n order.maxSlippageBps ??\n (typeof order.slippage === 'number'\n ? Math.round(order.slippage * BASIS_POINTS_DIVISOR)\n : undefined) ??\n ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n\n // Buying pays up to the cap, selling accepts down to it.\n const slippage = effectiveBps / BASIS_POINTS_DIVISOR;\n const capPrice = order.isBuy\n ? triggerPrice * (1 + slippage)\n : triggerPrice * (1 - slippage);\n\n return capPrice.toString();\n}\n\n/**\n * Map a placement type onto the SDK's order-type field.\n *\n * @param order - Order params carrying the placement type and trigger price\n * @returns The SDK order-type field\n */\nfunction adaptOrderTypeToSDK(order: PerpsOrderParams): SDKOrderParams['t'] {\n if (isTriggerOrderType(order.orderType)) {\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n if (!order.triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(order.orderType),\n triggerPx: order.triggerPrice,\n tpsl: getTriggerDirection(order.orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n }\n\n if (order.orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(order.timeInForce) } };\n }\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n}\n\n/**\n * Map the provider-agnostic TP/SL linkage onto HyperLiquid's grouping vocabulary.\n *\n * @param linkage - How the attached TP/SL is linked.\n * @returns The HyperLiquid grouping value.\n */\nexport function adaptTpslLinkageToGrouping(\n linkage: TpslLinkage,\n): 'na' | 'normalTpsl' | 'positionTpsl' {\n switch (linkage) {\n case 'position':\n return 'positionTpsl';\n case 'order':\n return 'normalTpsl';\n default:\n return 'na';\n }\n}\n\n/**\n * Margin Hyperliquid shows for a cross position. When cross equity is below\n * the cross initial margin, the venue scales each cross position's margin by\n * `accountValue / totalMarginUsed`.\n *\n * @param marginUsed - The position's raw margin used.\n * @param crossMarginSummary - The clearinghouse's cross margin summary.\n * @returns The displayed margin, or undefined when an input is not a number.\n */\nfunction deriveCrossDisplayMarginUsed(\n marginUsed: string,\n crossMarginSummary: ClearinghouseStateResponse['crossMarginSummary'],\n): string | undefined {\n const margin = new BigNumber(marginUsed);\n const accountValue = new BigNumber(crossMarginSummary.accountValue);\n const totalMarginUsed = new BigNumber(crossMarginSummary.totalMarginUsed);\n if (\n !margin.isFinite() ||\n !accountValue.isFinite() ||\n !totalMarginUsed.isFinite()\n ) {\n return undefined;\n }\n if (totalMarginUsed.lte(0) || accountValue.gte(totalMarginUsed)) {\n return margin.toFixed();\n }\n return BigNumber.max(\n margin.times(accountValue).div(totalMarginUsed),\n 0,\n ).toFixed();\n}\n\n/**\n * Adapt a Hyperliquid asset position.\n *\n * @param assetPosition - Position from a clearinghouse state.\n * @param crossMarginSummary - That clearinghouse's `crossMarginSummary`. When\n * given, a cross position also carries `displayMarginUsed`.\n * @returns The position.\n */\nexport function adaptPositionFromSDK(\n assetPosition: AssetPosition,\n crossMarginSummary?: ClearinghouseStateResponse['crossMarginSummary'],\n): Position {\n const pos = assetPosition.position;\n const displayMarginUsed =\n pos.leverage.type === 'cross' && crossMarginSummary\n ? deriveCrossDisplayMarginUsed(pos.marginUsed, crossMarginSummary)\n : undefined;\n return {\n symbol: pos.coin,\n size: pos.szi,\n entryPrice: pos.entryPx,\n positionValue: pos.positionValue,\n unrealizedPnl: pos.unrealizedPnl,\n marginUsed: pos.marginUsed,\n ...(displayMarginUsed !== undefined && { displayMarginUsed }),\n leverage: {\n type: pos.leverage.type,\n value: pos.leverage.value,\n rawUsd:\n pos.leverage.type === 'isolated' ? pos.leverage.rawUsd : undefined,\n },\n liquidationPrice: pos.liquidationPx,\n maxLeverage: pos.maxLeverage,\n returnOnEquity: pos.returnOnEquity,\n cumulativeFunding: pos.cumFunding,\n takeProfitCount: 0,\n stopLossCount: 0,\n };\n}\n\nexport function adaptOrderFromSDK(\n rawOrder: FrontendOrder,\n position?: Position,\n): Order {\n // TODO: Remove this widened boundary type when FrontendOrder includes\n // takeProfitPrice/stopLossPrice and takeProfitOrderId/stopLossOrderId.\n const parentTpslMetadata = getParentTpslMetadata(rawOrder);\n\n // Extract basic fields with appropriate conversions\n const orderId = rawOrder.oid?.toString() || '';\n const symbol = rawOrder.coin;\n const side: 'buy' | 'sell' = rawOrder.side === 'B' ? 'buy' : 'sell';\n const detailedOrderType = rawOrder.orderType;\n const { isTrigger } = rawOrder;\n const { reduceOnly } = rawOrder;\n\n const triggerOrderType = adaptTriggerOrderTypeFromSDK(detailedOrderType);\n\n let orderType: 'limit' | 'market' = 'market';\n if (triggerOrderType) {\n // Trigger orders always carry a limitPx (the slippage cap for\n // market-on-trigger execution), so the placement type is the only reliable\n // source for how the order actually executes.\n orderType = getTriggerExecution(triggerOrderType);\n } else if (\n detailedOrderType?.toLowerCase().includes('limit') ||\n rawOrder.limitPx\n ) {\n orderType = 'limit';\n }\n\n const price = rawOrder.limitPx || rawOrder.triggerPx || '0';\n\n let size = rawOrder.sz;\n let originalSize = rawOrder.origSz || size;\n\n let currentSize = parseFloat(size);\n let origSize = parseFloat(originalSize);\n\n if (rawOrder.isPositionTpsl && origSize === 0 && position) {\n const absPositionSize = Math.abs(parseFloat(position.size));\n currentSize = absPositionSize;\n origSize = absPositionSize;\n size = absPositionSize.toString();\n originalSize = absPositionSize.toString();\n }\n\n const filledSize = origSize - currentSize;\n\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n let takeProfitOrderId: string | undefined;\n let stopLossOrderId: string | undefined;\n\n // TODO: We assume that there can only be 1 TP and 1 SL as children but there can be several TPSLs as children\n if (rawOrder.children && rawOrder.children.length > 0) {\n rawOrder.children.forEach((child) => {\n if (child.isTrigger && child.orderType) {\n if (child.orderType.includes('Take Profit')) {\n // HyperLiquid represents \"no trigger price\" as an empty string, not\n // null/undefined, so `||` (not `??`) is required to fall back to\n // limitPx when triggerPx is ''.\n takeProfitPrice = child.triggerPx || child.limitPx;\n takeProfitOrderId = child.oid.toString();\n } else if (child.orderType.includes('Stop')) {\n stopLossPrice = child.triggerPx || child.limitPx;\n stopLossOrderId = child.oid.toString();\n }\n }\n });\n }\n\n // Fallback: preserve parent-level TP/SL metadata when children are absent.\n takeProfitPrice ??= parentTpslMetadata.takeProfitPrice;\n stopLossPrice ??= parentTpslMetadata.stopLossPrice;\n takeProfitOrderId ??= parentTpslMetadata.takeProfitOrderId;\n stopLossOrderId ??= parentTpslMetadata.stopLossOrderId;\n\n // Build the order object\n const order: Order = {\n orderId,\n symbol,\n side,\n orderType,\n size,\n originalSize,\n price,\n filledSize: filledSize.toString(),\n remainingSize: size,\n status: 'open' as const,\n timestamp: rawOrder.timestamp,\n detailedOrderType,\n isTrigger,\n reduceOnly,\n };\n\n const strategyGroupId = readScaleGroupId(rawOrder.cloid);\n if (strategyGroupId) {\n order.strategyGroupId = strategyGroupId;\n }\n\n if (typeof rawOrder.isPositionTpsl === 'boolean') {\n order.isPositionTpsl = rawOrder.isPositionTpsl;\n }\n\n if (takeProfitPrice) {\n order.takeProfitPrice = takeProfitPrice;\n order.takeProfitOrderId = takeProfitOrderId;\n }\n if (stopLossPrice) {\n order.stopLossPrice = stopLossPrice;\n order.stopLossOrderId = stopLossOrderId;\n }\n if (rawOrder.triggerPx) {\n order.triggerPrice = rawOrder.triggerPx;\n }\n\n if (triggerOrderType) {\n order.triggerOrderType = triggerOrderType;\n }\n\n return order;\n}\n\n/**\n * Map HyperLiquid's human-readable order type string onto the provider-agnostic\n * trigger placement type.\n *\n * @param detailedOrderType - HyperLiquid `orderType` string (e.g. `'Stop Limit'`)\n * @returns The normalized trigger placement type, or undefined for non-trigger orders\n */\nexport function adaptTriggerOrderTypeFromSDK(\n detailedOrderType: string | undefined,\n): TriggerOrderType | undefined {\n if (!detailedOrderType) {\n return undefined;\n }\n\n const isTakeProfit = detailedOrderType.includes('Take Profit');\n const isStop = detailedOrderType.includes('Stop');\n\n if (!isTakeProfit && !isStop) {\n return undefined;\n }\n\n return buildTriggerOrderType({\n direction: isTakeProfit ? 'take_profit' : 'stop',\n execution: detailedOrderType.includes('Limit') ? 'limit' : 'market',\n });\n}\n\n/**\n * Build the position-state view of a trigger order attached to a position.\n *\n * HyperLiquid encodes \"the whole position\" as size `0` for position-bound TP/SL,\n * which is resolved here against the position size so consumers always see a\n * concrete quantity and can tell partial triggers apart.\n *\n * @param params - Mapping parameters\n * @param params.rawOrder - Raw HyperLiquid frontend order\n * @param params.positionSize - Signed or unsigned position size\n * @param params.entryPrice - Entry price, used to classify a trigger the exchange left unnamed\n * @returns The normalized trigger order, or undefined when the order is not a trigger\n */\nexport function adaptPositionTriggerOrderFromSDK(params: {\n rawOrder: Pick<\n FrontendOrder,\n 'oid' | 'orderType' | 'triggerPx' | 'limitPx' | 'sz' | 'reduceOnly'\n >;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { rawOrder, positionSize, entryPrice } = params;\n\n const orderType = adaptTriggerOrderTypeFromSDK(rawOrder.orderType);\n\n // HyperLiquid uses '' for \"no trigger price\", so `||` (not `??`) is required.\n const triggerPrice = rawOrder.triggerPx || rawOrder.limitPx || '0';\n\n // Same rule as the WebSocket path: an unnamed trigger keeps its recoverable\n // direction and leaves its execution mode unstated, so both transports\n // report the same set of orders.\n const direction = orderType\n ? getTriggerDirection(orderType)\n : classifyTriggerDirection({ triggerPrice, entryPrice, positionSize });\n\n if (!direction) {\n return undefined;\n }\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(rawOrder.sz || '0'));\n\n // Position-bound TP/SL carries size 0, meaning the whole position.\n const size = rawSize > 0 ? rawSize : absolutePositionSize;\n\n return {\n orderId: rawOrder.oid.toString(),\n direction,\n orderType,\n triggerPrice,\n size: size.toString(),\n isPartial:\n rawSize > 0 && absolutePositionSize > 0 && rawSize < absolutePositionSize,\n reduceOnly: Boolean(rawOrder.reduceOnly),\n };\n}\n\nexport function adaptMarketFromSDK(\n sdkMarket: MetaResponse['universe'][number],\n): MarketInfo {\n // The venue also sends `normal` (no restriction), which the SDK type omits.\n // `MarketInfo.marginMode` carries restrictions only, so drop it.\n const venueMarginMode: string | undefined = sdkMarket.marginMode;\n return {\n name: sdkMarket.name,\n szDecimals: sdkMarket.szDecimals,\n maxLeverage: sdkMarket.maxLeverage,\n marginTableId: sdkMarket.marginTableId,\n onlyIsolated: sdkMarket.onlyIsolated,\n ...(!isUnrestrictedMarginMode(venueMarginMode) && {\n marginMode: sdkMarket.marginMode,\n }),\n isDelisted: sdkMarket.isDelisted,\n };\n}\n\n/**\n * Read one clearinghouse's cross-margin summary. A payload without the cross\n * fields reports none; present values must be finite decimals.\n *\n * @param perpsState - Clearinghouse state for one DEX.\n * @returns The summary, or undefined when the payload carries none.\n */\nfunction adaptCrossMarginSummaryFromSDK(\n perpsState: ClearinghouseStateResponse,\n): CrossMarginSummary | undefined {\n const { crossMarginSummary, crossMaintenanceMarginUsed } = perpsState;\n if (!crossMarginSummary || crossMaintenanceMarginUsed === undefined) {\n return undefined;\n }\n const summary: CrossMarginSummary = {\n accountValue: crossMarginSummary.accountValue,\n maintenanceMargin: crossMaintenanceMarginUsed,\n marginUsed: crossMarginSummary.totalMarginUsed,\n notional: crossMarginSummary.totalNtlPos,\n };\n for (const [field, value] of Object.entries(summary)) {\n if (parseFiniteDecimal(value) === null) {\n throw new Error(\n `Invalid HyperLiquid cross margin ${field} '${String(value)}'`,\n );\n }\n }\n return summary;\n}\n\n// Perps-only account adapter. Spot balances are layered on afterwards by\n// addSpotBalanceToAccountState, which enforces the USDC-only policy via\n// SPOT_COLLATERAL_COINS. Keeping spot logic out of here preserves a single\n// source of truth for spot balance math.\nexport function adaptAccountStateFromSDK(\n perpsState: ClearinghouseStateResponse,\n): AccountState {\n const { totalUnrealizedPnl, weightedReturnOnEquity } =\n perpsState.assetPositions.reduce(\n (acc, assetPos: AssetPosition) => {\n const unrealizedPnl = parseFloat(\n assetPos.position.unrealizedPnl || '0',\n );\n const marginUsed = parseFloat(assetPos.position.marginUsed || '0');\n const returnOnEquity = parseFloat(\n assetPos.position.returnOnEquity || '0',\n );\n acc.totalUnrealizedPnl += unrealizedPnl;\n acc.weightedReturnOnEquity += returnOnEquity * marginUsed;\n return acc;\n },\n {\n totalUnrealizedPnl: 0,\n weightedReturnOnEquity: 0,\n },\n );\n const totalMarginUsed = parseFloat(\n perpsState.marginSummary.totalMarginUsed || '0',\n );\n const totalReturnOnEquityPercentage =\n totalMarginUsed > 0\n ? ((weightedReturnOnEquity / totalMarginUsed) * 100).toString()\n : '0';\n\n const perpsBalance = parseFloat(perpsState.marginSummary.accountValue);\n\n const withdrawable = perpsState.withdrawable || '0';\n const crossMarginSummary = adaptCrossMarginSummaryFromSDK(perpsState);\n const accountState: AccountState = {\n spendableBalance: withdrawable,\n withdrawableBalance: withdrawable,\n totalBalance: perpsBalance.toString() || '0',\n marginUsed: perpsState.marginSummary.totalMarginUsed || '0',\n unrealizedPnl: totalUnrealizedPnl.toString() || '0',\n returnOnEquity: totalReturnOnEquityPercentage || '0',\n ...(crossMarginSummary ? { crossMarginSummary } : {}),\n };\n\n return accountState;\n}\n\nexport function buildAssetMapping(params: {\n metaUniverse: MetaResponse['universe'];\n dex?: string | null;\n perpDexIndex: number;\n}): {\n symbolToAssetId: Map<string, number>;\n assetIdToSymbol: Map<number, string>;\n} {\n const { metaUniverse, perpDexIndex } = params;\n const symbolToAssetId = new Map<string, number>();\n const assetIdToSymbol = new Map<number, string>();\n\n metaUniverse.forEach((asset, index) => {\n const assetId = calculateHip3AssetId(perpDexIndex, index);\n symbolToAssetId.set(asset.name, assetId);\n assetIdToSymbol.set(assetId, asset.name);\n });\n\n return { symbolToAssetId, assetIdToSymbol };\n}\n\nexport function formatHyperLiquidPrice(params: {\n price: string | number;\n szDecimals: number;\n}): string {\n const { price, szDecimals } = params;\n const priceNum = typeof price === 'string' ? parseFloat(price) : price;\n\n if (Number.isInteger(priceNum)) {\n return priceNum.toString();\n }\n\n const maxDecimalPlaces =\n DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals;\n\n let formattedPrice = priceNum.toFixed(maxDecimalPlaces);\n formattedPrice = parseFloat(formattedPrice).toString();\n\n const significantDigits = countSignificantFigures(formattedPrice);\n\n if (significantDigits > DECIMAL_PRECISION_CONFIG.MaxSignificantFigures) {\n formattedPrice = roundToSignificantFigures(formattedPrice);\n }\n\n return formattedPrice;\n}\n\nexport function formatHyperLiquidSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const { size, szDecimals } = params;\n const number = typeof size === 'string' ? parseFloat(size) : size;\n\n if (isNaN(number)) {\n return '0';\n }\n\n const formatted = number.toFixed(szDecimals);\n\n if (!formatted.includes('.')) {\n return formatted;\n }\n\n return formatted.replace(/\\.?0+$/u, '');\n}\n\nexport function calculatePositionSize(params: {\n usdValue: number;\n leverage: number;\n assetPrice: number;\n}): number {\n const { usdValue, leverage, assetPrice } = params;\n return (usdValue * leverage) / assetPrice;\n}\n\nexport function calculateHip3AssetId(\n perpDexIndex: number,\n indexInMeta: number,\n): number {\n if (perpDexIndex === 0) {\n return indexInMeta;\n }\n return (\n HIP3_ASSET_ID_CONFIG.BaseAssetId +\n perpDexIndex * HIP3_ASSET_ID_CONFIG.DexMultiplier +\n indexInMeta\n );\n}\n\n/**\n * Build the provider-neutral execution id for a HyperLiquid fill.\n *\n * HyperLiquid's `tid` is a 50-bit hash, and the venue documents\n * `(block_time, coin, tid)` as a trade's global identity, so all three go into\n * the id. REST and websocket fills report the same `time`, `coin` and `tid` for\n * one execution, so both transports yield the same id.\n *\n * @param fill - The raw HyperLiquid fill.\n * @param fill.coin - Venue asset name, including any HIP-3 dex prefix.\n * @param fill.time - Fill block time in milliseconds.\n * @param fill.tid - Venue trade id.\n * @returns The id, or `undefined` when the payload carries no `tid`. Omitting\n * it, rather than stringifying a missing value, keeps malformed fills from\n * sharing one id.\n */\nexport function buildHyperLiquidFillId(fill: {\n coin: string;\n time: number;\n tid?: number | null;\n}): string | undefined {\n if (fill.tid === undefined || fill.tid === null) {\n return undefined;\n }\n return `${fill.coin}:${fill.time}:${fill.tid}`;\n}\n\nexport function parseAssetName(assetName: string): {\n dex: string | null;\n symbol: string;\n} {\n const colonIndex = assetName.indexOf(':');\n if (colonIndex === -1) {\n return { dex: null, symbol: assetName };\n }\n return {\n dex: assetName.substring(0, colonIndex),\n symbol: assetName.substring(colonIndex + 1),\n };\n}\n\nexport function adaptHyperLiquidLedgerUpdateToUserHistoryItem(\n rawLedgerUpdates: RawLedgerUpdate[],\n): UserHistoryItem[] {\n return (rawLedgerUpdates || [])\n .filter((update) => {\n if (update.delta.type === 'deposit') {\n return true;\n }\n if (update.delta.type === 'withdraw') {\n return true;\n }\n if (update.delta.type === 'internalTransfer') {\n const usdc = Number.parseFloat(update.delta.usdc ?? '0');\n if (Number.isNaN(usdc)) {\n return false;\n }\n return usdc > 0;\n }\n return false;\n })\n .map((update) => {\n let amount = '0';\n let asset = 'USDC';\n\n if (hasProperty(update.delta, 'usdc') && update.delta.usdc) {\n amount = Math.abs(parseFloat(update.delta.usdc)).toString();\n }\n if (\n hasProperty(update.delta, 'coin') &&\n typeof update.delta.coin === 'string'\n ) {\n asset = update.delta.coin;\n }\n\n return {\n id: `history-${update.hash}`,\n timestamp: update.time,\n amount,\n asset,\n txHash: update.hash,\n status: 'completed' as const,\n type: update.delta.type === 'withdraw' ? 'withdrawal' : 'deposit',\n details: {\n source: '',\n bridgeContract: undefined,\n recipient: undefined,\n blockNumber: undefined,\n chainId: undefined,\n synthetic: undefined,\n },\n };\n });\n}\n\nconst HYPERLIQUID_ZERO_HASH = /^0x0+$/u;\nconst HYPERLIQUID_TRADE_SIDE = { B: 'buy', A: 'sell' } as const;\n\n/**\n * Adapt Hyperliquid public trades (REST `recentTrades` or WS `trades`) to\n * {@link PublicTrade}, newest first. Trades for another coin and malformed\n * trades are dropped. `side` is the aggressor's: `B` bought, `A` sold. The id\n * comes from {@link buildHyperLiquidFillId}, so both transports give one\n * execution the same id.\n *\n * @param trades - SDK trades.\n * @param symbol - Requested coin; other coins are dropped.\n * @returns The trades for `symbol`, newest first.\n */\nexport function adaptPublicTradesFromHyperLiquid(\n trades: readonly HyperLiquidPublicTrade[],\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const trade of trades) {\n if (trade.coin !== symbol) {\n continue;\n }\n const publicTrade = buildPublicTrade({\n id:\n typeof trade.tid === 'number'\n ? buildHyperLiquidFillId(trade)\n : undefined,\n symbol,\n price: trade.px,\n size: trade.sz,\n side: HYPERLIQUID_TRADE_SIDE[trade.side] ?? null,\n timestamp: trade.time,\n txHash:\n typeof trade.hash === 'string' &&\n !HYPERLIQUID_ZERO_HASH.test(trade.hash)\n ? trade.hash\n : undefined,\n providerId: 'hyperliquid',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\n}\n"]}
1
+ {"version":3,"file":"hyperLiquidAdapter.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAO,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAsB1D,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,mBAAmB,EACnB,mBAAmB,EACnB,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,gBAAgB,EAChB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAS3D,MA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AK,QAAQ;gBAC3B,CAAC,CAAC,sBAAsB,CAAC,KAAK,CAAC;gBAC/B,CAAC,CAAC,SAAS;YACf,MAAM;YACN,KAAK,EAAE,KAAK,CAAC,EAAE;YACf,IAAI,EAAE,KAAK,CAAC,EAAE;YACd,IAAI,EAAE,sBAAsB,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI;YAChD,SAAS,EAAE,KAAK,CAAC,IAAI;YACrB,MAAM,EACJ,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;gBAC9B,CAAC,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;gBACrC,CAAC,CAAC,KAAK,CAAC,IAAI;gBACZ,CAAC,CAAC,SAAS;YACf,UAAU,EAAE,aAAa;SAC1B,CAAC,CAAC;QACH,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IACD,OAAO,2BAA2B,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { hasProperty, Hex, isHexString } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\n isUnrestrictedMarginMode,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n DECIMAL_PRECISION_CONFIG,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n AssetPosition,\n FrontendOrder,\n ClearinghouseStateResponse,\n HyperLiquidPublicTrade,\n MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\n PublicTrade,\n RawLedgerUpdate,\n UserHistoryItem,\n} from '../types/index.js';\nimport type { TpslLinkage, TriggerOrderType } from '../types/perps-types.js';\nimport {\n buildTriggerOrderType,\n classifyTriggerDirection,\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n toSDKTimeInForce,\n} from './orderTypes.js';\nimport { roundToSignificantFiguresGrid } from './pricePrecision.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\ntype FrontendOrderWithParentTpsl = FrontendOrder & {\n takeProfitPrice?: unknown;\n stopLossPrice?: unknown;\n takeProfitOrderId?: unknown;\n stopLossOrderId?: unknown;\n};\n\nexport const HYPERLIQUID_SCALE_CLOID_MARKER = '4d4d5343';\n\n/**\n * Recover the Scale group shared by MetaMask-generated rung CLOIDs.\n *\n * @param clientOrderId - HyperLiquid client order ID.\n * @returns The Scale handle, or undefined for an unrelated order.\n */\nexport const readScaleGroupId = (\n clientOrderId: string | null | undefined,\n): string | undefined => {\n const normalized = clientOrderId?.toLowerCase();\n if (\n normalized?.length !== 34 ||\n !normalized.startsWith(`0x${HYPERLIQUID_SCALE_CLOID_MARKER}`)\n ) {\n return undefined;\n }\n return `scale:${normalized.slice(2, -2)}`;\n};\n\nconst readOptionalString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst readOptionalOrderId = (value: unknown): string | undefined => {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value.toString();\n }\n\n return undefined;\n};\n\nconst getParentTpslMetadata = (\n rawOrder: FrontendOrderWithParentTpsl,\n): {\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitOrderId?: string;\n stopLossOrderId?: string;\n} => ({\n takeProfitPrice: readOptionalString(rawOrder.takeProfitPrice),\n stopLossPrice: readOptionalString(rawOrder.stopLossPrice),\n takeProfitOrderId: readOptionalOrderId(rawOrder.takeProfitOrderId),\n stopLossOrderId: readOptionalOrderId(rawOrder.stopLossOrderId),\n});\n\n/**\n * HyperLiquid SDK Adapter Utilities\n *\n * These functions transform between MetaMask Perps API types and HyperLiquid SDK types.\n * The SDK uses cryptic property names for efficiency, but our API uses descriptive names\n * to provide a consistent interface across different perps protocols.\n */\n\nexport function adaptOrderToSDK(\n order: PerpsOrderParams,\n symbolToAssetId: Map<string, number>,\n): SDKOrderParams {\n const assetId = symbolToAssetId.get(order.symbol);\n if (assetId === undefined) {\n const availableDexs = new Set<string>();\n symbolToAssetId.forEach((_, symbol) => {\n if (symbol.includes(':')) {\n const dex = symbol.split(':')[0];\n availableDexs.add(dex);\n }\n });\n\n const dexHint =\n availableDexs.size > 0\n ? ` Available HIP-3 DEXs: ${Array.from(availableDexs).join(', ')}`\n : ' No HIP-3 DEXs currently available.';\n\n throw new Error(\n `Asset ${order.symbol} not found in asset mapping.${dexHint} Check console logs for \"HyperLiquidProvider: Asset mapping built\" to see available assets.`,\n );\n }\n\n return {\n a: assetId,\n b: order.isBuy,\n p: order.price ?? resolveTriggerCapPrice(order) ?? '0',\n s: order.size,\n r: order.reduceOnly ?? false,\n t: adaptOrderTypeToSDK(order),\n c:\n order.clientOrderId && isHexString(order.clientOrderId)\n ? order.clientOrderId\n : undefined,\n };\n}\n\n/**\n * Derive the slippage cap a market-on-trigger order submits as its price.\n *\n * A `stop_market` / `take_profit_market` order legitimately carries no limit\n * price, but the SDK still requires a positive `p` — it is the cap the order\n * fills against once the trigger fires, not a resting price. Sending `'0'`\n * fails SDK validation before the request is ever made.\n *\n * The cap follows the order's own tolerance, matching `calculateOrderPriceAndSize`\n * on the `placeOrder` path, so the same order priced through either route gets\n * the same execution bound.\n *\n * @param order - Order params carrying the placement type, trigger price, and\n * slippage tolerance.\n * @returns The formatted cap price, or undefined when the order needs no cap.\n */\nfunction resolveTriggerCapPrice(order: PerpsOrderParams): string | undefined {\n if (\n !isTriggerOrderType(order.orderType) ||\n isLimitExecutionOrderType(order.orderType) ||\n !order.triggerPrice\n ) {\n return undefined;\n }\n\n const triggerPrice = parseFloat(order.triggerPrice);\n if (!Number.isFinite(triggerPrice)) {\n return undefined;\n }\n\n // Accept the deprecated decimal `slippage` too, normalizing it to bps the way\n // `placeOrder` does, so neither spelling silently falls back to the default.\n const effectiveBps =\n order.maxSlippageBps ??\n (typeof order.slippage === 'number'\n ? Math.round(order.slippage * BASIS_POINTS_DIVISOR)\n : undefined) ??\n ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n\n // Buying pays up to the cap, selling accepts down to it.\n const slippage = effectiveBps / BASIS_POINTS_DIVISOR;\n const capPrice = order.isBuy\n ? triggerPrice * (1 + slippage)\n : triggerPrice * (1 - slippage);\n\n return capPrice.toString();\n}\n\n/**\n * Map a placement type onto the SDK's order-type field.\n *\n * @param order - Order params carrying the placement type and trigger price\n * @returns The SDK order-type field\n */\nfunction adaptOrderTypeToSDK(order: PerpsOrderParams): SDKOrderParams['t'] {\n if (isTriggerOrderType(order.orderType)) {\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n if (!order.triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(order.orderType),\n triggerPx: order.triggerPrice,\n tpsl: getTriggerDirection(order.orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n }\n\n if (order.orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(order.timeInForce) } };\n }\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n}\n\n/**\n * Map the provider-agnostic TP/SL linkage onto HyperLiquid's grouping vocabulary.\n *\n * @param linkage - How the attached TP/SL is linked.\n * @returns The HyperLiquid grouping value.\n */\nexport function adaptTpslLinkageToGrouping(\n linkage: TpslLinkage,\n): 'na' | 'normalTpsl' | 'positionTpsl' {\n switch (linkage) {\n case 'position':\n return 'positionTpsl';\n case 'order':\n return 'normalTpsl';\n default:\n return 'na';\n }\n}\n\n/**\n * Margin Hyperliquid shows for a cross position. When cross equity is below\n * the cross initial margin, the venue scales each cross position's margin by\n * `accountValue / totalMarginUsed`.\n *\n * @param marginUsed - The position's raw margin used.\n * @param crossMarginSummary - The clearinghouse's cross margin summary.\n * @returns The displayed margin, or undefined when an input is not a number.\n */\nfunction deriveCrossDisplayMarginUsed(\n marginUsed: string,\n crossMarginSummary: ClearinghouseStateResponse['crossMarginSummary'],\n): string | undefined {\n const margin = new BigNumber(marginUsed);\n const accountValue = new BigNumber(crossMarginSummary.accountValue);\n const totalMarginUsed = new BigNumber(crossMarginSummary.totalMarginUsed);\n if (\n !margin.isFinite() ||\n !accountValue.isFinite() ||\n !totalMarginUsed.isFinite()\n ) {\n return undefined;\n }\n if (totalMarginUsed.lte(0) || accountValue.gte(totalMarginUsed)) {\n return margin.toFixed();\n }\n return BigNumber.max(\n margin.times(accountValue).div(totalMarginUsed),\n 0,\n ).toFixed();\n}\n\n/**\n * Adapt a Hyperliquid asset position.\n *\n * @param assetPosition - Position from a clearinghouse state.\n * @param crossMarginSummary - That clearinghouse's `crossMarginSummary`. When\n * given, a cross position also carries `displayMarginUsed`.\n * @returns The position.\n */\nexport function adaptPositionFromSDK(\n assetPosition: AssetPosition,\n crossMarginSummary?: ClearinghouseStateResponse['crossMarginSummary'],\n): Position {\n const pos = assetPosition.position;\n const displayMarginUsed =\n pos.leverage.type === 'cross' && crossMarginSummary\n ? deriveCrossDisplayMarginUsed(pos.marginUsed, crossMarginSummary)\n : undefined;\n return {\n symbol: pos.coin,\n size: pos.szi,\n entryPrice: pos.entryPx,\n positionValue: pos.positionValue,\n unrealizedPnl: pos.unrealizedPnl,\n marginUsed: pos.marginUsed,\n ...(displayMarginUsed !== undefined && { displayMarginUsed }),\n leverage: {\n type: pos.leverage.type,\n value: pos.leverage.value,\n rawUsd:\n pos.leverage.type === 'isolated' ? pos.leverage.rawUsd : undefined,\n },\n liquidationPrice: pos.liquidationPx,\n maxLeverage: pos.maxLeverage,\n returnOnEquity: pos.returnOnEquity,\n cumulativeFunding: pos.cumFunding,\n takeProfitCount: 0,\n stopLossCount: 0,\n };\n}\n\nexport function adaptOrderFromSDK(\n rawOrder: FrontendOrder,\n position?: Position,\n): Order {\n // TODO: Remove this widened boundary type when FrontendOrder includes\n // takeProfitPrice/stopLossPrice and takeProfitOrderId/stopLossOrderId.\n const parentTpslMetadata = getParentTpslMetadata(rawOrder);\n\n // Extract basic fields with appropriate conversions\n const orderId = rawOrder.oid?.toString() || '';\n const symbol = rawOrder.coin;\n const side: 'buy' | 'sell' = rawOrder.side === 'B' ? 'buy' : 'sell';\n const detailedOrderType = rawOrder.orderType;\n const { isTrigger } = rawOrder;\n const { reduceOnly } = rawOrder;\n\n const triggerOrderType = adaptTriggerOrderTypeFromSDK(detailedOrderType);\n\n let orderType: 'limit' | 'market' = 'market';\n if (triggerOrderType) {\n // Trigger orders always carry a limitPx (the slippage cap for\n // market-on-trigger execution), so the placement type is the only reliable\n // source for how the order actually executes.\n orderType = getTriggerExecution(triggerOrderType);\n } else if (\n detailedOrderType?.toLowerCase().includes('limit') ||\n rawOrder.limitPx\n ) {\n orderType = 'limit';\n }\n\n const price = rawOrder.limitPx || rawOrder.triggerPx || '0';\n\n let size = rawOrder.sz;\n let originalSize = rawOrder.origSz || size;\n\n let currentSize = parseFloat(size);\n let origSize = parseFloat(originalSize);\n\n if (rawOrder.isPositionTpsl && origSize === 0 && position) {\n const absPositionSize = Math.abs(parseFloat(position.size));\n currentSize = absPositionSize;\n origSize = absPositionSize;\n size = absPositionSize.toString();\n originalSize = absPositionSize.toString();\n }\n\n const filledSize = origSize - currentSize;\n\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n let takeProfitOrderId: string | undefined;\n let stopLossOrderId: string | undefined;\n\n // TODO: We assume that there can only be 1 TP and 1 SL as children but there can be several TPSLs as children\n if (rawOrder.children && rawOrder.children.length > 0) {\n rawOrder.children.forEach((child) => {\n if (child.isTrigger && child.orderType) {\n if (child.orderType.includes('Take Profit')) {\n // HyperLiquid represents \"no trigger price\" as an empty string, not\n // null/undefined, so `||` (not `??`) is required to fall back to\n // limitPx when triggerPx is ''.\n takeProfitPrice = child.triggerPx || child.limitPx;\n takeProfitOrderId = child.oid.toString();\n } else if (child.orderType.includes('Stop')) {\n stopLossPrice = child.triggerPx || child.limitPx;\n stopLossOrderId = child.oid.toString();\n }\n }\n });\n }\n\n // Fallback: preserve parent-level TP/SL metadata when children are absent.\n takeProfitPrice ??= parentTpslMetadata.takeProfitPrice;\n stopLossPrice ??= parentTpslMetadata.stopLossPrice;\n takeProfitOrderId ??= parentTpslMetadata.takeProfitOrderId;\n stopLossOrderId ??= parentTpslMetadata.stopLossOrderId;\n\n // Build the order object\n const order: Order = {\n orderId,\n symbol,\n side,\n orderType,\n size,\n originalSize,\n price,\n filledSize: filledSize.toString(),\n remainingSize: size,\n status: 'open' as const,\n timestamp: rawOrder.timestamp,\n detailedOrderType,\n isTrigger,\n reduceOnly,\n };\n\n const strategyGroupId = readScaleGroupId(rawOrder.cloid);\n if (strategyGroupId) {\n order.strategyGroupId = strategyGroupId;\n }\n\n if (typeof rawOrder.isPositionTpsl === 'boolean') {\n order.isPositionTpsl = rawOrder.isPositionTpsl;\n }\n\n if (takeProfitPrice) {\n order.takeProfitPrice = takeProfitPrice;\n order.takeProfitOrderId = takeProfitOrderId;\n }\n if (stopLossPrice) {\n order.stopLossPrice = stopLossPrice;\n order.stopLossOrderId = stopLossOrderId;\n }\n if (rawOrder.triggerPx) {\n order.triggerPrice = rawOrder.triggerPx;\n }\n\n if (triggerOrderType) {\n order.triggerOrderType = triggerOrderType;\n }\n\n return order;\n}\n\n/**\n * Map HyperLiquid's human-readable order type string onto the provider-agnostic\n * trigger placement type.\n *\n * @param detailedOrderType - HyperLiquid `orderType` string (e.g. `'Stop Limit'`)\n * @returns The normalized trigger placement type, or undefined for non-trigger orders\n */\nexport function adaptTriggerOrderTypeFromSDK(\n detailedOrderType: string | undefined,\n): TriggerOrderType | undefined {\n if (!detailedOrderType) {\n return undefined;\n }\n\n const isTakeProfit = detailedOrderType.includes('Take Profit');\n const isStop = detailedOrderType.includes('Stop');\n\n if (!isTakeProfit && !isStop) {\n return undefined;\n }\n\n return buildTriggerOrderType({\n direction: isTakeProfit ? 'take_profit' : 'stop',\n execution: detailedOrderType.includes('Limit') ? 'limit' : 'market',\n });\n}\n\n/**\n * Build the position-state view of a trigger order attached to a position.\n *\n * HyperLiquid encodes \"the whole position\" as size `0` for position-bound TP/SL,\n * which is resolved here against the position size so consumers always see a\n * concrete quantity and can tell partial triggers apart.\n *\n * @param params - Mapping parameters\n * @param params.rawOrder - Raw HyperLiquid frontend order\n * @param params.positionSize - Signed or unsigned position size\n * @param params.entryPrice - Entry price, used to classify a trigger the exchange left unnamed\n * @returns The normalized trigger order, or undefined when the order is not a trigger\n */\nexport function adaptPositionTriggerOrderFromSDK(params: {\n rawOrder: Pick<\n FrontendOrder,\n 'oid' | 'orderType' | 'triggerPx' | 'limitPx' | 'sz' | 'reduceOnly'\n >;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { rawOrder, positionSize, entryPrice } = params;\n\n const orderType = adaptTriggerOrderTypeFromSDK(rawOrder.orderType);\n\n // HyperLiquid uses '' for \"no trigger price\", so `||` (not `??`) is required.\n const triggerPrice = rawOrder.triggerPx || rawOrder.limitPx || '0';\n\n // Same rule as the WebSocket path: an unnamed trigger keeps its recoverable\n // direction and leaves its execution mode unstated, so both transports\n // report the same set of orders.\n const direction = orderType\n ? getTriggerDirection(orderType)\n : classifyTriggerDirection({ triggerPrice, entryPrice, positionSize });\n\n if (!direction) {\n return undefined;\n }\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(rawOrder.sz || '0'));\n\n // Position-bound TP/SL carries size 0, meaning the whole position.\n const size = rawSize > 0 ? rawSize : absolutePositionSize;\n\n return {\n orderId: rawOrder.oid.toString(),\n direction,\n orderType,\n triggerPrice,\n size: size.toString(),\n isPartial:\n rawSize > 0 && absolutePositionSize > 0 && rawSize < absolutePositionSize,\n reduceOnly: Boolean(rawOrder.reduceOnly),\n };\n}\n\nexport function adaptMarketFromSDK(\n sdkMarket: MetaResponse['universe'][number],\n): MarketInfo {\n // The venue also sends `normal` (no restriction), which the SDK type omits.\n // `MarketInfo.marginMode` carries restrictions only, so drop it.\n const venueMarginMode: string | undefined = sdkMarket.marginMode;\n return {\n name: sdkMarket.name,\n szDecimals: sdkMarket.szDecimals,\n maxLeverage: sdkMarket.maxLeverage,\n marginTableId: sdkMarket.marginTableId,\n onlyIsolated: sdkMarket.onlyIsolated,\n ...(!isUnrestrictedMarginMode(venueMarginMode) && {\n marginMode: sdkMarket.marginMode,\n }),\n isDelisted: sdkMarket.isDelisted,\n };\n}\n\n/**\n * Read one clearinghouse's cross-margin summary. A payload without the cross\n * fields reports none; present values must be finite decimals.\n *\n * @param perpsState - Clearinghouse state for one DEX.\n * @returns The summary, or undefined when the payload carries none.\n */\nfunction adaptCrossMarginSummaryFromSDK(\n perpsState: ClearinghouseStateResponse,\n): CrossMarginSummary | undefined {\n const { crossMarginSummary, crossMaintenanceMarginUsed } = perpsState;\n if (!crossMarginSummary || crossMaintenanceMarginUsed === undefined) {\n return undefined;\n }\n const summary: CrossMarginSummary = {\n accountValue: crossMarginSummary.accountValue,\n maintenanceMargin: crossMaintenanceMarginUsed,\n marginUsed: crossMarginSummary.totalMarginUsed,\n notional: crossMarginSummary.totalNtlPos,\n };\n for (const [field, value] of Object.entries(summary)) {\n if (parseFiniteDecimal(value) === null) {\n throw new Error(\n `Invalid HyperLiquid cross margin ${field} '${String(value)}'`,\n );\n }\n }\n return summary;\n}\n\n// Perps-only account adapter. Spot balances are layered on afterwards by\n// addSpotBalanceToAccountState, which enforces the USDC-only policy via\n// SPOT_COLLATERAL_COINS. Keeping spot logic out of here preserves a single\n// source of truth for spot balance math.\nexport function adaptAccountStateFromSDK(\n perpsState: ClearinghouseStateResponse,\n): AccountState {\n const { totalUnrealizedPnl, weightedReturnOnEquity } =\n perpsState.assetPositions.reduce(\n (acc, assetPos: AssetPosition) => {\n const unrealizedPnl = parseFloat(\n assetPos.position.unrealizedPnl || '0',\n );\n const marginUsed = parseFloat(assetPos.position.marginUsed || '0');\n const returnOnEquity = parseFloat(\n assetPos.position.returnOnEquity || '0',\n );\n acc.totalUnrealizedPnl += unrealizedPnl;\n acc.weightedReturnOnEquity += returnOnEquity * marginUsed;\n return acc;\n },\n {\n totalUnrealizedPnl: 0,\n weightedReturnOnEquity: 0,\n },\n );\n const totalMarginUsed = parseFloat(\n perpsState.marginSummary.totalMarginUsed || '0',\n );\n const totalReturnOnEquityPercentage =\n totalMarginUsed > 0\n ? ((weightedReturnOnEquity / totalMarginUsed) * 100).toString()\n : '0';\n\n const perpsBalance = parseFloat(perpsState.marginSummary.accountValue);\n\n const withdrawable = perpsState.withdrawable || '0';\n const crossMarginSummary = adaptCrossMarginSummaryFromSDK(perpsState);\n const accountState: AccountState = {\n spendableBalance: withdrawable,\n withdrawableBalance: withdrawable,\n totalBalance: perpsBalance.toString() || '0',\n marginUsed: perpsState.marginSummary.totalMarginUsed || '0',\n unrealizedPnl: totalUnrealizedPnl.toString() || '0',\n returnOnEquity: totalReturnOnEquityPercentage || '0',\n ...(crossMarginSummary ? { crossMarginSummary } : {}),\n };\n\n return accountState;\n}\n\nexport function buildAssetMapping(params: {\n metaUniverse: MetaResponse['universe'];\n dex?: string | null;\n perpDexIndex: number;\n}): {\n symbolToAssetId: Map<string, number>;\n assetIdToSymbol: Map<number, string>;\n} {\n const { metaUniverse, perpDexIndex } = params;\n const symbolToAssetId = new Map<string, number>();\n const assetIdToSymbol = new Map<number, string>();\n\n metaUniverse.forEach((asset, index) => {\n const assetId = calculateHip3AssetId(perpDexIndex, index);\n symbolToAssetId.set(asset.name, assetId);\n assetIdToSymbol.set(assetId, asset.name);\n });\n\n return { symbolToAssetId, assetIdToSymbol };\n}\n\nexport function formatHyperLiquidPrice(params: {\n price: string | number;\n szDecimals: number;\n}): string {\n const { price, szDecimals } = params;\n return roundToSignificantFiguresGrid(\n price,\n DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals,\n DECIMAL_PRECISION_CONFIG.MaxSignificantFigures,\n );\n}\n\nexport function formatHyperLiquidSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const { size, szDecimals } = params;\n const number = typeof size === 'string' ? parseFloat(size) : size;\n\n if (isNaN(number)) {\n return '0';\n }\n\n const formatted = number.toFixed(szDecimals);\n\n if (!formatted.includes('.')) {\n return formatted;\n }\n\n return formatted.replace(/\\.?0+$/u, '');\n}\n\nexport function calculatePositionSize(params: {\n usdValue: number;\n leverage: number;\n assetPrice: number;\n}): number {\n const { usdValue, leverage, assetPrice } = params;\n return (usdValue * leverage) / assetPrice;\n}\n\nexport function calculateHip3AssetId(\n perpDexIndex: number,\n indexInMeta: number,\n): number {\n if (perpDexIndex === 0) {\n return indexInMeta;\n }\n return (\n HIP3_ASSET_ID_CONFIG.BaseAssetId +\n perpDexIndex * HIP3_ASSET_ID_CONFIG.DexMultiplier +\n indexInMeta\n );\n}\n\n/**\n * Build the provider-neutral execution id for a HyperLiquid fill.\n *\n * HyperLiquid's `tid` is a 50-bit hash, and the venue documents\n * `(block_time, coin, tid)` as a trade's global identity, so all three go into\n * the id. REST and websocket fills report the same `time`, `coin` and `tid` for\n * one execution, so both transports yield the same id.\n *\n * @param fill - The raw HyperLiquid fill.\n * @param fill.coin - Venue asset name, including any HIP-3 dex prefix.\n * @param fill.time - Fill block time in milliseconds.\n * @param fill.tid - Venue trade id.\n * @returns The id, or `undefined` when the payload carries no `tid`. Omitting\n * it, rather than stringifying a missing value, keeps malformed fills from\n * sharing one id.\n */\nexport function buildHyperLiquidFillId(fill: {\n coin: string;\n time: number;\n tid?: number | null;\n}): string | undefined {\n if (fill.tid === undefined || fill.tid === null) {\n return undefined;\n }\n return `${fill.coin}:${fill.time}:${fill.tid}`;\n}\n\nexport function parseAssetName(assetName: string): {\n dex: string | null;\n symbol: string;\n} {\n const colonIndex = assetName.indexOf(':');\n if (colonIndex === -1) {\n return { dex: null, symbol: assetName };\n }\n return {\n dex: assetName.substring(0, colonIndex),\n symbol: assetName.substring(colonIndex + 1),\n };\n}\n\nexport function adaptHyperLiquidLedgerUpdateToUserHistoryItem(\n rawLedgerUpdates: RawLedgerUpdate[],\n): UserHistoryItem[] {\n return (rawLedgerUpdates || [])\n .filter((update) => {\n if (update.delta.type === 'deposit') {\n return true;\n }\n if (update.delta.type === 'withdraw') {\n return true;\n }\n if (update.delta.type === 'internalTransfer') {\n const usdc = Number.parseFloat(update.delta.usdc ?? '0');\n if (Number.isNaN(usdc)) {\n return false;\n }\n return usdc > 0;\n }\n return false;\n })\n .map((update) => {\n let amount = '0';\n let asset = 'USDC';\n\n if (hasProperty(update.delta, 'usdc') && update.delta.usdc) {\n amount = Math.abs(parseFloat(update.delta.usdc)).toString();\n }\n if (\n hasProperty(update.delta, 'coin') &&\n typeof update.delta.coin === 'string'\n ) {\n asset = update.delta.coin;\n }\n\n return {\n id: `history-${update.hash}`,\n timestamp: update.time,\n amount,\n asset,\n txHash: update.hash,\n status: 'completed' as const,\n type: update.delta.type === 'withdraw' ? 'withdrawal' : 'deposit',\n details: {\n source: '',\n bridgeContract: undefined,\n recipient: undefined,\n blockNumber: undefined,\n chainId: undefined,\n synthetic: undefined,\n },\n };\n });\n}\n\nconst HYPERLIQUID_ZERO_HASH = /^0x0+$/u;\nconst HYPERLIQUID_TRADE_SIDE = { B: 'buy', A: 'sell' } as const;\n\n/**\n * Adapt Hyperliquid public trades (REST `recentTrades` or WS `trades`) to\n * {@link PublicTrade}, newest first. Trades for another coin and malformed\n * trades are dropped. `side` is the aggressor's: `B` bought, `A` sold. The id\n * comes from {@link buildHyperLiquidFillId}, so both transports give one\n * execution the same id.\n *\n * @param trades - SDK trades.\n * @param symbol - Requested coin; other coins are dropped.\n * @returns The trades for `symbol`, newest first.\n */\nexport function adaptPublicTradesFromHyperLiquid(\n trades: readonly HyperLiquidPublicTrade[],\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const trade of trades) {\n if (trade.coin !== symbol) {\n continue;\n }\n const publicTrade = buildPublicTrade({\n id:\n typeof trade.tid === 'number'\n ? buildHyperLiquidFillId(trade)\n : undefined,\n symbol,\n price: trade.px,\n size: trade.sz,\n side: HYPERLIQUID_TRADE_SIDE[trade.side] ?? null,\n timestamp: trade.time,\n txHash:\n typeof trade.hash === 'string' &&\n !HYPERLIQUID_ZERO_HASH.test(trade.hash)\n ? trade.hash\n : undefined,\n providerId: 'hyperliquid',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\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":"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;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,CAwGnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
@@ -8,6 +8,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
10
  import { parseAssetName } from './hyperLiquidAdapter.js';
11
+ import { isPriceOutsideDeviationBand } from './priceDeviation.js';
11
12
  /**
12
13
  * Calculate open interest in USD
13
14
  * Open interest from HyperLiquid is in contracts/units, not USD
@@ -56,16 +57,12 @@ export function isMarketTradable(params) {
56
57
  // Without usable prices we cannot assess deviation — default to tradable so missing
57
58
  // data never blocks the user. A non-positive price means "no data" (e.g. the transient
58
59
  // 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) {
60
+ if (midPrice === undefined || oraclePrice === undefined) {
65
61
  return true;
66
62
  }
67
- const deviation = Math.abs(midPrice - oraclePrice) / oraclePrice;
68
- return deviation <= deviationLimit;
63
+ // The same band clients use to check a limit price, so a market and an
64
+ // order at one price never disagree.
65
+ return !isPriceOutsideDeviationBand(midPrice, oraclePrice, deviationLimit);
69
66
  }
70
67
  /**
71
68
  * Calculate 24h percentage change
@@ -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,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;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAIhC;IACC,MAAM,EACJ,QAAQ,EACR,WAAW,EACX,cAAc,GAAG,kBAAkB,CAAC,yBAAyB,GAC9D,GAAG,MAAM,CAAC;IAEX,oFAAoF;IACpF,uFAAuF;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OAAO;gBACT,CAAC,CAAC,UAAU,CAAC,gBAAgB,CAAC,gBAAgB,CAAC;YACjD,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC;gBACnB,CAAC,CAAC,eAAe,CAAC,oBAAoB;gBACtC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;YACnC,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC;gBAC/B,CAAC,CAAC,eAAe,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;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,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","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;AAY9D,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,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;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAIhC;IACC,MAAM,EACJ,QAAQ,EACR,WAAW,EACX,cAAc,GAAG,kBAAkB,CAAC,yBAAyB,GAC9D,GAAG,MAAM,CAAC;IAEX,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C;gBACnB,CAAC,CAAC,eAAe,CAAC,oBAAoB;gBACtC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;YACnC,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC;gBAC/B,CAAC,CAAC,eAAe,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;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,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","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';\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 };\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"]}
@@ -31,6 +31,15 @@ export declare function groupMarketsByMarketKey(markets: readonly PerpsMarketDat
31
31
  * @returns A reference for persistence in a watchlist or recently viewed list.
32
32
  */
33
33
  export declare function toSavedPerpsMarketReference(symbol: string, marketKey?: string): string;
34
+ /**
35
+ * Whether every client can read a saved reference. Mobile and Extension match
36
+ * saved entries by venue symbol, so `market-key:` and `venue:` references stay
37
+ * in local state and are never written to shared storage.
38
+ *
39
+ * @param reference - A saved watchlist entry.
40
+ * @returns True for a bare venue symbol.
41
+ */
42
+ export declare function isSharedPerpsMarketReference(reference: string): boolean;
34
43
  /**
35
44
  * Match an explicit key and the saved venue entries of its confirmed rows.
36
45
  * Without a key, a row on the legacy venue is saved by its symbol and a row
@@ -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;AAYD;;;;;;;;;;;;;;GAcG;AACH,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B,YACtB,eAAe,EAAE,eACb,MAAM,KAClB,eAAe,EAYjB,CAAC"}
@@ -72,6 +72,18 @@ export function groupMarketsByMarketKey(markets, defaultProvider) {
72
72
  export function toSavedPerpsMarketReference(symbol, marketKey) {
73
73
  return marketKey ? `${SAVED_MARKET_KEY_PREFIX}${marketKey}` : symbol;
74
74
  }
75
+ /**
76
+ * Whether every client can read a saved reference. Mobile and Extension match
77
+ * saved entries by venue symbol, so `market-key:` and `venue:` references stay
78
+ * in local state and are never written to shared storage.
79
+ *
80
+ * @param reference - A saved watchlist entry.
81
+ * @returns True for a bare venue symbol.
82
+ */
83
+ export function isSharedPerpsMarketReference(reference) {
84
+ return (!reference.startsWith(SAVED_MARKET_KEY_PREFIX) &&
85
+ !reference.startsWith(SAVED_VENUE_PREFIX));
86
+ }
75
87
  function getVenueReference(symbol, provider, legacyProvider) {
76
88
  return provider && provider !== legacyProvider
77
89
  ? `${SAVED_VENUE_PREFIX}${provider}:${symbol}`