@metamask-previews/perps-controller 10.0.0-preview-a42e8d0d2 → 10.0.0-preview-5a03e1b92

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 (106) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/constants/eventNames.cjs +6 -0
  3. package/dist/constants/eventNames.cjs.map +1 -1
  4. package/dist/constants/eventNames.d.cts +4 -0
  5. package/dist/constants/eventNames.d.cts.map +1 -1
  6. package/dist/constants/eventNames.d.mts +4 -0
  7. package/dist/constants/eventNames.d.mts.map +1 -1
  8. package/dist/constants/eventNames.mjs +6 -0
  9. package/dist/constants/eventNames.mjs.map +1 -1
  10. package/dist/index.cjs +86 -74
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -1
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +3 -1
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +2 -0
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/perpsErrorCodes.cjs +16 -0
  19. package/dist/perpsErrorCodes.cjs.map +1 -1
  20. package/dist/perpsErrorCodes.d.cts +12 -0
  21. package/dist/perpsErrorCodes.d.cts.map +1 -1
  22. package/dist/perpsErrorCodes.d.mts +12 -0
  23. package/dist/perpsErrorCodes.d.mts.map +1 -1
  24. package/dist/perpsErrorCodes.mjs +16 -0
  25. package/dist/perpsErrorCodes.mjs.map +1 -1
  26. package/dist/providers/HyperLiquidProvider.cjs +674 -77
  27. package/dist/providers/HyperLiquidProvider.cjs.map +1 -1
  28. package/dist/providers/HyperLiquidProvider.d.cts +13 -0
  29. package/dist/providers/HyperLiquidProvider.d.cts.map +1 -1
  30. package/dist/providers/HyperLiquidProvider.d.mts +13 -0
  31. package/dist/providers/HyperLiquidProvider.d.mts.map +1 -1
  32. package/dist/providers/HyperLiquidProvider.mjs +676 -79
  33. package/dist/providers/HyperLiquidProvider.mjs.map +1 -1
  34. package/dist/selectors.cjs.map +1 -1
  35. package/dist/selectors.d.cts +17 -17
  36. package/dist/selectors.d.cts.map +1 -1
  37. package/dist/selectors.d.mts +17 -17
  38. package/dist/selectors.d.mts.map +1 -1
  39. package/dist/selectors.mjs.map +1 -1
  40. package/dist/services/HyperLiquidSubscriptionService.cjs +121 -11
  41. package/dist/services/HyperLiquidSubscriptionService.cjs.map +1 -1
  42. package/dist/services/HyperLiquidSubscriptionService.d.cts +21 -0
  43. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +1 -1
  44. package/dist/services/HyperLiquidSubscriptionService.d.mts +21 -0
  45. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +1 -1
  46. package/dist/services/HyperLiquidSubscriptionService.mjs +121 -11
  47. package/dist/services/HyperLiquidSubscriptionService.mjs.map +1 -1
  48. package/dist/services/TradingService.cjs +6 -2
  49. package/dist/services/TradingService.cjs.map +1 -1
  50. package/dist/services/TradingService.d.cts.map +1 -1
  51. package/dist/services/TradingService.d.mts.map +1 -1
  52. package/dist/services/TradingService.mjs +6 -2
  53. package/dist/services/TradingService.mjs.map +1 -1
  54. package/dist/types/index.cjs.map +1 -1
  55. package/dist/types/index.d.cts +69 -4
  56. package/dist/types/index.d.cts.map +1 -1
  57. package/dist/types/index.d.mts +69 -4
  58. package/dist/types/index.d.mts.map +1 -1
  59. package/dist/types/index.mjs.map +1 -1
  60. package/dist/types/perps-types.cjs.map +1 -1
  61. package/dist/types/perps-types.d.cts +35 -1
  62. package/dist/types/perps-types.d.cts.map +1 -1
  63. package/dist/types/perps-types.d.mts +35 -1
  64. package/dist/types/perps-types.d.mts.map +1 -1
  65. package/dist/types/perps-types.mjs.map +1 -1
  66. package/dist/utils/hyperLiquidAdapter.cjs +168 -10
  67. package/dist/utils/hyperLiquidAdapter.cjs.map +1 -1
  68. package/dist/utils/hyperLiquidAdapter.d.cts +35 -1
  69. package/dist/utils/hyperLiquidAdapter.d.cts.map +1 -1
  70. package/dist/utils/hyperLiquidAdapter.d.mts +35 -1
  71. package/dist/utils/hyperLiquidAdapter.d.mts.map +1 -1
  72. package/dist/utils/hyperLiquidAdapter.mjs +166 -11
  73. package/dist/utils/hyperLiquidAdapter.mjs.map +1 -1
  74. package/dist/utils/hyperLiquidValidation.cjs +160 -5
  75. package/dist/utils/hyperLiquidValidation.cjs.map +1 -1
  76. package/dist/utils/hyperLiquidValidation.d.cts +23 -4
  77. package/dist/utils/hyperLiquidValidation.d.cts.map +1 -1
  78. package/dist/utils/hyperLiquidValidation.d.mts +23 -4
  79. package/dist/utils/hyperLiquidValidation.d.mts.map +1 -1
  80. package/dist/utils/hyperLiquidValidation.mjs +160 -5
  81. package/dist/utils/hyperLiquidValidation.mjs.map +1 -1
  82. package/dist/utils/index.cjs +5 -1
  83. package/dist/utils/index.cjs.map +1 -1
  84. package/dist/utils/index.d.cts +2 -1
  85. package/dist/utils/index.d.cts.map +1 -1
  86. package/dist/utils/index.d.mts +2 -1
  87. package/dist/utils/index.d.mts.map +1 -1
  88. package/dist/utils/index.mjs +2 -1
  89. package/dist/utils/index.mjs.map +1 -1
  90. package/dist/utils/orderCalculations.cjs +363 -37
  91. package/dist/utils/orderCalculations.cjs.map +1 -1
  92. package/dist/utils/orderCalculations.d.cts +87 -2
  93. package/dist/utils/orderCalculations.d.cts.map +1 -1
  94. package/dist/utils/orderCalculations.d.mts +87 -2
  95. package/dist/utils/orderCalculations.d.mts.map +1 -1
  96. package/dist/utils/orderCalculations.mjs +359 -36
  97. package/dist/utils/orderCalculations.mjs.map +1 -1
  98. package/dist/utils/orderTypes.cjs +222 -0
  99. package/dist/utils/orderTypes.cjs.map +1 -0
  100. package/dist/utils/orderTypes.d.cts +114 -0
  101. package/dist/utils/orderTypes.d.cts.map +1 -0
  102. package/dist/utils/orderTypes.d.mts +114 -0
  103. package/dist/utils/orderTypes.d.mts.map +1 -0
  104. package/dist/utils/orderTypes.mjs +210 -0
  105. package/dist/utils/orderTypes.mjs.map +1 -0
  106. package/package.json +7 -6
