bitget-api 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +85 -140
  2. package/lib/broker-client.d.ts +46 -0
  3. package/lib/broker-client.js +113 -0
  4. package/lib/broker-client.js.map +1 -0
  5. package/lib/constants/enum.d.ts +17 -0
  6. package/lib/constants/enum.js +21 -0
  7. package/lib/constants/enum.js.map +1 -0
  8. package/lib/futures-client.d.ts +146 -0
  9. package/lib/futures-client.js +380 -0
  10. package/lib/futures-client.js.map +1 -0
  11. package/lib/index.d.ts +8 -1
  12. package/lib/index.js +22 -13
  13. package/lib/index.js.map +1 -1
  14. package/lib/spot-client.d.ts +109 -0
  15. package/lib/spot-client.js +201 -0
  16. package/lib/spot-client.js.map +1 -0
  17. package/lib/types/index.d.ts +4 -0
  18. package/lib/types/index.js +21 -0
  19. package/lib/types/index.js.map +1 -0
  20. package/lib/types/request/broker.d.ts +23 -0
  21. package/lib/types/request/broker.js +3 -0
  22. package/lib/types/request/broker.js.map +1 -0
  23. package/lib/types/request/futures.d.ts +114 -0
  24. package/lib/types/request/futures.js +3 -0
  25. package/lib/types/request/futures.js.map +1 -0
  26. package/lib/types/request/index.d.ts +4 -0
  27. package/lib/types/request/index.js +21 -0
  28. package/lib/types/request/index.js.map +1 -0
  29. package/lib/types/request/shared.d.ts +10 -0
  30. package/lib/types/request/shared.js +3 -0
  31. package/lib/types/request/shared.js.map +1 -0
  32. package/lib/types/request/spot.d.ts +19 -0
  33. package/lib/types/request/spot.js +3 -0
  34. package/lib/types/request/spot.js.map +1 -0
  35. package/lib/types/response/futures.d.ts +55 -0
  36. package/lib/types/response/futures.js +3 -0
  37. package/lib/types/response/futures.js.map +1 -0
  38. package/lib/types/response/index.d.ts +3 -0
  39. package/lib/types/response/index.js +20 -0
  40. package/lib/types/response/index.js.map +1 -0
  41. package/lib/types/response/shared.d.ts +6 -0
  42. package/lib/types/response/shared.js +3 -0
  43. package/lib/types/response/shared.js.map +1 -0
  44. package/lib/types/response/spot.d.ts +21 -0
  45. package/lib/types/response/spot.js +3 -0
  46. package/lib/types/response/spot.js.map +1 -0
  47. package/lib/types/shared.d.ts +5 -0
  48. package/lib/types/shared.js +3 -0
  49. package/lib/types/shared.js.map +1 -0
  50. package/lib/types/websockets/client.d.ts +37 -0
  51. package/lib/types/websockets/client.js +3 -0
  52. package/lib/types/websockets/client.js.map +1 -0
  53. package/lib/types/websockets/events.d.ts +75 -0
  54. package/lib/types/websockets/events.js +3 -0
  55. package/lib/types/websockets/events.js.map +1 -0
  56. package/lib/types/websockets/index.d.ts +2 -0
  57. package/lib/types/websockets/index.js +19 -0
  58. package/lib/types/websockets/index.js.map +1 -0
  59. package/lib/util/BaseRestClient.d.ts +40 -0
  60. package/lib/util/BaseRestClient.js +195 -0
  61. package/lib/util/BaseRestClient.js.map +1 -0
  62. package/lib/util/WsStore.d.ts +62 -0
  63. package/lib/util/WsStore.js +135 -0
  64. package/lib/util/WsStore.js.map +1 -0
  65. package/lib/util/browser-support.d.ts +1 -0
  66. package/lib/util/browser-support.js +44 -0
  67. package/lib/util/browser-support.js.map +1 -0
  68. package/lib/util/index.d.ts +6 -0
  69. package/lib/util/index.js +23 -0
  70. package/lib/util/index.js.map +1 -0
  71. package/lib/util/logger.d.ts +9 -0
  72. package/lib/util/logger.js +24 -0
  73. package/lib/util/logger.js.map +1 -0
  74. package/lib/util/node-support.d.ts +2 -0
  75. package/lib/util/node-support.js +33 -0
  76. package/lib/util/node-support.js.map +1 -0
  77. package/lib/util/requestUtils.d.ts +31 -0
  78. package/lib/util/requestUtils.js +53 -0
  79. package/lib/util/requestUtils.js.map +1 -0
  80. package/lib/util/type-guards.d.ts +9 -0
  81. package/lib/util/type-guards.js +50 -0
  82. package/lib/util/type-guards.js.map +1 -0
  83. package/lib/util/websocket-util.d.ts +38 -0
  84. package/lib/util/websocket-util.js +100 -0
  85. package/lib/util/websocket-util.js.map +1 -0
  86. package/lib/websocket-client.d.ts +121 -0
  87. package/lib/websocket-client.js +442 -0
  88. package/lib/websocket-client.js.map +1 -0
  89. package/package.json +16 -16
