-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.js
698 lines (621 loc) · 28.2 KB
/
bot.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//
// Garlicoin Discord Bot
// A bot written for NodeJS to compliment a Garlicoin cryptocurrency Discord server
// https://github.com/Beguiled/GarlicoinDiscordBot
//
// Created by Jason Egan (beguil3d#2285)
// Version 1.0
// Changelog
// 2018/04/23 Version 1.0 - Initial Release
let BOT_VERSION = "1.0";
// Define Discord objects
let Discord = require("discord.js");
let discordClient = new Discord.Client();
// Define helper objects
let http = require('http');
let https = require('https');
let fs = require('fs');
// JSON data storage objects
let config = require("./config.json");
let members = require("./members.json");
// Data object declarations
let jsonStats = {};
let latestPoolVelocity = [0, 0, 0, 0, 0, 0];
let latestPoolBlockData = [0, 0, 0];
let latestBlockHeight = 0;
let latestConfirmed = 0;
let botAdminRoles = [];
// Define start up timestamp (mainly for logging)
// We can then store all logging output to a timestamped log file which is helpful in case the script must be restarted
let startup = new Date();
let logFile = './logs/' + startup.toISOString().replace(/T|Z|-|:/gi, '').substr(0, 14) + '.log';
// Announce start up
consoleLog(`Garlicoin Discord Bot version ${BOT_VERSION} starting up...`);
consoleLog('Visit https://github.com/Beguiled/GarlicoinDiscordBot for help and updates');
// Discord Client "ready" event
discordClient.on("ready", () => {
// Set the username to the configured name in config.json
consoleLog(`Setting bot name to ${config.name}`);
discordClient.user.setUsername(config.name);
// Populate the botAdminRoles array
consoleLog(`Setting admin roles to ${config.bot_admin_roles}`);
botAdminRoles = config.bot_admin_roles.split(",");
// Poll the pool's API for the stats JSON data, then update the poolBlockData array
consoleLog(`Getting initial pool API data`);
getJsonStats().then(result => getPoolBlockData());
// Set the default activity to 'watching Garlicoin'
discordClient.user.setActivity(`Garlicoin | ${config.prefix}help`, {
type: 'WATCHING'
}).catch(O_o => {});
consoleLog(`Listening for commands with prefix ${config.prefix}`);
// Announce start up is complete
consoleLog(`${config.name} online`);
});
// Discord Client "guildMemberAdd" event
// Welcome the new member to your server!
discordClient.on("guildMemberAdd", member => {
let guild = member.guild;
guild.defaultChannel.send(`Welcome ${member.user} to the ${config.server_name} server! Use \`${config.prefix}help\` to see what commands are available for you to use.`).catch(function (error) {
consoleLog(`Error encountered in guildMemberAdd event:\r\n${error}`)
});
});
// Discord Client "message" event
// This parses any incoming messages to determine if the bot needs to respond
discordClient.on("message", message => {
// Ignore the message if it has been generated by a bot
if (message.author.bot) return;
// Ignore the message if the prefix does not exist
if (message.content.indexOf(config.prefix) !== 0) return;
// Store the message author for ease of reference later
let messageSender = message.member.user;
// Define the member in the members JSON object if they haven't been seen yet
// This will avoid issues when querying data points that are not yet defined
if (!members[messageSender.id])
members[messageSender.id] = {};
// Split the message into an array of arguments and set the first element as the command
let args = message.content.slice(config.prefix.length).trim().split(/ +/g);
let command = args.shift().toLowerCase();
// Determine if the user is in a role defined in the "bot_admin_roles" declaration to allow for admin commands
let isAdmin = false;
for (var i = 0; i < botAdminRoles.length; i++) {
if (message.member.roles.find("name", botAdminRoles[i])) isAdmin = true;
}
// Bot Admin Commands
if (isAdmin) {
if (command === "echo") {
// Delete the command message
message.delete().catch(O_o => {});
// Echo the message
let msg = args.join(" ");
sendReply(message, msg);
} else if (command === "broadcast") {
// Delete the command message
message.delete().catch(O_o => {});
// Broadcast the message
let msg = args.join(" ");
broadcast(msg);
} else if (command === "save") {
// Execute saveAll
saveAll();
// Notify the message author of the completion of the task
let messageAuthor = message.author;
messageAuthor.send("All configurations have been saved.");
// Delete the command message
message.delete().catch(O_o => {});
}
}
// General Commands
if (command === "help") {
// Display the list of available commands
// -- Example of how commands should display --
// Member Commands
//```\n
//me : View your details\n
//register : Set your wallet address\n
//notify : Receive block notifications\n
//```
// Pool Commands
//```\n
//block : Pool block data\n
//poolstats : Pool statistics\n
//velocity : Pool solve velocity\n
//workers : List of current pool workers\n
//```
// Market Data
//```
//cap : Garlicoin market cap\n
//market : Current crypto market data\n
//```
let msg = `${messageSender}, here are my available commands:\n`;
let embed = {
"color": 11510597,
"fields": [
{
"name": "Member Commands",
"value": "```\nme : View your details\nregister : Set or clear your wallet address\nnotify : Receive block notifications\n```"
},
{
"name": "Pool Commands",
"value": "```\nblock : Pool block data\npoolstats : Pool statistics\nvelocity : Pool solve velocity\nworkers : List of current pool workers\n```"
},
{
"name": "Market Data",
"value": "```\ncap : Garlicoin market cap\nmarket : Current crypto market data\n```"
}
]
};
message.channel.send(msg, {
embed
});
} else if (command === "block" || command === "blocks") {
// Display current pool block data
let msg = '';
msg += '```ml\n';
msg += `Confirmed : ${latestPoolBlockData[0]}\n`;
msg += `Pending : ${latestPoolBlockData[1]}\n`;
msg += `Orphaned : ${latestPoolBlockData[2]}\n`;
msg += '```';
sendReply(message, msg);
} else if (command === "cap") {
// Display market cap data for Garlicoin via CoinMarketCap
getCoinData("garlicoin").then(result => {
let priceUSD = result[0]["price_usd"];
let vol24h = result[0]["24h_volume_usd"];
let chg24h = result[0]["percent_change_24h"];
let mktCap = result[0]["market_cap_usd"];
let supply = result[0]["available_supply"];
let msg = '';
msg += '```md\n';
msg += ' Market Cap Data\n';
msg += '------------------------\n';
msg += `Price : ${priceUSD} USD\n`;
msg += `24h Vol : ${vol24h} USD\n`;
msg += `24h Chg : ${Number(chg24h) > 0 ? '+' : ''}${chg24h}%\n`;
msg += `Mkt Cap : ${Number(mktCap).toFixed(2)} USD\n`;
msg += `Supply : ${supply} GRLC\n`;
msg += '```';
sendReply(message, msg);
});
} else if (command === "market") {
// Display market data pulled from CoinMarketCap
let coins = ["bitcoin", "bitcoin-cash", "ethereum", "ripple", "litecoin", "nano", "ravencoin", "garlicoin"];
let combinedResult = [];
Promise.all(coins.map(coin => getCoinData(coin)))
.then((combinedResult) => {
let msg = '';
msg += '\`\`\`asciidoc\n';
msg += ' Current Cryptocurrency Market Data (via CoinMarketCap)\n';
msg += '----------------------------------------------------------------\n';
msg += ' Coin Value (USD) 1hr | 24hr | 7d | Mkt Cap \n';
for (let i = 0; i < coins.length; i++) {
let coinData = combinedResult[i][0];
let price = Number.parseFloat(coinData.price_usd).toFixed(coinData.price_usd < 10 ? 4 : 2).padStart(7, " ");
let change1h = Number.parseFloat(coinData.percent_change_1h).toFixed(2);
let change24h = Number.parseFloat(coinData.percent_change_24h).toFixed(2);
let change7d = Number.parseFloat(coinData.percent_change_7d).toFixed(2);
let mktcap = Number.parseFloat(coinData.market_cap_usd);
let denom = "";
if (mktcap > 1000000000) {
denom = "B";
mktcap = mktcap / 1000000000;
}
if (mktcap > 1000000) {
denom = "M";
mktcap = mktcap / 1000000;
}
if (mktcap > 1000) {
denom = "K";
mktcap = mktcap / 1000;
}
mktcap = mktcap.toFixed(2); //.padStart(6, " ");
if (Number(change1h) > 0) change1h = "+" + change1h;
if (Number(change24h) > 0) change24h = "+" + change24h;
if (Number(change7d) > 0) change7d = "+" + change7d;
change1h = change1h.padStart(7, " ");
change24h = change24h.padStart(7, " ");
change7d = change7d.padStart(7, " ");
mktcap = mktcap.padStart(7, " ");
msg += ` ${coinData.symbol.padEnd(9, " ")}`;
msg += `$ ${price}`;
msg += ` `;
msg += `${change1h}%`;
msg += ` | `;
msg += `${change24h}%`;
msg += ` | `;
msg += `${change7d}%`;
msg += ` | `;
msg += `${mktcap}${denom}`;
msg += `\n`;
}
msg += '\`\`\`';
sendReply(message, msg);
});
} else if (command === "me") {
// Display the user's current pool details (if they've used register to define their wallet address)
// If the definition does not exist, create it as an empty value
if (!members[messageSender.id].wallet)
members[messageSender.id].wallet = "";
let msg = '';
if (members[messageSender.id].wallet > "") {
let walletID = members[messageSender.id].wallet;
let workerNode = jsonStats.pools.garlicoin.workers[walletID];
let payout = calculatePayout(workerNode.hashrateString);
msg = '';
msg += '```';
msg += `Address : ${walletID}\n`;
msg += `Hashrate : ${workerNode.hashrateString}\n`
msg += `Est Payout : ${payout}\n`;
msg += '```';
} else {
// User has not set their wallet address yet - instruct them on how to do so
msg = `${messageSender} you have not defined your wallet address yet. Please use \`${config.prefix}register [wallet]\` to do so.`;
}
sendReply(message, msg);
} else if (command === "notify") {
// Allow members to set a notification preference for when blocks are solved and confirmed
// If member is not yet defined in members.json, create it
// If the definition does not exist, create it as an empty value (aka "off")
if (!members[messageSender.id].block_notify)
members[messageSender.id].block_notify = "";
let msg = '';
if (args[0] === "on") {
members[messageSender.id].block_notify = "on";
msg += `${messageSender}, you will be notified when blocks are solved or confirmed.`;
saveMembers("Member notification setting updated");
} else if (args[0] === "off") {
members[messageSender.id].block_notify = "";
msg += `${messageSender}, you will not be notified when blocks are solved or confirmed.`;
saveMembers("Member notification setting updated");
} else {
let setting = members[messageSender.id].block_notify == "on" ? "`on`" : "`off`";
msg += `${messageSender} your notification setting is currently ${setting}. You can change it by using \`${config.prefix}notify [on|off]\``;
}
sendReply(message, msg);
} else if (command === "poolstats") {
// Display a general list of pool statistics
let msg = '';
msg += '```ml\n';
msg += 'Blocks\n'
msg += ` Confirmed : ${jsonStats.pools.garlicoin.blocks.confirmed}\n`;
msg += ` Pending : ${jsonStats.pools.garlicoin.blocks.pending}\n`;
msg += ` Orphaned : ${jsonStats.pools.garlicoin.blocks.orphaned}\n`;
msg += 'Workers\n';
msg += ` Count : ${jsonStats.algos.allium.workers}\n`;
msg += ` Hashrate : ${jsonStats.algos.allium.hashrateString}\n`;
msg += 'Shares\n';
msg += ` Valid : ${jsonStats.pools.garlicoin.poolStats.validShares}\n`;
msg += ` Invalid : ${jsonStats.pools.garlicoin.poolStats.invalidShares}\n`;
msg += ` Total Paid : ${precisionRound(jsonStats.pools.garlicoin.poolStats.totalPaid, 5)} GRLC\n`;
msg += '```';
sendReply(message, msg);
} else if (command === "register") {
// Allow the member to set their wallet address
// If member is not yet defined in members.json, create it
if (!members[messageSender.id])
members[messageSender.id] = {};
let msg = '';
if (args.length == 0) {
msg += `${messageSender}, the correct format for this command is:\n`;
msg += '```\n';
msg += `${config.prefix}register [wallet] : Set your wallet address\n`;
msg += `${config.prefix}register forget : Remove your wallet address\n`;
msg += '```\n';
} else if (args[0] == "forget") {
members[messageSender.id].wallet = "";
msg = `${messageSender}, your stored wallet data has been cleared.`;
saveMembers("Member wallet data updated");
} else {
msg = `${messageSender}, your wallet has been set to: \`${args[0]}\``;
members[messageSender.id].wallet = args[0];
saveMembers("Member wallet data updated");
}
sendReply(message, msg);
} else if (command === "velocity") {
// Display the current pool block solve velocity (usually only good for up to about 12 hours of data from the API)
getVelocity().then(function (result) {
let count1 = result[0].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count6 = result[1].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count12 = result[2].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count24 = result[3].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count48 = result[4].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count168 = result[5].toFixed(2).padStart(6, " ").padEnd(7, " ");
let count1v = Number(count1).toFixed(2).padStart(6, " ").padEnd(8, " ");
let count6v = (Number(count6) / 6).toFixed(2).padStart(6, " ").padEnd(8, " ");
let count12v = (Number(count12) / 12).toFixed(2).padStart(6, " ").padEnd(8, " ");
let count24v = (Number(count24) / 24).toFixed(2).padStart(6, " ").padEnd(8, " ");
let count48v = (Number(count48) / 48).toFixed(2).padStart(6, " ").padEnd(8, " ");
let count168v = (Number(count168) / 168).toFixed(2).padStart(6, " ").padEnd(8, " ");
// Build the message output
// Always show the periods of last 1 and 6 hours
// Only show 12+ hours if data exists
let msg = '';
msg += '```prolog\n';
msg += `+-------------------------+\n`;
msg += `| Period | Count | Hourly |\n`;
msg += `+-------------------------+\n`;
msg += `| 1hr |${count1}|${count1v}|\n`;
msg += `| 6hr |${count6}|${count6v}|\n`;
if (count12v > 0) msg += `| 12hr |${count12}|${count12v}|\n`;
if (count24v > 0) msg += `| 24hr |${count24}|${count24v}|\n`;
if (count48v > 0) msg += `| 48hr |${count48}|${count48v}|\n`;
if (count168v > 0) msg += `| 7day |${count168}|${count168v}|\n`;
msg += `+-------------------------+\n`;
msg += '```';
sendReply(message, msg);
}, function (err) {
consoleLog(err);
});
} else if (command === "workers") {
// Display the list of workers currently mining and their hashrate
let msg = '';
let workers = jsonStats.pools.garlicoin.workers;
let workerArray = [];
let idx = 0;
Object.keys(workers).forEach(worker => {
let w = {
wallet: worker,
hashInt: getHashInt(workers[worker].hashrateString)
};
workerArray[idx] = w;
idx++;
});
// Sort from highest to lowest hashrate
workerArray.sort(function (a, b) {
return a.hashInt - b.hashInt
}).reverse();
// Display list
let padStart = 1;
if (workerArray.length >= 10) padStart++;
if (workerArray.length >= 100) padStart++;
msg += '```cpp\n';
msg += `${jsonStats.algos.allium.workers.toString().padStart(4 + padStart)} miners -- ${jsonStats.algos.allium.hashrateString}\n`;
for (let i = 0; i < workerArray.length; i++) {
let wallet = workerArray[i].wallet;
msg += `${(i + 1).toString().padStart(padStart)} ${wallet.substr(0,6)}...${wallet.substr(-4)} ${workers[wallet].hashrateString.padStart(9)}\n`;
}
msg += '```';
sendReply(message, msg);
} else {
// Do nothing
}
}); // END MESSAGE HANDLER
// Helpers
//////////
// Write out to the console (and log file)
function consoleLog(text) {
let str = `[${timeStamp()}] ${text}`;
console.log(str);
fs.appendFile(logFile, `${str}\r\n`, function (err) {
// if (err) throw err;
});
}
// A simple rounding function
function precisionRound(number, precision) {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
// Return the current timestamp in YYYYMMDD HHMMSS format
function timeStamp() {
let now = new Date();
let date = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
let time = [now.getHours(), now.getMinutes(), now.getSeconds()];
// If less than 10, add a zero
if (date[1] < 10)
date[1] = "0" + date[1];
for (let i = 0; i < 3; i++) {
if (time[i] < 10) {
time[i] = "0" + time[i];
}
}
return date.join("") + " " + time.join(":");
}
// Write data to the selected file
function writeToFile(file, data) {
let fs = require('fs');
fs.writeFile(file, data, 'utf8', function (err) {
if (err)
consoleLog(`Error attempting to write out ${file}\n${err}`);
});
}
// Reply to an incoming message with given text
function sendReply(message, text) {
message.channel.send(text).catch(function (error) {
consoleLog(`Error encountered in sendReply\r\n${e}`)
});
}
// A simple "Under Development" style message to prepend any new functionality
// Note: this may never be used
function underDevelopment(message) {
sendReply(message, "\`This functionality is under development.\`");
}
// Query the CoinMarketCap API for the provided coin's value
function getCoinData(coin) {
return new Promise(function (resolve, reject) {
let url = `https://api.coinmarketcap.com/v1/ticker/${coin}/`;
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(JSON.parse(data));
}).on('error', (e) => {
reject(e);
});
});
});
}
// Query the pool's API for stats data
function getJsonStats() {
return new Promise(function (resolve, reject) {
let url = `${config.pool_api_url}/stats`;
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
let json = JSON.parse(data);
jsonStats = json;
resolve(jsonStats);
} catch (e) {
resolve(jsonStats);
}
}).on('error', (e) => {
consoleLog(`Error in getJsonStats\n${e}`);
resolve(jsonStats);
});
});
});
}
// Calculate the current block solve velocity for the pool
function getVelocity() {
// NOMP codebase
if (config.pool_codebase.toLowerCase() === 'nomp') {
return new Promise(function (resolve, reject) {
let url = `${config.pool_api_url}/pool_stats`;
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
let json = JSON.parse(data);
let result = [0, 0, 0, 0, 0, 0];
let dateStampNow = new Date();
let blockHeight = 0;
let oldest_data_point = 0;
for (let i = 0; i < json.length; i++) {
let dateStamp = new Date(json[i].time * 1000);
let ticksPerHour = 3600000;
let timeDiff = (dateStampNow - dateStamp) / ticksPerHour;
if (oldest_data_point == 0)
oldest_data_point = Math.ceil(timeDiff); // Determine how many hours ago the oldest data point is
let pendingBlocks = json[i].pools.garlicoin.blocks.pending;
let confirmedBlocks = json[i].pools.garlicoin.blocks.confirmed;
curBlockHeight = Number(pendingBlocks) + Number(confirmedBlocks);
if (curBlockHeight > blockHeight) {
pendBlock = pendingBlocks;
confBlock = confirmedBlocks;
blockHeight = curBlockHeight;
if (timeDiff <= 1) result[0] = Number(result[0]) + 1; // 1hr
if (timeDiff <= 6) result[1] = Number(result[1]) + 1; // 6hr
if (timeDiff <= 12) result[2] = Number(result[2]) + 1; // 12hr
if (timeDiff <= 24) result[3] = Number(result[3]) + 1; // 24hr
if (timeDiff <= 48) result[4] = Number(result[4]) + 1; // 48hr
if (timeDiff <= 168) result[5] = Number(result[5]) + 1; // 7day
}
}
// Zero out any data points "older" than oldest_data_point to avoid them being displayed
if (oldest_data_point < 168)
result[5] = 0;
if (oldest_data_point < 48)
result[4] = 0;
if (oldest_data_point < 24)
result[3] = 0;
if (oldest_data_point < 12)
result[2] = 0;
if (oldest_data_point < 6)
result[1] = 0;
latestPoolVelocity = result;
resolve(result);
} catch (e) {
consoleLog(`Exception in getVelocity\r\n${e}`);
resolve(latestPoolVelocity);
}
}).on('error', (e) => {
consoleLog(`Error in getVelocity\r\n${e}`);
resolve(latestPoolVelocity);
});
});
});
}
return [0, 0, 0, 0, 0, 0];
}
// Set the current Hash Rate and Miner Count as the bot's activity
function setHashRateActivity() {
let activity = `${jsonStats.algos.allium.hashrateString} | ${jsonStats.algos.allium.workers} mining | ${config.prefix}help`;
discordClient.user.setActivity(activity, {
type: 'WATCHING'
}).catch(O_o => {});
}
// Check for any changes in the pool block data and broadcast notifications if something has changed
function getPoolBlockData() {
let blockNode = jsonStats.pools.garlicoin.blocks;
let msg = '';
if (blockNode.confirmed + blockNode.pending > latestBlockHeight && latestBlockHeight > 0) {
consoleLog(`New block solved: #${blockNode.confirmed + blockNode.pending} (${blockNode.confirmed} confirmed, ${blockNode.pending} pending)`);
msg += '```css\n';
msg += `We solved a block! (#${blockNode.confirmed + blockNode.pending})\n`;
msg += `${blockNode.confirmed} confirmed, ${blockNode.pending} pending\n`;
msg += '```';
}
if (blockNode.confirmed > latestConfirmed && latestConfirmed > 0) {
consoleLog(`Block confirmed: #${blockNode.confirmed} (${blockNode.confirmed} confirmed, ${blockNode.pending} pending)`);
msg += '```css\n';
msg += `Block #${blockNode.confirmed} has been confirmed!\n`;
msg += `${blockNode.confirmed} confirmed, ${blockNode.pending} pending\n`;
msg += '```';
}
if (msg.length > 0) {
broadcast(msg);
msg = '';
// Add any notifications for members seeking mentions
Object.keys(members).forEach(member => {
if (members[member].block_notify === "on")
msg += `<@${member}> `;
});
if (msg.length > 0)
broadcast(msg);
}
latestPoolBlockData = [blockNode.confirmed, blockNode.pending, blockNode.orphaned];
latestBlockHeight = blockNode.confirmed + blockNode.pending;
latestConfirmed = blockNode.confirmed;
}
// Broadcasts message to all channels in the channels
function broadcast(message) {
if (message.length == 0) return;
discordClient.channels.forEach(function (chan) {
if (chan.type === "text") {
chan.send(message).catch(O_o => {}); // Catch to avoid logging channel permission issues
}
});
}
// Determine the amount being paid out
// Note: This is nowhere near an exact value. It bases the result on the current pool hash rate which can fluctuate
// greatly based on the number of workers are involved. Ultimately this result is much closer in larger pools.
// The API does not surface the current submitted share data so we have to do a best guess based on hash rate reports.
function calculatePayout(hashrateString) {
return precisionRound(getHashInt(hashrateString) / parseFloat(jsonStats.algos.allium.hashrate) * 50, 5) + " GRLC";
}
// Convert a hashrateString into an int representing hashes per second
function getHashInt(hashrateString) {
let workerHashrate = parseFloat(hashrateString);
let hashSize = hashrateString.substr(hashrateString.length - 2, 2);
if (hashSize === "KH") workerHashrate *= 1000;
if (hashSize === "MH") workerHashrate *= 1000000;
return workerHashrate;
}
// Saves
//////////
function saveAll() {
saveConfig();
saveMembers();
}
function saveConfig() {
consoleLog('Writing config to config.json');
writeToFile('./config.json', JSON.stringify(config));
}
function saveMembers(reason) {
consoleLog('Writing members to members.json');
if (reason > "") consoleLog(`Reason: ${reason}`);
writeToFile('./members.json', JSON.stringify(members));
}
// Activate any timer-based functions
setInterval(getJsonStats, 5000);
setInterval(getPoolBlockData, 2500);
setInterval(setHashRateActivity, 5000);
// Log in to Discord to be present online
discordClient.login(config.token);