@clonegod/ttd-core 2.0.67 → 2.0.69

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.
package/dist/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export * from './quote';
10
10
  export * from './token';
11
11
  export * from './trade';
12
12
  export * from './chains';
13
+ export * from './ws';
13
14
  export declare const FAILED = "FAILED";
14
15
  export declare const SUCCESS = "SUCCESS";
15
16
  export declare const NOT_FOUND = "NOT_FOUND";
package/dist/index.js CHANGED
@@ -90,6 +90,7 @@ __exportStar(require("./quote"), exports);
90
90
  __exportStar(require("./token"), exports);
91
91
  __exportStar(require("./trade"), exports);
92
92
  __exportStar(require("./chains"), exports);
93
+ __exportStar(require("./ws"), exports);
93
94
  const short = require('short-uuid');
94
95
  const exec = require('util').promisify(require('child_process').exec);
95
96
  exports.FAILED = 'FAILED';
@@ -0,0 +1 @@
1
+ export * from './ws_client';
@@ -0,0 +1,17 @@
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("./ws_client"), exports);
@@ -0,0 +1,42 @@
1
+ export interface WebSocketClientOptions {
2
+ reconnectInterval?: number;
3
+ maxReconnectAttempts?: number;
4
+ headers?: {
5
+ [key: string]: string;
6
+ };
7
+ protocols?: string | string[];
8
+ handshakeTimeout?: number;
9
+ perMessageDeflate?: boolean | object;
10
+ timeout?: number;
11
+ keepAlive?: boolean;
12
+ keepAliveInterval?: number;
13
+ }
14
+ export declare class WebSocketClient {
15
+ private url;
16
+ private options;
17
+ private ws;
18
+ private reconnectInterval;
19
+ private onMessageCallback;
20
+ private onOpenCallback;
21
+ private onCloseCallback;
22
+ private onErrorCallback;
23
+ private reconnectAttempts;
24
+ private maxReconnectAttempts;
25
+ private isReconnecting;
26
+ private keepAliveTimer;
27
+ constructor(url: string, options?: WebSocketClientOptions);
28
+ private setDefaultOptions;
29
+ connect(): void;
30
+ onMessage(callback: (data: any) => void): void;
31
+ onOpen(callback: () => void): void;
32
+ onClose(callback: () => void): void;
33
+ onError(callback: (error: Error) => void): void;
34
+ send(data: any): boolean;
35
+ disconnect(): void;
36
+ private handleReconnect;
37
+ isConnected(): boolean;
38
+ getConnectionState(): string;
39
+ resetReconnectAttempts(): void;
40
+ private startKeepAlive;
41
+ private stopKeepAlive;
42
+ }
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WebSocketClient = void 0;
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const __1 = require("..");
9
+ class WebSocketClient {
10
+ constructor(url, options = {}) {
11
+ this.ws = null;
12
+ this.onMessageCallback = null;
13
+ this.onOpenCallback = null;
14
+ this.onCloseCallback = null;
15
+ this.onErrorCallback = null;
16
+ this.reconnectAttempts = 0;
17
+ this.maxReconnectAttempts = 10;
18
+ this.isReconnecting = false;
19
+ this.keepAliveTimer = null;
20
+ this.url = url;
21
+ this.options = this.setDefaultOptions(options);
22
+ this.reconnectInterval = this.options.reconnectInterval;
23
+ this.maxReconnectAttempts = this.options.maxReconnectAttempts;
24
+ (0, __1.log_info)(`WebSocketClient constructor, url: ${this.url}`, this.options);
25
+ }
26
+ setDefaultOptions(options) {
27
+ const defaults = {
28
+ reconnectInterval: 3000,
29
+ maxReconnectAttempts: 10,
30
+ keepAlive: true,
31
+ keepAliveInterval: 30000,
32
+ handshakeTimeout: 10000,
33
+ perMessageDeflate: true,
34
+ timeout: 5000,
35
+ };
36
+ return Object.assign(Object.assign({}, defaults), options);
37
+ }
38
+ connect() {
39
+ if (this.isReconnecting) {
40
+ return;
41
+ }
42
+ const wsOptions = {
43
+ headers: this.options.headers,
44
+ protocols: this.options.protocols,
45
+ handshakeTimeout: this.options.handshakeTimeout,
46
+ perMessageDeflate: this.options.perMessageDeflate
47
+ };
48
+ (0, __1.log_info)(`Connecting to ${this.url} with options:`, wsOptions);
49
+ this.ws = new ws_1.default(this.url, wsOptions);
50
+ this.ws.on('open', () => {
51
+ console.log(`Connected to ${this.url}`);
52
+ this.reconnectAttempts = 0;
53
+ this.isReconnecting = false;
54
+ this.startKeepAlive();
55
+ if (this.onOpenCallback)
56
+ this.onOpenCallback();
57
+ });
58
+ this.ws.on('message', (message) => {
59
+ try {
60
+ const data = JSON.parse(message.toString());
61
+ if (this.onMessageCallback)
62
+ this.onMessageCallback(data);
63
+ }
64
+ catch (err) {
65
+ console.error('Invalid message format:', err);
66
+ }
67
+ });
68
+ this.ws.on('close', (code, reason) => {
69
+ console.log(`Disconnected from server: ${code} - ${reason.toString()}`);
70
+ if (this.onCloseCallback)
71
+ this.onCloseCallback();
72
+ this.handleReconnect();
73
+ });
74
+ this.ws.on('error', (err) => {
75
+ console.error('WebSocket error:', err);
76
+ if (this.onErrorCallback)
77
+ this.onErrorCallback(err);
78
+ });
79
+ }
80
+ onMessage(callback) {
81
+ this.onMessageCallback = callback;
82
+ }
83
+ onOpen(callback) {
84
+ this.onOpenCallback = callback;
85
+ }
86
+ onClose(callback) {
87
+ this.onCloseCallback = callback;
88
+ }
89
+ onError(callback) {
90
+ this.onErrorCallback = callback;
91
+ }
92
+ send(data) {
93
+ if (this.ws && this.ws.readyState === ws_1.default.OPEN) {
94
+ this.ws.send(JSON.stringify(data));
95
+ return true;
96
+ }
97
+ else {
98
+ console.error('WebSocket is not connected');
99
+ return false;
100
+ }
101
+ }
102
+ disconnect() {
103
+ this.isReconnecting = false;
104
+ this.stopKeepAlive();
105
+ if (this.ws) {
106
+ this.ws.close();
107
+ this.ws = null;
108
+ }
109
+ }
110
+ handleReconnect() {
111
+ if (this.isReconnecting) {
112
+ return;
113
+ }
114
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
115
+ (0, __1.log_info)(`Max reconnection attempts (${this.maxReconnectAttempts}) reached`);
116
+ return;
117
+ }
118
+ this.isReconnecting = true;
119
+ this.reconnectAttempts++;
120
+ (0, __1.log_info)(`Scheduling reconnect in ${this.reconnectInterval}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
121
+ setTimeout(() => {
122
+ (0, __1.log_info)(`Attempting to reconnect to ${this.url}... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
123
+ this.connect();
124
+ }, this.reconnectInterval);
125
+ }
126
+ isConnected() {
127
+ return this.ws !== null && this.ws.readyState === ws_1.default.OPEN;
128
+ }
129
+ getConnectionState() {
130
+ if (!this.ws)
131
+ return 'DISCONNECTED';
132
+ switch (this.ws.readyState) {
133
+ case ws_1.default.CONNECTING:
134
+ return 'CONNECTING';
135
+ case ws_1.default.OPEN:
136
+ return 'OPEN';
137
+ case ws_1.default.CLOSING:
138
+ return 'CLOSING';
139
+ case ws_1.default.CLOSED:
140
+ return 'CLOSED';
141
+ default:
142
+ return 'UNKNOWN';
143
+ }
144
+ }
145
+ resetReconnectAttempts() {
146
+ this.reconnectAttempts = 0;
147
+ this.isReconnecting = false;
148
+ }
149
+ startKeepAlive() {
150
+ if (!this.options.keepAlive) {
151
+ (0, __1.log_info)('KeepAlive disabled');
152
+ return;
153
+ }
154
+ const interval = this.options.keepAliveInterval;
155
+ (0, __1.log_info)(`Starting keepAlive with interval: ${interval}ms`);
156
+ this.keepAliveTimer = setInterval(() => {
157
+ if (this.ws && this.ws.readyState === ws_1.default.OPEN) {
158
+ this.ws.ping();
159
+ (0, __1.log_info)('KeepAlive ping sent');
160
+ }
161
+ }, interval);
162
+ }
163
+ stopKeepAlive() {
164
+ if (this.keepAliveTimer) {
165
+ clearInterval(this.keepAliveTimer);
166
+ this.keepAliveTimer = null;
167
+ }
168
+ }
169
+ }
170
+ exports.WebSocketClient = WebSocketClient;
@@ -0,0 +1,5 @@
1
+ import { WebSocketClient } from './index';
2
+ declare const basicClient: WebSocketClient;
3
+ declare const fullClient: WebSocketClient;
4
+ declare const bscClient: WebSocketClient;
5
+ export { basicClient, fullClient, bscClient };
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bscClient = exports.fullClient = exports.basicClient = void 0;
4
+ const index_1 = require("./index");
5
+ const basicClient = new index_1.WebSocketClient('wss://api.blxrbdn.com/ws', {
6
+ headers: {
7
+ "Authorization": "YOUR_AUTHORIZATION_HEADER"
8
+ }
9
+ });
10
+ exports.basicClient = basicClient;
11
+ const fullClient = new index_1.WebSocketClient('wss://api.blxrbdn.com/ws', {
12
+ reconnectInterval: 2000,
13
+ maxReconnectAttempts: 15,
14
+ headers: {
15
+ "Authorization": "YOUR_AUTHORIZATION_HEADER",
16
+ "User-Agent": "MyApp/1.0"
17
+ },
18
+ protocols: ["echo-protocol"],
19
+ handshakeTimeout: 15000,
20
+ keepAlive: true,
21
+ keepAliveInterval: 20000,
22
+ timeout: 8000
23
+ });
24
+ exports.fullClient = fullClient;
25
+ const bscOptions = {
26
+ reconnectInterval: 2000,
27
+ maxReconnectAttempts: 15,
28
+ headers: {
29
+ "Authorization": "YOUR_BSC_AUTHORIZATION_HEADER"
30
+ },
31
+ keepAlive: true,
32
+ keepAliveInterval: 20000,
33
+ handshakeTimeout: 15000
34
+ };
35
+ const bscClient = new index_1.WebSocketClient('wss://singapore.bsc.blxrbdn.com/ws', bscOptions);
36
+ exports.bscClient = bscClient;
37
+ bscClient.onOpen(() => {
38
+ console.log('BSC WebSocket 连接成功');
39
+ bscClient.send({
40
+ jsonrpc: "2.0",
41
+ id: 1,
42
+ method: "subscribe",
43
+ params: ["newTxs", { "include": [], "blockchain_network": "BSC-Mainnet" }]
44
+ });
45
+ });
46
+ bscClient.onMessage((data) => {
47
+ console.log('收到 BSC 数据:', data);
48
+ });
49
+ bscClient.onError((error) => {
50
+ console.error('BSC WebSocket 错误:', error);
51
+ });
52
+ bscClient.onClose(() => {
53
+ console.log('BSC WebSocket 连接关闭');
54
+ });
55
+ bscClient.connect();
56
+ console.log('连接状态:', bscClient.getConnectionState());
57
+ console.log('是否连接:', bscClient.isConnected());
58
+ const success = bscClient.send({
59
+ jsonrpc: "2.0",
60
+ id: 2,
61
+ method: "subscribe",
62
+ params: ["traceBlocks", { "include": [], "blockchain_network": "BSC-Mainnet" }]
63
+ });
64
+ if (success) {
65
+ console.log('消息发送成功');
66
+ }
67
+ else {
68
+ console.log('消息发送失败');
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clonegod/ttd-core",
3
- "version": "2.0.67",
3
+ "version": "2.0.69",
4
4
  "description": "Common types and utilities for trading systems - use `npm run push` to publish",
5
5
  "main": "dist/index.js",
6
6
  "types": "types/index.d.ts",