@@ -0,0 +1,37 @@
1
+ import { WS_KEY_MAP } from '../../util';
2
+ export declare type WsPublicSpotTopic = 'ticker' | 'candle1W' | 'candle1D' | 'candle12H' | 'candle4H' | 'candle1H' | 'candle30m' | 'candle15m' | 'candle5m' | 'candle1m' | 'books' | 'books5' | 'trade';
3
+ export declare type WsPublicFuturesTopic = WsPublicSpotTopic;
4
+ export declare type WsPrivateSpotTopic = 'account' | 'orders';
5
+ export declare type WsPrivateFuturesTopic = 'account' | 'positions' | 'orders' | 'ordersAlgo';
6
+ export declare type WsPublicTopic = WsPublicSpotTopic | WsPublicFuturesTopic;
7
+ export declare type WsPrivateTopic = WsPrivateSpotTopic | WsPrivateFuturesTopic;
8
+ export declare type WsTopic = WsPublicTopic | WsPrivateTopic;
9
+ /** This is used to differentiate between each of the available websocket streams */
10
+ export declare type WsKey = typeof WS_KEY_MAP[keyof typeof WS_KEY_MAP];
11
+ export interface WSClientConfigurableOptions {
12
+ /** Your API key */
13
+ apiKey?: string;
14
+ /** Your API secret */
15
+ apiSecret?: string;
16
+ /** The passphrase you set when creating the API Key (NOT your account password) */
17
+ apiPass?: string;
18
+ /** How often to check if the connection is alive */
19
+ pingInterval?: number;
20
+ /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */
21
+ pongTimeout?: number;
22
+ /** Delay in milliseconds before respawning the connection */
23
+ reconnectTimeout?: number;
24
+ requestOptions?: {
25
+ /** override the user agent when opening the websocket connection (some proxies use this) */
26
+ agent?: string;
27
+ };
28
+ wsUrl?: string;
29
+ /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */
30
+ recvWindow?: number;
31
+ }
32
+ export interface WebsocketClientOptions extends WSClientConfigurableOptions {
33
+ pingInterval: number;
34
+ pongTimeout: number;
35
+ reconnectTimeout: number;
36
+ recvWindow: number;
37
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/types/websockets/client.ts"],"names":[],"mappings":""}
@@ -0,0 +1,75 @@
1
+ export interface WsBaseEvent<TAction = 'snapshot' | string, TData = unknown> {
2
+ action: TAction;
3
+ arg: unknown;
4
+ data: TData[];
5
+ }
6
+ export interface WsSnapshotChannelEvent extends WsBaseEvent<'snapshot'> {
7
+ arg: {
8
+ instType: string;
9
+ channel: string;
10
+ instId: string;
11
+ };
12
+ }
13
+ export interface WsSnapshotAccountEvent extends WsBaseEvent<'snapshot'> {
14
+ arg: {
15
+ instType: string;
16
+ channel: 'account';
17
+ instId: string;
18
+ };
19
+ }
20
+ export interface WsSnapshotPositionsEvent extends WsBaseEvent<'snapshot'> {
21
+ arg: {
22
+ instType: string;
23
+ channel: 'positions';
24
+ instId: string;
25
+ };
26
+ }
27
+ export interface WsAccountSnapshotUMCBL extends WsBaseEvent<'snapshot'> {
28
+ arg: {
29
+ instType: 'umcbl';
30
+ channel: 'account';
31
+ instId: string;
32
+ };
33
+ data: WsAccountSnapshotDataUMCBL[];
34
+ }
35
+ export interface WsAccountSnapshotDataUMCBL {
36
+ marginCoin: string;
37
+ locked: string;
38
+ available: string;
39
+ maxOpenPosAvailable: string;
40
+ maxTransferOut: string;
41
+ equity: string;
42
+ usdtEquity: string;
43
+ }
44
+ export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> {
45
+ arg: {
46
+ instType: 'umcbl';
47
+ channel: 'positions';
48
+ instId: string;
49
+ };
50
+ data: WsPositionSnapshotDataUMCBL[];
51
+ }
52
+ export interface WsPositionSnapshotDataUMCBL {
53
+ posId: string;
54
+ instId: string;
55
+ instName: string;
56
+ marginCoin: string;
57
+ margin: string;
58
+ marginMode: string;
59
+ holdSide: string;
60
+ holdMode: string;
61
+ total: string;
62
+ available: string;
63
+ locked: string;
64
+ averageOpenPrice: string;
65
+ leverage: number;
66
+ achievedProfits: string;
67
+ upl: string;
68
+ uplRate: string;
69
+ liqPx: string;
70
+ keepMarginRate: string;
71
+ marginRate: string;
72
+ cTime: string;
73
+ uTime: string;
74
+ markPrice: string;
75
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/types/websockets/events.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ export * from './client';
2
+ export * from './events';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client"), exports);
18
+ __exportStar(require("./events"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/websockets/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB"}
@@ -0,0 +1,40 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { RestClientType } from '../types';
3
+ import { RestClientOptions } from './requestUtils';
4
+ export default abstract class BaseRestClient {
5
+ private options;
6
+ private baseUrl;
7
+ private globalRequestOptions;
8
+ private apiKey;
9
+ private apiSecret;
10
+ private clientType;
11
+ private apiPass;
12
+ /** Defines the client type (affecting how requests & signatures behave) */
13
+ abstract getClientType(): RestClientType;
14
+ /**
15
+ * Create an instance of the REST client. Pass API credentials in the object in the first parameter.
16
+ * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
17
+ * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
18
+ */
19
+ constructor(restOptions?: RestClientOptions, networkOptions?: AxiosRequestConfig);
20
+ get(endpoint: string, params?: any): Promise<any>;
21
+ getPrivate(endpoint: string, params?: any): Promise<any>;
22
+ post(endpoint: string, params?: any): Promise<any>;
23
+ postPrivate(endpoint: string, params?: any): Promise<any>;
24
+ deletePrivate(endpoint: string, params?: any): Promise<any>;
25
+ /**
26
+ * @private Make a HTTP request to a specific endpoint. Private endpoints are automatically signed.
27
+ */
28
+ private _call;
29
+ /**
30
+ * @private generic handler to parse request exceptions
31
+ */
32
+ parseException(e: any): unknown;
33
+ /**
34
+ * @private sign request and set recv window
35
+ */
36
+ private signRequest;
37
+ private prepareSignParams;
38
+ /** Returns an axios request object. Handles signing process automatically if this is a private API call */
39
+ private buildRequest;
40
+ }
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const axios_1 = __importDefault(require("axios"));
16
+ const node_support_1 = require("./node-support");
17
+ const requestUtils_1 = require("./requestUtils");
18
+ class BaseRestClient {
19
+ /**
20
+ * Create an instance of the REST client. Pass API credentials in the object in the first parameter.
21
+ * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
22
+ * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
23
+ */
24
+ constructor(restOptions = {}, networkOptions = {}) {
25
+ this.clientType = this.getClientType();
26
+ this.options = Object.assign({ recvWindow: 5000,
27
+ /** Throw errors if any request params are empty */
28
+ strictParamValidation: false }, restOptions);
29
+ this.globalRequestOptions = Object.assign(Object.assign({
30
+ // in ms == 5 minutes by default
31
+ timeout: 1000 * 60 * 5 }, networkOptions), { headers: {
32
+ 'X-CHANNEL-CODE': '3tem',
33
+ 'Content-Type': 'application/json',
34
+ locale: 'en-US',
35
+ } });
36
+ this.baseUrl = (0, requestUtils_1.getRestBaseUrl)(false, restOptions);
37
+ this.apiKey = this.options.apiKey;
38
+ this.apiSecret = this.options.apiSecret;
39
+ this.apiPass = this.options.apiPass;
40
+ // Throw if one of the 3 values is missing, but at least one of them is set
41
+ const credentials = [this.apiKey, this.apiSecret, this.apiPass];
42
+ if (credentials.includes(undefined) &&
43
+ credentials.some((v) => typeof v === 'string')) {
44
+ throw new Error('API Key, Secret & Passphrase are ALL required to use the authenticated REST client');
45
+ }
46
+ }
47
+ get(endpoint, params) {
48
+ return this._call('GET', endpoint, params, true);
49
+ }
50
+ getPrivate(endpoint, params) {
51
+ return this._call('GET', endpoint, params, false);
52
+ }
53
+ post(endpoint, params) {
54
+ return this._call('POST', endpoint, params, true);
55
+ }
56
+ postPrivate(endpoint, params) {
57
+ return this._call('POST', endpoint, params, false);
58
+ }
59
+ deletePrivate(endpoint, params) {
60
+ return this._call('DELETE', endpoint, params, false);
61
+ }
62
+ /**
63
+ * @private Make a HTTP request to a specific endpoint. Private endpoints are automatically signed.
64
+ */
65
+ _call(method, endpoint, params, isPublicApi) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ // Sanity check to make sure it's only ever prefixed by one forward slash
68
+ const requestUrl = [this.baseUrl, endpoint].join(endpoint.startsWith('/') ? '' : '/');
69
+ // Build a request and handle signature process
70
+ const options = yield this.buildRequest(method, endpoint, requestUrl, params, isPublicApi);
71
+ // console.log('full request: ', options);
72
+ // Dispatch request
73
+ return (0, axios_1.default)(options)
74
+ .then((response) => {
75
+ var _a, _b;
76
+ // console.log('response: ', response.data);
77
+ // console.error('res: ', response);
78
+ // if (response.data && response.data?.code !== API_ERROR_CODE.SUCCESS) {
79
+ // throw response.data;
80
+ // }
81
+ if (response.status == 200) {
82
+ if (typeof ((_a = response.data) === null || _a === void 0 ? void 0 : _a.code) === 'string' &&
83
+ ((_b = response.data) === null || _b === void 0 ? void 0 : _b.code) !== '00000') {
84
+ throw { response };
85
+ }
86
+ return response.data;
87
+ }
88
+ throw { response };
89
+ })
90
+ .catch((e) => this.parseException(e));
91
+ });
92
+ }
93
+ /**
94
+ * @private generic handler to parse request exceptions
95
+ */
96
+ parseException(e) {
97
+ if (this.options.parseExceptions === false) {
98
+ throw e;
99
+ }
100
+ // Something happened in setting up the request that triggered an Error
101
+ if (!e.response) {
102
+ if (!e.request) {
103
+ throw e.message;
104
+ }
105
+ // request made but no response received
106
+ throw e;
107
+ }
108
+ // The request was made and the server responded with a status code
109
+ // that falls out of the range of 2xx
110
+ const response = e.response;
111
+ // console.error('err: ', response?.data);
112
+ throw {
113
+ code: response.status,
114
+ message: response.statusText,
115
+ body: response.data,
116
+ headers: response.headers,
117
+ requestOptions: Object.assign(Object.assign({}, this.options), { apiPass: 'omittedFromError', apiSecret: 'omittedFromError' }),
118
+ };
119
+ }
120
+ /**
121
+ * @private sign request and set recv window
122
+ */
123
+ signRequest(data, endpoint, method, signMethod) {
124
+ return __awaiter(this, void 0, void 0, function* () {
125
+ const timestamp = Date.now();
126
+ const res = {
127
+ originalParams: Object.assign({}, data),
128
+ sign: '',
129
+ timestamp,
130
+ recvWindow: 0,
131
+ serializedParams: '',
132
+ queryParamsWithSign: '',
133
+ };
134
+ if (!this.apiKey || !this.apiSecret) {
135
+ return res;
136
+ }
137
+ // It's possible to override the recv window on a per rquest level
138
+ const strictParamValidation = this.options.strictParamValidation;
139
+ if (signMethod === 'bitget') {
140
+ const signRequestParams = method === 'GET'
141
+ ? (0, requestUtils_1.serializeParams)(data, strictParamValidation, '?')
142
+ : JSON.stringify(data) || '';
143
+ const paramsStr = timestamp + method.toUpperCase() + endpoint + signRequestParams;
144
+ // console.log('sign params: ', paramsStr);
145
+ res.sign = yield (0, node_support_1.signMessage)(paramsStr, this.apiSecret, 'base64');
146
+ res.queryParamsWithSign = signRequestParams;
147
+ return res;
148
+ }
149
+ return res;
150
+ });
151
+ }
152
+ prepareSignParams(method, endpoint, signMethod, params, isPublicApi) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ if (isPublicApi) {
155
+ return {
156
+ originalParams: params,
157
+ paramsWithSign: params,
158
+ };
159
+ }
160
+ if (!this.apiKey || !this.apiSecret) {
161
+ throw new Error('Private endpoints require api and private keys set');
162
+ }
163
+ return this.signRequest(params, endpoint, method, signMethod);
164
+ });
165
+ }
166
+ /** Returns an axios request object. Handles signing process automatically if this is a private API call */
167
+ buildRequest(method, endpoint, url, params, isPublicApi) {
168
+ return __awaiter(this, void 0, void 0, function* () {
169
+ const options = Object.assign(Object.assign({}, this.globalRequestOptions), { url: url, method: method });
170
+ for (const key in params) {
171
+ if (typeof params[key] === 'undefined') {
172
+ delete params[key];
173
+ }
174
+ }
175
+ if (isPublicApi || !this.apiKey || !this.apiPass) {
176
+ return Object.assign(Object.assign({}, options), { params: params });
177
+ }
178
+ const signResult = yield this.prepareSignParams(method, endpoint, 'bitget', params, isPublicApi);
179
+ if (!options.headers) {
180
+ options.headers = {};
181
+ }
182
+ options.headers['ACCESS-KEY'] = this.apiKey;
183
+ options.headers['ACCESS-PASSPHRASE'] = this.apiPass;
184
+ options.headers['ACCESS-TIMESTAMP'] = signResult.timestamp;
185
+ options.headers['ACCESS-SIGN'] = signResult.sign;
186
+ options.headers['Content-Type'] = 'application/json';
187
+ if (method === 'GET') {
188
+ return Object.assign(Object.assign({}, options), { url: options.url + signResult.queryParamsWithSign });
189
+ }
190
+ return Object.assign(Object.assign({}, options), { data: params });
191
+ });
192
+ }
193
+ }
194
+ exports.default = BaseRestClient;
195
+ //# sourceMappingURL=BaseRestClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseRestClient.js","sourceRoot":"","sources":["../../src/util/BaseRestClient.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,kDAAyE;AAIzE,iDAA6C;AAC7C,iDAIwB;AA2CxB,MAA8B,cAAc;IAY1C;;;;OAIG;IACH,YACE,cAAiC,EAAE,EACnC,iBAAqC,EAAE;QAEvC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAEvC,IAAI,CAAC,OAAO,mBACV,UAAU,EAAE,IAAI;YAChB,mDAAmD;YACnD,qBAAqB,EAAE,KAAK,IACzB,WAAW,CACf,CAAC;QAEF,IAAI,CAAC,oBAAoB;YACvB,gCAAgC;YAChC,OAAO,EAAE,IAAI,GAAG,EAAE,GAAG,CAAC,IAEnB,cAAc,KACjB,OAAO,EAAE;gBACP,gBAAgB,EAAE,MAAM;gBACxB,cAAc,EAAE,kBAAkB;gBAClC,MAAM,EAAE,OAAO;aAChB,GACF,CAAC;QAEF,IAAI,CAAC,OAAO,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QAClD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;QAClC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,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AAC,OAAO,EAAE;gBACpB,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC;aACtB;YACD,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;YAC5C,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;YACpD,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,UAAU,CAAC,SAAS,CAAC;YAC3D,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC;YACjD,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;YAErD,IAAI,MAAM,KAAK,KAAK,EAAE;gBACpB,uCACK,OAAO,KACV,GAAG,EAAE,OAAO,CAAC,GAAG,GAAG,UAAU,CAAC,mBAAmB,IACjD;aACH;YAED,uCACK,OAAO,KACV,IAAI,EAAE,MAAM,IACZ;QACJ,CAAC;KAAA;CACF;AA7SD,iCA6SC"}
@@ -0,0 +1,62 @@
1
+ import WebSocket from 'isomorphic-ws';
2
+ import { WsTopic } from '../types';
3
+ import { DefaultLogger } from './logger';
4
+ export declare enum WsConnectionStateEnum {
5
+ INITIAL = 0,
6
+ CONNECTING = 1,
7
+ CONNECTED = 2,
8
+ CLOSING = 3,
9
+ RECONNECTING = 4
10
+ }
11
+ /** A "topic" is always a string */
12
+ export declare type BitgetInstType = 'SP' | 'SPBL' | 'MC' | 'UMCBL' | 'DMCBL';
13
+ export interface WsTopicSubscribeEventArgs {
14
+ instType: BitgetInstType;
15
+ channel: WsTopic;
16
+ /** The symbol, e.g. "BTCUSDT" */
17
+ instId: string;
18
+ }
19
+ declare type WsTopicList = Set<WsTopicSubscribeEventArgs>;
20
+ interface WsStoredState {
21
+ /** The currently active websocket connection */
22
+ ws?: WebSocket;
23
+ /** The current lifecycle state of the connection (enum) */
24
+ connectionState?: WsConnectionStateEnum;
25
+ /** A timer that will send an upstream heartbeat (ping) when it expires */
26
+ activePingTimer?: ReturnType<typeof setTimeout> | undefined;
27
+ /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
28
+ activePongTimer?: ReturnType<typeof setTimeout> | undefined;
29
+ /** If a reconnection is in progress, this will have the timer for the delayed reconnect */
30
+ activeReconnectTimer?: ReturnType<typeof setTimeout> | undefined;
31
+ /**
32
+ * All the topics we are expected to be subscribed to (and we automatically resubscribe to if the connection drops)
33
+ *
34
+ * A "Set" and a deep object match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
35
+ */
36
+ subscribedTopics: WsTopicList;
37
+ isAuthenticated?: boolean;
38
+ }
39
+ export default class WsStore<WsKey extends string> {
40
+ private wsState;
41
+ private logger;
42
+ constructor(logger: typeof DefaultLogger);
43
+ /** Get WS stored state for key, optionally create if missing */
44
+ get(key: WsKey, createIfMissing?: true): WsStoredState;
45
+ get(key: WsKey, createIfMissing?: false): WsStoredState | undefined;
46
+ getKeys(): WsKey[];
47
+ create(key: WsKey): WsStoredState | undefined;
48
+ delete(key: WsKey): void;
49
+ hasExistingActiveConnection(key: WsKey): boolean;
50
+ getWs(key: WsKey): WebSocket | undefined;
51
+ setWs(key: WsKey, wsConnection: WebSocket): WebSocket;
52
+ isWsOpen(key: WsKey): boolean;
53
+ getConnectionState(key: WsKey): WsConnectionStateEnum;
54
+ setConnectionState(key: WsKey, state: WsConnectionStateEnum): void;
55
+ isConnectionState(key: WsKey, state: WsConnectionStateEnum): boolean;
56
+ getTopics(key: WsKey): WsTopicList;
57
+ getTopicsByKey(): Record<string, WsTopicList>;
58
+ getMatchingTopic(key: WsKey, topic: WsTopicSubscribeEventArgs): WsTopicSubscribeEventArgs | undefined;
59
+ addTopic(key: WsKey, topic: WsTopicSubscribeEventArgs): WsTopicList;
60
+ deleteTopic(key: WsKey, topic: WsTopicSubscribeEventArgs): WsTopicList;
61
+ }
62
+ export {};
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WsConnectionStateEnum = void 0;
4
+ const logger_1 = require("./logger");
5
+ var WsConnectionStateEnum;
6
+ (function (WsConnectionStateEnum) {
7
+ WsConnectionStateEnum[WsConnectionStateEnum["INITIAL"] = 0] = "INITIAL";
8
+ WsConnectionStateEnum[WsConnectionStateEnum["CONNECTING"] = 1] = "CONNECTING";
9
+ WsConnectionStateEnum[WsConnectionStateEnum["CONNECTED"] = 2] = "CONNECTED";
10
+ WsConnectionStateEnum[WsConnectionStateEnum["CLOSING"] = 3] = "CLOSING";
11
+ WsConnectionStateEnum[WsConnectionStateEnum["RECONNECTING"] = 4] = "RECONNECTING";
12
+ // ERROR = 5,
13
+ })(WsConnectionStateEnum = exports.WsConnectionStateEnum || (exports.WsConnectionStateEnum = {}));
14
+ function isDeepObjectMatch(object1, object2) {
15
+ for (const key in object1) {
16
+ if (object1[key] !== object2[key]) {
17
+ return false;
18
+ }
19
+ }
20
+ return true;
21
+ }
22
+ class WsStore {
23
+ constructor(logger) {
24
+ this.wsState = {};
25
+ this.logger = logger || logger_1.DefaultLogger;
26
+ }
27
+ get(key, createIfMissing) {
28
+ if (this.wsState[key]) {
29
+ return this.wsState[key];
30
+ }
31
+ if (createIfMissing) {
32
+ return this.create(key);
33
+ }
34
+ }
35
+ getKeys() {
36
+ return Object.keys(this.wsState);
37
+ }
38
+ create(key) {
39
+ if (this.hasExistingActiveConnection(key)) {
40
+ this.logger.warning('WsStore setConnection() overwriting existing open connection: ', this.getWs(key));
41
+ }
42
+ this.wsState[key] = {
43
+ subscribedTopics: new Set(),
44
+ connectionState: WsConnectionStateEnum.INITIAL,
45
+ };
46
+ return this.get(key);
47
+ }
48
+ delete(key) {
49
+ // TODO: should we allow this at all? Perhaps block this from happening...
50
+ if (this.hasExistingActiveConnection(key)) {
51
+ const ws = this.getWs(key);
52
+ this.logger.warning('WsStore deleting state for connection still open: ', ws);
53
+ ws === null || ws === void 0 ? void 0 : ws.close();
54
+ }
55
+ delete this.wsState[key];
56
+ }
57
+ /* connection websocket */
58
+ hasExistingActiveConnection(key) {
59
+ return this.get(key) && this.isWsOpen(key);
60
+ }
61
+ getWs(key) {
62
+ var _a;
63
+ return (_a = this.get(key)) === null || _a === void 0 ? void 0 : _a.ws;
64
+ }
65
+ setWs(key, wsConnection) {
66
+ if (this.isWsOpen(key)) {
67
+ this.logger.warning('WsStore setConnection() overwriting existing open connection: ', this.getWs(key));
68
+ }
69
+ this.get(key, true).ws = wsConnection;
70
+ return wsConnection;
71
+ }
72
+ /* connection state */
73
+ isWsOpen(key) {
74
+ const existingConnection = this.getWs(key);
75
+ return (!!existingConnection &&
76
+ existingConnection.readyState === existingConnection.OPEN);
77
+ }
78
+ getConnectionState(key) {
79
+ return this.get(key, true).connectionState;
80
+ }
81
+ setConnectionState(key, state) {
82
+ this.get(key, true).connectionState = state;
83
+ }
84
+ isConnectionState(key, state) {
85
+ return this.getConnectionState(key) === state;
86
+ }
87
+ /* subscribed topics */
88
+ getTopics(key) {
89
+ return this.get(key, true).subscribedTopics;
90
+ }
91
+ getTopicsByKey() {
92
+ const result = {};
93
+ for (const refKey in this.wsState) {
94
+ result[refKey] = this.getTopics(refKey);
95
+ }
96
+ return result;
97
+ }
98
+ // Since topics are objects we can't rely on the set to detect duplicates
99
+ getMatchingTopic(key, topic) {
100
+ // if (typeof topic === 'string') {
101
+ // return this.getMatchingTopic(key, { channel: topic });
102
+ // }
103
+ const allTopics = this.getTopics(key).values();
104
+ for (const storedTopic of allTopics) {
105
+ if (isDeepObjectMatch(topic, storedTopic)) {
106
+ return storedTopic;
107
+ }
108
+ }
109
+ }
110
+ addTopic(key, topic) {
111
+ // if (typeof topic === 'string') {
112
+ // return this.addTopic(key, {
113
+ // instType: 'sp',
114
+ // channel: topic,
115
+ // instId: 'default',
116
+ // };
117
+ // }
118
+ // Check for duplicate topic. If already tracked, don't store this one
119
+ const existingTopic = this.getMatchingTopic(key, topic);
120
+ if (existingTopic) {
121
+ return this.getTopics(key);
122
+ }
123
+ return this.getTopics(key).add(topic);
124
+ }
125
+ deleteTopic(key, topic) {
126
+ // Check if we're subscribed to a topic like this
127
+ const storedTopic = this.getMatchingTopic(key, topic);
128
+ if (storedTopic) {
129
+ this.getTopics(key).delete(storedTopic);
130
+ }
131
+ return this.getTopics(key);
132
+ }
133
+ }
134
+ exports.default = WsStore;
135
+ //# sourceMappingURL=WsStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WsStore.js","sourceRoot":"","sources":["../../src/util/WsStore.ts"],"names":[],"mappings":";;;AAEA,qCAAyC;AAEzC,IAAY,qBAOX;AAPD,WAAY,qBAAqB;IAC/B,uEAAW,CAAA;IACX,6EAAc,CAAA;IACd,2EAAa,CAAA;IACb,uEAAW,CAAA;IACX,iFAAgB,CAAA;IAChB,aAAa;AACf,CAAC,EAPW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAOhC;AAmCD,SAAS,iBAAiB,CAAC,OAAY,EAAE,OAAY;IACnD,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;QACzB,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE;YACjC,OAAO,KAAK,CAAC;SACd;KACF;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAqB,OAAO;IAI1B,YAAY,MAA4B;QAHhC,YAAO,GAAkC,EAAE,CAAC;QAIlD,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,sBAAa,CAAC;IACxC,CAAC;IAKD,GAAG,CAAC,GAAU,EAAE,eAAyB;QACvC,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YACrB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;SAC1B;QAED,IAAI,eAAe,EAAE;YACnB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;SACzB;IACH,CAAC;IAED,OAAO;QACL,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAA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AAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QAC/C,KAAK,MAAM,WAAW,IAAI,SAAS,EAAE;YACnC,IAAI,iBAAiB,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE;gBACzC,OAAO,WAAW,CAAC;aACpB;SACF;IACH,CAAC;IAED,QAAQ,CAAC,GAAU,EAAE,KAAgC;QACnD,mCAAmC;QACnC,gCAAgC;QAChC,sBAAsB;QACtB,sBAAsB;QACtB,yBAAyB;QACzB,OAAO;QACP,IAAI;QACJ,sEAAsE;QACtE,MAAM,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACxD,IAAI,aAAa,EAAE;YACjB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;SAC5B;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;IAED,WAAW,CAAC,GAAU,EAAE,KAAgC;QACtD,iDAAiD;QACjD,MAAM,WAAW,GAAG,IAAI,CAAC,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtD,IAAI,WAAW,EAAE;YACf,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;SACzC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;CACF;AArJD,0BAqJC"}
@@ -0,0 +1 @@
1
+ export declare function signMessage(message: string, secret: string, method: 'hex' | 'base64'): Promise<string>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.signMessage = void 0;
13
+ function _arrayBufferToBase64(buffer) {
14
+ let binary = '';
15
+ const bytes = new Uint8Array(buffer);
16
+ const len = bytes.byteLength;
17
+ for (let i = 0; i < len; i++) {
18
+ binary += String.fromCharCode(bytes[i]);
19
+ }
20
+ return window.btoa(binary);
21
+ }
22
+ function signMessage(message, secret, method) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ const encoder = new TextEncoder();
25
+ const key = yield window.crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);
26
+ const signature = yield window.crypto.subtle.sign('HMAC', key, encoder.encode(message));
27
+ switch (method) {
28
+ case 'hex': {
29
+ return Array.prototype.map
30
+ .call(new Uint8Array(signature), (x) => ('00' + x.toString(16)).slice(-2))
31
+ .join('');
32
+ }
33
+ case 'base64': {
34
+ return _arrayBufferToBase64(signature);
35
+ }
36
+ default: {
37
+ ((x) => { })(method);
38
+ throw new Error(`Unhandled sign method: ${method}`);
39
+ }
40
+ }
41
+ });
42
+ }
43
+ exports.signMessage = signMessage;
44
+ //# sourceMappingURL=browser-support.js.map