@ln-markets/api
Version:
A set of wrappers to easily communicate with LN Markets API !
101 lines (100 loc) • 3.09 kB
JavaScript
import Websocket from 'ws';
import { randomBytes } from 'node:crypto';
import { getHostname } from './utils.js';
export const createWebsocketClient = async (options = {}) => {
const { network = process.env.LNM_API_NETWORK ?? 'mainnet', heartbeat = true, } = 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 { id, method, result, error, params } = 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 = {
jsonrpc: '2.0',
id: randomBytes(16).toString('hex'),
method,
params,
};
return new Promise((resolve, reject) => {
const done = (result, error) => {
if (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 publicPing = () => {
return send(`v1/public/ping`);
};
const publicChannels = () => {
return send(`v1/public/channels`);
};
const publicSubscribe = (channels) => {
return send(`v1/public/subscribe`, channels);
};
const publicUnsubscribe = (channels) => {
return send(`v1/public/unsubscribe`, channels);
};
return {
ws,
disconnect,
send,
publicSubscribe,
publicUnsubscribe,
publicPing,
publicChannels,
};
};