@ln-markets/sdk
Version:
TypeScript SDK for LNMarkets API v2
102 lines • 3.13 kB
JavaScript
import { randomBytes } from 'node:crypto';
import Websocket from 'ws';
import { getHostname } from './utils.js';
export const createWebsocketClient = async (options = {}) => {
const { heartbeat = true, network = process.env.LNM_API_NETWORK ?? 'mainnet', } = options;
const ws = await new Promise((resolve, reject) => {
const hostname = process.env.LNM_API_HOSTNAME ?? getHostname(network);
const url = `wss://${hostname}`;
const ws = new Websocket(url);
ws.once('error', reject);
ws.once('open', () => {
resolve(ws);
});
});
if (heartbeat) {
ws.ping();
ws.on('pong', () => {
setTimeout(() => {
ws.ping();
}, 5000);
});
}
ws.on('message', (data) => {
try {
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const response = JSON.parse(data.toString());
const { error, id, method, params, result } = response;
ws.emit('response', response);
if (method === 'subscription' && params) {
const { channel, data } = params;
ws.emit(channel, data);
}
else if (id) {
ws.emit(id, result, error);
}
}
catch {
ws.emit('error', data);
}
});
const disconnect = () => {
ws.close();
};
const send = (method, params) => {
if (ws.readyState !== 1) {
throw new Error('Websocket Client is not connected');
}
const payload = {
id: randomBytes(16).toString('hex'),
jsonrpc: '2.0',
method,
params,
};
return new Promise((resolve, reject) => {
const done = (result, error) => {
if (error) {
console.log('error', error);
if (typeof error === 'string') {
reject(new Error(error));
}
else if (error instanceof Error) {
reject(error);
}
else {
reject(new Error('Unknown error'));
}
}
else {
resolve(result);
}
};
ws.send(JSON.stringify(payload), (error) => {
if (error) {
reject(error);
}
ws.once(payload.id, done);
});
});
};
const ping = () => {
return send(`v1/public/ping`);
};
const getChannels = () => {
return send(`v1/public/channels`);
};
const subscribe = (channels) => {
return send(`v1/public/subscribe`, channels);
};
const unsubscribe = (channels) => {
return send(`v1/public/unsubscribe`, channels);
};
return {
disconnect,
getChannels,
ping,
send,
subscribe,
unsubscribe,
ws,
};
};
//# sourceMappingURL=websocket.js.map