-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (51 loc) · 1.76 KB
/
index.js
File metadata and controls
65 lines (51 loc) · 1.76 KB
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
const { createPublicClient, webSocket } = require('viem');
const { mainnet } = require('viem/chains');
const Database = require('better-sqlite3');
const { analyzeBlock, analyzeWatchedPairs } = require('./src/common');
const CONFIG = require('./config.json');
const transport = webSocket(CONFIG.wsRemote);
const client = createPublicClient({
chain: mainnet,
transport
});
client.watchBlockNumber({
onBlockNumber: block => parseBlockNumber(block)
});
async function parseBlockNumber(blockNumber) {
// @PITFALL - block is unfinalized at this point, uncertain if a delay is needed for accurate results
// console.log(`parseBlockNumber: ${blockNumber}`);
// console.log(`https://etherscan.io/block/${blockNumber}`);
// does not seem like db needs to reopened for each block
const db = new Database('monitor-node.db');
db.pragma('journal_mode = WAL');
await analyzeBlock({ client, db, blockNumber, outputToFile: false });
const watchedPairs = await analyzeWatchedPairs({ client, db });
await broadcastToClients('watchedPairs', watchedPairs);
db.close();
};
async function broadcastToClients(type, data) {
clients.forEach((client) => {
client.send(JSON.stringify({ type, data }));
});
}
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const clients = [];
const PORT = 5002;
app.use(cors());
wss.on('connection', (ws) => {
console.log('Client connected');
clients.push(ws);
ws.on('close', () => {
console.log('Client disconnected');
clients.splice(clients.indexOf(ws), 1);
});
});
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});