UNPKG

@drift-labs/common

Version:

Common functions for Drift

49 lines 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getResponseTime = exports.getRpcWithLowestPing = exports.getResponseTimes = void 0; const getResponseTimes = async (rpcOptions) => { const responseTimes = await Promise.all(rpcOptions.map(async (rpc) => { const responseTime = await (0, exports.getResponseTime)(rpc.value); return { value: rpc.value, latency: responseTime }; })); return responseTimes.filter((result) => result.latency != null); }; exports.getResponseTimes = getResponseTimes; const getRpcWithLowestPing = async (rpcEndpoints) => { const results = await Promise.all(rpcEndpoints.map((endpoint) => (0, exports.getResponseTime)(endpoint.value))); const validResults = results.filter((responseTime) => responseTime !== -1 && responseTime != null); if (validResults.length <= 0) return undefined; const lowestResponseTime = Math.min(...validResults); const rpcIndex = results.indexOf(lowestResponseTime); return rpcEndpoints[rpcIndex]; }; exports.getRpcWithLowestPing = getRpcWithLowestPing; const getResponseTime = async (endpoint) => { if (!endpoint) return null; const storage = typeof localStorage !== 'undefined' ? localStorage : require('localstorage-memory'); const accessToken = storage.getItem('auth-token'); const startTime = Date.now(); const result = await fetch(`${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + accessToken, }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }), }).catch((err) => { console.error('Error checking RPC response time ', err); return null; }); if (!result) return -1; if (!result.ok) return -1; const endTime = Date.now(); return endTime - startTime; }; exports.getResponseTime = getResponseTime; //# sourceMappingURL=rpcLatency.js.map