@@ -1 +1 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,IAAI;YACP,CAAC,EAAE;gBACD,OAAO,EAAE;oBACP,QAAQ,EAAE,IAAI;oBACd,SAAS,EAAE,sBAAsB,CAAC;wBAChC,KAAK,EAAE,gBAAgB;wBACvB,UAAU;qBACX,CAAC;oBACF,IAAI,EAAE,IAAI;iBACX;aACF;SACF,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;IAED,qBAAqB;IACrB,MAAM,aAAa,GACjB,QAAQ,IAAI,CAAC,CAAC,eAAe,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAEzE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';\nimport {\n MAX_ORDER_MARGIN_BUFFER,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { SDKOrderParams } from '../types/hyperliquid-types.js';\nimport type { PerpsDebugLogger } from '../types/index.js';\nimport {\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n} from './hyperLiquidAdapter.js';\n\n/**\n * Optional debug logger for order calculation functions.\n * When provided, enables detailed logging for debugging.\n */\nexport type OrderCalculationsDebugLogger = PerpsDebugLogger | undefined;\n\ntype PositionSizeParams = {\n amount: string;\n price: number;\n szDecimals: number;\n};\n\ntype MarginRequiredParams = {\n amount: string;\n leverage: number;\n};\n\ntype MaxAllowedAmountParams = {\n spendableBalance: number;\n assetPrice: number;\n assetSzDecimals: number;\n leverage: number;\n};\n\n// Advanced order calculation interfaces\nexport type CalculateFinalPositionSizeParams = {\n usdAmount?: string;\n size?: string;\n currentPrice: number;\n priceAtCalculation?: number;\n maxSlippageBps?: number;\n szDecimals: number;\n leverage?: number;\n debugLogger?: OrderCalculationsDebugLogger;\n};\n\nexport type CalculateFinalPositionSizeResult = {\n finalPositionSize: number;\n};\n\nexport type CalculateOrderPriceAndSizeParams = {\n orderType: 'market' | 'limit';\n isBuy: boolean;\n finalPositionSize: number;\n currentPrice: number;\n limitPrice?: string;\n // Max slippage in basis points (e.g. 300 = 3%). Only applied to market orders;\n // limit orders use limitPrice directly. Falls back to ORDER_SLIPPAGE_CONFIG\n // .DefaultMarketSlippageBps when omitted on a market order.\n maxSlippageBps?: number;\n szDecimals: number;\n};\n\nexport type CalculateOrderPriceAndSizeResult = {\n orderPrice: number;\n formattedSize: string;\n formattedPrice: string;\n};\n\nexport type BuildOrdersArrayParams = {\n assetId: number;\n isBuy: boolean;\n formattedPrice: string;\n formattedSize: string;\n reduceOnly: boolean;\n orderType: 'market' | 'limit';\n clientOrderId?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n szDecimals: number;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\nexport type BuildOrdersArrayResult = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\n/**\n * Calculate position size based on USD amount and asset price\n *\n * @param params - Amount in USD, current asset price, and required decimal precision\n * @returns Position size formatted to the asset's decimal precision\n */\nexport function calculatePositionSize(params: PositionSizeParams): string {\n const { amount, price, szDecimals } = params;\n\n // Validate required parameters\n if (szDecimals === undefined || szDecimals === null) {\n throw new Error('szDecimals is required for position size calculation');\n }\n if (szDecimals < 0) {\n throw new Error(`szDecimals must be >= 0, got: ${szDecimals}`);\n }\n\n const amountNum = parseFloat(amount || '0');\n\n if (isNaN(amountNum) || isNaN(price) || amountNum === 0 || price === 0) {\n return (0).toFixed(szDecimals);\n }\n\n const positionSize = amountNum / price;\n const multiplier = Math.pow(10, szDecimals);\n let rounded = Math.round(positionSize * multiplier) / multiplier;\n\n // Ensure rounded size meets requested USD (fix validation gap)\n const actualUsd = rounded * price;\n if (actualUsd < amountNum) {\n rounded += 1 / multiplier;\n }\n\n return rounded.toFixed(szDecimals);\n}\n\n/**\n * Calculate margin required for a position\n *\n * @param params - Position amount and leverage\n * @returns Margin required formatted to 2 decimal places\n */\nexport function calculateMarginRequired(params: MarginRequiredParams): string {\n const { amount, leverage } = params;\n const amountNum = parseFloat(amount || '0');\n\n if (\n isNaN(amountNum) ||\n isNaN(leverage) ||\n amountNum === 0 ||\n leverage === 0\n ) {\n return '0.00';\n }\n\n return (amountNum / leverage).toFixed(2);\n}\n\nexport function getMaxAllowedAmount(params: MaxAllowedAmountParams): number {\n const { spendableBalance, assetPrice, assetSzDecimals, leverage } = params;\n if (spendableBalance === 0 || !assetPrice || assetSzDecimals === undefined) {\n return 0;\n }\n\n // The theoretical maximum is simply spendableBalance * leverage\n const theoreticalMax = spendableBalance * leverage;\n\n // But we need to account for position size rounding\n // Find the largest whole dollar amount that fits within this limit\n let maxAmount = Math.floor(theoreticalMax);\n\n // Verify this amount doesn't exceed available balance after rounding\n const testPositionSize = calculatePositionSize({\n amount: maxAmount.toString(),\n price: assetPrice,\n szDecimals: assetSzDecimals,\n });\n\n const actualNotionalValue = parseFloat(testPositionSize) * assetPrice;\n const requiredMargin = actualNotionalValue / leverage;\n\n // If rounding caused us to exceed available balance, step down by one position increment\n if (requiredMargin > spendableBalance) {\n const minPositionSizeIncrement = 1 / Math.pow(10, assetSzDecimals);\n const positionSizeIncrementUsd = Math.ceil(\n minPositionSizeIncrement * assetPrice,\n );\n maxAmount -= positionSizeIncrementUsd;\n }\n\n // Apply margin buffer to reduce \"Insufficient margin\" rejections from the exchange\n // (fees, rounding, and exchange-side checks can make 100% theoretical max fail)\n const bufferedMax = maxAmount * (1 - MAX_ORDER_MARGIN_BUFFER);\n\n return Math.max(0, Math.floor(bufferedMax));\n}\n\n/**\n * Calculates final position size using USD as source of truth with price validation\n *\n * This function implements the hybrid approach where USD is the source of truth,\n * but includes price staleness validation and proper rounding to prevent precision loss.\n *\n * @param params - USD amount, size, prices, and configuration\n * @returns Final position size as a number\n */\nexport function calculateFinalPositionSize(\n params: CalculateFinalPositionSizeParams,\n): CalculateFinalPositionSizeResult {\n const {\n usdAmount,\n size,\n currentPrice,\n priceAtCalculation,\n maxSlippageBps,\n szDecimals,\n leverage,\n debugLogger,\n } = params;\n\n let finalPositionSize: number;\n\n if (usdAmount && parseFloat(usdAmount) > 0) {\n // USD amount provided - use it as source of truth\n const usdValue = parseFloat(usdAmount);\n\n // 1. Validate price staleness if priceAtCalculation provided\n if (priceAtCalculation) {\n const priceDeltaBps = Math.abs(\n ((currentPrice - priceAtCalculation) / priceAtCalculation) * 10000,\n );\n const maxSlippageBpsValue =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n\n if (priceDeltaBps > maxSlippageBpsValue) {\n throw new Error(\n `Price moved too much: ${priceDeltaBps.toFixed(0)} bps (max: ${maxSlippageBpsValue} bps). ` +\n `Expected: ${priceAtCalculation.toFixed(2)}, Current: ${currentPrice.toFixed(2)}`,\n );\n }\n\n debugLogger?.log('Price validation passed:', {\n priceAtCalculation,\n currentPrice,\n deltaBps: priceDeltaBps.toFixed(2),\n maxSlippageBps: maxSlippageBpsValue,\n });\n }\n\n // 2. Recalculate position size with fresh price\n finalPositionSize = usdValue / currentPrice;\n\n // 3. Apply size decimals rounding\n const multiplier = Math.pow(10, szDecimals);\n finalPositionSize = Math.round(finalPositionSize * multiplier) / multiplier;\n\n // 4. Ensure rounded size meets requested USD (fix validation gap)\n let actualNotionalValue = finalPositionSize * currentPrice;\n if (actualNotionalValue < usdValue) {\n // Add 1 minimum increment to meet requested USD\n finalPositionSize += 1 / multiplier;\n actualNotionalValue = finalPositionSize * currentPrice;\n\n debugLogger?.log('Position size adjusted to meet USD minimum:', {\n requestedUsd: usdValue,\n beforeAdjustment: finalPositionSize - 1 / multiplier,\n afterAdjustment: finalPositionSize,\n actualUsd: actualNotionalValue,\n });\n }\n\n const requiredMargin = actualNotionalValue / (leverage ?? 1);\n\n // Log if rounding caused significant difference\n const usdDifference = Math.abs(actualNotionalValue - usdValue);\n if (usdDifference > 0.01) {\n debugLogger?.log(\n 'Position size rounding caused USD difference (acceptable):',\n {\n requestedUsd: usdValue,\n actualUsd: actualNotionalValue,\n difference: usdDifference,\n positionSize: finalPositionSize,\n },\n );\n }\n\n debugLogger?.log('Recalculated position size with fresh price:', {\n usdAmount: usdValue,\n priceAtCalculation,\n currentPrice,\n originalSize: size,\n recalculatedSize: finalPositionSize,\n requiredMargin,\n minIncrement: 1 / multiplier,\n });\n } else {\n // Legacy: Use provided size (backward compatibility)\n finalPositionSize = parseFloat(size ?? '0');\n\n debugLogger?.log(\n 'Using legacy size calculation (no USD amount provided):',\n {\n providedSize: size,\n finalSize: finalPositionSize,\n },\n );\n }\n\n return { finalPositionSize };\n}\n\n/**\n * Calculates order price and formatted size based on order type\n *\n * @param params - Order parameters including type, direction, size, and prices\n * @returns Formatted order price, size, and price string\n */\nexport function calculateOrderPriceAndSize(\n params: CalculateOrderPriceAndSizeParams,\n): CalculateOrderPriceAndSizeResult {\n const {\n orderType,\n isBuy,\n finalPositionSize,\n currentPrice,\n limitPrice,\n maxSlippageBps,\n szDecimals,\n } = params;\n\n let orderPrice: number;\n let formattedSize: string;\n\n if (orderType === 'market') {\n // Market orders: apply slippage buffer to the live price so HyperLiquid\n // receives a worst-case acceptable limit price. Falls back to the\n // documented default if the caller does not provide one.\n const effectiveBps =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n const slippageValue = effectiveBps / BASIS_POINTS_DIVISOR;\n orderPrice = isBuy\n ? currentPrice * (1 + slippageValue)\n : currentPrice * (1 - slippageValue);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else {\n // Limit orders: use provided price (no slippage applied)\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n }\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals,\n });\n\n return { orderPrice, formattedSize, formattedPrice };\n}\n\n/**\n * Builds orders array including main order and optional TP/SL orders\n *\n * @param params - Order construction parameters\n * @returns Array of SDK order params and grouping type\n */\nexport function buildOrdersArray(\n params: BuildOrdersArrayParams,\n): BuildOrdersArrayResult {\n const {\n assetId,\n isBuy,\n formattedPrice,\n formattedSize,\n reduceOnly,\n orderType,\n clientOrderId,\n takeProfitPrice,\n stopLossPrice,\n szDecimals,\n grouping,\n } = params;\n\n const orders: SDKOrderParams[] = [];\n\n // 1. Main order\n const mainOrder: SDKOrderParams = {\n a: assetId,\n b: isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: reduceOnly || false,\n t:\n orderType === 'limit'\n ? { limit: { tif: 'Gtc' } }\n : { limit: { tif: 'FrontendMarket' } },\n c: clientOrderId ? (clientOrderId as Hex) : undefined,\n };\n orders.push(mainOrder);\n\n // 2. Take Profit order\n if (takeProfitPrice) {\n const tpOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n s: formattedSize,\n r: true,\n t: {\n trigger: {\n isMarket: false,\n triggerPx: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n tpsl: 'tp',\n },\n },\n };\n orders.push(tpOrder);\n }\n\n // 3. Stop Loss order\n if (stopLossPrice) {\n // Apply 10% slippage to SL limit price (executes as market order when triggered)\n // HyperLiquid recommended: 10% for TP/SL orders\n const stopLossPriceNum = parseFloat(stopLossPrice);\n const slippageValue = ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps / 10000;\n const limitPriceWithSlippage = isBuy\n ? stopLossPriceNum * (1 - slippageValue) // Selling to close long: willing to accept LESS (slippage protection)\n : stopLossPriceNum * (1 + slippageValue); // Buying to close short: willing to pay MORE (slippage protection)\n\n const slOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: limitPriceWithSlippage,\n szDecimals,\n }),\n s: formattedSize,\n r: true,\n t: {\n trigger: {\n isMarket: true,\n triggerPx: formatHyperLiquidPrice({\n price: stopLossPriceNum,\n szDecimals,\n }),\n tpsl: 'sl',\n },\n },\n };\n orders.push(slOrder);\n }\n\n // Determine grouping\n const finalGrouping: 'na' | 'normalTpsl' | 'positionTpsl' =\n grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');\n\n return { orders, grouping: finalGrouping };\n}\n"]}
1
+ {"version":3,"file":"orderCalculations.mjs","sourceRoot":"","sources":["../../src/utils/orderCalculations.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,2CAA0C;AACzE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACtB,qCAAoC;AACrC,OAAO,EAAE,iBAAiB,EAAE,+BAA8B;AAI1D,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,iCAAgC;AACjC,OAAO,EACL,mBAAmB,EACnB,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,EACjB,yBAAwB;AAQzB;;;GAGG;AACH,MAAM,eAAe,GAAG,IAAI,CAAC;AAiG7B;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA0B;IAC9D,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAE7C,+BAA+B;IAC/B,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;QACpD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,iCAAiC,UAAU,EAAE,CAAC,CAAC;IACjE,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,I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,CAAC,CAAC,eAAe,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAEzE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';\nimport {\n MAX_ORDER_MARGIN_BUFFER,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { SDKOrderParams } from '../types/hyperliquid-types.js';\nimport type { PerpsDebugLogger } from '../types/index.js';\nimport type { OrderType } from '../types/perps-types.js';\nimport {\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n} from './hyperLiquidAdapter.js';\nimport {\n getTriggerDirection,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n toSDKTimeInForce,\n} from './orderTypes.js';\n\n/**\n * Optional debug logger for order calculation functions.\n * When provided, enables detailed logging for debugging.\n */\nexport type OrderCalculationsDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Tolerance used when deciding whether a scaled size is already on the size\n * grid, guarding against floating-point representation error.\n */\nconst FLOAT_TOLERANCE = 1e-6;\n\ntype PositionSizeParams = {\n amount: string;\n price: number;\n szDecimals: number;\n};\n\ntype MarginRequiredParams = {\n amount: string;\n leverage: number;\n};\n\ntype MaxAllowedAmountParams = {\n spendableBalance: number;\n assetPrice: number;\n assetSzDecimals: number;\n leverage: number;\n // Placement type. Only a resting order is margin-checked against its own\n // submitted price; a marketable order is charged at the fill price. Defaults\n // to 'market'.\n orderType?: 'market' | 'limit';\n // Price a limit order will rest at. Needed to size a limit order that rests\n // above the market price.\n limitPrice?: number;\n};\n\n// Advanced order calculation interfaces\nexport type CalculateFinalPositionSizeParams = {\n usdAmount?: string;\n size?: string;\n currentPrice: number;\n priceAtCalculation?: number;\n maxSlippageBps?: number;\n szDecimals: number;\n leverage?: number;\n // Reduce-only orders (position closes) may never round up: HyperLiquid\n // rejects a reduce-only order whose size exceeds the live position with\n // \"Reduce only order would increase position\".\n reduceOnly?: boolean;\n debugLogger?: OrderCalculationsDebugLogger;\n};\n\nexport type CalculateFinalPositionSizeResult = {\n finalPositionSize: number;\n};\n\nexport type CalculateOrderPriceAndSizeParams = {\n orderType: OrderType;\n isBuy: boolean;\n finalPositionSize: number;\n currentPrice: number;\n limitPrice?: string;\n // Trigger price for stop_*/take_profit_* placements. Required for those types:\n // `*_limit` executes at `limitPrice`, `*_market` derives a slippage-capped\n // limit price from this trigger price.\n triggerPrice?: string;\n // Max slippage in basis points (e.g. 300 = 3%). Applied to market orders and to\n // market-executing trigger orders (where it caps the limit price derived from\n // the trigger price); limit orders use limitPrice directly. Falls back to\n // ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps for market orders and\n // .DefaultTpslSlippageBps for market-executing triggers.\n maxSlippageBps?: number;\n szDecimals: number;\n};\n\nexport type CalculateOrderPriceAndSizeResult = {\n orderPrice: number;\n formattedSize: string;\n formattedPrice: string;\n};\n\nexport type BuildOrdersArrayParams = {\n assetId: number;\n isBuy: boolean;\n formattedPrice: string;\n formattedSize: string;\n reduceOnly: boolean;\n orderType: OrderType;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n // Trigger price for stop_*/take_profit_* placements (required for those types)\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n // Partial TP/SL sizes; default to the full order size when omitted\n takeProfitSize?: string;\n stopLossSize?: string;\n szDecimals: number;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\nexport type BuildOrdersArrayResult = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\n/**\n * Calculate position size based on USD amount and asset price\n *\n * @param params - Amount in USD, current asset price, and required decimal precision\n * @returns Position size formatted to the asset's decimal precision\n */\nexport function calculatePositionSize(params: PositionSizeParams): string {\n const { amount, price, szDecimals } = params;\n\n // Validate required parameters\n if (szDecimals === undefined || szDecimals === null) {\n throw new Error('szDecimals is required for position size calculation');\n }\n if (szDecimals < 0) {\n throw new Error(`szDecimals must be >= 0, got: ${szDecimals}`);\n }\n\n const amountNum = parseFloat(amount || '0');\n\n if (isNaN(amountNum) || isNaN(price) || amountNum === 0 || price === 0) {\n return (0).toFixed(szDecimals);\n }\n\n const positionSize = amountNum / price;\n const multiplier = Math.pow(10, szDecimals);\n let rounded = Math.round(positionSize * multiplier) / multiplier;\n\n // Ensure rounded size meets requested USD (fix validation gap)\n const actualUsd = rounded * price;\n if (actualUsd < amountNum) {\n rounded += 1 / multiplier;\n }\n\n return rounded.toFixed(szDecimals);\n}\n\n/**\n * Calculate margin required for a position\n *\n * @param params - Position amount and leverage\n * @returns Margin required formatted to 2 decimal places\n */\nexport function calculateMarginRequired(params: MarginRequiredParams): string {\n const { amount, leverage } = params;\n const amountNum = parseFloat(amount || '0');\n\n if (\n isNaN(amountNum) ||\n isNaN(leverage) ||\n amountNum === 0 ||\n leverage === 0\n ) {\n return '0.00';\n }\n\n return (amountNum / leverage).toFixed(2);\n}\n\nexport function getMaxAllowedAmount(params: MaxAllowedAmountParams): number {\n const {\n spendableBalance,\n assetPrice,\n assetSzDecimals,\n leverage,\n orderType = 'market',\n limitPrice,\n } = params;\n if (spendableBalance === 0 || !assetPrice || assetSzDecimals === undefined) {\n return 0;\n }\n\n // HyperLiquid reserves initial margin for a RESTING order against the price\n // the order is submitted at, not the market price its size was derived from.\n // A limit order resting above the market price - typically a sell - therefore\n // needs more margin than a market-priced notional budgets for, and the\n // exchange refuses it with \"insufficient margin to place order\". Price the max\n // off that submitted price instead. A marketable order is charged at the fill\n // price, so it needs no adjustment.\n const executionPriceRatio =\n orderType === 'limit' && limitPrice && limitPrice > assetPrice\n ? limitPrice / assetPrice\n : 1;\n\n // The theoretical maximum is spendableBalance * leverage, expressed in the\n // market-price notional the caller works with.\n const theoreticalMax = (spendableBalance * leverage) / executionPriceRatio;\n\n // But we need to account for position size rounding\n // Find the largest whole dollar amount that fits within this limit\n let maxAmount = Math.floor(theoreticalMax);\n\n // Verify this amount doesn't exceed available balance after rounding\n const testPositionSize = calculatePositionSize({\n amount: maxAmount.toString(),\n price: assetPrice,\n szDecimals: assetSzDecimals,\n });\n\n const actualNotionalValue =\n parseFloat(testPositionSize) * assetPrice * executionPriceRatio;\n const requiredMargin = actualNotionalValue / leverage;\n\n // If rounding caused us to exceed available balance, step down by one position increment\n if (requiredMargin > spendableBalance) {\n const minPositionSizeIncrement = 1 / Math.pow(10, assetSzDecimals);\n const positionSizeIncrementUsd = Math.ceil(\n minPositionSizeIncrement * assetPrice,\n );\n maxAmount -= positionSizeIncrementUsd;\n }\n\n // Apply margin buffer to reduce \"Insufficient margin\" rejections from the exchange\n // (fees, rounding, and exchange-side checks can make 100% theoretical max fail)\n const bufferedMax = maxAmount * (1 - MAX_ORDER_MARGIN_BUFFER);\n\n return Math.max(0, Math.floor(bufferedMax));\n}\n\n/**\n * Round a size down onto the asset's size grid.\n *\n * Used for reduce-only orders, where rounding up would push the size past the\n * live position size. Values already on the grid are snapped rather than\n * truncated, because floating-point math can leave them just below a grid\n * point (0.0123 * 10000 === 122.99999999999999) and truncating would drop a\n * whole increment.\n *\n * The result is never greater than `size`, for negative sizes as well as\n * positive: the snap only ever recovers a grid point the input already\n * represents, so a value genuinely below a grid point is stepped down even when\n * the tolerance would have reached the point above it.\n *\n * A size whose scaled form reaches `2^53` is returned unchanged: doubles cannot\n * represent consecutive integers there, so the grid is finer than the spacing\n * between representable values and there is nothing to round down to.\n *\n * @param size - Size to round down.\n * @param szDecimals - The asset's size decimal precision.\n * @returns The size rounded down onto the size grid, never exceeding `size`.\n */\nexport function floorToSizeDecimals(size: number, szDecimals: number): number {\n const multiplier = Math.pow(10, szDecimals);\n const scaled = size * multiplier;\n\n // Past 2^53 a double cannot represent consecutive integers, so `units -= 1`\n // below would be a no-op and the step-down loop would never terminate. The\n // size grid is finer than the spacing between representable values at that\n // magnitude, so there is no increment to shave: return the input unchanged.\n if (!Number.isFinite(scaled) || Math.abs(scaled) >= Number.MAX_SAFE_INTEGER) {\n return size;\n }\n\n const nearest = Math.round(scaled);\n // The tolerance scales with the magnitude, because double-precision error\n // does too: a fixed epsilon would stop absorbing representation error for\n // sizes that scale past ~1e10 and would then shave off a whole increment.\n const tolerance = Math.max(\n FLOAT_TOLERANCE,\n Math.abs(scaled) * Number.EPSILON * 8,\n );\n let units =\n Math.abs(scaled - nearest) < tolerance ? nearest : Math.floor(scaled);\n\n // Step down until the result no longer exceeds the input. One pass is not\n // enough: a tolerance wide enough to absorb representation error at large\n // magnitudes also reaches the next grid point, and for an input less than half\n // an ulp below a grid point `size * multiplier` evaluates to exactly that grid\n // integer, so flooring the scaled value returns the same too-large result.\n // The comparison alone is the whole termination condition: for a non-negative\n // size the loop stops at or before zero, and for a negative size it stops once\n // the value is no longer above the input. Guarding on `units` instead would\n // skip a negative size below the tolerance, which snaps to `-0` — and\n // `-0 !== 0` is false. The 2^53 bail-out above keeps this bounded.\n while (units / multiplier > size) {\n units -= 1;\n }\n\n return units / multiplier;\n}\n\n/**\n * Calculates final position size using USD as source of truth with price validation\n *\n * This function implements the hybrid approach where USD is the source of truth,\n * but includes price staleness validation and proper rounding to prevent precision loss.\n *\n * @param params - USD amount, size, prices, and configuration\n * @returns Final position size as a number\n */\nexport function calculateFinalPositionSize(\n params: CalculateFinalPositionSizeParams,\n): CalculateFinalPositionSizeResult {\n const {\n usdAmount,\n size,\n currentPrice,\n priceAtCalculation,\n maxSlippageBps,\n szDecimals,\n leverage,\n reduceOnly,\n debugLogger,\n } = params;\n\n let finalPositionSize: number;\n\n // Validate price staleness whenever the caller supplied a calculation-time\n // price. This runs before the sizing branches on purpose: a full close submits\n // the exact live position size rather than a USD-derived one, and it must still\n // be rejected when the price has moved past the caller's tolerance.\n if (priceAtCalculation) {\n const priceDeltaBps = Math.abs(\n ((currentPrice - priceAtCalculation) / priceAtCalculation) * 10000,\n );\n const maxSlippageBpsValue =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n\n if (priceDeltaBps > maxSlippageBpsValue) {\n throw new Error(\n `Price moved too much: ${priceDeltaBps.toFixed(0)} bps (max: ${maxSlippageBpsValue} bps). ` +\n `Expected: ${priceAtCalculation.toFixed(2)}, Current: ${currentPrice.toFixed(2)}`,\n );\n }\n\n debugLogger?.log('Price validation passed:', {\n priceAtCalculation,\n currentPrice,\n deltaBps: priceDeltaBps.toFixed(2),\n maxSlippageBps: maxSlippageBpsValue,\n });\n }\n\n if (usdAmount && parseFloat(usdAmount) > 0) {\n // USD amount provided - use it as source of truth\n const usdValue = parseFloat(usdAmount);\n\n // Recalculate position size with fresh price\n finalPositionSize = usdValue / currentPrice;\n\n // A reduce-only order may never exceed the size the caller asked to close:\n // that size is already clamped to the live position, while the USD amount was\n // computed against an older price and can imply a larger size after an\n // adverse move. Capping here keeps USD accuracy in the common case and makes\n // the caller's clamp binding.\n if (reduceOnly && size) {\n const requestedSize = parseFloat(size);\n\n // A supplied size must be positive, or the cap below would submit a\n // zero/negative order. Reject it rather than silently falling back to the\n // USD-derived size, matching how closePosition treats the same input.\n if (!Number.isFinite(requestedSize) || requestedSize <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n finalPositionSize = Math.min(finalPositionSize, requestedSize);\n }\n\n // 3. Apply size decimals rounding (reduce-only never rounds up)\n const multiplier = Math.pow(10, szDecimals);\n const sizeBeforeRounding = finalPositionSize;\n finalPositionSize = reduceOnly\n ? floorToSizeDecimals(finalPositionSize, szDecimals)\n : Math.round(finalPositionSize * multiplier) / multiplier;\n\n // Rounding down can zero out a reduce-only order whose USD value is worth\n // less than one size increment. Fail with a clear error instead of\n // submitting a size of \"0\" the exchange will reject.\n if (reduceOnly && finalPositionSize <= 0 && sizeBeforeRounding > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n // 4. Ensure rounded size meets requested USD (fix validation gap).\n // Skipped for reduce-only orders: adding an increment there would submit\n // more than the position holds and HyperLiquid rejects the order.\n let actualNotionalValue = finalPositionSize * currentPrice;\n if (!reduceOnly && actualNotionalValue < usdValue) {\n // Add 1 minimum increment to meet requested USD\n finalPositionSize += 1 / multiplier;\n actualNotionalValue = finalPositionSize * currentPrice;\n\n debugLogger?.log('Position size adjusted to meet USD minimum:', {\n requestedUsd: usdValue,\n beforeAdjustment: finalPositionSize - 1 / multiplier,\n afterAdjustment: finalPositionSize,\n actualUsd: actualNotionalValue,\n });\n }\n\n const requiredMargin = actualNotionalValue / (leverage ?? 1);\n\n // Log if rounding caused significant difference\n const usdDifference = Math.abs(actualNotionalValue - usdValue);\n if (usdDifference > 0.01) {\n debugLogger?.log(\n 'Position size rounding caused USD difference (acceptable):',\n {\n requestedUsd: usdValue,\n actualUsd: actualNotionalValue,\n difference: usdDifference,\n positionSize: finalPositionSize,\n },\n );\n }\n\n debugLogger?.log('Recalculated position size with fresh price:', {\n usdAmount: usdValue,\n priceAtCalculation,\n currentPrice,\n originalSize: size,\n recalculatedSize: finalPositionSize,\n requiredMargin,\n minIncrement: 1 / multiplier,\n });\n } else {\n // Legacy: Use provided size (backward compatibility)\n finalPositionSize = parseFloat(size ?? '0');\n\n // Reduce-only sizes are formatted with toFixed() further down, which rounds\n // up; truncate onto the size grid first so a close can never exceed the\n // position it is closing.\n if (reduceOnly) {\n // A supplied size must be positive, or formatHyperLiquidSize would render\n // a zero or negative order size. The USD branch above rejects the same\n // input.\n if (size && !(finalPositionSize > 0)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n const sizeBeforeFlooring = finalPositionSize;\n finalPositionSize = floorToSizeDecimals(finalPositionSize, szDecimals);\n\n // A positive size that floors to zero is worth less than one increment\n if (finalPositionSize <= 0 && sizeBeforeFlooring > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n }\n\n debugLogger?.log(\n 'Using legacy size calculation (no USD amount provided):',\n {\n providedSize: size,\n finalSize: finalPositionSize,\n },\n );\n }\n\n return { finalPositionSize };\n}\n\n/**\n * Calculates order price and formatted size based on order type\n *\n * @param params - Order parameters including type, direction, size, and prices\n * @returns Formatted order price, size, and price string\n */\nexport function calculateOrderPriceAndSize(\n params: CalculateOrderPriceAndSizeParams,\n): CalculateOrderPriceAndSizeResult {\n const {\n orderType,\n isBuy,\n finalPositionSize,\n currentPrice,\n limitPrice,\n triggerPrice,\n maxSlippageBps,\n szDecimals,\n } = params;\n\n let orderPrice: number;\n let formattedSize: string;\n\n if (isTriggerOrderType(orderType)) {\n // Trigger placements price off the trigger, not the live market: the order\n // rests off-book until the trigger fires.\n if (!triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n const triggerPriceNum = parseFloat(triggerPrice);\n if (isNaN(triggerPriceNum) || triggerPriceNum <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE);\n }\n\n if (isLimitExecutionOrderType(orderType)) {\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n } else {\n // Market execution on trigger: HyperLiquid still needs a limit price, used\n // as a slippage cap. The caller's tolerance wins when supplied; otherwise\n // the 10% convention of the existing TP/SL children applies.\n const effectiveBps =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n const slippageValue = effectiveBps / BASIS_POINTS_DIVISOR;\n orderPrice = isBuy\n ? triggerPriceNum * (1 + slippageValue)\n : triggerPriceNum * (1 - slippageValue);\n }\n\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else if (orderType === 'market') {\n // Market orders: apply slippage buffer to the live price so HyperLiquid\n // receives a worst-case acceptable limit price. Falls back to the\n // documented default if the caller does not provide one.\n const effectiveBps =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n const slippageValue = effectiveBps / BASIS_POINTS_DIVISOR;\n orderPrice = isBuy\n ? currentPrice * (1 + slippageValue)\n : currentPrice * (1 - slippageValue);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else {\n // Limit orders: use provided price (no slippage applied)\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n }\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals,\n });\n\n return { orderPrice, formattedSize, formattedPrice };\n}\n\n/**\n * Build the SDK order-type field for the main order.\n *\n * Trigger placements map to the SDK's trigger shape; everything else keeps the\n * existing Gtc/FrontendMarket limit shape.\n *\n * @param params - Order type parameters\n * @param params.orderType - Placement type\n * @param params.timeInForce - Time in force; only limit orders may carry one\n * @param params.triggerPrice - Trigger price (required for trigger placements)\n * @param params.szDecimals - Asset size decimals, for price formatting\n * @returns The SDK `t` field for the main order\n */\nfunction buildMainOrderTypeField(params: {\n orderType: OrderType;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n triggerPrice?: string;\n szDecimals: number;\n}): SDKOrderParams['t'] {\n const { orderType, timeInForce, triggerPrice, szDecimals } = params;\n\n if (!isTriggerOrderType(orderType)) {\n if (orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(timeInForce) } };\n }\n if (timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n }\n\n if (timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n\n if (!triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(orderType),\n triggerPx: formatTriggerPrice({\n price: triggerPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n }),\n tpsl: getTriggerDirection(orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n}\n\n/**\n * Format a price that becomes a `triggerPx`, rejecting one that disappears at\n * the asset's precision.\n *\n * A positive price below the asset's tick (`0.0004` where the asset quotes to\n * three places) formats to `'0'`, which the exchange rejects. Callers validate\n * this up front via `validateOrderPrecision`; this is the guard on the build\n * path itself, so no caller can assemble an order that cannot be accepted.\n *\n * @param params - Price parameters\n * @param params.price - The requested price\n * @param params.szDecimals - Asset size decimals\n * @param params.error - Typed error to throw when the price rounds away\n * @returns The exchange-formatted price, guaranteed positive.\n */\nfunction formatTriggerPrice(params: {\n price: string;\n szDecimals: number;\n error: string;\n}): string {\n const { price, szDecimals, error } = params;\n const formatted = formatHyperLiquidPrice({ price, szDecimals });\n\n if (parseFloat(formatted) <= 0) {\n throw new Error(error);\n }\n\n return formatted;\n}\n\n/**\n * Resolve the size of an attached TP/SL order.\n *\n * @param params - Size parameters\n * @param params.tpslSize - Requested partial size, if any\n * @param params.formattedSize - Full order size, used when no partial size is given\n * @param params.szDecimals - Asset size decimals\n * @returns The exchange-formatted TP/SL order size\n */\nfunction formatTpslSize(params: {\n tpslSize?: string;\n formattedSize: string;\n szDecimals: number;\n}): string {\n const { tpslSize, formattedSize, szDecimals } = params;\n\n if (tpslSize === undefined) {\n return formattedSize;\n }\n\n // Validation compares the requested size against `params.size`, but a\n // usdAmount-based order is finally sized from a fresher price, so the parent\n // can end up smaller than the child that validated cleanly. Clamp so the\n // attached TP/SL never exceeds the order it protects.\n const requested = parseFloat(tpslSize);\n const parentSize = parseFloat(formattedSize);\n const size =\n Number.isFinite(parentSize) && Number.isFinite(requested)\n ? Math.min(requested, parentSize)\n : requested;\n\n return formatPartialTpslSize({ size, szDecimals });\n}\n\n/**\n * Check that an order's prices and partial sizes survive the asset's precision.\n *\n * Validation elsewhere sees the values the caller supplied; this sees what the\n * exchange will actually receive. A positive value below the asset's tick\n * formats to `'0'`, which either changes the order's meaning (a zero-sized\n * trigger covers the whole position) or is rejected outright (a zero\n * `triggerPx`).\n *\n * Callers run this before taking any side effect — cancelling the position's\n * existing triggers, changing leverage, moving HIP-3 margin — so a value that\n * would only fail once the orders are built cannot leave a position stripped of\n * its protection, or an account with leverage moved, for an order that was\n * never going to be accepted.\n *\n * @param params - Price and size parameters\n * @param params.triggerPrice - Trigger price for a trigger placement, if any\n * @param params.takeProfitPrice - Attached take profit price, if any\n * @param params.stopLossPrice - Attached stop loss price, if any\n * @param params.takeProfitSize - Requested partial take profit size, if any\n * @param params.stopLossSize - Requested partial stop loss size, if any\n * @param params.szDecimals - Asset size decimals\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderPrecision(params: {\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n szDecimals: number;\n}): { isValid: boolean; error?: string } {\n const {\n triggerPrice,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals,\n } = params;\n\n for (const size of [takeProfitSize, stopLossSize]) {\n if (size === undefined) {\n continue;\n }\n\n if (parseFloat(formatHyperLiquidSize({ size, szDecimals })) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n // Prices carry their own precision: an asset quotes to\n // `MaxPriceDecimals - szDecimals` places, so a positive price under that tick\n // formats to '0'. Every one of these becomes a `triggerPx` the exchange\n // rejects outright.\n const priceChecks: [string | undefined, string][] = [\n [triggerPrice, PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE],\n [takeProfitPrice, PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE],\n [stopLossPrice, PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE],\n ];\n\n for (const [price, error] of priceChecks) {\n if (price === undefined) {\n continue;\n }\n\n if (parseFloat(formatHyperLiquidPrice({ price, szDecimals })) <= 0) {\n return { isValid: false, error };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Format a partial TP/SL size, rejecting one that disappears at the asset\n * precision.\n *\n * Validation only sees the requested size, so a positive value below the\n * asset's precision (0.0004 against `szDecimals: 3`) passes and then formats to\n * `'0'`. HyperLiquid reads a zero-sized trigger as covering the whole position,\n * which would silently turn a partial TP/SL into a full close.\n *\n * @param params - Size parameters\n * @param params.size - The requested partial size\n * @param params.szDecimals - Asset size decimals\n * @returns The exchange-formatted size, guaranteed positive.\n */\nexport function formatPartialTpslSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const formatted = formatHyperLiquidSize(params);\n\n if (parseFloat(formatted) <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID);\n }\n\n return formatted;\n}\n\n/**\n * Builds orders array including main order and optional TP/SL orders\n *\n * @param params - Order construction parameters\n * @returns Array of SDK order params and grouping type\n */\nexport function buildOrdersArray(\n params: BuildOrdersArrayParams,\n): BuildOrdersArrayResult {\n const {\n assetId,\n isBuy,\n formattedPrice,\n formattedSize,\n reduceOnly,\n orderType,\n timeInForce,\n clientOrderId,\n triggerPrice,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals,\n grouping,\n } = params;\n\n const orders: SDKOrderParams[] = [];\n\n // 1. Main order\n const mainOrder: SDKOrderParams = {\n a: assetId,\n b: isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: reduceOnly || false,\n t: buildMainOrderTypeField({\n orderType,\n timeInForce,\n triggerPrice,\n szDecimals,\n }),\n c: clientOrderId ? (clientOrderId as Hex) : undefined,\n };\n orders.push(mainOrder);\n\n // 2. Take Profit order\n if (takeProfitPrice) {\n const tpOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n s: formatTpslSize({\n tpslSize: takeProfitSize,\n formattedSize,\n szDecimals,\n }),\n r: true,\n t: {\n trigger: {\n isMarket: false,\n triggerPx: formatTriggerPrice({\n price: takeProfitPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n }),\n tpsl: 'tp',\n },\n },\n };\n orders.push(tpOrder);\n }\n\n // 3. Stop Loss order\n if (stopLossPrice) {\n // Apply 10% slippage to SL limit price (executes as market order when triggered)\n // HyperLiquid recommended: 10% for TP/SL orders\n const stopLossPriceNum = parseFloat(stopLossPrice);\n const slippageValue = ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps / 10000;\n const limitPriceWithSlippage = isBuy\n ? stopLossPriceNum * (1 - slippageValue) // Selling to close long: willing to accept LESS (slippage protection)\n : stopLossPriceNum * (1 + slippageValue); // Buying to close short: willing to pay MORE (slippage protection)\n\n const slOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: limitPriceWithSlippage,\n szDecimals,\n }),\n s: formatTpslSize({ tpslSize: stopLossSize, formattedSize, szDecimals }),\n r: true,\n t: {\n trigger: {\n isMarket: true,\n triggerPx: formatTriggerPrice({\n price: stopLossPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n }),\n tpsl: 'sl',\n },\n },\n };\n orders.push(slOrder);\n }\n\n // Determine grouping\n const finalGrouping: 'na' | 'normalTpsl' | 'positionTpsl' =\n grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');\n\n return { orders, grouping: finalGrouping };\n}\n"]}
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hashTriggerOrders = exports.toSDKTimeInForce = exports.buildTriggerOrderType = exports.buildPositionTriggerOrderFromOrder = exports.classifyTriggerDirection = exports.getTriggerDirection = exports.getTriggerExecution = exports.isLimitExecutionOrderType = exports.isTriggerOrderType = exports.TRIGGER_ORDER_TYPES = void 0;
4
+ /**
5
+ * All trigger placement types, in a stable order suitable for iteration
6
+ * (validation tables, e2e matrices).
7
+ */
8
+ exports.TRIGGER_ORDER_TYPES = [
9
+ 'stop_market',
10
+ 'stop_limit',
11
+ 'take_profit_market',
12
+ 'take_profit_limit',
13
+ ];
14
+ /**
15
+ * Order types whose price field (`OrderParams.price`) is a real limit price the
16
+ * exchange must honour, as opposed to a slippage cap derived from the market.
17
+ */
18
+ const LIMIT_EXECUTION_ORDER_TYPES = [
19
+ 'limit',
20
+ 'stop_limit',
21
+ 'take_profit_limit',
22
+ ];
23
+ /**
24
+ * Check whether an order type is a trigger placement (stop / take profit).
25
+ *
26
+ * @param orderType - Order type to check.
27
+ * @returns True when the type requires `OrderParams.triggerPrice`.
28
+ */
29
+ function isTriggerOrderType(orderType) {
30
+ return exports.TRIGGER_ORDER_TYPES.includes(orderType);
31
+ }
32
+ exports.isTriggerOrderType = isTriggerOrderType;
33
+ /**
34
+ * Check whether an order type executes as a limit order.
35
+ *
36
+ * Covers plain limit orders and the `*_limit` trigger types, both of which
37
+ * require `OrderParams.price`.
38
+ *
39
+ * @param orderType - Order type to check.
40
+ * @returns True when the order executes as a limit order.
41
+ */
42
+ function isLimitExecutionOrderType(orderType) {
43
+ return LIMIT_EXECUTION_ORDER_TYPES.includes(orderType);
44
+ }
45
+ exports.isLimitExecutionOrderType = isLimitExecutionOrderType;
46
+ /**
47
+ * Get how an order executes, ignoring whether it is trigger-gated.
48
+ *
49
+ * This is also the coarse execution type that consumers predating trigger orders
50
+ * understand (fee tiers, max order value, analytics).
51
+ *
52
+ * @param orderType - Order type to inspect.
53
+ * @returns `'limit'` for limit and `*_limit` types, `'market'` otherwise.
54
+ */
55
+ function getTriggerExecution(orderType) {
56
+ return isLimitExecutionOrderType(orderType) ? 'limit' : 'market';
57
+ }
58
+ exports.getTriggerExecution = getTriggerExecution;
59
+ /**
60
+ * Get the direction a trigger order fires in.
61
+ *
62
+ * @param orderType - Trigger order type.
63
+ * @returns `'stop'` for `stop_*`, `'take_profit'` for `take_profit_*`.
64
+ */
65
+ function getTriggerDirection(orderType) {
66
+ return orderType === 'stop_market' || orderType === 'stop_limit'
67
+ ? 'stop'
68
+ : 'take_profit';
69
+ }
70
+ exports.getTriggerDirection = getTriggerDirection;
71
+ /**
72
+ * Recover which way a trigger fires from its price relative to the entry.
73
+ *
74
+ * Used when the exchange reports a trigger without naming its placement type:
75
+ * a long takes profit above its entry and stops out below, a short the other
76
+ * way round. Shared by both transports so they classify identically.
77
+ *
78
+ * @param params - Classification parameters
79
+ * @param params.triggerPrice - Price at which the order activates
80
+ * @param params.entryPrice - Entry price of the position it is attached to
81
+ * @param params.positionSize - Signed position size; its sign gives the side
82
+ * @returns The direction, or undefined when there is nothing to compare against
83
+ */
84
+ function classifyTriggerDirection(params) {
85
+ const { triggerPrice, entryPrice, positionSize } = params;
86
+ const trigger = parseFloat(triggerPrice ?? '');
87
+ const entry = parseFloat(entryPrice ?? '');
88
+ const signedSize = parseFloat(positionSize || '0');
89
+ if (!Number.isFinite(trigger) || !Number.isFinite(entry) || entry <= 0) {
90
+ return undefined;
91
+ }
92
+ // A long takes profit above its entry and stops out below; a short is the
93
+ // mirror image. A trigger sitting exactly at entry is neither, so both sides
94
+ // fall to 'stop' — matching the legacy price fallback the scalar
95
+ // takeProfitPrice/stopLossPrice fields still use. Splitting that tie the
96
+ // other way would file the order under takeProfitOrders while the scalar
97
+ // still reported it as a stop.
98
+ const isLong = signedSize > 0;
99
+ if (isLong) {
100
+ return trigger > entry ? 'take_profit' : 'stop';
101
+ }
102
+ return trigger < entry ? 'take_profit' : 'stop';
103
+ }
104
+ exports.classifyTriggerDirection = classifyTriggerDirection;
105
+ /**
106
+ * Project a normalized open order onto the position-state view of a trigger order.
107
+ *
108
+ * Returns undefined when the order is not a trigger, or when its direction can
109
+ * be established neither from a named placement type nor from its price.
110
+ *
111
+ * @param params - Mapping parameters
112
+ * @param params.order - Normalized open order
113
+ * @param params.positionSize - Size of the position the trigger is attached to
114
+ * @param params.entryPrice - Entry price, used to classify an unnamed trigger
115
+ * @returns The position trigger order, or undefined
116
+ */
117
+ function buildPositionTriggerOrderFromOrder(params) {
118
+ const { order, positionSize, entryPrice } = params;
119
+ if (!order.isTrigger) {
120
+ return undefined;
121
+ }
122
+ // HyperLiquid sometimes reports a bare 'Trigger', naming neither direction
123
+ // nor execution. The direction is still recoverable from the trigger price
124
+ // against the entry, and it is what decides which array the order belongs
125
+ // to — so an unnamed trigger is kept rather than dropped, with its execution
126
+ // mode left unstated. Without a position to compare against there is nothing
127
+ // to recover, and it is dropped.
128
+ const direction = order.triggerOrderType === undefined
129
+ ? classifyTriggerDirection({
130
+ triggerPrice: order.triggerPrice ?? order.price,
131
+ entryPrice,
132
+ positionSize,
133
+ })
134
+ : getTriggerDirection(order.triggerOrderType);
135
+ if (!direction) {
136
+ return undefined;
137
+ }
138
+ const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));
139
+ const rawSize = Math.abs(parseFloat(order.size || '0'));
140
+ // A position-bound TP/SL covers whatever the position currently is. The
141
+ // exchange encodes that as size 0, but `adaptOrderFromSDK` has already
142
+ // resolved it against the position as it stood when the order was adapted,
143
+ // so the size carried here goes stale as soon as the position is resized.
144
+ // The flag is the durable statement of what the trigger covers; the number
145
+ // is not. Reading the number instead would report the old size, and would
146
+ // call the order partial whenever the position had since grown.
147
+ const isPositionBound = order.isPositionTpsl === true;
148
+ const size = isPositionBound || rawSize === 0 ? absolutePositionSize : rawSize;
149
+ return {
150
+ orderId: order.orderId,
151
+ direction,
152
+ orderType: order.triggerOrderType,
153
+ triggerPrice: order.triggerPrice ?? order.price,
154
+ size: size.toString(),
155
+ isPartial: !isPositionBound &&
156
+ rawSize > 0 &&
157
+ absolutePositionSize > 0 &&
158
+ rawSize < absolutePositionSize,
159
+ reduceOnly: Boolean(order.reduceOnly),
160
+ };
161
+ }
162
+ exports.buildPositionTriggerOrderFromOrder = buildPositionTriggerOrderFromOrder;
163
+ /**
164
+ * Build a trigger order type from its two independent dimensions.
165
+ *
166
+ * @param params - Trigger dimensions.
167
+ * @param params.direction - Whether the trigger is a stop or a take profit.
168
+ * @param params.execution - How the order executes once triggered.
169
+ * @returns The matching trigger order type.
170
+ */
171
+ function buildTriggerOrderType(params) {
172
+ const { direction, execution } = params;
173
+ if (direction === 'stop') {
174
+ return execution === 'limit' ? 'stop_limit' : 'stop_market';
175
+ }
176
+ return execution === 'limit' ? 'take_profit_limit' : 'take_profit_market';
177
+ }
178
+ exports.buildTriggerOrderType = buildTriggerOrderType;
179
+ /**
180
+ * Map the controller's time in force onto the exchange's spelling.
181
+ *
182
+ * Shared by the two order-building paths so they cannot drift apart.
183
+ *
184
+ * @param timeInForce - Requested time in force; defaults to GTC.
185
+ * @returns The SDK time-in-force value.
186
+ */
187
+ function toSDKTimeInForce(timeInForce) {
188
+ switch (timeInForce) {
189
+ case 'IOC':
190
+ return 'Ioc';
191
+ case 'ALO':
192
+ return 'Alo';
193
+ default:
194
+ return 'Gtc';
195
+ }
196
+ }
197
+ exports.toSDKTimeInForce = toSDKTimeInForce;
198
+ /**
199
+ * Hash the identity of a position's trigger orders for change detection.
200
+ *
201
+ * Streamed positions only re-emit when their hash changes, so this has to move
202
+ * when a trigger is added, removed, repriced, resized, or retyped — otherwise
203
+ * subscribers never receive the updated arrays.
204
+ *
205
+ * The placement type is part of the identity because a trigger can be modified
206
+ * in place: switching a stop from market to limit execution keeps its order ID,
207
+ * trigger price, and size, so nothing else here would move even though the
208
+ * execution semantics subscribers rely on have changed.
209
+ *
210
+ * @param orders - Trigger orders attached to a position, if any.
211
+ * @returns A stable string; `'0'` for both empty and absent.
212
+ */
213
+ function hashTriggerOrders(orders) {
214
+ if (!orders || orders.length === 0) {
215
+ return '0';
216
+ }
217
+ return orders
218
+ .map((order) => `${order.orderId}:${order.direction}:${order.orderType ?? '?'}@${order.triggerPrice}x${order.size}${order.isPartial ? 'p' : ''}`)
219
+ .join(',');
220
+ }
221
+ exports.hashTriggerOrders = hashTriggerOrders;
222
+ //# sourceMappingURL=orderTypes.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderTypes.cjs","sourceRoot":"","sources":["../../src/utils/orderTypes.ts"],"names":[],"mappings":";;;AAQA;;;GAGG;AACU,QAAA,mBAAmB,GAAG;IACjC,aAAa;IACb,YAAY;IACZ,oBAAoB;IACpB,mBAAmB;CAC2B,CAAC;AAEjD;;;GAGG;AACH,MAAM,2BAA2B,GAAG;IAClC,OAAO;IACP,YAAY;IACZ,mBAAmB;CACoB,CAAC;AAE1C;;;;;GAKG;AACH,SAAgB,kBAAkB,CAChC,SAAoB;IAEpB,OAAQ,2BAA4C,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC3E,CAAC;AAJD,gDAIC;AAED;;;;;;;;GAQG;AACH,SAAgB,yBAAyB,CAAC,SAAoB;IAC5D,OAAQ,2BAAoD,CAAC,QAAQ,CACnE,SAAS,CACV,CAAC;AACJ,CAAC;AAJD,8DAIC;AAED;;;;;;;;GAQG;AACH,SAAgB,mBAAmB,CAAC,SAAoB;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;AACnE,CAAC;AAFD,kDAEC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,SAA2B;IAE3B,OAAO,SAAS,KAAK,aAAa,IAAI,SAAS,KAAK,YAAY;QAC9D,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,aAAa,CAAC;AACpB,CAAC;AAND,kDAMC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,wBAAwB,CAAC,MAIxC;IACC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM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AC,YAAY,CAAC,CAAC,CAAC,aAAa,CAAC;IAC9D,CAAC;IAED,OAAO,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,oBAAoB,CAAC;AAC5E,CAAC;AAXD,sDAWC;AAED;;;;;;;GAOG;AACH,SAAgB,gBAAgB,CAC9B,WAAmC;IAEnC,QAAQ,WAAW,EAAE,CAAC;QACpB,KAAK,KAAK;YACR,OAAO,KAAK,CAAC;QACf,KAAK,KAAK;YACR,OAAO,KAAK,CAAC;QACf;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC;AAXD,4CAWC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,iBAAiB,CAAC,MAA+B;IAC/D,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnC,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,MAAM;SACV,GAAG,CACF,CAAC,KAAK,EAAE,EAAE,CACR,GAAG,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,IAAI,GAAG,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CACnI;SACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC;AAVD,8CAUC","sourcesContent":["import type { Order, PositionTriggerOrder } from '../types/index.js';\nimport type {\n OrderExecution,\n OrderType,\n TriggerDirection,\n TriggerOrderType,\n} from '../types/perps-types.js';\n\n/**\n * All trigger placement types, in a stable order suitable for iteration\n * (validation tables, e2e matrices).\n */\nexport const TRIGGER_ORDER_TYPES = [\n 'stop_market',\n 'stop_limit',\n 'take_profit_market',\n 'take_profit_limit',\n] as const satisfies readonly TriggerOrderType[];\n\n/**\n * Order types whose price field (`OrderParams.price`) is a real limit price the\n * exchange must honour, as opposed to a slippage cap derived from the market.\n */\nconst LIMIT_EXECUTION_ORDER_TYPES = [\n 'limit',\n 'stop_limit',\n 'take_profit_limit',\n] as const satisfies readonly OrderType[];\n\n/**\n * Check whether an order type is a trigger placement (stop / take profit).\n *\n * @param orderType - Order type to check.\n * @returns True when the type requires `OrderParams.triggerPrice`.\n */\nexport function isTriggerOrderType(\n orderType: OrderType,\n): orderType is TriggerOrderType {\n return (TRIGGER_ORDER_TYPES as readonly OrderType[]).includes(orderType);\n}\n\n/**\n * Check whether an order type executes as a limit order.\n *\n * Covers plain limit orders and the `*_limit` trigger types, both of which\n * require `OrderParams.price`.\n *\n * @param orderType - Order type to check.\n * @returns True when the order executes as a limit order.\n */\nexport function isLimitExecutionOrderType(orderType: OrderType): boolean {\n return (LIMIT_EXECUTION_ORDER_TYPES as readonly OrderType[]).includes(\n orderType,\n );\n}\n\n/**\n * Get how an order executes, ignoring whether it is trigger-gated.\n *\n * This is also the coarse execution type that consumers predating trigger orders\n * understand (fee tiers, max order value, analytics).\n *\n * @param orderType - Order type to inspect.\n * @returns `'limit'` for limit and `*_limit` types, `'market'` otherwise.\n */\nexport function getTriggerExecution(orderType: OrderType): OrderExecution {\n return isLimitExecutionOrderType(orderType) ? 'limit' : 'market';\n}\n\n/**\n * Get the direction a trigger order fires in.\n *\n * @param orderType - Trigger order type.\n * @returns `'stop'` for `stop_*`, `'take_profit'` for `take_profit_*`.\n */\nexport function getTriggerDirection(\n orderType: TriggerOrderType,\n): TriggerDirection {\n return orderType === 'stop_market' || orderType === 'stop_limit'\n ? 'stop'\n : 'take_profit';\n}\n\n/**\n * Recover which way a trigger fires from its price relative to the entry.\n *\n * Used when the exchange reports a trigger without naming its placement type:\n * a long takes profit above its entry and stops out below, a short the other\n * way round. Shared by both transports so they classify identically.\n *\n * @param params - Classification parameters\n * @param params.triggerPrice - Price at which the order activates\n * @param params.entryPrice - Entry price of the position it is attached to\n * @param params.positionSize - Signed position size; its sign gives the side\n * @returns The direction, or undefined when there is nothing to compare against\n */\nexport function classifyTriggerDirection(params: {\n triggerPrice?: string;\n entryPrice?: string;\n positionSize: string;\n}): TriggerDirection | undefined {\n const { triggerPrice, entryPrice, positionSize } = params;\n\n const trigger = parseFloat(triggerPrice ?? '');\n const entry = parseFloat(entryPrice ?? '');\n const signedSize = parseFloat(positionSize || '0');\n\n if (!Number.isFinite(trigger) || !Number.isFinite(entry) || entry <= 0) {\n return undefined;\n }\n\n // A long takes profit above its entry and stops out below; a short is the\n // mirror image. A trigger sitting exactly at entry is neither, so both sides\n // fall to 'stop' — matching the legacy price fallback the scalar\n // takeProfitPrice/stopLossPrice fields still use. Splitting that tie the\n // other way would file the order under takeProfitOrders while the scalar\n // still reported it as a stop.\n const isLong = signedSize > 0;\n\n if (isLong) {\n return trigger > entry ? 'take_profit' : 'stop';\n }\n return trigger < entry ? 'take_profit' : 'stop';\n}\n\n/**\n * Project a normalized open order onto the position-state view of a trigger order.\n *\n * Returns undefined when the order is not a trigger, or when its direction can\n * be established neither from a named placement type nor from its price.\n *\n * @param params - Mapping parameters\n * @param params.order - Normalized open order\n * @param params.positionSize - Size of the position the trigger is attached to\n * @param params.entryPrice - Entry price, used to classify an unnamed trigger\n * @returns The position trigger order, or undefined\n */\nexport function buildPositionTriggerOrderFromOrder(params: {\n order: Order;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { order, positionSize, entryPrice } = params;\n\n if (!order.isTrigger) {\n return undefined;\n }\n\n // HyperLiquid sometimes reports a bare 'Trigger', naming neither direction\n // nor execution. The direction is still recoverable from the trigger price\n // against the entry, and it is what decides which array the order belongs\n // to — so an unnamed trigger is kept rather than dropped, with its execution\n // mode left unstated. Without a position to compare against there is nothing\n // to recover, and it is dropped.\n const direction =\n order.triggerOrderType === undefined\n ? classifyTriggerDirection({\n triggerPrice: order.triggerPrice ?? order.price,\n entryPrice,\n positionSize,\n })\n : getTriggerDirection(order.triggerOrderType);\n\n if (!direction) {\n return undefined;\n }\n\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(order.size || '0'));\n\n // A position-bound TP/SL covers whatever the position currently is. The\n // exchange encodes that as size 0, but `adaptOrderFromSDK` has already\n // resolved it against the position as it stood when the order was adapted,\n // so the size carried here goes stale as soon as the position is resized.\n // The flag is the durable statement of what the trigger covers; the number\n // is not. Reading the number instead would report the old size, and would\n // call the order partial whenever the position had since grown.\n const isPositionBound = order.isPositionTpsl === true;\n const size =\n isPositionBound || rawSize === 0 ? absolutePositionSize : rawSize;\n\n return {\n orderId: order.orderId,\n direction,\n orderType: order.triggerOrderType,\n triggerPrice: order.triggerPrice ?? order.price,\n size: size.toString(),\n isPartial:\n !isPositionBound &&\n rawSize > 0 &&\n absolutePositionSize > 0 &&\n rawSize < absolutePositionSize,\n reduceOnly: Boolean(order.reduceOnly),\n };\n}\n\n/**\n * Build a trigger order type from its two independent dimensions.\n *\n * @param params - Trigger dimensions.\n * @param params.direction - Whether the trigger is a stop or a take profit.\n * @param params.execution - How the order executes once triggered.\n * @returns The matching trigger order type.\n */\nexport function buildTriggerOrderType(params: {\n direction: TriggerDirection;\n execution: OrderExecution;\n}): TriggerOrderType {\n const { direction, execution } = params;\n\n if (direction === 'stop') {\n return execution === 'limit' ? 'stop_limit' : 'stop_market';\n }\n\n return execution === 'limit' ? 'take_profit_limit' : 'take_profit_market';\n}\n\n/**\n * Map the controller's time in force onto the exchange's spelling.\n *\n * Shared by the two order-building paths so they cannot drift apart.\n *\n * @param timeInForce - Requested time in force; defaults to GTC.\n * @returns The SDK time-in-force value.\n */\nexport function toSDKTimeInForce(\n timeInForce?: 'GTC' | 'IOC' | 'ALO',\n): 'Gtc' | 'Ioc' | 'Alo' {\n switch (timeInForce) {\n case 'IOC':\n return 'Ioc';\n case 'ALO':\n return 'Alo';\n default:\n return 'Gtc';\n }\n}\n\n/**\n * Hash the identity of a position's trigger orders for change detection.\n *\n * Streamed positions only re-emit when their hash changes, so this has to move\n * when a trigger is added, removed, repriced, resized, or retyped — otherwise\n * subscribers never receive the updated arrays.\n *\n * The placement type is part of the identity because a trigger can be modified\n * in place: switching a stop from market to limit execution keeps its order ID,\n * trigger price, and size, so nothing else here would move even though the\n * execution semantics subscribers rely on have changed.\n *\n * @param orders - Trigger orders attached to a position, if any.\n * @returns A stable string; `'0'` for both empty and absent.\n */\nexport function hashTriggerOrders(orders?: PositionTriggerOrder[]): string {\n if (!orders || orders.length === 0) {\n return '0';\n }\n return orders\n .map(\n (order) =>\n `${order.orderId}:${order.direction}:${order.orderType ?? '?'}@${order.triggerPrice}x${order.size}${order.isPartial ? 'p' : ''}`,\n )\n .join(',');\n}\n"]}
@@ -0,0 +1,114 @@
1
+ import type { Order, PositionTriggerOrder } from "../types/index.cjs";
2
+ import type { OrderExecution, OrderType, TriggerDirection, TriggerOrderType } from "../types/perps-types.cjs";
3
+ /**
4
+ * All trigger placement types, in a stable order suitable for iteration
5
+ * (validation tables, e2e matrices).
6
+ */
7
+ export declare const TRIGGER_ORDER_TYPES: readonly ["stop_market", "stop_limit", "take_profit_market", "take_profit_limit"];
8
+ /**
9
+ * Check whether an order type is a trigger placement (stop / take profit).
10
+ *
11
+ * @param orderType - Order type to check.
12
+ * @returns True when the type requires `OrderParams.triggerPrice`.
13
+ */
14
+ export declare function isTriggerOrderType(orderType: OrderType): orderType is TriggerOrderType;
15
+ /**
16
+ * Check whether an order type executes as a limit order.
17
+ *
18
+ * Covers plain limit orders and the `*_limit` trigger types, both of which
19
+ * require `OrderParams.price`.
20
+ *
21
+ * @param orderType - Order type to check.
22
+ * @returns True when the order executes as a limit order.
23
+ */
24
+ export declare function isLimitExecutionOrderType(orderType: OrderType): boolean;
25
+ /**
26
+ * Get how an order executes, ignoring whether it is trigger-gated.
27
+ *
28
+ * This is also the coarse execution type that consumers predating trigger orders
29
+ * understand (fee tiers, max order value, analytics).
30
+ *
31
+ * @param orderType - Order type to inspect.
32
+ * @returns `'limit'` for limit and `*_limit` types, `'market'` otherwise.
33
+ */
34
+ export declare function getTriggerExecution(orderType: OrderType): OrderExecution;
35
+ /**
36
+ * Get the direction a trigger order fires in.
37
+ *
38
+ * @param orderType - Trigger order type.
39
+ * @returns `'stop'` for `stop_*`, `'take_profit'` for `take_profit_*`.
40
+ */
41
+ export declare function getTriggerDirection(orderType: TriggerOrderType): TriggerDirection;
42
+ /**
43
+ * Recover which way a trigger fires from its price relative to the entry.
44
+ *
45
+ * Used when the exchange reports a trigger without naming its placement type:
46
+ * a long takes profit above its entry and stops out below, a short the other
47
+ * way round. Shared by both transports so they classify identically.
48
+ *
49
+ * @param params - Classification parameters
50
+ * @param params.triggerPrice - Price at which the order activates
51
+ * @param params.entryPrice - Entry price of the position it is attached to
52
+ * @param params.positionSize - Signed position size; its sign gives the side
53
+ * @returns The direction, or undefined when there is nothing to compare against
54
+ */
55
+ export declare function classifyTriggerDirection(params: {
56
+ triggerPrice?: string;
57
+ entryPrice?: string;
58
+ positionSize: string;
59
+ }): TriggerDirection | undefined;
60
+ /**
61
+ * Project a normalized open order onto the position-state view of a trigger order.
62
+ *
63
+ * Returns undefined when the order is not a trigger, or when its direction can
64
+ * be established neither from a named placement type nor from its price.
65
+ *
66
+ * @param params - Mapping parameters
67
+ * @param params.order - Normalized open order
68
+ * @param params.positionSize - Size of the position the trigger is attached to
69
+ * @param params.entryPrice - Entry price, used to classify an unnamed trigger
70
+ * @returns The position trigger order, or undefined
71
+ */
72
+ export declare function buildPositionTriggerOrderFromOrder(params: {
73
+ order: Order;
74
+ positionSize: string;
75
+ entryPrice?: string;
76
+ }): PositionTriggerOrder | undefined;
77
+ /**
78
+ * Build a trigger order type from its two independent dimensions.
79
+ *
80
+ * @param params - Trigger dimensions.
81
+ * @param params.direction - Whether the trigger is a stop or a take profit.
82
+ * @param params.execution - How the order executes once triggered.
83
+ * @returns The matching trigger order type.
84
+ */
85
+ export declare function buildTriggerOrderType(params: {
86
+ direction: TriggerDirection;
87
+ execution: OrderExecution;
88
+ }): TriggerOrderType;
89
+ /**
90
+ * Map the controller's time in force onto the exchange's spelling.
91
+ *
92
+ * Shared by the two order-building paths so they cannot drift apart.
93
+ *
94
+ * @param timeInForce - Requested time in force; defaults to GTC.
95
+ * @returns The SDK time-in-force value.
96
+ */
97
+ export declare function toSDKTimeInForce(timeInForce?: 'GTC' | 'IOC' | 'ALO'): 'Gtc' | 'Ioc' | 'Alo';
98
+ /**
99
+ * Hash the identity of a position's trigger orders for change detection.
100
+ *
101
+ * Streamed positions only re-emit when their hash changes, so this has to move
102
+ * when a trigger is added, removed, repriced, resized, or retyped — otherwise
103
+ * subscribers never receive the updated arrays.
104
+ *
105
+ * The placement type is part of the identity because a trigger can be modified
106
+ * in place: switching a stop from market to limit execution keeps its order ID,
107
+ * trigger price, and size, so nothing else here would move even though the
108
+ * execution semantics subscribers rely on have changed.
109
+ *
110
+ * @param orders - Trigger orders attached to a position, if any.
111
+ * @returns A stable string; `'0'` for both empty and absent.
112
+ */
113
+ export declare function hashTriggerOrders(orders?: PositionTriggerOrder[]): string;
114
+ //# sourceMappingURL=orderTypes.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderTypes.d.cts","sourceRoot":"","sources":["../../src/utils/orderTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,oBAAoB,EAAE,2BAA0B;AACrE,OAAO,KAAK,EACV,cAAc,EACd,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EACjB,iCAAgC;AAEjC;;;GAGG;AACH,eAAO,MAAM,mBAAmB,mFAKgB,CAAC;AAYjD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,SAAS,GACnB,SAAS,IAAI,gBAAgB,CAE/B;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAIvE;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,SAAS,GAAG,cAAc,CAExE;AAED;;;;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