@metamask-previews/perps-controller 25.0.0-preview-2be370e → 25.0.0-preview-c785ff081
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 +14 -6
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +71 -8
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +6 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +9 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +8 -1
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +8 -2
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +2 -2
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +8 -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/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +20 -13
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +5 -2
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +12 -2
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/types/index.d.ts +4 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +2 -13
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +5 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +9 -0
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +12 -0
- package/dist/utils/marketUtils.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/pricePrecision.d.ts +14 -2
- package/dist/utils/pricePrecision.d.ts.map +1 -1
- package/dist/utils/pricePrecision.js +31 -10
- package/dist/utils/pricePrecision.js.map +1 -1
- package/docs/architecture.md +17 -17
- package/docs/client-contract.md +14 -10
- package/docs/contracts/events.md +4 -2
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/venues/hyperliquid/trading-rules.md +2 -2
- package/docs/venues/lighter/capabilities.md +1 -1
- package/package.json +1 -1
package/dist/selectors.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SortOptionId } from './constants/perpsConfig.js';
|
|
2
2
|
import type { OrderBookPreferences, PerpsMode, ProLayoutPreferences } from './constants/perpsConfig.js';
|
|
3
3
|
import type { PerpsControllerState } from './PerpsController.js';
|
|
4
|
-
import type { MarginMode, OrderDirection, OrderType, PerpsProviderType, PerpsSelectedPaymentToken, SortDirection } from './types/index.js';
|
|
4
|
+
import type { MarginMode, OrderDirection, OrderType, PerpsMarketData, PerpsProviderType, PerpsSelectedPaymentToken, SortDirection } from './types/index.js';
|
|
5
5
|
/**
|
|
6
6
|
* Select whether the user is a first-time perps user
|
|
7
7
|
*
|
|
@@ -20,17 +20,26 @@ export declare const selectHasPlacedFirstOrder: (state: PerpsControllerState) =>
|
|
|
20
20
|
* Select watchlist markets for the current network
|
|
21
21
|
*
|
|
22
22
|
* @param state - PerpsController state
|
|
23
|
-
* @returns
|
|
23
|
+
* @returns Saved watchlist references for the current network (see
|
|
24
|
+
* `selectIsWatchlistMarket`)
|
|
24
25
|
*/
|
|
25
26
|
export declare const selectWatchlistMarkets: (state: PerpsControllerState) => string[];
|
|
26
27
|
/**
|
|
27
|
-
* Check if a
|
|
28
|
+
* Check if a market is in the watchlist on the current network. The
|
|
29
|
+
* watchlist holds saved references: a bare venue symbol, or a
|
|
30
|
+
* `market-key:` / `venue:` entry for a grouped or non-legacy-venue row. Pass
|
|
31
|
+
* the same `marketKey`, `venues` and `legacyProvider` as
|
|
32
|
+
* `PerpsController.isWatchlistMarket` to match those entries; with only a
|
|
33
|
+
* symbol this matches the bare symbol.
|
|
28
34
|
*
|
|
29
35
|
* @param state - PerpsController state
|
|
30
36
|
* @param symbol - Market symbol to check (e.g., 'BTC', 'ETH')
|
|
37
|
+
* @param marketKey - Optional cross-venue key for a grouped market.
|
|
38
|
+
* @param venues - Original rows from the group, used to match a legacy favorite.
|
|
39
|
+
* @param legacyProvider - Venue that owned saved symbols before grouping.
|
|
31
40
|
* @returns boolean indicating if market is in watchlist
|
|
32
41
|
*/
|
|
33
|
-
export declare const selectIsWatchlistMarket: (state: PerpsControllerState, symbol: string) => boolean;
|
|
42
|
+
export declare const selectIsWatchlistMarket: (state: PerpsControllerState, symbol: string, marketKey?: string, venues?: readonly PerpsMarketData[], legacyProvider?: PerpsProviderType) => boolean;
|
|
34
43
|
/**
|
|
35
44
|
* Select recently viewed markets for the current network.
|
|
36
45
|
*
|
|
@@ -39,7 +48,8 @@ export declare const selectIsWatchlistMarket: (state: PerpsControllerState, symb
|
|
|
39
48
|
* (24 hours). Returns an empty array when no qualifying entries exist.
|
|
40
49
|
*
|
|
41
50
|
* @param state - PerpsController state
|
|
42
|
-
* @returns Ordered
|
|
51
|
+
* @returns Ordered saved references of recently viewed markets; resolve
|
|
52
|
+
* them to rows with `resolveSavedPerpsMarkets`
|
|
43
53
|
*/
|
|
44
54
|
export declare const selectRecentlyViewedMarkets: (state: PerpsControllerState) => string[];
|
|
45
55
|
/**
|
package/dist/selectors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectors.d.ts","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,YAAY,EAKb,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EACV,oBAAoB,EACpB,SAAS,EACT,oBAAoB,EACrB,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"selectors.d.ts","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,YAAY,EAKb,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EACV,oBAAoB,EACpB,SAAS,EACT,oBAAoB,EACrB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjE,OAAO,KAAK,EACV,UAAU,EACV,cAAc,EACd,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,yBAAyB,EACzB,aAAa,EACd,MAAM,kBAAkB,CAAC;AAG1B;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,UACzB,oBAAoB,GAAG,SAAS,KACtC,OAKF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,UAC7B,oBAAoB,KAC1B,OAKF,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,UAC1B,oBAAoB,KAC1B,MAAM,EAKR,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB,UAC3B,oBAAoB,UACnB,MAAM,cACF,MAAM,WACT,SAAS,eAAe,EAAE,mBAClB,iBAAiB,KACjC,OAgBF,CAAC;AAEF;;;;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,UAC9B,oBAAoB,KAC1B,oBAGD,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,UAC3B,oBAAoB,KAC1B,SAAoE,CAAC;AAExE;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,UAC5B,oBAAoB,KAC1B,MAGsC,CAAC;AAE1C;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,UAAW,oBAAoB,KAAG,SAC3B,CAAC;AAEpC;;;;;;;;;GASG;AAEH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;2BAExB,oBAAoB,KAAG,OAAO,GAAG,SAAS,UAEzC,oBAAoB,SACpB,MAAM,KACZ,oBAAoB,CAAC,qBAAqB,CAAC,GAAG,SAAS,UAGjD,oBAAoB,SACpB,MAAM,eACA,iBAAiB,KAC7B,iBAAiB,GAAG,IAAI,WAElB,oBAAoB,QAAQ,MAAM,KAAG,MAAM;;;;;;;;CASvD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;2BAEjB,oBAAoB,KAAG,OAAO,GAAG,SAAS,UAEzC,oBAAoB,SACpB,MAAM,KACZ,oBAAoB,CAAC,qBAAqB,CAAC,GAAG,SAAS,UAGjD,oBAAoB,SACpB,MAAM,eACA,iBAAiB,KAC7B,iBAAiB,GAAG,IAAI,WAElB,oBAAoB,QAAQ,MAAM,KAAG,MAAM;;;;;;;;CASvD,CAAC"}
|
package/dist/selectors.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createSelector } from 'reselect';
|
|
2
2
|
import { VISIBLE_CANDLE_COUNT_CONFIG } from './constants/chartConfig.js';
|
|
3
3
|
import { MARKET_SORTING_CONFIG, PERPS_CONSTANTS, DEFAULT_ORDER_BOOK_PREFERENCES, DEFAULT_PRO_LAYOUT_PREFERENCES, DEFAULT_PERPS_MODE, DEFAULT_SELECTED_ORDER_TYPE, } from './constants/perpsConfig.js';
|
|
4
|
+
import { resolveWatchlistExchangeKey } from './PerpsController.js';
|
|
4
5
|
import { resolveTradeConfigProviderKey } from './routing/resolveTradeConfigProviderKey.js';
|
|
6
|
+
import { getPerpsWatchlistReferences } from './utils/marketUtils.js';
|
|
5
7
|
/**
|
|
6
8
|
* Select whether the user is a first-time perps user
|
|
7
9
|
*
|
|
@@ -30,7 +32,8 @@ export const selectHasPlacedFirstOrder = (state) => {
|
|
|
30
32
|
* Select watchlist markets for the current network
|
|
31
33
|
*
|
|
32
34
|
* @param state - PerpsController state
|
|
33
|
-
* @returns
|
|
35
|
+
* @returns Saved watchlist references for the current network (see
|
|
36
|
+
* `selectIsWatchlistMarket`)
|
|
34
37
|
*/
|
|
35
38
|
export const selectWatchlistMarkets = (state) => {
|
|
36
39
|
if (state?.isTestnet) {
|
|
@@ -39,15 +42,29 @@ export const selectWatchlistMarkets = (state) => {
|
|
|
39
42
|
return state?.watchlistMarkets?.mainnet ?? [];
|
|
40
43
|
};
|
|
41
44
|
/**
|
|
42
|
-
* Check if a
|
|
45
|
+
* Check if a market is in the watchlist on the current network. The
|
|
46
|
+
* watchlist holds saved references: a bare venue symbol, or a
|
|
47
|
+
* `market-key:` / `venue:` entry for a grouped or non-legacy-venue row. Pass
|
|
48
|
+
* the same `marketKey`, `venues` and `legacyProvider` as
|
|
49
|
+
* `PerpsController.isWatchlistMarket` to match those entries; with only a
|
|
50
|
+
* symbol this matches the bare symbol.
|
|
43
51
|
*
|
|
44
52
|
* @param state - PerpsController state
|
|
45
53
|
* @param symbol - Market symbol to check (e.g., 'BTC', 'ETH')
|
|
54
|
+
* @param marketKey - Optional cross-venue key for a grouped market.
|
|
55
|
+
* @param venues - Original rows from the group, used to match a legacy favorite.
|
|
56
|
+
* @param legacyProvider - Venue that owned saved symbols before grouping.
|
|
46
57
|
* @returns boolean indicating if market is in watchlist
|
|
47
58
|
*/
|
|
48
|
-
export const selectIsWatchlistMarket = (state, symbol) => {
|
|
59
|
+
export const selectIsWatchlistMarket = (state, symbol, marketKey, venues, legacyProvider) => {
|
|
49
60
|
const watchlist = selectWatchlistMarkets(state);
|
|
50
|
-
|
|
61
|
+
const references = getPerpsWatchlistReferences(symbol, marketKey, venues, legacyProvider);
|
|
62
|
+
// Same alias as the controller: an AUS-synced watchlist saves the venue
|
|
63
|
+
// symbol for a grouped favorite.
|
|
64
|
+
if (marketKey && resolveWatchlistExchangeKey(state.activeProvider)) {
|
|
65
|
+
references.push(getPerpsWatchlistReferences(symbol, undefined, venues, legacyProvider)[0]);
|
|
66
|
+
}
|
|
67
|
+
return references.some((reference) => watchlist.includes(reference));
|
|
51
68
|
};
|
|
52
69
|
/**
|
|
53
70
|
* Select recently viewed markets for the current network.
|
|
@@ -57,7 +74,8 @@ export const selectIsWatchlistMarket = (state, symbol) => {
|
|
|
57
74
|
* (24 hours). Returns an empty array when no qualifying entries exist.
|
|
58
75
|
*
|
|
59
76
|
* @param state - PerpsController state
|
|
60
|
-
* @returns Ordered
|
|
77
|
+
* @returns Ordered saved references of recently viewed markets; resolve
|
|
78
|
+
* them to rows with `resolveSavedPerpsMarkets`
|
|
61
79
|
*/
|
|
62
80
|
export const selectRecentlyViewedMarkets = (state) => {
|
|
63
81
|
const network = state?.isTestnet ? 'testnet' : 'mainnet';
|
package/dist/selectors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectors.js","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EACL,qBAAqB,EACrB,eAAe,EAEf,8BAA8B,EAC9B,8BAA8B,EAC9B,kBAAkB,EAClB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAU3F;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,KAAuC,E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AC,EAAE,iBAAiB,CAAC;AACnE,CAAC,CACF,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAC5C;IACE,CAAC,KAA2B,EAAuB,EAAE,CAAC,KAAK,EAAE,SAAS;IACtE,CACE,KAA2B,EAC3B,KAAa,EAC4C,EAAE,CAC3D,KAAK,EAAE,mBAAmB;IAC5B,CACE,KAA2B,EAC3B,KAAa,EACb,UAA8B,EACJ,EAAE,CAC5B,6BAA6B,CAAC,KAAK,EAAE,UAAU,CAAC;IAClD,CAAC,MAA4B,EAAE,IAAY,EAAU,EAAE,CAAC,IAAI;CAC7D,EACD,CAAC,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAA0B,EAAE;IAC7D,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IAClD,OAAO,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;AAC5D,CAAC,CACF,CAAC","sourcesContent":["import { createSelector } from 'reselect';\n\nimport { VISIBLE_CANDLE_COUNT_CONFIG } from './constants/chartConfig.js';\nimport {\n MARKET_SORTING_CONFIG,\n PERPS_CONSTANTS,\n SortOptionId,\n DEFAULT_ORDER_BOOK_PREFERENCES,\n DEFAULT_PRO_LAYOUT_PREFERENCES,\n DEFAULT_PERPS_MODE,\n DEFAULT_SELECTED_ORDER_TYPE,\n} from './constants/perpsConfig.js';\nimport type {\n OrderBookPreferences,\n PerpsMode,\n ProLayoutPreferences,\n} from './constants/perpsConfig.js';\nimport type { PerpsControllerState } from './PerpsController.js';\nimport { resolveTradeConfigProviderKey } from './routing/resolveTradeConfigProviderKey.js';\nimport type {\n MarginMode,\n OrderDirection,\n OrderType,\n PerpsProviderType,\n PerpsSelectedPaymentToken,\n SortDirection,\n} from './types/index.js';\n\n/**\n * Select whether the user is a first-time perps user\n *\n * @param state - PerpsController state\n * @returns true if user is first-time, false otherwise\n */\nexport const selectIsFirstTimeUser = (\n state: PerpsControllerState | undefined,\n): boolean => {\n if (state?.isTestnet) {\n return state?.isFirstTimeUser?.testnet ?? true;\n }\n return state?.isFirstTimeUser?.mainnet ?? true;\n};\n\n/**\n * Select whether user has ever placed their first successful order\n *\n * @param state - PerpsController state\n * @returns boolean indicating if first order was placed\n */\nexport const selectHasPlacedFirstOrder = (\n state: PerpsControllerState,\n): boolean => {\n if (state?.isTestnet) {\n return state?.hasPlacedFirstOrder?.testnet ?? false;\n }\n return state?.hasPlacedFirstOrder?.mainnet ?? false;\n};\n\n/**\n * Select watchlist markets for the current network\n *\n * @param state - PerpsController state\n * @returns Array of watchlist market symbols for current network\n */\nexport const selectWatchlistMarkets = (\n state: PerpsControllerState,\n): string[] => {\n if (state?.isTestnet) {\n return state?.watchlistMarkets?.testnet ?? [];\n }\n return state?.watchlistMarkets?.mainnet ?? [];\n};\n\n/**\n * Check if a specific market is in the watchlist on the current network\n *\n * @param state - PerpsController state\n * @param symbol - Market symbol to check (e.g., 'BTC', 'ETH')\n * @returns boolean indicating if market is in watchlist\n */\nexport const selectIsWatchlistMarket = (\n state: PerpsControllerState,\n symbol: string,\n): boolean => {\n const watchlist = selectWatchlistMarkets(state);\n return watchlist.includes(symbol);\n};\n\n/**\n * Select recently viewed markets for the current network.\n *\n * Returns up to PERPS_CONSTANTS.RecentlyViewedMarketsLimit symbols, ordered\n * newest-first, filtered to entries within PERPS_CONSTANTS.RecentlyViewedMarketsTtlMs\n * (24 hours). Returns an empty array when no qualifying entries exist.\n *\n * @param state - PerpsController state\n * @returns Ordered array of recently viewed market symbols\n */\nexport const selectRecentlyViewedMarkets = (\n state: PerpsControllerState,\n): string[] => {\n const network = state?.isTestnet ? 'testnet' : 'mainnet';\n const entries = state?.recentlyViewedMarkets?.[network] ?? [];\n const cutoff = Date.now() - PERPS_CONSTANTS.RecentlyViewedMarketsTtlMs;\n\n return entries\n .filter((entry) => entry.viewedAt > cutoff)\n .map((entry) => entry.symbol)\n .slice(0, PERPS_CONSTANTS.RecentlyViewedMarketsLimit);\n};\n\n/**\n * Select trade configuration for a specific market on the current network.\n * Uses memoization to return stable object references and prevent unnecessary re-renders.\n *\n * Usage: selectTradeConfiguration(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional venue the configuration was saved for. Defaults\n * to the live effective venue (active/saved default before initialization).\n * @returns The trade configuration for the specified market, or undefined.\n */\n\nexport const selectTradeConfiguration = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): { leverage?: number } | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n const config = configs?.[network]?.[provider]?.[coin];\n\n if (!config?.leverage) {\n return undefined;\n }\n\n return { leverage: config.leverage };\n },\n);\n\n/**\n * Pending trade configuration as returned to consumers (timestamp stripped).\n */\ntype PendingTradeConfiguration = {\n amount?: string;\n leverage?: number;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n limitPrice?: string;\n orderType?: OrderType;\n reduceOnly?: boolean;\n direction?: OrderDirection;\n selectedPaymentToken?: PerpsSelectedPaymentToken | null;\n};\n\n/**\n * Memoized extractor for the raw pending trade configuration of a market.\n *\n * Keyed on `isTestnet`, `tradeConfigurations`, and `coin` so it yields a stable\n * object reference (both the stripped `config` and its `timestamp`) while those\n * inputs are unchanged. The TTL is deliberately NOT evaluated here: because the\n * result is memoized, evaluating expiry inside this selector would freeze the\n * `Date.now()` check between input changes. Expiry is applied per-call by\n * `selectPendingTradeConfiguration` instead.\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @returns The stripped config and its save timestamp, or undefined.\n */\n\nconst selectRawPendingTradeConfiguration = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (\n isTestnet,\n configs,\n provider,\n coin,\n ): { timestamp: number; config: PendingTradeConfiguration } | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n const config = configs?.[network]?.[provider]?.[coin]?.pendingConfig;\n\n if (!config) {\n return undefined;\n }\n\n const { timestamp, ...configWithoutTimestamp } = config;\n return { timestamp, config: configWithoutTimestamp };\n },\n);\n\n/**\n * Select pending trade configuration for a specific market on the current network.\n * Returns undefined if config doesn't exist or has expired.\n *\n * The underlying data extraction is memoized for stable object references, but\n * the TTL is checked on every call (using `Date.now()`) so expiry stays accurate\n * even when the memoized inputs have not changed. This mirrors\n * `PerpsController.getPendingTradeConfiguration`, which also evaluates time on\n * every call.\n *\n * Usage: selectPendingTradeConfiguration(state, coin)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional venue the configuration was saved for. Defaults\n * to the live effective venue (active/saved default before initialization).\n * @returns The pending trade configuration, or undefined if expired or not found.\n */\nexport const selectPendingTradeConfiguration = (\n state: PerpsControllerState,\n coin: string,\n providerId?: PerpsProviderType,\n): PendingTradeConfiguration | undefined => {\n const raw = selectRawPendingTradeConfiguration(state, coin, providerId);\n\n if (!raw) {\n return undefined;\n }\n\n const age = Date.now() - raw.timestamp;\n\n if (age > PERPS_CONSTANTS.PendingTradeConfigurationTtlMs) {\n // Config expired, return undefined\n return undefined;\n }\n\n return raw.config;\n};\n\n/**\n * Select market filter preferences (network-independent)\n *\n * @param state - PerpsController state\n * @returns Sort/filter preferences object with optionId and direction\n */\nexport const selectMarketFilterPreferences = (\n state: PerpsControllerState,\n): { optionId: SortOptionId; direction: SortDirection } => {\n const pref = state?.marketFilterPreferences;\n\n // Handle legacy string format (backward compatibility)\n if (typeof pref === 'string') {\n // Map legacy compound IDs to new format\n // Old format: 'priceChange-desc' or 'priceChange-asc'\n // New format: { optionId: 'priceChange', direction: 'desc'/'asc' }\n if (pref === 'priceChange-desc') {\n return {\n optionId: 'priceChange',\n direction: 'desc',\n };\n }\n if (pref === 'priceChange-asc') {\n return {\n optionId: 'priceChange',\n direction: 'asc',\n };\n }\n\n // Handle other simple legacy strings (e.g., 'volume', 'openInterest', etc.)\n return {\n optionId: pref,\n direction: MARKET_SORTING_CONFIG.DefaultDirection,\n };\n }\n\n // Return new object format or default\n return (\n pref ?? {\n optionId: MARKET_SORTING_CONFIG.DefaultSortOptionId,\n direction: MARKET_SORTING_CONFIG.DefaultDirection,\n }\n );\n};\n\n/**\n * Select pro-mode layout preferences (network-independent).\n *\n * Merges over defaults so callers always receive a fully-populated object,\n * even when the state slice (or a nested field) is missing.\n *\n * @param state - PerpsController state\n * @returns The pro-mode layout preferences object\n */\nexport const selectProLayoutPreferences = (\n state: PerpsControllerState,\n): ProLayoutPreferences => ({\n ...DEFAULT_PRO_LAYOUT_PREFERENCES,\n ...state?.proLayoutPreferences,\n});\n\n/**\n * Select market-agnostic Pro order-book display preferences.\n *\n * @param state - PerpsController state\n * @returns The order-book display preferences\n */\nexport const selectOrderBookPreferences = (\n state: PerpsControllerState,\n): OrderBookPreferences => ({\n ...DEFAULT_ORDER_BOOK_PREFERENCES,\n ...state?.orderBookPreferences,\n});\n\n/**\n * Select the market-agnostic order type.\n *\n * @param state - PerpsController state\n * @returns The selected order type\n */\nexport const selectSelectedOrderType = (\n state: PerpsControllerState,\n): OrderType => state?.selectedOrderType ?? DEFAULT_SELECTED_ORDER_TYPE;\n\n/**\n * Select the visible candle count shared by Lite and Pro.\n *\n * @param state - PerpsController state\n * @returns The visible candle count\n */\nexport const selectVisibleCandleCount = (\n state: PerpsControllerState,\n): number =>\n Number.isFinite(state?.visibleCandleCount)\n ? state.visibleCandleCount\n : VISIBLE_CANDLE_COUNT_CONFIG.Default;\n\n/**\n * Select the current Perps interface mode (lite/pro).\n *\n * Falls back to the default mode when the state slice is missing.\n *\n * @param state - PerpsController state\n * @returns The current Perps mode\n */\nexport const selectPerpsMode = (state: PerpsControllerState): PerpsMode =>\n state?.mode ?? DEFAULT_PERPS_MODE;\n\n/**\n * Select order book grouping for a specific market on the current network.\n *\n * Usage: selectOrderBookGrouping(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional explicit venue; otherwise uses the effective venue.\n * @returns The order book grouping value, or undefined.\n */\n\nexport const selectOrderBookGrouping = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): number | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n return configs?.[network]?.[provider]?.[coin]?.orderBookGrouping;\n },\n);\n\n/**\n * Select the saved margin mode for a specific market on the current network.\n *\n * Usage: selectMarginMode(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional explicit venue; otherwise uses the effective venue.\n * @returns The saved margin mode, or undefined.\n */\nexport const selectMarginMode = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): MarginMode | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n return configs?.[network]?.[provider]?.[coin]?.marginMode;\n },\n);\n"]}
|
|
1
|
+
{"version":3,"file":"selectors.js","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EACL,qBAAqB,EACrB,eAAe,EAEf,8BAA8B,EAC9B,8BAA8B,EAC9B,kBAAkB,EAClB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AAMpC,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAU3F,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAErE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,KAAuC,EAC9B,EAAE;IACX,IAAI,KAAK,EAAE,SAAS,EAAE,CAAC;QACrB,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,IAAI,IAAI,CAAC;IACjD,CAAC;IACD,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,IAAI,IAAI,CAAC;AACjD,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CACvC,KAA2B,EAClB,EAAE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AO,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IAClD,OAAO,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,iBAAiB,CAAC;AACnE,CAAC,CACF,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAC5C;IACE,CAAC,KAA2B,EAAuB,EAAE,CAAC,KAAK,EAAE,SAAS;IACtE,CACE,KAA2B,EAC3B,KAAa,EAC4C,EAAE,CAC3D,KAAK,EAAE,mBAAmB;IAC5B,CACE,KAA2B,EAC3B,KAAa,EACb,UAA8B,EACJ,EAAE,CAC5B,6BAA6B,CAAC,KAAK,EAAE,UAAU,CAAC;IAClD,CAAC,MAA4B,EAAE,IAAY,EAAU,EAAE,CAAC,IAAI;CAC7D,EACD,CAAC,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAA0B,EAAE;IAC7D,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IAClD,OAAO,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;AAC5D,CAAC,CACF,CAAC","sourcesContent":["import { createSelector } from 'reselect';\n\nimport { VISIBLE_CANDLE_COUNT_CONFIG } from './constants/chartConfig.js';\nimport {\n MARKET_SORTING_CONFIG,\n PERPS_CONSTANTS,\n SortOptionId,\n DEFAULT_ORDER_BOOK_PREFERENCES,\n DEFAULT_PRO_LAYOUT_PREFERENCES,\n DEFAULT_PERPS_MODE,\n DEFAULT_SELECTED_ORDER_TYPE,\n} from './constants/perpsConfig.js';\nimport type {\n OrderBookPreferences,\n PerpsMode,\n ProLayoutPreferences,\n} from './constants/perpsConfig.js';\nimport { resolveWatchlistExchangeKey } from './PerpsController.js';\nimport type { PerpsControllerState } from './PerpsController.js';\nimport { resolveTradeConfigProviderKey } from './routing/resolveTradeConfigProviderKey.js';\nimport type {\n MarginMode,\n OrderDirection,\n OrderType,\n PerpsMarketData,\n PerpsProviderType,\n PerpsSelectedPaymentToken,\n SortDirection,\n} from './types/index.js';\nimport { getPerpsWatchlistReferences } from './utils/marketUtils.js';\n\n/**\n * Select whether the user is a first-time perps user\n *\n * @param state - PerpsController state\n * @returns true if user is first-time, false otherwise\n */\nexport const selectIsFirstTimeUser = (\n state: PerpsControllerState | undefined,\n): boolean => {\n if (state?.isTestnet) {\n return state?.isFirstTimeUser?.testnet ?? true;\n }\n return state?.isFirstTimeUser?.mainnet ?? true;\n};\n\n/**\n * Select whether user has ever placed their first successful order\n *\n * @param state - PerpsController state\n * @returns boolean indicating if first order was placed\n */\nexport const selectHasPlacedFirstOrder = (\n state: PerpsControllerState,\n): boolean => {\n if (state?.isTestnet) {\n return state?.hasPlacedFirstOrder?.testnet ?? false;\n }\n return state?.hasPlacedFirstOrder?.mainnet ?? false;\n};\n\n/**\n * Select watchlist markets for the current network\n *\n * @param state - PerpsController state\n * @returns Saved watchlist references for the current network (see\n * `selectIsWatchlistMarket`)\n */\nexport const selectWatchlistMarkets = (\n state: PerpsControllerState,\n): string[] => {\n if (state?.isTestnet) {\n return state?.watchlistMarkets?.testnet ?? [];\n }\n return state?.watchlistMarkets?.mainnet ?? [];\n};\n\n/**\n * Check if a market is in the watchlist on the current network. The\n * watchlist holds saved references: a bare venue symbol, or a\n * `market-key:` / `venue:` entry for a grouped or non-legacy-venue row. Pass\n * the same `marketKey`, `venues` and `legacyProvider` as\n * `PerpsController.isWatchlistMarket` to match those entries; with only a\n * symbol this matches the bare symbol.\n *\n * @param state - PerpsController state\n * @param symbol - Market symbol to check (e.g., 'BTC', 'ETH')\n * @param marketKey - Optional cross-venue key for a grouped market.\n * @param venues - Original rows from the group, used to match a legacy favorite.\n * @param legacyProvider - Venue that owned saved symbols before grouping.\n * @returns boolean indicating if market is in watchlist\n */\nexport const selectIsWatchlistMarket = (\n state: PerpsControllerState,\n symbol: string,\n marketKey?: string,\n venues?: readonly PerpsMarketData[],\n legacyProvider?: PerpsProviderType,\n): boolean => {\n const watchlist = selectWatchlistMarkets(state);\n const references = getPerpsWatchlistReferences(\n symbol,\n marketKey,\n venues,\n legacyProvider,\n );\n // Same alias as the controller: an AUS-synced watchlist saves the venue\n // symbol for a grouped favorite.\n if (marketKey && resolveWatchlistExchangeKey(state.activeProvider)) {\n references.push(\n getPerpsWatchlistReferences(symbol, undefined, venues, legacyProvider)[0],\n );\n }\n return references.some((reference) => watchlist.includes(reference));\n};\n\n/**\n * Select recently viewed markets for the current network.\n *\n * Returns up to PERPS_CONSTANTS.RecentlyViewedMarketsLimit symbols, ordered\n * newest-first, filtered to entries within PERPS_CONSTANTS.RecentlyViewedMarketsTtlMs\n * (24 hours). Returns an empty array when no qualifying entries exist.\n *\n * @param state - PerpsController state\n * @returns Ordered saved references of recently viewed markets; resolve\n * them to rows with `resolveSavedPerpsMarkets`\n */\nexport const selectRecentlyViewedMarkets = (\n state: PerpsControllerState,\n): string[] => {\n const network = state?.isTestnet ? 'testnet' : 'mainnet';\n const entries = state?.recentlyViewedMarkets?.[network] ?? [];\n const cutoff = Date.now() - PERPS_CONSTANTS.RecentlyViewedMarketsTtlMs;\n\n return entries\n .filter((entry) => entry.viewedAt > cutoff)\n .map((entry) => entry.symbol)\n .slice(0, PERPS_CONSTANTS.RecentlyViewedMarketsLimit);\n};\n\n/**\n * Select trade configuration for a specific market on the current network.\n * Uses memoization to return stable object references and prevent unnecessary re-renders.\n *\n * Usage: selectTradeConfiguration(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional venue the configuration was saved for. Defaults\n * to the live effective venue (active/saved default before initialization).\n * @returns The trade configuration for the specified market, or undefined.\n */\n\nexport const selectTradeConfiguration = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): { leverage?: number } | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n const config = configs?.[network]?.[provider]?.[coin];\n\n if (!config?.leverage) {\n return undefined;\n }\n\n return { leverage: config.leverage };\n },\n);\n\n/**\n * Pending trade configuration as returned to consumers (timestamp stripped).\n */\ntype PendingTradeConfiguration = {\n amount?: string;\n leverage?: number;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n limitPrice?: string;\n orderType?: OrderType;\n reduceOnly?: boolean;\n direction?: OrderDirection;\n selectedPaymentToken?: PerpsSelectedPaymentToken | null;\n};\n\n/**\n * Memoized extractor for the raw pending trade configuration of a market.\n *\n * Keyed on `isTestnet`, `tradeConfigurations`, and `coin` so it yields a stable\n * object reference (both the stripped `config` and its `timestamp`) while those\n * inputs are unchanged. The TTL is deliberately NOT evaluated here: because the\n * result is memoized, evaluating expiry inside this selector would freeze the\n * `Date.now()` check between input changes. Expiry is applied per-call by\n * `selectPendingTradeConfiguration` instead.\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @returns The stripped config and its save timestamp, or undefined.\n */\n\nconst selectRawPendingTradeConfiguration = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (\n isTestnet,\n configs,\n provider,\n coin,\n ): { timestamp: number; config: PendingTradeConfiguration } | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n const config = configs?.[network]?.[provider]?.[coin]?.pendingConfig;\n\n if (!config) {\n return undefined;\n }\n\n const { timestamp, ...configWithoutTimestamp } = config;\n return { timestamp, config: configWithoutTimestamp };\n },\n);\n\n/**\n * Select pending trade configuration for a specific market on the current network.\n * Returns undefined if config doesn't exist or has expired.\n *\n * The underlying data extraction is memoized for stable object references, but\n * the TTL is checked on every call (using `Date.now()`) so expiry stays accurate\n * even when the memoized inputs have not changed. This mirrors\n * `PerpsController.getPendingTradeConfiguration`, which also evaluates time on\n * every call.\n *\n * Usage: selectPendingTradeConfiguration(state, coin)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional venue the configuration was saved for. Defaults\n * to the live effective venue (active/saved default before initialization).\n * @returns The pending trade configuration, or undefined if expired or not found.\n */\nexport const selectPendingTradeConfiguration = (\n state: PerpsControllerState,\n coin: string,\n providerId?: PerpsProviderType,\n): PendingTradeConfiguration | undefined => {\n const raw = selectRawPendingTradeConfiguration(state, coin, providerId);\n\n if (!raw) {\n return undefined;\n }\n\n const age = Date.now() - raw.timestamp;\n\n if (age > PERPS_CONSTANTS.PendingTradeConfigurationTtlMs) {\n // Config expired, return undefined\n return undefined;\n }\n\n return raw.config;\n};\n\n/**\n * Select market filter preferences (network-independent)\n *\n * @param state - PerpsController state\n * @returns Sort/filter preferences object with optionId and direction\n */\nexport const selectMarketFilterPreferences = (\n state: PerpsControllerState,\n): { optionId: SortOptionId; direction: SortDirection } => {\n const pref = state?.marketFilterPreferences;\n\n // Handle legacy string format (backward compatibility)\n if (typeof pref === 'string') {\n // Map legacy compound IDs to new format\n // Old format: 'priceChange-desc' or 'priceChange-asc'\n // New format: { optionId: 'priceChange', direction: 'desc'/'asc' }\n if (pref === 'priceChange-desc') {\n return {\n optionId: 'priceChange',\n direction: 'desc',\n };\n }\n if (pref === 'priceChange-asc') {\n return {\n optionId: 'priceChange',\n direction: 'asc',\n };\n }\n\n // Handle other simple legacy strings (e.g., 'volume', 'openInterest', etc.)\n return {\n optionId: pref,\n direction: MARKET_SORTING_CONFIG.DefaultDirection,\n };\n }\n\n // Return new object format or default\n return (\n pref ?? {\n optionId: MARKET_SORTING_CONFIG.DefaultSortOptionId,\n direction: MARKET_SORTING_CONFIG.DefaultDirection,\n }\n );\n};\n\n/**\n * Select pro-mode layout preferences (network-independent).\n *\n * Merges over defaults so callers always receive a fully-populated object,\n * even when the state slice (or a nested field) is missing.\n *\n * @param state - PerpsController state\n * @returns The pro-mode layout preferences object\n */\nexport const selectProLayoutPreferences = (\n state: PerpsControllerState,\n): ProLayoutPreferences => ({\n ...DEFAULT_PRO_LAYOUT_PREFERENCES,\n ...state?.proLayoutPreferences,\n});\n\n/**\n * Select market-agnostic Pro order-book display preferences.\n *\n * @param state - PerpsController state\n * @returns The order-book display preferences\n */\nexport const selectOrderBookPreferences = (\n state: PerpsControllerState,\n): OrderBookPreferences => ({\n ...DEFAULT_ORDER_BOOK_PREFERENCES,\n ...state?.orderBookPreferences,\n});\n\n/**\n * Select the market-agnostic order type.\n *\n * @param state - PerpsController state\n * @returns The selected order type\n */\nexport const selectSelectedOrderType = (\n state: PerpsControllerState,\n): OrderType => state?.selectedOrderType ?? DEFAULT_SELECTED_ORDER_TYPE;\n\n/**\n * Select the visible candle count shared by Lite and Pro.\n *\n * @param state - PerpsController state\n * @returns The visible candle count\n */\nexport const selectVisibleCandleCount = (\n state: PerpsControllerState,\n): number =>\n Number.isFinite(state?.visibleCandleCount)\n ? state.visibleCandleCount\n : VISIBLE_CANDLE_COUNT_CONFIG.Default;\n\n/**\n * Select the current Perps interface mode (lite/pro).\n *\n * Falls back to the default mode when the state slice is missing.\n *\n * @param state - PerpsController state\n * @returns The current Perps mode\n */\nexport const selectPerpsMode = (state: PerpsControllerState): PerpsMode =>\n state?.mode ?? DEFAULT_PERPS_MODE;\n\n/**\n * Select order book grouping for a specific market on the current network.\n *\n * Usage: selectOrderBookGrouping(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional explicit venue; otherwise uses the effective venue.\n * @returns The order book grouping value, or undefined.\n */\n\nexport const selectOrderBookGrouping = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): number | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n return configs?.[network]?.[provider]?.[coin]?.orderBookGrouping;\n },\n);\n\n/**\n * Select the saved margin mode for a specific market on the current network.\n *\n * Usage: selectMarginMode(state, coin, providerId?)\n *\n * @param state - The perps controller state.\n * @param coin - The market coin symbol.\n * @param providerId - Optional explicit venue; otherwise uses the effective venue.\n * @returns The saved margin mode, or undefined.\n */\nexport const selectMarginMode = createSelector(\n [\n (state: PerpsControllerState): boolean | undefined => state?.isTestnet,\n (\n state: PerpsControllerState,\n _coin: string,\n ): PerpsControllerState['tradeConfigurations'] | undefined =>\n state?.tradeConfigurations,\n (\n state: PerpsControllerState,\n _coin: string,\n providerId?: PerpsProviderType,\n ): PerpsProviderType | null =>\n resolveTradeConfigProviderKey(state, providerId),\n (_state: PerpsControllerState, coin: string): string => coin,\n ],\n (isTestnet, configs, provider, coin): MarginMode | undefined => {\n if (provider === null) {\n return undefined;\n }\n const network = isTestnet ? 'testnet' : 'mainnet';\n return configs?.[network]?.[provider]?.[coin]?.marginMode;\n },\n);\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AggregatedOrderBookConnection.d.ts","sourceRoot":"","sources":["../../src/services/AggregatedOrderBookConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"AggregatedOrderBookConnection.d.ts","sourceRoot":"","sources":["../../src/services/AggregatedOrderBookConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGvD;;;;GAIG;AACH,KAAK,sBAAsB,GAAG;IAC5B,aAAa;IACb,EAAE,EAAE,MAAM,CAAC;IACX,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,mCAAmC;IACnC,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AAEF,gEAAgE;AAChE,KAAK,sBAAsB,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,CAAC,IAAI,EAAE,sBAAsB,EAAE,EAAE,IAAI,EAAE,sBAAsB,EAAE,CAAC,CAAC;IACzE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,yBAAyB,GAAG,YAAY,GAAG,WAAW,GAAG,OAAO,CAAC;AAE7E,MAAM,MAAM,kCAAkC,GAAG;IAC/C,kCAAkC;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,QAAQ,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,gDAAgD;IAChD,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACjB,4CAA4C;IAC5C,QAAQ,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;IACxC,2DAA2D;IAC3D,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,IAAI,CAAC;CAC9D,CAAC;AAEF,MAAM,MAAM,oCAAoC,GAAG;IACjD,sDAAsD;IACtD,SAAS,EAAE,MAAM,OAAO,CAAC;CAC1B,CAAC;AAMF;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,EAAE,sBAAsB,EAC5B,MAAM,EAAE,MAAM,GACb,aAAa,CAqDf;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,6BAA6B;;IA8BxC,YAAY,EAAE,SAAS,EAAE,EAAE,oCAAoC,EAE9D;IAED;;;;;;;;;;;;;;;OAeG;IACH,SAAS,CAAC,MAAM,EAAE,kCAAkC,GAAG,MAAM,IAAI,CAuNhE;IAED,+DAA+D;IAC/D,KAAK,IAAI,IAAI,CAEZ;CAgEF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SubscriptionClient, WebSocketTransport } from '@nktkas/hyperliquid';
|
|
2
2
|
import { HYPERLIQUID_TRANSPORT_CONFIG } from '../constants/hyperLiquidConfig.js';
|
|
3
|
+
import { calculateOrderBookSpread } from '../utils/orderBookGrouping.js';
|
|
3
4
|
// Fast mode streams 5 levels per side (slow mode streams 20). We run fast mode
|
|
4
5
|
// for lower-latency ladder updates, so the book never carries more than this.
|
|
5
6
|
const DEFAULT_LEVELS = 5;
|
|
@@ -48,20 +49,17 @@ export function processAggregatedOrderBook(data, levels) {
|
|
|
48
49
|
totalNotional: askCumulativeNotional.toFixed(2),
|
|
49
50
|
};
|
|
50
51
|
});
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
|
|
56
|
-
const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
|
|
57
|
-
const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
|
|
52
|
+
const top = calculateOrderBookSpread({
|
|
53
|
+
bestBid: bids[0]?.price,
|
|
54
|
+
bestAsk: asks[0]?.price,
|
|
55
|
+
});
|
|
58
56
|
const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
|
|
59
57
|
return {
|
|
60
58
|
bids,
|
|
61
59
|
asks,
|
|
62
|
-
spread: spread.toFixed(5),
|
|
63
|
-
spreadPercentage,
|
|
64
|
-
midPrice: midPrice.toFixed(5),
|
|
60
|
+
spread: (top?.spread ?? 0).toFixed(5),
|
|
61
|
+
spreadPercentage: top ? top.spreadPercentage.toFixed(4) : '0',
|
|
62
|
+
midPrice: (top?.midPrice ?? 0).toFixed(5),
|
|
65
63
|
lastUpdated: Date.now(),
|
|
66
64
|
maxTotal,
|
|
67
65
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AggregatedOrderBookConnection.js","sourceRoot":"","sources":["../../src/services/AggregatedOrderBookConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAG7E,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AA2DjF,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAM,cAAc,GAAG,CAAC,CAAC;AAEzB;;;;;;;;;GASG;AACH,MAAM,UAAU,0BAA0B,CACxC,IAA4B,EAC5B,MAAc;IAEd,MAAM,OAAO,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAExC,IAAI,iBAAiB,GAAG,CAAC,CAAC;IAC1B,IAAI,qBAAqB,GAAG,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,CA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rE,6EAA6E;QAC7E,0EAA0E;QAC1E,yEAAyE;QACzE,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACrD,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,wEAAwE;QACxE,yEAAyE;QACzE,2EAA2E;QAC3E,2EAA2E;QAC3E,+DAA+D;QAC/D,KAAK,MAAM,cAAc,IAAI,aAAa,EAAE,CAAC;YAC3C,cAAc,EAAE,CAAC;QACnB,CAAC;QACD,IAAI,SAAS,EAAE,CAAC;YACd,SAAS,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;IACH,CAAC;CACF","sourcesContent":["import { SubscriptionClient, WebSocketTransport } from '@nktkas/hyperliquid';\nimport type { ISubscription } from '@nktkas/hyperliquid';\n\nimport { HYPERLIQUID_TRANSPORT_CONFIG } from '../constants/hyperLiquidConfig.js';\nimport type { OrderBookData } from '../types/index.js';\n\n/**\n * A single L2 book price level as delivered by Hyperliquid's `l2Book`\n * subscription. Declared locally to avoid coupling to the SDK's exported type\n * names (and to keep this the only file that references the SDK's shapes).\n */\ntype HyperliquidL2BookLevel = {\n /** Price. */\n px: string;\n /** Total size resting at this price. */\n sz: string;\n /** Number of individual orders. */\n n: number;\n};\n\n/** `l2Book` snapshot event (index 0 = bids, index 1 = asks). */\ntype HyperliquidL2BookEvent = {\n coin: string;\n time: number;\n levels: [bids: HyperliquidL2BookLevel[], asks: HyperliquidL2BookLevel[]];\n spread?: string;\n};\n\n/**\n * Health of the dedicated order-book socket, surfaced to the UI so the panel\n * can show a reconnect affordance.\n *\n * - `connecting`: socket opening or reconnecting after a transient drop.\n * - `connected`: subscription is live.\n * - `error`: dropped and automatic reconnection was exhausted; needs a manual reconnect.\n */\nexport type OrderBookConnectionStatus = 'connecting' | 'connected' | 'error';\n\nexport type SubscribeAggregatedOrderBookParams = {\n /** Market symbol (e.g. 'BTC'). */\n symbol: string;\n /** Number of levels per side to keep. */\n levels?: number;\n /**\n * Server-side aggregation significant figures. Required: omitting it would\n * request the raw, full-precision book instead of an aggregated one, which\n * contradicts this service's contract.\n */\n nSigFigs: 2 | 3 | 4 | 5;\n /** Mantissa refinement when `nSigFigs` is 5. */\n mantissa?: 2 | 5;\n /** Invoked with each processed snapshot. */\n callback: (data: OrderBookData) => void;\n /** Invoked when the underlying socket's health changes. */\n onStatusChange?: (status: OrderBookConnectionStatus) => void;\n};\n\nexport type AggregatedOrderBookConnectionOptions = {\n /** Resolves the current network at subscribe time. */\n isTestnet: () => boolean;\n};\n\n// Fast mode streams 5 levels per side (slow mode streams 20). We run fast mode\n// for lower-latency ladder updates, so the book never carries more than this.\nconst DEFAULT_LEVELS = 5;\n\n/**\n * Transforms a raw Hyperliquid `l2Book` snapshot into the `OrderBookData` shape\n * the UI consumes. Mirrors the subscription service's internal\n * `processOrderBookData` so this dedicated connection is a drop-in replacement\n * for `subscribeToOrderBook` on the aggregated channel.\n *\n * @param data - Raw `l2Book` event.\n * @param levels - Number of levels per side to keep.\n * @returns Processed order-book snapshot.\n */\nexport function processAggregatedOrderBook(\n data: HyperliquidL2BookEvent,\n levels: number,\n): OrderBookData {\n const bidsRaw = data?.levels?.[0] ?? [];\n const asksRaw = data?.levels?.[1] ?? [];\n\n let bidCumulativeSize = 0;\n let bidCumulativeNotional = 0;\n const bids = bidsRaw.slice(0, levels).map((level) => {\n const price = Number.parseFloat(level.px);\n const size = Number.parseFloat(level.sz);\n const notional = price * size;\n bidCumulativeSize += size;\n bidCumulativeNotional += notional;\n return {\n price: level.px,\n size: level.sz,\n total: bidCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: bidCumulativeNotional.toFixed(2),\n };\n });\n\n let askCumulativeSize = 0;\n let askCumulativeNotional = 0;\n const asks = asksRaw.slice(0, levels).map((level) => {\n const price = Number.parseFloat(level.px);\n const size = Number.parseFloat(level.sz);\n const notional = price * size;\n askCumulativeSize += size;\n askCumulativeNotional += notional;\n return {\n price: level.px,\n size: level.sz,\n total: askCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: askCumulativeNotional.toFixed(2),\n };\n });\n\n const bestBid = bids[0];\n const bestAsk = asks[0];\n const bidPrice = bestBid ? Number.parseFloat(bestBid.price) : 0;\n const askPrice = bestAsk ? Number.parseFloat(bestAsk.price) : 0;\n const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;\n const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;\n const spreadPercentage =\n midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';\n const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();\n\n return {\n bids,\n asks,\n spread: spread.toFixed(5),\n spreadPercentage,\n midPrice: midPrice.toFixed(5),\n lastUpdated: Date.now(),\n maxTotal,\n };\n}\n\n/**\n * Owns a dedicated Hyperliquid WebSocket connection used solely for the\n * order-book panel's server-aggregated `l2Book` subscription.\n *\n * The main connection (managed by the subscription service) multiplexes every\n * subscription onto a single socket. The Hyperliquid SDK dispatches `l2Book`\n * events by `coin` only, so running the raw (full-precision) and the aggregated\n * (`nSigFigs`) subscriptions for the same coin on that shared socket\n * cross-contaminates them — the coarse ladder and the precise spread/slippage\n * clobber each other. Giving the aggregated subscription its own socket removes\n * the collision entirely: this socket only ever carries a single `l2Book`\n * stream, and the main socket is never touched by the panel's grouping.\n *\n * The socket is created lazily on the first subscription and torn down once the\n * last subscription is removed, so it exists only while an order-book panel is\n * open. Because network is a global setting, the transport is recreated if\n * `isTestnet` changes between (re)subscriptions.\n */\nexport class AggregatedOrderBookConnection {\n readonly #isTestnet: () => boolean;\n\n #transport: WebSocketTransport | null = null;\n\n #transportIsTestnet = false;\n\n #activeCount = 0;\n\n // Tracks the single `l2Book` payload the dedicated socket carries per asset,\n // keyed by symbol. The SDK dispatches `l2Book` events by `coin` only, so two\n // subscriptions for the same asset with different params (e.g. `nSigFigs`)\n // would cross-contaminate on this shared socket — exactly the collision this\n // connection exists to avoid. `count` refcounts the (identical) subscriptions\n // sharing a payload so the entry is dropped once the last one unsubscribes.\n readonly #payloads = new Map<string, { signature: string; count: number }>();\n\n // Force-terminate callback for every currently-active subscription. When a\n // transport rebuild (`#closeTransport`) shuts the socket down out from under\n // live subscriptions, these tear each one down — notifying the caller and\n // releasing its SDK subscription / socket listeners — instead of orphaning\n // them (stale handle, no more updates, and no further status because\n // reporting is suppressed once `transport !== this.#transport`).\n readonly #activeSubscriptions = new Set<() => void>();\n\n // Set when the socket's auto-reconnection is exhausted (its\n // `terminationSignal` aborts). A terminated socket cannot recover, so the next\n // subscribe must build a fresh transport instead of reusing the dead one.\n #terminated = false;\n\n constructor({ isTestnet }: AggregatedOrderBookConnectionOptions) {\n this.#isTestnet = isTestnet;\n }\n\n /**\n * Opens an aggregated `l2Book` subscription on the dedicated socket.\n *\n * Mirrors the subscription service's synchronous-unsubscribe contract: the\n * returned function can be called before the async subscribe resolves and\n * will cancel the pending subscription.\n *\n * Only one `l2Book` payload per asset may be active at a time. Subscribing to\n * an asset that already has a live subscription with different params (e.g. a\n * different `nSigFigs` or `mantissa`) throws, because the shared socket\n * dispatches by `coin` and the conflicting streams would clobber each other.\n *\n * @param params - Subscription parameters.\n * @returns An unsubscribe function.\n * @throws If the asset already has an active subscription with different params.\n */\n subscribe(params: SubscribeAggregatedOrderBookParams): () => void {\n const levels = params.levels ?? DEFAULT_LEVELS;\n // The `l2Book` subscription params the socket carries. `levels` is\n // client-side only (it slices each snapshot), so it is deliberately excluded\n // from the params and their signature.\n const l2BookParams = {\n coin: params.symbol,\n nSigFigs: params.nSigFigs,\n mantissa: params.mantissa ?? null,\n fast: true as const,\n };\n const signature = JSON.stringify(l2BookParams);\n\n const transport = this.#ensureTransport(this.#isTestnet());\n\n // Reject a conflicting payload for an asset already on this socket. A\n // recreated transport (first use, network change, or terminate) starts with\n // an empty payload map, so this can only trip on the reuse path — the shared\n // socket that would actually suffer the collision.\n const existingPayload = this.#payloads.get(params.symbol);\n if (existingPayload && existingPayload.signature !== signature) {\n throw new Error(\n `AggregatedOrderBookConnection: \"${params.symbol}\" is already subscribed with different params; only one l2Book payload per asset is allowed on the dedicated socket.`,\n );\n }\n\n const { socket } = transport;\n\n let cancelled = false;\n let subscription: ISubscription | null = null;\n this.#activeCount += 1;\n if (existingPayload) {\n existingPayload.count += 1;\n } else {\n this.#payloads.set(params.symbol, { signature, count: 1 });\n }\n\n // Set once this subscription's socket terminates (reconnection exhausted).\n // The `error` state is terminal until teardown/resubscribe, so once set we\n // suppress any late `connected`/`connecting` — e.g. from a subscribe promise\n // that resolves *after* the socket died — which would otherwise flip the UI\n // back to a healthy state on a dead socket and hide the manual-reconnect\n // affordance.\n let terminated = false;\n const reportStatus = (status: OrderBookConnectionStatus): void => {\n // Suppress reports from a subscription that no longer drives the UI: it\n // was unsubscribed (`cancelled`), its transport was replaced by a network\n // flip or recreate (`transport !== this.#transport`, so its socket is\n // dead), or its socket permanently terminated and `error` is now sticky\n // until teardown (`terminated`).\n if (\n cancelled ||\n transport !== this.#transport ||\n (terminated && status !== 'error')\n ) {\n return;\n }\n params.onStatusChange?.(status);\n };\n\n // Reflect the socket's live health. Every drop dispatches a `close` event;\n // the reconnecting socket only exposes permanent termination through its\n // `terminationSignal` (an `AbortSignal`), which it aborts *before* the final\n // close. So an aborted signal on close — unless it was our own `close()`\n // (`TERMINATED_BY_USER`) — means automatic reconnection is exhausted: the\n // unrecoverable state the UI surfaces with a manual reconnect button. A\n // still-live signal means a transient drop the socket will auto-reconnect.\n const handleOpen = (): void => reportStatus('connected');\n const handleClose = (): void => {\n // A torn-down subscription must not mutate shared connection state. Its\n // listeners are normally detached before the socket closes, but guard\n // anyway so a late `close` (e.g. from `transport.close()` racing listener\n // removal) can't wrongly flip `#terminated`.\n if (cancelled) {\n return;\n }\n const { terminationSignal } = socket;\n const terminatedByUser =\n (terminationSignal.reason as { code?: string } | undefined)?.code ===\n 'TERMINATED_BY_USER';\n if (terminationSignal.aborted && !terminatedByUser) {\n this.#terminated = true;\n terminated = true;\n reportStatus('error');\n return;\n }\n reportStatus('connecting');\n };\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('close', handleClose);\n\n const removeSocketListeners = (): void => {\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('close', handleClose);\n };\n\n // Ends this subscription when its transport is torn down beneath it (network\n // flip, post-termination resubscribe, or `close()`). Unlike `teardown` it\n // leaves the shared refcount/payload state alone — `#closeTransport` clears\n // those wholesale — but still notifies the caller and releases this\n // subscription's resources so nothing leaks on the dead socket.\n const forceTerminate = (): void => {\n if (cancelled) {\n return;\n }\n // Notify directly rather than via `reportStatus`: `#closeTransport`\n // detaches `#transport` before invoking these callbacks (so a reentrant\n // subscribe from this handler builds a fresh transport instead of binding\n // to the dying one), which would otherwise trip `reportStatus`'s\n // stale-transport guard. A subscription whose socket already terminated\n // has reported `error`; a still-live one (abandoned by a network flip or\n // `close()`) needs the terminal signal so the caller stops trusting a\n // now-dead book.\n if (!terminated) {\n params.onStatusChange?.('error');\n }\n cancelled = true;\n removeSocketListeners();\n this.#activeSubscriptions.delete(forceTerminate);\n if (subscription) {\n subscription.unsubscribe().catch(() => undefined);\n subscription = null;\n }\n };\n this.#activeSubscriptions.add(forceTerminate);\n\n // Releases this subscription's refcount and tears down the socket once no\n // subscriptions remain. Idempotent via `cancelled`, so it's safe whether it\n // runs from the returned unsubscribe or from a failed subscribe.\n const teardown = (): void => {\n if (cancelled) {\n return;\n }\n cancelled = true;\n removeSocketListeners();\n this.#activeSubscriptions.delete(forceTerminate);\n if (subscription) {\n subscription.unsubscribe().catch(() => undefined);\n subscription = null;\n }\n // Only touch the refcount/current socket if this subscription still\n // belongs to the active transport. If the transport was recreated (network\n // change or terminate), this subscription's socket is already dead and\n // `#activeCount` now tracks only the new transport's subscriptions — so an\n // older unsubscribe must not decrement it and tear down the live socket.\n if (transport === this.#transport) {\n this.#activeCount = Math.max(0, this.#activeCount - 1);\n const entry = this.#payloads.get(params.symbol);\n if (entry) {\n entry.count -= 1;\n if (entry.count <= 0) {\n this.#payloads.delete(params.symbol);\n }\n }\n if (this.#activeCount === 0) {\n this.#closeTransport();\n }\n }\n };\n\n // Surfaces a subscription failure the same way regardless of when it\n // happens: report `error` (before teardown flips `cancelled`, which gates\n // status updates) then release the refcount so the dead subscription doesn't\n // keep the dedicated socket open. Used for both the initial subscribe\n // rejection (`.catch`) and post-confirmation failures the SDK reports only\n // through `onError` — e.g. the server rejecting the re-subscription after a\n // reconnect, which removes the listener and stops all further events (a\n // frozen order book that would otherwise still read as `connected`).\n // Idempotent via `teardown`'s `cancelled` guard.\n const handleSubscriptionError = (): void => {\n reportStatus('error');\n teardown();\n };\n\n reportStatus('connecting');\n\n // Subscribe through the typed `l2Book` client so the params are validated\n // before they reach the wire (`fast: true` requests fast mode — 5 levels at\n // ~0.5s). The listener receives the decoded snapshot directly.\n new SubscriptionClient({ transport })\n .l2Book(\n l2BookParams,\n (data: HyperliquidL2BookEvent) => {\n if (cancelled || data?.coin !== params.symbol || !data?.levels) {\n return;\n }\n params.callback(processAggregatedOrderBook(data, levels));\n },\n // `onError` fires at most once for an *already confirmed* subscription\n // that later fails (rejected re-subscription after reconnect, permanent\n // termination, or a drop while re-subscription is disabled). The SDK\n // removes the listener and emits nothing further, so treat it exactly\n // like an initial failure.\n { onError: handleSubscriptionError },\n )\n .then(async (sub) => {\n // Stale if this subscription was unsubscribed (`cancelled`) or its\n // transport was replaced (network flip / recreate) before the subscribe\n // settled — either way the captured socket is dead, so clean up the SDK\n // subscription instead of storing it or announcing `connected`.\n if (cancelled || transport !== this.#transport) {\n try {\n await sub.unsubscribe();\n } catch {\n // Ignore cleanup errors on an already-cancelled/stale subscription.\n }\n return;\n }\n subscription = sub;\n reportStatus('connected');\n return;\n })\n .catch(handleSubscriptionError);\n\n return teardown;\n }\n\n /** Closes the dedicated socket and drops all subscriptions. */\n close(): void {\n this.#closeTransport();\n }\n\n #ensureTransport(isTestnet: boolean): WebSocketTransport {\n if (\n this.#transport &&\n this.#transportIsTestnet === isTestnet &&\n !this.#terminated\n ) {\n return this.#transport;\n }\n // First use, the network changed, or the previous socket was terminated —\n // (re)create the dedicated transport. Reuse the package's transport config\n // so this socket shares the finite five-attempt reconnection policy; without\n // it the SDK defaults `maxRetries` to Infinity and a sustained outage would\n // never exhaust reconnection to reach the `error`/manual-reconnect state.\n this.#closeTransport();\n // `#closeTransport` notifies subscribers, which may synchronously re-enter\n // `subscribe` and build a matching transport. Reuse it instead of orphaning\n // it (which would leak the reentrant subscription on an unreferenced socket).\n if (\n this.#transport &&\n this.#transportIsTestnet === isTestnet &&\n !this.#terminated\n ) {\n return this.#transport;\n }\n const transport = new WebSocketTransport({\n isTestnet,\n ...HYPERLIQUID_TRANSPORT_CONFIG,\n reconnect: HYPERLIQUID_TRANSPORT_CONFIG.reconnect,\n });\n this.#transport = transport;\n this.#transportIsTestnet = isTestnet;\n return transport;\n }\n\n #closeTransport(): void {\n const transport = this.#transport;\n // Snapshot the subscriptions to force-terminate, then detach ALL shared\n // state (the set, `#transport`, refcounts) *before* invoking any callback.\n // Those callbacks notify subscribers via `onStatusChange`, which can\n // synchronously re-enter `subscribe`; detaching first guarantees a reentrant\n // subscribe builds a fresh transport (rather than reusing this dying one)\n // and registers itself in a clean set (rather than being swept up by, or\n // lingering past, this teardown). Subscriptions torn down normally have\n // already removed themselves, so their entry is a no-op here.\n const subscriptions = [...this.#activeSubscriptions];\n this.#activeSubscriptions.clear();\n this.#transport = null;\n this.#activeCount = 0;\n this.#payloads.clear();\n this.#terminated = false;\n // Force-terminate (which detaches each subscription's socket listeners)\n // BEFORE closing the transport. `close()` on an already-exhausted socket\n // dispatches a final `close`; if a stale `handleClose` were still attached\n // it would re-set `#terminated` right after we cleared it, making the next\n // `#ensureTransport` tear down the healthy replacement socket.\n for (const forceTerminate of subscriptions) {\n forceTerminate();\n }\n if (transport) {\n transport.close();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AggregatedOrderBookConnection.js","sourceRoot":"","sources":["../../src/services/AggregatedOrderBookConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAG7E,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AA0DzE,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAM,cAAc,GAAG,CAAC,CAAC;AAEzB;;;;;;;;;GASG;AACH,MAAM,UAAU,0BAA0B,CACxC,IAA4B,EAC5B,MAAc;IAEd,MAAM,OAAO,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAExC,IAAI,iBAAiB,GAAG,CAAC,CAAC;IAC1B,IAAI,qBAAqB,GAAG,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAClD,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC1C,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACzC,MAAM,QAAQ,GAAG,KAAK,GAAG,IAAI,CAAC;QAC9B,iBAAiB,IAAI,IAAI,CAAC;QAC1B,qBAAqB,IAAI,QAAQ,CAAC;QAClC,OAAO;YACL,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;YACD,OAAO,IAAI,CAAC,UAAU,CAAC;QACzB,CAAC;QACD,MAAM,SAAS,GAAG,IAAI,kBAAkB,CAAC;YACvC,SAAS;YACT,GAAG,4BAA4B;YAC/B,SAAS,EAAE,4BAA4B,CAAC,SAAS;SAClD,CAAC,CAAC;QACH,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;QACrC,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,eAAe;QACb,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,wEAAwE;QACxE,2EAA2E;QAC3E,qEAAqE;QACrE,6EAA6E;QAC7E,0EAA0E;QAC1E,yEAAyE;QACzE,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACrD,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,wEAAwE;QACxE,yEAAyE;QACzE,2EAA2E;QAC3E,2EAA2E;QAC3E,+DAA+D;QAC/D,KAAK,MAAM,cAAc,IAAI,aAAa,EAAE,CAAC;YAC3C,cAAc,EAAE,CAAC;QACnB,CAAC;QACD,IAAI,SAAS,EAAE,CAAC;YACd,SAAS,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;IACH,CAAC;CACF","sourcesContent":["import { SubscriptionClient, WebSocketTransport } from '@nktkas/hyperliquid';\nimport type { ISubscription } from '@nktkas/hyperliquid';\n\nimport { HYPERLIQUID_TRANSPORT_CONFIG } from '../constants/hyperLiquidConfig.js';\nimport type { OrderBookData } from '../types/index.js';\nimport { calculateOrderBookSpread } from '../utils/orderBookGrouping.js';\n\n/**\n * A single L2 book price level as delivered by Hyperliquid's `l2Book`\n * subscription. Declared locally to avoid coupling to the SDK's exported type\n * names (and to keep this the only file that references the SDK's shapes).\n */\ntype HyperliquidL2BookLevel = {\n /** Price. */\n px: string;\n /** Total size resting at this price. */\n sz: string;\n /** Number of individual orders. */\n n: number;\n};\n\n/** `l2Book` snapshot event (index 0 = bids, index 1 = asks). */\ntype HyperliquidL2BookEvent = {\n coin: string;\n time: number;\n levels: [bids: HyperliquidL2BookLevel[], asks: HyperliquidL2BookLevel[]];\n spread?: string;\n};\n\n/**\n * Health of the dedicated order-book socket, surfaced to the UI so the panel\n * can show a reconnect affordance.\n *\n * - `connecting`: socket opening or reconnecting after a transient drop.\n * - `connected`: subscription is live.\n * - `error`: dropped and automatic reconnection was exhausted; needs a manual reconnect.\n */\nexport type OrderBookConnectionStatus = 'connecting' | 'connected' | 'error';\n\nexport type SubscribeAggregatedOrderBookParams = {\n /** Market symbol (e.g. 'BTC'). */\n symbol: string;\n /** Number of levels per side to keep. */\n levels?: number;\n /**\n * Server-side aggregation significant figures. Required: omitting it would\n * request the raw, full-precision book instead of an aggregated one, which\n * contradicts this service's contract.\n */\n nSigFigs: 2 | 3 | 4 | 5;\n /** Mantissa refinement when `nSigFigs` is 5. */\n mantissa?: 2 | 5;\n /** Invoked with each processed snapshot. */\n callback: (data: OrderBookData) => void;\n /** Invoked when the underlying socket's health changes. */\n onStatusChange?: (status: OrderBookConnectionStatus) => void;\n};\n\nexport type AggregatedOrderBookConnectionOptions = {\n /** Resolves the current network at subscribe time. */\n isTestnet: () => boolean;\n};\n\n// Fast mode streams 5 levels per side (slow mode streams 20). We run fast mode\n// for lower-latency ladder updates, so the book never carries more than this.\nconst DEFAULT_LEVELS = 5;\n\n/**\n * Transforms a raw Hyperliquid `l2Book` snapshot into the `OrderBookData` shape\n * the UI consumes. Mirrors the subscription service's internal\n * `processOrderBookData` so this dedicated connection is a drop-in replacement\n * for `subscribeToOrderBook` on the aggregated channel.\n *\n * @param data - Raw `l2Book` event.\n * @param levels - Number of levels per side to keep.\n * @returns Processed order-book snapshot.\n */\nexport function processAggregatedOrderBook(\n data: HyperliquidL2BookEvent,\n levels: number,\n): OrderBookData {\n const bidsRaw = data?.levels?.[0] ?? [];\n const asksRaw = data?.levels?.[1] ?? [];\n\n let bidCumulativeSize = 0;\n let bidCumulativeNotional = 0;\n const bids = bidsRaw.slice(0, levels).map((level) => {\n const price = Number.parseFloat(level.px);\n const size = Number.parseFloat(level.sz);\n const notional = price * size;\n bidCumulativeSize += size;\n bidCumulativeNotional += notional;\n return {\n price: level.px,\n size: level.sz,\n total: bidCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: bidCumulativeNotional.toFixed(2),\n };\n });\n\n let askCumulativeSize = 0;\n let askCumulativeNotional = 0;\n const asks = asksRaw.slice(0, levels).map((level) => {\n const price = Number.parseFloat(level.px);\n const size = Number.parseFloat(level.sz);\n const notional = price * size;\n askCumulativeSize += size;\n askCumulativeNotional += notional;\n return {\n price: level.px,\n size: level.sz,\n total: askCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: askCumulativeNotional.toFixed(2),\n };\n });\n\n const top = calculateOrderBookSpread({\n bestBid: bids[0]?.price,\n bestAsk: asks[0]?.price,\n });\n const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();\n\n return {\n bids,\n asks,\n spread: (top?.spread ?? 0).toFixed(5),\n spreadPercentage: top ? top.spreadPercentage.toFixed(4) : '0',\n midPrice: (top?.midPrice ?? 0).toFixed(5),\n lastUpdated: Date.now(),\n maxTotal,\n };\n}\n\n/**\n * Owns a dedicated Hyperliquid WebSocket connection used solely for the\n * order-book panel's server-aggregated `l2Book` subscription.\n *\n * The main connection (managed by the subscription service) multiplexes every\n * subscription onto a single socket. The Hyperliquid SDK dispatches `l2Book`\n * events by `coin` only, so running the raw (full-precision) and the aggregated\n * (`nSigFigs`) subscriptions for the same coin on that shared socket\n * cross-contaminates them — the coarse ladder and the precise spread/slippage\n * clobber each other. Giving the aggregated subscription its own socket removes\n * the collision entirely: this socket only ever carries a single `l2Book`\n * stream, and the main socket is never touched by the panel's grouping.\n *\n * The socket is created lazily on the first subscription and torn down once the\n * last subscription is removed, so it exists only while an order-book panel is\n * open. Because network is a global setting, the transport is recreated if\n * `isTestnet` changes between (re)subscriptions.\n */\nexport class AggregatedOrderBookConnection {\n readonly #isTestnet: () => boolean;\n\n #transport: WebSocketTransport | null = null;\n\n #transportIsTestnet = false;\n\n #activeCount = 0;\n\n // Tracks the single `l2Book` payload the dedicated socket carries per asset,\n // keyed by symbol. The SDK dispatches `l2Book` events by `coin` only, so two\n // subscriptions for the same asset with different params (e.g. `nSigFigs`)\n // would cross-contaminate on this shared socket — exactly the collision this\n // connection exists to avoid. `count` refcounts the (identical) subscriptions\n // sharing a payload so the entry is dropped once the last one unsubscribes.\n readonly #payloads = new Map<string, { signature: string; count: number }>();\n\n // Force-terminate callback for every currently-active subscription. When a\n // transport rebuild (`#closeTransport`) shuts the socket down out from under\n // live subscriptions, these tear each one down — notifying the caller and\n // releasing its SDK subscription / socket listeners — instead of orphaning\n // them (stale handle, no more updates, and no further status because\n // reporting is suppressed once `transport !== this.#transport`).\n readonly #activeSubscriptions = new Set<() => void>();\n\n // Set when the socket's auto-reconnection is exhausted (its\n // `terminationSignal` aborts). A terminated socket cannot recover, so the next\n // subscribe must build a fresh transport instead of reusing the dead one.\n #terminated = false;\n\n constructor({ isTestnet }: AggregatedOrderBookConnectionOptions) {\n this.#isTestnet = isTestnet;\n }\n\n /**\n * Opens an aggregated `l2Book` subscription on the dedicated socket.\n *\n * Mirrors the subscription service's synchronous-unsubscribe contract: the\n * returned function can be called before the async subscribe resolves and\n * will cancel the pending subscription.\n *\n * Only one `l2Book` payload per asset may be active at a time. Subscribing to\n * an asset that already has a live subscription with different params (e.g. a\n * different `nSigFigs` or `mantissa`) throws, because the shared socket\n * dispatches by `coin` and the conflicting streams would clobber each other.\n *\n * @param params - Subscription parameters.\n * @returns An unsubscribe function.\n * @throws If the asset already has an active subscription with different params.\n */\n subscribe(params: SubscribeAggregatedOrderBookParams): () => void {\n const levels = params.levels ?? DEFAULT_LEVELS;\n // The `l2Book` subscription params the socket carries. `levels` is\n // client-side only (it slices each snapshot), so it is deliberately excluded\n // from the params and their signature.\n const l2BookParams = {\n coin: params.symbol,\n nSigFigs: params.nSigFigs,\n mantissa: params.mantissa ?? null,\n fast: true as const,\n };\n const signature = JSON.stringify(l2BookParams);\n\n const transport = this.#ensureTransport(this.#isTestnet());\n\n // Reject a conflicting payload for an asset already on this socket. A\n // recreated transport (first use, network change, or terminate) starts with\n // an empty payload map, so this can only trip on the reuse path — the shared\n // socket that would actually suffer the collision.\n const existingPayload = this.#payloads.get(params.symbol);\n if (existingPayload && existingPayload.signature !== signature) {\n throw new Error(\n `AggregatedOrderBookConnection: \"${params.symbol}\" is already subscribed with different params; only one l2Book payload per asset is allowed on the dedicated socket.`,\n );\n }\n\n const { socket } = transport;\n\n let cancelled = false;\n let subscription: ISubscription | null = null;\n this.#activeCount += 1;\n if (existingPayload) {\n existingPayload.count += 1;\n } else {\n this.#payloads.set(params.symbol, { signature, count: 1 });\n }\n\n // Set once this subscription's socket terminates (reconnection exhausted).\n // The `error` state is terminal until teardown/resubscribe, so once set we\n // suppress any late `connected`/`connecting` — e.g. from a subscribe promise\n // that resolves *after* the socket died — which would otherwise flip the UI\n // back to a healthy state on a dead socket and hide the manual-reconnect\n // affordance.\n let terminated = false;\n const reportStatus = (status: OrderBookConnectionStatus): void => {\n // Suppress reports from a subscription that no longer drives the UI: it\n // was unsubscribed (`cancelled`), its transport was replaced by a network\n // flip or recreate (`transport !== this.#transport`, so its socket is\n // dead), or its socket permanently terminated and `error` is now sticky\n // until teardown (`terminated`).\n if (\n cancelled ||\n transport !== this.#transport ||\n (terminated && status !== 'error')\n ) {\n return;\n }\n params.onStatusChange?.(status);\n };\n\n // Reflect the socket's live health. Every drop dispatches a `close` event;\n // the reconnecting socket only exposes permanent termination through its\n // `terminationSignal` (an `AbortSignal`), which it aborts *before* the final\n // close. So an aborted signal on close — unless it was our own `close()`\n // (`TERMINATED_BY_USER`) — means automatic reconnection is exhausted: the\n // unrecoverable state the UI surfaces with a manual reconnect button. A\n // still-live signal means a transient drop the socket will auto-reconnect.\n const handleOpen = (): void => reportStatus('connected');\n const handleClose = (): void => {\n // A torn-down subscription must not mutate shared connection state. Its\n // listeners are normally detached before the socket closes, but guard\n // anyway so a late `close` (e.g. from `transport.close()` racing listener\n // removal) can't wrongly flip `#terminated`.\n if (cancelled) {\n return;\n }\n const { terminationSignal } = socket;\n const terminatedByUser =\n (terminationSignal.reason as { code?: string } | undefined)?.code ===\n 'TERMINATED_BY_USER';\n if (terminationSignal.aborted && !terminatedByUser) {\n this.#terminated = true;\n terminated = true;\n reportStatus('error');\n return;\n }\n reportStatus('connecting');\n };\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('close', handleClose);\n\n const removeSocketListeners = (): void => {\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('close', handleClose);\n };\n\n // Ends this subscription when its transport is torn down beneath it (network\n // flip, post-termination resubscribe, or `close()`). Unlike `teardown` it\n // leaves the shared refcount/payload state alone — `#closeTransport` clears\n // those wholesale — but still notifies the caller and releases this\n // subscription's resources so nothing leaks on the dead socket.\n const forceTerminate = (): void => {\n if (cancelled) {\n return;\n }\n // Notify directly rather than via `reportStatus`: `#closeTransport`\n // detaches `#transport` before invoking these callbacks (so a reentrant\n // subscribe from this handler builds a fresh transport instead of binding\n // to the dying one), which would otherwise trip `reportStatus`'s\n // stale-transport guard. A subscription whose socket already terminated\n // has reported `error`; a still-live one (abandoned by a network flip or\n // `close()`) needs the terminal signal so the caller stops trusting a\n // now-dead book.\n if (!terminated) {\n params.onStatusChange?.('error');\n }\n cancelled = true;\n removeSocketListeners();\n this.#activeSubscriptions.delete(forceTerminate);\n if (subscription) {\n subscription.unsubscribe().catch(() => undefined);\n subscription = null;\n }\n };\n this.#activeSubscriptions.add(forceTerminate);\n\n // Releases this subscription's refcount and tears down the socket once no\n // subscriptions remain. Idempotent via `cancelled`, so it's safe whether it\n // runs from the returned unsubscribe or from a failed subscribe.\n const teardown = (): void => {\n if (cancelled) {\n return;\n }\n cancelled = true;\n removeSocketListeners();\n this.#activeSubscriptions.delete(forceTerminate);\n if (subscription) {\n subscription.unsubscribe().catch(() => undefined);\n subscription = null;\n }\n // Only touch the refcount/current socket if this subscription still\n // belongs to the active transport. If the transport was recreated (network\n // change or terminate), this subscription's socket is already dead and\n // `#activeCount` now tracks only the new transport's subscriptions — so an\n // older unsubscribe must not decrement it and tear down the live socket.\n if (transport === this.#transport) {\n this.#activeCount = Math.max(0, this.#activeCount - 1);\n const entry = this.#payloads.get(params.symbol);\n if (entry) {\n entry.count -= 1;\n if (entry.count <= 0) {\n this.#payloads.delete(params.symbol);\n }\n }\n if (this.#activeCount === 0) {\n this.#closeTransport();\n }\n }\n };\n\n // Surfaces a subscription failure the same way regardless of when it\n // happens: report `error` (before teardown flips `cancelled`, which gates\n // status updates) then release the refcount so the dead subscription doesn't\n // keep the dedicated socket open. Used for both the initial subscribe\n // rejection (`.catch`) and post-confirmation failures the SDK reports only\n // through `onError` — e.g. the server rejecting the re-subscription after a\n // reconnect, which removes the listener and stops all further events (a\n // frozen order book that would otherwise still read as `connected`).\n // Idempotent via `teardown`'s `cancelled` guard.\n const handleSubscriptionError = (): void => {\n reportStatus('error');\n teardown();\n };\n\n reportStatus('connecting');\n\n // Subscribe through the typed `l2Book` client so the params are validated\n // before they reach the wire (`fast: true` requests fast mode — 5 levels at\n // ~0.5s). The listener receives the decoded snapshot directly.\n new SubscriptionClient({ transport })\n .l2Book(\n l2BookParams,\n (data: HyperliquidL2BookEvent) => {\n if (cancelled || data?.coin !== params.symbol || !data?.levels) {\n return;\n }\n params.callback(processAggregatedOrderBook(data, levels));\n },\n // `onError` fires at most once for an *already confirmed* subscription\n // that later fails (rejected re-subscription after reconnect, permanent\n // termination, or a drop while re-subscription is disabled). The SDK\n // removes the listener and emits nothing further, so treat it exactly\n // like an initial failure.\n { onError: handleSubscriptionError },\n )\n .then(async (sub) => {\n // Stale if this subscription was unsubscribed (`cancelled`) or its\n // transport was replaced (network flip / recreate) before the subscribe\n // settled — either way the captured socket is dead, so clean up the SDK\n // subscription instead of storing it or announcing `connected`.\n if (cancelled || transport !== this.#transport) {\n try {\n await sub.unsubscribe();\n } catch {\n // Ignore cleanup errors on an already-cancelled/stale subscription.\n }\n return;\n }\n subscription = sub;\n reportStatus('connected');\n return;\n })\n .catch(handleSubscriptionError);\n\n return teardown;\n }\n\n /** Closes the dedicated socket and drops all subscriptions. */\n close(): void {\n this.#closeTransport();\n }\n\n #ensureTransport(isTestnet: boolean): WebSocketTransport {\n if (\n this.#transport &&\n this.#transportIsTestnet === isTestnet &&\n !this.#terminated\n ) {\n return this.#transport;\n }\n // First use, the network changed, or the previous socket was terminated —\n // (re)create the dedicated transport. Reuse the package's transport config\n // so this socket shares the finite five-attempt reconnection policy; without\n // it the SDK defaults `maxRetries` to Infinity and a sustained outage would\n // never exhaust reconnection to reach the `error`/manual-reconnect state.\n this.#closeTransport();\n // `#closeTransport` notifies subscribers, which may synchronously re-enter\n // `subscribe` and build a matching transport. Reuse it instead of orphaning\n // it (which would leak the reentrant subscription on an unreferenced socket).\n if (\n this.#transport &&\n this.#transportIsTestnet === isTestnet &&\n !this.#terminated\n ) {\n return this.#transport;\n }\n const transport = new WebSocketTransport({\n isTestnet,\n ...HYPERLIQUID_TRANSPORT_CONFIG,\n reconnect: HYPERLIQUID_TRANSPORT_CONFIG.reconnect,\n });\n this.#transport = transport;\n this.#transportIsTestnet = isTestnet;\n return transport;\n }\n\n #closeTransport(): void {\n const transport = this.#transport;\n // Snapshot the subscriptions to force-terminate, then detach ALL shared\n // state (the set, `#transport`, refcounts) *before* invoking any callback.\n // Those callbacks notify subscribers via `onStatusChange`, which can\n // synchronously re-enter `subscribe`; detaching first guarantees a reentrant\n // subscribe builds a fresh transport (rather than reusing this dying one)\n // and registers itself in a clean set (rather than being swept up by, or\n // lingering past, this teardown). Subscriptions torn down normally have\n // already removed themselves, so their entry is a no-op here.\n const subscriptions = [...this.#activeSubscriptions];\n this.#activeSubscriptions.clear();\n this.#transport = null;\n this.#activeCount = 0;\n this.#payloads.clear();\n this.#terminated = false;\n // Force-terminate (which detaches each subscription's socket listeners)\n // BEFORE closing the transport. `close()` on an already-exhausted socket\n // dispatches a final `close`; if a stale `handleClose` were still attached\n // it would re-set `#terminated` right after we cleared it, making the next\n // `#ensureTransport` tear down the healthy replacement socket.\n for (const forceTerminate of subscriptions) {\n forceTerminate();\n }\n if (transport) {\n transport.close();\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HyperLiquidSubscriptionService.d.ts","sourceRoot":"","sources":["../../src/services/HyperLiquidSubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAO,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EAMV,mBAAmB,EAEnB,sBAAsB,EAItB,gBAAgB,EAMjB,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,KAAK,EAEV,0BAA0B,EAC3B,MAAM,+BAA+B,CAAC;AAMvC,OAAO,KAAK,EAEV,QAAQ,EACR,SAAS,EACT,KAAK,EAEL,kBAAkB,EAClB,SAAS,EACT,qBAAqB,EACrB,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,wBAAwB,EAGxB,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"HyperLiquidSubscriptionService.d.ts","sourceRoot":"","sources":["../../src/services/HyperLiquidSubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAO,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EAMV,mBAAmB,EAEnB,sBAAsB,E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AE1C;IAED;;;;;;;;OAQG;IACI,0BAA0B,IAAI,SAAS,EAAE,GAAG,IAAI,CAKtD;IAilCD;;;;;;;OAOG;IACI,oBAAoB,CAAC,MAAM,EAAE,wBAAwB,GAAG,MAAM,IAAI,CAiGxE;IAED;;;;;;;;;;;;;;;OAeG;IACI,0BAA0B,CAAC,MAAM,EAAE;QACxC,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,aAAa,CAAC;QAC1B,QAAQ,EAAE,CAAC,IAAI,EAAE,sBAAsB,KAAK,IAAI,CAAC;QACjD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;KAClC,GAAG,MAAM,IAAI,CAsJb;IAgJD;;;;;;OAMG;IACU,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CA0QjD;IAED;;OAEG;IACI,QAAQ,IAAI,IAAI,CAmQtB;CACF"}
|
|
@@ -11,6 +11,7 @@ import { ensureError } from '../utils/errorUtils.js';
|
|
|
11
11
|
import { adaptPositionFromSDK, adaptOrderFromSDK, adaptAccountStateFromSDK, buildHyperLiquidFillId, parseAssetName, } from '../utils/hyperLiquidAdapter.js';
|
|
12
12
|
import { processBboData } from '../utils/hyperLiquidOrderBookProcessor.js';
|
|
13
13
|
import { calculateOpenInterestUSD, isMarketTradable, } from '../utils/marketDataTransform.js';
|
|
14
|
+
import { calculateOrderBookSpread } from '../utils/orderBookGrouping.js';
|
|
14
15
|
import { buildPositionTriggerOrderFromOrder, hashTriggerOrders, resolvePositionTriggerSummaryPrice, } from '../utils/orderTypes.js';
|
|
15
16
|
import { parseFiniteDecimal } from '../utils/stringParseUtils.js';
|
|
16
17
|
/**
|
|
@@ -2373,6 +2374,11 @@ export class HyperLiquidSubscriptionService {
|
|
|
2373
2374
|
this.#positionSubscriberCount += 1;
|
|
2374
2375
|
const unsubscribe = () => {
|
|
2375
2376
|
removeListener();
|
|
2377
|
+
// An empty opt-in set stops refreshing the dedup hash, so a stale hash
|
|
2378
|
+
// could suppress the next resubscriber's first change.
|
|
2379
|
+
if (this.#completePositionSubscribers.size === 0) {
|
|
2380
|
+
this.#completePositionsHash = '';
|
|
2381
|
+
}
|
|
2376
2382
|
this.#positionSubscriberCount -= 1;
|
|
2377
2383
|
this.#cleanupSharedWebData3ISubscription();
|
|
2378
2384
|
};
|
|
@@ -2830,6 +2836,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
2830
2836
|
this.#orderSubscriberCount += 1;
|
|
2831
2837
|
const unsubscribe = () => {
|
|
2832
2838
|
removeListener();
|
|
2839
|
+
// See subscribeToPositions: keep the dedup hash from going stale.
|
|
2840
|
+
if (this.#completeOrderSubscribers.size === 0) {
|
|
2841
|
+
this.#completeOrdersHash = '';
|
|
2842
|
+
}
|
|
2833
2843
|
this.#orderSubscriberCount -= 1;
|
|
2834
2844
|
this.#cleanupSharedWebData3ISubscription();
|
|
2835
2845
|
};
|
|
@@ -4295,22 +4305,18 @@ export class HyperLiquidSubscriptionService {
|
|
|
4295
4305
|
totalNotional: askCumulativeNotional.toFixed(2),
|
|
4296
4306
|
};
|
|
4297
4307
|
});
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;
|
|
4303
|
-
const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
|
|
4304
|
-
const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
|
|
4305
|
-
const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
|
|
4308
|
+
const top = calculateOrderBookSpread({
|
|
4309
|
+
bestBid: bids[0]?.price,
|
|
4310
|
+
bestAsk: asks[0]?.price,
|
|
4311
|
+
});
|
|
4306
4312
|
// Calculate max total for depth chart scaling
|
|
4307
4313
|
const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
|
|
4308
4314
|
return {
|
|
4309
4315
|
bids,
|
|
4310
4316
|
asks,
|
|
4311
|
-
spread: spread.toFixed(5),
|
|
4312
|
-
spreadPercentage,
|
|
4313
|
-
midPrice: midPrice.toFixed(5),
|
|
4317
|
+
spread: (top?.spread ?? 0).toFixed(5),
|
|
4318
|
+
spreadPercentage: top ? top.spreadPercentage.toFixed(4) : '0',
|
|
4319
|
+
midPrice: (top?.midPrice ?? 0).toFixed(5),
|
|
4314
4320
|
lastUpdated: Date.now(),
|
|
4315
4321
|
maxTotal,
|
|
4316
4322
|
};
|
|
@@ -4476,8 +4482,9 @@ export class HyperLiquidSubscriptionService {
|
|
|
4476
4482
|
// reaches the caller's onError.
|
|
4477
4483
|
this.#activeAssetDataStreams.forEach((stream) => stream.reopen());
|
|
4478
4484
|
// Re-establish user data subscriptions if there are user data subscribers
|
|
4479
|
-
|
|
4480
|
-
|
|
4485
|
+
// The counts include opt-in complete-snapshot subscribers.
|
|
4486
|
+
if (this.#positionSubscriberCount > 0 ||
|
|
4487
|
+
this.#orderSubscriberCount > 0 ||
|
|
4481
4488
|
this.#accountSubscribers.size > 0 ||
|
|
4482
4489
|
this.#oiCapSubscribers.size > 0) {
|
|
4483
4490
|
// Retire pending opens as well as subscriptions on the old transport.
|