Back to OScope
Code
53 lines (48 loc) · 1.99 KB
// The one websocket to the OScope server, and plain reads.
import { emitter } from './util.js';
export const live = Object.assign(emitter(), { sol: 0, feed: false, lag: null, open: false, coins: 0 });
let ws = null, wait = 500;
const wants = { pulse: false, tape: false, coin: null, watch: [], track: [] };
function sendNow(o) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(o)); }
function connect() {
ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws');
ws.onopen = () => {
live.open = true; wait = 500;
if (wants.pulse) sendNow({ t: 'pulse', on: true });
if (wants.tape) sendNow({ t: 'tape', on: true });
if (wants.coin) sendNow({ t: 'coin', mint: wants.coin });
if (wants.watch.length) sendNow({ t: 'watch', mints: wants.watch });
if (wants.track.length) sendNow({ t: 'track', wallets: wants.track });
live.emit('status');
};
ws.onmessage = e => {
let m;
try { m = JSON.parse(e.data); } catch { return; }
if (m.t === 'hello' || m.t === 'st') {
if (m.sol) live.sol = m.sol;
live.feed = m.feed; live.lag = m.lag ?? null; if (m.coins) live.coins = m.coins;
if (m.stretchAt) live.stretchAt = m.stretchAt;
live.emit('status');
return;
}
live.emit(m.t, m);
};
ws.onclose = () => {
live.open = false; live.emit('status');
setTimeout(connect, wait);
wait = Math.min(wait * 2, 8000);
};
}
connect();
export const net = {
pulse(on) { wants.pulse = on; sendNow({ t: 'pulse', on }); },
tape(on) { wants.tape = on; sendNow({ t: 'tape', on }); },
coin(mint) { wants.coin = mint; sendNow({ t: 'coin', mint }); },
watch(mints) { wants.watch = mints; sendNow({ t: 'watch', mints }); },
track(wallets) { wants.track = wallets; sendNow({ t: 'track', wallets }); },
async get(path) {
const r = await fetch(path, { headers: { accept: 'application/json' } });
if (!r.ok) { const e = new Error('http ' + r.status); e.status = r.status; throw e; }
return r.json();
},
};