@metamask-previews/perps-controller 24.1.0-preview-e9ac9ffe1 → 24.1.0-preview-70269bbdb

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 (88) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/PerpsController-method-action-types.d.ts +26 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +20 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +159 -2
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +0 -6
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +0 -13
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +19 -3
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +21 -5
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/performanceMetrics.d.ts +2 -14
  18. package/dist/constants/performanceMetrics.d.ts.map +1 -1
  19. package/dist/constants/performanceMetrics.js +1 -17
  20. package/dist/constants/performanceMetrics.js.map +1 -1
  21. package/dist/constants/perpsConfig.d.ts +27 -0
  22. package/dist/constants/perpsConfig.d.ts.map +1 -1
  23. package/dist/constants/perpsConfig.js +27 -0
  24. package/dist/constants/perpsConfig.js.map +1 -1
  25. package/dist/index.d.ts +7 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +2 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +2 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/HyperLiquidProvider.d.ts +7 -3
  34. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  35. package/dist/providers/HyperLiquidProvider.js +161 -103
  36. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  37. package/dist/providers/LighterProvider.d.ts +3 -3
  38. package/dist/providers/LighterProvider.d.ts.map +1 -1
  39. package/dist/providers/LighterProvider.js +20 -9
  40. package/dist/providers/LighterProvider.js.map +1 -1
  41. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  42. package/dist/services/TerminalMarketService.js +4 -2
  43. package/dist/services/TerminalMarketService.js.map +1 -1
  44. package/dist/services/TradingService.js +11 -9
  45. package/dist/services/TradingService.js.map +1 -1
  46. package/dist/types/index.d.ts +107 -2
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/index.js +0 -1
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/advancedOrderLists.d.ts +104 -0
  51. package/dist/utils/advancedOrderLists.d.ts.map +1 -0
  52. package/dist/utils/advancedOrderLists.js +421 -0
  53. package/dist/utils/advancedOrderLists.js.map +1 -0
  54. package/dist/utils/advancedOrders.d.ts +275 -0
  55. package/dist/utils/advancedOrders.d.ts.map +1 -0
  56. package/dist/utils/advancedOrders.js +639 -0
  57. package/dist/utils/advancedOrders.js.map +1 -0
  58. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  59. package/dist/utils/hyperLiquidAdapter.js +4 -1
  60. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  61. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  62. package/dist/utils/hyperLiquidValidation.js +22 -57
  63. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  64. package/dist/utils/index.d.ts +2 -0
  65. package/dist/utils/index.d.ts.map +1 -1
  66. package/dist/utils/index.js +2 -0
  67. package/dist/utils/index.js.map +1 -1
  68. package/dist/utils/lighterScaleOrders.d.ts.map +1 -1
  69. package/dist/utils/lighterScaleOrders.js +16 -65
  70. package/dist/utils/lighterScaleOrders.js.map +1 -1
  71. package/dist/utils/perpsFormatters.d.ts +29 -4
  72. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  73. package/dist/utils/perpsFormatters.js +51 -5
  74. package/dist/utils/perpsFormatters.js.map +1 -1
  75. package/docs/README.md +28 -0
  76. package/docs/architecture.md +256 -0
  77. package/docs/contracts/events.md +267 -0
  78. package/docs/contracts/feature-flags.md +39 -0
  79. package/docs/contracts/traces.md +83 -0
  80. package/docs/formatting.md +82 -0
  81. package/docs/tpsl.md +89 -0
  82. package/docs/venues/hyperliquid/README.md +27 -0
  83. package/docs/venues/hyperliquid/init-flow.md +116 -0
  84. package/docs/venues/hyperliquid/order-types.md +60 -0
  85. package/docs/venues/hyperliquid/trading-rules.md +77 -0
  86. package/docs/venues/lighter/api-keys.md +58 -0
  87. package/docs/venues/lighter/capabilities.md +74 -0
  88. package/package.json +4 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advancedOrders.js","sourceRoot":"","sources":["../../src/utils/advancedOrders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAe1D,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAQzD,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B;;;;;;;;GAQG;AACH,MAAM,UAAU,gBAAgB,CAC9B,YAAgD,EAChD,QAAkB;IAElB,IACE,YAAY,EAAE,MAAM,KAAK,OAAO;QAChC,CAAC,YAAY,CAAC,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EACpD,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,YAAY,CAAC,aAAa,EAA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quidConfig.js';\nimport {\n CHASE_ORDER_CONFIG,\n CHASE_ORDER_STATUS,\n ORDER_PRICE_WARNING_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n ChaseOrder,\n ChaseOrderLists,\n ChaseOrderStatus,\n ChasePlacementCheck,\n PerpsOrderCapabilities,\n PerpsStrategyRules,\n ScaleLadderSizing,\n ScalePriceWarning,\n StrategyOrderType,\n TwapOrder,\n TwapOrderStatus,\n TwapSlicePreview,\n} from '../types/index.js';\nimport { splitScaleSizes } from './orderCalculations.js';\n\n/** Result shape shared with `validateOrderParams`. */\nexport type AdvancedOrderValidationResult = {\n isValid: boolean;\n error?: string;\n};\n\nconst SECONDS_PER_MINUTE = 60;\nconst PERCENT_PER_RATIO = 100;\n\n/**\n * The venue's rules for one strategy on a market, read from the result of\n * `getOrderCapabilities`.\n *\n * @param capabilities - Order capabilities of the market.\n * @param strategy - Strategy whose rules are wanted.\n * @returns The rules, or `undefined` when the market is unavailable, the\n * venue does not run that strategy there, or it does not report the rules.\n */\nexport function getStrategyRules<Strategy extends StrategyOrderType>(\n capabilities: PerpsOrderCapabilities | undefined,\n strategy: Strategy,\n): PerpsStrategyRules[Strategy] | undefined {\n if (\n capabilities?.status !== 'ready' ||\n !capabilities.supportedStrategies.includes(strategy)\n ) {\n return undefined;\n }\n return capabilities.strategyRules?.[strategy];\n}\n\n// ---------------------------------------------------------------------------\n// TWAP\n// ---------------------------------------------------------------------------\n\n/** TWAP statuses that mean the schedule is still executing. */\nexport const TWAP_ORDER_ACTIVE_STATUSES: readonly TwapOrderStatus[] =\n Object.freeze(['active']);\n\n/**\n * Whether a TWAP schedule is still executing.\n *\n * @param order - TWAP schedule.\n * @returns True for an active schedule; every other status has ended.\n */\nexport function isTwapOrderActive(order: Pick<TwapOrder, 'status'>): boolean {\n return TWAP_ORDER_ACTIVE_STATUSES.includes(order.status);\n}\n\n/**\n * Split TWAP schedules into running and ended ones, keeping their order.\n *\n * @param orders - TWAP schedules.\n * @returns Active and ended schedules.\n */\nexport function partitionTwapOrders(orders: readonly TwapOrder[]): {\n active: TwapOrder[];\n ended: TwapOrder[];\n} {\n const active: TwapOrder[] = [];\n const ended: TwapOrder[] = [];\n for (const order of orders) {\n (isTwapOrderActive(order) ? active : ended).push(order);\n }\n return { active, ended };\n}\n\n/**\n * Bound a TWAP's executed size to its schedule and derive what remains.\n *\n * @param totalSize - Schedule size.\n * @param executedSize - Executed size as reported or proven by fills.\n * @returns Executed size within `[0, totalSize]`, the remaining size and the\n * fill progress in basis points (floored; 0 for an empty schedule).\n */\nexport function boundTwapExecution(\n totalSize: BigNumber,\n executedSize: BigNumber,\n): {\n executedSize: BigNumber;\n remainingSize: BigNumber;\n fillProgressBps: number;\n} {\n const executed = BigNumber.max(0, BigNumber.min(executedSize, totalSize));\n return {\n executedSize: executed,\n remainingSize: BigNumber.max(totalSize.minus(executed), 0),\n fillProgressBps: totalSize.isGreaterThan(0)\n ? executed\n .dividedBy(totalSize)\n .multipliedBy(BASIS_POINTS_DIVISOR)\n .integerValue(BigNumber.ROUND_FLOOR)\n .toNumber()\n : 0,\n };\n}\n\n/**\n * Whether a TWAP record replaces the one held for the same schedule.\n *\n * A venue reports one lifecycle as an activation plus a terminal record, and\n * `lastUpdated` can tie between them (it folds in slice fills both receive) or\n * favor the activation (a read folds fills in milliseconds, a terminal push\n * carries whole seconds). Terminality therefore decides first, since an ended\n * schedule never runs again; otherwise the strictly newer record wins.\n *\n * @param candidate - Record just received.\n * @param existing - Record already held.\n * @returns True when the candidate replaces the held record.\n */\nexport function supersedesTwapOrder(\n candidate: Pick<TwapOrder, 'status' | 'lastUpdated'>,\n existing: Pick<TwapOrder, 'status' | 'lastUpdated'>,\n): boolean {\n const candidateIsTerminal = !isTwapOrderActive(candidate);\n if (candidateIsTerminal !== !isTwapOrderActive(existing)) {\n return candidateIsTerminal;\n }\n return candidate.lastUpdated > existing.lastUpdated;\n}\n\n/**\n * Raise a TWAP's execution totals to what its slice fills prove executed.\n *\n * A venue can keep reporting zero executed size while slices fill, so the\n * fills are the fresher record. The totals are only ever raised: fills a read\n * did not page in never lower what the venue already reported.\n *\n * @param order - TWAP schedule with the slice fills known for it.\n * @returns The schedule with totals and progress raised from its fills.\n */\nexport function reconcileTwapExecution(order: TwapOrder): TwapOrder {\n if (order.fills.length === 0) {\n return order;\n }\n let filledSize = new BigNumber(0);\n let filledNotional = new BigNumber(0);\n for (const fill of order.fills) {\n const size = new BigNumber(fill.size);\n filledSize = filledSize.plus(size);\n filledNotional = filledNotional.plus(size.multipliedBy(fill.price));\n }\n const totalSize = new BigNumber(order.size);\n const reportedSize = new BigNumber(order.executedSize);\n if (\n !filledSize.isFinite() ||\n !filledNotional.isFinite() ||\n !totalSize.isGreaterThan(0) ||\n !filledSize.isGreaterThan(reportedSize.isFinite() ? reportedSize : 0)\n ) {\n return order;\n }\n\n const { executedSize, remainingSize, fillProgressBps } = boundTwapExecution(\n totalSize,\n filledSize,\n );\n const executedNotional = executedSize.isEqualTo(filledSize)\n ? filledNotional\n : filledNotional.multipliedBy(executedSize).dividedBy(filledSize);\n return {\n ...order,\n executedSize: executedSize.toFixed(),\n remainingSize: remainingSize.toFixed(),\n executedNotional: executedNotional.toFixed(),\n averagePrice: filledNotional.dividedBy(filledSize).toFixed(),\n fillProgressBps,\n };\n}\n\n/**\n * Identity of a TWAP schedule across reads and stream pushes.\n *\n * @param order - TWAP schedule.\n * @returns Provider-scoped order key.\n */\nexport const twapOrderKey = (\n order: Pick<TwapOrder, 'orderId' | 'providerId'>,\n): string => `${order.providerId ?? ''}:${order.orderId}`;\n\n/**\n * Merge one TWAP record into the one already held for the same schedule.\n * Fills are united by ID; schedule fields come from the record that\n * supersedes (see `supersedesTwapOrder`) or, on an equal version, from the\n * incoming one, and the totals are then raised from the fills.\n *\n * @param retained - Record already held, if any.\n * @param incoming - Newer record from a read or a stream push.\n * @returns The merged record.\n */\nfunction mergeTwapOrder(\n retained: TwapOrder | undefined,\n incoming: TwapOrder,\n): TwapOrder {\n if (!retained) {\n return reconcileTwapExecution(incoming);\n }\n const fills = new Map(retained.fills.map((fill) => [fill.fillId, fill]));\n for (const fill of incoming.fills) {\n fills.set(fill.fillId, fill);\n }\n // An equal version still carries fresher read-time fields (elapsed time,\n // time progress), so it replaces the held record unless that would turn an\n // ended schedule back into a running one.\n const sameVersion =\n incoming.lastUpdated === retained.lastUpdated &&\n isTwapOrderActive(incoming) === isTwapOrderActive(retained);\n const schedule =\n sameVersion || supersedesTwapOrder(incoming, retained)\n ? incoming\n : retained;\n return reconcileTwapExecution({\n ...schedule,\n fills: [...fills.values()].sort(\n (left, right) => left.timestamp - right.timestamp,\n ),\n });\n}\n\n/**\n * Merge TWAP records from a read or a stream push into held ones.\n *\n * A record is matched by provider and order ID. Held records missing from\n * `incoming` are kept: a stream carries no fills and caps ended history, so\n * absence there is not proof a schedule is gone.\n *\n * @param retained - Records already held.\n * @param incoming - Records from a read or stream push.\n * @returns Merged records, newest first.\n */\nexport function mergeTwapOrders(\n retained: readonly TwapOrder[],\n incoming: readonly TwapOrder[],\n): TwapOrder[] {\n const merged = new Map(retained.map((order) => [twapOrderKey(order), order]));\n for (const order of incoming) {\n const key = twapOrderKey(order);\n merged.set(key, mergeTwapOrder(merged.get(key), order));\n }\n return [...merged.values()].sort(\n (left, right) => right.startedAt - left.startedAt,\n );\n}\n\n/**\n * Check a TWAP draft against the venue's rules.\n *\n * @param params - Draft values and venue rules.\n * @param params.rules - TWAP rules from `getStrategyRules`; absent means the\n * venue does not run TWAP on this market.\n * @param params.durationMinutes - Running time in whole minutes.\n * @param params.usdAmount - Total order value in USD, when known.\n * @returns Validation result with a `PERPS_ERROR_CODES` error.\n */\nexport function validateTwapOrder(params: {\n rules: PerpsStrategyRules['twap'];\n durationMinutes?: number;\n usdAmount?: string | number;\n}): AdvancedOrderValidationResult {\n const { rules, durationMinutes, usdAmount } = params;\n if (!rules) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,\n };\n }\n if (durationMinutes === undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,\n };\n }\n if (\n !Number.isInteger(durationMinutes) ||\n durationMinutes < rules.minDurationMinutes ||\n durationMinutes > rules.maxDurationMinutes\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,\n };\n }\n if (usdAmount !== undefined) {\n const amount = new BigNumber(usdAmount);\n if (!amount.isFinite() || amount.isLessThan(rules.minNotionalUsd)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL,\n };\n }\n }\n return { isValid: true };\n}\n\n/**\n * Preview how a TWAP is cut into slices on the venue's cadence.\n *\n * The slice size is floored to the venue's size grid, so it is never shown\n * finer than the venue can trade; `isBelowMinimumSize` flags a slice that\n * floors to nothing.\n *\n * @param params - Draft values and venue rules.\n * @param params.rules - TWAP rules from `getStrategyRules`.\n * @param params.durationMinutes - Running time in whole minutes.\n * @param params.size - Total size in base units.\n * @param params.sizeDecimals - Venue size precision of the market.\n * @param params.price - Reference price, to value each slice.\n * @returns The preview, or `undefined` when the rules or inputs are missing.\n */\nexport function computeTwapSlicePreview(params: {\n rules: PerpsStrategyRules['twap'];\n durationMinutes?: number;\n size?: string | number;\n sizeDecimals: number;\n price?: string | number;\n}): TwapSlicePreview | undefined {\n const { rules, durationMinutes, sizeDecimals } = params;\n if (!rules || durationMinutes === undefined) {\n return undefined;\n }\n const sliceCount = Math.floor(\n (durationMinutes * SECONDS_PER_MINUTE) / rules.sliceIntervalSeconds,\n );\n const size = new BigNumber(params.size ?? Number.NaN);\n if (\n !Number.isFinite(sliceCount) ||\n sliceCount < 1 ||\n !size.isFinite() ||\n !size.isGreaterThan(0) ||\n !Number.isInteger(sizeDecimals) ||\n sizeDecimals < 0\n ) {\n return undefined;\n }\n\n const sizePerSlice = size\n .dividedBy(sliceCount)\n .decimalPlaces(sizeDecimals, BigNumber.ROUND_DOWN);\n const minimumSize = new BigNumber(1).shiftedBy(-sizeDecimals);\n const price = new BigNumber(params.price ?? Number.NaN);\n return {\n sliceCount,\n sliceIntervalSeconds: rules.sliceIntervalSeconds,\n sizePerSlice: sizePerSlice.toFixed(),\n sizeDecimals,\n minimumSize: minimumSize.toFixed(),\n isBelowMinimumSize: sizePerSlice.isLessThan(minimumSize),\n ...(price.isFinite() &&\n price.isGreaterThan(0) && {\n notionalPerSlice: sizePerSlice.multipliedBy(price).toFixed(),\n }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Chase\n// ---------------------------------------------------------------------------\n\n/**\n * Chase statuses that belong in the running list: still chasing, or waiting\n * for a cancel to settle.\n */\nexport const CHASE_ORDER_RUNNING_STATUSES: readonly ChaseOrderStatus[] =\n Object.freeze([\n CHASE_ORDER_STATUS.Active,\n CHASE_ORDER_STATUS.TerminationPending,\n ]);\n\n/**\n * Whether a chase belongs in the running list rather than history.\n *\n * @param order - Chase snapshot.\n * @returns True while it chases or its cancel is pending.\n */\nexport function isChaseOrderRunning(\n order: Pick<ChaseOrder, 'status'>,\n): boolean {\n return CHASE_ORDER_RUNNING_STATUSES.includes(order.status);\n}\n\n/**\n * Whether cancelling a chase by its handle can still do something: it is\n * running (a pending cancel may be retried), or it stopped with a child order\n * still resting.\n *\n * @param order - Chase snapshot.\n * @returns True when a cancel should be offered.\n */\nexport function isChaseOrderCancelable(\n order: Pick<ChaseOrder, 'status' | 'restingOrderId'>,\n): boolean {\n return isChaseOrderRunning(order) || order.restingOrderId !== null;\n}\n\n/**\n * Check whether another chase can be placed under the venue's cap.\n *\n * Only chases that are still chasing take a slot; one waiting on a cancel or\n * stopped by a cap does not, matching what the provider enforces.\n *\n * @param params - Venue rules and current chase snapshots.\n * @param params.rules - Chase rules from `getStrategyRules`.\n * @param params.chaseOrders - Current chase snapshots for the account.\n * @returns Whether a placement fits, with the counts it was judged on.\n */\nexport function checkChasePlacement(params: {\n rules: PerpsStrategyRules['chase'];\n chaseOrders: readonly Pick<ChaseOrder, 'status'>[];\n}): ChasePlacementCheck {\n const { rules, chaseOrders } = params;\n const activeCount = chaseOrders.filter(\n (order) => order.status === CHASE_ORDER_STATUS.Active,\n ).length;\n if (!rules) {\n return {\n canPlace: false,\n activeCount,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,\n };\n }\n const { maxActiveSessions } = rules;\n if (maxActiveSessions !== undefined && activeCount >= maxActiveSessions) {\n return {\n canPlace: false,\n activeCount,\n maxActiveSessions,\n error: PERPS_ERROR_CODES.ORDER_CHASE_LIMIT_REACHED,\n };\n }\n return {\n canPlace: true,\n activeCount,\n ...(maxActiveSessions !== undefined && { maxActiveSessions }),\n };\n}\n\n/**\n * Identity of a chase session across reads.\n *\n * @param order - Chase snapshot.\n * @returns Provider-scoped handle key.\n */\nexport const chaseOrderKey = (\n order: Pick<ChaseOrder, 'handle' | 'providerId'>,\n): string => `${order.providerId ?? ''}:${order.handle}`;\n\nconst newestChaseFirst = (left: ChaseOrder, right: ChaseOrder): number =>\n right.startedAt - left.startedAt || left.handle.localeCompare(right.handle);\n\n/**\n * Build running and history chase lists from a fresh read, keeping ended\n * chases a provider has since dropped.\n *\n * A chase that vanishes while running is dropped: without its ending the list\n * would show a guess. History is bounded to the newest `historyLimit` rows.\n *\n * @param params - Previous lists and the latest read.\n * @param params.previous - Lists built from the previous read.\n * @param params.current - Chase snapshots from the latest read.\n * @param params.historyLimit - Most ended chases kept.\n * @returns Running and history lists, newest first.\n */\nexport function mergeChaseOrderHistory(params: {\n previous?: ChaseOrderLists;\n current: readonly ChaseOrder[];\n historyLimit?: number;\n}): ChaseOrderLists {\n const { previous, current } = params;\n const historyLimit = params.historyLimit ?? CHASE_ORDER_CONFIG.HistoryLimit;\n const running: ChaseOrder[] = [];\n const history = new Map<string, ChaseOrder>();\n for (const order of previous?.history ?? []) {\n history.set(chaseOrderKey(order), order);\n }\n for (const order of current) {\n if (isChaseOrderRunning(order)) {\n running.push(order);\n } else {\n history.set(chaseOrderKey(order), order);\n }\n }\n return {\n running: running.sort(newestChaseFirst),\n history: [...history.values()]\n .sort(newestChaseFirst)\n .slice(0, historyLimit),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Scale\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a positive decimal amount exactly.\n *\n * @param raw - Decimal string.\n * @returns The amount.\n * @throws `ORDER_SIZE_POSITIVE` when it is not a positive decimal.\n */\nfunction parsePositiveDecimal(raw: unknown): BigNumber {\n const value =\n typeof raw === 'string' &&\n /^(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u.test(raw)\n ? new BigNumber(raw)\n : new BigNumber(Number.NaN);\n if (!value.isFinite() || !value.isGreaterThan(0)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n return value;\n}\n\n/**\n * Size a scale ladder by the one rule every venue applies: an exact base size\n * is split as given; a USD amount buys the largest size on the venue's grid\n * whose ladder value, rung price times rung size, stays within it.\n *\n * @param params - Normalized ladder prices and the sizing intent.\n * @param params.prices - Venue-normalized rung prices, in ladder order.\n * @param params.sizeDecimals - Venue size precision of the market.\n * @param params.skew - Optional rung-size skew, as `splitScaleSizes` takes it.\n * @param params.size - Exact total base size.\n * @param params.usdAmount - Maximum ladder value in USD.\n * @returns Rung sizes and ladder totals.\n * @throws `ORDER_SIZE_POSITIVE` for a missing or non-positive amount, and\n * `ORDER_SCALE_SIZE_TOO_SMALL` when no rung can get a grid unit. The internal\n * guards `ORDER_SCALE_SIZE_CONSERVATION_FAILED` and\n * `ORDER_SCALE_EXPOSURE_EXCEEDS_INTENT` fire only if the split itself breaks.\n */\nexport function sizeScaleLadder(\n params: {\n prices: readonly string[];\n sizeDecimals: number;\n skew?: number;\n } & (\n | { size: string; usdAmount?: never }\n | { usdAmount: string; size?: never }\n ),\n): ScaleLadderSizing {\n const { prices, sizeDecimals: decimals, skew } = params;\n const count = prices.length;\n const budget =\n params.usdAmount === undefined\n ? undefined\n : parsePositiveDecimal(params.usdAmount);\n const lowestPrice = BigNumber.min(...prices.map(parsePositiveDecimal));\n const rawSize = budget\n ? budget.dividedBy(lowestPrice)\n : parsePositiveDecimal(params.size);\n const units = rawSize.shiftedBy(decimals).integerValue(BigNumber.ROUND_DOWN);\n if (units.isGreaterThan(Number.MAX_SAFE_INTEGER) || units.isLessThan(count)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n\n // `splitScaleSizes` works in floats, so each split is checked to keep every\n // grid unit and stay on the grid before it can be priced or placed.\n const split = (totalUnits: number): string[] => {\n const sizes = splitScaleSizes({\n totalSize: new BigNumber(totalUnits).shiftedBy(-decimals).toNumber(),\n count,\n szDecimals: decimals,\n skew,\n });\n const rungUnits = sizes.map((size) =>\n new BigNumber(size).shiftedBy(decimals),\n );\n if (\n rungUnits.some((unit) => !unit.isInteger()) ||\n !BigNumber.sum(...rungUnits).isEqualTo(totalUnits)\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);\n }\n return sizes;\n };\n const value = (sizes: string[]): BigNumber =>\n sizes.reduce(\n (total, size, index) =>\n total.plus(new BigNumber(size).times(prices[index])),\n new BigNumber(0),\n );\n\n let totalUnits = units.toNumber();\n if (budget) {\n let low = count;\n let high = totalUnits;\n let feasible: number | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n let sizes: string[];\n try {\n sizes = split(candidate);\n } catch {\n low = candidate + 1;\n continue;\n }\n if (value(sizes).isLessThanOrEqualTo(budget)) {\n feasible = candidate;\n low = candidate + 1;\n } else {\n high = candidate - 1;\n }\n }\n if (feasible === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n totalUnits = feasible;\n }\n\n const sizes = split(totalUnits);\n const totalSize = new BigNumber(totalUnits).shiftedBy(-decimals);\n const totalNotional = value(sizes);\n if (\n totalSize.isGreaterThan(rawSize) ||\n (budget && totalNotional.isGreaterThan(budget))\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_EXPOSURE_EXCEEDS_INTENT);\n }\n return {\n sizes,\n totalSize: totalSize.toFixed(),\n totalNotional: totalNotional.toFixed(),\n };\n}\n\n/**\n * Check a scale draft against the venue's rules and, when the venue preview\n * is known, its per-rung minimum.\n *\n * @param params - Draft values, venue rules and the optional venue preview.\n * @param params.rules - Scale rules from `getStrategyRules`.\n * @param params.minPrice - Lowest ladder price.\n * @param params.maxPrice - Highest ladder price.\n * @param params.count - Number of rungs.\n * @param params.skew - Optional rung-size skew.\n * @param params.preview - Ladder prices and sizes from `getScalePriceLadder`,\n * with the venue's per-order minimum value.\n * @returns Validation result with a `PERPS_ERROR_CODES` error.\n */\nexport function validateScaleOrder(params: {\n rules: PerpsStrategyRules['scale'];\n minPrice?: number;\n maxPrice?: number;\n count?: number;\n skew?: number;\n preview?: Readonly<{\n prices: readonly string[];\n sizes: readonly string[];\n minimumQuoteAmount: string;\n }>;\n}): AdvancedOrderValidationResult {\n const { rules, minPrice, maxPrice, count, skew, preview } = params;\n if (!rules) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,\n };\n }\n if (minPrice === undefined || maxPrice === undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,\n };\n }\n if (\n !Number.isFinite(minPrice) ||\n !Number.isFinite(maxPrice) ||\n minPrice <= 0 ||\n maxPrice <= minPrice\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,\n };\n }\n if (\n count === undefined ||\n !Number.isInteger(count) ||\n count < rules.minOrders ||\n count > rules.maxOrders\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,\n };\n }\n // Omitted is an even ladder, so only a supplied skew is checked.\n if (skew !== undefined && (!Number.isFinite(skew) || skew <= 0)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,\n };\n }\n if (preview) {\n // Each rung is its own order, so the venue minimum applies to every rung,\n // not to the ladder's total. An unreadable preview, or one without exactly\n // `count` rungs, fails.\n const minimum = new BigNumber(preview.minimumQuoteAmount);\n const belowMinimum =\n preview.prices.length !== count ||\n preview.sizes.length !== count ||\n preview.sizes.some(\n (size, index) =>\n !new BigNumber(size)\n .times(preview.prices[index])\n .isGreaterThanOrEqualTo(minimum),\n );\n if (belowMinimum) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL,\n };\n }\n }\n return { isValid: true };\n}\n\n/**\n * Classify scale ladder prices against the book for warnings.\n *\n * - `crosses_market` / `partially_crosses_market`: both or one ladder end is at\n * or through the opposite touch (best ask for a buy, best bid for a sell),\n * so those rungs fill at once as taker.\n * - `far_from_market`: the far ladder end sits more than\n * `ORDER_PRICE_WARNING_CONFIG.FarFromMarketRatio` from the near touch (best\n * bid for a buy, best ask for a sell); `distancePercent` is that distance,\n * rounded up to a whole percent.\n *\n * A reduce-only ladder gets no distance warning, since it only closes. Each\n * check is skipped while its touch is unknown.\n *\n * @param params - Ladder prices, side and top of book.\n * @param params.prices - Rung prices (any order).\n * @param params.isBuy - Whether the ladder buys.\n * @param params.bestBid - Best bid price.\n * @param params.bestAsk - Best ask price.\n * @param params.reduceOnly - Whether the ladder only reduces a position.\n * @returns Warnings, empty when there is nothing to warn about.\n */\nexport function classifyScalePriceWarnings(params: {\n prices: readonly (string | number)[];\n isBuy: boolean;\n bestBid?: string | number;\n bestAsk?: string | number;\n reduceOnly?: boolean;\n}): ScalePriceWarning[] {\n const { isBuy } = params;\n const prices = params.prices.map((price) => new BigNumber(price));\n if (\n prices.length === 0 ||\n prices.some((price) => !price.isFinite() || !price.isGreaterThan(0))\n ) {\n return [];\n }\n const touch = (price?: string | number): BigNumber | undefined => {\n const parsed = new BigNumber(price ?? Number.NaN);\n return parsed.isFinite() && parsed.isGreaterThan(0) ? parsed : undefined;\n };\n const oppositeTouch = touch(isBuy ? params.bestAsk : params.bestBid);\n const nearTouch = touch(isBuy ? params.bestBid : params.bestAsk);\n const ends = [BigNumber.min(...prices), BigNumber.max(...prices)];\n const warnings: ScalePriceWarning[] = [];\n\n if (oppositeTouch) {\n const crossing = ends.filter((price) =>\n isBuy\n ? price.isGreaterThanOrEqualTo(oppositeTouch)\n : price.isLessThanOrEqualTo(oppositeTouch),\n ).length;\n if (crossing === ends.length) {\n warnings.push({ code: 'crosses_market' });\n } else if (crossing > 0) {\n warnings.push({ code: 'partially_crosses_market' });\n }\n }\n\n if (nearTouch && !params.reduceOnly) {\n const far = isBuy ? ends[0] : ends[1];\n const distance = (\n isBuy ? nearTouch.minus(far) : far.minus(nearTouch)\n ).dividedBy(nearTouch);\n if (distance.isGreaterThan(ORDER_PRICE_WARNING_CONFIG.FarFromMarketRatio)) {\n warnings.push({\n code: 'far_from_market',\n distancePercent: distance\n .times(PERCENT_PER_RATIO)\n .integerValue(BigNumber.ROUND_CEIL)\n .toNumber(),\n });\n }\n }\n return warnings;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAWA,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,IAAI,gBAAgB,EAC/B,QAAQ,EACR,oBAAoB,EACpB,WAAW,EACX,eAAe,EACf,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EA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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"}
