@metamask-previews/perps-controller 22.2.0-preview-2ad7fb9 → 22.3.0-preview-55295a2

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.
@@ -1,3 +1,4 @@
1
+ import { MARGIN_ADJUSTMENT_CONFIG } from '../constants/perpsConfig.js';
1
2
  /** Token-size comparison tolerance (floating-point / szDecimals noise). */
2
3
  const SIZE_EPSILON = 1e-10;
3
4
  /**
@@ -8,6 +9,31 @@ const SIZE_EPSILON = 1e-10;
8
9
  * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margin-and-pnl
9
10
  */
10
11
  const SINGLE_TIER_MARGIN_TABLE_ID_MAX = 50;
12
+ /**
13
+ * Share of notional held back for the mark moving before the venue processes
14
+ * a margin removal, as Mobile's `MARGIN_REMOVAL_PRICE_MOVE_BUFFER`.
15
+ */
16
+ const MARGIN_REMOVAL_PRICE_MOVE_BUFFER = 0.01;
17
+ /**
18
+ * Whether {@link estimateIsolatedLeverageChange} models a provider's isolated
19
+ * positions. Hyperliquid's isolated `marginUsed` is the position's
20
+ * collateral; Lighter's is the margin the position requires, so its result is
21
+ * unknown.
22
+ */
23
+ const ISOLATED_LEVERAGE_CHANGE_MODELLED = {
24
+ hyperliquid: true,
25
+ lighter: false,
26
+ };
27
+ /**
28
+ * Whether margin may leave an open isolated position, by the market's
29
+ * Hyperliquid `marginMode`. `strictIsolated` prohibits it; `noCross` only
30
+ * rules out cross margin. A market with neither `marginMode` nor
31
+ * `onlyIsolated` has no restriction.
32
+ */
33
+ const MARGIN_REMOVAL_ALLOWED = {
34
+ strictIsolated: false,
35
+ noCross: true,
36
+ };
11
37
  const unavailable = () => ({ available: false });
