@metamask-previews/perps-controller 17.4.0-preview-be4d68b → 17.4.0-preview-4f493fb
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.
- package/CHANGELOG.md +3 -0
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +3 -2
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +2 -0
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +1 -0
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/errors.d.ts +50 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +39 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +8 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +11 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +9 -3
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +6 -1
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +49 -3
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +35 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +21 -0
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +22 -0
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidValidation.d.ts +2 -1
- package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
- package/dist/utils/hyperLiquidValidation.js +16 -2
- package/dist/utils/hyperLiquidValidation.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +3 -0
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/orderCalculations.d.ts.map +1 -1
- package/dist/utils/orderCalculations.js +18 -7
- package/dist/utils/orderCalculations.js.map +1 -1
- package/package.json +2 -2
|
@@ -76,6 +76,27 @@ export declare function calculatePositionSize(params: {
|
|
|
76
76
|
assetPrice: number;
|
|
77
77
|
}): number;
|
|
78
78
|
export declare function calculateHip3AssetId(perpDexIndex: number, indexInMeta: number): number;
|
|
79
|
+
/**
|
|
80
|
+
* Build the provider-neutral execution id for a HyperLiquid fill.
|
|
81
|
+
*
|
|
82
|
+
* HyperLiquid's `tid` is a 50-bit hash, and the venue documents
|
|
83
|
+
* `(block_time, coin, tid)` as a trade's global identity, so all three go into
|
|
84
|
+
* the id. REST and websocket fills report the same `time`, `coin` and `tid` for
|
|
85
|
+
* one execution, so both transports yield the same id.
|
|
86
|
+
*
|
|
87
|
+
* @param fill - The raw HyperLiquid fill.
|
|
88
|
+
* @param fill.coin - Venue asset name, including any HIP-3 dex prefix.
|
|
89
|
+
* @param fill.time - Fill block time in milliseconds.
|
|
90
|
+
* @param fill.tid - Venue trade id.
|
|
91
|
+
* @returns The id, or `undefined` when the payload carries no `tid`. Omitting
|
|
92
|
+
* it, rather than stringifying a missing value, keeps malformed fills from
|
|
93
|
+
* sharing one id.
|
|
94
|
+
*/
|
|
95
|
+
export declare function buildHyperLiquidFillId(fill: {
|
|
96
|
+
coin: string;
|
|
97
|
+
time: number;
|
|
98
|
+
tid?: number | null;
|
|
99
|
+
}): string | undefined;
|
|
79
100
|
export declare function parseAssetName(assetName: string): {
|
|
80
101
|
dex: string | null;
|
|
81
102
|
symbol: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidAdapter.d.ts","s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pB,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"}
|
|
@@ -435,6 +435,28 @@ export function calculateHip3AssetId(perpDexIndex, indexInMeta) {
|
|
|
435
435
|
perpDexIndex * HIP3_ASSET_ID_CONFIG.DexMultiplier +
|
|
436
436
|
indexInMeta);
|
|
437
437
|
}
|
|
438
|
+
/**
|
|
439
|
+
* Build the provider-neutral execution id for a HyperLiquid fill.
|
|
440
|
+
*
|
|
441
|
+
* HyperLiquid's `tid` is a 50-bit hash, and the venue documents
|
|
442
|
+
* `(block_time, coin, tid)` as a trade's global identity, so all three go into
|
|
443
|
+
* the id. REST and websocket fills report the same `time`, `coin` and `tid` for
|
|
444
|
+
* one execution, so both transports yield the same id.
|
|
445
|
+
*
|
|
446
|
+
* @param fill - The raw HyperLiquid fill.
|
|
447
|
+
* @param fill.coin - Venue asset name, including any HIP-3 dex prefix.
|
|
448
|
+
* @param fill.time - Fill block time in milliseconds.
|
|
449
|
+
* @param fill.tid - Venue trade id.
|
|
450
|
+
* @returns The id, or `undefined` when the payload carries no `tid`. Omitting
|
|
451
|
+
* it, rather than stringifying a missing value, keeps malformed fills from
|
|
452
|
+
* sharing one id.
|
|
453
|
+
*/
|
|
454
|
+
export function buildHyperLiquidFillId(fill) {
|
|
455
|
+
if (fill.tid === undefined || fill.tid === null) {
|
|
456
|
+
return undefined;
|
|
457
|
+
}
|
|
458
|
+
return `${fill.coin}:${fill.time}:${fill.tid}`;
|
|
459
|
+
}
|
|
438
460
|
export function parseAssetName(assetName) {
|
|
439
461
|
const colonIndex = assetName.indexOf(':');
|
|
440
462
|
if (colonIndex === -1) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidAdapter.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAO,WAAW,EAAE,MAAM,iBAAiB,CAAC;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;AAmB1D,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,mBAAmB,EACnB,mBAAmB,EACnB,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AASjC,MAAM,CAAC,MAAM,8BAA8B,GAAG,UAAU,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,aAAwC,EACpB,EAAE;IACtB,MAAM,UAAU,GAAG,aAAa,EAAE,WAAW,EAAE,CAAC;IAChD,IACE,UAAU,EAAE,MAAM,KAAK,EAAE;QACzB,CAAC,UAAU,CAAC,UAAU,CAAC,KAAK,8BAA8B,EAAE,CAAC,EAC7D,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,SAAS,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC5C,CAAC,CAAC;AAEF,MAAM,kBAAkB,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,CAAC;QACjB,IAAI,KAAK,GAAG,MAAM,CAAC;QAEnB,IAAI,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;YAC3D,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC9D,CAAC;QACD,IACE,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC;YACjC,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,EACrC,CAAC;YACD,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC;QAC5B,CAAC;QAED,OAAO;YACL,EAAE,EAAE,WAAW,MAAM,CAAC,IAAI,EAAE;YAC5B,SAAS,EAAE,MAAM,CAAC,IAAI;YACtB,MAAM;YACN,KAAK;YACL,MAAM,EAAE,MAAM,CAAC,IAAI;YACnB,MAAM,EAAE,WAAoB;YAC5B,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS;YACjE,OAAO,EAAE;gBACP,MAAM,EAAE,EAAE;gBACV,cAAc,EAAE,SAAS;gBACzB,SAAS,EAAE,SAAS;gBACpB,WAAW,EAAE,SAAS;gBACtB,OAAO,EAAE,SAAS;gBAClB,SAAS,EAAE,SAAS;aACrB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,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 MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\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 countSignificantFigures,\n roundToSignificantFigures,\n} from './significantFigures.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 as Hex)\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(\n rawOrder as FrontendOrderWithParentTpsl,\n );\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// 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 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 };\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\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"]}
|
|
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;AAmB1D,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,mBAAmB,EACnB,mBAAmB,EACnB,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AASjC,MAAM,CAAC,MAAM,8BAA8B,GAAG,UAAU,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,aAAwC,EACpB,EAAE;IACtB,MAAM,UAAU,GAAG,aAAa,EAAE,WAAW,EAAE,CAAC;IAChD,IACE,UAAU,EAAE,MAAM,KAAK,EA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AC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS;YACjE,OAAO,EAAE;gBACP,MAAM,EAAE,EAAE;gBACV,cAAc,EAAE,SAAS;gBACzB,SAAS,EAAE,SAAS;gBACpB,WAAW,EAAE,SAAS;gBACtB,OAAO,EAAE,SAAS;gBAClB,SAAS,EAAE,SAAS;aACrB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,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 MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\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 countSignificantFigures,\n roundToSignificantFigures,\n} from './significantFigures.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 as Hex)\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(\n rawOrder as FrontendOrderWithParentTpsl,\n );\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// 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 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 };\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"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CaipAssetId, Hex } from '@metamask/utils';
|
|
2
|
+
import type { PerpsErrorResultFields } from '../errors.js';
|
|
2
3
|
import type { GetSupportedPathsParams, PerpsDebugLogger } from '../types/index.js';
|
|
3
4
|
import type { OrderType, TpslLinkage } from '../types/perps-types.js';
|
|
4
5
|
/**
|
|
@@ -20,7 +21,7 @@ export type ValidationDebugLogger = PerpsDebugLogger | undefined;
|
|
|
20
21
|
export declare function createErrorResult<TValue extends {
|
|
21
22
|
success: boolean;
|
|
22
23
|
error?: string;
|
|
23
|
-
}>(error: unknown, defaultResponse: TValue): TValue;
|
|
24
|
+
}>(error: unknown, defaultResponse: TValue): TValue & PerpsErrorResultFields;
|
|
24
25
|
/**
|
|
25
26
|
* Validate withdrawal parameters.
|
|
26
27
|
*
|
|
@@ -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,EACV,uBAAuB,EACvB,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"hyperLiquidValidation.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AACA,OAAO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;;;;;GA8BG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,6BAA6B,GAAG;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,QAAQ,CAAC,EAAE,IAAI,GAAG,YAAY,GAAG,cAAc,CAAC;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,7 +1,9 @@
|
|
|
1
1
|
import { isValidHexAddress } from '@metamask/utils';
|
|
2
2
|
import { HYPERLIQUID_ASSET_CONFIGS, BASIS_POINTS_DIVISOR, getSupportedAssets, TRADING_DEFAULTS, } from '../constants/hyperLiquidConfig.js';
|
|
3
3
|
import { CHASE_ORDER_CONFIG, HYPERLIQUID_ORDER_LIMITS, HYPERLIQUID_TWAP_LIMITS, } from '../constants/perpsConfig.js';
|
|
4
|
-
import {
|
|
4
|
+
import { PerpsControllerError } from '../errors.js';
|
|
5
|
+
import { isPerpsErrorCode, PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
6
|
+
import { ensureError } from './errorUtils.js';
|
|
5
7
|
import { getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, isTriggerOrderType, SCALE_ORDER_COUNT, } from './orderTypes.js';
|
|
6
8
|
/**
|
|
7
9
|
* Validation utilities for HyperLiquid operations
|
|
@@ -14,10 +16,22 @@ import { getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, is
|
|
|
14
16
|
* @returns The error response with success=false and error message
|
|
15
17
|
*/
|
|
16
18
|
export function createErrorResult(error, defaultResponse) {
|
|
19
|
+
const normalizedError = ensureError(error, 'createErrorResult');
|
|
20
|
+
let errorFields = {};
|
|
21
|
+
if (error instanceof PerpsControllerError) {
|
|
22
|
+
errorFields = {
|
|
23
|
+
errorCode: error.errorCode,
|
|
24
|
+
errorDetails: error.errorDetails,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
else if (isPerpsErrorCode(normalizedError.message)) {
|
|
28
|
+
errorFields = { errorCode: normalizedError.message };
|
|
29
|
+
}
|
|
17
30
|
return {
|
|
18
31
|
...defaultResponse,
|
|
19
32
|
success: false,
|
|
20
|
-
error:
|
|
33
|
+
error: normalizedError.message,
|
|
34
|
+
...errorFields,
|
|
21
35
|
};
|
|
22
36
|
}
|
|
23
37
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidValidation.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGpD,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB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,CAAC,SAAS,CAAC,IAAI,IAAI,GAAG,SAAS,EAAE,CAAC;YACrE,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,iBAAiB,CAAC,uBAAuB;aACjD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,aAAkC;IAElC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,iBAAiB,CAAC,kBAAkB;SAC5C,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { isValidHexAddress } from '@metamask/utils';\nimport type { CaipAssetId, Hex } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_ASSET_CONFIGS,\n BASIS_POINTS_DIVISOR,\n getSupportedAssets,\n TRADING_DEFAULTS,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n CHASE_ORDER_CONFIG,\n HYPERLIQUID_ORDER_LIMITS,\n HYPERLIQUID_TWAP_LIMITS,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n GetSupportedPathsParams,\n PerpsDebugLogger,\n} from '../types/index.js';\nimport type { OrderType, TpslLinkage } from '../types/perps-types.js';\nimport {\n getTriggerExecution,\n isLimitExecutionOrderType,\n isStrategyOrderType,\n isTriggerOrderType,\n SCALE_ORDER_COUNT,\n} from './orderTypes.js';\n\n/**\n * Optional debug logger for validation functions.\n * When provided, enables detailed logging for debugging.\n * When omitted, validation runs silently.\n */\nexport type ValidationDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Validation utilities for HyperLiquid operations\n */\n\n/**\n * Create standardized error response.\n *\n * @param error - The error that occurred\n * @param defaultResponse - The default response object to use as template\n * @returns The error response with success=false and error message\n */\nexport function createErrorResult<\n TValue extends { success: boolean; error?: string },\n>(error: unknown, defaultResponse: TValue): TValue {\n return {\n ...defaultResponse,\n success: false,\n error:\n error instanceof Error ? error.message : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n}\n\n/**\n * Validate withdrawal parameters.\n *\n * @param params - Withdrawal parameters to validate\n * @param params.assetId - The CAIP asset ID to withdraw\n * @param params.amount - Amount to withdraw as string\n * @param params.destination - Optional destination hex address\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateWithdrawalParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n destination?: Hex;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateWithdrawalParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n hasDestination: Boolean(params.destination),\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateWithdrawalParams: Missing assetId', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateWithdrawalParams: Missing amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateWithdrawalParams: Invalid amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n };\n }\n\n // Validate destination address if provided\n if (params.destination && !isValidHexAddress(params.destination)) {\n debugLogger?.log('validateWithdrawalParams: Invalid destination address', {\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n destination: params.destination,\n isValidHex: isValidHexAddress(params.destination),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n };\n }\n\n debugLogger?.log('validateWithdrawalParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination ?? 'will use user wallet',\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate deposit parameters.\n *\n * @param params - Deposit parameters to validate\n * @param params.assetId - The CAIP asset ID to deposit\n * @param params.amount - Amount to deposit as string\n * @param params.isTestnet - Whether this is a testnet deposit\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateDepositParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n isTestnet?: boolean;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateDepositParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n isTestnet: params.isTestnet,\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateDepositParams: Missing assetId', {\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateDepositParams: Missing amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateDepositParams: Invalid amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n };\n }\n\n // Check minimum deposit amount\n const minimumAmount = params.isTestnet\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n debugLogger?.log('validateDepositParams: Checking minimum amount', {\n amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n network: params.isTestnet ? 'testnet' : 'mainnet',\n });\n\n if (amount < minimumAmount) {\n debugLogger?.log('validateDepositParams: Below minimum deposit', {\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n amount,\n minimumAmount,\n difference: minimumAmount - amount,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n };\n }\n\n debugLogger?.log('validateDepositParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n parsedAmount: amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate asset support for withdrawals using AssetRoute arrays.\n *\n * @param assetId - The CAIP asset ID to validate\n * @param supportedRoutes - Array of supported asset routes\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateAssetSupport(\n assetId: CaipAssetId,\n supportedRoutes: { assetId: CaipAssetId }[],\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateAssetSupport: Checking asset support', {\n assetId,\n supportedRoutesCount: supportedRoutes.length,\n });\n\n const supportedAssetIds = supportedRoutes.map((route) => route.assetId);\n\n // Check if asset is supported\n const isSupported = supportedAssetIds.includes(assetId);\n\n if (!isSupported) {\n // Also check case-insensitive match for contract addresses\n const isSupportedCaseInsensitive = supportedAssetIds.some(\n (supportedId) => supportedId.toLowerCase() === assetId.toLowerCase(),\n );\n\n if (!isSupportedCaseInsensitive) {\n debugLogger?.log('validateAssetSupport: Asset not supported', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n assetId,\n supportedAssetIds,\n checkedCaseInsensitive: true,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n };\n }\n\n debugLogger?.log(\n '⚠️ validateAssetSupport: Asset supported with case mismatch',\n {\n providedAssetId: assetId,\n matchedAssetId: supportedAssetIds.find(\n (id) => id.toLowerCase() === assetId.toLowerCase(),\n ),\n },\n );\n }\n\n debugLogger?.log('validateAssetSupport: Asset is supported', {\n assetId,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate balance against withdrawal amount.\n *\n * @param withdrawAmount - The amount to withdraw\n * @param withdrawableBalance - Max USD that can leave the venue right now\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateBalance(\n withdrawAmount: number,\n withdrawableBalance: number,\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateBalance: Checking balance sufficiency', {\n withdrawAmount,\n withdrawableBalance,\n difference: withdrawableBalance - withdrawAmount,\n });\n\n if (withdrawAmount > withdrawableBalance) {\n const shortfall = withdrawAmount - withdrawableBalance;\n\n debugLogger?.log('validateBalance: Insufficient balance', {\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n withdrawAmount,\n withdrawableBalance,\n shortfall,\n percentageOfAvailable: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n };\n }\n\n const remainingBalance = withdrawableBalance - withdrawAmount;\n debugLogger?.log('validateBalance: Balance is sufficient', {\n withdrawAmount,\n withdrawableBalance,\n remainingBalance,\n percentageUsed: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return { isValid: true };\n}\n\n/**\n * Apply filters to asset paths with comprehensive logging.\n *\n * @param assets - Array of CAIP asset IDs to filter\n * @param params - Filter parameters including chainId, symbol, and assetId\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Filtered array of CAIP asset IDs\n */\nexport function applyPathFilters(\n assets: CaipAssetId[],\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n if (!params) {\n debugLogger?.log(\n 'HyperLiquid: applyPathFilters - no params, returning all assets',\n { assets },\n );\n return assets;\n }\n\n let filtered = assets;\n\n debugLogger?.log('HyperLiquid: applyPathFilters - starting filter', {\n initialAssets: assets,\n filterParams: params,\n });\n\n if (params.chainId) {\n const before = filtered;\n filtered = filtered.filter((asset) =>\n asset.startsWith(params.chainId as string),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - chainId filter', {\n chainId: params.chainId,\n before,\n after: filtered,\n });\n }\n\n // Note: `in` is the idiomatic TypeScript way to narrow a string to\n // `keyof typeof` for indexed access; `hasProperty` types the indexed\n // result as `unknown` and loses the `{ testnet, mainnet }` shape.\n /* eslint-disable-next-line no-restricted-syntax */\n if (params.symbol && params.symbol in HYPERLIQUID_ASSET_CONFIGS) {\n const config =\n HYPERLIQUID_ASSET_CONFIGS[\n params.symbol as keyof typeof HYPERLIQUID_ASSET_CONFIGS\n ];\n const isTestnet = params.isTestnet ?? false;\n const selectedAsset = isTestnet ? config.testnet : config.mainnet;\n const before = filtered;\n filtered = [selectedAsset];\n debugLogger?.log('HyperLiquid: applyPathFilters - symbol filter', {\n symbol: params.symbol,\n isTestnet,\n config,\n selectedAsset,\n before,\n after: filtered,\n });\n }\n\n if (params.assetId) {\n const before = filtered;\n // Use case-insensitive comparison for asset ID matching to handle address case differences\n filtered = filtered.filter(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - assetId filter', {\n assetId: params.assetId,\n before,\n after: filtered,\n exactMatch: before.includes(params.assetId),\n caseInsensitiveMatch: before.some(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n ),\n });\n }\n\n debugLogger?.log('HyperLiquid: applyPathFilters - final result', {\n initialAssets: assets,\n finalFiltered: filtered,\n filterParams: params,\n });\n\n return filtered;\n}\n\n/**\n * Get supported deposit/withdrawal paths with filtering.\n *\n * @param params - Filter parameters including isTestnet, chainId, symbol\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Array of supported CAIP asset IDs\n */\nexport function getSupportedPaths(\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n const isTestnet = params?.isTestnet ?? false;\n const assets = getSupportedAssets(isTestnet);\n const filteredAssets = applyPathFilters(assets, params, debugLogger);\n\n debugLogger?.log('HyperLiquid: getSupportedPaths', {\n isTestnet,\n requestedParams: params,\n allAssets: assets,\n filteredAssets,\n returnType: 'CaipAssetId[]',\n example: filteredAssets[0],\n });\n\n return filteredAssets;\n}\n\n/**\n * Get maximum order value based on leverage and order type.\n * Based on HyperLiquid contract specifications.\n *\n * @param maxLeverage - The maximum leverage for the market\n * @param orderType - The order type; every type follows the limit/market\n * multiplier of its execution mode, so `stop_limit`, `scale` and `chase` are all\n * treated as limit orders and `twap` as a market order\n * @returns Maximum order value in USD\n */\nexport function getMaxOrderValue(\n maxLeverage: number,\n orderType: OrderType,\n): number {\n let marketLimit: number;\n\n if (maxLeverage >= 25) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.HighLeverage;\n } else if (maxLeverage >= 20) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumHighLeverage;\n } else if (maxLeverage >= 10) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumLeverage;\n } else {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.LowLeverage;\n }\n\n // The higher cap follows how the order executes, not whose price it uses: a\n // scale ladder and a chase rest limit orders on the book, so holding them to\n // the tighter market-order cap would bound them by how they were requested\n // rather than by what they do.\n return getTriggerExecution(orderType) === 'limit'\n ? marketLimit * HYPERLIQUID_ORDER_LIMITS.LimitOrderMultiplier\n : marketLimit;\n}\n\n/**\n * The `grouping` value each provider-agnostic linkage corresponds to, used to\n * detect a caller supplying both spellings with different meanings.\n */\nconst TPSL_LINKAGE_GROUPING: Record<\n TpslLinkage,\n 'na' | 'normalTpsl' | 'positionTpsl'\n> = {\n none: 'na',\n order: 'normalTpsl',\n position: 'positionTpsl',\n};\n\n/**\n * The strategy-placement fields of `OrderParams`, as validation sees them.\n *\n * Named so the provider can forward exactly this group to `validateOrderParams`\n * without the field list drifting between the two call sites.\n */\nexport type StrategyOrderValidationParams = {\n twapDuration?: number;\n twapRandomize?: boolean;\n scaleMinPrice?: string;\n scaleMaxPrice?: string;\n scaleNumOrders?: number;\n scaleSkew?: number;\n chaseIntervalMs?: number;\n chaseMaxDurationMs?: number;\n chaseMaxRepricings?: number;\n chaseMaxDistanceBps?: number;\n};\n\n/**\n * Which strategy owns each strategy-only field.\n *\n * Anything a placement does not own is rejected rather than ignored: a `twap`\n * carrying `scaleNumOrders` is a caller mistake, and dropping it silently would\n * execute something other than what was asked for.\n */\nconst STRATEGY_FIELD_OWNER: Record<\n keyof StrategyOrderValidationParams,\n 'twap' | 'scale' | 'chase'\n> = {\n twapDuration: 'twap',\n twapRandomize: 'twap',\n scaleMinPrice: 'scale',\n scaleMaxPrice: 'scale',\n scaleNumOrders: 'scale',\n scaleSkew: 'scale',\n chaseIntervalMs: 'chase',\n chaseMaxDurationMs: 'chase',\n chaseMaxRepricings: 'chase',\n chaseMaxDistanceBps: 'chase',\n};\n\n/**\n * Validate the TWAP-specific parameters of a `twap` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateTwapParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (params.twapDuration === undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,\n };\n }\n\n // The venue validates `twap.m` as a safe integer within these bounds before\n // the request is signed, so checking it here turns an opaque SDK failure into\n // a typed rejection that costs no round trip.\n if (\n !Number.isInteger(params.twapDuration) ||\n params.twapDuration < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||\n params.twapDuration > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the ladder parameters of a `scale` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateScaleParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (\n params.scaleMinPrice === undefined ||\n params.scaleMaxPrice === undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,\n };\n }\n\n const minPrice = parseFloat(params.scaleMinPrice);\n const maxPrice = parseFloat(params.scaleMaxPrice);\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\n if (\n params.scaleNumOrders === undefined ||\n !Number.isInteger(params.scaleNumOrders) ||\n params.scaleNumOrders < SCALE_ORDER_COUNT.min ||\n params.scaleNumOrders > SCALE_ORDER_COUNT.max\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,\n };\n }\n\n // Omitted is an even ladder, so only a supplied skew is checked. The value is\n // taken exactly as the caller wrote it: clients coerce their input to two\n // decimals, and rounding it again here would place a ladder weighted\n // differently from the one the form previewed.\n if (\n params.scaleSkew !== undefined &&\n (!Number.isFinite(params.scaleSkew) || params.scaleSkew <= 0)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the polling parameters of a `chase` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateChaseParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n const interval =\n params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;\n if (\n !Number.isFinite(interval) ||\n interval < CHASE_ORDER_CONFIG.MinIntervalMs\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_INTERVAL_INVALID,\n };\n }\n\n const maxDuration = params.chaseMaxDurationMs;\n // A window shorter than one poll would place the order and immediately stop\n // chasing it — a plain post-only limit order wearing a chase's name.\n if (\n maxDuration !== undefined &&\n (!Number.isFinite(maxDuration) || maxDuration < interval)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n const maxRepricings = params.chaseMaxRepricings;\n if (\n maxRepricings !== undefined &&\n (!Number.isInteger(maxRepricings) || maxRepricings < 1)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n if (\n params.chaseMaxDistanceBps !== undefined &&\n (!Number.isFinite(params.chaseMaxDistanceBps) ||\n params.chaseMaxDistanceBps <= 0 ||\n params.chaseMaxDistanceBps >= BASIS_POINTS_DIVISOR)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_MAX_DISTANCE_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate strategy placement parameters, and the absence of them.\n *\n * Runs before every other order rule so a strategy placement is rejected with a\n * strategy-shaped reason rather than with the trigger/limit rule its shape\n * happens to trip first.\n *\n * @param params - Order parameters to validate.\n * @param params.orderType - The order placement type.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateStrategyOrderParams(\n params: StrategyOrderValidationParams & {\n orderType?: OrderType;\n price?: string;\n triggerPrice?: string;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n },\n): { isValid: boolean; error?: string } {\n const { orderType } = params;\n const strategy =\n orderType !== undefined && isStrategyOrderType(orderType)\n ? orderType\n : undefined;\n\n // Every strategy-only field must belong to the placement carrying it. This\n // also covers the non-strategy case, where no field has an owner to match.\n const foreignField = (\n Object.keys(STRATEGY_FIELD_OWNER) as (keyof StrategyOrderValidationParams)[]\n ).find(\n (field) =>\n params[field] !== undefined && STRATEGY_FIELD_OWNER[field] !== strategy,\n );\n if (foreignField) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_PARAMS_NOT_SUPPORTED,\n };\n }\n\n if (!strategy) {\n return { isValid: true };\n }\n\n // A strategy owns its own execution: it derives its own prices, rests its own\n // orders, and decides its own time in force. Accepting these fields would\n // mean quietly ignoring them.\n //\n // `clientOrderId` is refused for the same reason and cannot be honoured even\n // in principle: the venue's TWAP action carries no client id, a scale ladder\n // is many orders and a client id must be unique per order, and a chase\n // replaces its order on every re-price. One id cannot name any of them.\n if (\n params.price !== undefined ||\n params.triggerPrice !== undefined ||\n params.timeInForce !== undefined ||\n params.clientOrderId !== undefined ||\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined ||\n params.takeProfitSize !== undefined ||\n params.stopLossSize !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_FIELD_UNSUPPORTED,\n };\n }\n\n if (strategy === 'twap') {\n return validateTwapParams(params);\n }\n if (strategy === 'scale') {\n return validateScaleParams(params);\n }\n return validateChaseParams(params);\n}\n\n/**\n * Validate order parameters.\n * Basic validation - checks required fields are present.\n * Amount validation (size/USD) is handled by validateOrder.\n *\n * @param params - Order parameters to validate\n * @param params.coin - The trading pair coin symbol\n * @param params.size - The order size as string\n * @param params.price - The order price as string\n * @param params.orderType - The order placement type\n * @param params.triggerPrice - Trigger price; required for trigger placement types and\n * rejected for market/limit orders so a stray value can never be silently dropped\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @param params.tpslLinkage - How an attached TP/SL is linked\n * @param params.grouping - Deprecated protocol-shaped spelling of `tpslLinkage`\n * @param params.timeInForce - Time in force; only a plain limit order can carry one\n * @param params.clientOrderId - Client-provided order ID; a strategy placement cannot carry one\n * @param params.twapDuration - TWAP window in whole minutes\n * @param params.twapRandomize - Whether to vary each TWAP suborder's size by up to ±20%\n * @param params.scaleMinPrice - Lowest price in a scale ladder\n * @param params.scaleMaxPrice - Highest price in a scale ladder\n * @param params.scaleNumOrders - How many orders a scale ladder fans out into\n * @param params.scaleSkew - How a scale ladder's size is weighted across its rungs\n * @param params.chaseIntervalMs - How often a chase re-reads the touch\n * @param params.chaseMaxDurationMs - How long a chase keeps re-pricing\n * @param params.chaseMaxRepricings - Cap on a chase's cancel/replace cycles\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderParams(\n params: StrategyOrderValidationParams & {\n coin?: string;\n size?: string;\n price?: string;\n orderType?: OrderType;\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n tpslLinkage?: TpslLinkage;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n },\n): { isValid: boolean; error?: string } {\n if (!params.coin) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_COIN_REQUIRED,\n };\n }\n\n // Note: Size validation removed - validateOrder handles amount validation using USD as source of truth\n\n // Strategy placements are decided first: their shape trips the limit-price and\n // trigger rules below, and the strategy-shaped reason is the useful one.\n const strategyValidation = validateStrategyOrderParams(params);\n if (!strategyValidation.isValid) {\n return strategyValidation;\n }\n\n const { orderType } = params;\n const isTrigger = orderType !== undefined && isTriggerOrderType(orderType);\n\n // Require price for orders that execute as limit orders (limit, stop_limit,\n // take_profit_limit)\n if (\n orderType !== undefined &&\n isLimitExecutionOrderType(orderType) &&\n !params.price\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,\n };\n }\n\n if (params.price && parseFloat(params.price) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n };\n }\n\n if (isTrigger) {\n if (!params.triggerPrice) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED,\n };\n }\n\n const triggerPrice = parseFloat(params.triggerPrice);\n if (isNaN(triggerPrice) || triggerPrice <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n };\n }\n\n // A trigger placement combined with attached TP/SL children is rejected\n // rather than silently reshaped: the exchange semantics of a triggered\n // parent owning triggered children are not part of this contract.\n // Each field is checked explicitly: a falsy-but-present price (e.g. '') is\n // still an attached TP/SL request and must be rejected, not skipped.\n if (\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_TPSL_UNSUPPORTED,\n };\n }\n // Consistent with the attached-TP/SL check above: a falsy-but-present value\n // (e.g. '') is still a request to place a trigger, not an absent field.\n } else if (params.triggerPrice !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_NOT_SUPPORTED,\n };\n }\n\n // `tpslLinkage` supersedes `grouping`, but two spellings that disagree are a\n // caller mistake — resolving one silently would hide it.\n if (params.tpslLinkage !== undefined && params.grouping !== undefined) {\n const expectedGrouping = TPSL_LINKAGE_GROUPING[params.tpslLinkage];\n if (expectedGrouping !== params.grouping) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_CONFLICT,\n };\n }\n }\n\n const hasAttachedTpsl =\n params.takeProfitPrice !== undefined || params.stopLossPrice !== undefined;\n\n // Every order in a `positionTpsl` batch has to be a trigger order, and no\n // shape of order placement produces one. With an attached TP/SL the batch\n // carries the ordinary parent order the TP/SL protects; without one it is\n // that parent order alone. HyperLiquid rejects both, so the linkage is\n // refused outright — it belongs to `updatePositionTPSL`, applied to the\n // position once the parent has filled.\n const requestsPositionLinkage =\n params.tpslLinkage === 'position' || params.grouping === 'positionTpsl';\n if (requestsPositionLinkage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_POSITION_LINKAGE_UNSUPPORTED,\n };\n }\n\n // `na` grouping submits the attached TP/SL as standalone triggers, bound to\n // neither the parent order nor the resulting position. An unfilled parent\n // then leaves them behind as orphan reduce-only triggers that fire against\n // whatever position happens to exist. An attached TP/SL needs a linkage that\n // links it, so the combination is a caller mistake rather than a mode.\n const requestsNoLinkage =\n params.tpslLinkage === 'none' || params.grouping === 'na';\n if (requestsNoLinkage && hasAttachedTpsl) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_REQUIRED,\n };\n }\n\n // Only a plain limit order rests on the book long enough for a time in force to\n // mean anything: a market order fills immediately and a trigger order's\n // execution is decided when it fires. Rejected here, at step 1 of placement, so\n // it cannot fire after leverage changes or a HIP-3 margin transfer.\n if (params.timeInForce !== undefined && orderType !== 'limit') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED,\n };\n }\n\n const partialTpslValidation = validatePartialTpslSizes(params);\n if (!partialTpslValidation.isValid) {\n return partialTpslValidation;\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate quantity-scoped (partial) TP/SL sizes against the parent order.\n *\n * @param params - Order parameters carrying the TP/SL prices and sizes\n * @param params.size - Parent order size\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @returns Validation result with isValid flag and optional error message\n */\nfunction validatePartialTpslSizes(params: {\n size?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n}): { isValid: boolean; error?: string } {\n const orderSize = params.size ? Math.abs(parseFloat(params.size)) : undefined;\n\n const entries: { size?: string; price?: string }[] = [\n { size: params.takeProfitSize, price: params.takeProfitPrice },\n { size: params.stopLossSize, price: params.stopLossPrice },\n ];\n\n for (const entry of entries) {\n if (entry.size === undefined) {\n continue;\n }\n\n // A size without its price would silently place nothing.\n if (!entry.price) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n const size = parseFloat(entry.size);\n if (isNaN(size) || size <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n if (orderSize !== undefined && !isNaN(orderSize) && size > orderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate coin exists in asset mapping.\n *\n * @param coin - The coin symbol to validate\n * @param coinToAssetId - Map of coin symbols to asset IDs\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateCoinExists(\n coin: string,\n coinToAssetId: Map<string, number>,\n): { isValid: boolean; error?: string } {\n if (!coinToAssetId.has(coin)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_UNKNOWN_COIN,\n };\n }\n\n return { isValid: true };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hyperLiquidValidation.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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,CAAC;AAC3B,CAAC","sourcesContent":["import { isValidHexAddress } from '@metamask/utils';\nimport type { CaipAssetId, Hex } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_ASSET_CONFIGS,\n BASIS_POINTS_DIVISOR,\n getSupportedAssets,\n TRADING_DEFAULTS,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n CHASE_ORDER_CONFIG,\n HYPERLIQUID_ORDER_LIMITS,\n HYPERLIQUID_TWAP_LIMITS,\n} from '../constants/perpsConfig.js';\nimport { PerpsControllerError } from '../errors.js';\nimport type { PerpsErrorResultFields } from '../errors.js';\nimport { isPerpsErrorCode, PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n GetSupportedPathsParams,\n PerpsDebugLogger,\n} from '../types/index.js';\nimport type { OrderType, TpslLinkage } from '../types/perps-types.js';\nimport { ensureError } from './errorUtils.js';\nimport {\n getTriggerExecution,\n isLimitExecutionOrderType,\n isStrategyOrderType,\n isTriggerOrderType,\n SCALE_ORDER_COUNT,\n} from './orderTypes.js';\n\n/**\n * Optional debug logger for validation functions.\n * When provided, enables detailed logging for debugging.\n * When omitted, validation runs silently.\n */\nexport type ValidationDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Validation utilities for HyperLiquid operations\n */\n\n/**\n * Create standardized error response.\n *\n * @param error - The error that occurred\n * @param defaultResponse - The default response object to use as template\n * @returns The error response with success=false and error message\n */\nexport function createErrorResult<\n TValue extends { success: boolean; error?: string },\n>(error: unknown, defaultResponse: TValue): TValue & PerpsErrorResultFields {\n const normalizedError = ensureError(error, 'createErrorResult');\n let errorFields: PerpsErrorResultFields = {};\n\n if (error instanceof PerpsControllerError) {\n errorFields = {\n errorCode: error.errorCode,\n errorDetails: error.errorDetails,\n };\n } else if (isPerpsErrorCode(normalizedError.message)) {\n errorFields = { errorCode: normalizedError.message };\n }\n\n return {\n ...defaultResponse,\n success: false,\n error: normalizedError.message,\n ...errorFields,\n };\n}\n\n/**\n * Validate withdrawal parameters.\n *\n * @param params - Withdrawal parameters to validate\n * @param params.assetId - The CAIP asset ID to withdraw\n * @param params.amount - Amount to withdraw as string\n * @param params.destination - Optional destination hex address\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateWithdrawalParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n destination?: Hex;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateWithdrawalParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n hasDestination: Boolean(params.destination),\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateWithdrawalParams: Missing assetId', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateWithdrawalParams: Missing amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateWithdrawalParams: Invalid amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n };\n }\n\n // Validate destination address if provided\n if (params.destination && !isValidHexAddress(params.destination)) {\n debugLogger?.log('validateWithdrawalParams: Invalid destination address', {\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n destination: params.destination,\n isValidHex: isValidHexAddress(params.destination),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n };\n }\n\n debugLogger?.log('validateWithdrawalParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination ?? 'will use user wallet',\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate deposit parameters.\n *\n * @param params - Deposit parameters to validate\n * @param params.assetId - The CAIP asset ID to deposit\n * @param params.amount - Amount to deposit as string\n * @param params.isTestnet - Whether this is a testnet deposit\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateDepositParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n isTestnet?: boolean;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateDepositParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n isTestnet: params.isTestnet,\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateDepositParams: Missing assetId', {\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateDepositParams: Missing amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateDepositParams: Invalid amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n };\n }\n\n // Check minimum deposit amount\n const minimumAmount = params.isTestnet\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n debugLogger?.log('validateDepositParams: Checking minimum amount', {\n amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n network: params.isTestnet ? 'testnet' : 'mainnet',\n });\n\n if (amount < minimumAmount) {\n debugLogger?.log('validateDepositParams: Below minimum deposit', {\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n amount,\n minimumAmount,\n difference: minimumAmount - amount,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n };\n }\n\n debugLogger?.log('validateDepositParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n parsedAmount: amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate asset support for withdrawals using AssetRoute arrays.\n *\n * @param assetId - The CAIP asset ID to validate\n * @param supportedRoutes - Array of supported asset routes\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateAssetSupport(\n assetId: CaipAssetId,\n supportedRoutes: { assetId: CaipAssetId }[],\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateAssetSupport: Checking asset support', {\n assetId,\n supportedRoutesCount: supportedRoutes.length,\n });\n\n const supportedAssetIds = supportedRoutes.map((route) => route.assetId);\n\n // Check if asset is supported\n const isSupported = supportedAssetIds.includes(assetId);\n\n if (!isSupported) {\n // Also check case-insensitive match for contract addresses\n const isSupportedCaseInsensitive = supportedAssetIds.some(\n (supportedId) => supportedId.toLowerCase() === assetId.toLowerCase(),\n );\n\n if (!isSupportedCaseInsensitive) {\n debugLogger?.log('validateAssetSupport: Asset not supported', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n assetId,\n supportedAssetIds,\n checkedCaseInsensitive: true,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n };\n }\n\n debugLogger?.log(\n '⚠️ validateAssetSupport: Asset supported with case mismatch',\n {\n providedAssetId: assetId,\n matchedAssetId: supportedAssetIds.find(\n (id) => id.toLowerCase() === assetId.toLowerCase(),\n ),\n },\n );\n }\n\n debugLogger?.log('validateAssetSupport: Asset is supported', {\n assetId,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate balance against withdrawal amount.\n *\n * @param withdrawAmount - The amount to withdraw\n * @param withdrawableBalance - Max USD that can leave the venue right now\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateBalance(\n withdrawAmount: number,\n withdrawableBalance: number,\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateBalance: Checking balance sufficiency', {\n withdrawAmount,\n withdrawableBalance,\n difference: withdrawableBalance - withdrawAmount,\n });\n\n if (withdrawAmount > withdrawableBalance) {\n const shortfall = withdrawAmount - withdrawableBalance;\n\n debugLogger?.log('validateBalance: Insufficient balance', {\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n withdrawAmount,\n withdrawableBalance,\n shortfall,\n percentageOfAvailable: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n };\n }\n\n const remainingBalance = withdrawableBalance - withdrawAmount;\n debugLogger?.log('validateBalance: Balance is sufficient', {\n withdrawAmount,\n withdrawableBalance,\n remainingBalance,\n percentageUsed: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return { isValid: true };\n}\n\n/**\n * Apply filters to asset paths with comprehensive logging.\n *\n * @param assets - Array of CAIP asset IDs to filter\n * @param params - Filter parameters including chainId, symbol, and assetId\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Filtered array of CAIP asset IDs\n */\nexport function applyPathFilters(\n assets: CaipAssetId[],\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n if (!params) {\n debugLogger?.log(\n 'HyperLiquid: applyPathFilters - no params, returning all assets',\n { assets },\n );\n return assets;\n }\n\n let filtered = assets;\n\n debugLogger?.log('HyperLiquid: applyPathFilters - starting filter', {\n initialAssets: assets,\n filterParams: params,\n });\n\n if (params.chainId) {\n const before = filtered;\n filtered = filtered.filter((asset) =>\n asset.startsWith(params.chainId as string),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - chainId filter', {\n chainId: params.chainId,\n before,\n after: filtered,\n });\n }\n\n // Note: `in` is the idiomatic TypeScript way to narrow a string to\n // `keyof typeof` for indexed access; `hasProperty` types the indexed\n // result as `unknown` and loses the `{ testnet, mainnet }` shape.\n /* eslint-disable-next-line no-restricted-syntax */\n if (params.symbol && params.symbol in HYPERLIQUID_ASSET_CONFIGS) {\n const config =\n HYPERLIQUID_ASSET_CONFIGS[\n params.symbol as keyof typeof HYPERLIQUID_ASSET_CONFIGS\n ];\n const isTestnet = params.isTestnet ?? false;\n const selectedAsset = isTestnet ? config.testnet : config.mainnet;\n const before = filtered;\n filtered = [selectedAsset];\n debugLogger?.log('HyperLiquid: applyPathFilters - symbol filter', {\n symbol: params.symbol,\n isTestnet,\n config,\n selectedAsset,\n before,\n after: filtered,\n });\n }\n\n if (params.assetId) {\n const before = filtered;\n // Use case-insensitive comparison for asset ID matching to handle address case differences\n filtered = filtered.filter(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - assetId filter', {\n assetId: params.assetId,\n before,\n after: filtered,\n exactMatch: before.includes(params.assetId),\n caseInsensitiveMatch: before.some(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n ),\n });\n }\n\n debugLogger?.log('HyperLiquid: applyPathFilters - final result', {\n initialAssets: assets,\n finalFiltered: filtered,\n filterParams: params,\n });\n\n return filtered;\n}\n\n/**\n * Get supported deposit/withdrawal paths with filtering.\n *\n * @param params - Filter parameters including isTestnet, chainId, symbol\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Array of supported CAIP asset IDs\n */\nexport function getSupportedPaths(\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n const isTestnet = params?.isTestnet ?? false;\n const assets = getSupportedAssets(isTestnet);\n const filteredAssets = applyPathFilters(assets, params, debugLogger);\n\n debugLogger?.log('HyperLiquid: getSupportedPaths', {\n isTestnet,\n requestedParams: params,\n allAssets: assets,\n filteredAssets,\n returnType: 'CaipAssetId[]',\n example: filteredAssets[0],\n });\n\n return filteredAssets;\n}\n\n/**\n * Get maximum order value based on leverage and order type.\n * Based on HyperLiquid contract specifications.\n *\n * @param maxLeverage - The maximum leverage for the market\n * @param orderType - The order type; every type follows the limit/market\n * multiplier of its execution mode, so `stop_limit`, `scale` and `chase` are all\n * treated as limit orders and `twap` as a market order\n * @returns Maximum order value in USD\n */\nexport function getMaxOrderValue(\n maxLeverage: number,\n orderType: OrderType,\n): number {\n let marketLimit: number;\n\n if (maxLeverage >= 25) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.HighLeverage;\n } else if (maxLeverage >= 20) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumHighLeverage;\n } else if (maxLeverage >= 10) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumLeverage;\n } else {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.LowLeverage;\n }\n\n // The higher cap follows how the order executes, not whose price it uses: a\n // scale ladder and a chase rest limit orders on the book, so holding them to\n // the tighter market-order cap would bound them by how they were requested\n // rather than by what they do.\n return getTriggerExecution(orderType) === 'limit'\n ? marketLimit * HYPERLIQUID_ORDER_LIMITS.LimitOrderMultiplier\n : marketLimit;\n}\n\n/**\n * The `grouping` value each provider-agnostic linkage corresponds to, used to\n * detect a caller supplying both spellings with different meanings.\n */\nconst TPSL_LINKAGE_GROUPING: Record<\n TpslLinkage,\n 'na' | 'normalTpsl' | 'positionTpsl'\n> = {\n none: 'na',\n order: 'normalTpsl',\n position: 'positionTpsl',\n};\n\n/**\n * The strategy-placement fields of `OrderParams`, as validation sees them.\n *\n * Named so the provider can forward exactly this group to `validateOrderParams`\n * without the field list drifting between the two call sites.\n */\nexport type StrategyOrderValidationParams = {\n twapDuration?: number;\n twapRandomize?: boolean;\n scaleMinPrice?: string;\n scaleMaxPrice?: string;\n scaleNumOrders?: number;\n scaleSkew?: number;\n chaseIntervalMs?: number;\n chaseMaxDurationMs?: number;\n chaseMaxRepricings?: number;\n chaseMaxDistanceBps?: number;\n};\n\n/**\n * Which strategy owns each strategy-only field.\n *\n * Anything a placement does not own is rejected rather than ignored: a `twap`\n * carrying `scaleNumOrders` is a caller mistake, and dropping it silently would\n * execute something other than what was asked for.\n */\nconst STRATEGY_FIELD_OWNER: Record<\n keyof StrategyOrderValidationParams,\n 'twap' | 'scale' | 'chase'\n> = {\n twapDuration: 'twap',\n twapRandomize: 'twap',\n scaleMinPrice: 'scale',\n scaleMaxPrice: 'scale',\n scaleNumOrders: 'scale',\n scaleSkew: 'scale',\n chaseIntervalMs: 'chase',\n chaseMaxDurationMs: 'chase',\n chaseMaxRepricings: 'chase',\n chaseMaxDistanceBps: 'chase',\n};\n\n/**\n * Validate the TWAP-specific parameters of a `twap` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateTwapParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (params.twapDuration === undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,\n };\n }\n\n // The venue validates `twap.m` as a safe integer within these bounds before\n // the request is signed, so checking it here turns an opaque SDK failure into\n // a typed rejection that costs no round trip.\n if (\n !Number.isInteger(params.twapDuration) ||\n params.twapDuration < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||\n params.twapDuration > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the ladder parameters of a `scale` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateScaleParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (\n params.scaleMinPrice === undefined ||\n params.scaleMaxPrice === undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,\n };\n }\n\n const minPrice = parseFloat(params.scaleMinPrice);\n const maxPrice = parseFloat(params.scaleMaxPrice);\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\n if (\n params.scaleNumOrders === undefined ||\n !Number.isInteger(params.scaleNumOrders) ||\n params.scaleNumOrders < SCALE_ORDER_COUNT.min ||\n params.scaleNumOrders > SCALE_ORDER_COUNT.max\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,\n };\n }\n\n // Omitted is an even ladder, so only a supplied skew is checked. The value is\n // taken exactly as the caller wrote it: clients coerce their input to two\n // decimals, and rounding it again here would place a ladder weighted\n // differently from the one the form previewed.\n if (\n params.scaleSkew !== undefined &&\n (!Number.isFinite(params.scaleSkew) || params.scaleSkew <= 0)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the polling parameters of a `chase` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateChaseParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n const interval =\n params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;\n if (\n !Number.isFinite(interval) ||\n interval < CHASE_ORDER_CONFIG.MinIntervalMs\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_INTERVAL_INVALID,\n };\n }\n\n const maxDuration = params.chaseMaxDurationMs;\n // A window shorter than one poll would place the order and immediately stop\n // chasing it — a plain post-only limit order wearing a chase's name.\n if (\n maxDuration !== undefined &&\n (!Number.isFinite(maxDuration) || maxDuration < interval)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n const maxRepricings = params.chaseMaxRepricings;\n if (\n maxRepricings !== undefined &&\n (!Number.isInteger(maxRepricings) || maxRepricings < 1)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n if (\n params.chaseMaxDistanceBps !== undefined &&\n (!Number.isFinite(params.chaseMaxDistanceBps) ||\n params.chaseMaxDistanceBps <= 0 ||\n params.chaseMaxDistanceBps >= BASIS_POINTS_DIVISOR)\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_MAX_DISTANCE_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate strategy placement parameters, and the absence of them.\n *\n * Runs before every other order rule so a strategy placement is rejected with a\n * strategy-shaped reason rather than with the trigger/limit rule its shape\n * happens to trip first.\n *\n * @param params - Order parameters to validate.\n * @param params.orderType - The order placement type.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateStrategyOrderParams(\n params: StrategyOrderValidationParams & {\n orderType?: OrderType;\n price?: string;\n triggerPrice?: string;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n },\n): { isValid: boolean; error?: string } {\n const { orderType } = params;\n const strategy =\n orderType !== undefined && isStrategyOrderType(orderType)\n ? orderType\n : undefined;\n\n // Every strategy-only field must belong to the placement carrying it. This\n // also covers the non-strategy case, where no field has an owner to match.\n const foreignField = (\n Object.keys(STRATEGY_FIELD_OWNER) as (keyof StrategyOrderValidationParams)[]\n ).find(\n (field) =>\n params[field] !== undefined && STRATEGY_FIELD_OWNER[field] !== strategy,\n );\n if (foreignField) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_PARAMS_NOT_SUPPORTED,\n };\n }\n\n if (!strategy) {\n return { isValid: true };\n }\n\n // A strategy owns its own execution: it derives its own prices, rests its own\n // orders, and decides its own time in force. Accepting these fields would\n // mean quietly ignoring them.\n //\n // `clientOrderId` is refused for the same reason and cannot be honoured even\n // in principle: the venue's TWAP action carries no client id, a scale ladder\n // is many orders and a client id must be unique per order, and a chase\n // replaces its order on every re-price. One id cannot name any of them.\n if (\n params.price !== undefined ||\n params.triggerPrice !== undefined ||\n params.timeInForce !== undefined ||\n params.clientOrderId !== undefined ||\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined ||\n params.takeProfitSize !== undefined ||\n params.stopLossSize !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_FIELD_UNSUPPORTED,\n };\n }\n\n if (strategy === 'twap') {\n return validateTwapParams(params);\n }\n if (strategy === 'scale') {\n return validateScaleParams(params);\n }\n return validateChaseParams(params);\n}\n\n/**\n * Validate order parameters.\n * Basic validation - checks required fields are present.\n * Amount validation (size/USD) is handled by validateOrder.\n *\n * @param params - Order parameters to validate\n * @param params.coin - The trading pair coin symbol\n * @param params.size - The order size as string\n * @param params.price - The order price as string\n * @param params.orderType - The order placement type\n * @param params.triggerPrice - Trigger price; required for trigger placement types and\n * rejected for market/limit orders so a stray value can never be silently dropped\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @param params.tpslLinkage - How an attached TP/SL is linked\n * @param params.grouping - Deprecated protocol-shaped spelling of `tpslLinkage`\n * @param params.timeInForce - Time in force; only a plain limit order can carry one\n * @param params.clientOrderId - Client-provided order ID; a strategy placement cannot carry one\n * @param params.twapDuration - TWAP window in whole minutes\n * @param params.twapRandomize - Whether to vary each TWAP suborder's size by up to ±20%\n * @param params.scaleMinPrice - Lowest price in a scale ladder\n * @param params.scaleMaxPrice - Highest price in a scale ladder\n * @param params.scaleNumOrders - How many orders a scale ladder fans out into\n * @param params.scaleSkew - How a scale ladder's size is weighted across its rungs\n * @param params.chaseIntervalMs - How often a chase re-reads the touch\n * @param params.chaseMaxDurationMs - How long a chase keeps re-pricing\n * @param params.chaseMaxRepricings - Cap on a chase's cancel/replace cycles\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderParams(\n params: StrategyOrderValidationParams & {\n coin?: string;\n size?: string;\n price?: string;\n orderType?: OrderType;\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n tpslLinkage?: TpslLinkage;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n },\n): { isValid: boolean; error?: string } {\n if (!params.coin) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_COIN_REQUIRED,\n };\n }\n\n // Note: Size validation removed - validateOrder handles amount validation using USD as source of truth\n\n // Strategy placements are decided first: their shape trips the limit-price and\n // trigger rules below, and the strategy-shaped reason is the useful one.\n const strategyValidation = validateStrategyOrderParams(params);\n if (!strategyValidation.isValid) {\n return strategyValidation;\n }\n\n const { orderType } = params;\n const isTrigger = orderType !== undefined && isTriggerOrderType(orderType);\n\n // Require price for orders that execute as limit orders (limit, stop_limit,\n // take_profit_limit)\n if (\n orderType !== undefined &&\n isLimitExecutionOrderType(orderType) &&\n !params.price\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,\n };\n }\n\n if (params.price && parseFloat(params.price) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n };\n }\n\n if (isTrigger) {\n if (!params.triggerPrice) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED,\n };\n }\n\n const triggerPrice = parseFloat(params.triggerPrice);\n if (isNaN(triggerPrice) || triggerPrice <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n };\n }\n\n // A trigger placement combined with attached TP/SL children is rejected\n // rather than silently reshaped: the exchange semantics of a triggered\n // parent owning triggered children are not part of this contract.\n // Each field is checked explicitly: a falsy-but-present price (e.g. '') is\n // still an attached TP/SL request and must be rejected, not skipped.\n if (\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_TPSL_UNSUPPORTED,\n };\n }\n // Consistent with the attached-TP/SL check above: a falsy-but-present value\n // (e.g. '') is still a request to place a trigger, not an absent field.\n } else if (params.triggerPrice !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_NOT_SUPPORTED,\n };\n }\n\n // `tpslLinkage` supersedes `grouping`, but two spellings that disagree are a\n // caller mistake — resolving one silently would hide it.\n if (params.tpslLinkage !== undefined && params.grouping !== undefined) {\n const expectedGrouping = TPSL_LINKAGE_GROUPING[params.tpslLinkage];\n if (expectedGrouping !== params.grouping) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_CONFLICT,\n };\n }\n }\n\n const hasAttachedTpsl =\n params.takeProfitPrice !== undefined || params.stopLossPrice !== undefined;\n\n // Every order in a `positionTpsl` batch has to be a trigger order, and no\n // shape of order placement produces one. With an attached TP/SL the batch\n // carries the ordinary parent order the TP/SL protects; without one it is\n // that parent order alone. HyperLiquid rejects both, so the linkage is\n // refused outright — it belongs to `updatePositionTPSL`, applied to the\n // position once the parent has filled.\n const requestsPositionLinkage =\n params.tpslLinkage === 'position' || params.grouping === 'positionTpsl';\n if (requestsPositionLinkage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_POSITION_LINKAGE_UNSUPPORTED,\n };\n }\n\n // `na` grouping submits the attached TP/SL as standalone triggers, bound to\n // neither the parent order nor the resulting position. An unfilled parent\n // then leaves them behind as orphan reduce-only triggers that fire against\n // whatever position happens to exist. An attached TP/SL needs a linkage that\n // links it, so the combination is a caller mistake rather than a mode.\n const requestsNoLinkage =\n params.tpslLinkage === 'none' || params.grouping === 'na';\n if (requestsNoLinkage && hasAttachedTpsl) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_REQUIRED,\n };\n }\n\n // Only a plain limit order rests on the book long enough for a time in force to\n // mean anything: a market order fills immediately and a trigger order's\n // execution is decided when it fires. Rejected here, at step 1 of placement, so\n // it cannot fire after leverage changes or a HIP-3 margin transfer.\n if (params.timeInForce !== undefined && orderType !== 'limit') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED,\n };\n }\n\n const partialTpslValidation = validatePartialTpslSizes(params);\n if (!partialTpslValidation.isValid) {\n return partialTpslValidation;\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate quantity-scoped (partial) TP/SL sizes against the parent order.\n *\n * @param params - Order parameters carrying the TP/SL prices and sizes\n * @param params.size - Parent order size\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @returns Validation result with isValid flag and optional error message\n */\nfunction validatePartialTpslSizes(params: {\n size?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n}): { isValid: boolean; error?: string } {\n const orderSize = params.size ? Math.abs(parseFloat(params.size)) : undefined;\n\n const entries: { size?: string; price?: string }[] = [\n { size: params.takeProfitSize, price: params.takeProfitPrice },\n { size: params.stopLossSize, price: params.stopLossPrice },\n ];\n\n for (const entry of entries) {\n if (entry.size === undefined) {\n continue;\n }\n\n // A size without its price would silently place nothing.\n if (!entry.price) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n const size = parseFloat(entry.size);\n if (isNaN(size) || size <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n if (orderSize !== undefined && !isNaN(orderSize) && size > orderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate coin exists in asset mapping.\n *\n * @param coin - The coin symbol to validate\n * @param coinToAssetId - Map of coin symbols to asset IDs\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateCoinExists(\n coin: string,\n coinToAssetId: Map<string, number>,\n): { isValid: boolean; error?: string } {\n if (!coinToAssetId.has(coin)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_UNKNOWN_COIN,\n };\n }\n\n return { isValid: true };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lighterAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,OAAO,KAAK,EACV,YAAY,EACZ,oBAAoB,EACpB,UAAU,EACV,KAAK,EACL,SAAS,EACT,eAAe,EACf,QAAQ,EACR,WAAW,EAEZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,2BAA2B,CAAC;AA+CnC;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,oBAAoB,EAC5B,WAAW,EAAE,MAAM,GAClB,UAAU,CAeZ;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,sBAAsB,EAC9B,UAAU,EAAE,oBAAoB,GAC/B,eAAe,CAmCjB;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,sBAAsB,EAC9B,SAAS,EAAE,MAAM,GAChB,WAAW,CAUb;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAC/C,IAAI,EAAE,mBAAmB,EACzB,SAAS,EAAE,MAAM,GAChB,WAAW,CAqBb;AAED;;;;;GAKG;AACH,wBAAgB,qCAAqC,CACnD,KAAK,EAAE,kBAAkB,GACxB,YAAY,CAwBd;AAED;;;;;;;;GAQG;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,OAAO,GAAG,SAAS,CAAC;IACjC,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,MAAM,CAuBT;AAkCD,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,gBAAgB,GAAG,cAAc,EACxC,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GACnB,SAAS,
|
|
1
|
+
{"version":3,"file":"lighterAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,OAAO,KAAK,EACV,YAAY,EACZ,oBAAoB,EACpB,UAAU,EACV,KAAK,EACL,SAAS,EAC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C5B,WAAW,GAAE,MAA6B,GACzC,QAAQ,CA8DV;AAMD;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,iBAAiB,GACzB,YAAY,CAgCd;AA0CD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,MAAM,GACb,KAAK,CA6EP"}
|
|
@@ -352,6 +352,9 @@ export function adaptFillFromLighterTrade(trade, symbol, accountIndex) {
|
|
|
352
352
|
}
|
|
353
353
|
return {
|
|
354
354
|
orderId: String(accountIsAsk ? trade.askId : trade.bidId),
|
|
355
|
+
// Lighter's unique execution id, validated as a safe non-negative
|
|
356
|
+
// integer above. Order id alone cannot separate two fills of one order.
|
|
357
|
+
fillId: String(trade.tradeId),
|
|
355
358
|
symbol,
|
|
356
359
|
side: accountIsAsk ? 'sell' : 'buy',
|
|
357
360
|
size: trade.size,
|