-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsStreamManager.tsx
More file actions
1645 lines (1446 loc) · 51.8 KB
/
PerpsStreamManager.tsx
File metadata and controls
1645 lines (1446 loc) · 51.8 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 React, { createContext, useContext } from 'react';
import { v4 as uuidv4 } from 'uuid';
import performance from 'react-native-performance';
import Engine from '../../../../core/Engine';
import { DevLogger } from '../../../../core/SDKConnect/utils/DevLogger';
import Logger from '../../../../util/Logger';
import { ensureError } from '../../../../util/errorUtils';
import {
trace,
endTrace,
TraceName,
TraceOperation,
} from '../../../../util/trace';
import PerpsConnectionManager from '../services/PerpsConnectionManager';
import {
PERFORMANCE_CONFIG,
PERPS_CONSTANTS,
PerpsMeasurementName,
type PriceUpdate,
type Position,
type Order,
type OrderFill,
type AccountState,
type PerpsMarketData,
findEvmAccount,
} from '@metamask/perps-controller';
import { PROVIDER_CONFIG } from '../constants/perpsConfig';
import { getE2EMockStreamManager } from '../utils/e2eBridgePerps';
import { CandleStreamChannel } from './channels/CandleStreamChannel';
import { getPreloadedData } from '../hooks/stream/hasCachedPerpsData';
import { InternalAccount } from '@metamask/keyring-internal-api';
/**
* Gets the EVM account from the selected account group.
* Mobile-specific helper using Engine context.
* @returns EVM account or null if not found
*/
function getEvmAccountFromSelectedAccountGroup() {
const { AccountTreeController } = Engine.context;
const accounts = AccountTreeController.getAccountsFromSelectedAccountGroup();
return findEvmAccount(accounts as InternalAccount[]);
}
// Generic subscription parameters
interface StreamSubscription<T> {
id: string;
callback: (data: T) => void;
throttleMs?: number;
timer?: NodeJS.Timeout;
pendingUpdate?: T;
hasReceivedFirstUpdate?: boolean; // Track if subscriber has received first update
}
// Base class for any stream type
abstract class StreamChannel<T> {
protected cache = new Map<string, T>();
protected subscribers = new Map<string, StreamSubscription<T>>();
protected wsSubscription: (() => void) | null = null;
// Track account context to prevent stale data across account switches
protected accountAddress: string | null = null;
// Track WebSocket connection timing for first data measurement
protected wsConnectionStartTime: number | null = null;
// Flag to pause emission during operations (keeps WebSocket alive)
protected isPaused = false;
// Retry counter for deferred connect() calls
protected connectRetryCount = 0;
// Timer handle for deferConnect so it can be cancelled on disconnect
protected deferConnectTimer: ReturnType<typeof setTimeout> | null = null;
private static readonly MAX_CONNECT_RETRIES = 150; // 30s at 200ms
protected notifySubscribers(updates: T) {
// Block emission if paused (WebSocket continues receiving updates)
if (this.isPaused) {
return;
}
this.subscribers.forEach((subscriber) => {
// Check if this is the first update for this subscriber
if (!subscriber.hasReceivedFirstUpdate) {
subscriber.callback(updates);
subscriber.hasReceivedFirstUpdate = true;
return; // Don't set up throttle for the first update
}
// If no throttling (throttleMs is 0 or undefined), notify immediately
if (!subscriber.throttleMs) {
subscriber.callback(updates);
return;
}
// For subsequent updates with throttling, use throttle logic
// Store pending update
subscriber.pendingUpdate = updates;
// Throttle pattern: Only set timer if one isn't already running
// This ensures callbacks fire at most once per throttleMs interval
// WITHOUT resetting the countdown on every update (which would be debouncing)
// The conditional check prevents timer accumulation - no memory leaks
subscriber.timer ??= setTimeout(() => {
if (subscriber.pendingUpdate) {
subscriber.callback(subscriber.pendingUpdate);
subscriber.pendingUpdate = undefined;
}
subscriber.timer = undefined;
}, subscriber.throttleMs);
});
}
subscribe(params: {
callback: (data: T) => void;
throttleMs?: number;
}): () => void {
const id = Math.random().toString(36);
const subscription: StreamSubscription<T> = {
id,
...params,
hasReceivedFirstUpdate: false, // Initialize as false
};
this.subscribers.set(id, subscription);
// Give immediate cached data if available
const cached = this.getCachedData();
if (cached != null) {
params.callback(cached);
// Mark as having received first update since we provided cached data
subscription.hasReceivedFirstUpdate = true;
}
// Ensure WebSocket connected
this.connect();
// Return unsubscribe function
return () => {
const sub = this.subscribers.get(id);
if (sub?.timer) {
clearTimeout(sub.timer);
sub.timer = undefined;
}
this.subscribers.delete(id);
// Disconnect if no subscribers
if (this.subscribers.size === 0) {
this.disconnect();
}
};
}
protected connect() {
// Override in subclasses
}
/**
* Schedule a deferred connect() retry with safety checks.
* Aborts if no subscribers remain or max retries exceeded.
*/
protected deferConnect(delayMs: number): void {
if (this.subscribers.size === 0) {
this.connectRetryCount = 0;
return;
}
if (this.connectRetryCount >= StreamChannel.MAX_CONNECT_RETRIES) {
DevLogger.log(
`${this.constructor.name}: Max connect retries exceeded (${StreamChannel.MAX_CONNECT_RETRIES}), giving up`,
);
this.connectRetryCount = 0;
return;
}
this.connectRetryCount++;
if (this.deferConnectTimer) {
clearTimeout(this.deferConnectTimer);
}
this.deferConnectTimer = setTimeout(() => {
this.deferConnectTimer = null;
this.connect();
}, delayMs);
}
/**
* Common initialization guard for connect().
* Returns true if the channel is ready to connect, false if deferred.
* Resets connectRetryCount on success.
*
* When the connection manager is actively connecting, awaits the connection
* promise and retries connect() once resolved, instead of blind 200ms polling.
*/
protected ensureReady(): boolean {
if (Engine.context.PerpsController.isCurrentlyReinitializing()) {
this.deferConnect(PERPS_CONSTANTS.ReconnectionCleanupDelayMs);
return false;
}
const connState = PerpsConnectionManager.getConnectionState();
if (!connState.isInitialized) {
// If actively connecting, await the connection promise instead of polling
if (connState.isConnecting) {
DevLogger.log(
`${this.constructor.name}: ensureReady: awaiting active connection`,
);
this.awaitConnectionThenConnect();
return false;
}
this.deferConnect(PERPS_CONSTANTS.ConnectRetryDelayMs);
return false;
}
this.connectRetryCount = 0;
return true;
}
/**
* Await the PerpsConnectionManager connection promise, then retry connect().
* This replaces blind 200ms polling when we know a connection is in progress.
*/
private awaitConnectionThenConnect(): void {
// Prevent duplicate awaits — only one outstanding wait at a time
if (this.deferConnectTimer) {
return;
}
// Use a sentinel timer value to signal that we're waiting on the promise
// This prevents deferConnect from also scheduling a parallel timer
const noop = () => {
/* sentinel timer */
};
const sentinel = setTimeout(noop, 0);
this.deferConnectTimer = sentinel;
PerpsConnectionManager.waitForConnection()
.then(() => {
// Only clear if our sentinel is still the active timer; a disconnect()
// followed by a new subscribe() may have replaced it with a real timer.
if (this.deferConnectTimer === sentinel) {
this.deferConnectTimer = null;
}
if (this.subscribers.size > 0) {
this.connect();
}
})
.catch(() => {
if (this.deferConnectTimer === sentinel) {
this.deferConnectTimer = null;
}
// Connection failed — fall back to normal defer polling
if (this.subscribers.size > 0) {
DevLogger.log(
`${this.constructor.name}: awaitConnectionThenConnect: connection failed, falling back to polling`,
);
this.deferConnect(PERPS_CONSTANTS.ConnectRetryDelayMs);
}
});
}
/**
* Reconnect the channel after WebSocket reconnection
* Clears dead subscription and re-establishes if there are active subscribers
*/
public reconnect() {
this.disconnect();
// Re-establish connection if there are active subscribers
if (this.subscribers.size > 0) {
this.connect();
}
}
public disconnect() {
this.connectRetryCount = 0;
if (this.deferConnectTimer) {
clearTimeout(this.deferConnectTimer);
this.deferConnectTimer = null;
}
// This prevents orphaned timers from continuing to run after disconnect
this.subscribers.forEach((subscriber) => {
if (subscriber.timer) {
clearTimeout(subscriber.timer);
subscriber.timer = undefined;
}
subscriber.pendingUpdate = undefined;
});
if (this.wsSubscription) {
this.wsSubscription();
this.wsSubscription = null;
}
this.accountAddress = null;
this.wsConnectionStartTime = null;
}
/**
* Pause emission of updates to subscribers
* WebSocket connection stays alive and continues receiving data
* Used during batch operations to prevent UI re-renders from stale data
*/
public pause(): void {
this.isPaused = true;
}
/**
* Resume emission of updates to subscribers
* Subscribers will receive the next update from the WebSocket
*/
public resume(): void {
this.isPaused = false;
}
protected getCachedData(): T | null {
// Override in subclasses to return null for no cache, or actual data
return null;
}
public clearCache(): void {
// This ensures no timers are orphaned during the disconnect/reconnect cycle
this.subscribers.forEach((subscriber) => {
// Clear any pending updates and timers
if (subscriber.timer) {
clearTimeout(subscriber.timer);
subscriber.timer = undefined;
}
subscriber.pendingUpdate = undefined;
subscriber.hasReceivedFirstUpdate = false;
});
// Disconnect the old WebSocket subscription to stop receiving old account data
if (this.wsSubscription) {
this.disconnect();
}
// Reset account context immediately
this.accountAddress = null;
this.wsConnectionStartTime = null;
// Clear the cache
this.cache.clear();
// Notify subscribers with cleared data to trigger loading state
// Using getClearedData() ensures type safety while maintaining loading semantics
this.subscribers.forEach((subscriber) => {
// Send cleared data to indicate "no data yet" (loading state)
subscriber.callback(this.getClearedData());
});
// If we have active subscribers, they'll trigger reconnect in their next render
// The connect() call will create a new WebSocket with the new account
}
protected abstract getClearedData(): T;
}
// Specific channel for prices
class PriceStreamChannel extends StreamChannel<Record<string, PriceUpdate>> {
private readonly symbols = new Set<string>();
private prewarmUnsubscribe?: () => void;
private actualPriceUnsubscribe?: () => void;
private allMarketSymbols: string[] = [];
// Unique ID per prewarm cycle to detect stale promises and prevent subscription leaks
private prewarmCycleId: number = 0;
// Override cache to store individual PriceUpdate objects
protected priceCache = new Map<string, PriceUpdate>();
protected connect() {
if (this.wsSubscription) {
return;
}
if (!this.ensureReady()) return;
// If we have a prewarm subscription, we're already subscribed to all markets
// No need to create another subscription
if (this.prewarmUnsubscribe) {
// Just notify subscribers with cached data
const cached = this.getCachedData();
if (cached) {
this.notifySubscribers(cached);
}
return;
}
// Collect all unique symbols from subscribers
const allSymbols = Array.from(this.symbols);
DevLogger.log(
`PriceStreamChannel: allSymbols len=`,
allSymbols.length,
allSymbols,
);
if (allSymbols.length === 0) {
return;
}
this.wsSubscription = Engine.context.PerpsController.subscribeToPrices({
symbols: allSymbols,
callback: (updates: PriceUpdate[]) => {
// Update cache and build price map
const priceMap: Record<string, PriceUpdate> = {};
updates.forEach((update) => {
// Map the update to PriceUpdate format
const priceUpdate: PriceUpdate = {
symbol: update.symbol,
price: update.price,
timestamp: Date.now(),
percentChange24h: update.percentChange24h,
bestBid: update.bestBid,
bestAsk: update.bestAsk,
spread: update.spread,
markPrice: update.markPrice,
funding: update.funding,
openInterest: update.openInterest,
volume24h: update.volume24h,
};
this.priceCache.set(update.symbol, priceUpdate);
priceMap[update.symbol] = priceUpdate;
});
this.notifySubscribers(priceMap);
},
});
}
protected getCachedData(): Record<string, PriceUpdate> | null {
if (this.priceCache.size === 0) return null;
const cached: Record<string, PriceUpdate> = {};
this.priceCache.forEach((value, key) => {
cached[key] = value;
});
return cached;
}
protected getClearedData(): Record<string, PriceUpdate> {
return {};
}
public clearCache(): void {
// Clear the price-specific cache
this.priceCache.clear();
// Cleanup pre-warm subscription
this.cleanupPrewarm();
// Call parent clearCache
super.clearCache();
}
subscribeToSymbols(params: {
symbols: string[];
callback: (prices: Record<string, PriceUpdate>) => void;
throttleMs?: number;
}): () => void {
// Track symbols for filtering
params.symbols.forEach((s) => {
this.symbols.add(s);
});
// Ensure connection is established (allMids provides all symbols)
// No need to reconnect when new symbols are added since allMids
// already provides prices for all markets
if (!this.wsSubscription && !this.prewarmUnsubscribe) {
this.connect();
}
return this.subscribe({
callback: (allPrices) => {
// Filter to only requested symbols
const filtered: Record<string, PriceUpdate> = {};
params.symbols.forEach((symbol) => {
if (allPrices?.[symbol]) {
filtered[symbol] = allPrices[symbol];
}
});
params.callback(filtered);
},
throttleMs: params.throttleMs,
});
}
/**
* Pre-warm the channel by subscribing to all market prices
* This keeps a single WebSocket connection alive with all price updates
* Non-blocking: Returns immediately while market fetch happens in background
* @returns Cleanup function to call when leaving Perps environment
*/
public async prewarm(): Promise<() => void> {
if (this.prewarmUnsubscribe) {
DevLogger.log('PriceStreamChannel: Already pre-warmed');
return this.prewarmUnsubscribe;
}
const controller = Engine.context.PerpsController;
if (!controller) return () => undefined;
// Increment cycle ID to detect stale promises from previous prewarm cycles
// This prevents subscription leaks when user navigates: Perps → away → back quickly
this.prewarmCycleId++;
const currentCycleId = this.prewarmCycleId;
// Start market fetch in background (non-blocking)
// We need the symbols to register subscribers, but we can return immediately
controller
.getMarkets()
.then((markets) => {
// If this promise is from a stale cycle, don't set up subscription
// This prevents leaks when prewarm is called multiple times rapidly
if (currentCycleId !== this.prewarmCycleId) {
DevLogger.log('PriceStreamChannel: Skipping stale prewarm cycle', {
currentCycleId,
activeCycleId: this.prewarmCycleId,
});
return;
}
// If already cleaned up, don't set up subscription
if (this.prewarmUnsubscribe === undefined) {
return;
}
this.allMarketSymbols = markets.map((market) => market.name);
DevLogger.log(
'PriceStreamChannel: Pre-warming with all market symbols',
{
symbolCount: this.allMarketSymbols.length,
symbols: this.allMarketSymbols.slice(0, 10),
},
);
// WARNING: Do NOT set includeMarketData: true here. It triggers
// per-symbol activeAssetCtx subscriptions (N symbols × N DEXs = N²
// WebSocket connections). assetCtxs (1 per DEX) is always established
// by the subscription service regardless of this flag.
const unsub = controller.subscribeToPrices({
symbols: this.allMarketSymbols,
includeMarketData: false,
callback: (updates: PriceUpdate[]) => {
const priceMap: Record<string, PriceUpdate> = {};
updates.forEach((update) => {
const priceUpdate: PriceUpdate = {
symbol: update.symbol,
price: update.price,
timestamp: Date.now(),
percentChange24h: update.percentChange24h,
bestBid: update.bestBid,
bestAsk: update.bestAsk,
spread: update.spread,
markPrice: update.markPrice,
funding: update.funding,
openInterest: update.openInterest,
volume24h: update.volume24h,
};
this.priceCache.set(update.symbol, priceUpdate);
priceMap[update.symbol] = priceUpdate;
});
if (this.subscribers.size > 0) {
this.notifySubscribers(priceMap);
}
},
});
// Store the actual unsubscribe function
this.actualPriceUnsubscribe = unsub;
})
.catch((error) => {
Logger.error(
ensureError(error, 'PriceStreamChannel.prewarm.backgroundFetch'),
{
context: 'PriceStreamChannel.prewarm.backgroundFetch',
},
);
// Reset state so subsequent prewarm/connect calls can recover
this.prewarmUnsubscribe = undefined;
this.allMarketSymbols = [];
// Reconnect waiting subscribers that were skipped because prewarm was pending
if (this.subscribers.size > 0) {
this.connect();
}
});
// Return cleanup function immediately (before markets load)
this.prewarmUnsubscribe = () => {
DevLogger.log('PriceStreamChannel: Cleaning up prewarm subscription');
this.cleanupPrewarm();
};
return this.prewarmUnsubscribe;
}
/**
* Cleanup pre-warm subscription
*/
public cleanupPrewarm(): void {
if (this.actualPriceUnsubscribe) {
this.actualPriceUnsubscribe();
this.actualPriceUnsubscribe = undefined;
}
this.prewarmUnsubscribe = undefined;
this.allMarketSymbols = [];
}
}
// Specific channel for orders (null = cleared on account switch; hooks show skeleton until next update)
class OrderStreamChannel extends StreamChannel<Order[] | null> {
private prewarmUnsubscribe?: () => void;
private firstDataTraceId?: string;
protected connect() {
if (this.wsSubscription) return;
if (!this.ensureReady()) return;
// Start trace for first data measurement (before subscription)
this.firstDataTraceId = uuidv4();
trace({
name: TraceName.PerpsWebSocketFirstOrders,
id: this.firstDataTraceId,
op: TraceOperation.PerpsOperation,
});
// Track WebSocket connection start time for duration calculation
this.wsConnectionStartTime = performance.now();
this.wsSubscription = Engine.context.PerpsController.subscribeToOrders({
callback: (orders: Order[]) => {
// Validate account context
const currentAccount =
getEvmAccountFromSelectedAccountGroup()?.address || null;
if (this.accountAddress && this.accountAddress !== currentAccount) {
Logger.error(new Error('OrderStreamChannel: Wrong account context'), {
expected: currentAccount,
received: this.accountAddress,
});
return;
}
this.accountAddress = currentAccount;
// Track first order data from WebSocket (only once per connection)
if (this.wsConnectionStartTime !== null && this.firstDataTraceId) {
const firstDataDuration =
performance.now() - this.wsConnectionStartTime;
// Log WebSocket performance measurement
DevLogger.log(
`${PERFORMANCE_CONFIG.LoggingMarkers.WebsocketPerformance} PerpsWS: First order data received`,
{
duration: `${firstDataDuration.toFixed(0)}ms`,
},
);
// End trace with accurate duration
endTrace({
name: TraceName.PerpsWebSocketFirstOrders,
id: this.firstDataTraceId,
data: {
success: true,
duration: firstDataDuration,
},
});
this.wsConnectionStartTime = null;
this.firstDataTraceId = undefined;
}
this.cache.set('orders', orders);
this.notifySubscribers(orders);
},
});
}
protected getCachedData() {
const cached = this.cache.get('orders');
if (cached !== undefined) return cached;
return getPreloadedData<Order[]>('cachedOrders');
}
protected getClearedData(): Order[] | null {
return null;
}
/**
* Pre-warm the channel by creating a persistent subscription
* This keeps the WebSocket connection alive and caches data continuously
* @returns Cleanup function to call when leaving Perps environment
*/
public prewarm(): () => void {
if (this.prewarmUnsubscribe) {
DevLogger.log('OrderStreamChannel: Already pre-warmed');
return this.prewarmUnsubscribe;
}
// Create a real subscription with no-op callback to keep connection alive
this.prewarmUnsubscribe = this.subscribe({
callback: () => {
// No-op callback - just keeps the connection alive for caching
},
throttleMs: 0, // No throttle for pre-warm
});
// Return cleanup function that clears internal state
return () => {
DevLogger.log('OrderStreamChannel: Cleaning up prewarm subscription');
this.cleanupPrewarm();
};
}
/**
* Cleanup pre-warm subscription
*/
public cleanupPrewarm(): void {
if (this.prewarmUnsubscribe) {
this.prewarmUnsubscribe();
this.prewarmUnsubscribe = undefined;
}
}
public disconnect() {
this.firstDataTraceId = undefined;
super.disconnect();
}
public clearCache(): void {
// Cleanup pre-warm subscription
this.cleanupPrewarm();
this.firstDataTraceId = undefined;
// Call parent clearCache
super.clearCache();
}
}
// Specific channel for positions (null = cleared on account switch; hooks show skeleton until next update)
class PositionStreamChannel extends StreamChannel<Position[] | null> {
private prewarmUnsubscribe?: () => void;
private firstDataTraceId?: string;
protected connect() {
if (this.wsSubscription) return;
if (!this.ensureReady()) return;
// Start trace for first data measurement (before subscription)
this.firstDataTraceId = uuidv4();
trace({
name: TraceName.PerpsWebSocketFirstPositions,
id: this.firstDataTraceId,
op: TraceOperation.PerpsOperation,
});
// Track WebSocket connection start time for duration calculation
this.wsConnectionStartTime = performance.now();
this.wsSubscription = Engine.context.PerpsController.subscribeToPositions({
callback: (positions: Position[]) => {
// Validate account context
const currentAccount =
getEvmAccountFromSelectedAccountGroup()?.address || null;
if (this.accountAddress && this.accountAddress !== currentAccount) {
Logger.error(
new Error('PositionStreamChannel: Wrong account context'),
{
expected: currentAccount,
received: this.accountAddress,
},
);
return;
}
this.accountAddress = currentAccount;
// Track first position data from WebSocket (only once per connection)
if (this.wsConnectionStartTime !== null && this.firstDataTraceId) {
const firstDataDuration =
performance.now() - this.wsConnectionStartTime;
// Log WebSocket performance measurement
DevLogger.log(
`${PERFORMANCE_CONFIG.LoggingMarkers.WebsocketPerformance} PerpsWS: First position data received`,
{
metric: PerpsMeasurementName.PerpsWebsocketFirstPositionData,
duration: `${firstDataDuration.toFixed(0)}ms`,
},
);
// End trace with accurate duration
endTrace({
name: TraceName.PerpsWebSocketFirstPositions,
id: this.firstDataTraceId,
data: {
success: true,
duration: firstDataDuration,
},
});
this.wsConnectionStartTime = null;
this.firstDataTraceId = undefined;
}
this.cache.set('positions', positions);
this.notifySubscribers(positions);
},
});
}
protected getCachedData() {
const cached = this.cache.get('positions');
if (cached !== undefined) return cached;
return getPreloadedData<Position[]>('cachedPositions');
}
protected getClearedData(): Position[] | null {
return null;
}
/**
* Pre-warm the channel by creating a persistent subscription
* This keeps the WebSocket connection alive and caches data continuously
* @returns Cleanup function to call when leaving Perps environment
*/
public prewarm(): () => void {
if (this.prewarmUnsubscribe) {
DevLogger.log('PositionStreamChannel: Already pre-warmed');
return this.prewarmUnsubscribe;
}
// Create a real subscription with no-op callback to keep connection alive
this.prewarmUnsubscribe = this.subscribe({
callback: () => {
// No-op callback - just keeps the connection alive for caching
},
throttleMs: 0, // No throttle for pre-warm
});
// Return cleanup function that clears internal state
return () => {
DevLogger.log('PositionStreamChannel: Cleaning up prewarm subscription');
this.cleanupPrewarm();
};
}
public disconnect() {
this.firstDataTraceId = undefined;
super.disconnect();
}
public clearCache(): void {
// Cleanup pre-warm subscription
this.cleanupPrewarm();
this.firstDataTraceId = undefined;
// Call parent clearCache
super.clearCache();
}
/**
* Cleanup pre-warm subscription
*/
public cleanupPrewarm(): void {
if (this.prewarmUnsubscribe) {
this.prewarmUnsubscribe();
this.prewarmUnsubscribe = undefined;
}
}
/**
* Apply optimistic update for TP/SL prices to a position
* This immediately updates the UI before WebSocket confirms the change
* @param coin - The coin/asset symbol
* @param takeProfitPrice - The new take profit price (undefined to remove)
* @param stopLossPrice - The new stop loss price (undefined to remove)
*/
public updatePositionTPSLOptimistic(
coin: string,
takeProfitPrice: string | undefined,
stopLossPrice: string | undefined,
): void {
const cachedPositions = this.cache.get('positions');
if (!cachedPositions) {
DevLogger.log(
'PositionStreamChannel: Cannot apply optimistic update - no cached positions',
);
return;
}
const positionIndex = cachedPositions.findIndex((p) => p.symbol === coin);
if (positionIndex === -1) {
DevLogger.log(
`PositionStreamChannel: Cannot apply optimistic update - position not found for ${coin}`,
);
return;
}
// Create updated positions array with the optimistic TP/SL values
const updatedPositions = cachedPositions.map((position, index) => {
if (index === positionIndex) {
return {
...position,
takeProfitPrice,
stopLossPrice,
// Update counts based on whether TP/SL is set
takeProfitCount: takeProfitPrice ? 1 : 0,
stopLossCount: stopLossPrice ? 1 : 0,
};
}
return position;
});
DevLogger.log('PositionStreamChannel: Applying optimistic TP/SL update', {
coin,
takeProfitPrice,
stopLossPrice,
});
// Update cache and notify subscribers immediately
this.cache.set('positions', updatedPositions);
this.notifySubscribers(updatedPositions);
}
}
// Specific channel for fills
class FillStreamChannel extends StreamChannel<OrderFill[]> {
private prewarmUnsubscribe?: () => void;
protected connect() {
if (this.wsSubscription) return;
if (!this.ensureReady()) return;
this.wsSubscription = Engine.context.PerpsController.subscribeToOrderFills({
callback: (fills: OrderFill[], isSnapshot?: boolean) => {
let updated: OrderFill[];
if (isSnapshot) {
// Snapshot: replace cache with initial historical data
// Sort by timestamp descending (newest first)
updated = [...fills]
.sort((a, b) => b.timestamp - a.timestamp)
.slice(0, 100);
} else {
// Streaming: prepend new fills to existing (newest first)
const existing = this.cache.get('fills') || [];
// New fills go at the beginning since they're most recent
updated = [...fills, ...existing].slice(0, 100);
}
this.cache.set('fills', updated);
this.notifySubscribers(updated);
},
});
}
protected getCachedData() {
return this.cache.get('fills') || [];
}
protected getClearedData(): OrderFill[] {
return [];
}
/**
* Pre-warm the channel by creating a persistent subscription
* This keeps the WebSocket connection alive and caches fills data continuously
* @returns Cleanup function to call when leaving Perps environment
*/
public prewarm(): () => void {
if (this.prewarmUnsubscribe) {
DevLogger.log('FillStreamChannel: Already pre-warmed');
return this.prewarmUnsubscribe;
}
// Create a real subscription with no-op callback to keep connection alive
this.prewarmUnsubscribe = this.subscribe({
callback: () => {
// No-op callback - just keeps the connection alive for caching
},
throttleMs: 0, // No throttle for pre-warm
});
// Return cleanup function that clears internal state
return () => {
DevLogger.log('FillStreamChannel: Cleaning up prewarm subscription');
this.cleanupPrewarm();
};
}
/**
* Cleanup pre-warm subscription
*/
public cleanupPrewarm(): void {
if (this.prewarmUnsubscribe) {
this.prewarmUnsubscribe();
this.prewarmUnsubscribe = undefined;
}
}
public clearCache(): void {
// Cleanup pre-warm subscription
this.cleanupPrewarm();
// Call parent clearCache
super.clearCache();
}
}
// Specific channel for account state
class AccountStreamChannel extends StreamChannel<AccountState | null> {
private prewarmUnsubscribe?: () => void;
private firstDataTraceId?: string;
protected connect() {
if (this.wsSubscription) return;