@@ -345,13 +345,16 @@ export function adaptPositionTriggerOrderFromSDK(params) {
345
345
  };
346
346
  }
347
347
  export function adaptMarketFromSDK(sdkMarket) {
348
+ // The venue also sends `normal` (no restriction), which the SDK type omits.
349
+ // `MarketInfo.marginMode` carries restrictions only, so drop it.
350
+ const venueMarginMode = sdkMarket.marginMode;
348
351
  return {
349
352
  name: sdkMarket.name,
350
353
  szDecimals: sdkMarket.szDecimals,
351
354
  maxLeverage: sdkMarket.maxLeverage,
352
355
  marginTableId: sdkMarket.marginTableId,
353
356
  onlyIsolated: sdkMarket.onlyIsolated,
354
- marginMode: sdkMarket.marginMode,
357
+ ...(venueMarginMode !== 'normal' && { marginMode: sdkMarket.marginMode }),
355
358
  isDelisted: sdkMarket.isDelisted,
356
359
  };
357
360
  }
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidAdapter.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAO,WA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AAM;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';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\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\nexport function adaptPositionFromSDK(assetPosition: AssetPosition): Position {\n const pos = assetPosition.position;\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 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 return {\n name: sdkMarket.name,\n szDecimals: sdkMarket.szDecimals,\n maxLeverage: sdkMarket.maxLeverage,\n marginTableId: sdkMarket.marginTableId,\n onlyIsolated: sdkMarket.onlyIsolated,\n marginMode: sdkMarket.marginMode,\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;AAEhE,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAsB1D,OAAO,EACL,qBAAq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AK,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';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\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\nexport function adaptPositionFromSDK(assetPosition: AssetPosition): Position {\n const pos = assetPosition.position;\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 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 ...(venueMarginMode !== 'normal' && { marginMode: sdkMarket.marginMode }),\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 +1 @@
1
- {"version":3,"file":"hyperLiquidValidation.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAcxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAE3D,OAAO,KAAK,EACV,uBAAuB,EACvB,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,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AAC;IAChD,WAAW,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GACA;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CA4ItC;AA2DD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAStC"}
@@ -1,10 +1,11 @@
1
1
  import { isValidHexAddress } from '@metamask/utils';
2
- import { HYPERLIQUID_ASSET_CONFIGS, BASIS_POINTS_DIVISOR, getSupportedAssets, TRADING_DEFAULTS, } from '../constants/hyperLiquidConfig.js';
3
- import { CHASE_ORDER_CONFIG, HYPERLIQUID_ORDER_LIMITS, HYPERLIQUID_TWAP_LIMITS, } from '../constants/perpsConfig.js';
2
+ import { HYPERLIQUID_ASSET_CONFIGS, HYPERLIQUID_ORDER_CAPABILITIES, BASIS_POINTS_DIVISOR, getSupportedAssets, TRADING_DEFAULTS, } from '../constants/hyperLiquidConfig.js';
3
+ import { CHASE_ORDER_CONFIG, HYPERLIQUID_ORDER_LIMITS, } from '../constants/perpsConfig.js';
4
4
  import { PerpsControllerError } from '../errors.js';
5
5
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
6
+ import { validateScaleOrder, validateTwapOrder } from './advancedOrders.js';
6
7
  import { ensureError } from './errorUtils.js';
7
- import { getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, isTriggerOrderType, SCALE_ORDER_COUNT, } from './orderTypes.js';
8
+ import { getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, isTriggerOrderType, } from './orderTypes.js';
8
9
  /**
9
10
  * Validation utilities for HyperLiquid operations
10
11
  */
@@ -418,24 +419,13 @@ const STRATEGY_FIELD_OWNER = {
418
419
  * @returns Validation result with isValid flag and optional error message.
419
420
  */
420
421
  function validateTwapParams(params) {
421
- if (params.twapDuration === undefined) {
422
- return {
423
- isValid: false,
424
- error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,
425
- };
426
- }
427
422
  // The venue validates `twap.m` as a safe integer within these bounds before
428
423
  // the request is signed, so checking it here turns an opaque SDK failure into
429
424
  // a typed rejection that costs no round trip.
430
- if (!Number.isInteger(params.twapDuration) ||
431
- params.twapDuration < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||
432
- params.twapDuration > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes) {
433
- return {
434
- isValid: false,
435
- error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,
436
- };
437
- }
438
- return { isValid: true };
425
+ return validateTwapOrder({
426
+ rules: HYPERLIQUID_ORDER_CAPABILITIES.strategyRules?.twap,
427
+ durationMinutes: params.twapDuration,
428
+ });
439
429
  }
440
430
  /**
441
431
  * Validate the ladder parameters of a `scale` placement.
@@ -444,45 +434,20 @@ function validateTwapParams(params) {
444
434
  * @returns Validation result with isValid flag and optional error message.
445
435
  */
446
436
  function validateScaleParams(params) {
447
- if (params.scaleMinPrice === undefined ||
448
- params.scaleMaxPrice === undefined) {
449
- return {
450
- isValid: false,
451
- error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,
452
- };
453
- }
454
- const minPrice = parseFloat(params.scaleMinPrice);
455
- const maxPrice = parseFloat(params.scaleMaxPrice);
456
- if (!Number.isFinite(minPrice) ||
457
- !Number.isFinite(maxPrice) ||
458
- minPrice <= 0 ||
459
- maxPrice <= minPrice) {
460
- return {
461
- isValid: false,
462
- error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,
463
- };
464
- }
465
- if (params.scaleNumOrders === undefined ||
466
- !Number.isInteger(params.scaleNumOrders) ||
467
- params.scaleNumOrders < SCALE_ORDER_COUNT.min ||
468
- params.scaleNumOrders > SCALE_ORDER_COUNT.max) {
469
- return {
470
- isValid: false,
471
- error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,
472
- };
473
- }
474
- // Omitted is an even ladder, so only a supplied skew is checked. The value is
475
- // taken exactly as the caller wrote it: clients coerce their input to two
476
- // decimals, and rounding it again here would place a ladder weighted
477
- // differently from the one the form previewed.
478
- if (params.scaleSkew !== undefined &&
479
- (!Number.isFinite(params.scaleSkew) || params.scaleSkew <= 0)) {
480
- return {
481
- isValid: false,
482
- error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,
483
- };
484
- }
485
- return { isValid: true };
437
+ // The skew is taken exactly as the caller wrote it: clients coerce their
438
+ // input to two decimals, and rounding it again here would place a ladder
439
+ // weighted differently from the one the form previewed.
440
+ return validateScaleOrder({
441
+ rules: HYPERLIQUID_ORDER_CAPABILITIES.strategyRules?.scale,
442
+ minPrice: params.scaleMinPrice === undefined
443
+ ? undefined
444
+ : parseFloat(params.scaleMinPrice),
445
+ maxPrice: params.scaleMaxPrice === undefined
446
+ ? undefined
447
+ : parseFloat(params.scaleMaxPrice),
448
+ count: params.scaleNumOrders,
449
+ skew: params.scaleSkew,
450
+ });
486
451
  }
487
452
  /**
488
453
  * Validate the polling parameters of a `chase` placement.