blob: 6172f5ebf3b458410d8f581d2e23748dc119d121 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import got from "got";
import config from "$config";
import { err } from "$lib/logging";
import { g, s } from "$lib/db";
import { sleep } from "$lib/utils";
import WebSocket from "ws";
let last;
let ws;
let connect = async () => {
if (ws && ws.readyState === 1 && Date.now() - last < 5000) return;
if (ws) ws.terminate() && (await sleep(Math.round(Math.random() * 1000)));
ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");
ws.onmessage = async function (event) {
try {
let msg = JSON.parse(event.data);
let rates = await g("rates") || {};
let fx = await g("fx");
if (fx) ({ fx } = fx);
if (!fx) return;
Object.keys(fx).map((symbol) => {
rates[symbol] = msg.c * fx[symbol];
});
s("rate", msg.c);
s("rates", rates);
last = Date.now();
} catch (e) {
console.log(e);
err("binance message error", e.message);
}
};
ws.onerror = async function (error) {
err("binance socket error", error.message);
};
return ws;
};
export let getFx = async () => {
connect();
let date = 0,
fx = await g("fx");
if (fx) ({ date, fx } = fx);
if (Date.now() - date > 24 * 60 * 60 * 1000) {
date = Date.now();
try {
if (config.fixer) {
({ rates: fx } = (await got(
`http://data.fixer.io/api/latest?access_key=${config.fixer}`,
).json()) as any);
} else {
({ fx } = (await got("https://coinos.io/api/fx").json()) as any);
}
let USD = fx["USD"];
Object.keys(fx).map((k) => {
fx[k] = fx[k] / USD;
});
await s("fx", { date, fx });
} catch (e) {
err("error fetching rates", e.message);
}
}
setTimeout(getFx, 30000);
};
|