@metamask-previews/perps-controller 25.0.0-preview-c785ff081 → 26.1.0-preview-037c8a905
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 +115 -4
- package/dist/PerpsController-method-action-types.d.ts +149 -3
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +132 -6
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +769 -33
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +63 -0
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +73 -0
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +15 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +14 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/lighterConfig.d.ts +5 -0
- package/dist/constants/lighterConfig.d.ts.map +1 -1
- package/dist/constants/lighterConfig.js +5 -0
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +19 -1
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +22 -1
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +11 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/internal/accountReturnOnEquity.d.ts +12 -0
- package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
- package/dist/internal/accountReturnOnEquity.js +18 -0
- package/dist/internal/accountReturnOnEquity.js.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
- package/dist/internal/marketNumericValues.d.ts +10 -0
- package/dist/internal/marketNumericValues.d.ts.map +1 -0
- package/dist/internal/marketNumericValues.js +9 -0
- package/dist/internal/marketNumericValues.js.map +1 -0
- package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
- package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
- package/dist/internal/perpsDisplaySymbol.js +21 -0
- package/dist/internal/perpsDisplaySymbol.js.map +1 -0
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +54 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +153 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +72 -4
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +749 -157
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +9 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +28 -5
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/DataLakeService.d.ts.map +1 -1
- package/dist/services/DataLakeService.js +7 -28
- package/dist/services/DataLakeService.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +8 -0
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +65 -0
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +97 -17
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/LighterNotificationEnrollmentService.d.ts +40 -0
- package/dist/services/LighterNotificationEnrollmentService.d.ts.map +1 -0
- package/dist/services/LighterNotificationEnrollmentService.js +102 -0
- package/dist/services/LighterNotificationEnrollmentService.js.map +1 -0
- package/dist/services/MarketDataService.d.ts +15 -1
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +43 -1
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +139 -0
- package/dist/services/StreamChannelManager.d.ts.map +1 -0
- package/dist/services/StreamChannelManager.js +475 -0
- package/dist/services/StreamChannelManager.js.map +1 -0
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +7 -0
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/TradingService.d.ts +2 -0
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +11 -3
- package/dist/services/TradingService.js.map +1 -1
- package/dist/services/agentSigner.d.ts +8 -0
- package/dist/services/agentSigner.d.ts.map +1 -1
- package/dist/services/agentSigner.js +13 -0
- package/dist/services/agentSigner.js.map +1 -1
- package/dist/services/getOptionalBearerToken.d.ts +12 -0
- package/dist/services/getOptionalBearerToken.d.ts.map +1 -0
- package/dist/services/getOptionalBearerToken.js +22 -0
- package/dist/services/getOptionalBearerToken.js.map +1 -0
- package/dist/types/hyperliquid-types.d.ts +9 -1
- package/dist/types/hyperliquid-types.d.ts.map +1 -1
- package/dist/types/hyperliquid-types.js +10 -0
- package/dist/types/hyperliquid-types.js.map +1 -1
- package/dist/types/index.d.ts +445 -14
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +17 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -1
- package/dist/utils/accountAggregation.js +21 -5
- package/dist/utils/accountAggregation.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +31 -10
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +68 -28
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +17 -4
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +23 -7
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +17 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +264 -29
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +4 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +46 -9
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/lighterClientOrderTag.d.ts +23 -0
- package/dist/utils/lighterClientOrderTag.d.ts.map +1 -0
- package/dist/utils/lighterClientOrderTag.js +43 -0
- package/dist/utils/lighterClientOrderTag.js.map +1 -0
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +8 -0
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +1 -2
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +7 -17
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +35 -5
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +62 -6
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
- package/dist/utils/perpsDiskPersistence.js +10 -0
- package/dist/utils/perpsDiskPersistence.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +31 -0
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +26 -0
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/dist/utils/sortMarkets.d.ts +13 -5
- package/dist/utils/sortMarkets.d.ts.map +1 -1
- package/dist/utils/sortMarkets.js +60 -38
- package/dist/utils/sortMarkets.js.map +1 -1
- package/docs/architecture.md +70 -38
- package/docs/client-contract.md +42 -17
- package/docs/contracts/events.md +34 -30
- package/docs/formatting.md +2 -0
- package/docs/venues/lighter/capabilities.md +18 -15
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidPositionPreview.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidPositionPreview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAWvE,2EAA2E;AAC3E,MAAM,YAAY,GAAG,KAAK,CAAC;AAE3B;;;;;;GAMG;AACH,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAE3C;;;GAGG;AACH,MAAM,gCAAgC,GAAG,IAAI,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,iCAAiC,GAAuC;IAC5E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAAK;CACf,CAAC;AAEF;;;;;GAKG;AACH,MAAM,sBAAsB,GAGxB;IACF,cAAc,EAAE,KAAK;IACrB,OAAO,EAAE,IAAI;CACd,CAAC;AAyEF,MAAM,WAAW,GAAG,GAAyB,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;AAEvE,MAAM,SAAS,GAAG,CAAC,KAAa,EAAwB,EAAE,CAAC,CAAC;IAC1D,SAAS,EAAE,I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\n PerpsProviderType,\n Position,\n PositionModifyPreviewCurrent,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n PositionPreviewValue,\n} from '../types/index.js';\n\n/** Token-size comparison tolerance (floating-point / szDecimals noise). */\nconst SIZE_EPSILON = 1e-10;\n\n/**\n * HyperLiquid documents margin-table IDs below 50 as a single tier whose max\n * leverage equals the table id. Multi-tier tables need the `meta.marginTables`\n * entry; without it liquidation is withheld.\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margin-and-pnl\n */\nconst SINGLE_TIER_MARGIN_TABLE_ID_MAX = 50;\n\n/**\n * Share of notional held back for the mark moving before the venue processes\n * a margin removal, as Mobile's `MARGIN_REMOVAL_PRICE_MOVE_BUFFER`.\n */\nconst MARGIN_REMOVAL_PRICE_MOVE_BUFFER = 0.01;\n\n/**\n * Whether {@link estimateIsolatedLeverageChange} models a provider's isolated\n * positions. Hyperliquid's isolated `marginUsed` is the position's\n * collateral; Lighter's is the margin the position requires, so its result is\n * unknown.\n */\nconst ISOLATED_LEVERAGE_CHANGE_MODELLED: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Whether margin may leave an open isolated position, by the market's\n * Hyperliquid `marginMode`. `strictIsolated` prohibits it; `noCross` only\n * rules out cross margin. A market with neither `marginMode` nor\n * `onlyIsolated` has no restriction.\n */\nconst MARGIN_REMOVAL_ALLOWED: Record<\n NonNullable<MarketInfo['marginMode']>,\n boolean\n> = {\n strictIsolated: false,\n noCross: true,\n};\n\nexport type HyperLiquidMarginTier = {\n /** Inclusive notional lower bound in USD. */\n lowerBound: number;\n maxLeverage: number;\n};\n\nexport type PreviewHyperLiquidIsolatedPositionModifyParams =\n PositionModifyPreviewParams & {\n /**\n * Maintenance tiers for the asset, lowest notional first. `null` or empty\n * withholds liquidation while still returning margin when it can be known.\n */\n marginTiers?: HyperLiquidMarginTier[] | null;\n };\n\ntype MaintenanceScheduleTier = {\n lowerBound: number;\n upperBound: number;\n maxLeverage: number;\n maintenanceMarginRate: number;\n maintenanceDeduction: number;\n};\n\n/**\n * Inputs to {@link estimateIsolatedLeverageChange}.\n */\nexport type IsolatedLeverageChangeParams = {\n /** The open position; a `Position` can be passed as-is. */\n position: Pick<Position, 'size' | 'marginUsed' | 'positionValue'> & {\n leverage: Pick<Position['leverage'], 'type' | 'value'>;\n };\n /**\n * Provider holding the position. Only Hyperliquid isolated positions are\n * modelled; others return undefined.\n */\n providerId: PerpsProviderType;\n /**\n * The position's market, whose `marginMode` says whether margin may leave\n * it. A `MarketInfo` from `getMarkets` can be passed as-is. Undefined while\n * the market is unknown, which makes every figure undefined. So does\n * `onlyIsolated` without `marginMode`: Hyperliquid sends both, and the\n * restriction is lost where `marginMode` was dropped.\n */\n market: Pick<MarketInfo, 'marginMode' | 'onlyIsolated'> | undefined;\n /** Leverage the position moves to, at least 1. Undefined until chosen. */\n leverage: number | undefined;\n /**\n * Margin tiers for the asset, as {@link resolveHyperLiquidMarginTiers}\n * returns. The tier the position's notional is in caps `leverage`; tiers\n * that do not cover the notional make every figure undefined. Without\n * tiers the cap is not checked and the liquidation price is undefined.\n */\n marginTiers?: HyperLiquidMarginTier[] | null;\n};\n\n/**\n * An isolated position after a leverage change with no size change.\n */\nexport type IsolatedLeverageChange = {\n /**\n * Margin the change frees: the drop in initial margin, notional / current\n * leverage less notional / new leverage, limited to what may leave the\n * position. 0 unless leverage rises, and 0 on a strict isolated market.\n */\n removableMargin: number | undefined;\n /** Margin afterwards, once `removableMargin` is removed. */\n margin: number | undefined;\n /** Liquidation price at `margin`. */\n liquidationPrice: number | undefined;\n};\n\nconst unavailable = (): PositionPreviewValue => ({ available: false });\n\nconst available = (value: number): PositionPreviewValue => ({\n available: true,\n value,\n});\n\nconst parseFiniteNumber = (value: string | null | undefined): number =>\n Number.parseFloat(value ?? '');\n\nconst isPositiveFinite = (value: number | undefined): value is number =>\n value !== undefined && Number.isFinite(value) && value > 0;\n\nconst isNonNegativeFinite = (value: number | undefined): value is number =>\n value !== undefined && Number.isFinite(value) && value >= 0;\n\nconst currentFromPosition = (params: {\n currentMargin: number;\n currentLiquidationPrice: number;\n}): PositionModifyPreviewCurrent => ({\n margin: isNonNegativeFinite(params.currentMargin)\n ? available(params.currentMargin)\n : unavailable(),\n liquidationPrice: isPositiveFinite(params.currentLiquidationPrice)\n ? available(params.currentLiquidationPrice)\n : unavailable(),\n});\n\n/**\n * Resolves the HyperLiquid margin table into preview tiers.\n *\n * Table IDs below 50 are single-tier. IDs at or above 50 require the matching\n * `marginTables` row; missing data returns `null` so liquidation is withheld.\n * An unknown table id (asset missing from `meta.universe`) also returns `null`\n * instead of inventing a single tier from max leverage.\n *\n * @param params - Margin table id, asset max leverage, and optional tables.\n * @param params.marginTableId - HyperLiquid margin table id from `meta.universe`.\n * @param params.maxLeverage - Asset max leverage used for single-tier tables.\n * @param params.marginTables - `meta.marginTables` rows; required for table ids ≥ 50.\n * @returns Tiers for liquidation, or `null` when the table identity is unknown.\n */\nexport function resolveHyperLiquidMarginTiers(params: {\n marginTableId?: number;\n maxLeverage?: number;\n marginTables?:\n | [number, { marginTiers: { lowerBound: string; maxLeverage: number }[] }][]\n | null;\n}): HyperLiquidMarginTier[] | null {\n const { marginTableId, maxLeverage, marginTables } = params;\n\n if (typeof marginTableId !== 'number' || !Number.isFinite(marginTableId)) {\n return null;\n }\n\n if (marginTableId >= SINGLE_TIER_MARGIN_TABLE_ID_MAX) {\n const table = marginTables?.find(([id]) => id === marginTableId)?.[1];\n const tiers = table?.marginTiers\n ?.map((tier) => ({\n lowerBound: Number.parseFloat(tier.lowerBound),\n maxLeverage: tier.maxLeverage,\n }))\n .filter(\n (tier) =>\n Number.isFinite(tier.lowerBound) &&\n tier.lowerBound >= 0 &&\n isPositiveFinite(tier.maxLeverage),\n );\n return tiers && tiers.length > 0 ? tiers : null;\n }\n\n if (marginTableId <= 0) {\n return null;\n }\n\n const tierMaxLeverage =\n typeof maxLeverage === 'number' && isPositiveFinite(maxLeverage)\n ? maxLeverage\n : marginTableId;\n if (!isPositiveFinite(tierMaxLeverage)) {\n return null;\n }\n\n return [{ lowerBound: 0, maxLeverage: tierMaxLeverage }];\n}\n\n/**\n * Builds the continuous maintenance-margin schedule from HyperLiquid tiers.\n *\n * `maintenance_margin = notional * mmr - deduction`, with\n * `mmr = 1 / (2 * tierMaxLeverage)` and deduction chosen so the function is\n * continuous across tier boundaries.\n *\n * @param tiers - Notional lower bounds and per-tier max leverage.\n * @returns Sorted schedule used to pick the tier at liquidation notional.\n */\nexport function buildMaintenanceSchedule(\n tiers: HyperLiquidMarginTier[],\n): MaintenanceScheduleTier[] {\n const sorted = [...tiers]\n .filter(\n (tier) =>\n Number.isFinite(tier.lowerBound) &&\n tier.lowerBound >= 0 &&\n isPositiveFinite(tier.maxLeverage),\n )\n .sort((left, right) => left.lowerBound - right.lowerBound);\n\n const schedule: MaintenanceScheduleTier[] = [];\n let deduction = 0;\n let previousMmr = 0;\n\n for (let index = 0; index < sorted.length; index++) {\n const tier = sorted[index];\n const maintenanceMarginRate = 1 / (2 * tier.maxLeverage);\n if (index > 0) {\n deduction += tier.lowerBound * (maintenanceMarginRate - previousMmr);\n }\n schedule.push({\n lowerBound: tier.lowerBound,\n upperBound:\n index + 1 < sorted.length ? sorted[index + 1].lowerBound : Infinity,\n maxLeverage: tier.maxLeverage,\n maintenanceMarginRate,\n maintenanceDeduction: deduction,\n });\n previousMmr = maintenanceMarginRate;\n }\n\n return schedule;\n}\n\n/**\n * Isolated liquidation from mark, margin, size, and a maintenance tier.\n *\n * HyperLiquid liquidations use mark price, not average entry. Isolated\n * `marginUsed` is mark-based equity (includes unrealized PnL), so the\n * closed form must use the same reference:\n *\n * Long: `(mark - margin/size - deduction/size) / (1 - mmr)`\n * Short: `(mark + margin/size + deduction/size) / (1 + mmr)`\n *\n * @param params - Position geometry plus the tier's mmr and deduction.\n * @param params.isLong - Whether the remaining position is long.\n * @param params.markPrice - Projected mark after the proposed fill.\n * @param params.margin - Isolated margin after the proposed fill.\n * @param params.positionSize - Absolute remaining size in token units.\n * @param params.maintenanceMarginRate - `1 / (2 * tierMaxLeverage)` for the tier.\n * @param params.maintenanceDeduction - Continuity deduction at this tier.\n * @returns Liquidation price, or `null` when the inputs cannot produce one.\n */\nexport function estimateIsolatedLiquidationPrice(params: {\n isLong: boolean;\n markPrice: number;\n margin: number;\n positionSize: number;\n maintenanceMarginRate: number;\n maintenanceDeduction?: number;\n}): number | null {\n const {\n isLong,\n markPrice,\n margin,\n positionSize,\n maintenanceMarginRate,\n maintenanceDeduction = 0,\n } = params;\n\n if (\n !isPositiveFinite(markPrice) ||\n !isPositiveFinite(margin) ||\n !isPositiveFinite(positionSize) ||\n !Number.isFinite(maintenanceMarginRate) ||\n maintenanceMarginRate < 0 ||\n !Number.isFinite(maintenanceDeduction)\n ) {\n return null;\n }\n\n const direction = isLong ? -1 : 1;\n const side = isLong ? 1 : -1;\n const adjustmentFactor = 1 - maintenanceMarginRate * side;\n if (Math.abs(adjustmentFactor) < 0.0001) {\n return null;\n }\n\n const liquidationPrice =\n (markPrice +\n direction * (margin / positionSize) +\n direction * (maintenanceDeduction / positionSize)) /\n adjustmentFactor;\n\n if (!isPositiveFinite(liquidationPrice)) {\n return null;\n }\n\n return liquidationPrice;\n}\n\n/**\n * Picks the maintenance tier whose notional range contains the liquidation\n * notional (`size * liqPrice`), including that tier's deduction.\n *\n * @param params - Resulting geometry and the asset's maintenance schedule.\n * @param params.isLong - Whether the remaining position is long.\n * @param params.markPrice - Projected mark after the proposed fill.\n * @param params.margin - Isolated margin after the proposed fill.\n * @param params.positionSize - Absolute remaining size in token units.\n * @param params.marginTiers - Maintenance tiers, lowest notional first.\n * @returns Liquidation price when a consistent tier exists.\n */\nexport function estimateIsolatedLiquidationPriceAtTier(params: {\n isLong: boolean;\n markPrice: number;\n margin: number;\n positionSize: number;\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n}): number | null {\n const schedule = buildMaintenanceSchedule(params.marginTiers ?? []);\n if (schedule.length === 0) {\n return null;\n }\n\n for (const tier of schedule) {\n const liquidationPrice = estimateIsolatedLiquidationPrice({\n isLong: params.isLong,\n markPrice: params.markPrice,\n margin: params.margin,\n positionSize: params.positionSize,\n maintenanceMarginRate: tier.maintenanceMarginRate,\n maintenanceDeduction: tier.maintenanceDeduction,\n });\n if (liquidationPrice === null) {\n continue;\n }\n const notionalAtLiquidation = params.positionSize * liquidationPrice;\n if (\n notionalAtLiquidation >= tier.lowerBound &&\n notionalAtLiquidation < tier.upperBound\n ) {\n return liquidationPrice;\n }\n }\n\n return null;\n}\n\n/** A cross-margin position for {@link estimateCrossMaintenanceMargin}. */\nexport type CrossMarginPosition = {\n /** Position value at mark in USD; the sign is ignored. */\n notional: number;\n /** Maintenance tiers, as {@link resolveHyperLiquidMarginTiers} returns. */\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n};\n\n/**\n * Picks the maintenance tier whose notional range contains `notional`.\n *\n * @param schedule - Schedule from {@link buildMaintenanceSchedule}.\n * @param notional - Non-negative position value in USD.\n * @returns The tier, or undefined when no tier covers the notional.\n */\nconst findMaintenanceTier = (\n schedule: MaintenanceScheduleTier[],\n notional: number,\n): MaintenanceScheduleTier | undefined =>\n schedule.find(\n (tier) => notional >= tier.lowerBound && notional < tier.upperBound,\n );\n\n/**\n * Maintenance margin a cross account must hold for its cross positions:\n * the sum of `notional * mmr - deduction` at each position's tier. Below this\n * account value, HyperLiquid liquidates the cross positions.\n *\n * @param positions - Every cross position on the account.\n * @returns Maintenance margin in USD, or `null` when a position's notional\n * or tiers are unknown.\n */\nexport function estimateCrossMaintenanceMargin(\n positions: readonly CrossMarginPosition[],\n): number | null {\n let maintenanceMargin = 0;\n for (const position of positions) {\n const notional = Math.abs(position.notional);\n const tier = Number.isFinite(notional)\n ? findMaintenanceTier(\n buildMaintenanceSchedule(position.marginTiers ?? []),\n notional,\n )\n : undefined;\n if (!tier) {\n return null;\n }\n maintenanceMargin +=\n notional * tier.maintenanceMarginRate - tier.maintenanceDeduction;\n }\n return maintenanceMargin;\n}\n\n/**\n * Cross-margin liquidation price of one position, holding the account's\n * other positions at their current value: the price at which account value\n * falls to the maintenance margin. Within one tier this is HyperLiquid's\n * documented `mark - side * (accountValue - maintenanceMargin) / size /\n * (1 - mmr * side)`; the tier the position's notional reaches at that price\n * is used when it differs from the current one.\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/liquidations\n * @param params - Position geometry and the cross account's figures.\n * @param params.isLong - Whether the position is long.\n * @param params.markPrice - Current mark price.\n * @param params.positionSize - Absolute position size in base units.\n * @param params.accountValue - Cross account value, unrealized PnL included.\n * @param params.maintenanceMargin - Maintenance margin of every cross\n * position including this one, as {@link estimateCrossMaintenanceMargin}.\n * @param params.marginTiers - This market's maintenance tiers.\n * @returns Liquidation price, or `null` when the inputs cannot produce a\n * positive one (a long with enough collateral to never be liquidated, or\n * unknown inputs).\n */\nexport function estimateCrossLiquidationPrice(params: {\n isLong: boolean;\n markPrice: number;\n positionSize: number;\n accountValue: number;\n maintenanceMargin: number;\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n}): number | null {\n const { isLong, markPrice, positionSize, accountValue, maintenanceMargin } =\n params;\n if (\n !isPositiveFinite(markPrice) ||\n !isPositiveFinite(positionSize) ||\n !Number.isFinite(accountValue) ||\n !isNonNegativeFinite(maintenanceMargin)\n ) {\n return null;\n }\n const schedule = buildMaintenanceSchedule(params.marginTiers ?? []);\n const currentTier = findMaintenanceTier(schedule, positionSize * markPrice);\n if (!currentTier) {\n return null;\n }\n\n const side = isLong ? 1 : -1;\n for (const tier of schedule) {\n const denominator = positionSize * (side - tier.maintenanceMarginRate);\n if (Math.abs(denominator) < Number.EPSILON) {\n continue;\n }\n const liquidationPrice =\n (maintenanceMargin -\n accountValue +\n currentTier.maintenanceDeduction -\n tier.maintenanceDeduction +\n positionSize * markPrice * (side - currentTier.maintenanceMarginRate)) /\n denominator;\n if (!isPositiveFinite(liquidationPrice)) {\n continue;\n }\n const notionalAtLiquidation = positionSize * liquidationPrice;\n if (\n notionalAtLiquidation >= tier.lowerBound &&\n notionalAtLiquidation < tier.upperBound\n ) {\n return liquidationPrice;\n }\n }\n return null;\n}\n\n/**\n * Whether margin may leave an open isolated position on a market.\n *\n * @param market - The market, or undefined when unknown.\n * @returns Whether removal is allowed, or undefined when the market or its\n * margin mode is unknown, including an isolated-only market without\n * `marginMode`, which may be strict isolated or `noCross`.\n */\nconst isMarginRemovalAllowed = (\n market: Pick<MarketInfo, 'marginMode' | 'onlyIsolated'> | undefined,\n): boolean | undefined => {\n if (market === undefined) {\n return undefined;\n }\n const { marginMode, onlyIsolated } = market;\n if (marginMode === undefined) {\n return onlyIsolated ? undefined : true;\n }\n return Object.hasOwn(MARGIN_REMOVAL_ALLOWED, marginMode)\n ? MARGIN_REMOVAL_ALLOWED[marginMode]\n : undefined;\n};\n\n/**\n * Isolated margin a Hyperliquid position holds once its leverage changes,\n * before any order. The venue keeps the margin, so a later order margins only\n * its own size at the new leverage. It rejects lowering leverage when the\n * margin is below the initial margin at the new leverage (\"isolated position\n * does not have sufficient margin available to decrease leverage\").\n *\n * @param params - Current margin and notional, and both leverages.\n * @param params.currentMargin - Isolated margin held now.\n * @param params.notional - Position value at mark.\n * @param params.currentLeverage - Leverage now.\n * @param params.leverage - Leverage after the change.\n * @returns Margin after the change, or undefined when the venue rejects it.\n */\nconst isolatedMarginAfterLeverageChange = (params: {\n currentMargin: number;\n notional: number;\n currentLeverage: number;\n leverage: number;\n}): number | undefined =>\n params.leverage < params.currentLeverage - SIZE_EPSILON &&\n params.currentMargin < params.notional / params.leverage - SIZE_EPSILON\n ? undefined\n : params.currentMargin;\n\n/**\n * An isolated position after its leverage changes with no size change: the\n * margin the change frees, and the margin and liquidation price afterwards.\n *\n * Hyperliquid keeps an isolated position's margin when leverage changes. On a\n * rise, the change frees the drop in initial margin, notional / current\n * leverage less notional / new leverage, at mark. Only margin above the\n * transfer requirement may leave: the larger of the initial margin at the new\n * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of\n * notional, plus 1% of notional held back for the mark moving. Margin added\n * on top of the initial margin and unrealized profit stay. `margin` assumes\n * `removableMargin` is removed. A strict isolated market prohibits removing\n * margin from an open position, so nothing is removable there and `margin`\n * is the margin held. A fall frees nothing, and the venue rejects one the\n * margin cannot cover.\n *\n * @param params - The position, provider, market, new leverage and margin\n * tiers.\n * @param params.position - The open position.\n * @param params.providerId - Provider holding the position.\n * @param params.market - The position's market, which says whether margin may\n * leave it.\n * @param params.leverage - Leverage the position moves to.\n * @param params.marginTiers - Margin tiers for the asset, which cap the\n * leverage and set the maintenance rate.\n * @returns The change. Every figure is undefined for cross margin, a provider\n * other than Hyperliquid, an unknown market or margin mode, a leverage above\n * the max leverage of the margin tier the position's notional is in, a fall\n * the margin cannot cover, or a missing or unusable input. Without margin\n * tiers the leverage limit is not checked and the liquidation price is\n * undefined.\n */\nexport function estimateIsolatedLeverageChange({\n position,\n providerId,\n market,\n leverage,\n marginTiers,\n}: IsolatedLeverageChangeParams): IsolatedLeverageChange {\n const signedSize = parseFiniteNumber(position.size);\n const size = Math.abs(signedSize);\n const currentMargin = parseFiniteNumber(position.marginUsed);\n const notional = parseFiniteNumber(position.positionValue);\n const currentLeverage = position.leverage.value;\n const marginRemovalAllowed = isMarginRemovalAllowed(market);\n // The venue caps leverage by the tier the position's notional is in.\n const schedule = buildMaintenanceSchedule(marginTiers ?? []);\n const maxLeverage = marginTiers?.length\n ? schedule.find(\n (tier) => notional >= tier.lowerBound && notional < tier.upperBound,\n )?.maxLeverage\n : Number.POSITIVE_INFINITY;\n const unknown: IsolatedLeverageChange = {\n removableMargin: undefined,\n margin: undefined,\n liquidationPrice: undefined,\n };\n\n if (\n position.leverage.type !== 'isolated' ||\n !Object.hasOwn(ISOLATED_LEVERAGE_CHANGE_MODELLED, providerId) ||\n !ISOLATED_LEVERAGE_CHANGE_MODELLED[providerId] ||\n marginRemovalAllowed === undefined ||\n leverage === undefined ||\n !Number.isFinite(leverage) ||\n leverage < 1 ||\n maxLeverage === undefined ||\n leverage > maxLeverage ||\n currentLeverage === undefined ||\n !Number.isFinite(currentLeverage) ||\n currentLeverage < 1 ||\n !isPositiveFinite(size) ||\n !isPositiveFinite(currentMargin) ||\n !isPositiveFinite(notional)\n ) {\n return unknown;\n }\n\n const heldMargin = isolatedMarginAfterLeverageChange({\n currentMargin,\n notional,\n currentLeverage,\n leverage,\n });\n if (heldMargin === undefined) {\n return unknown;\n }\n const freedInitialMargin = notional / currentLeverage - notional / leverage;\n const transferMarginRequired = Math.max(\n notional / leverage,\n notional * MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer,\n );\n const removableMargin = marginRemovalAllowed\n ? Math.max(\n 0,\n Math.min(\n freedInitialMargin,\n heldMargin -\n transferMarginRequired -\n notional * MARGIN_REMOVAL_PRICE_MOVE_BUFFER,\n ),\n )\n : 0;\n const margin = heldMargin - removableMargin;\n const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({\n isLong: signedSize > 0,\n markPrice: notional / size,\n margin,\n positionSize: size,\n marginTiers,\n });\n\n return {\n removableMargin,\n margin,\n liquidationPrice: liquidationPrice ?? undefined,\n };\n}\n\nconst resultingLeverage = (params: {\n notional: number;\n margin: number | undefined;\n fallback: number;\n}): number => {\n if (params.margin !== undefined && params.margin > 0 && params.notional > 0) {\n return params.notional / params.margin;\n }\n return params.fallback;\n};\n\n/**\n * Projects the isolated position that would remain after a proposed order.\n *\n * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing\n * margin when the selected leverage differs; the order then margins only its\n * own size at the selected leverage. The venue rejects a lower leverage that\n * the existing margin cannot cover, so margin and liquidation are unavailable\n * then. Maintenance tiers apply at the resulting liquidation notional.\n * Liquidation uses the projected mark, not average entry, because isolated\n * `marginUsed` is mark-based equity.\n * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.\n *\n * `price` is the fill or resting-limit price the caller expects. A marketable\n * order should pass its execution price; a limit should pass the limit. The\n * preview does not distinguish order types itself, does not model whether a\n * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.\n * Decrease margin is the remaining share of the isolated collateral after the\n * leverage change; close fees and realized PnL settle to the account, not the\n * leftover margin.\n *\n * @param params - Live isolated position, proposed order, and optional tiers.\n * @returns Discriminated preview; margin and liquidation are independently available.\n */\nexport function previewHyperLiquidIsolatedPositionModify(\n params: PreviewHyperLiquidIsolatedPositionModifyParams,\n): PositionModifyPreviewResult {\n const { position, direction, reduceOnly = false, marginTiers } = params;\n\n if (position.leverage.type === 'cross') {\n return { status: 'unsupported', reason: 'cross_margin' };\n }\n\n const currentSize = Math.abs(parseFiniteNumber(position.size));\n const signedSize = parseFiniteNumber(position.size);\n const currentMargin = parseFiniteNumber(position.marginUsed);\n const currentEntry = parseFiniteNumber(position.entryPrice);\n const currentLiquidationPrice = parseFiniteNumber(position.liquidationPrice);\n const currentLeverage = position.leverage.value;\n const selectedLeverage = params.leverage;\n const orderSize = parseFiniteNumber(params.size);\n const orderPrice = parseFiniteNumber(params.price);\n // An omitted, NaN or negative fee is unknown, never $0: increases and\n // flips then have no resulting margin.\n const feeAmountUsd = isNonNegativeFinite(params.feeAmountUsd)\n ? params.feeAmountUsd\n : undefined;\n\n if (\n !isPositiveFinite(currentSize) ||\n !Number.isFinite(signedSize) ||\n signedSize === 0 ||\n !isNonNegativeFinite(currentMargin) ||\n !isPositiveFinite(currentEntry) ||\n !isPositiveFinite(selectedLeverage) ||\n !isPositiveFinite(currentLeverage)\n ) {\n return { status: 'none' };\n }\n\n const openDirection: 'long' | 'short' = signedSize > 0 ? 'long' : 'short';\n const currentSnapshot = currentFromPosition({\n currentMargin,\n currentLiquidationPrice,\n });\n\n if (!isPositiveFinite(orderSize)) {\n return { status: 'none' };\n }\n\n const positionValue = parseFiniteNumber(position.positionValue);\n const currentNotional = isPositiveFinite(positionValue)\n ? positionValue\n : currentSize * currentEntry;\n\n const existingMarginAfterLeverage = isolatedMarginAfterLeverageChange({\n currentMargin,\n notional: currentNotional,\n currentLeverage,\n leverage: selectedLeverage,\n });\n\n const withResultingLiquidation = (preview: {\n kind: 'increase' | 'decrease' | 'flip';\n resultingDirection: 'long' | 'short';\n resultingSize: number;\n resultingEntryPrice: number;\n resultingMarkPrice: number;\n resultingNotional: number;\n newMargin: number | undefined;\n }): PositionModifyPreviewResult => {\n const liquidationPrice =\n preview.newMargin === undefined\n ? null\n : estimateIsolatedLiquidationPriceAtTier({\n isLong: preview.resultingDirection === 'long',\n markPrice: preview.resultingMarkPrice,\n margin: preview.newMargin,\n positionSize: preview.resultingSize,\n marginTiers,\n });\n\n return {\n status: 'open',\n kind: preview.kind,\n current: currentSnapshot,\n resulting: {\n direction: preview.resultingDirection,\n size: preview.resultingSize,\n entryPrice: preview.resultingEntryPrice,\n leverage: resultingLeverage({\n notional: preview.resultingNotional,\n margin: preview.newMargin,\n fallback: selectedLeverage,\n }),\n margin:\n preview.newMargin === undefined\n ? unavailable()\n : available(preview.newMargin),\n liquidationPrice:\n liquidationPrice === null\n ? unavailable()\n : available(liquidationPrice),\n },\n };\n };\n\n const isSameDirection = openDirection === direction;\n const fillPrice = isPositiveFinite(orderPrice) ? orderPrice : null;\n\n // Reduce-only in the position's own direction cannot add size and does not\n // close it, so there is no resulting position to project.\n if (isSameDirection && reduceOnly) {\n return { status: 'none' };\n }\n\n if (isSameDirection) {\n if (fillPrice === null) {\n return { status: 'none' };\n }\n const orderMargin = (orderSize * fillPrice) / selectedLeverage;\n const resultingSize = currentSize + orderSize;\n const resultingEntryPrice =\n (currentSize * currentEntry + orderSize * fillPrice) / resultingSize;\n const newMargin =\n existingMarginAfterLeverage === undefined || feeAmountUsd === undefined\n ? undefined\n : Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);\n\n return withResultingLiquidation({\n kind: 'increase',\n resultingDirection: openDirection,\n resultingSize,\n resultingEntryPrice,\n resultingMarkPrice: fillPrice,\n resultingNotional: resultingSize * fillPrice,\n newMargin,\n });\n }\n\n if (orderSize + SIZE_EPSILON < currentSize) {\n const remainingRatio = (currentSize - orderSize) / currentSize;\n const resultingSize = currentSize - orderSize;\n const newMargin =\n existingMarginAfterLeverage === undefined\n ? undefined\n : Math.max(0, existingMarginAfterLeverage * remainingRatio);\n const currentMarkPrice = currentNotional / currentSize;\n const resultingMarkPrice = fillPrice ?? currentMarkPrice;\n\n return withResultingLiquidation({\n kind: 'decrease',\n resultingDirection: openDirection,\n resultingSize,\n resultingEntryPrice: currentEntry,\n resultingMarkPrice,\n resultingNotional: resultingSize * resultingMarkPrice,\n newMargin,\n });\n }\n\n const leftover = orderSize - currentSize;\n if (leftover > SIZE_EPSILON && !reduceOnly) {\n if (fillPrice === null) {\n return { status: 'none' };\n }\n const orderMargin = (orderSize * fillPrice) / selectedLeverage;\n const leftoverRatio = leftover / orderSize;\n const leftoverMargin =\n existingMarginAfterLeverage === undefined || feeAmountUsd === undefined\n ? undefined\n : Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);\n\n return withResultingLiquidation({\n kind: 'flip',\n resultingDirection: direction,\n resultingSize: leftover,\n resultingEntryPrice: fillPrice,\n resultingMarkPrice: fillPrice,\n resultingNotional: leftover * fillPrice,\n newMargin: leftoverMargin,\n });\n }\n\n return {\n status: 'full_close',\n current: currentSnapshot,\n resultingDirection: openDirection,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hyperLiquidPositionPreview.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidPositionPreview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,yCAAyC,CAAC;AAYvF,2EAA2E;AAC3E,MAAM,YAAY,GAAG,KAAK,CAAC;AAE3B;;;;;;GAMG;AACH,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAE3C;;;GAGG;AACH,MAAM,gCAAgC,GAAG,IAAI,CAAC;AAE9C;;;;;GAKG;A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AU,GAAG,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAC5B,CAAC;IACD,MAAM,UAAU,GAAG,qCAAqC,CAAC,MAAM,CAAC,CAAC;IACjE,IAAI,UAAU,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;QACjC,OAAO,UAAU,CAAC;IACpB,CAAC;IACD,MAAM,OAAO,GAAG,mBAAmB,CAAC;QAClC,aAAa,EAAE,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC5D,uBAAuB,EAAE,iBAAiB,CACxC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CACjC;KACF,CAAC,CAAC;IACH,IAAI,UAAU,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;QACvC,OAAO,EAAE,GAAG,UAAU,EAAE,OAAO,EAAE,CAAC;IACpC,CAAC;IACD,OAAO;QACL,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,OAAO;QACP,SAAS,EAAE;YACT,SAAS,EAAE,UAAU,CAAC,SAAS;YAC/B,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,UAAU,EAAE,UAAU,CAAC,UAAU;YACjC,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,MAAM,EAAE,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC;YACpC,gBAAgB,EAAE,uBAAuB,CAAC,UAAU,CAAC,WAAW,CAAC;SAClE;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { MARGIN_ADJUSTMENT_CONFIG } from '../constants/perpsConfig.js';\nimport { calculateHip3RebalanceAmount } from '../internal/hyperLiquidHip3Rebalance.js';\nimport type {\n MarketInfo,\n PerpsProviderType,\n Position,\n PositionModifyPreviewCurrent,\n PositionModifyPreviewKind,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n PositionPreviewValue,\n} from '../types/index.js';\n\n/** Token-size comparison tolerance (floating-point / szDecimals noise). */\nconst SIZE_EPSILON = 1e-10;\n\n/**\n * HyperLiquid documents margin-table IDs below 50 as a single tier whose max\n * leverage equals the table id. Multi-tier tables need the `meta.marginTables`\n * entry; without it liquidation is withheld.\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margin-and-pnl\n */\nconst SINGLE_TIER_MARGIN_TABLE_ID_MAX = 50;\n\n/**\n * Share of notional held back for the mark moving before the venue processes\n * a margin removal, as Mobile's `MARGIN_REMOVAL_PRICE_MOVE_BUFFER`.\n */\nconst MARGIN_REMOVAL_PRICE_MOVE_BUFFER = 0.01;\n\n/**\n * Whether {@link estimateIsolatedLeverageChange} models a provider's isolated\n * positions. Hyperliquid's isolated `marginUsed` is the position's\n * collateral; Lighter's is the margin the position requires, so its result is\n * unknown.\n */\nconst ISOLATED_LEVERAGE_CHANGE_MODELLED: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Whether margin may leave an open isolated position, by the market's\n * Hyperliquid `marginMode`. `strictIsolated` prohibits it; `noCross` only\n * rules out cross margin. A market with neither `marginMode` nor\n * `onlyIsolated` has no restriction.\n */\nconst MARGIN_REMOVAL_ALLOWED: Record<\n NonNullable<MarketInfo['marginMode']>,\n boolean\n> = {\n strictIsolated: false,\n noCross: true,\n};\n\nexport type HyperLiquidMarginTier = {\n /** Inclusive notional lower bound in USD. */\n lowerBound: number;\n maxLeverage: number;\n};\n\nexport type PreviewHyperLiquidIsolatedPositionModifyParams =\n PositionModifyPreviewParams & {\n /**\n * Maintenance tiers for the asset, lowest notional first. `null` or empty\n * withholds liquidation while still returning margin when it can be known.\n */\n marginTiers?: HyperLiquidMarginTier[] | null;\n };\n\ntype MaintenanceScheduleTier = {\n lowerBound: number;\n upperBound: number;\n maxLeverage: number;\n maintenanceMarginRate: number;\n maintenanceDeduction: number;\n};\n\n/**\n * Inputs to {@link estimateIsolatedLeverageChange}.\n */\nexport type IsolatedLeverageChangeParams = {\n /** The open position; a `Position` can be passed as-is. */\n position: Pick<Position, 'size' | 'marginUsed' | 'positionValue'> & {\n leverage: Pick<Position['leverage'], 'type' | 'value'>;\n };\n /**\n * Provider holding the position. Only Hyperliquid isolated positions are\n * modelled; others return undefined.\n */\n providerId: PerpsProviderType;\n /**\n * The position's market, whose `marginMode` says whether margin may leave\n * it. A `MarketInfo` from `getMarkets` can be passed as-is. Undefined while\n * the market is unknown, which makes every figure undefined. So does\n * `onlyIsolated` without `marginMode`: Hyperliquid sends both, and the\n * restriction is lost where `marginMode` was dropped.\n */\n market: Pick<MarketInfo, 'marginMode' | 'onlyIsolated'> | undefined;\n /** Leverage the position moves to, at least 1. Undefined until chosen. */\n leverage: number | undefined;\n /**\n * Margin tiers for the asset, as {@link resolveHyperLiquidMarginTiers}\n * returns. The tier the position's notional is in caps `leverage`; tiers\n * that do not cover the notional make every figure undefined. Without\n * tiers the cap is not checked and the liquidation price is undefined.\n */\n marginTiers?: HyperLiquidMarginTier[] | null;\n};\n\n/**\n * An isolated position after a leverage change with no size change.\n */\nexport type IsolatedLeverageChange = {\n /**\n * Margin the change frees: the drop in initial margin, notional / current\n * leverage less notional / new leverage, limited to what may leave the\n * position. 0 unless leverage rises, and 0 on a strict isolated market.\n */\n removableMargin: number | undefined;\n /** Margin afterwards, once `removableMargin` is removed. */\n margin: number | undefined;\n /** Liquidation price at `margin`. */\n liquidationPrice: number | undefined;\n};\n\nconst unavailable = (): PositionPreviewValue => ({ available: false });\n\nconst available = (value: number): PositionPreviewValue => ({\n available: true,\n value,\n});\n\nconst parseFiniteNumber = (value: string | null | undefined): number =>\n Number.parseFloat(value ?? '');\n\nconst isPositiveFinite = (value: number | undefined): value is number =>\n value !== undefined && Number.isFinite(value) && value > 0;\n\nconst isNonNegativeFinite = (value: number | undefined): value is number =>\n value !== undefined && Number.isFinite(value) && value >= 0;\n\nconst currentFromPosition = (params: {\n currentMargin: number;\n currentLiquidationPrice: number;\n}): PositionModifyPreviewCurrent => ({\n margin: isNonNegativeFinite(params.currentMargin)\n ? available(params.currentMargin)\n : unavailable(),\n liquidationPrice: isPositiveFinite(params.currentLiquidationPrice)\n ? available(params.currentLiquidationPrice)\n : unavailable(),\n});\n\n/**\n * Resolves the HyperLiquid margin table into preview tiers.\n *\n * Table IDs below 50 are single-tier. IDs at or above 50 require the matching\n * `marginTables` row; missing data returns `null` so liquidation is withheld.\n * An unknown table id (asset missing from `meta.universe`) also returns `null`\n * instead of inventing a single tier from max leverage.\n *\n * @param params - Margin table id, asset max leverage, and optional tables.\n * @param params.marginTableId - HyperLiquid margin table id from `meta.universe`.\n * @param params.maxLeverage - Asset max leverage used for single-tier tables.\n * @param params.marginTables - `meta.marginTables` rows; required for table ids ≥ 50.\n * @returns Tiers for liquidation, or `null` when the table identity is unknown.\n */\nexport function resolveHyperLiquidMarginTiers(params: {\n marginTableId?: number;\n maxLeverage?: number;\n marginTables?:\n | [number, { marginTiers: { lowerBound: string; maxLeverage: number }[] }][]\n | null;\n}): HyperLiquidMarginTier[] | null {\n const { marginTableId, maxLeverage, marginTables } = params;\n\n if (typeof marginTableId !== 'number' || !Number.isFinite(marginTableId)) {\n return null;\n }\n\n if (marginTableId >= SINGLE_TIER_MARGIN_TABLE_ID_MAX) {\n const table = marginTables?.find(([id]) => id === marginTableId)?.[1];\n const tiers = table?.marginTiers\n ?.map((tier) => ({\n lowerBound: Number.parseFloat(tier.lowerBound),\n maxLeverage: tier.maxLeverage,\n }))\n .filter(\n (tier) =>\n Number.isFinite(tier.lowerBound) &&\n tier.lowerBound >= 0 &&\n isPositiveFinite(tier.maxLeverage),\n );\n return tiers && tiers.length > 0 ? tiers : null;\n }\n\n if (marginTableId <= 0) {\n return null;\n }\n\n const tierMaxLeverage =\n typeof maxLeverage === 'number' && isPositiveFinite(maxLeverage)\n ? maxLeverage\n : marginTableId;\n if (!isPositiveFinite(tierMaxLeverage)) {\n return null;\n }\n\n return [{ lowerBound: 0, maxLeverage: tierMaxLeverage }];\n}\n\n/**\n * Builds the continuous maintenance-margin schedule from HyperLiquid tiers.\n *\n * `maintenance_margin = notional * mmr - deduction`, with\n * `mmr = 1 / (2 * tierMaxLeverage)` and deduction chosen so the function is\n * continuous across tier boundaries.\n *\n * @param tiers - Notional lower bounds and per-tier max leverage.\n * @returns Sorted schedule used to pick the tier at liquidation notional.\n */\nexport function buildMaintenanceSchedule(\n tiers: HyperLiquidMarginTier[],\n): MaintenanceScheduleTier[] {\n const sorted = [...tiers]\n .filter(\n (tier) =>\n Number.isFinite(tier.lowerBound) &&\n tier.lowerBound >= 0 &&\n isPositiveFinite(tier.maxLeverage),\n )\n .sort((left, right) => left.lowerBound - right.lowerBound);\n\n const schedule: MaintenanceScheduleTier[] = [];\n let deduction = 0;\n let previousMmr = 0;\n\n for (let index = 0; index < sorted.length; index++) {\n const tier = sorted[index];\n const maintenanceMarginRate = 1 / (2 * tier.maxLeverage);\n if (index > 0) {\n deduction += tier.lowerBound * (maintenanceMarginRate - previousMmr);\n }\n schedule.push({\n lowerBound: tier.lowerBound,\n upperBound:\n index + 1 < sorted.length ? sorted[index + 1].lowerBound : Infinity,\n maxLeverage: tier.maxLeverage,\n maintenanceMarginRate,\n maintenanceDeduction: deduction,\n });\n previousMmr = maintenanceMarginRate;\n }\n\n return schedule;\n}\n\n/**\n * Isolated liquidation from mark, margin, size, and a maintenance tier.\n *\n * HyperLiquid liquidations use mark price, not average entry. Isolated\n * `marginUsed` is mark-based equity (includes unrealized PnL), so the\n * closed form must use the same reference:\n *\n * Long: `(mark - margin/size - deduction/size) / (1 - mmr)`\n * Short: `(mark + margin/size + deduction/size) / (1 + mmr)`\n *\n * @param params - Position geometry plus the tier's mmr and deduction.\n * @param params.isLong - Whether the remaining position is long.\n * @param params.markPrice - Projected mark after the proposed fill.\n * @param params.margin - Isolated margin after the proposed fill.\n * @param params.positionSize - Absolute remaining size in token units.\n * @param params.maintenanceMarginRate - `1 / (2 * tierMaxLeverage)` for the tier.\n * @param params.maintenanceDeduction - Continuity deduction at this tier.\n * @returns Liquidation price, or `null` when the inputs cannot produce one.\n */\nexport function estimateIsolatedLiquidationPrice(params: {\n isLong: boolean;\n markPrice: number;\n margin: number;\n positionSize: number;\n maintenanceMarginRate: number;\n maintenanceDeduction?: number;\n}): number | null {\n const {\n isLong,\n markPrice,\n margin,\n positionSize,\n maintenanceMarginRate,\n maintenanceDeduction = 0,\n } = params;\n\n if (\n !isPositiveFinite(markPrice) ||\n !isPositiveFinite(margin) ||\n !isPositiveFinite(positionSize) ||\n !Number.isFinite(maintenanceMarginRate) ||\n maintenanceMarginRate < 0 ||\n !Number.isFinite(maintenanceDeduction)\n ) {\n return null;\n }\n\n const direction = isLong ? -1 : 1;\n const side = isLong ? 1 : -1;\n const adjustmentFactor = 1 - maintenanceMarginRate * side;\n if (Math.abs(adjustmentFactor) < 0.0001) {\n return null;\n }\n\n const liquidationPrice =\n (markPrice +\n direction * (margin / positionSize) +\n direction * (maintenanceDeduction / positionSize)) /\n adjustmentFactor;\n\n if (!isPositiveFinite(liquidationPrice)) {\n return null;\n }\n\n return liquidationPrice;\n}\n\n/**\n * Picks the maintenance tier whose notional range contains the liquidation\n * notional (`size * liqPrice`), including that tier's deduction.\n *\n * @param params - Resulting geometry and the asset's maintenance schedule.\n * @param params.isLong - Whether the remaining position is long.\n * @param params.markPrice - Projected mark after the proposed fill.\n * @param params.margin - Isolated margin after the proposed fill.\n * @param params.positionSize - Absolute remaining size in token units.\n * @param params.marginTiers - Maintenance tiers, lowest notional first.\n * @returns Liquidation price when a consistent tier exists.\n */\nexport function estimateIsolatedLiquidationPriceAtTier(params: {\n isLong: boolean;\n markPrice: number;\n margin: number;\n positionSize: number;\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n}): number | null {\n const schedule = buildMaintenanceSchedule(params.marginTiers ?? []);\n if (schedule.length === 0) {\n return null;\n }\n\n for (const tier of schedule) {\n const liquidationPrice = estimateIsolatedLiquidationPrice({\n isLong: params.isLong,\n markPrice: params.markPrice,\n margin: params.margin,\n positionSize: params.positionSize,\n maintenanceMarginRate: tier.maintenanceMarginRate,\n maintenanceDeduction: tier.maintenanceDeduction,\n });\n if (liquidationPrice === null) {\n continue;\n }\n const notionalAtLiquidation = params.positionSize * liquidationPrice;\n if (\n notionalAtLiquidation >= tier.lowerBound &&\n notionalAtLiquidation < tier.upperBound\n ) {\n return liquidationPrice;\n }\n }\n\n return null;\n}\n\n/** A cross-margin position for {@link estimateCrossMaintenanceMargin}. */\nexport type CrossMarginPosition = {\n /** Position value at mark in USD; the sign is ignored. */\n notional: number;\n /** Maintenance tiers, as {@link resolveHyperLiquidMarginTiers} returns. */\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n};\n\n/**\n * Picks the maintenance tier whose notional range contains `notional`.\n *\n * @param schedule - Schedule from {@link buildMaintenanceSchedule}.\n * @param notional - Non-negative position value in USD.\n * @returns The tier, or undefined when no tier covers the notional.\n */\nconst findMaintenanceTier = (\n schedule: MaintenanceScheduleTier[],\n notional: number,\n): MaintenanceScheduleTier | undefined =>\n schedule.find(\n (tier) => notional >= tier.lowerBound && notional < tier.upperBound,\n );\n\n/**\n * Maintenance margin a cross account must hold for its cross positions:\n * the sum of `notional * mmr - deduction` at each position's tier. Below this\n * account value, HyperLiquid liquidates the cross positions.\n *\n * @param positions - Every cross position on the account.\n * @returns Maintenance margin in USD, or `null` when a position's notional\n * or tiers are unknown.\n */\nexport function estimateCrossMaintenanceMargin(\n positions: readonly CrossMarginPosition[],\n): number | null {\n let maintenanceMargin = 0;\n for (const position of positions) {\n const notional = Math.abs(position.notional);\n const tier = Number.isFinite(notional)\n ? findMaintenanceTier(\n buildMaintenanceSchedule(position.marginTiers ?? []),\n notional,\n )\n : undefined;\n if (!tier) {\n return null;\n }\n maintenanceMargin +=\n notional * tier.maintenanceMarginRate - tier.maintenanceDeduction;\n }\n return maintenanceMargin;\n}\n\n/** Inputs to {@link estimateCrossLiquidationPrice}. */\nexport type CrossLiquidationPriceParams = {\n isLong: boolean;\n markPrice: number;\n positionSize: number;\n accountValue: number;\n maintenanceMargin: number;\n marginTiers: HyperLiquidMarginTier[] | null | undefined;\n};\n\n/**\n * A Cross liquidation price, classified: a positive `price`,\n * `covered_by_account` for a long that no positive price liquidates (the\n * collateral covers its loss down to a zero price plus the other positions'\n * maintenance), or `missing_inputs` when the inputs are unknown or produce\n * no price.\n */\nexport type CrossLiquidationClassification =\n | { status: 'price'; price: number }\n | { status: 'covered_by_account' }\n | { status: 'missing_inputs' };\n\nconst missingInputs = { status: 'missing_inputs' } as const;\n\n/**\n * Classifies the Cross liquidation price of one position, holding the\n * account's other positions at their current value: the price at which\n * account value falls to the maintenance margin. Within one tier this is\n * HyperLiquid's documented\n * `mark - side * (accountValue - maintenanceMargin) / size / (1 - mmr * side)`;\n * the tier the position's notional reaches at that price is used when it\n * differs from the current one. The one Cross\n * liquidation formula: {@link estimateCrossLiquidationPrice}, the\n * provider's estimates and the Cross preview all read it.\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/liquidations\n * @param params - Position geometry and the cross account's figures, as\n * {@link estimateCrossLiquidationPrice} takes them.\n * @returns The classified price.\n */\nexport function classifyCrossLiquidationPrice(\n params: CrossLiquidationPriceParams,\n): CrossLiquidationClassification {\n const { isLong, markPrice, positionSize, accountValue, maintenanceMargin } =\n params;\n if (\n !isPositiveFinite(markPrice) ||\n !isPositiveFinite(positionSize) ||\n !Number.isFinite(accountValue) ||\n !isNonNegativeFinite(maintenanceMargin)\n ) {\n return missingInputs;\n }\n const currentMaintenance = estimateCrossMaintenanceMargin([\n { notional: positionSize * markPrice, marginTiers: params.marginTiers },\n ]);\n if (currentMaintenance === null) {\n return missingInputs;\n }\n const otherMaintenance = maintenanceMargin - currentMaintenance;\n const schedule = buildMaintenanceSchedule(params.marginTiers ?? []);\n\n // A long loses at most its notional, and its maintenance falls to 0 with\n // the price. Collateral still above the other positions' maintenance at a\n // zero price leaves no positive liquidation price.\n if (\n isLong &&\n schedule[0].lowerBound === 0 &&\n accountValue - positionSize * markPrice >= otherMaintenance\n ) {\n return { status: 'covered_by_account' };\n }\n\n const side = isLong ? 1 : -1;\n for (const tier of schedule) {\n const denominator = positionSize * (side - tier.maintenanceMarginRate);\n if (Math.abs(denominator) < Number.EPSILON) {\n continue;\n }\n const liquidationPrice =\n (otherMaintenance -\n accountValue +\n side * positionSize * markPrice -\n tier.maintenanceDeduction) /\n denominator;\n if (!isPositiveFinite(liquidationPrice)) {\n continue;\n }\n const notionalAtLiquidation = positionSize * liquidationPrice;\n if (\n notionalAtLiquidation >= tier.lowerBound &&\n notionalAtLiquidation < tier.upperBound\n ) {\n return { status: 'price', price: liquidationPrice };\n }\n }\n return missingInputs;\n}\n\n/**\n * Cross-margin liquidation price of one position, holding the account's\n * other positions at their current value: the price at which account value\n * falls to the maintenance margin. Within one tier this is HyperLiquid's\n * documented `mark - side * (accountValue - maintenanceMargin) / size /\n * (1 - mmr * side)`; the tier the position's notional reaches at that price\n * is used when it differs from the current one.\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/liquidations\n * @param params - Position geometry and the cross account's figures.\n * @param params.isLong - Whether the position is long.\n * @param params.markPrice - Current mark price.\n * @param params.positionSize - Absolute position size in base units.\n * @param params.accountValue - Cross account value, unrealized PnL included.\n * @param params.maintenanceMargin - Maintenance margin of every cross\n * position including this one, as {@link estimateCrossMaintenanceMargin}.\n * @param params.marginTiers - This market's maintenance tiers.\n * @returns Liquidation price, or `null` when the inputs cannot produce a\n * positive one (a long with enough collateral to never be liquidated, or\n * unknown inputs).\n */\nexport function estimateCrossLiquidationPrice(\n params: CrossLiquidationPriceParams,\n): number | null {\n const result = classifyCrossLiquidationPrice(params);\n return result.status === 'price' ? result.price : null;\n}\n\n/**\n * Whether margin may leave an open isolated position on a market.\n *\n * @param market - The market, or undefined when unknown.\n * @returns Whether removal is allowed, or undefined when the market or its\n * margin mode is unknown, including an isolated-only market without\n * `marginMode`, which may be strict isolated or `noCross`.\n */\nexport const isMarginRemovalAllowed = (\n market: Pick<MarketInfo, 'marginMode' | 'onlyIsolated'> | undefined,\n): boolean | undefined => {\n if (market === undefined) {\n return undefined;\n }\n const { marginMode, onlyIsolated } = market;\n if (marginMode === undefined) {\n return onlyIsolated ? undefined : true;\n }\n return Object.hasOwn(MARGIN_REMOVAL_ALLOWED, marginMode)\n ? MARGIN_REMOVAL_ALLOWED[marginMode]\n : undefined;\n};\n\n/**\n * Isolated margin a Hyperliquid position holds once its leverage changes,\n * before any order. The venue keeps the margin, so a later order margins only\n * its own size at the new leverage. It rejects lowering leverage when the\n * margin is below the initial margin at the new leverage (\"isolated position\n * does not have sufficient margin available to decrease leverage\").\n *\n * @param params - Current margin and notional, and both leverages.\n * @param params.currentMargin - Isolated margin held now.\n * @param params.notional - Position value at mark.\n * @param params.currentLeverage - Leverage now.\n * @param params.leverage - Leverage after the change.\n * @returns Margin after the change, or undefined when the venue rejects it.\n */\nconst isolatedMarginAfterLeverageChange = (params: {\n currentMargin: number;\n notional: number;\n currentLeverage: number;\n leverage: number;\n}): number | undefined =>\n params.leverage < params.currentLeverage - SIZE_EPSILON &&\n params.currentMargin < params.notional / params.leverage - SIZE_EPSILON\n ? undefined\n : params.currentMargin;\n\n/**\n * An isolated position after its leverage changes with no size change: the\n * margin the change frees, and the margin and liquidation price afterwards.\n *\n * Hyperliquid keeps an isolated position's margin when leverage changes. On a\n * rise, the change frees the drop in initial margin, notional / current\n * leverage less notional / new leverage, at mark. Only margin above the\n * transfer requirement may leave: the larger of the initial margin at the new\n * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of\n * notional, plus 1% of notional held back for the mark moving. Margin added\n * on top of the initial margin and unrealized profit stay. `margin` assumes\n * `removableMargin` is removed. A strict isolated market prohibits removing\n * margin from an open position, so nothing is removable there and `margin`\n * is the margin held. A fall frees nothing, and the venue rejects one the\n * margin cannot cover.\n *\n * @param params - The position, provider, market, new leverage and margin\n * tiers.\n * @param params.position - The open position.\n * @param params.providerId - Provider holding the position.\n * @param params.market - The position's market, which says whether margin may\n * leave it.\n * @param params.leverage - Leverage the position moves to.\n * @param params.marginTiers - Margin tiers for the asset, which cap the\n * leverage and set the maintenance rate.\n * @returns The change. Every figure is undefined for cross margin, a provider\n * other than Hyperliquid, an unknown market or margin mode, a leverage above\n * the max leverage of the margin tier the position's notional is in, a fall\n * the margin cannot cover, or a missing or unusable input. Without margin\n * tiers the leverage limit is not checked and the liquidation price is\n * undefined.\n */\nexport function estimateIsolatedLeverageChange({\n position,\n providerId,\n market,\n leverage,\n marginTiers,\n}: IsolatedLeverageChangeParams): IsolatedLeverageChange {\n const signedSize = parseFiniteNumber(position.size);\n const size = Math.abs(signedSize);\n const currentMargin = parseFiniteNumber(position.marginUsed);\n const notional = parseFiniteNumber(position.positionValue);\n const currentLeverage = position.leverage.value;\n const marginRemovalAllowed = isMarginRemovalAllowed(market);\n // The venue caps leverage by the tier the position's notional is in.\n const schedule = buildMaintenanceSchedule(marginTiers ?? []);\n const maxLeverage = marginTiers?.length\n ? schedule.find(\n (tier) => notional >= tier.lowerBound && notional < tier.upperBound,\n )?.maxLeverage\n : Number.POSITIVE_INFINITY;\n const unknown: IsolatedLeverageChange = {\n removableMargin: undefined,\n margin: undefined,\n liquidationPrice: undefined,\n };\n\n if (\n position.leverage.type !== 'isolated' ||\n !Object.hasOwn(ISOLATED_LEVERAGE_CHANGE_MODELLED, providerId) ||\n !ISOLATED_LEVERAGE_CHANGE_MODELLED[providerId] ||\n marginRemovalAllowed === undefined ||\n leverage === undefined ||\n !Number.isFinite(leverage) ||\n leverage < 1 ||\n maxLeverage === undefined ||\n leverage > maxLeverage ||\n currentLeverage === undefined ||\n !Number.isFinite(currentLeverage) ||\n currentLeverage < 1 ||\n !isPositiveFinite(size) ||\n !isPositiveFinite(currentMargin) ||\n !isPositiveFinite(notional)\n ) {\n return unknown;\n }\n\n const heldMargin = isolatedMarginAfterLeverageChange({\n currentMargin,\n notional,\n currentLeverage,\n leverage,\n });\n if (heldMargin === undefined) {\n return unknown;\n }\n const freedInitialMargin = notional / currentLeverage - notional / leverage;\n const transferMarginRequired = Math.max(\n notional / leverage,\n notional * MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer,\n );\n const removableMargin = marginRemovalAllowed\n ? Math.max(\n 0,\n Math.min(\n freedInitialMargin,\n heldMargin -\n transferMarginRequired -\n notional * MARGIN_REMOVAL_PRICE_MOVE_BUFFER,\n ),\n )\n : 0;\n const margin = heldMargin - removableMargin;\n const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({\n isLong: signedSize > 0,\n markPrice: notional / size,\n margin,\n positionSize: size,\n marginTiers,\n });\n\n return {\n removableMargin,\n margin,\n liquidationPrice: liquidationPrice ?? undefined,\n };\n}\n\nconst resultingLeverage = (params: {\n notional: number;\n margin: number | undefined;\n fallback: number;\n}): number => {\n if (params.margin !== undefined && params.margin > 0 && params.notional > 0) {\n return params.notional / params.margin;\n }\n return params.fallback;\n};\n\n/**\n * Projects the isolated position that would remain after a proposed order.\n *\n * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing\n * margin when the selected leverage differs; the order then margins only its\n * own size at the selected leverage. The venue rejects a lower leverage that\n * the existing margin cannot cover, so margin and liquidation are unavailable\n * then. Maintenance tiers apply at the resulting liquidation notional.\n * Liquidation uses the projected mark, not average entry, because isolated\n * `marginUsed` is mark-based equity.\n * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.\n *\n * `price` is the fill or resting-limit price the caller expects. A marketable\n * order should pass its execution price; a limit should pass the limit. The\n * preview does not distinguish order types itself, does not model whether a\n * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.\n * Decrease margin is the remaining share of the isolated collateral after the\n * leverage change; close fees and realized PnL settle to the account, not the\n * leftover margin.\n *\n * @param params - Live isolated position, proposed order, and optional tiers.\n * @returns Discriminated preview; margin and liquidation are independently available.\n */\nexport function previewHyperLiquidIsolatedPositionModify(\n params: PreviewHyperLiquidIsolatedPositionModifyParams,\n): PositionModifyPreviewResult {\n const { position, direction, reduceOnly = false, marginTiers } = params;\n\n if (position.leverage.type === 'cross') {\n return { status: 'unsupported', reason: 'cross_margin' };\n }\n\n const currentSize = Math.abs(parseFiniteNumber(position.size));\n const signedSize = parseFiniteNumber(position.size);\n const currentMargin = parseFiniteNumber(position.marginUsed);\n const currentEntry = parseFiniteNumber(position.entryPrice);\n const currentLiquidationPrice = parseFiniteNumber(position.liquidationPrice);\n const currentLeverage = position.leverage.value;\n const selectedLeverage = params.leverage;\n const orderSize = parseFiniteNumber(params.size);\n const orderPrice = parseFiniteNumber(params.price);\n // An omitted, NaN or negative fee is unknown, never $0: increases and\n // flips then have no resulting margin.\n const feeAmountUsd = isNonNegativeFinite(params.feeAmountUsd)\n ? params.feeAmountUsd\n : undefined;\n\n if (\n !isPositiveFinite(currentSize) ||\n !Number.isFinite(signedSize) ||\n signedSize === 0 ||\n !isNonNegativeFinite(currentMargin) ||\n !isPositiveFinite(currentEntry) ||\n !isPositiveFinite(selectedLeverage) ||\n !isPositiveFinite(currentLeverage)\n ) {\n return { status: 'none' };\n }\n\n const openDirection: 'long' | 'short' = signedSize > 0 ? 'long' : 'short';\n const currentSnapshot = currentFromPosition({\n currentMargin,\n currentLiquidationPrice,\n });\n\n if (!isPositiveFinite(orderSize)) {\n return { status: 'none' };\n }\n\n const positionValue = parseFiniteNumber(position.positionValue);\n const currentNotional = isPositiveFinite(positionValue)\n ? positionValue\n : currentSize * currentEntry;\n\n const existingMarginAfterLeverage = isolatedMarginAfterLeverageChange({\n currentMargin,\n notional: currentNotional,\n currentLeverage,\n leverage: selectedLeverage,\n });\n\n const withResultingLiquidation = (preview: {\n kind: 'increase' | 'decrease' | 'flip';\n resultingDirection: 'long' | 'short';\n resultingSize: number;\n resultingEntryPrice: number;\n resultingMarkPrice: number;\n resultingNotional: number;\n newMargin: number | undefined;\n }): PositionModifyPreviewResult => {\n const liquidationPrice =\n preview.newMargin === undefined\n ? null\n : estimateIsolatedLiquidationPriceAtTier({\n isLong: preview.resultingDirection === 'long',\n markPrice: preview.resultingMarkPrice,\n margin: preview.newMargin,\n positionSize: preview.resultingSize,\n marginTiers,\n });\n\n return {\n status: 'open',\n kind: preview.kind,\n current: currentSnapshot,\n resulting: {\n direction: preview.resultingDirection,\n size: preview.resultingSize,\n entryPrice: preview.resultingEntryPrice,\n leverage: resultingLeverage({\n notional: preview.resultingNotional,\n margin: preview.newMargin,\n fallback: selectedLeverage,\n }),\n margin:\n preview.newMargin === undefined\n ? unavailable()\n : available(preview.newMargin),\n liquidationPrice:\n liquidationPrice === null\n ? unavailable()\n : available(liquidationPrice),\n },\n };\n };\n\n const isSameDirection = openDirection === direction;\n const fillPrice = isPositiveFinite(orderPrice) ? orderPrice : null;\n\n // Reduce-only in the position's own direction cannot add size and does not\n // close it, so there is no resulting position to project.\n if (isSameDirection && reduceOnly) {\n return { status: 'none' };\n }\n\n if (isSameDirection) {\n if (fillPrice === null) {\n return { status: 'none' };\n }\n const orderMargin = (orderSize * fillPrice) / selectedLeverage;\n const resultingSize = currentSize + orderSize;\n const resultingEntryPrice =\n (currentSize * currentEntry + orderSize * fillPrice) / resultingSize;\n const newMargin =\n existingMarginAfterLeverage === undefined || feeAmountUsd === undefined\n ? undefined\n : Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);\n\n return withResultingLiquidation({\n kind: 'increase',\n resultingDirection: openDirection,\n resultingSize,\n resultingEntryPrice,\n resultingMarkPrice: fillPrice,\n resultingNotional: resultingSize * fillPrice,\n newMargin,\n });\n }\n\n if (orderSize + SIZE_EPSILON < currentSize) {\n const remainingRatio = (currentSize - orderSize) / currentSize;\n const resultingSize = currentSize - orderSize;\n const newMargin =\n existingMarginAfterLeverage === undefined\n ? undefined\n : Math.max(0, existingMarginAfterLeverage * remainingRatio);\n const currentMarkPrice = currentNotional / currentSize;\n const resultingMarkPrice = fillPrice ?? currentMarkPrice;\n\n return withResultingLiquidation({\n kind: 'decrease',\n resultingDirection: openDirection,\n resultingSize,\n resultingEntryPrice: currentEntry,\n resultingMarkPrice,\n resultingNotional: resultingSize * resultingMarkPrice,\n newMargin,\n });\n }\n\n const leftover = orderSize - currentSize;\n if (leftover > SIZE_EPSILON && !reduceOnly) {\n if (fillPrice === null) {\n return { status: 'none' };\n }\n const orderMargin = (orderSize * fillPrice) / selectedLeverage;\n const leftoverRatio = leftover / orderSize;\n const leftoverMargin =\n existingMarginAfterLeverage === undefined || feeAmountUsd === undefined\n ? undefined\n : Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);\n\n return withResultingLiquidation({\n kind: 'flip',\n resultingDirection: direction,\n resultingSize: leftover,\n resultingEntryPrice: fillPrice,\n resultingMarkPrice: fillPrice,\n resultingNotional: leftover * fillPrice,\n newMargin: leftoverMargin,\n });\n }\n\n return {\n status: 'full_close',\n current: currentSnapshot,\n resultingDirection: openDirection,\n };\n}\n\n/**\n * The cross account a {@link projectHyperLiquidCrossPositionModify} order\n * draws on.\n */\nexport type HyperLiquidCrossAccount = {\n /** Cross collateral, as `getCrossCollateral` returns. */\n accountValue: number;\n /**\n * Maintenance margin of every cross position, the modified one included at\n * its current notional.\n */\n maintenanceMargin: number;\n /**\n * Standard account on a HIP-3 DEX only. Placement moves collateral into the\n * DEX when its withdrawable balance is below the order's required margin,\n * then returns the excess the order leaves (`calculateHip3RebalanceAmount`)\n * to the source DEX. Omit on a Unified account and on the main DEX.\n */\n hip3Funding?: {\n /** The DEX's withdrawable balance before the order. */\n withdrawable: number;\n /** Margin placement requires on the DEX before the order. */\n requiredMargin: number;\n };\n};\n\nexport type ProjectHyperLiquidCrossPositionModifyParams =\n PositionModifyPreviewParams & {\n /** This market's maintenance tiers. */\n marginTiers?: HyperLiquidMarginTier[] | null;\n /** `null` when unknown: margin is projected, liquidation is not. */\n crossAccount: HyperLiquidCrossAccount | null;\n };\n\n/** A Cross position after an order, from {@link projectHyperLiquidCrossPositionModify}. */\nexport type HyperLiquidCrossPositionModifyProjection =\n | { status: 'none' }\n | { status: 'full_close'; resultingDirection: 'long' | 'short' }\n | {\n status: 'open';\n kind: PositionModifyPreviewKind;\n direction: 'long' | 'short';\n size: number;\n entryPrice: number;\n /** Notional at the projected mark divided by the order leverage. */\n margin: number;\n /** The resulting position's liquidation price, classified. */\n liquidation: CrossLiquidationClassification;\n };\n\n/**\n * Projects the Cross position, flat or open, that would remain after a\n * proposed order.\n *\n * The venue sets the asset's Cross leverage to the order leverage, so the\n * resulting margin is the notional at the projected mark over that leverage.\n * Liquidation holds the account's other positions at their current value:\n * the account gains the existing size's move from its mark to the fill\n * price, pays the fee on an add or flip, and replaces this position's\n * maintenance with the resulting position's. A reduce ignores the fee, as the\n * isolated preview does. On a Standard HIP-3 DEX that placement funds (see\n * {@link HyperLiquidCrossAccount}), the DEX also receives the shortfall and\n * returns the excess placement would rebalance away. Without the position\n * value the current mark is unknown, so liquidation is `missing_inputs`.\n *\n * @param params - The position (size `'0'` for an opening), the proposed\n * order, the market's tiers and the cross account.\n * @returns The projection; `none` for an order that changes nothing or lacks\n * an input.\n */\nexport function projectHyperLiquidCrossPositionModify(\n params: ProjectHyperLiquidCrossPositionModifyParams,\n): HyperLiquidCrossPositionModifyProjection {\n const { position, direction, reduceOnly = false, leverage } = params;\n const { marginTiers, crossAccount } = params;\n const signedSize = parseFiniteNumber(position.size);\n const currentSize = Math.abs(signedSize);\n const currentEntry = parseFiniteNumber(position.entryPrice);\n const currentMargin = parseFiniteNumber(position.marginUsed);\n const orderSize = parseFiniteNumber(params.size);\n const orderPrice = parseFiniteNumber(params.price);\n const fillPrice = isPositiveFinite(orderPrice) ? orderPrice : null;\n const none = { status: 'none' } as const;\n\n if (\n !Number.isFinite(signedSize) ||\n (currentSize > 0 &&\n (!isPositiveFinite(currentEntry) ||\n !isNonNegativeFinite(currentMargin))) ||\n !isPositiveFinite(leverage) ||\n !isPositiveFinite(orderSize)\n ) {\n return none;\n }\n\n const positionValue = parseFiniteNumber(position.positionValue);\n // Without the position value the mark is unknown: margin is projected at\n // entry, liquidation is not.\n const currentMarkKnown = currentSize === 0 || isPositiveFinite(positionValue);\n let currentNotional = 0;\n if (currentSize > 0) {\n currentNotional = isPositiveFinite(positionValue)\n ? positionValue\n : currentSize * currentEntry;\n }\n let openDirection: 'long' | 'short' = direction;\n if (signedSize !== 0) {\n openDirection = signedSize > 0 ? 'long' : 'short';\n }\n\n let resulting: {\n kind: PositionModifyPreviewKind;\n direction: 'long' | 'short';\n size: number;\n entryPrice: number;\n markPrice: number;\n };\n if (openDirection === direction) {\n if (reduceOnly || fillPrice === null) {\n return none;\n }\n const size = currentSize + orderSize;\n resulting = {\n kind: 'increase',\n direction,\n size,\n entryPrice:\n ((currentSize > 0 ? currentSize * currentEntry : 0) +\n orderSize * fillPrice) /\n size,\n markPrice: fillPrice,\n };\n } else if (orderSize + SIZE_EPSILON < currentSize) {\n resulting = {\n kind: 'decrease',\n direction: openDirection,\n size: currentSize - orderSize,\n entryPrice: currentEntry,\n markPrice: fillPrice ?? currentNotional / currentSize,\n };\n } else if (orderSize - currentSize > SIZE_EPSILON && !reduceOnly) {\n if (fillPrice === null) {\n return none;\n }\n resulting = {\n kind: 'flip',\n direction,\n size: orderSize - currentSize,\n entryPrice: fillPrice,\n markPrice: fillPrice,\n };\n } else {\n return { status: 'full_close', resultingDirection: openDirection };\n }\n\n const margin = (resulting.size * resulting.markPrice) / leverage;\n // An omitted, NaN or negative fee is unknown, never $0.\n let feeAmountUsd: number | undefined = 0;\n if (resulting.kind !== 'decrease') {\n feeAmountUsd = isNonNegativeFinite(params.feeAmountUsd)\n ? params.feeAmountUsd\n : undefined;\n }\n const currentMaintenance =\n currentSize > 0\n ? estimateCrossMaintenanceMargin([\n { notional: currentNotional, marginTiers },\n ])\n : 0;\n const resultingMaintenance = estimateCrossMaintenanceMargin([\n { notional: resulting.size * resulting.markPrice, marginTiers },\n ]);\n\n let liquidation: CrossLiquidationClassification = missingInputs;\n if (\n crossAccount &&\n currentMarkKnown &&\n feeAmountUsd !== undefined &&\n currentMaintenance !== null &&\n resultingMaintenance !== null\n ) {\n const { hip3Funding } = crossAccount;\n const currentMark =\n currentSize > 0 ? currentNotional / currentSize : resulting.markPrice;\n let accountValue =\n crossAccount.accountValue -\n feeAmountUsd +\n signedSize * (resulting.markPrice - currentMark);\n if (hip3Funding && hip3Funding.withdrawable < hip3Funding.requiredMargin) {\n // Placement transfers the shortfall in, then returns the excess the\n // order leaves withdrawable, as `calculateHip3RebalanceAmount` decides.\n accountValue += hip3Funding.requiredMargin - hip3Funding.withdrawable;\n const committed =\n crossAccount.accountValue -\n hip3Funding.withdrawable +\n margin -\n (currentSize > 0 ? currentMargin : 0);\n accountValue -= calculateHip3RebalanceAmount({\n postOrderBalance: accountValue - committed,\n });\n }\n liquidation = classifyCrossLiquidationPrice({\n isLong: resulting.direction === 'long',\n markPrice: resulting.markPrice,\n positionSize: resulting.size,\n accountValue,\n maintenanceMargin:\n crossAccount.maintenanceMargin -\n currentMaintenance +\n resultingMaintenance,\n marginTiers,\n });\n }\n\n return {\n status: 'open',\n kind: resulting.kind,\n direction: resulting.direction,\n size: resulting.size,\n entryPrice: resulting.entryPrice,\n margin,\n liquidation,\n };\n}\n\n/**\n * A Cross liquidation estimate as a preview value.\n *\n * @param liquidation - As {@link classifyCrossLiquidationPrice} returns.\n * @returns The price, or unavailable with the classification as `reason`.\n */\nconst crossLiquidationPreview = (\n liquidation: CrossLiquidationClassification,\n): PositionPreviewValue =>\n liquidation.status === 'price'\n ? available(liquidation.price)\n : { available: false, reason: liquidation.status };\n\n/**\n * Previews the Cross position that would remain after a proposed order, as\n * {@link projectHyperLiquidCrossPositionModify} projects it, in the shape of\n * the isolated preview. An unavailable resulting liquidation price carries\n * `reason`: `covered_by_account` when no positive price liquidates the\n * position, `missing_inputs` otherwise.\n *\n * @param params - The open Cross position, the proposed order, the market's\n * tiers and the cross account.\n * @returns Discriminated preview; `none` for a flat position.\n */\nexport function previewHyperLiquidCrossPositionModify(\n params: ProjectHyperLiquidCrossPositionModifyParams,\n): PositionModifyPreviewResult {\n const signedSize = parseFiniteNumber(params.position.size);\n if (!Number.isFinite(signedSize) || signedSize === 0) {\n return { status: 'none' };\n }\n const projection = projectHyperLiquidCrossPositionModify(params);\n if (projection.status === 'none') {\n return projection;\n }\n const current = currentFromPosition({\n currentMargin: parseFiniteNumber(params.position.marginUsed),\n currentLiquidationPrice: parseFiniteNumber(\n params.position.liquidationPrice,\n ),\n });\n if (projection.status === 'full_close') {\n return { ...projection, current };\n }\n return {\n status: 'open',\n kind: projection.kind,\n current,\n resulting: {\n direction: projection.direction,\n size: projection.size,\n entryPrice: projection.entryPrice,\n leverage: params.leverage,\n margin: available(projection.margin),\n liquidationPrice: crossLiquidationPreview(projection.liquidation),\n },\n };\n}\n"]}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -5,11 +5,13 @@
|
|
|
5
5
|
* We use selective exports to avoid the name collision.
|
|
6
6
|
*/
|
|
7
7
|
export * from './accountUtils.js';
|
|
8
|
+
export { calculateAccountReturnOnEquity } from './accountAggregation.js';
|
|
9
|
+
export type { AccountReturnOnEquityParams } from './accountAggregation.js';
|
|
8
10
|
export * from './advancedOrderLists.js';
|
|
9
11
|
export * from './advancedOrders.js';
|
|
10
12
|
export { getBatchOperationStatus } from './batchOperationStatus.js';
|
|
11
13
|
export { estimateCloseReceive, calculateNetClosedPnl, calculateCloseSize, } from './closeCalculations.js';
|
|
12
|
-
export type { CloseSize, CloseSizeParams, CloseReceiveEstimateParams, CloseReceiveEstimate, NetClosedPnlParams, } from './closeCalculations.js';
|
|
14
|
+
export type { CloseSize, CloseSizeParams, CloseSizeRounding, CloseReceiveEstimateParams, CloseReceiveEstimate, NetClosedPnlParams, } from './closeCalculations.js';
|
|
13
15
|
export * from './errorUtils.js';
|
|
14
16
|
export { calculateFeeNotionalUsd, calculateUndiscountedFeeAmount, getUndiscountedFeeRate, } from './feeAmounts.js';
|
|
15
17
|
export type { FeeNotionalParams } from './feeAmounts.js';
|
|
@@ -24,7 +26,7 @@ export * from './marketDataTransform.js';
|
|
|
24
26
|
export * from './marketSearch.js';
|
|
25
27
|
export * from './marketUtils.js';
|
|
26
28
|
export { aggregateOrderBookLevels, calculateOrderBookAggregationParams, calculateOrderBookGroupingOptions, calculateOrderBookSpread, groupOrderBook, selectDefaultOrderBookGrouping, } from './orderBookGrouping.js';
|
|
27
|
-
export type { GroupedOrderBook, OrderBookAggregationParams, OrderBookSpread, } from './orderBookGrouping.js';
|
|
29
|
+
export type { GroupedOrderBook, OrderBookAggregationParams, OrderBookGroupingLadder, OrderBookGroupingOptionsParams, OrderBookSpread, } from './orderBookGrouping.js';
|
|
28
30
|
export { estimateOrderBookSlippage } from './orderBookSlippage.js';
|
|
29
31
|
export type { OrderBookSlippageEstimate, OrderBookSlippageParams, } from './orderBookSlippage.js';
|
|
30
32
|
export * from './orderCalculations.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,SAAS,EACT,eAAe,EACf,0BAA0B,EAC1B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,uBAAuB,EACvB,8BAA8B,EAC9B,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,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C1C,OAAO,EACL,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAG1B,eAAO,MAAM,cAAc,QAAO,KAAK,GAAG,MAGzC,CAAC;AACF,cAAc,sBAAsB,CAAC"}
|
package/dist/utils/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* We use selective exports to avoid the name collision.
|
|
6
6
|
*/
|
|
7
7
|
export * from './accountUtils.js';
|
|
8
|
+
export { calculateAccountReturnOnEquity } from './accountAggregation.js';
|
|
8
9
|
export * from './advancedOrderLists.js';
|
|
9
10
|
export * from './advancedOrders.js';
|
|
10
11
|
export { getBatchOperationStatus } from './batchOperationStatus.js';
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,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AAChC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAE9B,cAAc,2BAA2B,CAAC;AAC1C,OAAO,EACL,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAE1B,qFAAqF;AACrF,MAAM,CAAC,MAAM,cAAc,GAAG,GAAmB,EAAE;IACjD,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,QAAQ,IAAI,YAAY,CAAC;IAC9D,OAAO,GAAG,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;AAC/C,CAAC,CAAC;AACF,cAAc,sBAAsB,CAAC","sourcesContent":["/**\n * Barrel re-export for all portable utilities in controllers/utils/\n *\n * Note: hyperLiquidAdapter and orderCalculations both export calculatePositionSize.\n * We use selective exports to avoid the name collision.\n */\nexport * from './accountUtils.js';\nexport { calculateAccountReturnOnEquity } from './accountAggregation.js';\nexport type { AccountReturnOnEquityParams } from './accountAggregation.js';\nexport * from './advancedOrderLists.js';\nexport * from './advancedOrders.js';\nexport { getBatchOperationStatus } from './batchOperationStatus.js';\nexport {\n estimateCloseReceive,\n calculateNetClosedPnl,\n calculateCloseSize,\n} from './closeCalculations.js';\nexport type {\n CloseSize,\n CloseSizeParams,\n CloseSizeRounding,\n CloseReceiveEstimateParams,\n CloseReceiveEstimate,\n NetClosedPnlParams,\n} from './closeCalculations.js';\nexport * from './errorUtils.js';\nexport {\n calculateFeeNotionalUsd,\n calculateUndiscountedFeeAmount,\n getUndiscountedFeeRate,\n} from './feeAmounts.js';\nexport type { FeeNotionalParams } from './feeAmounts.js';\n// hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations\nexport {\n adaptOrderToSDK,\n adaptPositionFromSDK,\n adaptOrderFromSDK,\n adaptPositionTriggerOrderFromSDK,\n adaptTpslLinkageToGrouping,\n adaptTriggerOrderTypeFromSDK,\n adaptMarketFromSDK,\n adaptAccountStateFromSDK,\n buildAssetMapping,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n calculateHip3AssetId,\n parseAssetName,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n} from './hyperLiquidAdapter.js';\nexport * from './hyperLiquidOrderBookProcessor.js';\nexport * from './hyperLiquidPositionPreview.js';\nexport * from './hyperLiquidValidation.js';\nexport {\n calculateMaxRemovableMargin,\n estimateLiquidationPriceAfterMarginChange,\n} from './marginAdjustment.js';\nexport type {\n MaxRemovableMarginParams,\n LiquidationPriceAfterMarginChangeParams,\n} from './marginAdjustment.js';\nexport * from './idUtils.js';\nexport * from './marketDataTransform.js';\nexport * from './marketSearch.js';\nexport * from './marketUtils.js';\nexport {\n aggregateOrderBookLevels,\n calculateOrderBookAggregationParams,\n calculateOrderBookGroupingOptions,\n calculateOrderBookSpread,\n groupOrderBook,\n selectDefaultOrderBookGrouping,\n} from './orderBookGrouping.js';\nexport type {\n GroupedOrderBook,\n OrderBookAggregationParams,\n OrderBookGroupingLadder,\n OrderBookGroupingOptionsParams,\n OrderBookSpread,\n} from './orderBookGrouping.js';\nexport { estimateOrderBookSlippage } from './orderBookSlippage.js';\nexport type {\n OrderBookSlippageEstimate,\n OrderBookSlippageParams,\n} from './orderBookSlippage.js';\nexport * from './orderCalculations.js';\nexport {\n normalizeHyperLiquidScalePriceLadder,\n sizeHyperLiquidScaleLadder,\n} from './hyperLiquidScaleOrders.js';\nexport { getFillAggregationKey, getOrderFillKey } from './orderFills.js';\nexport * from './orderTypes.js';\nexport {\n getPerpsErrorCopy,\n PERPS_ERROR_COPY,\n PERPS_ORDER_TYPE_LABELS,\n} from './perpsClientCopy.js';\nexport type { PerpsErrorCopy, PerpsOrderTypeLabel } from './perpsClientCopy.js';\nexport * from './perpsDiskPersistence.js';\nexport {\n getPositionDirection,\n recomputePositionAtPrice,\n} from './positionCalculations.js';\nexport {\n getPriceDeviationBand,\n isPriceOutsideDeviationBand,\n} from './priceDeviation.js';\nexport { roundPerpsPrice } from './pricePrecision.js';\nexport * from './rewardsUtils.js';\nexport * from './significantFigures.js';\nexport * from './sortMarkets.js';\nexport * from './standaloneInfoClient.js';\nexport * from './stringParseUtils.js';\nexport * from './subscriptionFeeWaiver.js';\nexport * from './tpslCalculations.js';\nexport * from './transferData.js';\nexport * from './wait.js';\n\n// Inline from former utils.ts (getEnvironment was previously at perps/utils.ts root)\nexport const getEnvironment = (): 'DEV' | 'PROD' => {\n const env = globalThis.process?.env?.NODE_ENV ?? 'production';\n return env === 'production' ? 'PROD' : 'DEV';\n};\nexport * from './perpsFormatters.js';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lighterAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;
|
|
1
|
+
{"version":3,"file":"lighterAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAYH,OAAO,KAAK,EACV,YAAY,EACZ,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,KAAK,EACL,SAAS,EACT,eAAe,EACf,QAAQ,EACR,WAAW,EACX,WAAW,EAEZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,sBAAsB,EACtB,o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AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,kBAAkB,EAC5B,WAAW,GAAE,MAA6B,GACzC,QAAQ,CA6EV;AAMD;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,iBAAiB,GACzB,YAAY,CA0Cd;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kCAAkC,CAChD,OAAO,EAAE,iBAAiB,EAC1B,YAAY,EAAE,MAAM,EACpB,sBAAsB,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GAC7D,kBAAkB,GAAG,SAAS,CA4DhC;AAMD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,CA4BhE;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,MAAM,GACb,KAAK,CA6EP"}
|
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* - USDC collateral, single margin mode per account in the POC (cross).
|
|
13
13
|
*/
|
|
14
14
|
import { LIGHTER_DATA_INTEGRITY_PREFIX, LIGHTER_MARGIN_MODE_ISOLATED, LIGHTER_MAX_LEVERAGE, LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX, parseLighterStrictDecimal, } from '../constants/lighterConfig.js';
|
|
15
|
+
import { PERPS_CONSTANTS } from '../constants/perpsConfig.js';
|
|
16
|
+
import { accountReturnOnEquity } from '../internal/accountReturnOnEquity.js';
|
|
17
|
+
import { buildMarketNumericValues } from '../internal/marketNumericValues.js';
|
|
18
|
+
import { calculateOpenInterestUSD } from './marketDataTransform.js';
|
|
15
19
|
import { buildPublicTrade, sortPublicTradesNewestFirst, } from './publicTrades.js';
|
|
16
20
|
/**
|
|
17
21
|
* Parse an account-state number at the untrusted venue boundary. Account
|
|
@@ -71,6 +75,22 @@ export function adaptMarketFromLighter(market, maxLeverage) {
|
|
|
71
75
|
...(market.status === 'active' ? {} : { isDelisted: true }),
|
|
72
76
|
};
|
|
73
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Lighter reports open interest in base units; convert it to USD with
|
|
80
|
+
* `calculateOpenInterestUSD`, as Hyperliquid does.
|
|
81
|
+
*
|
|
82
|
+
* @param baseAmount - Open interest in base units.
|
|
83
|
+
* @param price - Price to convert at.
|
|
84
|
+
* @returns Open interest in USD, or undefined without a positive price or a
|
|
85
|
+
* finite amount.
|
|
86
|
+
*/
|
|
87
|
+
function toUsdOpenInterest(baseAmount, price) {
|
|
88
|
+
if (!(price > 0)) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
const usd = calculateOpenInterestUSD(baseAmount, price);
|
|
92
|
+
return Number.isFinite(usd) ? usd : undefined;
|
|
93
|
+
}
|
|
74
94
|
/**
|
|
75
95
|
* Transform a Lighter order book detail into UI-ready PerpsMarketData.
|
|
76
96
|
*
|
|
@@ -93,6 +113,8 @@ export function adaptMarketDataFromLighter(detail, formatters) {
|
|
|
93
113
|
if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {
|
|
94
114
|
throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} invalid authoritative leverage for ${detail.symbol}`);
|
|
95
115
|
}
|
|
116
|
+
// The detail has no mark price, so convert at the last trade price.
|
|
117
|
+
const openInterestUsd = toUsdOpenInterest(detail.openInterest, price);
|
|
96
118
|
return {
|
|
97
119
|
symbol: detail.symbol,
|
|
98
120
|
name: detail.symbol,
|
|
@@ -103,7 +125,15 @@ export function adaptMarketDataFromLighter(detail, formatters) {
|
|
|
103
125
|
change24h: formatChange(changeAbs, formatters),
|
|
104
126
|
change24hPercent: `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`,
|
|
105
127
|
volume: formatters.formatVolume(detail.dailyQuoteTokenVolume ?? 0),
|
|
106
|
-
openInterest:
|
|
128
|
+
openInterest: openInterestUsd === undefined
|
|
129
|
+
? PERPS_CONSTANTS.FallbackPriceDisplay
|
|
130
|
+
: formatters.formatVolume(openInterestUsd),
|
|
131
|
+
numericValues: buildMarketNumericValues({
|
|
132
|
+
price: detail.lastTradePrice,
|
|
133
|
+
change24hPercent: detail.dailyPriceChange,
|
|
134
|
+
volume: detail.dailyQuoteTokenVolume,
|
|
135
|
+
openInterest: openInterestUsd,
|
|
136
|
+
}),
|
|
107
137
|
};
|
|
108
138
|
}
|
|
109
139
|
/**
|
|
@@ -115,13 +145,15 @@ export function adaptMarketDataFromLighter(detail, formatters) {
|
|
|
115
145
|
* @returns MetaMask Perps API price update object.
|
|
116
146
|
*/
|
|
117
147
|
export function adaptPriceUpdateFromLighter(detail, timestamp) {
|
|
148
|
+
// The detail has no mark price, so convert at the last trade price.
|
|
149
|
+
const openInterest = toUsdOpenInterest(detail.openInterest, detail.lastTradePrice);
|
|
118
150
|
return {
|
|
119
151
|
symbol: detail.symbol,
|
|
120
152
|
price: String(detail.lastTradePrice ?? 0),
|
|
121
153
|
timestamp,
|
|
122
154
|
percentChange24h: String(detail.dailyPriceChange ?? 0),
|
|
123
155
|
volume24h: detail.dailyQuoteTokenVolume ?? 0,
|
|
124
|
-
openInterest
|
|
156
|
+
...(openInterest !== undefined && { openInterest }),
|
|
125
157
|
isTradable: detail.status === 'active',
|
|
126
158
|
};
|
|
127
159
|
}
|
|
@@ -139,6 +171,8 @@ export function adaptPriceUpdateFromLighterWsStat(stat, timestamp) {
|
|
|
139
171
|
const spread = Number.isFinite(bestBid) && Number.isFinite(bestAsk)
|
|
140
172
|
? String(bestAsk - bestBid)
|
|
141
173
|
: undefined;
|
|
174
|
+
const markPrice = parseFloat(stat.markPrice);
|
|
175
|
+
const openInterest = toUsdOpenInterest(parseFloat(stat.openInterest), markPrice > 0 ? markPrice : parseFloat(stat.lastTradePrice));
|
|
142
176
|
return {
|
|
143
177
|
symbol: stat.symbol,
|
|
144
178
|
price: stat.midPrice,
|
|
@@ -148,8 +182,9 @@ export function adaptPriceUpdateFromLighterWsStat(stat, timestamp) {
|
|
|
148
182
|
bestAsk: stat.bestAskPrice,
|
|
149
183
|
spread,
|
|
150
184
|
markPrice: stat.markPrice,
|
|
185
|
+
oraclePrice: stat.indexPrice,
|
|
151
186
|
funding: parseFloat(stat.currentFundingRate ?? stat.fundingRate ?? '0'),
|
|
152
|
-
openInterest
|
|
187
|
+
...(openInterest !== undefined && { openInterest }),
|
|
153
188
|
volume24h: stat.dailyQuoteTokenVolume ?? 0,
|
|
154
189
|
isTradable: true,
|
|
155
190
|
};
|
|
@@ -164,6 +199,8 @@ export function adaptAccountStateFromLighterUserStats(stats) {
|
|
|
164
199
|
const collateral = parseStrictAccountDecimal(stats.collateral, 'WebSocket collateral');
|
|
165
200
|
const available = parseStrictAccountDecimal(stats.availableBalance, 'WebSocket available balance');
|
|
166
201
|
const portfolioValue = parseStrictAccountDecimal(stats.portfolioValue, 'WebSocket portfolio value');
|
|
202
|
+
const marginUsed = Math.max(collateral - available, 0);
|
|
203
|
+
const unrealizedPnl = portfolioValue - collateral;
|
|
167
204
|
return {
|
|
168
205
|
totalBalance: String(portfolioValue),
|
|
169
206
|
spendableBalance: String(available),
|
|
@@ -172,11 +209,10 @@ export function adaptAccountStateFromLighterUserStats(stats) {
|
|
|
172
209
|
// spot USDC to add, and this read is a known account, so the amount is 0
|
|
173
210
|
// rather than unknown.
|
|
174
211
|
spotCollateral: '0',
|
|
175
|
-
marginUsed: String(
|
|
176
|
-
unrealizedPnl: String(
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
: '0',
|
|
212
|
+
marginUsed: String(marginUsed),
|
|
213
|
+
unrealizedPnl: String(unrealizedPnl),
|
|
214
|
+
// Same rate as the REST account state: '0' only when no margin is used.
|
|
215
|
+
returnOnEquity: String(accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber() ?? 0),
|
|
180
216
|
};
|
|
181
217
|
}
|
|
182
218
|
/**
|
|
@@ -541,7 +577,8 @@ export function adaptAccountStateFromLighter(account) {
|
|
|
541
577
|
spotCollateral: '0',
|
|
542
578
|
marginUsed: String(marginUsed),
|
|
543
579
|
unrealizedPnl: String(unrealizedPnl),
|
|
544
|
-
|
|
580
|
+
// '0' only when no margin is used, as before.
|
|
581
|
+
returnOnEquity: String(accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber() ?? 0),
|
|
545
582
|
providerId: 'lighter',
|
|
546
583
|
};
|
|
547
584
|
}
|