import {createHash} from 'crypto'; import {EventEmitter} from 'events'; import {Agent} from 'http'; import {Dashboard, defaultDashboard} from '@ex-master/core'; import {WebSocketClient} from '@ex-master/utilities/websocket-client'; import {Dict} from 'tslang'; import {ZBAPIFullToken, ZBAPIToken} from '../types'; import {sign} from './@signature'; const DEFAULT_ZB_SPOT_WEBSOCKET_API_BASE_URL = 'wss://api.zb.center/websocket'; const PING_INTERVAL = 5000; const userDataChannelRegEx = /^push_|_order$|_cancelorder$|_getorder$|_getorders$|_getordersignoretradetype$|getaccountinfo$|addSubUser|getSubUserList|doTransferFunds|createSubUserKey/i; export type ZBSpotWebSocketListener = (data?: any) => void; export interface ZBSpotWebSocketAPIOptions { baseURL?: string; token?: ZBAPIToken; dashboard?: Dashboard; agent?: Agent; } export class ZBSpotWebSocketAPI extends EventEmitter { private token: ZBAPIFullToken | undefined; private websocketClient: WebSocketClient; private dashboard: Dashboard = this.options.dashboard || defaultDashboard; private addedChannelSet = new Set(); constructor(readonly options: ZBSpotWebSocketAPIOptions) { super(); this.token = options.token ? { ...options.token, sha: createHash('sha1') .update(options.token.secret) .digest('hex'), } : undefined; this.websocketClient = new WebSocketClient( this.options.baseURL || DEFAULT_ZB_SPOT_WEBSOCKET_API_BASE_URL, { pingInterval: PING_INTERVAL, }, ); let resendMessageHandler: (() => void) | undefined; this.websocketClient.on('open', () => { if (resendMessageHandler) { resendMessageHandler(); } }); this.websocketClient.on('message', message => { this.emit('message', message); }); this.websocketClient.on('close', () => { resendMessageHandler = () => { resendMessageHandler = undefined; for (const channel of this.addedChannelSet) { this.websocketClient.send(channel).catch(error => { this.dashboard.error(error); this.websocketClient.close(); }); } }; this.emit('error', new Error('zb websocket connection closed')); }); } async addChannel(channel: string, args: Dict = {}): Promise { let params: Dict = { event: 'addChannel', channel, ...args, }; if (userDataChannelRegEx.test(channel)) { params = sign(this.token!, params, JSON.stringify); } channel = JSON.stringify(params); if (this.addedChannelSet.has(channel)) { return; } this.addedChannelSet.add(channel); await this.websocketClient.send(channel); } destroy(): void { this.addedChannelSet.clear(); this.websocketClient.terminate(); this.websocketClient.removeAllListeners(); this.removeAllListeners(); } }