forked from tiagosiebler/bybit-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket-client.ts
1267 lines (1130 loc) · 36.4 KB
/
websocket-client.ts
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
/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { EventEmitter } from 'events';
import WebSocket from 'isomorphic-ws';
import { InverseClient } from './inverse-client';
import { LinearClient } from './linear-client';
import { SpotClientV3 } from './spot-client-v3';
import { SpotClient } from './spot-client';
import { USDCOptionClient } from './usdc-option-client';
import { USDCPerpetualClient } from './usdc-perpetual-client';
import { UnifiedMarginClient } from './unified-margin-client';
import { ContractClient } from './contract-client';
import { signMessage } from './util/node-support';
import WsStore from './util/WsStore';
import {
APIMarket,
CategoryV5,
KlineInterval,
RESTClient,
WSClientConfigurableOptions,
WebsocketClientOptions,
WsKey,
WsTopic,
} from './types';
import {
DefaultLogger,
PUBLIC_WS_KEYS,
WS_AUTH_ON_CONNECT_KEYS,
WS_KEY_MAP,
WsConnectionStateEnum,
getMaxTopicsPerSubscribeEvent,
getWsKeyForTopic,
getWsUrl,
isPrivateWsTopic,
isTopicSubscriptionConfirmation,
isTopicSubscriptionSuccess,
isWsPong,
neverGuard,
safeTerminateWs,
serializeParams,
} from './util';
import { RestClientV5 } from './rest-client-v5';
import { WebsocketTopicSubscriptionConfirmationEvent } from './types/ws-events/topic-subscription-confirmation';
const loggerCategory = { category: 'bybit-ws' };
export type WsClientEvent =
| 'open'
| 'update'
| 'close'
| 'error'
| 'reconnect'
| 'reconnected'
| 'response';
interface WebsocketClientEvents {
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
open: (evt: { wsKey: WsKey; event: any }) => void;
/** Reconnecting a dropped connection */
reconnect: (evt: { wsKey: WsKey; event: any }) => void;
/** Successfully reconnected a connection that dropped */
reconnected: (evt: { wsKey: WsKey; event: any }) => void;
/** Connection closed */
close: (evt: { wsKey: WsKey; event: any }) => void;
/** Received reply to websocket command (e.g. after subscribing to topics) */
response: (response: any) => void;
/** Received data for topic */
update: (response: any) => void;
/** Exception from ws client OR custom listeners */
error: (response: any) => void;
}
type TopicsPendingSubscriptionsResolver = () => void;
type TopicsPendingSubscriptionsRejector = (reason: string) => void;
interface TopicsPendingSubscriptions {
wsKey: string;
failedTopicsSubscriptions: Set<string>;
pendingTopicsSubscriptions: Set<string>;
resolver: TopicsPendingSubscriptionsResolver;
rejector: TopicsPendingSubscriptionsRejector;
}
// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837
export declare interface WebsocketClient {
on<U extends keyof WebsocketClientEvents>(
event: U,
listener: WebsocketClientEvents[U],
): this;
emit<U extends keyof WebsocketClientEvents>(
event: U,
...args: Parameters<WebsocketClientEvents[U]>
): boolean;
}
// eslint-disable-next-line no-redeclare
export class WebsocketClient extends EventEmitter {
private logger: typeof DefaultLogger;
private restClient?: RESTClient;
private options: WebsocketClientOptions;
private wsStore: WsStore;
private pendingTopicsSubscriptions: TopicsPendingSubscriptions[] = [];
constructor(
options: WSClientConfigurableOptions,
logger?: typeof DefaultLogger,
) {
super();
this.logger = logger || DefaultLogger;
this.wsStore = new WsStore(this.logger);
this.options = {
testnet: false,
pongTimeout: 1000,
pingInterval: 10000,
reconnectTimeout: 500,
recvWindow: 5000,
fetchTimeOffsetBeforeAuth: false,
...options,
};
this.options.restOptions = {
...this.options.restOptions,
testnet: this.options.testnet,
};
this.prepareRESTClient();
// add default error handling so this doesn't crash node (if the user didn't set a handler)
// eslint-disable-next-line @typescript-eslint/no-empty-function
this.on('error', () => {});
}
/** Get the WsStore that tracks websockets & topics */
public getWsStore(): WsStore {
return this.wsStore;
}
public isTestnet(): boolean {
return this.options.testnet === true;
}
/**
* Subscribe to V5 topics & track/persist them.
* @param wsTopics - topic or list of topics
* @param category - the API category this topic is for (e.g. "linear"). The value is only important when connecting to public topics and will be ignored for private topics.
* @param isPrivateTopic - optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
*/
public subscribeV5(
wsTopics: WsTopic[] | WsTopic,
category: CategoryV5,
isPrivateTopic?: boolean,
) {
const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
return new Promise<void>((resolver, rejector) => {
topics.forEach((topic) => {
const wsKey = getWsKeyForTopic(
this.options.market,
topic,
isPrivateTopic,
category,
);
// Persist topic for reconnects
this.wsStore.addTopic(wsKey, topic);
this.upsertPendingTopicsSubscriptions(wsKey, topic, resolver, rejector);
// if connected, send subscription request
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED)
) {
return this.requestSubscribeTopics(wsKey, [topic]);
}
// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
if (
!this.wsStore.isConnectionState(
wsKey,
WsConnectionStateEnum.CONNECTING,
) &&
!this.wsStore.isConnectionState(
wsKey,
WsConnectionStateEnum.RECONNECTING,
)
) {
return this.connect(wsKey);
}
});
});
}
/**
* Subscribe to V1-V3 topics & track/persist them.
*
* Note: for public V5 topics use the `subscribeV5()` method.
*
* Topics will be automatically resubscribed to if the connection resets/drops/reconnects.
* @param wsTopics - topic or list of topics
* @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
*/
public subscribe(
wsTopics: WsTopic[] | WsTopic,
isPrivateTopic?: boolean,
): Promise<void> {
const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
if (this.options.market === 'v5') {
topics.forEach((topic) => {
if (!isPrivateWsTopic(topic)) {
throw new Error(
'For public "v5" websocket topics, use the subscribeV5() method & provide the category parameter',
);
}
});
}
return new Promise<void>((resolver, rejector) => {
topics.forEach((topic) => {
const wsKey = getWsKeyForTopic(
this.options.market,
topic,
isPrivateTopic,
);
// Persist topic for reconnects
this.wsStore.addTopic(wsKey, topic);
this.upsertPendingTopicsSubscriptions(wsKey, topic, resolver, rejector);
// if connected, send subscription request
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED)
) {
return this.requestSubscribeTopics(wsKey, [topic]);
}
// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
if (
!this.wsStore.isConnectionState(
wsKey,
WsConnectionStateEnum.CONNECTING,
) &&
!this.wsStore.isConnectionState(
wsKey,
WsConnectionStateEnum.RECONNECTING,
)
) {
return this.connect(wsKey);
}
});
});
}
private upsertPendingTopicsSubscriptions(
wsKey: string,
topic: string,
resolver: TopicsPendingSubscriptionsResolver,
rejector: TopicsPendingSubscriptionsRejector,
) {
const existingWsKeyPendingSubscriptions =
this.pendingTopicsSubscriptions.find((s) => s.wsKey === wsKey);
if (!existingWsKeyPendingSubscriptions) {
this.pendingTopicsSubscriptions.push({
wsKey,
resolver,
rejector,
failedTopicsSubscriptions: new Set(),
pendingTopicsSubscriptions: new Set([topic]),
});
return;
}
existingWsKeyPendingSubscriptions.pendingTopicsSubscriptions.add(topic);
}
/**
* Unsubscribe from V5 topics & remove them from memory. They won't be re-subscribed to if the connection reconnects.
* @param wsTopics - topic or list of topics
* @param category - the API category this topic is for (e.g. "linear"). The value is only important when connecting to public topics and will be ignored for private topics.
* @param isPrivateTopic - optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
*/
public unsubscribeV5(
wsTopics: WsTopic[] | WsTopic,
category: CategoryV5,
isPrivateTopic?: boolean,
) {
const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
topics.forEach((topic) => {
const wsKey = getWsKeyForTopic(
this.options.market,
topic,
isPrivateTopic,
category,
);
// Remove topic from persistence for reconnects
this.wsStore.deleteTopic(wsKey, topic);
this.removeTopicPendingSubscription(wsKey, topic);
// unsubscribe request only necessary if active connection exists
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED)
) {
this.requestUnsubscribeTopics(wsKey, [topic]);
}
});
}
private removeTopicPendingSubscription(wsKey: string, topic: string) {
const existingWsKeyPendingSubscriptions =
this.pendingTopicsSubscriptions.find((s) => s.wsKey === wsKey);
if (existingWsKeyPendingSubscriptions) {
existingWsKeyPendingSubscriptions.pendingTopicsSubscriptions.delete(
topic,
);
if (!existingWsKeyPendingSubscriptions.pendingTopicsSubscriptions.size) {
this.pendingTopicsSubscriptions =
this.pendingTopicsSubscriptions.filter((s) => s.wsKey !== wsKey);
}
}
}
private clearTopicsPendingSubscriptions(wsKey: string) {
this.pendingTopicsSubscriptions = this.pendingTopicsSubscriptions.filter(
(s) => s.wsKey !== wsKey,
);
}
/**
* Unsubscribe from V1-V3 topics & remove them from memory. They won't be re-subscribed to if the connection reconnects.
*
* Note: For public V5 topics, use `unsubscribeV5()` instead!
*
* @param wsTopics topic or list of topics
* @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
*/
public unsubscribe(wsTopics: WsTopic[] | WsTopic, isPrivateTopic?: boolean) {
const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
if (this.options.market === 'v5') {
topics.forEach((topic) => {
if (!isPrivateWsTopic(topic)) {
throw new Error(
'For public "v5" websocket topics, use the unsubscribeV5() method & provide the category parameter',
);
}
});
}
topics.forEach((topic) => {
const wsKey = getWsKeyForTopic(
this.options.market,
topic,
isPrivateTopic,
);
// Remove topic from persistence for reconnects
this.wsStore.deleteTopic(wsKey, topic);
this.removeTopicPendingSubscription(wsKey, topic);
// unsubscribe request only necessary if active connection exists
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED)
) {
this.requestUnsubscribeTopics(wsKey, [topic]);
}
});
}
/**
* @private Only used if we fetch exchange time before attempting auth. Disabled by default.
* I've removed this for ftx and it's working great, tempted to remove this here
*/
private prepareRESTClient(): void {
switch (this.options.market) {
case 'inverse': {
this.restClient = new InverseClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'linear': {
this.restClient = new LinearClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'spot': {
this.restClient = new SpotClient(
this.options.restOptions,
this.options.requestOptions,
);
this.connectPublic();
break;
}
case 'spotv3': {
this.restClient = new SpotClientV3(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'usdcOption': {
this.restClient = new USDCOptionClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'usdcPerp': {
this.restClient = new USDCPerpetualClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'unifiedOption':
case 'unifiedPerp': {
this.restClient = new UnifiedMarginClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'contractInverse':
case 'contractUSDT': {
this.restClient = new ContractClient(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
case 'v5': {
this.restClient = new RestClientV5(
this.options.restOptions,
this.options.requestOptions,
);
break;
}
default: {
throw neverGuard(
this.options.market,
'prepareRESTClient(): Unhandled market',
);
}
}
}
public close(wsKey: WsKey, force?: boolean) {
this.logger.info('Closing connection', { ...loggerCategory, wsKey });
this.setWsState(wsKey, WsConnectionStateEnum.CLOSING);
this.clearTimers(wsKey);
const ws = this.getWs(wsKey);
ws?.close();
if (force) {
safeTerminateWs(ws);
}
}
public closeAll(force?: boolean) {
const keys = this.wsStore.getKeys();
this.logger.info(`Closing all ws connections: ${keys}`);
keys.forEach((key) => {
this.close(key, force);
});
}
/**
* Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
*/
public connectAll(): Promise<WebSocket | undefined>[] {
switch (this.options.market) {
case 'inverse': {
// only one for inverse
return [...this.connectPublic()];
}
// these all have separate public & private ws endpoints
case 'linear':
case 'spot':
case 'spotv3':
case 'usdcOption':
case 'usdcPerp':
case 'unifiedPerp':
case 'unifiedOption':
case 'contractUSDT':
case 'contractInverse': {
return [...this.connectPublic(), this.connectPrivate()];
}
case 'v5': {
return [this.connectPrivate()];
}
default: {
throw neverGuard(this.options.market, 'connectAll(): Unhandled market');
}
}
}
public connectPublic(): Promise<WebSocket | undefined>[] {
switch (this.options.market) {
case 'inverse': {
return [this.connect(WS_KEY_MAP.inverse)];
}
case 'linear': {
return [this.connect(WS_KEY_MAP.linearPublic)];
}
case 'spot': {
return [this.connect(WS_KEY_MAP.spotPublic)];
}
case 'spotv3': {
return [this.connect(WS_KEY_MAP.spotV3Public)];
}
case 'usdcOption': {
return [this.connect(WS_KEY_MAP.usdcOptionPublic)];
}
case 'usdcPerp': {
return [this.connect(WS_KEY_MAP.usdcPerpPublic)];
}
case 'unifiedOption': {
return [this.connect(WS_KEY_MAP.unifiedOptionPublic)];
}
case 'unifiedPerp': {
return [
this.connect(WS_KEY_MAP.unifiedPerpUSDTPublic),
this.connect(WS_KEY_MAP.unifiedPerpUSDCPublic),
];
}
case 'contractUSDT':
return [this.connect(WS_KEY_MAP.contractUSDTPublic)];
case 'contractInverse':
return [this.connect(WS_KEY_MAP.contractInversePublic)];
case 'v5': {
return [
this.connect(WS_KEY_MAP.v5SpotPublic),
this.connect(WS_KEY_MAP.v5LinearPublic),
this.connect(WS_KEY_MAP.v5InversePublic),
this.connect(WS_KEY_MAP.v5OptionPublic),
];
}
default: {
throw neverGuard(
this.options.market,
'connectPublic(): Unhandled market',
);
}
}
}
public connectPrivate(): Promise<WebSocket | undefined> {
switch (this.options.market) {
case 'inverse': {
return this.connect(WS_KEY_MAP.inverse);
}
case 'linear': {
return this.connect(WS_KEY_MAP.linearPrivate);
}
case 'spot': {
return this.connect(WS_KEY_MAP.spotPrivate);
}
case 'spotv3': {
return this.connect(WS_KEY_MAP.spotV3Private);
}
case 'usdcOption': {
return this.connect(WS_KEY_MAP.usdcOptionPrivate);
}
case 'usdcPerp': {
return this.connect(WS_KEY_MAP.usdcPerpPrivate);
}
case 'unifiedPerp':
case 'unifiedOption': {
return this.connect(WS_KEY_MAP.unifiedPrivate);
}
case 'contractUSDT':
return this.connect(WS_KEY_MAP.contractUSDTPrivate);
case 'contractInverse':
return this.connect(WS_KEY_MAP.contractInversePrivate);
case 'v5': {
return this.connect(WS_KEY_MAP.v5Private);
}
default: {
throw neverGuard(
this.options.market,
'connectPrivate(): Unhandled market',
);
}
}
}
private async connect(wsKey: WsKey): Promise<WebSocket | undefined> {
try {
if (this.wsStore.isWsOpen(wsKey)) {
this.logger.error(
'Refused to connect to ws with existing active connection',
{ ...loggerCategory, wsKey },
);
return this.wsStore.getWs(wsKey);
}
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTING)
) {
this.logger.error(
'Refused to connect to ws, connection attempt already active',
{ ...loggerCategory, wsKey },
);
return;
}
if (
!this.wsStore.getConnectionState(wsKey) ||
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.INITIAL)
) {
this.setWsState(wsKey, WsConnectionStateEnum.CONNECTING);
}
const authParams = await this.getAuthParams(wsKey);
const url = getWsUrl(wsKey, this.options, this.logger);
const ws = this.connectToWsUrl(url + authParams, wsKey);
return this.wsStore.setWs(wsKey, ws);
} catch (err) {
this.parseWsError('Connection failed', err, wsKey);
this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
}
}
private parseWsError(context: string, error: any, wsKey: WsKey) {
if (!error.message) {
this.logger.error(`${context} due to unexpected error: `, error);
this.emit('error', error);
return;
}
switch (error.message) {
case 'Unexpected server response: 401':
this.logger.error(`${context} due to 401 authorization failure.`, {
...loggerCategory,
wsKey,
});
break;
default:
if (
this.wsStore.getConnectionState(wsKey) !==
WsConnectionStateEnum.CLOSING
) {
this.logger.error(
`${context} due to unexpected response error: "${
error?.msg || error?.message || error
}"`,
{ ...loggerCategory, wsKey, error },
);
this.executeReconnectableClose(wsKey, 'unhandled onWsError');
} else {
this.logger.info(
`${wsKey} socket forcefully closed. Will not reconnect.`,
);
}
break;
}
this.emit('error', error);
}
/**
* Return params required to make authorized request
*/
private async getAuthParams(wsKey: WsKey): Promise<string> {
if (PUBLIC_WS_KEYS.includes(wsKey)) {
this.logger.debug('Starting public only websocket client.', {
...loggerCategory,
wsKey,
});
return '';
}
try {
const { signature, expiresAt } = await this.getWsAuthSignature(wsKey);
const authParams = {
api_key: this.options.key,
expires: expiresAt,
signature,
};
return '?' + serializeParams(authParams);
} catch (e) {
this.logger.error(e, { ...loggerCategory, wsKey });
return '';
}
}
private async sendAuthRequest(wsKey: WsKey): Promise<void> {
try {
const { signature, expiresAt } = await this.getWsAuthSignature(wsKey);
const request = {
op: 'auth',
args: [this.options.key, expiresAt, signature],
req_id: `${wsKey}-auth`,
};
return this.tryWsSend(wsKey, JSON.stringify(request));
} catch (e) {
this.logger.error(e, { ...loggerCategory, wsKey });
}
}
private async getWsAuthSignature(
wsKey: WsKey,
): Promise<{ expiresAt: number; signature: string }> {
const { key, secret } = this.options;
if (!key || !secret) {
this.logger.warning(
'Cannot authenticate websocket, either api or private keys missing.',
{ ...loggerCategory, wsKey },
);
throw new Error('Cannot auth - missing api or secret in config');
}
this.logger.debug("Getting auth'd request params", {
...loggerCategory,
wsKey,
});
const timeOffset = this.options.fetchTimeOffsetBeforeAuth
? (await this.restClient?.fetchTimeOffset()) || 0
: 0;
const recvWindow = this.options.recvWindow || 5000;
const signatureExpiresAt = Date.now() + timeOffset + recvWindow;
const signature = await signMessage(
'GET/realtime' + signatureExpiresAt,
secret,
);
return {
expiresAt: signatureExpiresAt,
signature,
};
}
private reconnectWithDelay(wsKey: WsKey, connectionDelayMs: number) {
this.clearTimers(wsKey);
if (
this.wsStore.getConnectionState(wsKey) !==
WsConnectionStateEnum.CONNECTING
) {
this.setWsState(wsKey, WsConnectionStateEnum.RECONNECTING);
}
if (this.wsStore.get(wsKey)?.activeReconnectTimer) {
this.clearReconnectTimer(wsKey);
}
this.wsStore.get(wsKey, true).activeReconnectTimer = setTimeout(() => {
this.logger.info('Reconnecting to websocket', {
...loggerCategory,
wsKey,
});
this.clearReconnectTimer(wsKey);
this.connect(wsKey);
}, connectionDelayMs);
}
private ping(wsKey: WsKey) {
if (this.wsStore.get(wsKey, true).activePongTimer) {
return;
}
this.clearPongTimer(wsKey);
this.logger.silly('Sending ping', { ...loggerCategory, wsKey });
this.tryWsSend(wsKey, JSON.stringify({ op: 'ping' }));
this.wsStore.get(wsKey, true).activePongTimer = setTimeout(
() => this.executeReconnectableClose(wsKey, 'Pong timeout'),
this.options.pongTimeout,
);
}
/**
* Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously.
* If closed, trigger a reconnect immediately
*/
private executeReconnectableClose(wsKey: WsKey, reason: string) {
this.logger.info(`${reason} - closing socket to reconnect`, {
...loggerCategory,
wsKey,
reason,
});
const wasOpen = this.wsStore.isWsOpen(wsKey);
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
const ws = this.getWs(wsKey);
if (ws) {
ws.close();
safeTerminateWs(ws);
}
if (!wasOpen) {
this.logger.info(
`${reason} - socket already closed - trigger immediate reconnect`,
{
...loggerCategory,
wsKey,
reason,
},
);
this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
}
}
private clearTimers(wsKey: WsKey) {
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
this.clearReconnectTimer(wsKey);
}
// Send a ping at intervals
private clearPingTimer(wsKey: WsKey) {
const wsState = this.wsStore.get(wsKey);
if (wsState?.activePingTimer) {
clearInterval(wsState.activePingTimer);
wsState.activePingTimer = undefined;
}
}
// Expect a pong within a time limit
private clearPongTimer(wsKey: WsKey) {
const wsState = this.wsStore.get(wsKey);
if (wsState?.activePongTimer) {
clearTimeout(wsState.activePongTimer);
wsState.activePongTimer = undefined;
}
}
private clearReconnectTimer(wsKey: WsKey) {
const wsState = this.wsStore.get(wsKey);
if (wsState?.activeReconnectTimer) {
clearTimeout(wsState.activeReconnectTimer);
wsState.activeReconnectTimer = undefined;
}
}
/**
* @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics.
*/
private requestSubscribeTopics(wsKey: WsKey, topics: string[]) {
if (!topics.length) {
return;
}
const maxTopicsPerEvent = getMaxTopicsPerSubscribeEvent(
this.options.market,
wsKey,
);
if (maxTopicsPerEvent && topics.length > maxTopicsPerEvent) {
this.logger.silly(
`Subscribing to topics in batches of ${maxTopicsPerEvent}`,
);
for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Subscribing to batch of ${batch.length}`);
this.requestSubscribeTopics(wsKey, batch);
}
this.logger.silly(
`Finished batch subscribing to ${topics.length} topics`,
);
return;
}
const wsMessage = JSON.stringify({
req_id: topics.join(','),
op: 'subscribe',
args: topics,
});
this.tryWsSend(wsKey, wsMessage);
}
/**
* @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
*/
private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) {
if (!topics.length) {
return;
}
const maxTopicsPerEvent = getMaxTopicsPerSubscribeEvent(
this.options.market,
wsKey,
);
if (maxTopicsPerEvent && topics.length > maxTopicsPerEvent) {
this.logger.silly(
`Unsubscribing to topics in batches of ${maxTopicsPerEvent}`,
);
for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Unsubscribing to batch of ${batch.length}`);
this.requestUnsubscribeTopics(wsKey, batch);
}
this.logger.silly(
`Finished batch unsubscribing to ${topics.length} topics`,
);
return;
}
const wsMessage = JSON.stringify({
op: 'unsubscribe',
args: topics,
});
this.tryWsSend(wsKey, wsMessage);
}
public tryWsSend(wsKey: WsKey, wsMessage: string) {
try {
this.logger.silly('Sending upstream ws message: ', {
...loggerCategory,
wsMessage,
wsKey,
});
if (!wsKey) {
throw new Error(
'Cannot send message due to no known websocket for this wsKey',
);
}
const ws = this.getWs(wsKey);
if (!ws) {
throw new Error(
`${wsKey} socket not connected yet, call "connect(${wsKey}) first then try again when the "open" event arrives`,
);
}
ws.send(wsMessage);
} catch (e) {
this.logger.error('Failed to send WS message', {
...loggerCategory,
wsMessage,
wsKey,
exception: e,
});
}
}
private connectToWsUrl(url: string, wsKey: WsKey): WebSocket {
this.logger.silly(`Opening WS connection to URL: ${url}`, {
...loggerCategory,
wsKey,
});
const agent = this.options.requestOptions?.agent;
const ws = new WebSocket(url, undefined, agent ? { agent } : undefined);
ws.onopen = (event) => this.onWsOpen(event, wsKey);
ws.onmessage = (event) => this.onWsMessage(event, wsKey);
ws.onerror = (event) =>
this.parseWsError('Websocket onWsError', event, wsKey);
ws.onclose = (event) => this.onWsClose(event, wsKey);
return ws;
}
private async onWsOpen(event, wsKey: WsKey) {
if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTING)
) {
this.logger.info('Websocket connected', {
...loggerCategory,
wsKey,
testnet: this.isTestnet(),
market: this.options.market,
});
this.emit('open', { wsKey, event });
} else if (
this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.RECONNECTING)
) {
this.logger.info('Websocket reconnected', { ...loggerCategory, wsKey });
this.emit('reconnected', { wsKey, event });
}
this.setWsState(wsKey, WsConnectionStateEnum.CONNECTED);
// Some websockets require an auth packet to be sent after opening the connection