-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsController.ts
More file actions
5014 lines (4576 loc) · 158 KB
/
PerpsController.ts
File metadata and controls
5014 lines (4576 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
BaseController,
ControllerGetStateAction,
ControllerStateChangeEvent,
StateMetadata,
} from '@metamask/base-controller';
import type { StateChangeListener } from '@metamask/base-controller';
import { ORIGIN_METAMASK } from '@metamask/controller-utils';
import type { Messenger } from '@metamask/messenger';
import type { Json } from '@metamask/utils';
import { v4 as uuidv4 } from 'uuid';
import { CandlePeriod } from './constants/chartConfig';
import {
PERPS_EVENT_PROPERTY,
PERPS_EVENT_VALUE,
} from './constants/eventNames';
import { USDC_SYMBOL } from './constants/hyperLiquidConfig';
import { PerpsMeasurementName } from './constants/performanceMetrics';
import {
PERPS_CONSTANTS,
MARKET_SORTING_CONFIG,
PROVIDER_CONFIG,
PERPS_DISK_CACHE_MARKETS,
PERPS_DISK_CACHE_USER_DATA,
buildProviderCacheKey,
} from './constants/perpsConfig';
import type { SortOptionId } from './constants/perpsConfig';
import type { PerpsControllerMethodActions } from './PerpsController-method-action-types';
import { PERPS_ERROR_CODES } from './perpsErrorCodes';
import { AggregatedPerpsProvider } from './providers/AggregatedPerpsProvider';
import { HyperLiquidProvider } from './providers/HyperLiquidProvider';
import { AccountService } from './services/AccountService';
import { DataLakeService } from './services/DataLakeService';
import { DepositService } from './services/DepositService';
import { EligibilityService } from './services/EligibilityService';
import { FeatureFlagConfigurationService } from './services/FeatureFlagConfigurationService';
import { MarketDataService } from './services/MarketDataService';
import { RewardsIntegrationService } from './services/RewardsIntegrationService';
import type { ServiceContext } from './services/ServiceContext';
import { TradingService } from './services/TradingService';
// PerpsStreamChannelKey removed: using string for channel keys (PerpsStreamManager.pauseChannel takes string)
import {
WebSocketConnectionState,
PerpsAnalyticsEvent,
PerpsTraceNames,
PerpsTraceOperations,
isVersionGatedFeatureFlag,
// Platform dependencies interface for core migration (bundles all platform-specific deps)
} from './types';
import type {
AccountState,
AssetRoute,
CancelOrderParams,
CancelOrderResult,
CancelOrdersParams,
CancelOrdersResult,
ClosePositionParams,
ClosePositionsParams,
ClosePositionsResult,
DepositWithConfirmationParams,
EditOrderParams,
FeeCalculationParams,
FeeCalculationResult,
FlipPositionParams,
Funding,
GetAccountStateParams,
GetAvailableDexsParams,
GetFundingParams,
GetMarketsParams,
GetOrderFillsParams,
GetOrdersParams,
GetPositionsParams,
PerpsProvider,
LiquidationPriceParams,
LiveDataConfig,
MaintenanceMarginParams,
MarginResult,
MarketInfo,
Order,
OrderFill,
OrderParams,
OrderResult,
PerpsControllerConfig,
PerpsMarketData,
Position,
SubscribeAccountParams,
SubscribeCandlesParams,
SubscribeOICapsParams,
SubscribeOrderBookParams,
SubscribeOrderFillsParams,
SubscribeOrdersParams,
SubscribePositionsParams,
SubscribePricesParams,
SwitchProviderResult,
ToggleTestnetResult,
UpdateMarginParams,
UpdatePositionTPSLParams,
WithdrawParams,
WithdrawResult,
GetHistoricalPortfolioParams,
HistoricalPortfolioResult,
OrderType,
PerpsPlatformDependencies,
PerpsLogger,
PerpsActiveProviderMode,
PerpsProviderType,
PerpsSelectedPaymentToken,
PerpsRemoteFeatureFlagState,
PerpsTransactionParams,
PerpsAddTransactionOptions,
MYXCredentials,
} from './types';
import type {
PerpsControllerAllowedActions,
PerpsControllerAllowedEvents,
} from './types/messenger';
import type { CandleData } from './types/perps-types';
import {
LastTransactionResult,
TransactionStatus,
} from './types/transactionTypes';
import { getSelectedEvmAccountFromMessenger } from './utils/accountUtils';
import { ensureError } from './utils/errorUtils';
import {
hydrateFromDiskSync,
persistMarketEntriesToDisk,
persistUserEntriesToDisk,
} from './utils/perpsDiskPersistence';
import type { SortDirection } from './utils/sortMarkets';
import { wait } from './utils/wait';
/** Derived type for logger options from PerpsLogger interface */
type PerpsLoggerOptions = Parameters<PerpsLogger['error']>[1];
/**
* Returns the first non-empty string from the given values.
* Env vars default to '' (not null/undefined), so ?? wouldn't fall through.
*
* @param vals - String values to check in order.
* @returns The first non-empty string, or '' if all are empty/undefined.
*/
export function firstNonEmpty(...vals: (string | undefined)[]): string {
return (
vals.find((val) => val !== null && val !== undefined && val !== '') ?? ''
);
}
/**
* Resolves MYX auth config from provider credentials, handling
* testnet/mainnet fallback logic.
*
* @param myx - MYX provider credentials.
* @param isTestnet - Whether the controller is in testnet mode.
* @returns Resolved appId, apiSecret, and brokerAddress.
*/
export function resolveMyxAuthConfig(
myx: MYXCredentials,
isTestnet: boolean,
): { appId: string; apiSecret: string; brokerAddress: string } {
return {
appId: isTestnet
? (myx.appIdTestnet ?? '')
: firstNonEmpty(myx.appIdMainnet, myx.appIdTestnet),
apiSecret: isTestnet
? (myx.apiSecretTestnet ?? '')
: firstNonEmpty(myx.apiSecretMainnet, myx.apiSecretTestnet),
brokerAddress: isTestnet
? (myx.brokerAddressTestnet ?? '')
: firstNonEmpty(myx.brokerAddressMainnet, myx.brokerAddressTestnet),
};
}
// PaymentToken: minimal interface for deposit flow (replaces mobile-only AssetType)
/**
* Minimal payment token stored in PerpsController state.
* Only required fields for identification, Perps balance detection, and analytics.
*/
export type SelectedPaymentTokenSnapshot = {
description?: string;
address: string;
chainId: string;
symbol?: string;
};
// Re-export error codes from separate file to avoid circular dependencies
export { PERPS_ERROR_CODES, type PerpsErrorCode } from './perpsErrorCodes';
/**
* Initialization state enum for state machine tracking
*/
export enum InitializationState {
Uninitialized = 'uninitialized',
Initializing = 'initializing',
Initialized = 'initialized',
Failed = 'failed',
}
/**
* State shape for PerpsController
*/
export type PerpsControllerState = {
// Active provider
activeProvider: PerpsActiveProviderMode;
isTestnet: boolean; // Dev toggle for testnet
// Initialization state machine
initializationState: InitializationState;
initializationError: string | null;
initializationAttempts: number;
// Account data (persisted) - using HyperLiquid property names
accountState: AccountState | null;
// Perps balances per provider for portfolio display (historical data)
perpsBalances: {
[provider: string]: {
totalBalance: string; // Current total account value (cash + positions) in USD
unrealizedPnl: string; // Current P&L from open positions in USD
accountValue1dAgo: string; // Account value 24h ago for daily change calculation in USD
lastUpdated: number; // Timestamp of last update
};
};
// Simple deposit state (transient, for UI feedback)
depositInProgress: boolean;
// Internal transaction id for the deposit transaction
// We use this to fetch the bridge quotes and get the estimated time.
lastDepositTransactionId: string | null;
lastDepositResult: LastTransactionResult | null;
// Simple withdrawal state (transient, for UI feedback)
// Note: withdrawInProgress is now derived from withdrawalRequests having pending/bridging entries
withdrawInProgress: boolean;
lastWithdrawResult: LastTransactionResult | null;
// FIFO guard for withdrawal completion matching.
// Timestamp is persisted — survives app restarts so the hook skips
// already-processed history entries even after relaunch.
// TxHashes array is NOT persisted — it tracks completions within a
// single session to prevent re-matching (direct completions,
// same-millisecond API completions). Resets naturally on app restart;
// the timestamp guard provides cross-restart protection.
lastCompletedWithdrawalTimestamp: number | null;
lastCompletedWithdrawalTxHashes: string[];
// Withdrawal request tracking (persistent, for transaction history)
withdrawalRequests: {
id: string;
amount: string;
asset: string;
accountAddress: string; // Account that initiated this withdrawal
txHash?: string;
timestamp: number;
success: boolean;
status: TransactionStatus;
destination?: string;
source?: string;
transactionId?: string;
withdrawalId?: string;
depositId?: string;
}[];
// Withdrawal progress tracking (persistent across navigation)
withdrawalProgress: {
progress: number; // 0-100
lastUpdated: number; // timestamp
activeWithdrawalId: string | null; // ID of the withdrawal being tracked
};
// Deposit request tracking (persistent, for transaction history)
depositRequests: {
id: string;
amount: string;
asset: string;
accountAddress: string; // Account that initiated this deposit
txHash?: string;
timestamp: number;
success: boolean;
status: TransactionStatus;
destination?: string;
source?: string;
transactionId?: string;
withdrawalId?: string;
depositId?: string;
}[];
// Eligibility (Geo-Blocking)
isEligible: boolean;
// Tutorial/First time user tracking (per network)
isFirstTimeUser: {
testnet: boolean;
mainnet: boolean;
};
// Notification tracking
hasPlacedFirstOrder: {
testnet: boolean;
mainnet: boolean;
};
// Watchlist markets tracking (per network)
watchlistMarkets: {
testnet: string[]; // Array of watchlist market symbols for testnet
mainnet: string[]; // Array of watchlist market symbols for mainnet
};
// Trade configurations per market (per network)
tradeConfigurations: {
testnet: {
[marketSymbol: string]: {
leverage?: number; // Last used leverage for this market
orderBookGrouping?: number; // Persisted price grouping for order book
// Pending trade configuration (temporary, expires after 5 minutes)
pendingConfig?: {
amount?: string; // Order size in USD
leverage?: number; // Leverage
takeProfitPrice?: string; // Take profit price
stopLossPrice?: string; // Stop loss price
limitPrice?: string; // Limit price (for limit orders)
orderType?: OrderType; // Market vs limit
timestamp: number; // When the config was saved (for expiration check)
};
};
};
mainnet: {
[marketSymbol: string]: {
leverage?: number;
orderBookGrouping?: number; // Persisted price grouping for order book
// Pending trade configuration (temporary, expires after 5 minutes)
pendingConfig?: {
amount?: string; // Order size in USD
leverage?: number; // Leverage
takeProfitPrice?: string; // Take profit price
stopLossPrice?: string; // Stop loss price
limitPrice?: string; // Limit price (for limit orders)
orderType?: OrderType; // Market vs limit
timestamp: number; // When the config was saved (for expiration check)
};
};
};
};
// Market filter preferences (network-independent) - includes both sorting and filtering options
marketFilterPreferences: {
optionId: SortOptionId;
direction: SortDirection;
};
// Error handling
lastError: string | null;
lastUpdateTimestamp: number;
// HIP-3 Configuration Version (incremented when HIP-3 remote flags change)
// Used to trigger reconnection and cache invalidation in ConnectionManager
hip3ConfigVersion: number;
// Selected payment token for Perps order/deposit flow (null = Perps balance). Stored as Json (minimal shape: description, address, chainId).
selectedPaymentToken: Json | null;
// Cached market data from background preloading (REST snapshots, not WebSocket)
// Keyed by "providerId:network" (e.g. 'hyperliquid:mainnet', 'myx:testnet')
cachedMarketDataByProvider: Record<
string,
{ data: PerpsMarketData[]; timestamp: number }
>;
// Cached user data from background preloading (REST snapshots, not WebSocket)
// Keyed by "providerId:network" (e.g. 'hyperliquid:mainnet', 'myx:testnet')
cachedUserDataByProvider: Record<
string,
{
positions: Position[];
orders: Order[];
accountState: AccountState | null;
timestamp: number;
address: string;
}
>;
};
/**
* Get default PerpsController state
*
* To change the active provider, modify the `activeProvider` value below:
* - 'hyperliquid': HyperLiquid provider (default, production)
* - 'aggregated': Multi-provider aggregation mode
* - 'myx': MYX provider (future implementation)
*
* @returns The default perps controller state.
*/
export const getDefaultPerpsControllerState = (): PerpsControllerState => ({
activeProvider: 'hyperliquid',
isTestnet: false, // Default to mainnet
initializationState: InitializationState.Uninitialized,
initializationError: null,
initializationAttempts: 0,
accountState: null,
perpsBalances: {},
depositInProgress: false,
lastDepositResult: null,
withdrawInProgress: false,
lastDepositTransactionId: null,
lastWithdrawResult: null,
lastCompletedWithdrawalTimestamp: null,
lastCompletedWithdrawalTxHashes: [],
withdrawalRequests: [],
withdrawalProgress: {
progress: 0,
lastUpdated: 0,
activeWithdrawalId: null,
},
depositRequests: [],
lastError: null,
lastUpdateTimestamp: 0,
isEligible: false,
isFirstTimeUser: {
testnet: true,
mainnet: true,
},
hasPlacedFirstOrder: {
testnet: false,
mainnet: false,
},
watchlistMarkets: {
testnet: [],
mainnet: [],
},
tradeConfigurations: {
testnet: {},
mainnet: {},
},
marketFilterPreferences: {
optionId: MARKET_SORTING_CONFIG.DefaultSortOptionId,
direction: MARKET_SORTING_CONFIG.DefaultDirection,
},
hip3ConfigVersion: 0,
selectedPaymentToken: null,
cachedMarketDataByProvider: {},
cachedUserDataByProvider: {},
});
/**
* State metadata for the PerpsController
*/
const metadata: StateMetadata<PerpsControllerState> = {
accountState: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
perpsBalances: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
isTestnet: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
activeProvider: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
initializationState: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
initializationError: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
initializationAttempts: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
depositInProgress: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastDepositTransactionId: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastDepositResult: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
withdrawInProgress: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastWithdrawResult: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastCompletedWithdrawalTimestamp: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastCompletedWithdrawalTxHashes: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
withdrawalRequests: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
withdrawalProgress: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
depositRequests: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
lastError: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
lastUpdateTimestamp: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
isEligible: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
isFirstTimeUser: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
hasPlacedFirstOrder: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
watchlistMarkets: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
tradeConfigurations: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
marketFilterPreferences: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
hip3ConfigVersion: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
selectedPaymentToken: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
cachedMarketDataByProvider: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
cachedUserDataByProvider: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
};
/**
* PerpsController events
*/
export type PerpsControllerEvents = ControllerStateChangeEvent<
'PerpsController',
PerpsControllerState
>;
/**
* The action which can be used to retrieve the state of the
* {@link PerpsController}.
*/
export type PerpsControllerGetStateAction = ControllerGetStateAction<
'PerpsController',
PerpsControllerState
>;
/**
* PerpsController actions
*/
export type PerpsControllerActions =
| PerpsControllerGetStateAction
| PerpsControllerMethodActions;
/**
* PerpsController messenger constraints.
* Includes both PerpsController's own actions/events and
* allowed actions/events from external controllers.
*/
export type PerpsControllerMessenger = Messenger<
'PerpsController',
PerpsControllerActions | PerpsControllerAllowedActions,
PerpsControllerEvents | PerpsControllerAllowedEvents
>;
/**
* PerpsController options
*/
export type PerpsControllerOptions = {
messenger: PerpsControllerMessenger;
state?: Partial<PerpsControllerState>;
clientConfig?: PerpsControllerConfig;
/**
* Platform-specific dependencies (required)
* Provides logging, metrics, tracing, stream management, and rewards.
* Cross-controller communication uses the messenger pattern.
* Must be provided by the platform (mobile/extension) at instantiation time.
*/
infrastructure: PerpsPlatformDependencies;
/**
* When true, defers the initial eligibility (geolocation) check until
* `startEligibilityMonitoring()` is called. This prevents the eager
* geolocation fetch from firing during wallet onboarding (privacy compliance).
*/
deferEligibilityCheck?: boolean;
};
type BlockedRegionList = {
list: string[];
source: 'remote' | 'fallback';
};
const MESSENGER_EXPOSED_METHODS = [
'calculateFees',
'calculateLiquidationPrice',
'calculateMaintenanceMargin',
'cancelOrder',
'cancelOrders',
'clearDepositResult',
'clearPendingTradeConfiguration',
'clearPendingTransactionRequests',
'clearWithdrawResult',
'closePosition',
'closePositions',
'completeWithdrawalFromHistory',
'depositWithConfirmation',
'depositWithOrder',
'disconnect',
'editOrder',
'fetchHistoricalCandles',
'flipPosition',
'getAccountState',
'getActiveProvider',
'getActiveProviderOrNull',
'getAvailableDexs',
'getBlockExplorerUrl',
'getCachedMarketDataForActiveProvider',
'getCachedUserDataForActiveProvider',
'getCurrentNetwork',
'getFunding',
'getHistoricalPortfolio',
'getMarketDataWithPrices',
'getMarketFilterPreferences',
'getMarkets',
'getMaxLeverage',
'getOpenOrders',
'getOrderBookGrouping',
'getOrderFills',
'getOrders',
'getPendingTradeConfiguration',
'getPositions',
'getTradeConfiguration',
'getWatchlistMarkets',
'getWebSocketConnectionState',
'getWithdrawalProgress',
'getWithdrawalRoutes',
'init',
'isCurrentlyReinitializing',
'isFirstTimeUserOnCurrentNetwork',
'isWatchlistMarket',
'markFirstOrderCompleted',
'markTutorialCompleted',
'placeOrder',
'reconnect',
'refreshEligibility',
'resetFirstTimeUserState',
'resetSelectedPaymentToken',
'saveMarketFilterPreferences',
'saveOrderBookGrouping',
'savePendingTradeConfiguration',
'saveTradeConfiguration',
'setLiveDataConfig',
'setSelectedPaymentToken',
'startEligibilityMonitoring',
'startMarketDataPreload',
'stopEligibilityMonitoring',
'stopMarketDataPreload',
'subscribeToAccount',
'subscribeToCandles',
'subscribeToConnectionState',
'subscribeToOICaps',
'subscribeToOrderBook',
'subscribeToOrderFills',
'subscribeToOrders',
'subscribeToPositions',
'subscribeToPrices',
'switchProvider',
'toggleTestnet',
'toggleWatchlistMarket',
'updateMargin',
'updatePositionTPSL',
'updateWithdrawalProgress',
'updateWithdrawalStatus',
'validateClosePosition',
'validateOrder',
'validateWithdrawal',
'withdraw',
] as const;
/**
* PerpsController - Protocol-agnostic perpetuals trading controller
*
* Provides a unified interface for perpetual futures trading across multiple protocols.
* Features dual data flow architecture:
* - Trading actions use Redux for persistence and optimistic updates
* - Live data uses direct callbacks for maximum performance
*/
export class PerpsController extends BaseController<
'PerpsController',
PerpsControllerState,
PerpsControllerMessenger
> {
protected providers: Map<PerpsProviderType, PerpsProvider>;
protected isInitialized = false;
#initializationPromise: Promise<void> | null = null;
#isReinitializing = false;
/** Tracks the async MYX dynamic import so performInitialization can await it. */
#myxRegistrationPromise: Promise<void> | null = null;
protected blockedRegionList: BlockedRegionList = {
list: [],
source: 'fallback',
};
/**
* Version counter for blocked region list.
* Used to prevent race conditions where stale eligibility checks
* (started with fallback config) overwrite results from newer checks
* (started with remote config).
*/
#blockedRegionListVersion = 0;
// Store HIP-3 configuration (mutable for runtime updates from remote flags)
#hip3Enabled: boolean;
#hip3AllowlistMarkets: string[];
#hip3BlocklistMarkets: string[];
#hip3ConfigSource: 'remote' | 'fallback' = 'fallback';
/**
* Check if MYX provider is enabled via feature flag
* Uses same pattern as other feature flags in FeatureFlagConfigurationService
*
* @returns True if the condition is met.
*/
#isMYXProviderEnabled(): boolean {
const myx = this.#options.clientConfig?.providerCredentials?.myx;
// Local env-var override (MM_PERPS_MYX_PROVIDER_ENABLED) always wins —
// matches the UI selector (resolvePerpsMyxProviderEnabled) so controller
// and UI agree on whether MYX is available.
if (myx?.enabled) {
return true;
}
// Credentials present → MYX is enabled regardless of remote flag.
// Use || so empty-string env vars (default '') fall through.
const hasCredentials = Boolean(
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
myx?.appIdTestnet || myx?.appIdMainnet,
);
if (hasCredentials) {
return true;
}
// No local override or credentials — check remote flag as fallback
try {
const remoteState = this.messenger.call(
'RemoteFeatureFlagController:getState',
);
const remoteFlag =
remoteState.remoteFeatureFlags?.perpsMyxProviderEnabled;
if (isVersionGatedFeatureFlag(remoteFlag)) {
const validated =
this.#options.infrastructure.featureFlags.validateVersionGated(
remoteFlag,
);
return validated ?? false;
}
return false;
} catch {
return false;
}
}
/**
* Active provider instance for routing operations.
* When activeProvider is 'hyperliquid' or 'myx': points to specific provider directly
* When activeProvider is 'aggregated': points to AggregatedPerpsProvider wrapper
*/
protected activeProviderInstance: PerpsProvider | null = null;
/**
* Cached standalone provider for pre-initialization discovery queries.
* Avoids creating a new HyperLiquidProvider (and potentially leaking WebSocket
* connections) on every standalone call from the preload cycle.
*/
#standaloneProvider: HyperLiquidProvider | null = null;
#handlersRegistered = false;
#standaloneProviderIsTestnet: boolean | null = null;
#standaloneProviderHip3Version: number | null = null;
#eligibilityCheckDeferred: boolean;
// Store options for dependency injection (allows core package to inject platform-specific services)
readonly #options: PerpsControllerOptions;
// Service instances (instantiated with platform dependencies)
readonly #tradingService: TradingService;
readonly #marketDataService: MarketDataService;
readonly #accountService: AccountService;
readonly #eligibilityService: EligibilityService;
readonly #dataLakeService: DataLakeService;
readonly #depositService: DepositService;
readonly #featureFlagConfigurationService: FeatureFlagConfigurationService;
readonly #rewardsIntegrationService: RewardsIntegrationService;
constructor({
messenger,
state = {},
clientConfig = {},
infrastructure,
deferEligibilityCheck = false,
}: PerpsControllerOptions) {
super({
name: 'PerpsController',
metadata,
messenger,
state: { ...getDefaultPerpsControllerState(), ...state },
});
this.#eligibilityCheckDeferred = deferEligibilityCheck;
// Store options for dependency injection
this.#options = {
messenger,
state,
clientConfig,
infrastructure,
};
// Instantiate services with platform dependencies
// Services that need cross-controller access receive the messenger
this.#tradingService = new TradingService(infrastructure);
this.#marketDataService = new MarketDataService(infrastructure);
this.#accountService = new AccountService(infrastructure, messenger);
this.#eligibilityService = new EligibilityService(infrastructure);
this.#dataLakeService = new DataLakeService(infrastructure, messenger);
this.#depositService = new DepositService(infrastructure, messenger);
this.#featureFlagConfigurationService = new FeatureFlagConfigurationService(
infrastructure,
);
this.#rewardsIntegrationService = new RewardsIntegrationService(
infrastructure,
messenger,
);
// Set HIP-3 fallback configuration from client (will be updated if remote flags available)
this.#hip3Enabled = clientConfig.fallbackHip3Enabled ?? false;
this.#hip3AllowlistMarkets = [
...(clientConfig.fallbackHip3AllowlistMarkets ?? []),
];
this.#hip3BlocklistMarkets = [
...(clientConfig.fallbackHip3BlocklistMarkets ?? []),
];
// Immediately set the fallback region list since RemoteFeatureFlagController is empty by default and takes a moment to populate.
this.setBlockedRegionList(
clientConfig.fallbackBlockedRegions ?? [],
'fallback',
);
/**
* Immediately read current state to catch any flags already loaded
* This is necessary to avoid race conditions where the RemoteFeatureFlagController fetches flags
* before the PerpsController initializes its RemoteFeatureFlagController subscription.
*
* We still subscribe in case the RemoteFeatureFlagController is not yet populated and updates later.
*/
try {
const currentRemoteFeatureFlagState = this.messenger.call(
'RemoteFeatureFlagController:getState',
);
this.refreshEligibilityOnFeatureFlagChange(currentRemoteFeatureFlagState);
} catch (error) {
// If we can't read the remote feature flags at construction time, we'll rely on:
// 1. The fallback blocked regions already set above
// 2. The subscription to catch updates when RemoteFeatureFlagController is ready
this.#logError(
ensureError(error, 'PerpsController.constructor'),
this.#getErrorContext('constructor', {
operation: 'readRemoteFeatureFlags',
}),
);
}
// Subscribe for the full controller lifetime — intentionally not stored;
// geo-blocking and HIP-3 flag propagation must remain active across
// disconnect → reconnect cycles and must never be torn down.
this.messenger.subscribe(
'RemoteFeatureFlagController:stateChange',
this.refreshEligibilityOnFeatureFlagChange.bind(this),
);
this.providers = new Map();