12
38
  const available = (value) => ({
13
39
  available: true,
@@ -183,8 +209,141 @@ export function estimateIsolatedLiquidationPriceAtTier(params) {
183
209
  }
184
210
  return null;
185
211
  }
212
+ /**
213
+ * Whether margin may leave an open isolated position on a market.
214
+ *
215
+ * @param market - The market, or undefined when unknown.
216
+ * @returns Whether removal is allowed, or undefined when the market or its
217
+ * margin mode is unknown, including an isolated-only market without
218
+ * `marginMode`, which may be strict isolated or `noCross`.
219
+ */
220
+ const isMarginRemovalAllowed = (market) => {
221
+ if (market === undefined) {
222
+ return undefined;
223
+ }
224
+ const { marginMode, onlyIsolated } = market;
225
+ if (marginMode === undefined) {
226
+ return onlyIsolated ? undefined : true;
227
+ }
228
+ return Object.hasOwn(MARGIN_REMOVAL_ALLOWED, marginMode)
229
+ ? MARGIN_REMOVAL_ALLOWED[marginMode]
230
+ : undefined;
231
+ };
232
+ /**
233
+ * Isolated margin a Hyperliquid position holds once its leverage changes,
234
+ * before any order. The venue keeps the margin, so a later order margins only
235
+ * its own size at the new leverage. It rejects lowering leverage when the
236
+ * margin is below the initial margin at the new leverage ("isolated position
237
+ * does not have sufficient margin available to decrease leverage").
238
+ *
239
+ * @param params - Current margin and notional, and both leverages.
240
+ * @param params.currentMargin - Isolated margin held now.
241
+ * @param params.notional - Position value at mark.
242
+ * @param params.currentLeverage - Leverage now.
243
+ * @param params.leverage - Leverage after the change.
244
+ * @returns Margin after the change, or undefined when the venue rejects it.
245
+ */
246
+ const isolatedMarginAfterLeverageChange = (params) => params.leverage < params.currentLeverage - SIZE_EPSILON &&
247
+ params.currentMargin < params.notional / params.leverage - SIZE_EPSILON
248
+ ? undefined
249
+ : params.currentMargin;
250
+ /**
251
+ * An isolated position after its leverage changes with no size change: the
252
+ * margin the change frees, and the margin and liquidation price afterwards.
253
+ *
254
+ * Hyperliquid keeps an isolated position's margin when leverage changes. On a
255
+ * rise, the change frees the drop in initial margin, notional / current
256
+ * leverage less notional / new leverage, at mark. Only margin above the
257
+ * transfer requirement may leave: the larger of the initial margin at the new
258
+ * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of
259
+ * notional, plus 1% of notional held back for the mark moving. Margin added
260
+ * on top of the initial margin and unrealized profit stay. `margin` assumes
261
+ * `removableMargin` is removed. A strict isolated market prohibits removing
262
+ * margin from an open position, so nothing is removable there and `margin`
263
+ * is the margin held. A fall frees nothing, and the venue rejects one the
264
+ * margin cannot cover.
265
+ *
266
+ * @param params - The position, provider, market, new leverage and margin
267
+ * tiers.
268
+ * @param params.position - The open position.
269
+ * @param params.providerId - Provider holding the position.
270
+ * @param params.market - The position's market, which says whether margin may
271
+ * leave it.
272
+ * @param params.leverage - Leverage the position moves to.
273
+ * @param params.marginTiers - Margin tiers for the asset, which cap the
274
+ * leverage and set the maintenance rate.
275
+ * @returns The change. Every figure is undefined for cross margin, a provider
276
+ * other than Hyperliquid, an unknown market or margin mode, a leverage above
277
+ * the max leverage of the margin tier the position's notional is in, a fall
278
+ * the margin cannot cover, or a missing or unusable input. Without margin
279
+ * tiers the leverage limit is not checked and the liquidation price is
280
+ * undefined.
281
+ */
282
+ export function estimateIsolatedLeverageChange({ position, providerId, market, leverage, marginTiers, }) {
283
+ const signedSize = parseFiniteNumber(position.size);
284
+ const size = Math.abs(signedSize);
285
+ const currentMargin = parseFiniteNumber(position.marginUsed);
286
+ const notional = parseFiniteNumber(position.positionValue);
287
+ const currentLeverage = position.leverage.value;
288
+ const marginRemovalAllowed = isMarginRemovalAllowed(market);
289
+ // The venue caps leverage by the tier the position's notional is in.
290
+ const schedule = buildMaintenanceSchedule(marginTiers ?? []);
291
+ const maxLeverage = marginTiers?.length
292
+ ? schedule.find((tier) => notional >= tier.lowerBound && notional < tier.upperBound)?.maxLeverage
293
+ : Number.POSITIVE_INFINITY;
294
+ const unknown = {
295
+ removableMargin: undefined,
296
+ margin: undefined,
297
+ liquidationPrice: undefined,
298
+ };
299
+ if (position.leverage.type !== 'isolated' ||
300
+ !Object.hasOwn(ISOLATED_LEVERAGE_CHANGE_MODELLED, providerId) ||
301
+ !ISOLATED_LEVERAGE_CHANGE_MODELLED[providerId] ||
302
+ marginRemovalAllowed === undefined ||
303
+ leverage === undefined ||
304
+ !Number.isFinite(leverage) ||
305
+ leverage < 1 ||
306
+ maxLeverage === undefined ||
307
+ leverage > maxLeverage ||
308
+ !Number.isFinite(currentLeverage) ||
309
+ currentLeverage < 1 ||
310
+ !isPositiveFinite(size) ||
311
+ !isPositiveFinite(currentMargin) ||
312
+ !isPositiveFinite(notional)) {
313
+ return unknown;
314
+ }
315
+ const heldMargin = isolatedMarginAfterLeverageChange({
316
+ currentMargin,
317
+ notional,
318
+ currentLeverage,
319
+ leverage,
320
+ });
321
+ if (heldMargin === undefined) {
322
+ return unknown;
323
+ }
324
+ const freedInitialMargin = notional / currentLeverage - notional / leverage;
325
+ const transferMarginRequired = Math.max(notional / leverage, notional * MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer);
326
+ const removableMargin = marginRemovalAllowed
327
+ ? Math.max(0, Math.min(freedInitialMargin, heldMargin -
328
+ transferMarginRequired -
329
+ notional * MARGIN_REMOVAL_PRICE_MOVE_BUFFER))
330
+ : 0;
331
+ const margin = heldMargin - removableMargin;
332
+ const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({
333
+ isLong: signedSize > 0,
334
+ markPrice: notional / size,
335
+ margin,
336
+ positionSize: size,
337
+ marginTiers,
338
+ });
339
+ return {
340
+ removableMargin,
341
+ margin,
342
+ liquidationPrice: liquidationPrice ?? undefined,
343
+ };
344
+ }
186
345
  const resultingLeverage = (params) => {
187
- if (params.margin > 0 && params.notional > 0) {
346
+ if (params.margin !== undefined && params.margin > 0 && params.notional > 0) {
188
347
  return params.notional / params.margin;
189
348
  }
190
349
  return params.fallback;
@@ -192,18 +351,21 @@ const resultingLeverage = (params) => {
192
351
  /**
193
352
  * Projects the isolated position that would remain after a proposed order.
194
353
  *
195
- * Models HyperLiquid's isolated `updateLeverage` (the selected leverage is
196
- * applied to the whole asset before the fill) and maintenance tiers at the
197
- * resulting liquidation notional. Liquidation uses the projected mark, not
198
- * average entry, because isolated `marginUsed` is mark-based equity.
354
+ * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing
355
+ * margin when the selected leverage differs; the order then margins only its
356
+ * own size at the selected leverage. The venue rejects a lower leverage that
357
+ * the existing margin cannot cover, so margin and liquidation are unavailable
358
+ * then. Maintenance tiers apply at the resulting liquidation notional.
359
+ * Liquidation uses the projected mark, not average entry, because isolated
360
+ * `marginUsed` is mark-based equity.
199
361
  * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.
200
362
  *
201
363
  * `price` is the fill or resting-limit price the caller expects. A marketable
202
364
  * order should pass its execution price; a limit should pass the limit. The
203
365
  * preview does not distinguish order types itself, does not model whether a
204
366
  * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.
205
- * Decrease margin is the remaining isolated collateral after leverage
206
- * reallocation; close fees and realized PnL settle to the account, not the
367
+ * Decrease margin is the remaining share of the isolated collateral after the
368
+ * leverage change; close fees and realized PnL settle to the account, not the
207
369
  * leftover margin.
208
370
  *
209
371
  * @param params - Live isolated position, proposed order, and optional tiers.
@@ -247,18 +409,22 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
247
409
  const currentNotional = isPositiveFinite(positionValue)
248
410
  ? positionValue
249
411
  : currentSize * currentEntry;
250
- const leverageChanged = Math.abs(selectedLeverage - currentLeverage) > SIZE_EPSILON;
251
- const existingMarginAfterLeverage = leverageChanged
252
- ? currentNotional / selectedLeverage
253
- : currentMargin;
412
+ const existingMarginAfterLeverage = isolatedMarginAfterLeverageChange({
413
+ currentMargin,
414
+ notional: currentNotional,
415
+ currentLeverage,
416
+ leverage: selectedLeverage,
417
+ });
254
418
  const withResultingLiquidation = (preview) => {
255
- const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({
256
- isLong: preview.resultingDirection === 'long',
257
- markPrice: preview.resultingMarkPrice,
258
- margin: preview.newMargin,
259
- positionSize: preview.resultingSize,
260
- marginTiers,
261
- });
419
+ const liquidationPrice = preview.newMargin === undefined
420
+ ? null
421
+ : estimateIsolatedLiquidationPriceAtTier({
422
+ isLong: preview.resultingDirection === 'long',
423
+ markPrice: preview.resultingMarkPrice,
424
+ margin: preview.newMargin,
425
+ positionSize: preview.resultingSize,
426
+ marginTiers,
427
+ });
262
428
  return {
263
429
  status: 'open',
264
430
  kind: preview.kind,
@@ -272,7 +438,9 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
272
438
  margin: preview.newMargin,
273
439
  fallback: selectedLeverage,
274
440
  }),
275
- margin: available(preview.newMargin),
441
+ margin: preview.newMargin === undefined
442
+ ? unavailable()
443
+ : available(preview.newMargin),
276
444
  liquidationPrice: liquidationPrice === null
277
445
  ? unavailable()
278
446
  : available(liquidationPrice),
@@ -293,7 +461,9 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
293
461
  const orderMargin = (orderSize * fillPrice) / selectedLeverage;
294
462
  const resultingSize = currentSize + orderSize;
295
463
  const resultingEntryPrice = (currentSize * currentEntry + orderSize * fillPrice) / resultingSize;
296
- const newMargin = Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);
464
+ const newMargin = existingMarginAfterLeverage === undefined
465
+ ? undefined
466
+ : Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);
297
467
  return withResultingLiquidation({
298
468
  kind: 'increase',
299
469
  resultingDirection: openDirection,
@@ -307,7 +477,9 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
307
477
  if (orderSize + SIZE_EPSILON < currentSize) {
308
478
  const remainingRatio = (currentSize - orderSize) / currentSize;
309
479
  const resultingSize = currentSize - orderSize;
310
- const newMargin = Math.max(0, existingMarginAfterLeverage * remainingRatio);
480
+ const newMargin = existingMarginAfterLeverage === undefined
481
+ ? undefined
482
+ : Math.max(0, existingMarginAfterLeverage * remainingRatio);
311
483
  const currentMarkPrice = currentNotional / currentSize;
312
484
  const resultingMarkPrice = fillPrice ?? currentMarkPrice;
313
485
  return withResultingLiquidation({
@@ -327,7 +499,9 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
327
499
  }
328
500
  const orderMargin = (orderSize * fillPrice) / selectedLeverage;
329
501
  const leftoverRatio = leftover / orderSize;
330
- const leftoverMargin = Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);
502
+ const leftoverMargin = existingMarginAfterLeverage === undefined
503
+ ? undefined
504
+ : Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);
331
505
  return withResultingLiquidation({
332
506
  kind: 'flip',
333
507
  resultingDirection: direction,
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidPositionPreview.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidPositionPreview.ts"],"names":[],"mappings":"AAOA,2EAA2E;AAC3E,MAAM,YAAY,GAAG,KAAK,CAAC;AAE3B;;;;;;GAMG;AACH,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAyB3C,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,IAAI;IACf,KAAK;CACN,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,CAAC,KAAgC,EAAU,EAAE,CACrE,MAAM,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;AAEjC,MAAM,gBAAgB,GAAG,CAAC,KAAa,EAAW,EAAE,CAClD,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC;AAEtC,MAAM,mBAAmB,GAAG,CAAC,KAAa,EAAW,EAAE,CACrD,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAEvC,MAAM,mBAAmB,GAAG,CAAC,MAG5B,EAAgC,EAAE,CAAC,CAAC;IACnC,MAAM,EAAE,mBAAmB,CAAC,MAAM,CAAC,aAAa,CAAC;QAC/C,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;QACjC,CAAC,CAAC,WAAW,EAAE;IACjB,gBAAgB,EAAE,gBAAgB,CAAC,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MAAM,EAAE,CAAC;QAC5B,CAAC;QACD,MAAM,WAAW,GAAG,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,gBAAgB,CAAC;QAC/D,MAAM,aAAa,GAAG,QAAQ,GAAG,SAAS,CAAC;QAC3C,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAC7B,CAAC,EACD,CAAC,WAAW,GAAG,YAAY,CAAC,GAAG,aAAa,CAC7C,CAAC;QAEF,OAAO,wBAAwB,CAAC;YAC9B,IAAI,EAAE,MAAM;YACZ,kBAAkB,EAAE,SAAS;YAC7B,aAAa,EAAE,QAAQ;YACvB,mBAAmB,EAAE,SAAS;YAC9B,kBAAkB,EAAE,SAAS;YAC7B,iBAAiB,EAAE,QAAQ,GAAG,SAAS;YACvC,SAAS,EAAE,cAAc;SAC1B,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,eAAe;QACxB,kBAAkB,EAAE,aAAa;KAClC,CAAC;AACJ,CAAC","sourcesContent":["import type {\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\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\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): boolean =>\n Number.isFinite(value) && value > 0;\n\nconst isNonNegativeFinite = (value: number): boolean =>\n 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\nconst resultingLeverage = (params: {\n notional: number;\n margin: number;\n fallback: number;\n}): number => {\n if (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` (the selected leverage is\n * applied to the whole asset before the fill) and maintenance tiers at the\n * resulting liquidation notional. Liquidation uses the projected mark, not\n * average entry, because isolated `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 isolated collateral after leverage\n * reallocation; 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 const feeAmountUsd =\n typeof params.feeAmountUsd === 'number' && params.feeAmountUsd > 0\n ? params.feeAmountUsd\n : 0;\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 leverageChanged =\n Math.abs(selectedLeverage - currentLeverage) > SIZE_EPSILON;\n const existingMarginAfterLeverage = leverageChanged\n ? currentNotional / selectedLeverage\n : currentMargin;\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;\n }): PositionModifyPreviewResult => {\n const liquidationPrice = 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: 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 = Math.max(\n 0,\n existingMarginAfterLeverage + orderMargin - feeAmountUsd,\n );\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 = 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 = Math.max(\n 0,\n (orderMargin - feeAmountUsd) * leftoverRatio,\n );\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;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,IAAI;IACf,KAAK;CACN,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,CAAC,KAAg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B,CAAC;QAEzD,OAAO,wBAAwB,CAAC;YAC9B,IAAI,EAAE,UAAU;YAChB,kBAAkB,EAAE,aAAa;YACjC,aAAa;YACb,mBAAmB,EAAE,YAAY;YACjC,kBAAkB;YAClB,iBAAiB,EAAE,aAAa,GAAG,kBAAkB;YACrD,SAAS;SACV,CAAC,CAAC;IACL,CAAC;IAED,MAAM,QAAQ,GAAG,SAAS,GAAG,WAAW,CAAC;IACzC,IAAI,QAAQ,GAAG,YAAY,IAAI,CAAC,UAAU,EAAE,CAAC;QAC3C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;YACvB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QAC5B,CAAC;QACD,MAAM,WAAW,GAAG,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,gBAAgB,CAAC;QAC/D,MAAM,aAAa,GAAG,QAAQ,GAAG,SAAS,CAAC;QAC3C,MAAM,cAAc,GAClB,2BAA2B,KAAK,SAAS;YACvC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,WAAW,GAAG,YAAY,CAAC,GAAG,aAAa,CAAC,CAAC;QAEhE,OAAO,wBAAwB,CAAC;YAC9B,IAAI,EAAE,MAAM;YACZ,kBAAkB,EAAE,SAAS;YAC7B,aAAa,EAAE,QAAQ;YACvB,mBAAmB,EAAE,SAAS;YAC9B,kBAAkB,EAAE,SAAS;YAC7B,iBAAiB,EAAE,QAAQ,GAAG,SAAS;YACvC,SAAS,EAAE,cAAc;SAC1B,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,eAAe;QACxB,kBAAkB,EAAE,aAAa;KAClC,CAAC;AACJ,CAAC","sourcesContent":["import { MARGIN_ADJUSTMENT_CONFIG } from '../constants/perpsConfig.js';\nimport type {\n MarketInfo,\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): boolean =>\n Number.isFinite(value) && value > 0;\n\nconst isNonNegativeFinite = (value: number): boolean =>\n 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/**\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 !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 const feeAmountUsd =\n typeof params.feeAmountUsd === 'number' && params.feeAmountUsd > 0\n ? params.feeAmountUsd\n : 0;\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\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\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"]}
@@ -5,6 +5,8 @@
5
5
  * We use selective exports to avoid the name collision.
6
6
  */
7
7
  export * from './accountUtils.js';
8
+ export { estimateCloseReceive, calculateNetClosedPnl, } from './closeCalculations.js';
9
+ export type { CloseReceiveEstimateParams, CloseReceiveEstimate, NetClosedPnlParams, } from './closeCalculations.js';
8
10
  export * from './errorUtils.js';
9
11
  export { adaptOrderToSDK, adaptPositionFromSDK, adaptOrderFromSDK, adaptPositionTriggerOrderFromSDK, adaptTpslLinkageToGrouping, adaptTriggerOrderTypeFromSDK, adaptMarketFromSDK, adaptAccountStateFromSDK, buildAssetMapping, formatHyperLiquidPrice, formatHyperLiquidSize, calculateHip3AssetId, parseAssetName, adaptHyperLiquidLedgerUpdateToUserHistoryItem, } from './hyperLiquidAdapter.js';
10
12
  export * from './hyperLiquidOrderBookProcessor.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,iBAAiB,CAAC;AAEhC,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,gCAAgC,EAChC,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,GAC9C,MAAM,yBAAyB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iBAAiB,CAAC;AAChC,cAAc,2BAA2B,CAAC;AAC1C,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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,0BAA0B,EAC1B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAEhC,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,gCAAgC,EAChC,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,GAC9C,MAAM,yBAAyB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iBAAiB,CAAC;AAChC,cAAc,2BAA2B,CAAC;AAC1C,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"}
@@ -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 { estimateCloseReceive, calculateNetClosedPnl, } from './closeCalculations.js';
8
9
  export * from './errorUtils.js';
9
10
  // hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations
10
11
  export { adaptOrderToSDK, adaptPositionFromSDK, adaptOrderFromSDK, adaptPositionTriggerOrderFromSDK, adaptTpslLinkageToGrouping, adaptTriggerOrderTypeFromSDK, adaptMarketFromSDK, adaptAccountStateFromSDK, buildAssetMapping, formatHyperLiquidPrice, formatHyperLiquidSize, calculateHip3AssetId, parseAssetName, adaptHyperLiquidLedgerUpdateToUserHistoryItem, } from './hyperLiquidAdapter.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,mGAAmG;AACnG,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,gCAAgC,EAChC,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,GAC9C,MAAM,yBAAyB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iBAAiB,CAAC;AAChC,cAAc,2BAA2B,CAAC;AAC1C,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 * from './errorUtils.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 * from './idUtils.js';\nexport * from './marketDataTransform.js';\nexport * from './marketSearch.js';\nexport * from './marketUtils.js';\nexport * from './orderCalculations.js';\nexport * from './orderTypes.js';\nexport * from './perpsDiskPersistence.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
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAMhC,cAAc,iBAAiB,CAAC;AAChC,mGAAmG;AACnG,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,gCAAgC,EAChC,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,GAC9C,MAAM,yBAAyB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,iBAAiB,CAAC;AAChC,cAAc,2BAA2B,CAAC;AAC1C,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 {\n estimateCloseReceive,\n calculateNetClosedPnl,\n} from './closeCalculations.js';\nexport type {\n CloseReceiveEstimateParams,\n CloseReceiveEstimate,\n NetClosedPnlParams,\n} from './closeCalculations.js';\nexport * from './errorUtils.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 * from './idUtils.js';\nexport * from './marketDataTransform.js';\nexport * from './marketSearch.js';\nexport * from './marketUtils.js';\nexport * from './orderCalculations.js';\nexport * from './orderTypes.js';\nexport * from './perpsDiskPersistence.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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/perps-controller",
3
- "version": "22.2.0-preview-2ad7fb9",
3
+ "version": "22.3.0-preview-55295a2",
4
4
  "description": "Controller for perpetual trading functionality in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",