@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -9
- package/dist/PerpsController-method-action-types.d.ts +149 -3
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +125 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +787 -31
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +69 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +82 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +15 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +14 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +10 -2
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +11 -3
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +10 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/internal/accountReturnOnEquity.d.ts +12 -0
- package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
- package/dist/internal/accountReturnOnEquity.js +18 -0
- package/dist/internal/accountReturnOnEquity.js.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
- package/dist/internal/marketNumericValues.d.ts +10 -0
- package/dist/internal/marketNumericValues.d.ts.map +1 -0
- package/dist/internal/marketNumericValues.js +9 -0
- package/dist/internal/marketNumericValues.js.map +1 -0
- package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
- package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
- package/dist/internal/perpsDisplaySymbol.js +21 -0
- package/dist/internal/perpsDisplaySymbol.js.map +1 -0
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +140 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +72 -4
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +751 -159
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +2 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +11 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/selectors.d.ts +15 -5
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +23 -5
- package/dist/selectors.js.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.js +8 -10
- package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +8 -0
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +65 -0
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +117 -30
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +20 -3
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +55 -3
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +139 -0
- package/dist/services/StreamChannelManager.d.ts.map +1 -0
- package/dist/services/StreamChannelManager.js +475 -0
- package/dist/services/StreamChannelManager.js.map +1 -0
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +7 -0
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/agentSigner.d.ts +8 -0
- package/dist/services/agentSigner.d.ts.map +1 -1
- package/dist/services/agentSigner.js +13 -0
- package/dist/services/agentSigner.js.map +1 -1
- package/dist/types/hyperliquid-types.d.ts +9 -1
- package/dist/types/hyperliquid-types.d.ts.map +1 -1
- package/dist/types/hyperliquid-types.js +10 -0
- package/dist/types/hyperliquid-types.js.map +1 -1
- package/dist/types/index.d.ts +434 -17
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +17 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -1
- package/dist/utils/accountAggregation.js +21 -5
- package/dist/utils/accountAggregation.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +31 -10
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +68 -28
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +17 -4
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +23 -7
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +17 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +264 -29
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +4 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +46 -9
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +13 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +1 -2
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +7 -17
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +35 -5
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +62 -6
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
- package/dist/utils/perpsDiskPersistence.js +10 -0
- package/dist/utils/perpsDiskPersistence.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +31 -0
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +26 -0
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/dist/utils/priceDeviation.d.ts +9 -6
- package/dist/utils/priceDeviation.d.ts.map +1 -1
- package/dist/utils/priceDeviation.js +17 -26
- package/dist/utils/priceDeviation.js.map +1 -1
- package/dist/utils/sortMarkets.d.ts +13 -5
- package/dist/utils/sortMarkets.d.ts.map +1 -1
- package/dist/utils/sortMarkets.js +60 -38
- package/dist/utils/sortMarkets.js.map +1 -1
- package/docs/architecture.md +54 -24
- package/docs/client-contract.md +52 -27
- package/docs/contracts/events.md +38 -32
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/formatting.md +2 -0
- package/docs/venues/lighter/capabilities.md +18 -15
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"priceDeviation.js","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC
|
|
1
|
+
{"version":3,"file":"priceDeviation.js","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CACnC,cAAsB,EACtB,YAAoB;IAEpB,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC;QAChC,cAAc,IAAI,CAAC;QACnB,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC9B,YAAY,IAAI,CAAC,EACjB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,SAAS,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IACpD,OAAO;QACL,GAAG,EAAE,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE;QACzD,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE;KACvC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,cAAsB,EACtB,YAAoB;IAEpB,0EAA0E;IAC1E,qCAAqC;IACrC,MAAM,IAAI,GAAG,qBAAqB,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;AAC9C,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\n/**\n * Prices a venue accepts around a reference price under a deviation limit\n * such as `PerpsOrderLimits.maxOraclePriceDeviation`: up to `maxDeviation`\n * times the reference away from it on either side, so a price `p` is inside\n * when `|p - reference| / reference <= maxDeviation`. HyperLiquid's rule\n * (\"Order price cannot be more than 95% away from the reference price\") and\n * `isMarketTradable` use this band. The lower bound never goes below 0.\n * Bounds are computed in exact decimals, so `1 - 0.95` is exactly 0.05.\n *\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a positive fraction.\n * @returns The inclusive band, or undefined when either input is unusable.\n */\nexport function getPriceDeviationBand(\n referencePrice: number,\n maxDeviation: number,\n): { min: number; max: number } | undefined {\n if (\n !Number.isFinite(referencePrice) ||\n referencePrice <= 0 ||\n !Number.isFinite(maxDeviation) ||\n maxDeviation <= 0\n ) {\n return undefined;\n }\n const reference = new BigNumber(referencePrice);\n const offset = reference.multipliedBy(maxDeviation);\n return {\n min: BigNumber.max(reference.minus(offset), 0).toNumber(),\n max: reference.plus(offset).toNumber(),\n };\n}\n\n/**\n * Whether a price is outside the inclusive band {@link getPriceDeviationBand}\n * returns, i.e. more than `maxDeviation` times the reference away from it.\n *\n * @param price - Order or market price.\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a fraction, such as\n * `PerpsOrderLimits.maxOraclePriceDeviation`.\n * @returns True when the price is outside the band; false when it is inside,\n * on a bound, or an input is missing, so unknown input never blocks an order.\n */\nexport function isPriceOutsideDeviationBand(\n price: number,\n referencePrice: number,\n maxDeviation: number,\n): boolean {\n // Compare with the numbers getPriceDeviationBand returns, so a price on a\n // bound it reports is always inside.\n const band = getPriceDeviationBand(referencePrice, maxDeviation);\n if (band === undefined || !Number.isFinite(price) || price <= 0) {\n return false;\n }\n return price < band.min || price > band.max;\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import type { PerpsMarketData, SortDirection
|
|
1
|
+
import type { MarketSortField, PerpsMarketData, SortDirection } from '../types/index.js';
|
|
2
2
|
export type SortMarketsParams = {
|
|
3
3
|
markets: PerpsMarketData[];
|
|
4
|
-
sortBy:
|
|
4
|
+
sortBy: MarketSortField;
|
|
5
5
|
direction?: SortDirection;
|
|
6
|
+
/** Where markets without a value for `sortBy` go: `last` (default) in either direction. */
|
|
7
|
+
missing?: 'last';
|
|
6
8
|
};
|
|
7
9
|
/**
|
|
8
10
|
* Parse a formatted volume string (e.g., "$1.5M", "$2.3B") to a numeric value.
|
|
@@ -13,12 +15,18 @@ export type SortMarketsParams = {
|
|
|
13
15
|
*/
|
|
14
16
|
export declare const parseVolume: (volumeStr: string | undefined) => number;
|
|
15
17
|
/**
|
|
16
|
-
* Sorts markets
|
|
18
|
+
* Sorts markets by an unformatted value: volume, price change, funding rate,
|
|
19
|
+
* open interest or price, or by `name`: the display symbol, case-insensitive,
|
|
20
|
+
* then the full symbol. Markets without a value for the field sort last in
|
|
21
|
+
* either direction (`missing: 'last'`, the only and default placement).
|
|
22
|
+
* Rows with `numericValues` sort on them only; their display strings are not
|
|
23
|
+
* parsed.
|
|
17
24
|
*
|
|
18
25
|
* @param options0 - The sorting configuration.
|
|
19
26
|
* @param options0.markets - The array of market data to sort.
|
|
20
|
-
* @param options0.sortBy - The field to sort by
|
|
21
|
-
* @param options0.direction - The sort direction
|
|
27
|
+
* @param options0.sortBy - The field to sort by.
|
|
28
|
+
* @param options0.direction - The sort direction: defaults to `asc` for
|
|
29
|
+
* `name` and `desc` for every other field.
|
|
22
30
|
* @returns A new sorted array of market data.
|
|
23
31
|
*/
|
|
24
32
|
export declare const sortMarkets: ({ markets, sortBy, direction, }: SortMarketsParams) => PerpsMarketData[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sortMarkets.d.ts","sourceRoot":"","sources":["../../src/utils/sortMarkets.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sortMarkets.d.ts","sourceRoot":"","sources":["../../src/utils/sortMarkets.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,eAAe,EAAE,CAAC;IAC3B,MAAM,EAAE,eAAe,CAAC;IACxB,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,2FAA2F;IAC3F,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAaF;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,cAAe,MAAM,GAAG,SAAS,KAAG,MA4B3D,CAAC;AAuDF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,WAAW,oCAMrB,iBAAiB,KAAG,eAAe,EAoBrC,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MARKET_SORTING_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
|
|
2
|
+
import { getPerpsDisplaySymbol } from '../internal/perpsDisplaySymbol.js';
|
|
2
3
|
const VOLUME_SUFFIX_REGEX = /\$?([\d.,]+)([KMBT])?/u;
|
|
3
4
|
const multipliers = {
|
|
4
5
|
K: 1e3,
|
|
@@ -38,51 +39,72 @@ export const parseVolume = (volumeStr) => {
|
|
|
38
39
|
const parsed = Number.parseFloat(cleaned);
|
|
39
40
|
return Number.isNaN(parsed) ? -1 : parsed;
|
|
40
41
|
};
|
|
42
|
+
const compareText = (first, second) => first.localeCompare(second, undefined, { sensitivity: 'base' });
|
|
43
|
+
const toFinite = (value) => value !== undefined && Number.isFinite(value) ? value : undefined;
|
|
44
|
+
const toNonNegative = (value) => value !== undefined && value >= 0 ? toFinite(value) : undefined;
|
|
45
|
+
// parseVolume reports an unreadable display string as -1.
|
|
46
|
+
const parseAmount = (display) => toNonNegative(parseVolume(display));
|
|
41
47
|
/**
|
|
42
|
-
*
|
|
48
|
+
* Unformatted value of a market row for a numeric sort field. Reads
|
|
49
|
+
* `PerpsMarketData.numericValues`. Only a row built without `numericValues`
|
|
50
|
+
* falls back to parsing its display strings: producers write placeholders such
|
|
51
|
+
* as `-100.00%`, `+0.00%` or `$0` there when a value is missing.
|
|
52
|
+
*
|
|
53
|
+
* @param market - The market row.
|
|
54
|
+
* @param sortBy - The numeric field.
|
|
55
|
+
* @returns The value, or undefined when the market has none.
|
|
56
|
+
*/
|
|
57
|
+
const getNumericSortValue = (market, sortBy) => {
|
|
58
|
+
const values = market.numericValues;
|
|
59
|
+
switch (sortBy) {
|
|
60
|
+
case MARKET_SORTING_CONFIG.SortFields.Volume:
|
|
61
|
+
return values ? toNonNegative(values.volume) : parseAmount(market.volume);
|
|
62
|
+
case MARKET_SORTING_CONFIG.SortFields.OpenInterest:
|
|
63
|
+
return values
|
|
64
|
+
? toNonNegative(values.openInterest)
|
|
65
|
+
: parseAmount(market.openInterest);
|
|
66
|
+
case MARKET_SORTING_CONFIG.SortFields.Price:
|
|
67
|
+
return values ? toNonNegative(values.price) : parseAmount(market.price);
|
|
68
|
+
case MARKET_SORTING_CONFIG.SortFields.PriceChange:
|
|
69
|
+
return toFinite(values
|
|
70
|
+
? values.change24hPercent
|
|
71
|
+
: Number.parseFloat(market.change24hPercent?.replace(/[%+]/gu, '')));
|
|
72
|
+
case MARKET_SORTING_CONFIG.SortFields.FundingRate:
|
|
73
|
+
return toFinite(market.fundingRate);
|
|
74
|
+
default:
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Sorts markets by an unformatted value: volume, price change, funding rate,
|
|
80
|
+
* open interest or price, or by `name`: the display symbol, case-insensitive,
|
|
81
|
+
* then the full symbol. Markets without a value for the field sort last in
|
|
82
|
+
* either direction (`missing: 'last'`, the only and default placement).
|
|
83
|
+
* Rows with `numericValues` sort on them only; their display strings are not
|
|
84
|
+
* parsed.
|
|
43
85
|
*
|
|
44
86
|
* @param options0 - The sorting configuration.
|
|
45
87
|
* @param options0.markets - The array of market data to sort.
|
|
46
|
-
* @param options0.sortBy - The field to sort by
|
|
47
|
-
* @param options0.direction - The sort direction
|
|
88
|
+
* @param options0.sortBy - The field to sort by.
|
|
89
|
+
* @param options0.direction - The sort direction: defaults to `asc` for
|
|
90
|
+
* `name` and `desc` for every other field.
|
|
48
91
|
* @returns A new sorted array of market data.
|
|
49
92
|
*/
|
|
50
|
-
export const sortMarkets = ({ markets, sortBy, direction = MARKET_SORTING_CONFIG.
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const changeB = parseFloat(b.change24hPercent?.replace(/[%+]/gu, '') || '0');
|
|
64
|
-
compareValue = changeA - changeB;
|
|
65
|
-
break;
|
|
66
|
-
}
|
|
67
|
-
case MARKET_SORTING_CONFIG.SortFields.FundingRate: {
|
|
68
|
-
const fundingA = a.fundingRate ?? 0;
|
|
69
|
-
const fundingB = b.fundingRate ?? 0;
|
|
70
|
-
compareValue = fundingA - fundingB;
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
case MARKET_SORTING_CONFIG.SortFields.OpenInterest: {
|
|
74
|
-
const openInterestA = parseVolume(a.openInterest);
|
|
75
|
-
const openInterestB = parseVolume(b.openInterest);
|
|
76
|
-
compareValue = openInterestA - openInterestB;
|
|
77
|
-
break;
|
|
78
|
-
}
|
|
79
|
-
default:
|
|
80
|
-
break;
|
|
93
|
+
export const sortMarkets = ({ markets, sortBy, direction = sortBy === MARKET_SORTING_CONFIG.SortFields.Name
|
|
94
|
+
? 'asc'
|
|
95
|
+
: MARKET_SORTING_CONFIG.DefaultDirection, }) => {
|
|
96
|
+
const sign = direction === MARKET_SORTING_CONFIG.DefaultDirection ? -1 : 1;
|
|
97
|
+
return [...markets].sort((a, b) => {
|
|
98
|
+
if (sortBy === MARKET_SORTING_CONFIG.SortFields.Name) {
|
|
99
|
+
return (sign *
|
|
100
|
+
(compareText(getPerpsDisplaySymbol(a.symbol), getPerpsDisplaySymbol(b.symbol)) || compareText(a.symbol, b.symbol)));
|
|
101
|
+
}
|
|
102
|
+
const valueA = getNumericSortValue(a, sortBy);
|
|
103
|
+
const valueB = getNumericSortValue(b, sortBy);
|
|
104
|
+
if (valueA === undefined || valueB === undefined) {
|
|
105
|
+
return Number(valueA === undefined) - Number(valueB === undefined);
|
|
81
106
|
}
|
|
82
|
-
return
|
|
83
|
-
? compareValue * -1
|
|
84
|
-
: compareValue;
|
|
107
|
+
return sign * (valueA - valueB);
|
|
85
108
|
});
|
|
86
|
-
return sortedMarkets;
|
|
87
109
|
};
|
|
88
110
|
//# sourceMappingURL=sortMarkets.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sortMarkets.js","sourceRoot":"","sources":["../../src/utils/sortMarkets.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,eAAe,GAChB,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"sortMarkets.js","sourceRoot":"","sources":["../../src/utils/sortMarkets.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAe1E,MAAM,mBAAmB,GAAG,wBAAwB,CAAC;AAErD,MAAM,WAAW,GAA2B;IAC1C,CAAC,EAAE,GAAG;IACN,CAAC,EAAE,GAAG;IACN,CAAC,EAAE,GAAG;IACN,CAAC,EAAE,IAAI;CACC,CAAC;AAEX,MAAM,YAAY,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,SAA6B,EAAU,EAAE;IACnE,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,CAAC,CAAC,CAAC;IACZ,CAAC;IAED,IAAI,SAAS,KAAK,eAAe,CAAC,oBAAoB,EAAE,CAAC;QACvD,OAAO,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,IAAI,SAAS,KAAK,KAAK,EAAE,CAAC;QACxB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,WAAW,GAAG,mBAAmB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACxD,IAAI,WAAW,EAAE,CAAC;QAChB,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,WAAW,CAAC;QAC3C,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC;QAE9D,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5B,OAAO,CAAC,CAAC,CAAC;QACZ,CAAC;QAED,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9D,CAAC;IAED,yCAAyC;IACzC,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAC1C,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAC5C,CAAC,CAAC;AAEF,MAAM,WAAW,GAAG,CAAC,KAAa,EAAE,MAAc,EAAU,EAAE,CAC5D,KAAK,CAAC,aAAa,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;AAElE,MAAM,QAAQ,GAAG,CAAC,KAAyB,EAAsB,EAAE,CACjE,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAEpE,MAAM,aAAa,GAAG,CAAC,KAAyB,EAAsB,EAAE,CACtE,KAAK,KAAK,SAAS,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAElE,0DAA0D;AAC1D,MAAM,WAAW,GAAG,CAAC,OAA2B,EAAsB,EAAE,CACtE,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AAEtC;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAG,CAC1B,MAAuB,EACvB,MAGC,EACmB,EAAE;IACtB,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;IACpC,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,qBAAqB,CAAC,UAAU,CAAC,MAAM;YAC1C,OAAO,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5E,KAAK,qBAAqB,CAAC,UAAU,CAAC,YAAY;YAChD,OAAO,MAAM;gBACX,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,YAAY,CAAC;gBACpC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QACvC,KAAK,qBAAqB,CAAC,UAAU,CAAC,KAAK;YACzC,OAAO,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC1E,KAAK,qBAAqB,CAAC,UAAU,CAAC,WAAW;YAC/C,OAAO,QAAQ,CACb,MAAM;gBACJ,CAAC,CAAC,MAAM,CAAC,gBAAgB;gBACzB,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,gBAAgB,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CACtE,CAAC;QACJ,KAAK,qBAAqB,CAAC,UAAU,CAAC,WAAW;YAC/C,OAAO,QAAQ,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QACtC;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,EAC1B,OAAO,EACP,MAAM,EACN,SAAS,GAAG,MAAM,KAAK,qBAAqB,CAAC,UAAU,CAAC,IAAI;IAC1D,CAAC,CAAC,KAAK;IACP,CAAC,CAAC,qBAAqB,CAAC,gBAAgB,GACxB,EAAqB,EAAE;IACzC,MAAM,IAAI,GAAG,SAAS,KAAK,qBAAqB,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3E,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QAChC,IAAI,MAAM,KAAK,qBAAqB,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO,CACL,IAAI;gBACJ,CAAC,WAAW,CACV,qBAAqB,CAAC,CAAC,CAAC,MAAM,CAAC,EAC/B,qBAAqB,CAAC,CAAC,CAAC,MAAM,CAAC,CAChC,IAAI,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CACtC,CAAC;QACJ,CAAC;QACD,MAAM,MAAM,GAAG,mBAAmB,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAC9C,MAAM,MAAM,GAAG,mBAAmB,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAC9C,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACjD,OAAO,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,GAAG,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC;QACrE,CAAC;QACD,OAAO,IAAI,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["import {\n MARKET_SORTING_CONFIG,\n PERPS_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { getPerpsDisplaySymbol } from '../internal/perpsDisplaySymbol.js';\nimport type {\n MarketSortField,\n PerpsMarketData,\n SortDirection,\n} from '../types/index.js';\n\nexport type SortMarketsParams = {\n markets: PerpsMarketData[];\n sortBy: MarketSortField;\n direction?: SortDirection;\n /** Where markets without a value for `sortBy` go: `last` (default) in either direction. */\n missing?: 'last';\n};\n\nconst VOLUME_SUFFIX_REGEX = /\\$?([\\d.,]+)([KMBT])?/u;\n\nconst multipliers: Record<string, number> = {\n K: 1e3,\n M: 1e6,\n B: 1e9,\n T: 1e12,\n} as const;\n\nconst removeCommas = (str: string): string => str.replace(/,/gu, '');\n\n/**\n * Parse a formatted volume string (e.g., \"$1.5M\", \"$2.3B\") to a numeric value.\n * Extracted from hooks/usePerpsMarkets.ts for portability.\n *\n * @param volumeStr - The formatted volume string to parse.\n * @returns The numeric volume value, or -1 if unparseable.\n */\nexport const parseVolume = (volumeStr: string | undefined): number => {\n if (!volumeStr) {\n return -1;\n }\n\n if (volumeStr === PERPS_CONSTANTS.FallbackPriceDisplay) {\n return -1;\n }\n if (volumeStr === '$<1') {\n return 0.5;\n }\n\n const suffixMatch = VOLUME_SUFFIX_REGEX.exec(volumeStr);\n if (suffixMatch) {\n const [, numberPart, suffix] = suffixMatch;\n const baseValue = Number.parseFloat(removeCommas(numberPart));\n\n if (Number.isNaN(baseValue)) {\n return -1;\n }\n\n return suffix ? baseValue * multipliers[suffix] : baseValue;\n }\n\n // Fallback: try to parse as plain number\n const cleaned = volumeStr.replace(/[$,]/gu, '');\n const parsed = Number.parseFloat(cleaned);\n return Number.isNaN(parsed) ? -1 : parsed;\n};\n\nconst compareText = (first: string, second: string): number =>\n first.localeCompare(second, undefined, { sensitivity: 'base' });\n\nconst toFinite = (value: number | undefined): number | undefined =>\n value !== undefined && Number.isFinite(value) ? value : undefined;\n\nconst toNonNegative = (value: number | undefined): number | undefined =>\n value !== undefined && value >= 0 ? toFinite(value) : undefined;\n\n// parseVolume reports an unreadable display string as -1.\nconst parseAmount = (display: string | undefined): number | undefined =>\n toNonNegative(parseVolume(display));\n\n/**\n * Unformatted value of a market row for a numeric sort field. Reads\n * `PerpsMarketData.numericValues`. Only a row built without `numericValues`\n * falls back to parsing its display strings: producers write placeholders such\n * as `-100.00%`, `+0.00%` or `$0` there when a value is missing.\n *\n * @param market - The market row.\n * @param sortBy - The numeric field.\n * @returns The value, or undefined when the market has none.\n */\nconst getNumericSortValue = (\n market: PerpsMarketData,\n sortBy: Exclude<\n MarketSortField,\n typeof MARKET_SORTING_CONFIG.SortFields.Name\n >,\n): number | undefined => {\n const values = market.numericValues;\n switch (sortBy) {\n case MARKET_SORTING_CONFIG.SortFields.Volume:\n return values ? toNonNegative(values.volume) : parseAmount(market.volume);\n case MARKET_SORTING_CONFIG.SortFields.OpenInterest:\n return values\n ? toNonNegative(values.openInterest)\n : parseAmount(market.openInterest);\n case MARKET_SORTING_CONFIG.SortFields.Price:\n return values ? toNonNegative(values.price) : parseAmount(market.price);\n case MARKET_SORTING_CONFIG.SortFields.PriceChange:\n return toFinite(\n values\n ? values.change24hPercent\n : Number.parseFloat(market.change24hPercent?.replace(/[%+]/gu, '')),\n );\n case MARKET_SORTING_CONFIG.SortFields.FundingRate:\n return toFinite(market.fundingRate);\n default:\n return undefined;\n }\n};\n\n/**\n * Sorts markets by an unformatted value: volume, price change, funding rate,\n * open interest or price, or by `name`: the display symbol, case-insensitive,\n * then the full symbol. Markets without a value for the field sort last in\n * either direction (`missing: 'last'`, the only and default placement).\n * Rows with `numericValues` sort on them only; their display strings are not\n * parsed.\n *\n * @param options0 - The sorting configuration.\n * @param options0.markets - The array of market data to sort.\n * @param options0.sortBy - The field to sort by.\n * @param options0.direction - The sort direction: defaults to `asc` for\n * `name` and `desc` for every other field.\n * @returns A new sorted array of market data.\n */\nexport const sortMarkets = ({\n markets,\n sortBy,\n direction = sortBy === MARKET_SORTING_CONFIG.SortFields.Name\n ? 'asc'\n : MARKET_SORTING_CONFIG.DefaultDirection,\n}: SortMarketsParams): PerpsMarketData[] => {\n const sign = direction === MARKET_SORTING_CONFIG.DefaultDirection ? -1 : 1;\n\n return [...markets].sort((a, b) => {\n if (sortBy === MARKET_SORTING_CONFIG.SortFields.Name) {\n return (\n sign *\n (compareText(\n getPerpsDisplaySymbol(a.symbol),\n getPerpsDisplaySymbol(b.symbol),\n ) || compareText(a.symbol, b.symbol))\n );\n }\n const valueA = getNumericSortValue(a, sortBy);\n const valueB = getNumericSortValue(b, sortBy);\n if (valueA === undefined || valueB === undefined) {\n return Number(valueA === undefined) - Number(valueB === undefined);\n }\n return sign * (valueA - valueB);\n });\n};\n"]}
|
package/docs/architecture.md
CHANGED
|
@@ -31,20 +31,20 @@ Code: `src/PerpsController.ts` `PerpsController`; `src/types/index.ts` `PerpsPro
|
|
|
31
31
|
|
|
32
32
|
## What the controller owns
|
|
33
33
|
|
|
34
|
-
| Concern | Where it lives
|
|
35
|
-
| ------------------------------------ |
|
|
36
|
-
| Order, TP/SL, close and margin math | `src/utils/orderCalculations.ts`, `tpslCalculations.ts`, `closeCalculations.ts`, `marginAdjustment.ts`, `positionProtection.ts
|
|
37
|
-
| Fee resolution | `src/services/RewardsIntegrationService.ts`, `src/utils/subscriptionFeeWaiver.ts`
|
|
38
|
-
| Advanced orders (TWAP, chase, scale) | `src/utils/advancedOrders.ts` (rules from `getOrderCapabilities().strategyRules`, validation, previews, ladder sizing, price warnings), `advancedOrderLists.ts` (live lists); actions `subscribeToLiveTwapOrders`, `subscribeToChaseOrderLists`
|
|
39
|
-
| Display formatting | `src/utils/perpsFormatters.ts`; locale number formatting injected as `marketDataFormatters`
|
|
40
|
-
| Venue adapters and validation | `src/utils/hyperLiquidAdapter.ts`, `hyperLiquidOrderBookProcessor.ts`, `hyperLiquidValidation.ts`, `marketDataTransform.ts`, `marketUtils.ts`, `sortMarkets.ts`, `idUtils.ts`, `standaloneInfoClient.ts`
|
|
41
|
-
| Request reliability | `src/utils/providerHealth.ts`, `coalescePerpsRestRequest.ts`, `guardedHyperLiquidClient.ts`
|
|
42
|
-
| Constants | `src/constants/` (`perpsConfig.ts` `PERPS_CONSTANTS`, `hyperLiquidConfig.ts`, `lighterConfig.ts` and others)
|
|
43
|
-
| Connection primitives | `PerpsController` `init`, `disconnect`, `reconnect`, `toggleTestnet`, `switchProvider`
|
|
44
|
-
| State | `PerpsControllerState`, `getDefaultPerpsControllerState`; selectors in `src/selectors.ts`
|
|
45
|
-
| Messenger events | `PerpsControllerEvents`
|
|
46
|
-
| Analytics properties | `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`, `PERPS_EVENT_VALUE`; sent through the injected `metrics`
|
|
47
|
-
| Errors | `src/perpsErrorCodes.ts`, `src/errors.ts`
|
|
34
|
+
| Concern | Where it lives |
|
|
35
|
+
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
36
|
+
| Order, TP/SL, close and margin math | `src/utils/orderCalculations.ts`, `tpslCalculations.ts`, `closeCalculations.ts`, `marginAdjustment.ts`, `positionProtection.ts`, `positionCalculations.ts` (live PnL at a price), `feeAmounts.ts`, `pricePrecision.ts`, `priceDeviation.ts` (oracle band), `orderBookGrouping.ts` and `orderBookSlippage.ts` (book grouping, spread, slippage), `orderFills.ts`, `hyperLiquidScaleOrders.ts`, `accountUtils.ts` (cross-margin tone); actions `calculateFees`, `calculateLiquidationPrice`, `calculateMaintenanceMargin` |
|
|
37
|
+
| Fee resolution | `src/services/RewardsIntegrationService.ts`, `src/utils/subscriptionFeeWaiver.ts` |
|
|
38
|
+
| Advanced orders (TWAP, chase, scale) | `src/utils/advancedOrders.ts` (rules from `getOrderCapabilities().strategyRules`, validation, previews, ladder sizing, price warnings), `advancedOrderLists.ts` (live lists); actions `subscribeToLiveTwapOrders`, `subscribeToChaseOrderLists` |
|
|
39
|
+
| Display formatting | `src/utils/perpsFormatters.ts`; locale number formatting injected as `marketDataFormatters` |
|
|
40
|
+
| Venue adapters and validation | `src/utils/hyperLiquidAdapter.ts`, `hyperLiquidOrderBookProcessor.ts`, `hyperLiquidValidation.ts`, `marketDataTransform.ts`, `marketUtils.ts`, `sortMarkets.ts`, `idUtils.ts`, `standaloneInfoClient.ts` |
|
|
41
|
+
| Request reliability | `src/utils/providerHealth.ts`, `coalescePerpsRestRequest.ts`, `guardedHyperLiquidClient.ts` |
|
|
42
|
+
| Constants | `src/constants/` (`perpsConfig.ts` `PERPS_CONSTANTS`, `hyperLiquidConfig.ts`, `lighterConfig.ts` and others) |
|
|
43
|
+
| Connection primitives | `PerpsController` `init`, `disconnect`, `reconnect`, `toggleTestnet`, `switchProvider` |
|
|
44
|
+
| State | `PerpsControllerState`, `getDefaultPerpsControllerState`; selectors in `src/selectors.ts` |
|
|
45
|
+
| Messenger events | `PerpsControllerEvents` |
|
|
46
|
+
| Analytics properties | `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`, `PERPS_EVENT_VALUE`; sent through the injected `metrics` |
|
|
47
|
+
| Errors | `src/perpsErrorCodes.ts`, `src/errors.ts` |
|
|
48
48
|
|
|
49
49
|
Code: `src/utils/`, `src/constants/`, `src/selectors.ts`, `src/PerpsController.ts` `PerpsControllerState`.
|
|
50
50
|
|
|
@@ -130,9 +130,9 @@ Code: `src/services/`; `src/PerpsController.ts` constructor.
|
|
|
130
130
|
|
|
131
131
|
Aggregated reads return the original venue rows. A market served directly from a v4 snapshot carries the provider ID that Core validated. Clients can call `groupMarketsByMarketKey(rows, defaultProvider)` for display. Rows group when they share a backend key and each explicitly has `priceScale: 1`. Each group puts the default venue first when present. Use `rowId` as the display row identity and the selected venue's `providerId` and `symbol` for charts and trading. Rows with missing keys or with missing or non-unit scales remain separate and omit `marketKey`. Saving one stores its bare symbol when it is on the legacy venue, otherwise `venue:<provider>:<symbol>`, never a backend key.
|
|
132
132
|
|
|
133
|
-
`toggleWatchlistMarket`, `isWatchlistMarket` and `recordMarketViewed` take an optional backend key from a unit-scale row. Pass the original group's `venues` as the third argument and the venue that owned saved symbols as the fourth (`legacyProvider`, default HyperLiquid, the same default as `resolveSavedPerpsMarkets`). These actions also match each tagged group row with the same backend key and `priceScale: 1` by the entry it would have saved ungrouped: its symbol on the legacy venue, otherwise `venue:<provider>:<symbol>`. A favorite or recent saved before the row grouped is replaced with the keyed entry. When opening a saved item, pass the saved strings and ungrouped venue rows to `resolveSavedPerpsMarkets`. A legacy symbol requires an exact match on its original venue and stays unresolved while that row is unavailable. A `venue:` reference opens only that venue's row with the same symbol. The resolver defaults legacy ownership to HyperLiquid and accepts the prior venue for entries saved on Lighter. New keyed entries look for unit-scale rows and prefer the configured default venue. The HyperLiquid watchlist syncs to AuthenticatedUserStorageService, where Mobile and Extension match entries by symbol, so in that mode a grouped favorite is saved by its venue symbol and keeps the backend key only as an alias. `market-key:` and `venue:` entries stay local and are never written to AUS.
|
|
133
|
+
`toggleWatchlistMarket`, `isWatchlistMarket` and `recordMarketViewed` take an optional backend key from a unit-scale row. Pass the original group's `venues` as the third argument and the venue that owned saved symbols as the fourth (`legacyProvider`, default HyperLiquid, the same default as `resolveSavedPerpsMarkets`). Redux-style clients get the same match from `selectIsWatchlistMarket(state, symbol, marketKey, venues, legacyProvider)`. Direct-mode rows from `getMarketDataWithPrices` carry the active provider as `providerId`, so a direct Lighter row saves as `venue:lighter:<symbol>` even though it never passed through the aggregator. These actions also match each tagged group row with the same backend key and `priceScale: 1` by the entry it would have saved ungrouped: its symbol on the legacy venue, otherwise `venue:<provider>:<symbol>`. A favorite or recent saved before the row grouped is replaced with the keyed entry. When opening a saved item, pass the saved strings and ungrouped venue rows to `resolveSavedPerpsMarkets`. A legacy symbol requires an exact match on its original venue and stays unresolved while that row is unavailable. A `venue:` reference opens only that venue's row with the same symbol. The resolver defaults legacy ownership to HyperLiquid and accepts the prior venue for entries saved on Lighter. New keyed entries look for unit-scale rows and prefer the configured default venue. The HyperLiquid watchlist syncs to AuthenticatedUserStorageService, where Mobile and Extension match entries by symbol, so in that mode a grouped favorite is saved by its venue symbol and keeps the backend key only as an alias. `market-key:` and `venue:` entries stay local and are never written to AUS.
|
|
134
134
|
|
|
135
|
-
With snapshots configured, a missing or expired venue
|
|
135
|
+
With snapshots configured, a missing or expired slice of a registered venue invalidates the aggregated preload. The client can fetch a fresh list from Core.
|
|
136
136
|
|
|
137
137
|
## Platform dependencies
|
|
138
138
|
|
|
@@ -161,7 +161,7 @@ Code: `src/types/index.ts` `PerpsPlatformDependencies`, `PerpsCacheInvalidator`,
|
|
|
161
161
|
|
|
162
162
|
## Messenger surface
|
|
163
163
|
|
|
164
|
-
-
|
|
164
|
+
- 148 method actions named `PerpsController:<method>`, generated into `PerpsController-method-action-types.ts` from `MESSENGER_EXPOSED_METHODS`, plus `PerpsController:getState`. Handlers are registered on the first `init()`, not in the constructor.
|
|
165
165
|
- 3 own events: `stateChange`, `stateChanged` and `chaseOrderMaxDistanceReached`.
|
|
166
166
|
- 16 allowed external actions and 3 allowed external events (`RemoteFeatureFlagController:stateChange`, `AccountsController:selectedAccountChange`, `AccountTreeController:selectedAccountGroupChange`).
|
|
167
167
|
|
|
@@ -182,7 +182,7 @@ Code: `src/PerpsController-method-action-types.ts`; `src/PerpsController.ts` `ME
|
|
|
182
182
|
|
|
183
183
|
- `startMarketDataPreload()` runs the market and user preloads in parallel at once, then every 5 minutes (`#preloadRefreshMs`).
|
|
184
184
|
- It re-runs both preloads when `isTestnet` or `hip3ConfigVersion` changes, and the user preload on `AccountsController:selectedAccountChange` and `AccountTreeController:selectedAccountGroupChange`.
|
|
185
|
-
- `#performMarketDataPreload` skips during reinitialization or when the entry is newer than `#preloadGuardMs` (30 s). It calls `getMarketDataWithPrices({ standalone: true })` and writes `cachedMarketDataByProvider[providerNetworkKey]`; aggregated mode writes one entry per provider plus an empty sentinel.
|
|
185
|
+
- `#performMarketDataPreload` skips during reinitialization or when the entry is newer than `#preloadGuardMs` (30 s). In aggregated mode it skips only while the aggregate cache is complete: every registered venue has a current slice (with a snapshot URL, HyperLiquid and, once registered, Lighter), and a slice of a venue that did not register this session is ignored. It calls `getMarketDataWithPrices({ standalone: true })` and writes `cachedMarketDataByProvider[providerNetworkKey]`; aggregated mode writes one entry per provider plus an empty sentinel.
|
|
186
186
|
- `#performUserDataPreload` needs a selected EVM address. It skips when the matching entry is newer than 30 s, or exists while the WebSocket is connected. It writes `cachedUserDataByProvider[providerNetworkKey]`.
|
|
187
187
|
- `stopMarketDataPreload()` and `disconnect()` both stop the timer and its subscriptions. After a disconnect, preload restarts only when the client calls `startMarketDataPreload()` again.
|
|
188
188
|
|
|
@@ -209,24 +209,54 @@ The controller provides the connect and disconnect primitives. The client decide
|
|
|
209
209
|
| Event | What the controller does |
|
|
210
210
|
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
211
211
|
| `init()` | Waits for any disconnect or reinitialization in flight, reuses `#initializationPromise`, runs `#performInitialization`. Up to 3 attempts, with a 1 s then a 2 s wait between them. On final failure it sets `initializationState` to `Failed` and `initializationError`, then resolves without throwing. |
|
|
212
|
-
| Data call before init | `getActiveProvider()` throws `CLIENT_REINITIALIZING`, `CLIENT_NOT_INITIALIZED` or `PROVIDER_NOT_AVAILABLE`. `subscribeTo*`
|
|
212
|
+
| Data call before init | `getActiveProvider()` throws `CLIENT_REINITIALIZING`, `CLIENT_NOT_INITIALIZED` or `PROVIDER_NOT_AVAILABLE`. `subscribeTo*` joins a pending channel that opens on the next successful init (see Streams). |
|
|
213
213
|
| `reconnect()` | Delegates to `provider.reconnect()`. HyperLiquid rebuilds its socket through `HyperLiquidClientService` (up to 10 attempts); the SDK transport also retries 5 times. |
|
|
214
214
|
| `disconnect()` | Serialised. Stops the preload timer and subscriptions, waits for init or reinit in flight, disconnects the active provider, clears it and `effectiveProvider`, retires the standalone provider, resets `isInitialized`. State caches and the feature-flag subscription stay. |
|
|
215
215
|
| Network change (`toggleTestnet`) or provider change (`switchProvider`) | `#beginReinitialization` sets `isReinitializing`, the state flips, init runs again. Failure rolls back. When preload is running it re-runs for the new key. |
|
|
216
|
-
| Account change | No reinit. User preload refreshes
|
|
216
|
+
| Account change | No reinit. User preload refreshes, the rewards address re-registers and default-account stream channels move to the new account. |
|
|
217
217
|
| HIP-3 remote flag change | `FeatureFlagConfigurationService` bumps `hip3ConfigVersion` and the preload watcher re-preloads. Providers get the new HIP-3 config on the next `init()`. |
|
|
218
218
|
|
|
219
219
|
`PERPS_CONSTANTS` carries the default timings clients use, among them `ConnectionGracePeriodMs` (20 s), `ConnectionAttemptTimeoutMs` (30 s) and `ConnectRetryDelayMs` (200 ms). The controller does not read them; each client's connection owner does.
|
|
220
220
|
|
|
221
221
|
Code: `src/PerpsController.ts` `init`, `#performInitialization`, `#beginReinitialization`, `getActiveProvider`, `reconnect`, `disconnect`, `#performDisconnect`, `toggleTestnet`, `switchProvider`; `src/services/HyperLiquidClientService.ts` `reconnect`; `src/constants/hyperLiquidConfig.ts` `HYPERLIQUID_TRANSPORT_CONFIG`; `src/constants/perpsConfig.ts` `PERPS_CONSTANTS`.
|
|
222
222
|
|
|
223
|
+
## Streams
|
|
224
|
+
|
|
225
|
+
Every `subscribeTo*` method goes through one `StreamChannelManager` (`src/services/StreamChannelManager.ts`). The public method is a thin wrapper that calls `#subscribeToChannel(stream, params, open)`; `#open<Name>` opens the venue subscription.
|
|
226
|
+
|
|
227
|
+
- One channel per key: stream name, provider instance, account (the selected one when none is given) and every other parameter except the callbacks, `onReset` and `throttleMs`. `prices` symbols are sorted, so their order does not split channels. Two subscribers with the same key share one venue subscription; the last one to leave closes it. `#getChannelKey` builds every key.
|
|
228
|
+
- A subscriber that joins an open channel gets the last value replayed (on a microtask), except event streams such as fills and public trades.
|
|
229
|
+
- `throttleMs` throttles each subscriber on its own.
|
|
230
|
+
- REST is read only while the transport is down: to seed a channel opened while disconnected, and once per drop. Nothing polls.
|
|
231
|
+
- A channel whose source fails is detached from its key: it keeps serving the subscribers it has until they leave and is never reopened, and the next subscribe on that key opens a fresh source. A reader retries after `onError` by unsubscribing and subscribing again.
|
|
232
|
+
- Channels follow the controller context (`StreamChannelManager.rebind`). When init starts, and on `disconnect`, every channel stops its source and waits under a pending provider key. After a successful init or reinitialization (`switchProvider`, `toggleTestnet`) it moves to the new provider instance and reopens; on a selected-account change, default-account channels move to the new account. A move drops the last value and calls each reader's `onReset` when there was one; the next delivery is the new context's data. A subscribe made before init joins a pending channel the same way. Unsubscribe handles stay valid throughout, so a client does not resubscribe after re-init or an account switch. In aggregated mode the channel, not `#trackProviderSubscription`, rebinds its venue subscription.
|
|
233
|
+
- `#withStreamPause` pauses a stream by name (`StreamChannelManager.pause`, ref-counted). While paused, values keep arriving and the latest is kept; when the last pause is released, pending throttled deliveries are dropped and each reader gets the latest value once. `infrastructure.streamManager.pauseChannel`/`resumeChannel` are still called for one release and are deprecated.
|
|
234
|
+
- `getStreamSnapshot(stream, params)` returns the channel's last delivered callback arguments for the same parameters a `subscribeTo*` call takes, or `undefined`. Pair it with the subscription for React's `useSyncExternalStore`.
|
|
235
|
+
- `resubscribeStreams()` stops and restarts every open channel's venue subscription, keeping readers and last values. Call it when a socket reports open but has stopped delivering, such as after an app returns to the foreground. A socket reconnect does not need it: HyperLiquid's `restoreSubscriptions` and `reopenOnReconnect` (order book, public trades) cover that.
|
|
236
|
+
- To keep data warm across screens, hold a no-op `subscribeTo*` subscription; the channel stays open while any reader holds it.
|
|
237
|
+
|
|
238
|
+
| Subscription | Initial value | Updates on |
|
|
239
|
+
| ----------------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
240
|
+
| `subscribeToMarketMeta` | Provider market list from its session cache | Each market data preload (`startMarketDataPreload`), which re-reads the venue; a delisting shows on the next preload |
|
|
241
|
+
| `subscribeToMarginAdjustmentLimits` | Computed from the live account and position streams once the market is known | Each account or position push; HyperLiquid makes no venue read |
|
|
242
|
+
| `subscribeToConnectionLatency` | Last keepalive round trip, when there is one | Each answered keepalive ping the transport already sends |
|
|
243
|
+
| `subscribeToFeeRates` | One `calculateFees` read for a taker and a maker fill | The account's own fills, account switch, default provider change, `invalidateSubscriptionBenefits` |
|
|
244
|
+
| `subscribeToTradingAgentValidity` | One read: agent resolved, then listed by the venue (`extraAgents`) | `setAgentSigner` / `clearAgentSigners`, venue rejection of the agent, account switch, one timeout at the agent's `validUntil` |
|
|
245
|
+
|
|
246
|
+
How each client consumes them:
|
|
247
|
+
|
|
248
|
+
- Mobile and Extension: their client-local `PerpsStreamManager` switches to these Core channels in their own PRs, and their per-screen polling of the same data goes away.
|
|
249
|
+
- Terminal: reads market metadata, latency, fee rates and trading-agent validity through the hooks of its `ControllerPerpsProvider`. It has no margin adjustment screen, so it does not consume `subscribeToMarginAdjustmentLimits`.
|
|
250
|
+
|
|
251
|
+
Code: `src/services/StreamChannelManager.ts`; `src/PerpsController.ts` `#subscribeToChannel`, `#getChannelKey`, `#rebindStreams`, `#withStreamPause`, `getStreamSnapshot`, `resubscribeStreams`, `ACCOUNT_STREAMS`; `src/providers/HyperLiquidProvider.ts` `subscribeToMarginAdjustmentLimits`, `subscribeToTradingAgentValidity`; `src/services/HyperLiquidClientService.ts` `subscribeToLatency`.
|
|
252
|
+
|
|
223
253
|
## What a client must do
|
|
224
254
|
|
|
225
255
|
Agreed for every client ([TAT-4656](https://consensyssoftware.atlassian.net/browse/TAT-4656)). Perps review checks each line on Mobile, Extension and Terminal. Bracketed values are the current constants.
|
|
226
256
|
|
|
227
257
|
- One owner per client decides when to call `init` and `disconnect`. Other components read state; they don't connect.
|
|
228
258
|
- Read connection timings from one config per client. It defaults to the `PERPS_CONSTANTS` timings (`ConnectionGracePeriodMs` 20 s, `ConnectionAttemptTimeoutMs` 30 s, `ConnectRetryDelayMs` 200 ms), and an override goes in that config, not in a local literal.
|
|
229
|
-
- On account change,
|
|
259
|
+
- On account change, don't resubscribe streams: default-account channels move to the new account and call `onReset`. The controller refreshes preload but does not reconnect the provider.
|
|
230
260
|
- While `initializationState` is not ready, show the loading or failed state; don't call data methods.
|
|
231
261
|
- Every `subscribeTo*` call keeps its unsubscribe and calls it on teardown.
|
|
232
262
|
|
|
@@ -236,9 +266,9 @@ Balance display must keep spendable balance, collateral and HyperLiquid account
|
|
|
236
266
|
|
|
237
267
|
| Field | Meaning | HyperLiquid value |
|
|
238
268
|
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
239
|
-
| `totalBalance` | Equity on the venue, collateral plus unrealized PnL | `marginSummary.accountValue` + spot USDC − spot hold
|
|
240
|
-
| `spendableBalance` | USD that can collateralize a new position now, with no transfer | Unified `
|
|
241
|
-
| `withdrawableBalance` | USD that can leave the venue to the external wallet | Unified `
|
|
269
|
+
| `totalBalance` | Equity on the venue, collateral plus unrealized PnL | Unified spot USDC `total`; Standard `marginSummary.accountValue` + spot USDC − spot hold |
|
|
270
|
+
| `spendableBalance` | USD that can collateralize a new position now, with no transfer | Unified spot USDC `total − hold`; Standard `withdrawable` |
|
|
271
|
+
| `withdrawableBalance` | USD that can leave the venue to the external wallet | Unified spot USDC `total − hold`; Standard `withdrawable` |
|
|
242
272
|
| `marginUsed`, `unrealizedPnl`, `returnOnEquity` | Margin and PnL summary | |
|
|
243
273
|
| `crossMarginSummary` | Optional `accountValue`, `maintenanceMargin`, `marginUsed`, `notional` | Summed across DEXs |
|
|
244
274
|
| `spotCollateral` | Optional spot USDC counted as cross collateral; pass it to `calculateAccountSummary`. Absent while spot state or abstraction mode is unknown, or when the USDC balance is malformed | `'0'` for Standard (`disabled`, `default`); free spot USDC, `max(0, total - hold)`, for Unified and portfolio margin; `'0'` on Lighter |
|
package/docs/client-contract.md
CHANGED
|
@@ -15,21 +15,21 @@ Shared answers clients used to keep their own copies of. Each one is exported fr
|
|
|
15
15
|
|
|
16
16
|
`orderLimits`:
|
|
17
17
|
|
|
18
|
-
| Field | HyperLiquid
|
|
19
|
-
| ------------------------- |
|
|
20
|
-
| `sizeDecimals` | market `szDecimals`
|
|
21
|
-
| `minOrderNotionalUsd` | per-order minimum ($10)
|
|
22
|
-
| `minOrderSize` | not reported
|
|
23
|
-
| `minimumAppliesTo` | `all_orders`
|
|
24
|
-
| `scaleOrderCount` | `SCALE_ORDER_COUNT`
|
|
25
|
-
| `twap` | `HYPERLIQUID_TWAP_LIMITS`
|
|
26
|
-
| `maxOraclePriceDeviation` | `0.95` (`
|
|
18
|
+
| Field | HyperLiquid | Lighter |
|
|
19
|
+
| ------------------------- | ------------------------------------------------------- | ------------------------- |
|
|
20
|
+
| `sizeDecimals` | market `szDecimals` | `supported_size_decimals` |
|
|
21
|
+
| `minOrderNotionalUsd` | per-order minimum ($10) | `min_quote_amount` |
|
|
22
|
+
| `minOrderSize` | not reported | `min_base_amount` |
|
|
23
|
+
| `minimumAppliesTo` | `all_orders` | `resting_limit_orders` |
|
|
24
|
+
| `scaleOrderCount` | `SCALE_ORDER_COUNT` | `SCALE_ORDER_COUNT` |
|
|
25
|
+
| `twap` | `HYPERLIQUID_TWAP_LIMITS` | not reported (no TWAP) |
|
|
26
|
+
| `maxOraclePriceDeviation` | `0.95` (`HYPERLIQUID_CONFIG.OraclePriceDeviationLimit`) | not reported |
|
|
27
27
|
|
|
28
28
|
Apply the reported minimums to the orders named by `minimumAppliesTo`. On Lighter, market and IOC orders can go down to one size step. Lighter reports `resting_limit_orders` even when maker minimums are unavailable. It omits both minimums if either is missing or invalid, if either grid is unavailable, or if the maker bounds cannot be met within the venue's wire limits. The largest base size is `(2^48 − 1) × 10^(-sizeDecimals)`, and the largest quote notional is that size times the largest wire price expressed in quote units. A valid grid remains available independently.
|
|
29
29
|
|
|
30
30
|
A verified full close can qualify for an exception to the normal minimum notional. The close must still satisfy the venue's size grid. For example, a HyperLiquid batch close refuses a position whose size rounds down to zero, with `ORDER_SIZE_POSITIVE` on that row.
|
|
31
31
|
|
|
32
|
-
Check a limit price against `maxOraclePriceDeviation` with `isPriceOutsideDeviationBand(price, oraclePrice, maxOraclePriceDeviation)`, or show the accepted range from `getPriceDeviationBand`. Skip the check when the venue omits the limit. Round a price onto the reported grid with `roundPerpsPrice({ price, pricePrecision })`: a HyperLiquid grid gives the same string as `formatHyperLiquidPrice` except that a price rounding to zero returns `undefined` rather than `'0'`, and a Lighter grid rounds the supplied decimal string half up to `tickSize`.
|
|
32
|
+
Check a limit price against `maxOraclePriceDeviation` with `isPriceOutsideDeviationBand(price, oraclePrice, maxOraclePriceDeviation)`, or show the accepted range from `getPriceDeviationBand`. Both use `|price - oracle| / oracle <= maxOraclePriceDeviation`, the same rule as `isMarketTradable` and `PriceUpdate.isTradable`, and Hyperliquid reports the limit the provider was configured with (`fallbackPriceDeviationLimit`, default `0.95`). Skip the check when the venue omits the limit. Round a price onto the reported grid with `roundPerpsPrice({ price, pricePrecision })`: a HyperLiquid grid gives the same string as `formatHyperLiquidPrice` except that a price rounding to zero returns `undefined` rather than `'0'`, and a Lighter grid rounds the supplied decimal string half up to `tickSize`.
|
|
33
33
|
|
|
34
34
|
`attachedTpslGroupLimit` (`{ takeProfit, stopLoss }`) is the most take-profit and stop-loss legs one order can attach. HyperLiquid and Lighter both report one of each.
|
|
35
35
|
|
|
@@ -44,36 +44,59 @@ For HyperLiquid markets that prohibit Cross, `getOrderCapabilities` reports `sup
|
|
|
44
44
|
- Sizes and notionals are summed per bucket (a level without a readable notional counts `price * size`); `total` and `totalNotional` are rebuilt from the best price outward.
|
|
45
45
|
- A `null` grouping only trims, for a stream the venue already aggregated.
|
|
46
46
|
|
|
47
|
-
`calculateOrderBookGroupingOptions(midPrice)` builds the grouping ladder (`ORDER_BOOK_GROUPING_CONFIG`) and `selectDefaultOrderBookGrouping(options)` picks the one a book opens at. On HyperLiquid, `calculateOrderBookAggregationParams(grouping, price)` gives the `nSigFigs`/`mantissa` to subscribe at so the venue aggregates the stream. `calculateOrderBookSpread({ bestBid, bestAsk })` returns the spread, mid and spread percent as numbers. `estimateOrderBookSlippage` sweeps the visible book for a market order's average and worst-level slippage in basis points; compare `worstSlippageBps` with the max-slippage setting for a cap check.
|
|
47
|
+
`calculateOrderBookGroupingOptions({ midPrice, tickSize, ladder })` builds the grouping ladder (`ORDER_BOOK_GROUPING_CONFIG`). With `tickSize` it is the market tick times 1, 2, 5, 10, 20 and 50, keeping widths the venue's streamed buckets divide; with a bare mid price (or `ladder: 'decade'`) it is Mobile's mid-price decade ladder. `selectDefaultOrderBookGrouping(options)` picks the one a book opens at. Pass `tickSize` as a number from `getPriceTick`, not a parsed `PerpsPricePrecision.tickSize`. The `tick` ladder filters to Hyperliquid's `nSigFigs`/`mantissa` grid, so it is for Hyperliquid books: on Lighter, which streams raw levels, use `ladder: 'decade'` or pass the raw tick widths you group client-side with `groupOrderBook`. On HyperLiquid, `calculateOrderBookAggregationParams(grouping, price)` gives the `nSigFigs`/`mantissa` to subscribe at so the venue aggregates the stream. `calculateOrderBookSpread({ bestBid, bestAsk })` returns the spread, mid and spread percent as numbers. `estimateOrderBookSlippage` sweeps the visible book for a market order's average and worst-level slippage in basis points; compare `worstSlippageBps` with the max-slippage setting for a cap check.
|
|
48
|
+
|
|
49
|
+
## Market list sorting
|
|
50
|
+
|
|
51
|
+
`sortMarkets({ markets, sortBy, direction })` sorts on `PerpsMarketData.numericValues` (unformatted price, 24h change in percent, and USD volume and open interest), not on the display strings. A row that has `numericValues` is never read from its display strings, since producers write placeholders such as `-100.00%` or `$0` there; only a row built without `numericValues` falls back to parsing them. `sortBy` is a `MarketSortField`: the `SortField` columns plus `'price'` and `'name'`; `getMarketDataWithPrices` and `applyMarketFilters` accept the same field. `direction` defaults to `'asc'` for `'name'` and `'desc'` otherwise. Markets without a value for the column sort last in either direction; `missing: 'last'` states that placement and is the only one. Lighter open interest is converted from base units to USD at the last trade price.
|
|
52
|
+
|
|
53
|
+
Clients that overlay live values on rows before sorting (Mobile's `usePerpsTopMovers` writes the live `change24hPercent`) must update `numericValues` too, or the sort ranks on the stale numbers while the row shows live ones.
|
|
54
|
+
|
|
55
|
+
`matchesCategory(market, 'memecoin')` matches a main-DEX market tagged `memecoin`, whatever its `marketType`, and never a HIP-3 market, as Mobile's `isMemecoinMarket`.
|
|
56
|
+
|
|
57
|
+
## Prices, margin tiers and account balances
|
|
58
|
+
|
|
59
|
+
- Prices: `PriceUpdate.price` is the mid, `markPrice` is the venue mark (Hyperliquid `markPx`, Lighter `mark_price`), and `oraclePrice` is the oracle/index price (Hyperliquid `oraclePx`, Lighter `index_price`). Show `markPrice` as Mark. Use `oraclePrice` for oracle deviation checks and oracle reference prices. `isTradable` already uses the oracle.
|
|
60
|
+
- Margin tiers: `MarketInfo.marginTiers` and ready `getOrderCapabilities(...).marginTiers` give Hyperliquid's tiers (`lowerBound` notional in USD, `maxLeverage`), ascending, resolved from the cached `meta`. Pass them to `estimateCrossLiquidationPrice` and the position preview helpers. Don't fetch `meta` in the client. Market lists from Terminal snapshots omit them, so read `getOrderCapabilities` for the selected market.
|
|
61
|
+
- Margin-mode lock: `getMarginModeLock({ symbol })` answers from the live position, order and TWAP streams when they are subscribed and current for the selected account, with no venue request. Otherwise it reads REST. Call it freely while the order form is open. Keep `subscribeToAvailableToTrade` open for the order form's market, and a lock from a resting order needs no venue read either.
|
|
62
|
+
- Margin adjustment: `getMarginAdjustmentLimits({ symbol })` gives the Add/Remove maxima for an isolated position. On Hyperliquid Unified accounts the venue reserves Cross margin too: `maxAdd` is spot USDC total minus every margin in use, the amount `updateIsolatedMargin` accepts. Standard accounts use the DEX's perps withdrawable. Show `maxAdd` / `maxRemove` as they are; do not use `withdrawable` or recompute. On `unavailable`, hide or disable the control: `no_isolated_position`, `account_unknown` (retry), `provider`. `account_unknown` also covers an unknown market, margin mode or position figure. `maxRemove` is `'0'` only on a confirmed strict-isolated market. `account_unknown` also covers a failed venue read (retry); `provider` means the account mode or provider has no isolated margin limits (hide the control).
|
|
63
|
+
- Market meta: `getMarketMeta({ symbol })` returns `marginTiers` (null when the venue lists no tiered table for the market, or the Hyperliquid table could not be resolved from the cached meta; use `maxLeverage` in both cases), `isDelisted`, `maxLeverage` and `onlyIsolated` (no Cross margin) from the provider's session cache, so two calls make one venue read. Omit `symbol` for every market. Don't read `meta` in the client. Through the messenger, the result is `PerpsMarketMeta | PerpsMarketMeta[]`; narrow with `Array.isArray`. In aggregated mode it reads one venue: `providerId`, else the default. An unregistered `providerId` throws `PROVIDER_NOT_FOUND`, and a failed venue read rejects; neither reports `MARKET_NOT_FOUND`.
|
|
64
|
+
- Account balances (Hyperliquid Unified): `totalBalance` is the account value hyperliquid.xyz shows (the spot USDC total, which already includes every DEX's perps account value). `spendableBalance` and `withdrawableBalance` are free USDC (total minus margin in use). On Unified accounts this is the venue's limit for adding margin to an isolated position; don't subtract position margins again. Standard accounts keep perps-plus-spot balances. On Unified, a spot read with a missing or invalid USDC `total` or `hold` keeps the perps figures. Those perps-only figures understate a Unified balance: `getAccountState({ throwOnUnavailable: true })` rejects with `ACCOUNT_STATE_FAILED` instead, and `getMarginAdjustmentLimits` returns `unavailable/account_unknown`.
|
|
65
|
+
- Account summary: pass `accountMode` from the `AccountState` to `calculateAccountSummary`. `accountMode` is set by both the stream and `getAccountState`, and absent while the mode is unknown. On a Standard account (`disabled`, `default`), account leverage is cross notional over cross account value (hyperliquid.xyz Cross Account Leverage). On Unified and Portfolio Margin, and when the mode is unknown, it is over total equity.
|
|
48
66
|
|
|
49
67
|
## Order, fee and position helpers
|
|
50
68
|
|
|
51
|
-
| Helper | Use it for
|
|
52
|
-
| ------------------------------------------------------------------------------------- |
|
|
53
|
-
| `calculateCloseSize` | Size to close for a percent or USD amount, on the venue's size grid; a full close returns the exact position size
|
|
54
|
-
| `calculateFeeNotionalUsd`, `getUndiscountedFeeRate`, `calculateUndiscountedFeeAmount` | Fee notional (a TP/SL pair uses its higher trigger price) and the fee before a MetaMask discount
|
|
55
|
-
| `isTriggerPriceOnValidSide` | Whether a stop or take-profit price sits on the side its order fires from
|
|
56
|
-
| `getOrderFillKey`, `getFillAggregationKey` | Deduplicating REST and live fills, and grouping fills into one trade
|
|
57
|
-
| `getPositionDirection` | `long` / `short` from a signed size; `undefined` for zero
|
|
58
|
-
| `normalizeHyperLiquidScalePriceLadder`, `sizeHyperLiquidScaleLadder` | A Hyperliquid scale ladder: grid prices, and rung sizes that meet a USD target (Mobile's rule) or split an exact on-grid size
|
|
59
|
-
| `recomputePositionAtPrice` | PnL, value and return on equity at a live price between account updates
|
|
60
|
-
| `CROSS_MARGIN_RATIO_THRESHOLDS`, `getCrossMarginRatioTone` | Warning and danger levels for `accountRatio`
|
|
61
|
-
| `buildProviderCacheKey` | The `provider:network` key the controller caches per-venue data under
|
|
69
|
+
| Helper | Use it for |
|
|
70
|
+
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
71
|
+
| `calculateCloseSize` | Size to close for a percent or USD amount, on the venue's size grid; a full close returns the exact position size. Pass `rounding: 'down'` for split take-profit levels so they never exceed the position; it returns `undefined` when a level rounds down to zero |
|
|
72
|
+
| `calculateFeeNotionalUsd`, `getUndiscountedFeeRate`, `calculateUndiscountedFeeAmount` | Fee notional (a TP/SL pair uses its higher trigger price) and the fee before a MetaMask discount |
|
|
73
|
+
| `isTriggerPriceOnValidSide` | Whether a stop or take-profit price sits on the side its order fires from |
|
|
74
|
+
| `getOrderFillKey`, `getFillAggregationKey` | Deduplicating REST and live fills, and grouping fills into one trade |
|
|
75
|
+
| `getPositionDirection` | `long` / `short` from a signed size; `undefined` for zero |
|
|
76
|
+
| `normalizeHyperLiquidScalePriceLadder`, `sizeHyperLiquidScaleLadder` | A Hyperliquid scale ladder: grid prices, and rung sizes that meet a USD target (Mobile's rule) or split an exact on-grid size |
|
|
77
|
+
| `recomputePositionAtPrice` | PnL, value and return on equity at a live price between account updates |
|
|
78
|
+
| `CROSS_MARGIN_RATIO_THRESHOLDS`, `getCrossMarginRatioTone` | Warning and danger levels for `accountRatio` |
|
|
79
|
+
| `buildProviderCacheKey` | The `provider:network` key the controller caches per-venue data under |
|
|
80
|
+
| `calculateAccountReturnOnEquity` | Account return on equity in percent from its totals, `ΣunrealizedPnl / ΣmarginUsed`, as REST and aggregated account states report it. The Hyperliquid account stream's `returnOnEquity` is instead the margin-weighted venue position RoE, and venue RoE is over each position's entry margin, so the two can differ |
|
|
62
81
|
|
|
63
82
|
A missing or unreadable number gives `undefined` rather than 0: the whole result for the scalar helpers, the affected fields for `estimateOrderBookSlippage`, and the position unchanged for `recomputePositionAtPrice`. `isPriceOutsideDeviationBand` fails open instead: it returns `false` for unusable input so an unknown price never blocks an order.
|
|
64
83
|
|
|
84
|
+
## Leverage display
|
|
85
|
+
|
|
86
|
+
`formatLeverage(value, options?)` renders account and position leverage with an `x` suffix, at most `PERPS_DISPLAY_PRECISION.Leverage` (2) decimals with trailing zeros dropped ("0.2x", "1.21x"). Pass `minimumFractionDigits` / `maximumFractionDigits` for a fixed precision (`{ minimumFractionDigits: 2 }` renders "0.20x", as hyperliquid.xyz; `{ minimumFractionDigits: 1, maximumFractionDigits: 1 }` matches Mobile's account summary) and `formatters` for the locale. Missing, non-finite or negative leverage renders `--`. Don't build `${leverage}x` or `toFixed` strings in the client.
|
|
87
|
+
|
|
65
88
|
## Cross-margin liquidation
|
|
66
89
|
|
|
67
90
|
Beside the isolated estimates in `hyperLiquidPositionPreview`:
|
|
68
91
|
|
|
69
92
|
- `estimateCrossMaintenanceMargin(positions)`: the maintenance margin of every cross position, `notional * mmr - deduction` at each position's tier. `null` when any notional or tier set is unknown.
|
|
70
|
-
- `estimateCrossLiquidationPrice({ isLong, markPrice, positionSize, accountValue, maintenanceMargin, marginTiers })`: the price at which cross account value reaches maintenance margin, holding other positions at their current value. Within one tier it is HyperLiquid's `mark - side * (accountValue - maintenanceMargin) / size / (1 - mmr * side)`. `null` when no positive price exists (a long that cannot be liquidated) or inputs are unknown; render it as unavailable, never as 0.
|
|
93
|
+
- `estimateCrossLiquidationPrice({ isLong, markPrice, positionSize, accountValue, maintenanceMargin, marginTiers })`: the price at which cross account value reaches maintenance margin, holding other positions at their current value. Within one tier it is HyperLiquid's `mark - side * (accountValue - maintenanceMargin) / size / (1 - mmr * side)`. `null` when no positive price exists (a long that cannot be liquidated) or inputs are unknown; render it as unavailable, never as 0. To tell a long that cannot be liquidated from unknown inputs, use `PerpsController.estimateCrossLiquidation`.
|
|
71
94
|
|
|
72
95
|
Pass tiers from `resolveHyperLiquidMarginTiers`; do not assume a default max leverage.
|
|
73
96
|
|
|
74
97
|
- `accountValue` is the cross collateral: `getCrossCollateral(crossMarginSummary, spotCollateral)`, which counts spot collateral on a unified account.
|
|
75
98
|
- For an existing position, `maintenanceMargin` is `crossMarginSummary.maintenanceMargin` (it already includes the position) or `estimateCrossMaintenanceMargin` over every cross position.
|
|
76
|
-
- For an
|
|
99
|
+
- For an order preview, call `PerpsController.estimateCrossLiquidation`; for an order on an open Cross position, `previewPositionModify` also works. Both replace the position's maintenance with the resulting position's. Keep Mobile's guard for Scale orders.
|
|
77
100
|
|
|
78
101
|
### Open position liquidation price
|
|
79
102
|
|
|
@@ -81,11 +104,13 @@ Pass tiers from `resolveHyperLiquidMarginTiers`; do not assume a default max lev
|
|
|
81
104
|
|
|
82
105
|
### Controller liquidation previews
|
|
83
106
|
|
|
84
|
-
`PerpsController.
|
|
107
|
+
`PerpsController.estimateCrossLiquidation({ symbol, direction, size, entryPrice, leverage, providerId? })` (messenger `PerpsController:estimateCrossLiquidation`) never rejects. Render `{ status: 'price', price }` as the price, `{ status: 'none', reason: 'covered_by_account' }` as no liquidation risk (N/A), and `{ status: 'unavailable', reason }` as "can't estimate": `missing_inputs` (invalid order, unknown market or tiers, an isolated position already open in that market, or the order closes the position), `account_unknown` (the account could not be read or changed during the read), `provider` (Lighter, or a Hyperliquid account mode other than Unified or Standard). Hyperliquid reads the selected wallet's position and prices an opening, add, reduce or flip of it, without the fee. Unified uses shared Cross equity and spot USDC. Standard uses the market's DEX clearinghouse; on a HIP-3 DEX it assumes placement moves margin in when the DEX's withdrawable balance is below the order's required margin and returns the excess above the 0.1 USDC buffer afterwards, only when that excess is over 0.1 USDC, as placement does.
|
|
108
|
+
|
|
109
|
+
`PerpsController.calculateLiquidationPrice` returns `Promise<string>`. For HyperLiquid Cross (`marginType: 'cross'`, `asset`, `entryPrice`, `direction`, `leverage`, positive `positionSize`) it delegates to `estimateCrossLiquidation`: `price` resolves the price, `none` resolves `'0'` (no liquidation risk, as the isolated estimate), and `unavailable` rejects with `errorCode: 'LIQUIDATION_PRICE_UNAVAILABLE'`. This replaces the old `'0.00'` sentinel on HyperLiquid. Handle the rejection as an unavailable estimate and clear any stale price for that input. Lighter rejects a Cross preview with the same code. New code should call `estimateCrossLiquidation`.
|
|
85
110
|
|
|
86
|
-
|
|
111
|
+
`previewPositionModify` on a HyperLiquid Cross position returns the same `open` / `full_close` / `none` shapes as isolated. `resulting.margin` is the resulting notional at `leverage`, and `resulting.leverage` is `leverage`. An unavailable `resulting.liquidationPrice` carries `reason: 'covered_by_account'` (render N/A) or `'missing_inputs'` (the account's Cross figures, the fee of an add or flip, or the tiers are unknown; the account holds no Cross position in that market (none, or an isolated one), or its position value is unknown). When the account read succeeds, the projection starts from the position the account holds, not the `position` passed in. Isolated previews and `current.*` omit `reason`. HyperLiquid no longer returns `reason: 'cross_margin'`.
|
|
87
112
|
|
|
88
|
-
Clients that map every `PerpsErrorCode` need entries for
|
|
113
|
+
Clients that map every `PerpsErrorCode` need entries for `ORDERS_FAILED`, `LIQUIDATION_PRICE_UNAVAILABLE` and `MARKET_NOT_FOUND` when they bump this package. Use `perps.errors.ordersFailed` for an unavailable orders read, `perps.errors.liquidationPriceUnavailable` for an unavailable estimate and `perps.errors.marketNotFound` when `getMarketMeta` finds no market with that symbol. Update Mobile's exhaustive map and Extension's map and coverage test.
|
|
89
114
|
|
|
90
115
|
## Error copy
|
|
91
116
|
|