@metamask-previews/perps-controller 22.2.0-preview-4dd847ca3 → 22.2.0-preview-2ad7fb9

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,4 +1,4 @@
1
- import type { PerpsProviderType, Position, PositionModifyPreviewParams, PositionModifyPreviewResult } from '../types/index.js';
1
+ import type { PositionModifyPreviewParams, PositionModifyPreviewResult } from '../types/index.js';
2
2
  export type HyperLiquidMarginTier = {
3
3
  /** Inclusive notional lower bound in USD. */
4
4
  lowerBound: number;
@@ -18,44 +18,6 @@ type MaintenanceScheduleTier = {
18
18
  maintenanceMarginRate: number;
19
19
  maintenanceDeduction: number;
20
20
  };
21
- /**
22
- * Inputs to {@link estimateIsolatedLeverageChange}.
23
- */
24
- export type IsolatedLeverageChangeParams = {
25
- /** The open position; a `Position` can be passed as-is. */
26
- position: Pick<Position, 'size' | 'marginUsed' | 'positionValue'> & {
27
- leverage: Pick<Position['leverage'], 'type' | 'value'>;
28
- };
29
- /**
30
- * Provider holding the position. Only Hyperliquid isolated positions are
31
- * modelled; others return undefined.
32
- */
33
- providerId: PerpsProviderType;
34
- /** Leverage the position moves to, at least 1. Undefined until chosen. */
35
- leverage: number | undefined;
36
- /**
37
- * Margin tiers for the asset, as {@link resolveHyperLiquidMarginTiers}
38
- * returns. The tier the position's notional is in caps `leverage`; tiers
39
- * that do not cover the notional make every figure undefined. Without
40
- * tiers the cap is not checked and the liquidation price is undefined.
41
- */
42
- marginTiers?: HyperLiquidMarginTier[] | null;
43
- };
44
- /**
45
- * An isolated position after a leverage change with no size change.
46
- */
47
- export type IsolatedLeverageChange = {
48
- /**
49
- * Margin the change frees: the drop in initial margin, notional / current
50
- * leverage less notional / new leverage, limited to what may leave the
51
- * position. 0 unless leverage rises.
52
- */
53
- removableMargin: number | undefined;
54
- /** Margin afterwards, once `removableMargin` is removed. */
55
- margin: number | undefined;
56
- /** Liquidation price at `margin`. */
57
- liquidationPrice: number | undefined;
58
- };
59
21
  /**
60
22
  * Resolves the HyperLiquid margin table into preview tiers.
61
23
  *
@@ -137,51 +99,21 @@ export declare function estimateIsolatedLiquidationPriceAtTier(params: {
137
99
  positionSize: number;
138
100
  marginTiers: HyperLiquidMarginTier[] | null | undefined;
139
101
  }): number | null;
140
- /**
141
- * An isolated position after its leverage changes with no size change: the
142
- * margin the change frees, and the margin and liquidation price afterwards.
143
- *
144
- * Hyperliquid keeps an isolated position's margin when leverage changes. On a
145
- * rise, the change frees the drop in initial margin, notional / current
146
- * leverage less notional / new leverage, at mark. Only margin above the
147
- * transfer requirement may leave: the larger of the initial margin at the new
148
- * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of
149
- * notional, plus 1% of notional held back for the mark moving. Margin added
150
- * on top of the initial margin and unrealized profit stay. `margin` assumes
151
- * `removableMargin` is removed. A fall frees nothing, and the venue rejects
152
- * one the margin cannot cover.
153
- *
154
- * @param params - The position, provider, new leverage and margin tiers.
155
- * @param params.position - The open position.
156
- * @param params.providerId - Provider holding the position.
157
- * @param params.leverage - Leverage the position moves to.
158
- * @param params.marginTiers - Margin tiers for the asset, which cap the
159
- * leverage and set the maintenance rate.
160
- * @returns The change. Every figure is undefined for cross margin, a provider
161
- * other than Hyperliquid, a leverage above the max leverage of the margin
162
- * tier the position's notional is in, a fall the margin cannot cover, or a
163
- * missing or unusable input. Without margin tiers the leverage limit is not
164
- * checked and the liquidation price is undefined.
165
- */
166
- export declare function estimateIsolatedLeverageChange({ position, providerId, leverage, marginTiers, }: IsolatedLeverageChangeParams): IsolatedLeverageChange;
167
102
  /**
168
103
  * Projects the isolated position that would remain after a proposed order.
169
104
  *
170
- * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing
171
- * margin when the selected leverage differs; the order then margins only its
172
- * own size at the selected leverage. The venue rejects a lower leverage that
173
- * the existing margin cannot cover, so margin and liquidation are unavailable
174
- * then. Maintenance tiers apply at the resulting liquidation notional.
175
- * Liquidation uses the projected mark, not average entry, because isolated
176
- * `marginUsed` is mark-based equity.
105
+ * Models HyperLiquid's isolated `updateLeverage` (the selected leverage is
106
+ * applied to the whole asset before the fill) and maintenance tiers at the
107
+ * resulting liquidation notional. Liquidation uses the projected mark, not
108
+ * average entry, because isolated `marginUsed` is mark-based equity.
177
109
  * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.
178
110
  *
179
111
  * `price` is the fill or resting-limit price the caller expects. A marketable
180
112
  * order should pass its execution price; a limit should pass the limit. The
181
113
  * preview does not distinguish order types itself, does not model whether a
182
114
  * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.
183
- * Decrease margin is the remaining share of the isolated collateral after the
184
- * leverage change; close fees and realized PnL settle to the account, not the
115
+ * Decrease margin is the remaining isolated collateral after leverage
116
+ * reallocation; close fees and realized PnL settle to the account, not the
185
117
  * leftover margin.
186
118
  *
187
119
  * @param params - Live isolated position, proposed order, and optional tiers.
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidPositionPreview.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidPositionPreview.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,QAAQ,EAER,2BAA2B,EAC3B,2BAA2B,EAE5B,MAAM,mBAAmB,CAAC;AA+B3B,MAAM,MAAM,qBAAqB,GAAG;IAClC,6CAA6C;IAC7C,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,8CAA8C,GACxD,2BAA2B,GAAG;IAC5B;;;OAGG;IACH,WAAW,CAAC,EAAE,qBAAqB,EAAE,GAAG,IAAI,CAAC;CAC9C,CAAC;AAEJ,KAAK,uBAAuB,GAAG;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,qBAAqB,EAAE,MAAM,CAAC;IAC9B,oBAAoB,EAAE,MAAM,C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;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,wCAAwC,CACtD,MAAM,EAAE,8CAA8C,GACrD,2BAA2B,CA4K7B"}
@@ -1,4 +1,3 @@
1
- import { MARGIN_ADJUSTMENT_CONFIG } from '../constants/perpsConfig.js';
2
1
  /** Token-size comparison tolerance (floating-point / szDecimals noise). */
3
2
  const SIZE_EPSILON = 1e-10;
4
3
  /**
@@ -9,21 +8,6 @@ const SIZE_EPSILON = 1e-10;
9
8
  * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margin-and-pnl
10
9
  */
11
10
  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
11
  const unavailable = () => ({ available: false });
28
12
  const available = (value) => ({
29
13
  available: true,
@@ -199,111 +183,8 @@ export function estimateIsolatedLiquidationPriceAtTier(params) {
199
183
  }
200
184
  return null;
201
185
  }
202
- /**
203
- * Isolated margin a Hyperliquid position holds once its leverage changes,
204
- * before any order. The venue keeps the margin, so a later order margins only
205
- * its own size at the new leverage. It rejects lowering leverage when the
206
- * margin is below the initial margin at the new leverage ("isolated position
207
- * does not have sufficient margin available to decrease leverage").
208
- *
209
- * @param params - Current margin and notional, and both leverages.
210
- * @param params.currentMargin - Isolated margin held now.
211
- * @param params.notional - Position value at mark.
212
- * @param params.currentLeverage - Leverage now.
213
- * @param params.leverage - Leverage after the change.
214
- * @returns Margin after the change, or undefined when the venue rejects it.
215
- */
216
- const isolatedMarginAfterLeverageChange = (params) => params.leverage < params.currentLeverage - SIZE_EPSILON &&
217
- params.currentMargin < params.notional / params.leverage - SIZE_EPSILON
218
- ? undefined
219
- : params.currentMargin;
220
- /**
221
- * An isolated position after its leverage changes with no size change: the
222
- * margin the change frees, and the margin and liquidation price afterwards.
223
- *
224
- * Hyperliquid keeps an isolated position's margin when leverage changes. On a
225
- * rise, the change frees the drop in initial margin, notional / current
226
- * leverage less notional / new leverage, at mark. Only margin above the
227
- * transfer requirement may leave: the larger of the initial margin at the new
228
- * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of
229
- * notional, plus 1% of notional held back for the mark moving. Margin added
230
- * on top of the initial margin and unrealized profit stay. `margin` assumes
231
- * `removableMargin` is removed. A fall frees nothing, and the venue rejects
232
- * one the margin cannot cover.
233
- *
234
- * @param params - The position, provider, new leverage and margin tiers.
235
- * @param params.position - The open position.
236
- * @param params.providerId - Provider holding the position.
237
- * @param params.leverage - Leverage the position moves to.
238
- * @param params.marginTiers - Margin tiers for the asset, which cap the
239
- * leverage and set the maintenance rate.
240
- * @returns The change. Every figure is undefined for cross margin, a provider
241
- * other than Hyperliquid, a leverage above the max leverage of the margin
242
- * tier the position's notional is in, a fall the margin cannot cover, or a
243
- * missing or unusable input. Without margin tiers the leverage limit is not
244
- * checked and the liquidation price is undefined.
245
- */
246
- export function estimateIsolatedLeverageChange({ position, providerId, leverage, marginTiers, }) {
247
- const signedSize = parseFiniteNumber(position.size);
248
- const size = Math.abs(signedSize);
249
- const currentMargin = parseFiniteNumber(position.marginUsed);
250
- const notional = parseFiniteNumber(position.positionValue);
251
- const currentLeverage = position.leverage.value;
252
- // The venue caps leverage by the tier the position's notional is in.
253
- const schedule = buildMaintenanceSchedule(marginTiers ?? []);
254
- const maxLeverage = marginTiers?.length
255
- ? schedule.find((tier) => notional >= tier.lowerBound && notional < tier.upperBound)?.maxLeverage
256
- : Number.POSITIVE_INFINITY;
257
- const unknown = {
258
- removableMargin: undefined,
259
- margin: undefined,
260
- liquidationPrice: undefined,
261
- };
262
- if (position.leverage.type !== 'isolated' ||
263
- !Object.hasOwn(ISOLATED_LEVERAGE_CHANGE_MODELLED, providerId) ||
264
- !ISOLATED_LEVERAGE_CHANGE_MODELLED[providerId] ||
265
- leverage === undefined ||
266
- !Number.isFinite(leverage) ||
267
- leverage < 1 ||
268
- maxLeverage === undefined ||
269
- leverage > maxLeverage ||
270
- !Number.isFinite(currentLeverage) ||
271
- currentLeverage < 1 ||
272
- !isPositiveFinite(size) ||
273
- !isPositiveFinite(currentMargin) ||
274
- !isPositiveFinite(notional)) {
275
- return unknown;
276
- }
277
- const heldMargin = isolatedMarginAfterLeverageChange({
278
- currentMargin,
279
- notional,
280
- currentLeverage,
281
- leverage,
282
- });
283
- if (heldMargin === undefined) {
284
- return unknown;
285
- }
286
- const freedInitialMargin = notional / currentLeverage - notional / leverage;
287
- const transferMarginRequired = Math.max(notional / leverage, notional * MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer);
288
- const removableMargin = Math.max(0, Math.min(freedInitialMargin, heldMargin -
289
- transferMarginRequired -
290
- notional * MARGIN_REMOVAL_PRICE_MOVE_BUFFER));
291
- const margin = heldMargin - removableMargin;
292
- const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({
293
- isLong: signedSize > 0,
294
- markPrice: notional / size,
295
- margin,
296
- positionSize: size,
297
- marginTiers,
298
- });
299
- return {
300
- removableMargin,
301
- margin,
302
- liquidationPrice: liquidationPrice ?? undefined,
303
- };
304
- }
305
186
  const resultingLeverage = (params) => {
306
- if (params.margin !== undefined && params.margin > 0 && params.notional > 0) {
187
+ if (params.margin > 0 && params.notional > 0) {
307
188
  return params.notional / params.margin;
308
189
  }
309
190
  return params.fallback;
@@ -311,21 +192,18 @@ const resultingLeverage = (params) => {
311
192
  /**
312
193
  * Projects the isolated position that would remain after a proposed order.
313
194
  *
314
- * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing
315
- * margin when the selected leverage differs; the order then margins only its
316
- * own size at the selected leverage. The venue rejects a lower leverage that
317
- * the existing margin cannot cover, so margin and liquidation are unavailable
318
- * then. Maintenance tiers apply at the resulting liquidation notional.
319
- * Liquidation uses the projected mark, not average entry, because isolated
320
- * `marginUsed` is mark-based equity.
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.
321
199
  * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.
322
200
  *
323
201
  * `price` is the fill or resting-limit price the caller expects. A marketable
324
202
  * order should pass its execution price; a limit should pass the limit. The
325
203
  * preview does not distinguish order types itself, does not model whether a
326
204
  * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.
327
- * Decrease margin is the remaining share of the isolated collateral after the
328
- * leverage change; close fees and realized PnL settle to the account, not the
205
+ * Decrease margin is the remaining isolated collateral after leverage
206
+ * reallocation; close fees and realized PnL settle to the account, not the
329
207
  * leftover margin.
330
208
  *
331
209
  * @param params - Live isolated position, proposed order, and optional tiers.
@@ -369,22 +247,18 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
369
247
  const currentNotional = isPositiveFinite(positionValue)
370
248
  ? positionValue
371
249
  : currentSize * currentEntry;
372
- const existingMarginAfterLeverage = isolatedMarginAfterLeverageChange({
373
- currentMargin,
374
- notional: currentNotional,
375
- currentLeverage,
376
- leverage: selectedLeverage,
377
- });
250
+ const leverageChanged = Math.abs(selectedLeverage - currentLeverage) > SIZE_EPSILON;
251
+ const existingMarginAfterLeverage = leverageChanged
252
+ ? currentNotional / selectedLeverage
253
+ : currentMargin;
378
254
  const withResultingLiquidation = (preview) => {
379
- const liquidationPrice = preview.newMargin === undefined
380
- ? null
381
- : estimateIsolatedLiquidationPriceAtTier({
382
- isLong: preview.resultingDirection === 'long',
383
- markPrice: preview.resultingMarkPrice,
384
- margin: preview.newMargin,
385
- positionSize: preview.resultingSize,
386
- marginTiers,
387
- });
255
+ const liquidationPrice = estimateIsolatedLiquidationPriceAtTier({
256
+ isLong: preview.resultingDirection === 'long',
257
+ markPrice: preview.resultingMarkPrice,
258
+ margin: preview.newMargin,
259
+ positionSize: preview.resultingSize,
260
+ marginTiers,
261
+ });
388
262
  return {
389
263
  status: 'open',
390
264
  kind: preview.kind,
@@ -398,9 +272,7 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
398
272
  margin: preview.newMargin,
399
273
  fallback: selectedLeverage,
400
274
  }),
401
- margin: preview.newMargin === undefined
402
- ? unavailable()
403
- : available(preview.newMargin),
275
+ margin: available(preview.newMargin),
404
276
  liquidationPrice: liquidationPrice === null
405
277
  ? unavailable()
406
278
  : available(liquidationPrice),
@@ -421,9 +293,7 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
421
293
  const orderMargin = (orderSize * fillPrice) / selectedLeverage;
422
294
  const resultingSize = currentSize + orderSize;
423
295
  const resultingEntryPrice = (currentSize * currentEntry + orderSize * fillPrice) / resultingSize;
424
- const newMargin = existingMarginAfterLeverage === undefined
425
- ? undefined
426
- : Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);
296
+ const newMargin = Math.max(0, existingMarginAfterLeverage + orderMargin - feeAmountUsd);
427
297
  return withResultingLiquidation({
428
298
  kind: 'increase',
429
299
  resultingDirection: openDirection,
@@ -437,9 +307,7 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
437
307
  if (orderSize + SIZE_EPSILON < currentSize) {
438
308
  const remainingRatio = (currentSize - orderSize) / currentSize;
439
309
  const resultingSize = currentSize - orderSize;
440
- const newMargin = existingMarginAfterLeverage === undefined
441
- ? undefined
442
- : Math.max(0, existingMarginAfterLeverage * remainingRatio);
310
+ const newMargin = Math.max(0, existingMarginAfterLeverage * remainingRatio);
443
311
  const currentMarkPrice = currentNotional / currentSize;
444
312
  const resultingMarkPrice = fillPrice ?? currentMarkPrice;
445
313
  return withResultingLiquidation({
@@ -459,9 +327,7 @@ export function previewHyperLiquidIsolatedPositionModify(params) {
459
327
  }
460
328
  const orderMargin = (orderSize * fillPrice) / selectedLeverage;
461
329
  const leftoverRatio = leftover / orderSize;
462
- const leftoverMargin = existingMarginAfterLeverage === undefined
463
- ? undefined
464
- : Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);
330
+ const leftoverMargin = Math.max(0, (orderMargin - feeAmountUsd) * leftoverRatio);
465
331
  return withResultingLiquidation({
466
332
  kind: 'flip',
467
333
  resultingDirection: direction,
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidPositionPreview.js","sourceRoot":"","sources":["../../src/utils/hyperLiquidPositionPreview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAUvE,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;AAiEF,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;A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,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 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\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 /** 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.\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 * 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 fall frees nothing, and the venue rejects\n * one the margin cannot cover.\n *\n * @param params - The position, provider, new leverage and margin tiers.\n * @param params.position - The open position.\n * @param params.providerId - Provider holding the position.\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, a leverage above the max leverage of the margin\n * tier the position's notional is in, a fall the margin cannot cover, or a\n * missing or unusable input. Without margin tiers the leverage limit is not\n * checked and the liquidation price is undefined.\n */\nexport function estimateIsolatedLeverageChange({\n position,\n providerId,\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 // 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 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 = Math.max(\n 0,\n Math.min(\n freedInitialMargin,\n heldMargin -\n transferMarginRequired -\n notional * MARGIN_REMOVAL_PRICE_MOVE_BUFFER,\n ),\n );\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"]}
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,MAA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M,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"]}
@@ -5,8 +5,6 @@
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';
10
8
  export * from './errorUtils.js';
11
9
  export { adaptOrderToSDK, adaptPositionFromSDK, adaptOrderFromSDK, adaptPositionTriggerOrderFromSDK, adaptTpslLinkageToGrouping, adaptTriggerOrderTypeFromSDK, adaptMarketFromSDK, adaptAccountStateFromSDK, buildAssetMapping, formatHyperLiquidPrice, formatHyperLiquidSize, calculateHip3AssetId, parseAssetName, adaptHyperLiquidLedgerUpdateToUserHistoryItem, } from './hyperLiquidAdapter.js';
12
10
  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,OAAO,EACL,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,0BAA0B,EAC1B,oBAAoB,EACpB,kBAAkB,GACnB,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,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,7 +5,6 @@
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
8
  export * from './errorUtils.js';
10
9
  // hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations
11
10
  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,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"]}
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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/perps-controller",
3
- "version": "22.2.0-preview-4dd847ca3",
3
+ "version": "22.2.0-preview-2ad7fb9",
4
4
  "description": "Controller for perpetual trading functionality in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",