@orderly.network/net 1.0.1

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.
@@ -0,0 +1,22 @@
1
+
2
+ > @orderly.network/net@1.0.0 build /Users/leo/orderly/orderly-web/packages/net
3
+ > tsup
4
+
5
+ CLI Building entry: src/index.ts
6
+ CLI Using tsconfig: tsconfig.json
7
+ CLI tsup v7.1.0
8
+ CLI Using tsup config: /Users/leo/orderly/orderly-web/packages/net/tsup.config.ts
9
+ CLI Target: es6
10
+ CLI Cleaning output folder
11
+ CJS Build start
12
+ ESM Build start
13
+ ESM dist/index.mjs 10.09 KB
14
+ ESM dist/index.mjs.map 16.58 KB
15
+ ESM ⚡️ Build success in 11ms
16
+ CJS dist/index.js 11.13 KB
17
+ CJS dist/index.js.map 16.80 KB
18
+ CJS ⚡️ Build success in 11ms
19
+ DTS Build start
20
+ DTS ⚡️ Build success in 545ms
21
+ DTS dist/index.d.ts 1.16 KB
22
+ DTS dist/index.d.mts 1.16 KB
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @orderly.network/net
2
+
3
+ ## 1.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - first publish
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ futures-dev 环境信息:
2
+ api url:https://futures-api.orderly.network
3
+ website:https://futures-dex.woo.org
@@ -0,0 +1,11 @@
1
+ import WebSocketClient from "../src/ws";
2
+
3
+ describe("createWebSocket", () => {
4
+ let ws;
5
+
6
+ beforeAll(() => {
7
+ ws = new WebSocketClient({ url: "ws://localhost:8080" });
8
+ });
9
+
10
+ test("should create a websocket", () => {});
11
+ });
@@ -0,0 +1,13 @@
1
+ import { get } from "../src";
2
+
3
+ test("get function", async () => {
4
+ const res = await get("https://testnet-api.orderly.org/v1/public/info");
5
+ const data = await res.json();
6
+ console.log(data)
7
+ // expect(res).toEqual({
8
+ // completed: false,
9
+ // id: 1,
10
+ // title: "delectus aut autem",
11
+ // userId: 1,
12
+ // });
13
+ });
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ presets: [
3
+ ["@babel/preset-env", { targets: { node: "current" } }],
4
+ "@babel/preset-typescript",
5
+ ],
6
+ };
@@ -0,0 +1,37 @@
1
+ import { Observable } from 'rxjs';
2
+
3
+ declare function get<R>(url: string, options?: RequestInit, formatter?: (data: any) => R): Promise<R>;
4
+ declare function post(url: string, data: any, options?: Omit<RequestInit, "method">): Promise<any>;
5
+
6
+ type NetworkId = "testnet" | "mainnet";
7
+ type WSOptions = {
8
+ url?: string;
9
+ networkId?: NetworkId;
10
+ accountId?: string;
11
+ onSigntureRequest?: (accountId: string) => Promise<any>;
12
+ };
13
+ declare class WebSocketClient {
14
+ private static __topicRefCountMap;
15
+ private wsSubject;
16
+ private privateWsSubject?;
17
+ private authenticated;
18
+ private _pendingPrivateSubscribe;
19
+ constructor(options: WSOptions);
20
+ private createSubject;
21
+ private createPrivateSubject;
22
+ private bindSubscribe;
23
+ private authenticate;
24
+ send: (message: any) => void;
25
+ privateSend: (message: any) => void;
26
+ get isAuthed(): boolean;
27
+ observe<T>(params: any, unsubscribe?: () => any, messageFilter?: (value: T) => boolean): Observable<T>;
28
+ privateObserve<T>(params: any, unsubscribe?: () => any, messageFilter?: (value: T) => boolean): Observable<T>;
29
+ private _observe;
30
+ private generateMessage;
31
+ private _sendPendingPrivateMessage;
32
+ desotry(): void;
33
+ }
34
+
35
+ declare const __ORDERLY_API_URL_KEY__: string;
36
+
37
+ export { WebSocketClient, __ORDERLY_API_URL_KEY__, get, post };
@@ -0,0 +1,37 @@
1
+ import { Observable } from 'rxjs';
2
+
3
+ declare function get<R>(url: string, options?: RequestInit, formatter?: (data: any) => R): Promise<R>;
4
+ declare function post(url: string, data: any, options?: Omit<RequestInit, "method">): Promise<any>;
5
+
6
+ type NetworkId = "testnet" | "mainnet";
7
+ type WSOptions = {
8
+ url?: string;
9
+ networkId?: NetworkId;
10
+ accountId?: string;
11
+ onSigntureRequest?: (accountId: string) => Promise<any>;
12
+ };
13
+ declare class WebSocketClient {
14
+ private static __topicRefCountMap;
15
+ private wsSubject;
16
+ private privateWsSubject?;
17
+ private authenticated;
18
+ private _pendingPrivateSubscribe;
19
+ constructor(options: WSOptions);
20
+ private createSubject;
21
+ private createPrivateSubject;
22
+ private bindSubscribe;
23
+ private authenticate;
24
+ send: (message: any) => void;
25
+ privateSend: (message: any) => void;
26
+ get isAuthed(): boolean;
27
+ observe<T>(params: any, unsubscribe?: () => any, messageFilter?: (value: T) => boolean): Observable<T>;
28
+ privateObserve<T>(params: any, unsubscribe?: () => any, messageFilter?: (value: T) => boolean): Observable<T>;
29
+ private _observe;
30
+ private generateMessage;
31
+ private _sendPendingPrivateMessage;
32
+ desotry(): void;
33
+ }
34
+
35
+ declare const __ORDERLY_API_URL_KEY__: string;
36
+
37
+ export { WebSocketClient, __ORDERLY_API_URL_KEY__, get, post };
package/dist/index.js ADDED
@@ -0,0 +1,410 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+ var __async = (__this, __arguments, generator) => {
37
+ return new Promise((resolve, reject) => {
38
+ var fulfilled = (value) => {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var rejected = (value) => {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
+ step((generator = generator.apply(__this, __arguments)).next());
54
+ });
55
+ };
56
+
57
+ // src/index.ts
58
+ var src_exports = {};
59
+ __export(src_exports, {
60
+ WebSocketClient: () => ws_default,
61
+ __ORDERLY_API_URL_KEY__: () => __ORDERLY_API_URL_KEY__,
62
+ get: () => get,
63
+ post: () => post
64
+ });
65
+ module.exports = __toCommonJS(src_exports);
66
+
67
+ // src/fetch/index.ts
68
+ function request(url, options) {
69
+ return __async(this, null, function* () {
70
+ if (!url.startsWith("http")) {
71
+ throw new Error("url must start with http(s)");
72
+ }
73
+ const urlInstance = new URL(url);
74
+ const response = yield fetch(urlInstance, __spreadProps(__spreadValues({}, options), {
75
+ // mode: "cors",
76
+ // credentials: "include",
77
+ headers: _createHeaders(options.headers)
78
+ })).catch((err) => {
79
+ throw new Error(err);
80
+ });
81
+ if (response.ok) {
82
+ return response.json();
83
+ }
84
+ throw new Error(response.statusText);
85
+ });
86
+ }
87
+ function _createHeaders(headers = {}) {
88
+ const _headers = new Headers(headers);
89
+ if (!_headers.has("Content-Type")) {
90
+ _headers.append("Content-Type", "application/json;charset=utf-8");
91
+ }
92
+ return _headers;
93
+ }
94
+ function get(url, options, formatter) {
95
+ return __async(this, null, function* () {
96
+ const res = yield request(url, __spreadValues({
97
+ method: "GET"
98
+ }, options));
99
+ if (res.success) {
100
+ if (typeof formatter === "function") {
101
+ return formatter(res.data);
102
+ }
103
+ if (Array.isArray(res.data["rows"])) {
104
+ return res.data["rows"];
105
+ }
106
+ return res.data;
107
+ }
108
+ throw new Error(res.message);
109
+ });
110
+ }
111
+ function post(url, data, options) {
112
+ return __async(this, null, function* () {
113
+ const res = yield request(url, __spreadValues({
114
+ method: "POST",
115
+ body: JSON.stringify(data)
116
+ }, options));
117
+ return res;
118
+ });
119
+ }
120
+
121
+ // src/ws/index.ts
122
+ var import_webSocket = require("rxjs/webSocket");
123
+
124
+ // src/ws/contants.ts
125
+ var WS_URL = {
126
+ testnet: {
127
+ // public: "wss://testnet-ws.orderly.org/ws/stream/",
128
+ public: "wss://dev-ws-v2.orderly.org/ws/stream/",
129
+ // private:
130
+ // "wss://dev-ws-private-v2.orderly.org/wsprivate/v2/ws/private/stream/",
131
+ private: "wss://dev-ws-private-v2.orderly.org/v2/ws/private/stream/"
132
+ },
133
+ mainnet: {
134
+ public: "wss://mainnet-ws.orderly.io",
135
+ private: "wss://mainnet-ws.orderly.io"
136
+ }
137
+ };
138
+
139
+ // src/ws/index.ts
140
+ var import_rxjs = require("rxjs");
141
+
142
+ // src/ws/handler/baseHandler.ts
143
+ var BaseHandler = class {
144
+ // constructor(readonly wsSubject: WebSocketSubject<any>) {}
145
+ handle(message, send) {
146
+ throw new Error("Method not implemented.");
147
+ }
148
+ };
149
+
150
+ // src/ws/handler/ping.ts
151
+ var PingHandler = class extends BaseHandler {
152
+ handle(_, send) {
153
+ send({ event: "pong", ts: Date.now() });
154
+ }
155
+ };
156
+
157
+ // src/ws/handler/handler.ts
158
+ var messageHandlers = /* @__PURE__ */ new Map([
159
+ ["ping", new PingHandler()]
160
+ ]);
161
+
162
+ // src/ws/index.ts
163
+ var _WebSocketClient = class _WebSocketClient {
164
+ constructor(options) {
165
+ this.authenticated = false;
166
+ this._pendingPrivateSubscribe = [];
167
+ this.send = (message) => {
168
+ this.wsSubject.next(message);
169
+ };
170
+ this.privateSend = (message) => {
171
+ if (!this.privateWsSubject) {
172
+ console.warn("private ws not connected");
173
+ return;
174
+ }
175
+ this.privateWsSubject.next(message);
176
+ };
177
+ this.wsSubject = this.createSubject(options);
178
+ if (!!options.accountId) {
179
+ this.privateWsSubject = this.createPrivateSubject(options);
180
+ }
181
+ this.bindSubscribe();
182
+ }
183
+ createSubject(options) {
184
+ let url;
185
+ if (typeof options.url === "string") {
186
+ url = options.url;
187
+ } else {
188
+ url = WS_URL[options.networkId || "testnet"].public;
189
+ }
190
+ return (0, import_webSocket.webSocket)({
191
+ url: `${url}${options.accountId || ""}`,
192
+ openObserver: {
193
+ next: () => {
194
+ console.log("Connection ok");
195
+ }
196
+ },
197
+ closeObserver: {
198
+ next: () => {
199
+ console.log("Connection closed");
200
+ }
201
+ }
202
+ });
203
+ }
204
+ createPrivateSubject(options) {
205
+ const url = WS_URL[options.networkId || "testnet"].private;
206
+ const ws = (0, import_webSocket.webSocket)({
207
+ url: `${url}${options.accountId}`,
208
+ openObserver: {
209
+ next: () => {
210
+ var _a;
211
+ console.log("Private connection ok");
212
+ if (this.authenticated || !options.accountId)
213
+ return;
214
+ (_a = options.onSigntureRequest) == null ? void 0 : _a.call(options, options.accountId).then((signature) => {
215
+ this.authenticate(options.accountId, signature);
216
+ });
217
+ }
218
+ },
219
+ closeObserver: {
220
+ next: () => {
221
+ console.log("Private connection closed");
222
+ this.authenticated = false;
223
+ }
224
+ }
225
+ });
226
+ return ws;
227
+ }
228
+ bindSubscribe() {
229
+ this.wsSubject.subscribe({
230
+ next: (message) => {
231
+ const handler = messageHandlers.get(message.event);
232
+ if (handler) {
233
+ handler.handle(message, this.send);
234
+ }
235
+ },
236
+ error(err) {
237
+ console.log("WS Error: ", err);
238
+ },
239
+ complete() {
240
+ console.log("WS Connection closed");
241
+ }
242
+ });
243
+ if (!this.privateWsSubject)
244
+ return;
245
+ this.privateWsSubject.subscribe({
246
+ next: (message) => {
247
+ if (message.event === "auth") {
248
+ this.authenticated = true;
249
+ this._sendPendingPrivateMessage();
250
+ return;
251
+ }
252
+ const handler = messageHandlers.get(message.event);
253
+ if (handler) {
254
+ handler.handle(message, this.privateSend);
255
+ }
256
+ },
257
+ error(err) {
258
+ console.log("WS Error: ", err);
259
+ },
260
+ complete() {
261
+ console.log("WS Connection closed");
262
+ }
263
+ });
264
+ }
265
+ authenticate(accountId, message) {
266
+ var _a;
267
+ if (this.authenticated)
268
+ return;
269
+ if (!this.privateWsSubject) {
270
+ console.error("private ws not connected");
271
+ return;
272
+ }
273
+ console.log("push auth message:", message);
274
+ (_a = this.privateWsSubject) == null ? void 0 : _a.next({
275
+ id: "auth",
276
+ event: "auth",
277
+ params: {
278
+ orderly_key: message.publicKey,
279
+ sign: message.signature,
280
+ timestamp: message.timestamp
281
+ }
282
+ });
283
+ }
284
+ get isAuthed() {
285
+ return this.authenticated;
286
+ }
287
+ // observe<T>(topic: string): Observable<T>;
288
+ // observe<T>(topic: string, unsubscribe?: () => any): Observable<T>;
289
+ // observe<T>(
290
+ // params: {
291
+ // event: string;
292
+ // } & Record<string, any>,
293
+ // unsubscribe?: () => any
294
+ // ): Observable<T>;
295
+ observe(params, unsubscribe, messageFilter) {
296
+ return this._observe(false, params, unsubscribe, messageFilter);
297
+ }
298
+ // privateObserve<T>(topic: string): Observable<T>;
299
+ // privateObserve<T>(topic: string, unsubscribe?: () => any): Observable<T>;
300
+ // privateObserve<T>(
301
+ // params: {
302
+ // event: string;
303
+ // } & Record<string, any>,
304
+ // unsubscribe?: () => any
305
+ // ): Observable<T>;
306
+ privateObserve(params, unsubscribe, messageFilter) {
307
+ return this._observe(true, params, unsubscribe, messageFilter);
308
+ }
309
+ _observe(isPrivate, params, unsubscribe, messageFilter) {
310
+ if (isPrivate && !this.privateWsSubject) {
311
+ throw new Error("private ws not connected");
312
+ }
313
+ const subject = isPrivate ? this.privateWsSubject : this.wsSubject;
314
+ const sendFunc = isPrivate ? this.privateSend : this.send;
315
+ const [subscribeMessage, unsubscribeMessage, filter, messageFormatter] = this.generateMessage(params, unsubscribe, messageFilter);
316
+ return new import_rxjs.Observable((observer) => {
317
+ if (isPrivate && !this.authenticated) {
318
+ this._pendingPrivateSubscribe.push(params);
319
+ return;
320
+ }
321
+ try {
322
+ const refCount = _WebSocketClient.__topicRefCountMap.get(subscribeMessage.topic) || 0;
323
+ if (refCount === 0) {
324
+ sendFunc(subscribeMessage);
325
+ _WebSocketClient.__topicRefCountMap.set(
326
+ subscribeMessage.topic,
327
+ refCount + 1
328
+ );
329
+ }
330
+ } catch (err) {
331
+ observer.error(err);
332
+ }
333
+ const subscription = subject.subscribe({
334
+ next: (x) => {
335
+ try {
336
+ if (filter(x)) {
337
+ observer.next(messageFormatter(x));
338
+ }
339
+ } catch (err) {
340
+ observer.error(err);
341
+ }
342
+ },
343
+ error: (err) => observer.error(err),
344
+ complete: () => observer.complete()
345
+ });
346
+ return () => {
347
+ try {
348
+ const refCount = _WebSocketClient.__topicRefCountMap.get(subscribeMessage.topic) || 0;
349
+ if (refCount > 1) {
350
+ _WebSocketClient.__topicRefCountMap.set(
351
+ subscribeMessage.topic,
352
+ refCount - 1
353
+ );
354
+ return;
355
+ }
356
+ if (!!unsubscribeMessage) {
357
+ this.send(unsubscribeMessage);
358
+ }
359
+ _WebSocketClient.__topicRefCountMap.delete(subscribeMessage.topic);
360
+ } catch (err) {
361
+ observer.error(err);
362
+ }
363
+ subscription.unsubscribe();
364
+ };
365
+ });
366
+ }
367
+ generateMessage(params, unsubscribe, messageFilter) {
368
+ let subscribeMessage, unsubscribeMessage;
369
+ let filter, messageFormatter = (message) => message.data;
370
+ if (typeof params === "string") {
371
+ subscribeMessage = { event: "subscribe", topic: params };
372
+ unsubscribeMessage = { event: "unsubscribe", topic: params };
373
+ filter = (message) => message.topic === params;
374
+ } else {
375
+ subscribeMessage = params;
376
+ unsubscribeMessage = typeof unsubscribe === "function" ? unsubscribe() : unsubscribe;
377
+ filter = messageFilter || ((message) => true);
378
+ }
379
+ return [subscribeMessage, unsubscribeMessage, filter, messageFormatter];
380
+ }
381
+ _sendPendingPrivateMessage() {
382
+ if (this._pendingPrivateSubscribe.length === 0)
383
+ return;
384
+ this._pendingPrivateSubscribe.forEach((params) => {
385
+ this.privateObserve(params).subscribe();
386
+ });
387
+ this._pendingPrivateSubscribe = [];
388
+ }
389
+ // 取消所有订阅
390
+ desotry() {
391
+ var _a;
392
+ this.wsSubject.unsubscribe();
393
+ (_a = this.privateWsSubject) == null ? void 0 : _a.unsubscribe();
394
+ }
395
+ };
396
+ // the topic reference count;
397
+ _WebSocketClient.__topicRefCountMap = /* @__PURE__ */ new Map();
398
+ var WebSocketClient = _WebSocketClient;
399
+ var ws_default = WebSocketClient;
400
+
401
+ // src/constants.ts
402
+ var __ORDERLY_API_URL_KEY__ = "__ORDERLY_API_URL__";
403
+ // Annotate the CommonJS export names for ESM import in node:
404
+ 0 && (module.exports = {
405
+ WebSocketClient,
406
+ __ORDERLY_API_URL_KEY__,
407
+ get,
408
+ post
409
+ });
410
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/fetch/index.ts","../src/ws/index.ts","../src/ws/contants.ts","../src/ws/handler/baseHandler.ts","../src/ws/handler/ping.ts","../src/ws/handler/handler.ts","../src/constants.ts"],"sourcesContent":["export { get, post } from \"./fetch\";\n\nexport { default as WebSocketClient } from \"./ws\";\nexport { __ORDERLY_API_URL_KEY__ } from \"./constants\";\n","async function request(url: string, options: RequestInit) {\n // console.log(\"request\", url, options);\n if (!url.startsWith(\"http\")) {\n throw new Error(\"url must start with http(s)\");\n }\n const urlInstance = new URL(url);\n const response = await fetch(urlInstance, {\n ...options,\n // mode: \"cors\",\n // credentials: \"include\",\n headers: _createHeaders(options.headers),\n }).catch((err) => {\n throw new Error(err);\n });\n\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n}\n\nfunction _createHeaders(headers: HeadersInit = {}): HeadersInit {\n // console.log(\"headers\", headers);\n const _headers = new Headers(headers);\n // _headers.append(\"Accept\", \"application/json\");\n\n if (!_headers.has(\"Content-Type\")) {\n _headers.append(\"Content-Type\", \"application/json;charset=utf-8\");\n }\n\n return _headers;\n}\n\nasync function get<R>(\n url: string,\n options?: RequestInit,\n formatter?: (data: any) => R\n): Promise<R> {\n const res = await request(url, {\n method: \"GET\",\n ...options,\n });\n\n if (res.success) {\n if (typeof formatter === \"function\") {\n return formatter(res.data);\n }\n // 根据返回的数据结构,返回需要的数据\n if (Array.isArray(res.data[\"rows\"])) {\n return res.data[\"rows\"] as R;\n }\n return res.data;\n }\n throw new Error(res.message);\n}\nasync function post(\n url: string,\n data: any,\n options?: Omit<RequestInit, \"method\">\n): Promise<any> {\n const res = await request(url, {\n method: \"POST\",\n body: JSON.stringify(data),\n ...options,\n });\n\n return res;\n}\n\nexport { get, post };\n","import { type WebSocketSubject, webSocket } from \"rxjs/webSocket\";\n\nimport { WS_URL } from \"./contants\";\nimport { Observable, Observer, Subject, tap } from \"rxjs\";\nimport { messageHandlers } from \"@/ws/handler/handler\";\n\nexport type NetworkId = \"testnet\" | \"mainnet\";\n\nexport type WSOptions = {\n url?: string;\n networkId?: NetworkId;\n accountId?: string;\n\n onSigntureRequest?: (accountId: string) => Promise<any>;\n};\n\nclass WebSocketClient {\n // the topic reference count;\n private static __topicRefCountMap: Map<string, number> = new Map();\n private wsSubject: WebSocketSubject<any>;\n private privateWsSubject?: WebSocketSubject<any>;\n\n private authenticated: boolean = false;\n\n private _pendingPrivateSubscribe: any[] = [];\n\n constructor(options: WSOptions) {\n this.wsSubject = this.createSubject(options);\n\n if (!!options.accountId) {\n this.privateWsSubject = this.createPrivateSubject(options);\n }\n\n this.bindSubscribe();\n }\n private createSubject(options: WSOptions): WebSocketSubject<any> {\n let url;\n if (typeof options.url === \"string\") {\n url = options.url;\n } else {\n url = WS_URL[options.networkId || \"testnet\"].public;\n }\n\n return webSocket({\n url: `${url}${options.accountId || \"\"}`,\n openObserver: {\n next: () => {\n console.log(\"Connection ok\");\n },\n },\n closeObserver: {\n next: () => {\n console.log(\"Connection closed\");\n },\n },\n });\n }\n\n private createPrivateSubject(options: WSOptions): WebSocketSubject<any> {\n const url = WS_URL[options.networkId || \"testnet\"].private;\n const ws = webSocket({\n url: `${url}${options.accountId}`,\n openObserver: {\n next: () => {\n console.log(\"Private connection ok\");\n if (this.authenticated || !options.accountId) return;\n\n options.onSigntureRequest?.(options.accountId).then((signature) => {\n this.authenticate(options.accountId!, signature);\n });\n },\n },\n closeObserver: {\n next: () => {\n console.log(\"Private connection closed\");\n this.authenticated = false;\n },\n },\n });\n // authenticate\n\n return ws;\n }\n\n private bindSubscribe() {\n /// 处理ping,auth等消息\n\n this.wsSubject.subscribe({\n next: (message) => {\n const handler = messageHandlers.get(message.event);\n if (handler) {\n handler.handle(message, this.send);\n }\n },\n error(err) {\n console.log(\"WS Error: \", err);\n },\n complete() {\n console.log(\"WS Connection closed\");\n },\n });\n\n if (!this.privateWsSubject) return;\n\n this.privateWsSubject.subscribe({\n next: (message) => {\n if (message.event === \"auth\") {\n this.authenticated = true;\n // 认证成功后,发送之前的订阅消息\n this._sendPendingPrivateMessage();\n return;\n }\n\n const handler = messageHandlers.get(message.event);\n\n if (handler) {\n handler.handle(message, this.privateSend);\n }\n },\n error(err) {\n console.log(\"WS Error: \", err);\n },\n complete() {\n console.log(\"WS Connection closed\");\n },\n });\n }\n\n private authenticate(\n accountId: string,\n message: {\n publicKey: string;\n signature: string;\n timestamp: number;\n }\n ) {\n if (this.authenticated) return;\n if (!this.privateWsSubject) {\n console.error(\"private ws not connected\");\n return;\n }\n\n console.log(\"push auth message:\", message);\n this.privateWsSubject?.next({\n id: \"auth\",\n event: \"auth\",\n params: {\n orderly_key: message.publicKey,\n sign: message.signature,\n timestamp: message.timestamp,\n },\n });\n // this.wsSubject.next({ type: \"authenticate\" });\n // this.authenticated = true;\n }\n\n send = (message: any) => {\n this.wsSubject.next(message);\n };\n\n privateSend = (message: any) => {\n if (!this.privateWsSubject) {\n console.warn(\"private ws not connected\");\n return;\n }\n\n this.privateWsSubject.next(message);\n };\n\n get isAuthed() {\n return this.authenticated;\n }\n\n // observe<T>(topic: string): Observable<T>;\n // observe<T>(topic: string, unsubscribe?: () => any): Observable<T>;\n // observe<T>(\n // params: {\n // event: string;\n // } & Record<string, any>,\n // unsubscribe?: () => any\n // ): Observable<T>;\n observe<T>(\n params: any,\n unsubscribe?: () => any,\n messageFilter?: (value: T) => boolean\n ): Observable<T> {\n return this._observe(false, params, unsubscribe, messageFilter);\n }\n\n // privateObserve<T>(topic: string): Observable<T>;\n // privateObserve<T>(topic: string, unsubscribe?: () => any): Observable<T>;\n // privateObserve<T>(\n // params: {\n // event: string;\n // } & Record<string, any>,\n // unsubscribe?: () => any\n // ): Observable<T>;\n privateObserve<T>(\n params: any,\n unsubscribe?: () => any,\n messageFilter?: (value: T) => boolean\n ): Observable<T> {\n return this._observe(true, params, unsubscribe, messageFilter);\n }\n\n private _observe<T>(\n isPrivate: boolean,\n params: any,\n unsubscribe?: () => any,\n messageFilter?: (value: T) => boolean\n ) {\n if (isPrivate && !this.privateWsSubject) {\n throw new Error(\"private ws not connected\");\n }\n\n const subject = isPrivate ? this.privateWsSubject : this.wsSubject;\n const sendFunc = isPrivate ? this.privateSend : this.send;\n\n const [subscribeMessage, unsubscribeMessage, filter, messageFormatter] =\n this.generateMessage(params, unsubscribe, messageFilter);\n\n return new Observable((observer: Observer<T>) => {\n // 如果是private ws, 但是没有连接,就先缓存起来,等连接上了再订阅\n if (isPrivate && !this.authenticated) {\n this._pendingPrivateSubscribe.push(params);\n return;\n }\n\n try {\n //TODO: add ref count, only send subscribe message when ref count is 0\n // 如果已经订阅过了,就不再发送订阅消息\n const refCount =\n WebSocketClient.__topicRefCountMap.get(subscribeMessage.topic) || 0;\n if (refCount === 0) {\n // WS.__topicRefCountMap.set(subscribeMessage.topic, WS.__topicRefCountMap.get(subscribeMessage.topic) + 1);\n // this.send(subscribeMessage);\n sendFunc(subscribeMessage);\n WebSocketClient.__topicRefCountMap.set(\n subscribeMessage.topic,\n refCount + 1\n );\n }\n } catch (err) {\n observer.error(err);\n }\n\n const subscription = subject!.subscribe({\n next: (x) => {\n try {\n if (filter(x)) {\n observer.next(messageFormatter(x));\n }\n } catch (err) {\n observer.error(err);\n }\n },\n error: (err) => observer.error(err),\n complete: () => observer.complete(),\n });\n\n return () => {\n try {\n // console.log(\"******* unsubscribe\", unsubscribeMessage);\n const refCount =\n WebSocketClient.__topicRefCountMap.get(subscribeMessage.topic) || 0;\n if (refCount > 1) {\n WebSocketClient.__topicRefCountMap.set(\n subscribeMessage.topic,\n refCount - 1\n );\n return;\n }\n if (!!unsubscribeMessage) {\n this.send(unsubscribeMessage);\n }\n WebSocketClient.__topicRefCountMap.delete(subscribeMessage.topic);\n } catch (err) {\n observer.error(err);\n }\n subscription.unsubscribe();\n };\n });\n }\n\n private generateMessage(\n params: any,\n unsubscribe?: () => any,\n messageFilter?: (value: any) => boolean\n ): [\n Record<string, any>,\n Record<string, any>,\n (message: any) => boolean,\n (message: any) => any\n ] {\n let subscribeMessage: Record<string, any>,\n unsubscribeMessage: Record<string, any>;\n let filter: (message: any) => boolean,\n messageFormatter: (message: any) => any = (message: any) => message.data;\n\n if (typeof params === \"string\") {\n subscribeMessage = { event: \"subscribe\", topic: params };\n unsubscribeMessage = { event: \"unsubscribe\", topic: params };\n filter = (message: any) => message.topic === params;\n } else {\n subscribeMessage = params;\n unsubscribeMessage =\n typeof unsubscribe === \"function\" ? unsubscribe() : unsubscribe;\n filter = messageFilter || ((message: any) => true);\n }\n\n return [subscribeMessage, unsubscribeMessage, filter, messageFormatter];\n }\n\n private _sendPendingPrivateMessage() {\n if (this._pendingPrivateSubscribe.length === 0) return;\n this._pendingPrivateSubscribe.forEach((params) => {\n this.privateObserve(params).subscribe();\n });\n this._pendingPrivateSubscribe = [];\n }\n\n // 取消所有订阅\n desotry() {\n this.wsSubject.unsubscribe();\n this.privateWsSubject?.unsubscribe();\n }\n}\n\nexport default WebSocketClient;\n","export const WS_URL = {\n testnet: {\n // public: \"wss://testnet-ws.orderly.org/ws/stream/\",\n public: \"wss://dev-ws-v2.orderly.org/ws/stream/\",\n // private:\n // \"wss://dev-ws-private-v2.orderly.org/wsprivate/v2/ws/private/stream/\",\n private: \"wss://dev-ws-private-v2.orderly.org/v2/ws/private/stream/\",\n },\n mainnet: {\n public: \"wss://mainnet-ws.orderly.io\",\n private: \"wss://mainnet-ws.orderly.io\",\n },\n};\n","import { MessageHandler, SendFunc } from \"@/types/ws\";\nimport { WebSocketSubject } from \"rxjs/webSocket\";\n\nexport default class BaseHandler implements MessageHandler {\n // constructor(readonly wsSubject: WebSocketSubject<any>) {}\n handle(message: any, send: SendFunc) {\n throw new Error(\"Method not implemented.\");\n }\n}\n","import BaseHandler from \"./baseHandler\";\nimport { SendFunc } from \"@/types/ws\";\n\nexport default class PingHandler extends BaseHandler {\n handle(_: any, send: SendFunc) {\n send({ event: \"pong\", ts: Date.now() });\n }\n}\n","import { MessageHandler } from \"@/types/ws\";\nimport PingHandler from \"./ping\";\n\nexport type MessageType =\n | \"ping\"\n | \"pong\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"authenticate\"\n | \"message\"\n | \"error\"\n | \"auth\"\n | \"close\";\n\nexport const messageHandlers = new Map<MessageType, MessageHandler>([\n [\"ping\", new PingHandler()],\n]);\n","export const __ORDERLY_API_URL_KEY__: string = \"__ORDERLY_API_URL__\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;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