@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -9
- package/dist/PerpsController-method-action-types.d.ts +149 -3
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +125 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +787 -31
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +69 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +82 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +15 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +14 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +10 -2
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +11 -3
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +10 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/internal/accountReturnOnEquity.d.ts +12 -0
- package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
- package/dist/internal/accountReturnOnEquity.js +18 -0
- package/dist/internal/accountReturnOnEquity.js.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
- package/dist/internal/marketNumericValues.d.ts +10 -0
- package/dist/internal/marketNumericValues.d.ts.map +1 -0
- package/dist/internal/marketNumericValues.js +9 -0
- package/dist/internal/marketNumericValues.js.map +1 -0
- package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
- package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
- package/dist/internal/perpsDisplaySymbol.js +21 -0
- package/dist/internal/perpsDisplaySymbol.js.map +1 -0
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +140 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +72 -4
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +751 -159
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +2 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +11 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/selectors.d.ts +15 -5
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +23 -5
- package/dist/selectors.js.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.js +8 -10
- package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +8 -0
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +65 -0
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +117 -30
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +20 -3
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +55 -3
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +139 -0
- package/dist/services/StreamChannelManager.d.ts.map +1 -0
- package/dist/services/StreamChannelManager.js +475 -0
- package/dist/services/StreamChannelManager.js.map +1 -0
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +7 -0
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/agentSigner.d.ts +8 -0
- package/dist/services/agentSigner.d.ts.map +1 -1
- package/dist/services/agentSigner.js +13 -0
- package/dist/services/agentSigner.js.map +1 -1
- package/dist/types/hyperliquid-types.d.ts +9 -1
- package/dist/types/hyperliquid-types.d.ts.map +1 -1
- package/dist/types/hyperliquid-types.js +10 -0
- package/dist/types/hyperliquid-types.js.map +1 -1
- package/dist/types/index.d.ts +434 -17
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +17 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -1
- package/dist/utils/accountAggregation.js +21 -5
- package/dist/utils/accountAggregation.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +31 -10
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +68 -28
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +17 -4
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +23 -7
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +17 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +264 -29
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +4 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +46 -9
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +13 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +1 -2
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +7 -17
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +35 -5
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +62 -6
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
- package/dist/utils/perpsDiskPersistence.js +10 -0
- package/dist/utils/perpsDiskPersistence.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +31 -0
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +26 -0
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/dist/utils/priceDeviation.d.ts +9 -6
- package/dist/utils/priceDeviation.d.ts.map +1 -1
- package/dist/utils/priceDeviation.js +17 -26
- package/dist/utils/priceDeviation.js.map +1 -1
- package/dist/utils/sortMarkets.d.ts +13 -5
- package/dist/utils/sortMarkets.d.ts.map +1 -1
- package/dist/utils/sortMarkets.js +60 -38
- package/dist/utils/sortMarkets.js.map +1 -1
- package/docs/architecture.md +54 -24
- package/docs/client-contract.md +52 -27
- package/docs/contracts/events.md +38 -32
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/formatting.md +2 -0
- package/docs/venues/lighter/capabilities.md +18 -15
- package/package.json +1 -1
package/dist/PerpsController.js
CHANGED
|
@@ -5,7 +5,7 @@ import { hasProperty } from '@metamask/utils';
|
|
|
5
5
|
import { v4 as uuidv4 } from 'uuid';
|
|
6
6
|
import { VISIBLE_CANDLE_COUNT_CONFIG, } from './constants/chartConfig.js';
|
|
7
7
|
import { PERPS_EVENT_PROPERTY, PERPS_EVENT_VALUE, } from './constants/eventNames.js';
|
|
8
|
-
import { canonicalizeHyperLiquidDexes, MAINNET_HIP3_CONFIG, TESTNET_HIP3_CONFIG, USDC_SYMBOL, } from './constants/hyperLiquidConfig.js';
|
|
8
|
+
import { canonicalizeHyperLiquidDexes, isCrossMarginSupported, MAINNET_HIP3_CONFIG, TESTNET_HIP3_CONFIG, USDC_SYMBOL, } from './constants/hyperLiquidConfig.js';
|
|
9
9
|
import { PerpsMeasurementName } from './constants/performanceMetrics.js';
|
|
10
10
|
import { PERPS_CONSTANTS, MARKET_SORTING_CONFIG, buildProviderCacheKey, MAX_SLIPPAGE_BOUNDS, DEFAULT_PERPS_MODE, DEFAULT_ORDER_BOOK_PREFERENCES, DEFAULT_PRO_LAYOUT_PREFERENCES, DEFAULT_SELECTED_ORDER_TYPE, } from './constants/perpsConfig.js';
|
|
11
11
|
import { PERPS_ERROR_CODES } from './perpsErrorCodes.js';
|
|
@@ -24,6 +24,7 @@ import { MarketDataService } from './services/MarketDataService.js';
|
|
|
24
24
|
import { isMissingActionHandlerError } from './services/missingActionHandler.js';
|
|
25
25
|
import { isProviderOnTestnet } from './services/providerNetwork.js';
|
|
26
26
|
import { RewardsIntegrationService } from './services/RewardsIntegrationService.js';
|
|
27
|
+
import { StreamChannelManager } from './services/StreamChannelManager.js';
|
|
27
28
|
import { TerminalMarketService } from './services/TerminalMarketService.js';
|
|
28
29
|
import { TradingService } from './services/TradingService.js';
|
|
29
30
|
// PerpsStreamChannelKey removed: using string for channel keys (PerpsStreamManager.pauseChannel takes string)
|
|
@@ -478,6 +479,26 @@ const metadata = {
|
|
|
478
479
|
* Number of public trades `getPublicTrades` returns when no limit is given.
|
|
479
480
|
*/
|
|
480
481
|
const PUBLIC_TRADES_DEFAULT_LIMIT = 50;
|
|
482
|
+
/** `subscribeTo*` streams that read an account rather than a market. */
|
|
483
|
+
const ACCOUNT_STREAMS = new Set([
|
|
484
|
+
'account',
|
|
485
|
+
'availableToTrade',
|
|
486
|
+
'chaseOrderLists',
|
|
487
|
+
'feeRates',
|
|
488
|
+
'liveTwapOrders',
|
|
489
|
+
'marginAdjustmentLimits',
|
|
490
|
+
'oiCaps',
|
|
491
|
+
'orderFills',
|
|
492
|
+
'orders',
|
|
493
|
+
'positions',
|
|
494
|
+
'tradingAgentValidity',
|
|
495
|
+
'twapOrders',
|
|
496
|
+
]);
|
|
497
|
+
/**
|
|
498
|
+
* Provider part of the key of a channel subscribed while no provider is
|
|
499
|
+
* active. The channel opens on the next successful initialization.
|
|
500
|
+
*/
|
|
501
|
+
const PENDING_PROVIDER_CHANNEL_ID = 'pending';
|
|
481
502
|
const MESSENGER_EXPOSED_METHODS = [
|
|
482
503
|
'approveSubscriptionBuilderFee',
|
|
483
504
|
'calculateFees',
|
|
@@ -529,6 +550,8 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
529
550
|
'getOrderBookPreferences',
|
|
530
551
|
'getOrderCapabilities',
|
|
531
552
|
'getMarginModeLock',
|
|
553
|
+
'getMarginAdjustmentLimits',
|
|
554
|
+
'getMarketMeta',
|
|
532
555
|
'getScalePriceLadder',
|
|
533
556
|
'getOrderFills',
|
|
534
557
|
'getOrders',
|
|
@@ -537,6 +560,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
537
560
|
'getPositions',
|
|
538
561
|
'getProviderHealth',
|
|
539
562
|
'getPublicTrades',
|
|
563
|
+
'getStreamSnapshot',
|
|
540
564
|
'getSelectedOrderType',
|
|
541
565
|
'getRecoveredDispatches',
|
|
542
566
|
'getAttachedOrderGroups',
|
|
@@ -564,12 +588,14 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
564
588
|
'placeOrder',
|
|
565
589
|
'prepareTradingWallet',
|
|
566
590
|
'previewPositionModify',
|
|
591
|
+
'estimateCrossLiquidation',
|
|
567
592
|
'reconnect',
|
|
568
593
|
'recordMarketViewed',
|
|
569
594
|
'refreshEligibility',
|
|
570
595
|
'replacePositionTPSLLeg',
|
|
571
596
|
'resetFirstTimeUserState',
|
|
572
597
|
'resetSelectedPaymentToken',
|
|
598
|
+
'resubscribeStreams',
|
|
573
599
|
'getMaxSlippage',
|
|
574
600
|
'setMaxSlippage',
|
|
575
601
|
'setOrderBookPreferences',
|
|
@@ -596,8 +622,12 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
596
622
|
'subscribeToAvailableToTrade',
|
|
597
623
|
'subscribeToCandles',
|
|
598
624
|
'subscribeToChaseOrderLists',
|
|
625
|
+
'subscribeToConnectionLatency',
|
|
599
626
|
'subscribeToConnectionState',
|
|
627
|
+
'subscribeToFeeRates',
|
|
600
628
|
'subscribeToLiveTwapOrders',
|
|
629
|
+
'subscribeToMarginAdjustmentLimits',
|
|
630
|
+
'subscribeToMarketMeta',
|
|
601
631
|
'subscribeToOICaps',
|
|
602
632
|
'subscribeToOrderBook',
|
|
603
633
|
'subscribeToOrderFills',
|
|
@@ -606,6 +636,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
606
636
|
'subscribeToPrices',
|
|
607
637
|
'subscribeToProviderHealth',
|
|
608
638
|
'subscribeToPublicTrades',
|
|
639
|
+
'subscribeToTradingAgentValidity',
|
|
609
640
|
'subscribeToTwapOrders',
|
|
610
641
|
'suspendChaseOrders',
|
|
611
642
|
'switchProvider',
|
|
@@ -753,8 +784,26 @@ export class PerpsController extends BaseController {
|
|
|
753
784
|
* owned one of its references. The newer toggle undoes them if it fails too.
|
|
754
785
|
*/
|
|
755
786
|
#deferredWatchlistRestores = new Map();
|
|
787
|
+
/**
|
|
788
|
+
* References an older toggle added but failed to write while a newer
|
|
789
|
+
* toggle owned them. Remote storage never held them, so the newer toggle
|
|
790
|
+
* must not restore them if it fails too.
|
|
791
|
+
*/
|
|
792
|
+
#unpersistedWatchlistAdds = new Map();
|
|
756
793
|
#userDiskWrite = Promise.resolve();
|
|
757
794
|
#providerSubscriptions = new Set();
|
|
795
|
+
/** The shared stream layer behind every `subscribeTo*` method. */
|
|
796
|
+
#streams = new StreamChannelManager({
|
|
797
|
+
subscribeToConnectionState: (listener) => this.subscribeToConnectionState(listener),
|
|
798
|
+
onError: (error) => this.#logError(ensureError(error, 'PerpsController.streams'), this.#getErrorContext('streams')),
|
|
799
|
+
});
|
|
800
|
+
#providerChannelIds = new WeakMap();
|
|
801
|
+
/**
|
|
802
|
+
* Channel sources being opened. Their provider subscriptions are not
|
|
803
|
+
* tracked for aggregated rebinding: the channel rebinds them itself.
|
|
804
|
+
*/
|
|
805
|
+
#openingChannelSources = 0;
|
|
806
|
+
#nextProviderChannelId = 0;
|
|
758
807
|
// A failed automatic rollback does not end the consumers' subscription context.
|
|
759
808
|
#hasPendingSubscriptionRecovery = false;
|
|
760
809
|
// Store options for dependency injection (allows core package to inject platform-specific services)
|
|
@@ -873,10 +922,16 @@ export class PerpsController extends BaseController {
|
|
|
873
922
|
});
|
|
874
923
|
}
|
|
875
924
|
};
|
|
876
|
-
this.messenger.subscribe('AccountsController:selectedAccountChange', () =>
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
925
|
+
this.messenger.subscribe('AccountsController:selectedAccountChange', () => {
|
|
926
|
+
updateSelectedTradingAccount(getSelectedEvmAccountFromMessenger(this.messenger));
|
|
927
|
+
this.#rebindStreams();
|
|
928
|
+
});
|
|
929
|
+
this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId) => {
|
|
930
|
+
updateSelectedTradingAccount(groupId === ''
|
|
931
|
+
? null
|
|
932
|
+
: getSelectedEvmAccountFromMessenger(this.messenger));
|
|
933
|
+
this.#rebindStreams();
|
|
934
|
+
});
|
|
880
935
|
this.providers = new Map();
|
|
881
936
|
// Migrate old persisted data without accountAddress
|
|
882
937
|
this.#migrateRequestsIfNeeded();
|
|
@@ -985,6 +1040,15 @@ export class PerpsController extends BaseController {
|
|
|
985
1040
|
providerIds.add('lighter');
|
|
986
1041
|
}
|
|
987
1042
|
}
|
|
1043
|
+
if (this.isInitialized) {
|
|
1044
|
+
// A disk-hydrated slice of a venue that did not register this session
|
|
1045
|
+
// is never refreshed, so it must not decide the aggregate's freshness.
|
|
1046
|
+
for (const providerId of providerIds) {
|
|
1047
|
+
if (!this.providers.has(providerId)) {
|
|
1048
|
+
providerIds.delete(providerId);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
988
1052
|
const assembled = [];
|
|
989
1053
|
for (const providerId of providerIds) {
|
|
990
1054
|
const entry = cache[buildProviderCacheKey(providerId, isTestnet)];
|
|
@@ -1668,6 +1732,7 @@ export class PerpsController extends BaseController {
|
|
|
1668
1732
|
async #withStreamPause(operation, channels) {
|
|
1669
1733
|
const pausedChannels = [];
|
|
1670
1734
|
const { streamManager } = this.#options.infrastructure;
|
|
1735
|
+
const releases = channels.map((channel) => this.#streams.pause(channel));
|
|
1671
1736
|
// Pause emission on specified channels (WebSocket stays connected)
|
|
1672
1737
|
// Track which channels successfully paused to ensure proper cleanup
|
|
1673
1738
|
for (const channel of channels) {
|
|
@@ -1689,6 +1754,9 @@ export class PerpsController extends BaseController {
|
|
|
1689
1754
|
return await operation();
|
|
1690
1755
|
}
|
|
1691
1756
|
finally {
|
|
1757
|
+
for (const release of releases) {
|
|
1758
|
+
release();
|
|
1759
|
+
}
|
|
1692
1760
|
// Resume only channels that were successfully paused
|
|
1693
1761
|
for (const channel of pausedChannels) {
|
|
1694
1762
|
try {
|
|
@@ -1785,6 +1853,8 @@ export class PerpsController extends BaseController {
|
|
|
1785
1853
|
this.#reinitializationOperationPromise = operation;
|
|
1786
1854
|
return () => {
|
|
1787
1855
|
this.#isReinitializing = false;
|
|
1856
|
+
// Streams wait for the provider until the whole operation ends.
|
|
1857
|
+
this.#rebindStreams();
|
|
1788
1858
|
resolveOperation();
|
|
1789
1859
|
if (this.#reinitializationOperationPromise === operation) {
|
|
1790
1860
|
this.#reinitializationOperationPromise = null;
|
|
@@ -1875,6 +1945,7 @@ export class PerpsController extends BaseController {
|
|
|
1875
1945
|
if (preserveSubscriptions) {
|
|
1876
1946
|
this.#restoreProviderSubscriptions();
|
|
1877
1947
|
}
|
|
1948
|
+
this.#rebindStreams();
|
|
1878
1949
|
return; // Exit retry loop on success
|
|
1879
1950
|
}
|
|
1880
1951
|
catch (error) {
|
|
@@ -1946,6 +2017,7 @@ export class PerpsController extends BaseController {
|
|
|
1946
2017
|
?.subscriptionBuilderAddressMainnet,
|
|
1947
2018
|
onChaseOrderMaxDistanceReached: this.#publishChaseOrderMaxDistanceReached,
|
|
1948
2019
|
getAgentSigner: this.#agentBindings.resolve,
|
|
2020
|
+
hasAgentSource: this.#agentBindings.hasSource,
|
|
1949
2021
|
onAgentRejected: (account, agentAddress) => {
|
|
1950
2022
|
this.#agentBindings.release(account, agentAddress);
|
|
1951
2023
|
this.#options.clientConfig?.providerCredentials?.hyperliquid?.onAgentRejected?.(account, agentAddress);
|
|
@@ -2488,6 +2560,356 @@ export class PerpsController extends BaseController {
|
|
|
2488
2560
|
return this.#getUnavailableMarginModeLock('provider_unavailable', resolvedProviderId);
|
|
2489
2561
|
}
|
|
2490
2562
|
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Get how much margin an isolated position can take in (`maxAdd`, what the
|
|
2565
|
+
* venue's isolated margin update accepts) and release (`maxRemove`),
|
|
2566
|
+
* through the active provider route used by order placement. Never throws;
|
|
2567
|
+
* failures report an unavailable status.
|
|
2568
|
+
*
|
|
2569
|
+
* @param params - Market and optional provider route.
|
|
2570
|
+
* @returns The limits, or a typed unavailable result.
|
|
2571
|
+
*/
|
|
2572
|
+
async getMarginAdjustmentLimits(params) {
|
|
2573
|
+
try {
|
|
2574
|
+
const activeProvider = await this.#getActiveProviderWhenReady();
|
|
2575
|
+
if (this.#hasConflictingProviderRoute(params.providerId, activeProvider) ||
|
|
2576
|
+
!activeProvider.getMarginAdjustmentLimits) {
|
|
2577
|
+
return { status: 'unavailable', reason: 'provider' };
|
|
2578
|
+
}
|
|
2579
|
+
return await activeProvider.getMarginAdjustmentLimits(params);
|
|
2580
|
+
}
|
|
2581
|
+
catch (error) {
|
|
2582
|
+
this.#debugLog('PerpsController: Margin adjustment limits unavailable', {
|
|
2583
|
+
error: ensureError(error, 'PerpsController.getMarginAdjustmentLimits')
|
|
2584
|
+
.message,
|
|
2585
|
+
});
|
|
2586
|
+
return { status: 'unavailable', reason: 'provider' };
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
async getMarketMeta(params) {
|
|
2590
|
+
const provider = await this.#getActiveProviderWhenReady();
|
|
2591
|
+
const providerId = params?.providerId;
|
|
2592
|
+
if (this.#hasConflictingProviderRoute(providerId, provider)) {
|
|
2593
|
+
throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
|
|
2594
|
+
}
|
|
2595
|
+
const symbol = params?.symbol;
|
|
2596
|
+
const metas = await this.#readMarketMetas(provider, providerId, symbol === undefined ? undefined : { symbols: [symbol] });
|
|
2597
|
+
if (symbol === undefined) {
|
|
2598
|
+
return metas;
|
|
2599
|
+
}
|
|
2600
|
+
const meta = metas.find((item) => item.symbol.toLowerCase() === symbol.toLowerCase());
|
|
2601
|
+
if (!meta) {
|
|
2602
|
+
throw new Error(PERPS_ERROR_CODES.MARKET_NOT_FOUND);
|
|
2603
|
+
}
|
|
2604
|
+
return meta;
|
|
2605
|
+
}
|
|
2606
|
+
/**
|
|
2607
|
+
* Read one venue's market list as metadata. The aggregated list drops a
|
|
2608
|
+
* failed venue, so the routed venue is read alone: a failure rejects
|
|
2609
|
+
* instead of reading as missing markets.
|
|
2610
|
+
*
|
|
2611
|
+
* @param provider - Active provider.
|
|
2612
|
+
* @param providerId - Optional explicit route.
|
|
2613
|
+
* @param marketsParams - Optional market filter and cache bypass.
|
|
2614
|
+
* @returns The venue's markets as metadata.
|
|
2615
|
+
*/
|
|
2616
|
+
async #readMarketMetas(provider, providerId, marketsParams) {
|
|
2617
|
+
const markets = provider instanceof AggregatedPerpsProvider
|
|
2618
|
+
? await provider.getProviderMarkets(provider.getWriteProviderId(providerId), marketsParams)
|
|
2619
|
+
: await provider.getMarkets(marketsParams);
|
|
2620
|
+
return markets.map((market) => ({
|
|
2621
|
+
symbol: market.name,
|
|
2622
|
+
marginTiers: market.marginTiers ?? null,
|
|
2623
|
+
isDelisted: market.isDelisted === true,
|
|
2624
|
+
maxLeverage: market.maxLeverage,
|
|
2625
|
+
onlyIsolated: !isCrossMarginSupported(market),
|
|
2626
|
+
}));
|
|
2627
|
+
}
|
|
2628
|
+
/**
|
|
2629
|
+
* Stream every market's metadata (margin tiers, delisting, max leverage,
|
|
2630
|
+
* Cross support) from the routed venue. The callback receives the current
|
|
2631
|
+
* list at once, from the provider's session cache, then a new list each
|
|
2632
|
+
* time the market data preload refreshes (`startMarketDataPreload`), which
|
|
2633
|
+
* re-reads the venue's metadata. It adds no timer of its own. A failed read
|
|
2634
|
+
* goes to `onError` and leaves the last list current; an empty list is
|
|
2635
|
+
* never reported for a failure. In aggregated mode an unrouted stream
|
|
2636
|
+
* rebinds to the new default provider.
|
|
2637
|
+
*
|
|
2638
|
+
* @param params - Optional provider route, callback and error handler.
|
|
2639
|
+
* @returns Cleanup function.
|
|
2640
|
+
*/
|
|
2641
|
+
subscribeToMarketMeta(params) {
|
|
2642
|
+
return this.#subscribeToChannel('marketMeta', params, (channelParams) => this.#openMarketMeta(channelParams));
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Open the venue subscription behind a `marketMeta` channel.
|
|
2646
|
+
*
|
|
2647
|
+
* @param params - The channel's parameters.
|
|
2648
|
+
* @returns A cleanup function to remove the subscription.
|
|
2649
|
+
*/
|
|
2650
|
+
#openMarketMeta(params) {
|
|
2651
|
+
const provider = this.getActiveProviderOrNull();
|
|
2652
|
+
if (!provider ||
|
|
2653
|
+
this.#hasConflictingProviderRoute(params.providerId, provider)) {
|
|
2654
|
+
params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
|
|
2655
|
+
return () => undefined;
|
|
2656
|
+
}
|
|
2657
|
+
const subscriber = { params, lastList: null };
|
|
2658
|
+
const open = (nextProvider) => {
|
|
2659
|
+
subscriber.provider = nextProvider;
|
|
2660
|
+
subscriber.lastList = null;
|
|
2661
|
+
this.#marketMetaSubscribers.add(subscriber);
|
|
2662
|
+
this.#emitMarketMeta(subscriber, false).catch(() => undefined);
|
|
2663
|
+
return () => {
|
|
2664
|
+
this.#marketMetaSubscribers.delete(subscriber);
|
|
2665
|
+
};
|
|
2666
|
+
};
|
|
2667
|
+
return this.#trackProviderSubscription(provider, open);
|
|
2668
|
+
}
|
|
2669
|
+
/**
|
|
2670
|
+
* Read the subscriber's venue and report its list when it changed.
|
|
2671
|
+
*
|
|
2672
|
+
* @param subscriber - Market metadata subscriber.
|
|
2673
|
+
* @param skipCache - Re-read the venue's metadata instead of the cache.
|
|
2674
|
+
*/
|
|
2675
|
+
async #emitMarketMeta(subscriber, skipCache) {
|
|
2676
|
+
const { provider, params } = subscriber;
|
|
2677
|
+
if (!provider) {
|
|
2678
|
+
return;
|
|
2679
|
+
}
|
|
2680
|
+
try {
|
|
2681
|
+
const metas = await this.#readMarketMetas(provider, params.providerId, skipCache ? { skipCache: true } : undefined);
|
|
2682
|
+
// A subscriber that left, or rebound to another provider, during the
|
|
2683
|
+
// read gets nothing; an empty read is a failure, not a delisting.
|
|
2684
|
+
if (!this.#marketMetaSubscribers.has(subscriber) ||
|
|
2685
|
+
subscriber.provider !== provider) {
|
|
2686
|
+
return;
|
|
2687
|
+
}
|
|
2688
|
+
if (metas.length === 0) {
|
|
2689
|
+
throw new Error(PERPS_ERROR_CODES.MARKETS_FAILED);
|
|
2690
|
+
}
|
|
2691
|
+
const list = JSON.stringify(metas);
|
|
2692
|
+
if (list === subscriber.lastList) {
|
|
2693
|
+
return;
|
|
2694
|
+
}
|
|
2695
|
+
subscriber.lastList = list;
|
|
2696
|
+
params.callback(metas);
|
|
2697
|
+
}
|
|
2698
|
+
catch (error) {
|
|
2699
|
+
if (this.#marketMetaSubscribers.has(subscriber)) {
|
|
2700
|
+
params.onError?.(ensureError(error, 'PerpsController.subscribeToMarketMeta'));
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
/** Re-read every market metadata subscriber's venue after a preload. */
|
|
2705
|
+
#refreshMarketMetaSubscribers() {
|
|
2706
|
+
for (const subscriber of this.#marketMetaSubscribers) {
|
|
2707
|
+
this.#emitMarketMeta(subscriber, true).catch(() => undefined);
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
/**
|
|
2711
|
+
* Stream an isolated position's margin adjustment limits from the routed
|
|
2712
|
+
* provider's live account and position streams, with no venue reads. The
|
|
2713
|
+
* callback receives the current limits at once, then each change: the
|
|
2714
|
+
* same result `getMarginAdjustmentLimits` returns. A provider without the
|
|
2715
|
+
* stream, or a route that conflicts with the active provider, reports
|
|
2716
|
+
* `unavailable`/`provider` once.
|
|
2717
|
+
*
|
|
2718
|
+
* @param params - Market, optional route, callback and error handler.
|
|
2719
|
+
* @returns Cleanup function.
|
|
2720
|
+
*/
|
|
2721
|
+
subscribeToMarginAdjustmentLimits(params) {
|
|
2722
|
+
return this.#subscribeToChannel('marginAdjustmentLimits', params, (channelParams) => this.#openMarginAdjustmentLimits(channelParams));
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* Open the venue subscription behind a `marginAdjustmentLimits` channel.
|
|
2726
|
+
*
|
|
2727
|
+
* @param params - The channel's parameters.
|
|
2728
|
+
* @returns A cleanup function to remove the subscription.
|
|
2729
|
+
*/
|
|
2730
|
+
#openMarginAdjustmentLimits(params) {
|
|
2731
|
+
const unsupported = () => {
|
|
2732
|
+
params.callback({ status: 'unavailable', reason: 'provider' });
|
|
2733
|
+
return () => undefined;
|
|
2734
|
+
};
|
|
2735
|
+
const provider = this.getActiveProviderOrNull();
|
|
2736
|
+
if (!provider ||
|
|
2737
|
+
this.#hasConflictingProviderRoute(params.providerId, provider)) {
|
|
2738
|
+
return unsupported();
|
|
2739
|
+
}
|
|
2740
|
+
try {
|
|
2741
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider) ||
|
|
2742
|
+
!nextProvider.subscribeToMarginAdjustmentLimits
|
|
2743
|
+
? unsupported()
|
|
2744
|
+
: nextProvider.subscribeToMarginAdjustmentLimits(params));
|
|
2745
|
+
}
|
|
2746
|
+
catch (error) {
|
|
2747
|
+
this.#logError(ensureError(error, 'PerpsController.subscribeToMarginAdjustmentLimits'), this.#getErrorContext('subscribeToMarginAdjustmentLimits', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
|
|
2748
|
+
return unsupported();
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Stream the routed provider's WebSocket keepalive round trip, in whole
|
|
2753
|
+
* milliseconds. The callback receives the last measurement at once when
|
|
2754
|
+
* there is one, then each new one, at the keepalive's own cadence. A
|
|
2755
|
+
* provider without a keepalive measurement never calls back.
|
|
2756
|
+
*
|
|
2757
|
+
* @param params - Optional provider route, callback and error handler.
|
|
2758
|
+
* @returns Cleanup function.
|
|
2759
|
+
*/
|
|
2760
|
+
subscribeToConnectionLatency(params) {
|
|
2761
|
+
return this.#subscribeToChannel('connectionLatency', params, (channelParams) => this.#openConnectionLatency(channelParams));
|
|
2762
|
+
}
|
|
2763
|
+
/**
|
|
2764
|
+
* Open the venue subscription behind a `connectionLatency` channel.
|
|
2765
|
+
*
|
|
2766
|
+
* @param params - The channel's parameters.
|
|
2767
|
+
* @returns A cleanup function to remove the subscription.
|
|
2768
|
+
*/
|
|
2769
|
+
#openConnectionLatency(params) {
|
|
2770
|
+
const provider = this.getActiveProviderOrNull();
|
|
2771
|
+
if (!provider ||
|
|
2772
|
+
this.#hasConflictingProviderRoute(params.providerId, provider)) {
|
|
2773
|
+
return () => undefined;
|
|
2774
|
+
}
|
|
2775
|
+
try {
|
|
2776
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
|
|
2777
|
+
? () => undefined
|
|
2778
|
+
: (nextProvider.subscribeToConnectionLatency?.(params) ??
|
|
2779
|
+
(() => undefined)));
|
|
2780
|
+
}
|
|
2781
|
+
catch (error) {
|
|
2782
|
+
params.onError?.(ensureError(error, 'PerpsController.subscribeToConnectionLatency'));
|
|
2783
|
+
return () => undefined;
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
/**
|
|
2787
|
+
* Stream a market's post-discount fee rates: the `calculateFees` results
|
|
2788
|
+
* for a taker and a maker fill. The callback receives one read at once,
|
|
2789
|
+
* then a new read only on events: a fill on the account's own fills stream
|
|
2790
|
+
* (its volume tier can change), an account switch, a default provider
|
|
2791
|
+
* change in aggregated mode, and `invalidateSubscriptionBenefits`. There is
|
|
2792
|
+
* no timer. A failed read goes to `onError` and leaves the last rates
|
|
2793
|
+
* current; an unchanged read is not delivered.
|
|
2794
|
+
*
|
|
2795
|
+
* @param params - Market, optional order type, route, account, callback
|
|
2796
|
+
* and error handler.
|
|
2797
|
+
* @returns Cleanup function.
|
|
2798
|
+
*/
|
|
2799
|
+
subscribeToFeeRates(params) {
|
|
2800
|
+
return this.#subscribeToChannel('feeRates', params, (channelParams) => this.#openFeeRates(channelParams));
|
|
2801
|
+
}
|
|
2802
|
+
/**
|
|
2803
|
+
* Open the reads behind a `feeRates` channel.
|
|
2804
|
+
*
|
|
2805
|
+
* @param params - The channel's parameters.
|
|
2806
|
+
* @returns A cleanup function to stop the reads.
|
|
2807
|
+
*/
|
|
2808
|
+
#openFeeRates(params) {
|
|
2809
|
+
const provider = this.getActiveProviderOrNull();
|
|
2810
|
+
if (!provider) {
|
|
2811
|
+
params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
|
|
2812
|
+
return () => undefined;
|
|
2813
|
+
}
|
|
2814
|
+
const { symbol, orderType, providerId, accountId } = params;
|
|
2815
|
+
let closed = false;
|
|
2816
|
+
let readId = 0;
|
|
2817
|
+
let last;
|
|
2818
|
+
const read = () => {
|
|
2819
|
+
readId += 1;
|
|
2820
|
+
const id = readId;
|
|
2821
|
+
const quote = async (isMaker) => await this.calculateFees({
|
|
2822
|
+
symbol,
|
|
2823
|
+
providerId,
|
|
2824
|
+
isMaker,
|
|
2825
|
+
orderType: orderType ?? (isMaker ? 'limit' : 'market'),
|
|
2826
|
+
});
|
|
2827
|
+
Promise.all([quote(false), quote(true)])
|
|
2828
|
+
.then(([taker, maker]) => {
|
|
2829
|
+
// Only the newest read is reported, so an older one never wins.
|
|
2830
|
+
if (closed || id !== readId) {
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
const rates = { symbol, taker, maker };
|
|
2834
|
+
const key = JSON.stringify(rates);
|
|
2835
|
+
if (key !== last) {
|
|
2836
|
+
last = key;
|
|
2837
|
+
params.callback(rates);
|
|
2838
|
+
}
|
|
2839
|
+
})
|
|
2840
|
+
.catch((error) => {
|
|
2841
|
+
if (!closed && id === readId) {
|
|
2842
|
+
params.onError?.(ensureError(error, 'PerpsController.subscribeToFeeRates'));
|
|
2843
|
+
}
|
|
2844
|
+
});
|
|
2845
|
+
};
|
|
2846
|
+
this.#feeRateRefreshers.add(read);
|
|
2847
|
+
// Re-read when the aggregated default provider changes as well.
|
|
2848
|
+
const stopRoute = this.#trackProviderSubscription(provider, () => {
|
|
2849
|
+
read();
|
|
2850
|
+
return () => undefined;
|
|
2851
|
+
});
|
|
2852
|
+
const stopFills = this.subscribeToOrderFills({
|
|
2853
|
+
accountId,
|
|
2854
|
+
callback: (_fills, isSnapshot) => {
|
|
2855
|
+
if (!isSnapshot) {
|
|
2856
|
+
read();
|
|
2857
|
+
}
|
|
2858
|
+
},
|
|
2859
|
+
});
|
|
2860
|
+
// An account switch rebinds the channel, which reopens this read.
|
|
2861
|
+
return () => {
|
|
2862
|
+
closed = true;
|
|
2863
|
+
this.#feeRateRefreshers.delete(read);
|
|
2864
|
+
stopRoute();
|
|
2865
|
+
stopFills();
|
|
2866
|
+
};
|
|
2867
|
+
}
|
|
2868
|
+
/**
|
|
2869
|
+
* Report whether the selected (or given) account's trading agent is valid
|
|
2870
|
+
* for the routed venue (`PerpsTradingAgentValidity`). The callback receives
|
|
2871
|
+
* one read at once, then a new value on events only: an agent set or
|
|
2872
|
+
* cleared (`setAgentSigner`, `clearAgentSigners`), a venue rejection of the
|
|
2873
|
+
* agent, an account switch, and the agent's `validUntil` expiry, a single
|
|
2874
|
+
* timeout at that deadline. A venue without an agent step reports
|
|
2875
|
+
* `not_required`.
|
|
2876
|
+
*
|
|
2877
|
+
* @param params - Optional account and route, callback and error handler.
|
|
2878
|
+
* @returns Cleanup function.
|
|
2879
|
+
*/
|
|
2880
|
+
subscribeToTradingAgentValidity(params) {
|
|
2881
|
+
return this.#subscribeToChannel('tradingAgentValidity', params, (channelParams) => this.#openTradingAgentValidity(channelParams));
|
|
2882
|
+
}
|
|
2883
|
+
/**
|
|
2884
|
+
* Open the venue subscription behind a `tradingAgentValidity` channel.
|
|
2885
|
+
*
|
|
2886
|
+
* @param params - The channel's parameters.
|
|
2887
|
+
* @returns A cleanup function to remove the subscription.
|
|
2888
|
+
*/
|
|
2889
|
+
#openTradingAgentValidity(params) {
|
|
2890
|
+
const provider = this.getActiveProviderOrNull();
|
|
2891
|
+
if (!provider ||
|
|
2892
|
+
this.#hasConflictingProviderRoute(params.providerId, provider)) {
|
|
2893
|
+
params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
|
|
2894
|
+
return () => undefined;
|
|
2895
|
+
}
|
|
2896
|
+
const open = (nextProvider) => {
|
|
2897
|
+
if (!nextProvider.subscribeToTradingAgentValidity) {
|
|
2898
|
+
params.callback({ status: 'not_required' });
|
|
2899
|
+
return () => undefined;
|
|
2900
|
+
}
|
|
2901
|
+
return nextProvider.subscribeToTradingAgentValidity(params);
|
|
2902
|
+
};
|
|
2903
|
+
try {
|
|
2904
|
+
// An account switch rebinds the channel, which reads the new account's
|
|
2905
|
+
// agent afresh.
|
|
2906
|
+
return this.#trackProviderSubscription(provider, open);
|
|
2907
|
+
}
|
|
2908
|
+
catch (error) {
|
|
2909
|
+
params.onError?.(ensureError(error, 'PerpsController.subscribeToTradingAgentValidity'));
|
|
2910
|
+
return () => undefined;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2491
2913
|
#getUnavailableMarginModeLock(reason, providerId) {
|
|
2492
2914
|
return providerId
|
|
2493
2915
|
? { status: 'unavailable', providerId, reason }
|
|
@@ -4297,6 +4719,10 @@ export class PerpsController extends BaseController {
|
|
|
4297
4719
|
'hip3ConfigVersion',
|
|
4298
4720
|
]);
|
|
4299
4721
|
#preloadTimer = null;
|
|
4722
|
+
/** Market metadata streams, refreshed after each market data preload. */
|
|
4723
|
+
#marketMetaSubscribers = new Set();
|
|
4724
|
+
/** Fee rate streams, re-read when subscription benefits are invalidated. */
|
|
4725
|
+
#feeRateRefreshers = new Set();
|
|
4300
4726
|
#preloadStartRequested = false;
|
|
4301
4727
|
#isPreloading = false;
|
|
4302
4728
|
#marketPreloadQueued = false;
|
|
@@ -4392,7 +4818,9 @@ export class PerpsController extends BaseController {
|
|
|
4392
4818
|
this.#previousIsTestnet = this.state.isTestnet;
|
|
4393
4819
|
this.#previousHip3ConfigVersion = this.state.hip3ConfigVersion;
|
|
4394
4820
|
// Immediate preload
|
|
4395
|
-
this.#performMarketDataPreload()
|
|
4821
|
+
this.#performMarketDataPreload()
|
|
4822
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
4823
|
+
.catch(() => {
|
|
4396
4824
|
/* fire-and-forget */
|
|
4397
4825
|
});
|
|
4398
4826
|
this.#performUserDataPreload().catch(() => {
|
|
@@ -4400,7 +4828,9 @@ export class PerpsController extends BaseController {
|
|
|
4400
4828
|
});
|
|
4401
4829
|
// Periodic refresh
|
|
4402
4830
|
this.#preloadTimer = setInterval(() => {
|
|
4403
|
-
this.#performMarketDataPreload()
|
|
4831
|
+
this.#performMarketDataPreload()
|
|
4832
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
4833
|
+
.catch(() => {
|
|
4404
4834
|
/* fire-and-forget */
|
|
4405
4835
|
});
|
|
4406
4836
|
this.#performUserDataPreload().catch(() => {
|
|
@@ -4431,7 +4861,9 @@ export class PerpsController extends BaseController {
|
|
|
4431
4861
|
// No need to clear user data cache — per-provider keys include the
|
|
4432
4862
|
// network, so different networks don't collide. Re-preload will
|
|
4433
4863
|
// populate the new key.
|
|
4434
|
-
this.#performMarketDataPreload()
|
|
4864
|
+
this.#performMarketDataPreload()
|
|
4865
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
4866
|
+
.catch(() => {
|
|
4435
4867
|
/* fire-and-forget */
|
|
4436
4868
|
});
|
|
4437
4869
|
this.#performUserDataPreload().catch(() => {
|
|
@@ -4664,7 +5096,9 @@ export class PerpsController extends BaseController {
|
|
|
4664
5096
|
this.#isPreloading = false;
|
|
4665
5097
|
if (this.#marketPreloadQueued && this.#preloadTimer) {
|
|
4666
5098
|
this.#marketPreloadQueued = false;
|
|
4667
|
-
this.#performMarketDataPreload()
|
|
5099
|
+
this.#performMarketDataPreload()
|
|
5100
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
5101
|
+
.catch(() => {
|
|
4668
5102
|
// Background preload is best-effort.
|
|
4669
5103
|
});
|
|
4670
5104
|
}
|
|
@@ -4970,9 +5404,10 @@ export class PerpsController extends BaseController {
|
|
|
4970
5404
|
});
|
|
4971
5405
|
}
|
|
4972
5406
|
/**
|
|
4973
|
-
* Project the
|
|
5407
|
+
* Project the position that would remain after a proposed order.
|
|
4974
5408
|
* Margin and liquidation availability are independent: a missing liquidation
|
|
4975
|
-
* does not hide a valid margin projection.
|
|
5409
|
+
* does not hide a valid margin projection. Hyperliquid projects Cross
|
|
5410
|
+
* positions against the account's Cross collateral.
|
|
4976
5411
|
*
|
|
4977
5412
|
* @param params - Live position plus the proposed order.
|
|
4978
5413
|
* @returns Discriminated preview of the resulting position.
|
|
@@ -4986,6 +5421,28 @@ export class PerpsController extends BaseController {
|
|
|
4986
5421
|
context,
|
|
4987
5422
|
});
|
|
4988
5423
|
}
|
|
5424
|
+
/**
|
|
5425
|
+
* Estimate the liquidation price of the Cross position an order would
|
|
5426
|
+
* leave: an opening, or an add, reduce or flip of the market's position.
|
|
5427
|
+
* Never rejects: `price`, `none` when no price liquidates it at the
|
|
5428
|
+
* account's collateral, or `unavailable` with a typed reason.
|
|
5429
|
+
*
|
|
5430
|
+
* @param params - The proposed Cross order.
|
|
5431
|
+
* @returns The typed estimate.
|
|
5432
|
+
*/
|
|
5433
|
+
async estimateCrossLiquidation(params) {
|
|
5434
|
+
// Not initialized or reinitializing: no provider to ask. A direct-mode
|
|
5435
|
+
// route that names another venue would answer for the wrong venue.
|
|
5436
|
+
const provider = this.getActiveProviderOrNull();
|
|
5437
|
+
if (!provider ||
|
|
5438
|
+
this.#hasConflictingProviderRoute(params.providerId, provider)) {
|
|
5439
|
+
return { status: 'unavailable', reason: 'provider' };
|
|
5440
|
+
}
|
|
5441
|
+
return this.#marketDataService.estimateCrossLiquidation({
|
|
5442
|
+
provider,
|
|
5443
|
+
params,
|
|
5444
|
+
});
|
|
5445
|
+
}
|
|
4989
5446
|
/**
|
|
4990
5447
|
* Calculate maintenance margin for a specific asset
|
|
4991
5448
|
* Returns a percentage (e.g., 0.0125 for 1.25%)
|
|
@@ -5225,7 +5682,9 @@ export class PerpsController extends BaseController {
|
|
|
5225
5682
|
// The state-change listener may have already fired during reinit
|
|
5226
5683
|
// but was skipped due to the #isReinitializing guard.
|
|
5227
5684
|
if (this.#preloadTimer) {
|
|
5228
|
-
this.#performMarketDataPreload()
|
|
5685
|
+
this.#performMarketDataPreload()
|
|
5686
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
5687
|
+
.catch(() => {
|
|
5229
5688
|
/* fire-and-forget */
|
|
5230
5689
|
});
|
|
5231
5690
|
this.#performUserDataPreload().catch(() => {
|
|
@@ -5392,7 +5851,9 @@ export class PerpsController extends BaseController {
|
|
|
5392
5851
|
completeReinitialization();
|
|
5393
5852
|
// Re-trigger preload now that reinit is complete.
|
|
5394
5853
|
if (this.#preloadTimer) {
|
|
5395
|
-
this.#performMarketDataPreload()
|
|
5854
|
+
this.#performMarketDataPreload()
|
|
5855
|
+
.then(() => this.#refreshMarketMetaSubscribers())
|
|
5856
|
+
.catch(() => {
|
|
5396
5857
|
/* fire-and-forget */
|
|
5397
5858
|
});
|
|
5398
5859
|
this.#performUserDataPreload().catch(() => {
|
|
@@ -5599,17 +6060,16 @@ export class PerpsController extends BaseController {
|
|
|
5599
6060
|
*
|
|
5600
6061
|
* @param provider - Initially active provider.
|
|
5601
6062
|
* @param open - Opens this subscription on a provider.
|
|
5602
|
-
* @param onInvalidate - Invalidates a cached value while the route is detached.
|
|
5603
6063
|
* @returns Cleanup that always removes the current binding.
|
|
5604
6064
|
*/
|
|
5605
|
-
#trackProviderSubscription(provider, open
|
|
5606
|
-
if (provider.protocolId !== 'aggregated'
|
|
6065
|
+
#trackProviderSubscription(provider, open) {
|
|
6066
|
+
if (provider.protocolId !== 'aggregated' ||
|
|
6067
|
+
this.#openingChannelSources > 0) {
|
|
5607
6068
|
return open(provider);
|
|
5608
6069
|
}
|
|
5609
6070
|
const subscription = {
|
|
5610
6071
|
open,
|
|
5611
6072
|
unsubscribe: open(provider),
|
|
5612
|
-
onInvalidate,
|
|
5613
6073
|
};
|
|
5614
6074
|
this.#providerSubscriptions.add(subscription);
|
|
5615
6075
|
return () => {
|
|
@@ -5641,15 +6101,10 @@ export class PerpsController extends BaseController {
|
|
|
5641
6101
|
catch (error) {
|
|
5642
6102
|
this.#logProviderSubscriptionError(error);
|
|
5643
6103
|
}
|
|
5644
|
-
if (!discard && this.#providerSubscriptions.has(subscription)) {
|
|
5645
|
-
try {
|
|
5646
|
-
subscription.onInvalidate?.();
|
|
5647
|
-
}
|
|
5648
|
-
catch (error) {
|
|
5649
|
-
this.#logProviderSubscriptionError(error);
|
|
5650
|
-
}
|
|
5651
|
-
}
|
|
5652
6104
|
}
|
|
6105
|
+
// Stream channels stop before their provider disconnects; readers stay
|
|
6106
|
+
// and the next successful initialization reopens them.
|
|
6107
|
+
this.#streams.rebind((key) => key.providerId === PENDING_PROVIDER_CHANNEL_ID, (key) => ({ ...key, providerId: PENDING_PROVIDER_CHANNEL_ID }));
|
|
5653
6108
|
}
|
|
5654
6109
|
/** Reattach surviving registrations after rollback or a later recovery. */
|
|
5655
6110
|
#restoreProviderSubscriptions() {
|
|
@@ -5685,6 +6140,148 @@ export class PerpsController extends BaseController {
|
|
|
5685
6140
|
#logProviderSubscriptionError(error) {
|
|
5686
6141
|
this.#logError(ensureError(error, 'PerpsController.providerSubscriptionRollback'), this.#getErrorContext('providerSubscriptionRollback'));
|
|
5687
6142
|
}
|
|
6143
|
+
/**
|
|
6144
|
+
* Join the shared channel for one `subscribeTo*` call, opening the venue
|
|
6145
|
+
* subscription when it is the first reader. The key comes from
|
|
6146
|
+
* `#getChannelKey`. A call made while no provider is active joins a pending
|
|
6147
|
+
* channel that opens on the next successful initialization.
|
|
6148
|
+
*
|
|
6149
|
+
* @param stream - Stream name.
|
|
6150
|
+
* @param params - The caller's parameters.
|
|
6151
|
+
* @param open - Opens the venue subscription for the channel.
|
|
6152
|
+
* @param source - Replay and REST seed behaviour of the stream.
|
|
6153
|
+
* @param source.replay - Replay the last value to later readers.
|
|
6154
|
+
* @param source.read - REST read seeding the channel and run once per drop.
|
|
6155
|
+
* @returns Cleanup that leaves the channel.
|
|
6156
|
+
*/
|
|
6157
|
+
#subscribeToChannel(stream, params, open, source = {}) {
|
|
6158
|
+
const { callback, onError, throttleMs, onReset, ...options } = params;
|
|
6159
|
+
const { read } = source;
|
|
6160
|
+
return this.#streams.subscribe(this.#getChannelKey(stream, options), {
|
|
6161
|
+
...source,
|
|
6162
|
+
read: read
|
|
6163
|
+
? async (key) => key.providerId === PENDING_PROVIDER_CHANNEL_ID
|
|
6164
|
+
? undefined
|
|
6165
|
+
: await read()
|
|
6166
|
+
: undefined,
|
|
6167
|
+
open: (emit, fail, key) => {
|
|
6168
|
+
// A pending channel opens when `#rebindStreams` finds a provider.
|
|
6169
|
+
if (key.providerId === PENDING_PROVIDER_CHANNEL_ID) {
|
|
6170
|
+
return () => undefined;
|
|
6171
|
+
}
|
|
6172
|
+
this.#openingChannelSources += 1;
|
|
6173
|
+
try {
|
|
6174
|
+
return open({
|
|
6175
|
+
...params,
|
|
6176
|
+
throttleMs: undefined,
|
|
6177
|
+
onReset: undefined,
|
|
6178
|
+
callback: emit,
|
|
6179
|
+
// Every reader of the channel hears its failures, not only the
|
|
6180
|
+
// reader that opened it.
|
|
6181
|
+
onError: fail,
|
|
6182
|
+
});
|
|
6183
|
+
}
|
|
6184
|
+
finally {
|
|
6185
|
+
this.#openingChannelSources -= 1;
|
|
6186
|
+
}
|
|
6187
|
+
},
|
|
6188
|
+
}, { callback, onError, throttleMs, onReset });
|
|
6189
|
+
}
|
|
6190
|
+
/**
|
|
6191
|
+
* The channel key of a stream: every parameter but the callbacks and
|
|
6192
|
+
* `throttleMs` (each reader throttles on its own), the active provider
|
|
6193
|
+
* instance, and for account streams the account, the selected one when none
|
|
6194
|
+
* is given. `prices` symbols are sorted so their order does not split
|
|
6195
|
+
* channels.
|
|
6196
|
+
*
|
|
6197
|
+
* @param stream - Stream name.
|
|
6198
|
+
* @param options - The stream's parameters without callbacks.
|
|
6199
|
+
* @returns The channel key.
|
|
6200
|
+
*/
|
|
6201
|
+
#getChannelKey(stream, options) {
|
|
6202
|
+
const provider = this.getActiveProviderOrNull();
|
|
6203
|
+
const { symbols } = options;
|
|
6204
|
+
return {
|
|
6205
|
+
stream,
|
|
6206
|
+
providerId: provider
|
|
6207
|
+
? String(this.#getProviderChannelId(provider))
|
|
6208
|
+
: PENDING_PROVIDER_CHANNEL_ID,
|
|
6209
|
+
accountId: ACCOUNT_STREAMS.has(stream)
|
|
6210
|
+
? this.#getChannelAccountId(options)
|
|
6211
|
+
: undefined,
|
|
6212
|
+
options: stream === 'prices' && Array.isArray(symbols)
|
|
6213
|
+
? { ...options, symbols: symbols.map(String).sort() }
|
|
6214
|
+
: options,
|
|
6215
|
+
};
|
|
6216
|
+
}
|
|
6217
|
+
/**
|
|
6218
|
+
* Move channels whose provider or selected account changed to the current
|
|
6219
|
+
* one: readers keep their subscription, receive `onReset`, then the new
|
|
6220
|
+
* context's data. Pending channels open here. Does nothing while no
|
|
6221
|
+
* provider is active.
|
|
6222
|
+
*/
|
|
6223
|
+
#rebindStreams() {
|
|
6224
|
+
if (!this.getActiveProviderOrNull()) {
|
|
6225
|
+
return;
|
|
6226
|
+
}
|
|
6227
|
+
const nextKey = (key) => this.#getChannelKey(key.stream, key.options ?? {});
|
|
6228
|
+
this.#streams.rebind((key) => {
|
|
6229
|
+
const next = nextKey(key);
|
|
6230
|
+
return (next.providerId === key.providerId && next.accountId === key.accountId);
|
|
6231
|
+
}, nextKey);
|
|
6232
|
+
}
|
|
6233
|
+
/**
|
|
6234
|
+
* The last value a stream's channel delivered, for a synchronous first
|
|
6235
|
+
* render (such as React's `useSyncExternalStore`). Uses the same channel
|
|
6236
|
+
* as a `subscribeTo*` call with these parameters.
|
|
6237
|
+
*
|
|
6238
|
+
* @param stream - Stream name.
|
|
6239
|
+
* @param params - The `subscribeTo*` parameters; callbacks and throttle are
|
|
6240
|
+
* ignored.
|
|
6241
|
+
* @returns The callback arguments last delivered, or `undefined` when the
|
|
6242
|
+
* channel is not open or has no value yet.
|
|
6243
|
+
*/
|
|
6244
|
+
getStreamSnapshot(stream, params) {
|
|
6245
|
+
const { callback: _callback, onError: _onError, onReset: _onReset, throttleMs: _throttleMs, ...options } = params;
|
|
6246
|
+
return this.#streams.getLast(this.#getChannelKey(stream, options));
|
|
6247
|
+
}
|
|
6248
|
+
/**
|
|
6249
|
+
* Stop and restart every open stream's venue subscription, keeping readers
|
|
6250
|
+
* and last values. For a socket that reports open but no longer delivers,
|
|
6251
|
+
* such as after an app returns to the foreground.
|
|
6252
|
+
*/
|
|
6253
|
+
resubscribeStreams() {
|
|
6254
|
+
this.#streams.reopenAll();
|
|
6255
|
+
}
|
|
6256
|
+
/**
|
|
6257
|
+
* Account part of an account stream's channel key: the explicit account,
|
|
6258
|
+
* else the selected one.
|
|
6259
|
+
*
|
|
6260
|
+
* @param options - The stream's parameters without callbacks.
|
|
6261
|
+
* @returns The account key.
|
|
6262
|
+
*/
|
|
6263
|
+
#getChannelAccountId(options) {
|
|
6264
|
+
if ('accountId' in options && typeof options.accountId === 'string') {
|
|
6265
|
+
return options.accountId;
|
|
6266
|
+
}
|
|
6267
|
+
const selected = getSelectedEvmAccountFromMessenger(this.messenger);
|
|
6268
|
+
return `selected:${selected?.address.toLowerCase() ?? 'none'}`;
|
|
6269
|
+
}
|
|
6270
|
+
/**
|
|
6271
|
+
* Stable id of a provider instance for channel keys.
|
|
6272
|
+
*
|
|
6273
|
+
* @param provider - Provider instance.
|
|
6274
|
+
* @returns Its id.
|
|
6275
|
+
*/
|
|
6276
|
+
#getProviderChannelId(provider) {
|
|
6277
|
+
let id = this.#providerChannelIds.get(provider);
|
|
6278
|
+
if (id === undefined) {
|
|
6279
|
+
this.#nextProviderChannelId += 1;
|
|
6280
|
+
id = this.#nextProviderChannelId;
|
|
6281
|
+
this.#providerChannelIds.set(provider, id);
|
|
6282
|
+
}
|
|
6283
|
+
return id;
|
|
6284
|
+
}
|
|
5688
6285
|
// Live data delegation (NO Redux) - delegates to active provider
|
|
5689
6286
|
/**
|
|
5690
6287
|
* Subscribe to live price updates
|
|
@@ -5693,6 +6290,15 @@ export class PerpsController extends BaseController {
|
|
|
5693
6290
|
* @returns A cleanup function to remove the subscription.
|
|
5694
6291
|
*/
|
|
5695
6292
|
subscribeToPrices(params) {
|
|
6293
|
+
return this.#subscribeToChannel('prices', params, (channelParams) => this.#openPrices(channelParams));
|
|
6294
|
+
}
|
|
6295
|
+
/**
|
|
6296
|
+
* Open the venue subscription behind a `prices` channel.
|
|
6297
|
+
*
|
|
6298
|
+
* @param params - The channel's parameters.
|
|
6299
|
+
* @returns A cleanup function to remove the subscription.
|
|
6300
|
+
*/
|
|
6301
|
+
#openPrices(params) {
|
|
5696
6302
|
const provider = this.getActiveProviderOrNull();
|
|
5697
6303
|
if (!provider) {
|
|
5698
6304
|
return () => {
|
|
@@ -5718,6 +6324,19 @@ export class PerpsController extends BaseController {
|
|
|
5718
6324
|
* @returns A cleanup function to remove the subscription.
|
|
5719
6325
|
*/
|
|
5720
6326
|
subscribeToPositions(params) {
|
|
6327
|
+
return this.#subscribeToChannel('positions', params, (channelParams) => this.#openPositions(channelParams), {
|
|
6328
|
+
read: async () => params.accountId === undefined
|
|
6329
|
+
? [await this.getPositions(), params.includeSnapshotStatus]
|
|
6330
|
+
: undefined,
|
|
6331
|
+
});
|
|
6332
|
+
}
|
|
6333
|
+
/**
|
|
6334
|
+
* Open the venue subscription behind a `positions` channel.
|
|
6335
|
+
*
|
|
6336
|
+
* @param params - The channel's parameters.
|
|
6337
|
+
* @returns A cleanup function to remove the subscription.
|
|
6338
|
+
*/
|
|
6339
|
+
#openPositions(params) {
|
|
5721
6340
|
const provider = this.getActiveProviderOrNull();
|
|
5722
6341
|
if (!provider) {
|
|
5723
6342
|
return () => {
|
|
@@ -5743,6 +6362,15 @@ export class PerpsController extends BaseController {
|
|
|
5743
6362
|
* @returns A cleanup function to remove the subscription.
|
|
5744
6363
|
*/
|
|
5745
6364
|
subscribeToOrderFills(params) {
|
|
6365
|
+
return this.#subscribeToChannel('orderFills', params, (channelParams) => this.#openOrderFills(channelParams), { replay: false });
|
|
6366
|
+
}
|
|
6367
|
+
/**
|
|
6368
|
+
* Open the venue subscription behind a `orderFills` channel.
|
|
6369
|
+
*
|
|
6370
|
+
* @param params - The channel's parameters.
|
|
6371
|
+
* @returns A cleanup function to remove the subscription.
|
|
6372
|
+
*/
|
|
6373
|
+
#openOrderFills(params) {
|
|
5746
6374
|
const provider = this.getActiveProviderOrNull();
|
|
5747
6375
|
if (!provider) {
|
|
5748
6376
|
return () => {
|
|
@@ -5772,6 +6400,15 @@ export class PerpsController extends BaseController {
|
|
|
5772
6400
|
* @returns A cleanup function to remove the subscription.
|
|
5773
6401
|
*/
|
|
5774
6402
|
subscribeToTwapOrders(params) {
|
|
6403
|
+
return this.#subscribeToChannel('twapOrders', params, (channelParams) => this.#openTwapOrders(channelParams));
|
|
6404
|
+
}
|
|
6405
|
+
/**
|
|
6406
|
+
* Open the venue subscription behind a `twapOrders` channel.
|
|
6407
|
+
*
|
|
6408
|
+
* @param params - The channel's parameters.
|
|
6409
|
+
* @returns A cleanup function to remove the subscription.
|
|
6410
|
+
*/
|
|
6411
|
+
#openTwapOrders(params) {
|
|
5775
6412
|
const provider = this.getActiveProviderOrNull();
|
|
5776
6413
|
if (!provider?.subscribeToTwapOrders) {
|
|
5777
6414
|
return () => {
|
|
@@ -5779,7 +6416,7 @@ export class PerpsController extends BaseController {
|
|
|
5779
6416
|
};
|
|
5780
6417
|
}
|
|
5781
6418
|
try {
|
|
5782
|
-
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined)
|
|
6419
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined));
|
|
5783
6420
|
}
|
|
5784
6421
|
catch (error) {
|
|
5785
6422
|
this.#logError(ensureError(error, 'PerpsController.subscribeToTwapOrders'), this.#getErrorContext('subscribeToTwapOrders', {
|
|
@@ -5800,6 +6437,15 @@ export class PerpsController extends BaseController {
|
|
|
5800
6437
|
* @returns A cleanup function that stops reads and the stream.
|
|
5801
6438
|
*/
|
|
5802
6439
|
subscribeToLiveTwapOrders(params) {
|
|
6440
|
+
return this.#subscribeToChannel('liveTwapOrders', params, (channelParams) => this.#openLiveTwapOrders(channelParams));
|
|
6441
|
+
}
|
|
6442
|
+
/**
|
|
6443
|
+
* Open the venue subscription behind a `liveTwapOrders` channel.
|
|
6444
|
+
*
|
|
6445
|
+
* @param params - The channel's parameters.
|
|
6446
|
+
* @returns A cleanup function to remove the subscription.
|
|
6447
|
+
*/
|
|
6448
|
+
#openLiveTwapOrders(params) {
|
|
5803
6449
|
return createLiveTwapOrderList({
|
|
5804
6450
|
source: {
|
|
5805
6451
|
getTwapOrders: async () => await this.getTwapOrders(),
|
|
@@ -5872,6 +6518,15 @@ export class PerpsController extends BaseController {
|
|
|
5872
6518
|
* @returns A cleanup function that stops reads.
|
|
5873
6519
|
*/
|
|
5874
6520
|
subscribeToChaseOrderLists(params) {
|
|
6521
|
+
return this.#subscribeToChannel('chaseOrderLists', params, (channelParams) => this.#openChaseOrderLists(channelParams));
|
|
6522
|
+
}
|
|
6523
|
+
/**
|
|
6524
|
+
* Open the venue subscription behind a `chaseOrderLists` channel.
|
|
6525
|
+
*
|
|
6526
|
+
* @param params - The channel's parameters.
|
|
6527
|
+
* @returns A cleanup function to remove the subscription.
|
|
6528
|
+
*/
|
|
6529
|
+
#openChaseOrderLists(params) {
|
|
5875
6530
|
return createLiveChaseOrderList({
|
|
5876
6531
|
source: {
|
|
5877
6532
|
getChaseOrders: async () => await this.getChaseOrders(),
|
|
@@ -5927,6 +6582,23 @@ export class PerpsController extends BaseController {
|
|
|
5927
6582
|
* @returns A cleanup function to remove the subscription.
|
|
5928
6583
|
*/
|
|
5929
6584
|
subscribeToOrders(params) {
|
|
6585
|
+
return this.#subscribeToChannel('orders', params, (channelParams) => this.#openOrders(channelParams), {
|
|
6586
|
+
read: async () => params.accountId === undefined
|
|
6587
|
+
? [
|
|
6588
|
+
await this.getOpenOrders({ throwOnUnavailable: true }),
|
|
6589
|
+
undefined,
|
|
6590
|
+
params.includeSnapshotStatus,
|
|
6591
|
+
]
|
|
6592
|
+
: undefined,
|
|
6593
|
+
});
|
|
6594
|
+
}
|
|
6595
|
+
/**
|
|
6596
|
+
* Open the venue subscription behind a `orders` channel.
|
|
6597
|
+
*
|
|
6598
|
+
* @param params - The channel's parameters.
|
|
6599
|
+
* @returns A cleanup function to remove the subscription.
|
|
6600
|
+
*/
|
|
6601
|
+
#openOrders(params) {
|
|
5930
6602
|
const provider = this.getActiveProviderOrNull();
|
|
5931
6603
|
if (!provider) {
|
|
5932
6604
|
return () => {
|
|
@@ -5993,6 +6665,15 @@ export class PerpsController extends BaseController {
|
|
|
5993
6665
|
* @returns A cleanup function to remove the subscription.
|
|
5994
6666
|
*/
|
|
5995
6667
|
subscribeToAccount(params) {
|
|
6668
|
+
return this.#subscribeToChannel('account', params, (channelParams) => this.#openAccount(channelParams));
|
|
6669
|
+
}
|
|
6670
|
+
/**
|
|
6671
|
+
* Open the venue subscription behind a `account` channel.
|
|
6672
|
+
*
|
|
6673
|
+
* @param params - The channel's parameters.
|
|
6674
|
+
* @returns A cleanup function to remove the subscription.
|
|
6675
|
+
*/
|
|
6676
|
+
#openAccount(params) {
|
|
5996
6677
|
const provider = this.getActiveProviderOrNull();
|
|
5997
6678
|
if (!provider) {
|
|
5998
6679
|
return () => {
|
|
@@ -6110,7 +6791,7 @@ export class PerpsController extends BaseController {
|
|
|
6110
6791
|
}
|
|
6111
6792
|
throw error;
|
|
6112
6793
|
}
|
|
6113
|
-
}
|
|
6794
|
+
});
|
|
6114
6795
|
}
|
|
6115
6796
|
catch (error) {
|
|
6116
6797
|
this.#logError(ensureError(error, 'PerpsController.subscribeToAccount'), this.#getErrorContext('subscribeToAccount', {
|
|
@@ -6129,6 +6810,16 @@ export class PerpsController extends BaseController {
|
|
|
6129
6810
|
* @returns A cleanup function to remove the subscription.
|
|
6130
6811
|
*/
|
|
6131
6812
|
subscribeToOrderBook(params) {
|
|
6813
|
+
// A replaced transport does not restore the book; the channel reopens it.
|
|
6814
|
+
return this.#subscribeToChannel('orderBook', params, (channelParams) => this.#openOrderBook(channelParams), { reopenOnReconnect: true });
|
|
6815
|
+
}
|
|
6816
|
+
/**
|
|
6817
|
+
* Open the venue subscription behind a `orderBook` channel.
|
|
6818
|
+
*
|
|
6819
|
+
* @param params - The channel's parameters.
|
|
6820
|
+
* @returns A cleanup function to remove the subscription.
|
|
6821
|
+
*/
|
|
6822
|
+
#openOrderBook(params) {
|
|
6132
6823
|
const provider = this.getActiveProviderOrNull();
|
|
6133
6824
|
if (!provider) {
|
|
6134
6825
|
return () => {
|
|
@@ -6163,6 +6854,15 @@ export class PerpsController extends BaseController {
|
|
|
6163
6854
|
* @returns A cleanup function to remove the subscription.
|
|
6164
6855
|
*/
|
|
6165
6856
|
subscribeToAvailableToTrade(params) {
|
|
6857
|
+
return this.#subscribeToChannel('availableToTrade', params, (channelParams) => this.#openAvailableToTrade(channelParams));
|
|
6858
|
+
}
|
|
6859
|
+
/**
|
|
6860
|
+
* Open the venue subscription behind a `availableToTrade` channel.
|
|
6861
|
+
*
|
|
6862
|
+
* @param params - The channel's parameters.
|
|
6863
|
+
* @returns A cleanup function to remove the subscription.
|
|
6864
|
+
*/
|
|
6865
|
+
#openAvailableToTrade(params) {
|
|
6166
6866
|
const noop = () => {
|
|
6167
6867
|
// No-op: value unavailable for this route
|
|
6168
6868
|
};
|
|
@@ -6175,7 +6875,7 @@ export class PerpsController extends BaseController {
|
|
|
6175
6875
|
return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
|
|
6176
6876
|
? () => undefined
|
|
6177
6877
|
: (nextProvider.subscribeToAvailableToTrade?.(params) ??
|
|
6178
|
-
(() => undefined))
|
|
6878
|
+
(() => undefined)));
|
|
6179
6879
|
}
|
|
6180
6880
|
catch (error) {
|
|
6181
6881
|
this.#logError(ensureError(error, 'PerpsController.subscribeToAvailableToTrade'), this.#getErrorContext('subscribeToAvailableToTrade', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
|
|
@@ -6249,6 +6949,17 @@ export class PerpsController extends BaseController {
|
|
|
6249
6949
|
* @returns A cleanup function to remove the subscription.
|
|
6250
6950
|
*/
|
|
6251
6951
|
subscribeToPublicTrades(params) {
|
|
6952
|
+
return this.#subscribeToChannel('publicTrades', params, (channelParams) => this.#openPublicTrades(channelParams),
|
|
6953
|
+
// A replaced transport does not restore trades; the channel reopens it.
|
|
6954
|
+
{ replay: false, reopenOnReconnect: true });
|
|
6955
|
+
}
|
|
6956
|
+
/**
|
|
6957
|
+
* Open the venue subscription behind a `publicTrades` channel.
|
|
6958
|
+
*
|
|
6959
|
+
* @param params - The channel's parameters.
|
|
6960
|
+
* @returns A cleanup function to remove the subscription.
|
|
6961
|
+
*/
|
|
6962
|
+
#openPublicTrades(params) {
|
|
6252
6963
|
const noop = () => {
|
|
6253
6964
|
// No-op: no public trade feed for this route
|
|
6254
6965
|
};
|
|
@@ -6299,6 +7010,15 @@ export class PerpsController extends BaseController {
|
|
|
6299
7010
|
* @returns A cleanup function to remove the subscription.
|
|
6300
7011
|
*/
|
|
6301
7012
|
subscribeToCandles(params) {
|
|
7013
|
+
return this.#subscribeToChannel('candles', params, (channelParams) => this.#openCandles(channelParams));
|
|
7014
|
+
}
|
|
7015
|
+
/**
|
|
7016
|
+
* Open the venue subscription behind a `candles` channel.
|
|
7017
|
+
*
|
|
7018
|
+
* @param params - The channel's parameters.
|
|
7019
|
+
* @returns A cleanup function to remove the subscription.
|
|
7020
|
+
*/
|
|
7021
|
+
#openCandles(params) {
|
|
6302
7022
|
const provider = this.getActiveProviderOrNull();
|
|
6303
7023
|
if (!provider) {
|
|
6304
7024
|
return () => {
|
|
@@ -6327,6 +7047,15 @@ export class PerpsController extends BaseController {
|
|
|
6327
7047
|
* @returns A cleanup function to remove the subscription.
|
|
6328
7048
|
*/
|
|
6329
7049
|
subscribeToOICaps(params) {
|
|
7050
|
+
return this.#subscribeToChannel('oiCaps', params, (channelParams) => this.#openOICaps(channelParams));
|
|
7051
|
+
}
|
|
7052
|
+
/**
|
|
7053
|
+
* Open the venue subscription behind a `oiCaps` channel.
|
|
7054
|
+
*
|
|
7055
|
+
* @param params - The channel's parameters.
|
|
7056
|
+
* @returns A cleanup function to remove the subscription.
|
|
7057
|
+
*/
|
|
7058
|
+
#openOICaps(params) {
|
|
6330
7059
|
const provider = this.getActiveProviderOrNull();
|
|
6331
7060
|
if (!provider) {
|
|
6332
7061
|
return () => {
|
|
@@ -6550,6 +7279,10 @@ export class PerpsController extends BaseController {
|
|
|
6550
7279
|
*/
|
|
6551
7280
|
invalidateSubscriptionBenefits() {
|
|
6552
7281
|
this.#rewardsIntegrationService.invalidateSubscriptionBenefits();
|
|
7282
|
+
// The discount the fee rates were priced with may have changed.
|
|
7283
|
+
for (const refresh of this.#feeRateRefreshers) {
|
|
7284
|
+
refresh();
|
|
7285
|
+
}
|
|
6553
7286
|
}
|
|
6554
7287
|
/**
|
|
6555
7288
|
* Disconnect provider and cleanup subscriptions
|
|
@@ -7456,6 +8189,7 @@ export class PerpsController extends BaseController {
|
|
|
7456
8189
|
// (hydration, other toggles), so restoring the earlier snapshot would
|
|
7457
8190
|
// discard those changes.
|
|
7458
8191
|
const deferred = this.#deferredWatchlistRestores.get(toggle) ?? [];
|
|
8192
|
+
const unpersisted = this.#unpersistedWatchlistAdds.get(toggle);
|
|
7459
8193
|
this.update((state) => {
|
|
7460
8194
|
if (!isWatchlisted && isLatestToggle(reference)) {
|
|
7461
8195
|
state.watchlistMarkets[currentNetwork] = state.watchlistMarkets[currentNetwork].filter((marketSymbol) => marketSymbol !== reference);
|
|
@@ -7470,6 +8204,14 @@ export class PerpsController extends BaseController {
|
|
|
7470
8204
|
.map((entry) => this.#pendingWatchlistToggles.get(toggleKey(entry)))
|
|
7471
8205
|
.find((pending) => pending !== undefined && pending !== toggle);
|
|
7472
8206
|
if (newerToggle) {
|
|
8207
|
+
const newerUnpersisted = new Set([
|
|
8208
|
+
...(this.#unpersistedWatchlistAdds.get(newerToggle) ?? []),
|
|
8209
|
+
...(unpersisted ?? []),
|
|
8210
|
+
...(isWatchlisted ? [] : [reference]),
|
|
8211
|
+
]);
|
|
8212
|
+
if (newerUnpersisted.size > 0) {
|
|
8213
|
+
this.#unpersistedWatchlistAdds.set(newerToggle, newerUnpersisted);
|
|
8214
|
+
}
|
|
7473
8215
|
// Hand over only what remote storage still holds.
|
|
7474
8216
|
this.#deferredWatchlistRestores.set(newerToggle, [
|
|
7475
8217
|
...(isWatchlisted
|
|
@@ -7481,7 +8223,13 @@ export class PerpsController extends BaseController {
|
|
|
7481
8223
|
return;
|
|
7482
8224
|
}
|
|
7483
8225
|
const restores = isWatchlisted
|
|
7484
|
-
? [
|
|
8226
|
+
? [
|
|
8227
|
+
{
|
|
8228
|
+
entries: references.filter((entry) => !unpersisted?.has(entry)),
|
|
8229
|
+
snapshot: currentWatchlist,
|
|
8230
|
+
},
|
|
8231
|
+
...deferred,
|
|
8232
|
+
]
|
|
7485
8233
|
: deferred;
|
|
7486
8234
|
const watchlist = state.watchlistMarkets[currentNetwork];
|
|
7487
8235
|
for (const { entries, snapshot } of restores) {
|
|
@@ -7495,6 +8243,7 @@ export class PerpsController extends BaseController {
|
|
|
7495
8243
|
}
|
|
7496
8244
|
finally {
|
|
7497
8245
|
this.#deferredWatchlistRestores.delete(toggle);
|
|
8246
|
+
this.#unpersistedWatchlistAdds.delete(toggle);
|
|
7498
8247
|
for (const entry of references) {
|
|
7499
8248
|
if (isLatestToggle(entry)) {
|
|
7500
8249
|
this.#pendingWatchlistToggles.delete(toggleKey(entry));
|
|
@@ -7759,9 +8508,16 @@ export class PerpsController extends BaseController {
|
|
|
7759
8508
|
// AUS has an entry for this exchange — hydrate local state from it,
|
|
7760
8509
|
// keeping any toggle made while the read was in flight.
|
|
7761
8510
|
const hydrated = applyWatchlistEdits(remoteExchangeWatchlist, editsDuringHydration);
|
|
8511
|
+
// AUS holds only bare symbols; keep the local keyed and venue entries.
|
|
7762
8512
|
this.update((state) => {
|
|
7763
|
-
|
|
7764
|
-
|
|
8513
|
+
for (const network of ['testnet', 'mainnet']) {
|
|
8514
|
+
const localOnly = state.watchlistMarkets[network].filter((entry) => !isSharedPerpsMarketReference(entry) &&
|
|
8515
|
+
!hydrated[network].includes(entry));
|
|
8516
|
+
state.watchlistMarkets[network] = [
|
|
8517
|
+
...hydrated[network],
|
|
8518
|
+
...localOnly,
|
|
8519
|
+
];
|
|
8520
|
+
}
|
|
7765
8521
|
});
|
|
7766
8522
|
this.#debugLog('PerpsController: Watchlist hydrated from AUS', {
|
|
7767
8523
|
exchangeKey,
|