-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsConnectionManager.test.ts
More file actions
1651 lines (1358 loc) · 57.7 KB
/
PerpsConnectionManager.test.ts
File metadata and controls
1651 lines (1358 loc) · 57.7 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
// Mock wait utility to avoid delays in tests
jest.mock('@metamask/perps-controller', () => {
const actual = jest.requireActual('@metamask/perps-controller');
return {
...actual,
wait: jest.fn().mockResolvedValue(undefined),
TradingReadinessCache: {
clear: jest.fn(),
clearAll: jest.fn(),
clearUnifiedAccount: jest.fn(),
clearBuilderFee: jest.fn(),
clearReferral: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
};
});
jest.mock('../../../../core/SDKConnect/utils/DevLogger');
jest.mock('../../../../core/Engine', () => ({
context: {
PerpsController: {
init: jest.fn(),
getAccountState: jest.fn(),
disconnect: jest.fn(),
reconnectWithNewContext: jest.fn(),
getActiveProvider: jest.fn(() => ({
ping: jest.fn().mockResolvedValue(undefined),
})),
isCurrentlyReinitializing: jest.fn(() => false),
},
},
}));
// Store the subscription callbacks
const storeCallbacks: (() => void)[] = [];
// Mock Redux store like other tests do
jest.mock('../../../../store', () => ({
store: {
subscribe: jest.fn((callback) => {
storeCallbacks.push(callback);
return jest.fn(); // Returns unsubscribe function
}),
getState: jest.fn(),
dispatch: jest.fn(),
},
}));
// Mock selectors
jest.mock('../../../../selectors/accountsController', () => ({
selectSelectedInternalAccountAddress: jest.fn(),
selectInternalAccounts: jest.fn(() => []),
}));
jest.mock('../../../../selectors/multichainAccounts/accounts', () => ({
selectSelectedInternalAccountByScope: jest.fn(() => () => ({
address: '0x1234567890123456789012345678901234567890',
})),
}));
jest.mock('../selectors/perpsController', () => ({
selectPerpsNetwork: jest.fn(),
selectPerpsProvider: jest.fn(),
}));
// Mock StreamManager - create a singleton mock instance
const mockStreamManagerInstance = {
positions: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
orders: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
account: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
marketData: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
prices: { clearCache: jest.fn(), prewarm: jest.fn(async () => jest.fn()) },
oiCaps: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
fills: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
topOfBook: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
candles: { clearCache: jest.fn(), prewarm: jest.fn(() => jest.fn()) },
resetDiskCacheThrottles: jest.fn(),
};
jest.mock('../providers/PerpsStreamManager', () => ({
getStreamManagerInstance: jest.fn(() => mockStreamManagerInstance),
}));
// Mock Device and BackgroundTimer for grace period tests
jest.mock('../../../../util/device', () => ({
isIos: jest.fn(),
isAndroid: jest.fn(),
}));
jest.mock('react-native-background-timer', () => ({
setTimeout: jest.fn(),
clearTimeout: jest.fn(),
start: jest.fn(),
stop: jest.fn(),
}));
jest.mock('../../../../store/storage-wrapper', () => ({
getItem: jest.fn().mockResolvedValue(null),
setItem: jest.fn().mockResolvedValue(undefined),
removeItem: jest.fn().mockResolvedValue(undefined),
}));
// Import non-singleton modules first
import { addEventListener as mockNetInfoAddEventListener } from '@react-native-community/netinfo';
import { DevLogger } from '../../../../core/SDKConnect/utils/DevLogger';
import Engine from '../../../../core/Engine';
import { store } from '../../../../store';
import { selectSelectedInternalAccountByScope } from '../../../../selectors/multichainAccounts/accounts';
import { selectPerpsNetwork } from '../selectors/perpsController';
import { TradingReadinessCache } from '@metamask/perps-controller';
// Import PerpsConnectionManager after mocks are set up
// This is imported here after mocks to ensure store.subscribe is mocked before the singleton is created
import { PerpsConnectionManager } from './PerpsConnectionManager';
import { PERPS_CONNECTION_SOURCE } from '../constants/perpsConfig';
// Get reference to the mocked TradingReadinessCache
const mockTradingReadinessCache = TradingReadinessCache as jest.Mocked<
typeof TradingReadinessCache
>;
// Helper to reset private properties for testing
const resetManager = (manager: unknown) => {
const m = manager as {
isConnected: boolean;
isConnecting: boolean;
isInitialized: boolean;
isDisconnecting: boolean;
connectionRefCount: number;
initPromise: Promise<void> | null;
disconnectPromise: Promise<void> | null;
pendingReconnectPromise: Promise<void> | null;
ensureConnectedPromise: Promise<void> | null;
unsubscribeFromStore: (() => void) | null;
previousAddress: string | undefined;
previousPerpsNetwork: 'mainnet' | 'testnet' | undefined;
error: string | null;
isInGracePeriod: boolean;
gracePeriodTimer: number | null;
hasPreloaded: boolean;
isPreloading: boolean;
prewarmCleanups: (() => void)[];
netInfoUnsubscribe: (() => void) | null;
wasOffline: boolean;
};
// Call unsubscribe if it exists before resetting
if (m.unsubscribeFromStore) {
m.unsubscribeFromStore();
}
if (m.netInfoUnsubscribe) {
m.netInfoUnsubscribe();
m.netInfoUnsubscribe = null;
}
m.wasOffline = false;
// Clean up any prewarm subscriptions
m.prewarmCleanups.forEach((cleanup) => cleanup());
m.prewarmCleanups = [];
// Reset all state properties
m.isConnected = false;
m.isConnecting = false;
m.isInitialized = false;
m.isDisconnecting = false;
m.connectionRefCount = 0;
m.initPromise = null;
m.disconnectPromise = null;
m.pendingReconnectPromise = null;
m.ensureConnectedPromise = null;
m.unsubscribeFromStore = null;
m.previousAddress = undefined;
m.previousPerpsNetwork = undefined;
m.error = null;
m.isInGracePeriod = false;
m.gracePeriodTimer = null;
m.hasPreloaded = false;
m.isPreloading = false;
};
describe('PerpsConnectionManager', () => {
let mockDevLogger: jest.Mocked<typeof DevLogger>;
let mockPerpsController: {
init: jest.MockedFunction<() => Promise<void>>;
getAccountState: jest.MockedFunction<
() => Promise<Record<string, unknown>>
>;
disconnect: jest.MockedFunction<() => Promise<void>>;
reconnectWithNewContext: jest.MockedFunction<() => Promise<void>>;
};
// No need for beforeAll - singleton is created on first access
beforeEach(() => {
jest.clearAllMocks();
// Clear store callbacks array for test isolation
storeCallbacks.length = 0;
// Mock Redux state with proper structure for selectors
(store.getState as jest.Mock).mockReturnValue({
engine: {
backgroundState: {
PerpsController: {
hip3ConfigVersion: 0,
},
},
},
});
// Clear StreamManager mock calls
mockStreamManagerInstance.positions.clearCache.mockClear();
mockStreamManagerInstance.orders.clearCache.mockClear();
mockStreamManagerInstance.account.clearCache.mockClear();
mockStreamManagerInstance.marketData.clearCache.mockClear();
mockStreamManagerInstance.prices.clearCache.mockClear();
mockStreamManagerInstance.positions.prewarm.mockClear();
mockStreamManagerInstance.orders.prewarm.mockClear();
mockStreamManagerInstance.account.prewarm.mockClear();
mockStreamManagerInstance.marketData.prewarm.mockClear();
mockStreamManagerInstance.prices.prewarm.mockClear();
// Reset the singleton instance state
resetManager(PerpsConnectionManager);
mockDevLogger = DevLogger as jest.Mocked<typeof DevLogger>;
mockPerpsController = Engine.context
.PerpsController as unknown as typeof mockPerpsController;
});
describe('getInstance', () => {
it('returns the same singleton instance on repeated calls', () => {
const instance1 = PerpsConnectionManager;
const instance2 = PerpsConnectionManager;
expect(instance1).toBe(instance2);
});
});
describe('connect', () => {
it('initializes providers and connects on first call', async () => {
mockPerpsController.init.mockResolvedValueOnce();
await PerpsConnectionManager.connect();
expect(mockPerpsController.init).toHaveBeenCalledTimes(1);
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('Successfully connected'),
);
});
it('increments reference count on each connect call', async () => {
mockPerpsController.init.mockResolvedValue();
await PerpsConnectionManager.connect();
await PerpsConnectionManager.connect();
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: 1'),
);
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: 2'),
);
});
it('returns existing promise when connection is already in progress', async () => {
// This test verifies that concurrent connect calls share the same promise
// Track promises from both connect calls
const promises: Promise<void>[] = [];
// Mock a slow initialization
mockPerpsController.init.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 50)),
);
mockPerpsController.getAccountState.mockResolvedValue({});
// Start two connections concurrently
promises.push(PerpsConnectionManager.connect());
promises.push(PerpsConnectionManager.connect());
// Wait for both to complete
await Promise.all(promises);
// Should only initialize once - this proves they shared the same init process
expect(mockPerpsController.init).toHaveBeenCalledTimes(1);
// Both connects should have incremented ref count
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: 1'),
);
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: 2'),
);
});
it('sets error state and resets flags when connection fails', async () => {
const error = new Error('Connection failed');
mockPerpsController.init.mockRejectedValueOnce(error);
await expect(PerpsConnectionManager.connect()).rejects.toThrow(
'Connection failed',
);
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('Connection failed'),
error,
);
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnected).toBe(false);
expect(state.isInitialized).toBe(false);
expect(state.isConnecting).toBe(false);
expect(state.error).toBe('Connection failed');
});
it('skips reconnection when already connected', async () => {
// First successful connection
mockPerpsController.init.mockResolvedValueOnce();
await PerpsConnectionManager.connect();
// Second connect should return early without reinitializing
await PerpsConnectionManager.connect();
// initializeProviders should only be called once
// (Stale connection detection removed for performance - connections issues
// will surface when components attempt to use the connection)
expect(mockPerpsController.init).toHaveBeenCalledTimes(1);
});
it('cancels grace period timer when reconnecting during grace period', async () => {
// Setup initial connection
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
// Connect first
await PerpsConnectionManager.connect();
expect(PerpsConnectionManager.getConnectionState().isConnected).toBe(
true,
);
// Disconnect (enters grace period)
await PerpsConnectionManager.disconnect();
expect(PerpsConnectionManager.getConnectionState().isInGracePeriod).toBe(
true,
);
// Immediately reconnect (should cancel grace period)
await PerpsConnectionManager.connect();
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnected).toBe(true);
// The grace period cancellation might not be immediate - just ensure we're connected
// Should not have called actual disconnect due to grace period cancellation
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
});
describe('disconnect', () => {
beforeEach(async () => {
// Setup initial connection
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
mockPerpsController.disconnect.mockResolvedValue();
});
it('decrements reference count on disconnect', async () => {
await PerpsConnectionManager.connect();
await PerpsConnectionManager.connect();
await PerpsConnectionManager.disconnect();
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: 1'),
);
// Should not actually disconnect yet
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
it('starts grace period only when reference count reaches zero', async () => {
await PerpsConnectionManager.connect();
await PerpsConnectionManager.connect();
await PerpsConnectionManager.disconnect();
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
await PerpsConnectionManager.disconnect();
// Should enter grace period instead of immediate disconnection
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
expect(PerpsConnectionManager.getConnectionState().isInGracePeriod).toBe(
true,
);
});
it('starts grace period timer on disconnect instead of disconnecting immediately', async () => {
await PerpsConnectionManager.connect();
// Disconnect should not throw even if controller would fail later
await expect(PerpsConnectionManager.disconnect()).resolves.not.toThrow();
// Should enter grace period without immediate disconnect
const state = PerpsConnectionManager.getConnectionState();
expect(state.isInGracePeriod).toBe(true);
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
it('prevents reference count from going below zero', async () => {
await PerpsConnectionManager.disconnect();
await PerpsConnectionManager.disconnect();
// The log will show -1 first, but the actual refCount is clamped to 0
// Check that disconnect was called with refCount: -1 (before clamping)
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('refCount: -1'),
);
// Verify the state is properly reset
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnected).toBe(false);
});
it('maintains connected state during grace period', async () => {
await PerpsConnectionManager.connect();
const connectedState = PerpsConnectionManager.getConnectionState();
expect(connectedState.isConnected).toBe(true);
expect(connectedState.isInitialized).toBe(true);
await PerpsConnectionManager.disconnect();
const gracePeriodState = PerpsConnectionManager.getConnectionState();
// Connection remains available during grace period
expect(gracePeriodState.isConnected).toBe(true);
expect(gracePeriodState.isInitialized).toBe(true);
expect(gracePeriodState.isConnecting).toBe(false);
expect(gracePeriodState.isInGracePeriod).toBe(true);
});
it('maintains state monitoring during grace period', async () => {
// Connect to set up monitoring
await PerpsConnectionManager.connect();
// Verify monitoring was set up
const subscribeCallsBefore = (store.subscribe as jest.Mock).mock.calls
.length;
expect(subscribeCallsBefore).toBeGreaterThan(0);
// Disconnect - should enter grace period, maintaining monitoring
await PerpsConnectionManager.disconnect();
// Should not clean up monitoring during grace period
expect(mockDevLogger.log).not.toHaveBeenCalledWith(
'PerpsConnectionManager: State monitoring cleaned up',
);
// Verify monitoring is still active during grace period
expect(
(PerpsConnectionManager as unknown as { unsubscribeFromStore: unknown })
.unsubscribeFromStore,
).not.toBeNull();
});
});
describe('getConnectionState', () => {
it('returns initial disconnected state', () => {
const state = PerpsConnectionManager.getConnectionState();
expect(state).toEqual({
isConnected: false,
isConnecting: false,
isInitialized: false,
isDisconnecting: false,
isInGracePeriod: false,
error: null,
});
});
it('returns connecting state while connection is in progress', async () => {
mockPerpsController.init.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100)),
);
mockPerpsController.getAccountState.mockResolvedValue({});
const connectPromise = PerpsConnectionManager.connect();
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnecting).toBe(true);
expect(state.isConnected).toBe(false);
await connectPromise;
const finalState = PerpsConnectionManager.getConnectionState();
expect(finalState.isConnecting).toBe(false);
expect(finalState.isConnected).toBe(true);
expect(finalState.isInitialized).toBe(true);
});
});
describe('grace period functionality', () => {
beforeEach(async () => {
// Setup initial connection mocks
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
mockPerpsController.disconnect.mockResolvedValue();
});
it('maintains connection during grace period', async () => {
// Given: A connected manager
await PerpsConnectionManager.connect();
expect(PerpsConnectionManager.getConnectionState().isConnected).toBe(
true,
);
// When: All references are disconnected
await PerpsConnectionManager.disconnect();
// Then: Connection remains available during grace period
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnected).toBe(true); // Still connected for users
expect(mockPerpsController.disconnect).not.toHaveBeenCalled(); // No actual disconnection yet
});
it('cancels grace period when reconnecting', async () => {
// Given: A manager in grace period
await PerpsConnectionManager.connect();
await PerpsConnectionManager.disconnect(); // Enter grace period
// When: A new connection is requested
await PerpsConnectionManager.connect();
// Then: Connection is maintained without actual disconnection
const state = PerpsConnectionManager.getConnectionState();
expect(state.isConnected).toBe(true);
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
it('schedules disconnection during grace period', async () => {
// Given: A manager in grace period
await PerpsConnectionManager.connect();
// When: Disconnection is requested
await PerpsConnectionManager.disconnect();
// Then: Grace period state is tracked correctly
const state = PerpsConnectionManager.getConnectionState();
expect(state.isInGracePeriod).toBe(true);
expect(state.isConnected).toBe(true); // Connection maintained during grace period
expect(mockPerpsController.disconnect).not.toHaveBeenCalled(); // No immediate disconnection
});
it('handles multiple references correctly', async () => {
// Given: Multiple connections
await PerpsConnectionManager.connect(); // refCount = 1
await PerpsConnectionManager.connect(); // refCount = 2
// When: First disconnect
await PerpsConnectionManager.disconnect(); // refCount = 1
// Then: No grace period yet (still has references)
expect(PerpsConnectionManager.getConnectionState().isConnected).toBe(
true,
);
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
// When: Final disconnect
await PerpsConnectionManager.disconnect(); // refCount = 0
// Then: Grace period starts, connection maintained
expect(PerpsConnectionManager.getConnectionState().isConnected).toBe(
true,
);
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
});
describe('concurrent operations', () => {
it('serializes concurrent connect and disconnect operations', async () => {
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
mockPerpsController.disconnect.mockResolvedValue();
// Simulate concurrent operations
const operations = [
PerpsConnectionManager.connect(),
PerpsConnectionManager.connect(),
PerpsConnectionManager.disconnect(),
PerpsConnectionManager.connect(),
PerpsConnectionManager.disconnect(),
];
await Promise.all(operations);
// Final ref count should be 1 (3 connects - 2 disconnects)
const finalDisconnect = PerpsConnectionManager.disconnect();
await finalDisconnect;
// Should enter grace period when ref count reaches 0
const state = PerpsConnectionManager.getConnectionState();
expect(state.isInGracePeriod).toBe(true);
expect(mockPerpsController.disconnect).not.toHaveBeenCalled();
});
});
describe('state monitoring', () => {
let storeCallback: () => void;
beforeEach(() => {
// Setup initial values for selectors
(
selectSelectedInternalAccountByScope as unknown as jest.Mock
).mockReturnValue(() => ({ address: '0xabc123' }));
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('mainnet');
(store.getState as jest.Mock).mockReturnValue({});
});
it('sets up Redux store subscription on first connect', async () => {
// Connect to trigger monitoring setup
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
// Verify subscription was set up
expect(store.subscribe).toHaveBeenCalled();
expect(storeCallbacks.length).toBeGreaterThan(0);
// The callback should be a function
expect(typeof storeCallbacks[storeCallbacks.length - 1]).toBe('function');
});
it('detects account changes and triggers reconnection', async () => {
// Setup connected state
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
// Get the store callback that was registered
storeCallback = storeCallbacks[storeCallbacks.length - 1];
// Clear mock calls from connection
mockDevLogger.log.mockClear();
// Simulate account change
(
selectSelectedInternalAccountByScope as unknown as jest.Mock
).mockReturnValue(() => ({ address: '0xdef456' }));
// Trigger the store callback with the changed value
storeCallback();
// Wait for async operations
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('State change detected'),
expect.objectContaining({
accountChanged: true,
networkChanged: false,
previousAddress: '0xabc123',
currentAddress: '0xdef456',
}),
);
expect(
mockStreamManagerInstance.marketData.clearCache,
).toHaveBeenCalledWith(true);
});
it('detects network changes and triggers reconnection', async () => {
// Setup connected state
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
// Get the store callback that was registered
expect(storeCallbacks.length).toBeGreaterThan(0);
storeCallback = storeCallbacks[storeCallbacks.length - 1];
expect(typeof storeCallback).toBe('function');
// Clear mock calls from connection
mockDevLogger.log.mockClear();
// Simulate network change
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('testnet');
// Trigger the store callback with the changed value
storeCallback();
// Wait for async operations
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('State change detected'),
expect.objectContaining({
accountChanged: false,
networkChanged: true,
previousNetwork: 'mainnet',
currentNetwork: 'testnet',
}),
);
expect(
mockStreamManagerInstance.marketData.clearCache,
).toHaveBeenCalledWith(false);
});
it('debounces rapid state changes into a single reconnection', async () => {
// Arrange
jest.useFakeTimers();
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
const storeCallback = storeCallbacks[storeCallbacks.length - 1];
// Simulate two rapid state changes within 50ms
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('testnet');
storeCallback();
(
selectSelectedInternalAccountByScope as unknown as jest.Mock
).mockReturnValue(() => ({ address: '0xnew' }));
storeCallback();
// Advance past the 50ms debounce window
jest.advanceTimersByTime(60);
await Promise.resolve();
// Assert: reconnect was called once, not twice (debounced)
const initCallCount = mockPerpsController.init.mock.calls.length;
// init was called once for connect(); any debounced reconnect fires one more time
expect(initCallCount).toBeGreaterThanOrEqual(1);
jest.useRealTimers();
});
it('ANDs pendingSkipMarketNotify across debounce window so network change keeps it false', async () => {
jest.useFakeTimers();
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
const cb = storeCallbacks[storeCallbacks.length - 1];
mockStreamManagerInstance.marketData.clearCache.mockClear();
// 1) Network change fires first → accountOnly=false → flag=false
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('testnet');
cb();
// 2) Account change fires within debounce window → accountOnly would be true,
// but AND with existing false keeps flag false
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('testnet'); // still changed
(
selectSelectedInternalAccountByScope as unknown as jest.Mock
).mockReturnValue(() => ({ address: '0xnew' }));
cb();
// Advance past debounce
jest.advanceTimersByTime(60);
await Promise.resolve();
await Promise.resolve();
// The second clearCache call inside performReconnection should use false
const calls = mockStreamManagerInstance.marketData.clearCache.mock.calls;
const lastCall = calls[calls.length - 1];
expect(lastCall[0]).toBe(false);
jest.useRealTimers();
});
it('clears pending debounce timer when cleanupStateMonitoring is called', async () => {
// Arrange: arm the debounce timer via a state change
jest.useFakeTimers();
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
await PerpsConnectionManager.connect();
const storeCallback = storeCallbacks[storeCallbacks.length - 1];
(selectPerpsNetwork as unknown as jest.Mock).mockReturnValue('testnet');
storeCallback();
const m = PerpsConnectionManager as unknown as {
stateChangeDebounceTimer: ReturnType<typeof setTimeout> | null;
cleanupStateMonitoring: () => void;
};
expect(m.stateChangeDebounceTimer).not.toBeNull();
// Act: invoke teardown directly to cover the timer-clearing branch
m.cleanupStateMonitoring();
// Assert: timer is cleared and no reconnect fires
expect(m.stateChangeDebounceTimer).toBeNull();
jest.advanceTimersByTime(100);
// init was only called once (for connect), not again from the cancelled debounce
expect(mockPerpsController.init).toHaveBeenCalledTimes(1);
jest.useRealTimers();
});
it('continues monitoring state changes during grace period', async () => {
// Setup but don't connect
mockPerpsController.init.mockResolvedValue();
mockPerpsController.getAccountState.mockResolvedValue({});
// Connect and immediately disconnect to set up monitoring
await PerpsConnectionManager.connect();
await PerpsConnectionManager.disconnect();
// Get the store callback that was registered (if any)
if (storeCallbacks.length > 0) {
storeCallback = storeCallbacks[storeCallbacks.length - 1];
// Clear mock calls
mockDevLogger.log.mockClear();
// Simulate account change
(
selectSelectedInternalAccountByScope as unknown as jest.Mock
).mockReturnValue(() => ({ address: '0xdef456' }));
// Trigger the store callback with changed values
storeCallback();
// Should still log account change detection during grace period
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('State change detected'),
expect.any(Object),
);
}
});
});
describe('reconnectWithNewContext', () => {
beforeEach(() => {
mockPerpsController.reconnectWithNewContext.mockResolvedValue();
});
it('clears all StreamManager caches on reconnection', async () => {
// Setup connected state first
mockPerpsController.init.mockResolvedValue();
await PerpsConnectionManager.connect();
// Now call reconnectWithNewContext through the private method
await (
PerpsConnectionManager as unknown as {
reconnectWithNewContext: () => Promise<void>;
}
).reconnectWithNewContext();
expect(mockStreamManagerInstance.positions.clearCache).toHaveBeenCalled();
expect(mockStreamManagerInstance.orders.clearCache).toHaveBeenCalled();
expect(mockStreamManagerInstance.account.clearCache).toHaveBeenCalled();
expect(
mockStreamManagerInstance.marketData.clearCache,
).toHaveBeenCalled();
expect(mockStreamManagerInstance.prices.clearCache).toHaveBeenCalled();
});
it('reinitializes controller with new account and network context', async () => {
mockPerpsController.init.mockResolvedValue();
await (
PerpsConnectionManager as unknown as {
reconnectWithNewContext: () => Promise<void>;
}
).reconnectWithNewContext();
// Manager now calls initializeProviders directly (Controller.reconnectWithNewContext was removed as redundant)
// Account data will be fetched via WebSocket subscriptions during preload, no explicit getAccountState() call
expect(mockPerpsController.init).toHaveBeenCalled();
});
it('waits for concurrent controller reinit before health-check ping', async () => {
// Arrange: controller reports reinitializing on first call, ready on second
mockPerpsController.init.mockResolvedValue();
const isReinitializing = (
Engine.context.PerpsController as unknown as {
isCurrentlyReinitializing: jest.Mock;
}
).isCurrentlyReinitializing;
isReinitializing
.mockReturnValueOnce(true)
.mockReturnValueOnce(true)
.mockReturnValue(false);
// Act
await (
PerpsConnectionManager as unknown as {
reconnectWithNewContext: () => Promise<void>;
}
).reconnectWithNewContext();
// Assert: polled at least twice before calling getActiveProvider
expect(isReinitializing.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(
Engine.context.PerpsController.getActiveProvider,
).toHaveBeenCalled();
});
it('logs error and resets connecting flag when reconnection fails', async () => {
const error = new Error('Reconnection failed');
mockPerpsController.init.mockRejectedValueOnce(error);
// Reconnection errors are caught, logged, and re-thrown (so caller can handle)
await expect(
(
PerpsConnectionManager as unknown as {
reconnectWithNewContext: () => Promise<void>;
}
).reconnectWithNewContext(),
).rejects.toThrow('Reconnection failed');
expect(mockDevLogger.log).toHaveBeenCalledWith(
expect.stringContaining('Reconnection with new context failed'),
error,
);
});
});
describe('Unified Account Cache Clearing (PR 25334)', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('clearUnifiedAccountCache', () => {
it('clears only unified account for specific network and user address', () => {
// Arrange
const network = 'mainnet' as const;
const userAddress = '0x1234567890123456789012345678901234567890';
// Act
PerpsConnectionManager.clearUnifiedAccountCache(network, userAddress);
// Assert - should call clearUnifiedAccount, NOT clear (which deletes entire entry)
expect(
mockTradingReadinessCache.clearUnifiedAccount,
).toHaveBeenCalledWith(network, userAddress);
expect(mockTradingReadinessCache.clear).not.toHaveBeenCalled();
expect(mockDevLogger.log).toHaveBeenCalledWith(
'PerpsConnectionManager: Unified Account cache cleared',
{ network, userAddress },
);
});
it('handles testnet network', () => {
// Arrange
const network = 'testnet' as const;
const userAddress = '0xTestnetUser12345678901234567890123456';
// Act
PerpsConnectionManager.clearUnifiedAccountCache(network, userAddress);
// Assert
expect(
mockTradingReadinessCache.clearUnifiedAccount,
).toHaveBeenCalledWith(network, userAddress);
});
});
describe('clearAllSigningCache', () => {
it('clears all cache entries', () => {
// Act
PerpsConnectionManager.clearAllSigningCache();
// Assert
expect(mockTradingReadinessCache.clearAll).toHaveBeenCalled();
expect(mockDevLogger.log).toHaveBeenCalledWith(
'PerpsConnectionManager: All signing cache cleared',
);
});
});
describe('clearAllDexAbstractionCache (deprecated)', () => {
it('delegates to clearAllSigningCache for backward compatibility', () => {
// Act
PerpsConnectionManager.clearAllDexAbstractionCache();
// Assert - should still clear all, just with new log message
expect(mockTradingReadinessCache.clearAll).toHaveBeenCalled();
expect(mockDevLogger.log).toHaveBeenCalledWith(
'PerpsConnectionManager: All signing cache cleared',
);
});
});
});
describe('preloadSubscriptions concurrency guard', () => {
it('skips concurrent preload when one is already in flight', async () => {
// Arrange
const m = PerpsConnectionManager as unknown as {
isPreloading: boolean;
hasPreloaded: boolean;
preloadSubscriptions: () => Promise<void>;
};
m.isPreloading = true;
// Act
await m.preloadSubscriptions();