-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
executable file
·71 lines (55 loc) · 2.67 KB
/
index.mjs
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
#!/usr/bin/env node
import { readFile, appendFile } from "fs/promises";
import { existsSync } from "fs";
import pkg from "./package.json" assert { type: "json" };
import { getTokenTx } from "./lib/etherscan.mjs";
import { sendMessage } from "./lib/telegram.mjs";
import { formatAccountUrl, formatNewTxs, formatError, formatStatus } from "./lib/messages.mjs";
import { readConfig } from "./lib/config.mjs";
import { sleep } from "./lib/utils.mjs";
import { sendPermanentMessage } from "./lib/permanent.mjs";
const {
telegramToken,
chatId,
watch = [],
etherscanSleepMs = 5000, // 5 seconds
} = await readConfig();
const TXS_PER_MESSAGE = 16;
const setStatusMessage = sendPermanentMessage(telegramToken, chatId);
console.log(`${pkg.name} (v${pkg.version}) is listening for new transactions and sending messages to ${chatId}`);
while (true) {
const newTxs = await Promise.all(Object.entries(watch).map(async ([etherscan, { apiKey, accounts }]) => {
const ignoreFile = `${etherscan}.ignore.txt`;
const ignoreFileExists = existsSync(ignoreFile);
const ignoreHashes = ignoreFileExists ? (await readFile(ignoreFile, "ascii")).split("\n").map(line => line.trim()) : [];
const txs = [];
for (const account of accounts) {
try {
const result = await getTokenTx(etherscan, {
apiKey,
offset: ignoreFileExists ? "50" : "10000",
...account
});
const newTxs = result.filter(({ hash }) => !ignoreHashes.includes(hash.toLowerCase()));
console.log(`Got ${newTxs.length} new transactions for ${formatAccountUrl(etherscan, account)}`);
txs.push(...newTxs);
} catch (error) {
console.error("Watch error", error);
sendMessage(telegramToken, chatId, formatError(etherscan)).catch(error => console.log(`Cannot send error message ${error}`));
}
await sleep(etherscanSleepMs);
}
return { etherscan, txs, ignoreFile, ignoreFileExists };
}));
for (const { etherscan, txs, ignoreFile, ignoreFileExists } of newTxs) {
if (txs.length === 0) continue;
if (ignoreFileExists) {
for (let page = 0; page < txs.length / TXS_PER_MESSAGE; page++) {
const messageTxs = txs.slice(page * TXS_PER_MESSAGE, (page + 1) * TXS_PER_MESSAGE);
await sendMessage(telegramToken, chatId, formatNewTxs(messageTxs, etherscan));
}
}
await appendFile(ignoreFile, txs.map(({ hash }) => hash.toLowerCase()).join('\n') + '\n', "ascii");
}
setStatusMessage(formatStatus(watch, pkg));
}