-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
1475 lines (1291 loc) · 56.7 KB
/
app.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var hive = require('@hiveio/hive-js');
const { MongoClient, MongoTopologyClosedError } = require('mongodb');
const fetch = require('node-fetch');
const { Webhook, MessageBuilder } = require('discord-webhook-node');
require('dotenv').config();
var seedrandom = require('seedrandom');
//connect to Webhook using retry on limit
const hook = new Webhook(process.env.DISCORD_WEBHOOK);
//seciondary webhook for registrations
const hook2 = new Webhook(process.env.DISCORD_WEBHOOK_2);
//hook for quest completions
const hook3 = new Webhook(process.env.DISCORD_WEBHOOK_3);
const dbName = 'terracore';
const SYMBOL = 'SCRAP';
const wif = process.env.ACTIVE_KEY;
var client = new MongoClient(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, connectTimeoutMS: 30000, serverSelectionTimeoutMS: 30000 });
const db = client.db(dbName);
const nodes = ['https://api.deathwing.me', 'https://api.hive.blog', 'https://hived.emre.sh', 'https://api.openhive.network', 'https://techcoderx.com', 'https://hive-api.arcange.eu'];
async function getLastUsedEndpoint() {
const db = client.db(dbName);
const collection = db.collection('lastUsedEndpoint');
const lastUsed = await collection.findOne({}, { sort: { _id: -1 } });
return lastUsed ? lastUsed.endpoint : null;
}
async function updateLastUsedEndpoint(endpoint) {
const db = client.db(dbName);
const collection = db.collection('lastUsedEndpoint');
await collection.insertOne({ endpoint: endpoint, timestamp: new Date() });
}
async function testNodeEndpoints(nodes) {
let fastestEndpoint = '';
let fastestResponseTime = Infinity;
const lastUsedEndpoint = await getLastUsedEndpoint();
let endpointsToTest = nodes.filter(endpoint => endpoint !== lastUsedEndpoint);
for (const endpoint of endpointsToTest) {
const startTime = Date.now();
try {
const response = await fetch(endpoint, {
method: 'POST',
body: JSON.stringify({
jsonrpc: "2.0",
method: "condenser_api.get_dynamic_global_properties",
params: [],
id: 1
}),
headers: { 'Content-Type': 'application/json' }
});
const result = await response.json();
if (response.ok) {
const responseTime = Date.now() - startTime;
console.log(`${endpoint}: ${responseTime}ms`);
if (responseTime < fastestResponseTime) {
fastestResponseTime = responseTime;
fastestEndpoint = endpoint;
}
} else {
throw new Error(`Response error: ${response.statusText}`);
}
} catch (error) {
console.log(`${endpoint} error: ${error.message}`);
}
}
if (fastestEndpoint) {
console.log(`Fastest endpoint: ${fastestEndpoint} (${fastestResponseTime}ms)`);
await updateLastUsedEndpoint(fastestEndpoint);
} else {
let remainingEndpoints = nodes.filter(endpoint => endpoint !== lastUsedEndpoint);
fastestEndpoint = remainingEndpoints[Math.floor(Math.random() * remainingEndpoints.length)];
console.log(`No fastest endpoint found. Randomly selected endpoint: ${fastestEndpoint}`);
await updateLastUsedEndpoint(fastestEndpoint);
}
hive.api.setOptions({ url: fastestEndpoint });
}
async function changeNode() {
(async () => {
await testNodeEndpoints(nodes);
})();
}
async function webhook(title, message, color) {
const embed = new MessageBuilder()
.setTitle(title)
.addField('Message: ', message, true)
.setColor(color)
.setTimestamp();
try {
hook.send(embed).catch(err => console.log(err.message));
}
catch (err) {
console.log(chalk.red("Discord Webhook Error"));
}
}
async function webhook2(title, message, color) {
let collection = db.collection('players');
let totalPlayers = await collection.countDocuments();
//from stats collection, find the total players registered today
collection = db.collection('stats');
let todaysPlayers = await collection.findOne({ date: new Date().toISOString().slice(0, 10) });
if (todaysPlayers) {
todaysPlayers = todaysPlayers.players;
} else {
todaysPlayers = 0;
}
const embed = new MessageBuilder()
.setTitle(title)
.addField('New Citizen: ', message, true)
.addField('Total Citizens: ', totalPlayers.toString(), true)
.addField('New Citizens Today: ', todaysPlayers.toString(), true)
.setColor(color)
.setTimestamp();
try {
hook2.send(embed).then(() => console.log('Sent webhook successfully!'))
.catch(err => console.log(err.message));
}
catch (err) {
console.log(chalk.red("Discord Webhook Error"));
}
}
async function webhook3(title, common, uncommon, rare, epic, legendary) {
//send embed to discord
const embed = new MessageBuilder()
.setTitle(title)
.addField('Common Relics: ', common, true)
.addField('Uncommon Relics: ', uncommon, false)
.addField('Rare Relics: ', rare, false)
.addField('Epic Relics: ', epic, false)
.addField('Legendary Relics: ', legendary, false)
.setColor('#00ff00')
.setTimestamp();
try {
hook3.send(embed).then(() => console.log('Sent webhook successfully!'))
.catch(err => console.log(err.message));
}
catch (err) {
console.log(chalk.red("Discord Webhook Error"));
}
}
async function webhook4(title, msg) {
//send embed to discord red color
const embed = new MessageBuilder()
.setTitle(title)
.addField('Message: ', msg, true)
.setColor('#ff0000')
.setTimestamp();
try {
hook3.send(embed).then(() => console.log('Sent webhook successfully!'))
.catch(err => console.log(err.message));
}
catch (err) {
console.log(chalk.red("Discord Webhook Error"));
}
}
//switch this to look at DB
async function scrapStaked(username) {
try{
let collection = db.collection('players');
//find the player
let player = await collection.findOne({ username: username });
if (player) {
return player.hiveEngineStake
} else {
return 0;
}
} catch (error) {
console.log(error);
}
}
//pay refferrer
async function payReferrer(referrer, username, amount) {
try {
console.log('Paying ' + referrer + ' for referring ' + username + ' ' + amount + ' HIVE');
const xfer = new Object();
xfer.from = "terracore";
xfer.to = referrer;
xfer.amount = amount;
xfer.memo = 'Here is your Refferal Bonus for inviting ' + username + ' to TerraCore!';
await hive.broadcast.transfer(wif, xfer.from, xfer.to, xfer.amount, xfer.memo, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
//add to referrer collection in DB to keep track of who referred who and how much they got paid
let collection = db.collection('referrers');
await collection.insertOne({referrer: referrer, username: username, amount: amount, time: Date.now()});
return;
} catch (error) {
console.log(error);
}
}
async function register(username, referrer, amount) {
try{
//cehck if amount == registration_fee in price_feed db
let registration_fee_query = await db.collection('price_feed').findOne({date: "global"});
let registration_fee = registration_fee_query.registration_fee;
let referrer_fee = registration_fee_query.referral_fee;
//remove HIVE from registration_fee string with 3 decimal places
registration_fee = parseFloat(registration_fee.split(' ')[0]).toFixed(3);
amount = parseFloat(amount.split(' ')[0]).toFixed(3);
console.log('Amount: ' + amount + ' Registration Fee: ' + registration_fee);
if (amount < registration_fee) {
console.log('Amount does not match registration fee');
//await refund(username, amount);
return false;
}
let collection = db.collection('players');
let user = await collection.findOne({ username: username });
if (user) {
console.log(username + ' already exists');
return false;
}
await collection.insertOne({username: username , favor: 0, scrap: 1, health: 10, damage: 10, defense: 10, engineering:1, cooldown: Date.now(), minerate: 0.0001, attacks: 3, lastregen: Date.now(), claims: 3, lastclaim: Date.now(), registrationTime: Date.now(), lastBattle: Date.now()});
console.log('New User ' + username + ' now registered');
collection = db.collection('stats');
const bulkOps = [
{
updateOne: {
filter: { date: 'global' },
update: { $inc: { players: 1 } }
}
},
{
updateOne: {
filter: { date: new Date().toISOString().slice(0, 10) },
update: { $inc: { players: 1 } },
upsert: true
}
}
];
// Perform the bulk operation
await collection.bulkWrite(bulkOps);
if (referrer != 'terracore' && referrer != username && referrer !== undefined) {
webhook2('A New Citizen of Terracore has Registered', username + ' was invited by ' + referrer, 0x00ff00);
payReferrer(referrer, username, referrer_fee);
}
else{
webhook2('A New Citizen of Terracore has Registered', username, 0x00ff00);
}
return true;
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return false;
}
}
}
//store hash in mongo collection that stores all regsitration hashes
async function storeRegistration(hash, username) {
try{
let collection = db.collection('registrations');
await collection.insertOne({hash: hash, username: username, time: Date.now()});
console.log('Hash ' + hash + ' stored');
return;
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return;
}
}
}
async function storeClaim(username, qty) {
try{
let collection = db.collection('claims');
await collection.insertOne({username: username, qty: qty, time: Date.now()});
return;
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return;
}
}
}
//create a function where you can send transactions to be queued to be sent
async function sendTransaction(username, type, target, blockId, trxId, hash) {
//create a que where new transactions are added and then sent in order 1 by 1
try{
let collection = db.collection('transactions');
let result = await collection.insertOne({username: username, type: type, target: target, blockId: blockId, trxId: trxId, hash: hash, time: Date.now()});
console.log('Transaction ' + result.insertedId + ' added to queue');
return;
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return;
}
}
}
//create a function that can be called to send all transactions in the queue
async function sendTransactions() {
try{
lastCheck = Date.now();
let collection = db.collection('transactions');
let transactions = await collection.find({})
.sort({ time: 1 })
.toArray()
//check if length of transactions is more than 25 change node if so
if(transactions.length > 25) {
changeNode();
}
//check if there are any transactions to send
if(transactions.length != 0) {
console.log('-------------------------------------------------------')
console.log('Sending ' + transactions.length + ' transactions');
console.log('-------------------------------------------------------')
for (let i = 0; i < transactions.length; i++) {
lastCheck = Date.now();
let transaction = transactions[i];
console.log('Sending ' + transaction.type + ' transaction ' + (i+ 1).toString() + ' of ' + transactions.length.toString());
if(transaction.type == 'claim') {
while(true){
//const result = await Promise.race([claim(transaction.username), timeout(5000)]);
const result = await claim(transaction.username);
if(result) {
let maxAttempts = 3;
let delay = 3000;
for (let i = 0; i < maxAttempts; i++) {
let clear = await collection.deleteOne({ _id: transaction._id });
if(clear.deletedCount == 1){
break;
}
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 1.2; // exponential backoff
}
}
break;
}
}
else if(transaction.type == 'battle') {
while(true){
var result2 = await battle(transaction.username, transaction.target, transaction.blockId, transaction.trxId, transaction.hash);
//const result2 = await Promise.race([battle(transaction.username, transaction.target, transaction.blockId, transaction.trxId, transaction.hash), timeout(3000)]);
if(result2) {
let maxAttempts = 3;
let delay = 3000;
for (let i = 0; i < maxAttempts; i++) {
let clear = await collection.deleteOne({ _id: transaction._id });
if(clear.deletedCount == 1){
break;
}
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 1.2; // exponential backoff
}
}
break;
}
}
else if(transaction.type == 'progress') {
await progressQuest(transaction.username, transaction.blockId, transaction.trxId);
await collection.deleteOne({ _id: transaction._id });
}
else if(transaction.type == 'complete') {
await completeQuest(transaction.username);
await collection.deleteOne({ _id: transaction._id });
}
}
console.log('Completed Sending Transactions');
return true;
}
else {
return true;
}
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return true;
}
}
}
//call send transactions and wait for it to return true then call check transactions
async function checkTransactions() {
try{
//check if there are any transactions in the queue, if no return in 3 seconds kill the process
let done = await sendTransactions();
if(done) {
setTimeout(checkTransactions, 200);
}
}
catch (err) {
client.close();
process.exit(1);
}
}
async function performUpdate(collection, username, user) {
while (true) {
const updateResult = await collection.findOneAndUpdate(
{ username, claims: { $gt: 0 }, lastPayout: { $lt: Date.now() - 30000 } },
{
$set: { scrap: 0, claims: user.claims - 1, lastPayout: Date.now() },
$inc: { version: 1 }
},
{ returnOriginal: false }
);
if (updateResult.value) {
return true; // Successful update
}
}
}
//claim favorcheckDodge
async function claim(username) {
try {
const collection = db.collection('players');
const user = await collection.findOne({ username });
if (!user) {
console.log('User ' + username + ' does not exist');
return true;
}
if (user.claims === 0) {
console.log('User ' + username + ' has no claims left');
return true;
}
//check if user.lastPayout exists if not add it to the user object
if (!user.lastPayout) {
await collection.updateOne({ username }, { $set: { lastPayout: Date.now() - 60000 } });
}
if ((Date.now() - user.lastPayout) < 30000) {
return true;
}
const qty = user.scrap.toFixed(8);
const data = {
contractName: 'tokens',
contractAction: 'issue',
contractPayload: {
symbol: 'SCRAP',
to: username,
quantity: qty.toString(),
memo: 'terracore_claim_mint'
}
};
const claimSuccess = await hive.broadcast.customJsonAsync(wif, ['terracore'], [], 'ssc-mainnet-hive', JSON.stringify(data));
if (!claimSuccess) {
await collection.insertOne({username: username, qty: 'failed', time: Date.now()});
return true;
}
await performUpdate(collection, username, user);
await storeClaim(username, qty);
webhook("Scrap Claimed", `${username} claimed ${qty} SCRAP`, '#6130ff');
return true;
} catch (err) {
if (err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
//webhook("Error", `Error claiming scrap for user ${username}. Error: ${err}`, '#ff0000');
return false;
}
}
//battle function
async function battle(username, _target, blockId, trxId, hash) {
try{
if(username == _target) {
console.log('Error : Battle User: ' + username + ' tried to battle themselves');
return true;
}
var collection = db.collection('players');
var result = await collection.find({
$or: [
{ username: username },
{ username: _target }
]
}).toArray();
var user = result.find(entry => entry.username === username);
var target = result.find(entry => entry.username === _target);
if (!user) {
console.log('User ' + username + ' does not exist');
return true;
}
if (!target) {
console.log('Target ' + target + ' does not exist');
return true;
}
//check if target.registrationTime exists
if (target.registrationTime) {
//check if target registrationTime is less than 24 hours ago
if (Date.now() - target.registrationTime < 86400000) {
//send webhook stating target is has new user protection inc version
await collection.updateOne({ username: username }, { $inc: { attacks: -1 , version: 1 } });
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, dodged:false, timestamp: Date.now()});
webhook("New User Protection", "User " + username + " tried to attack " + _target + " but they have new user protection", '#ff6eaf')
return true;
}
}
//check if target.consumable.protection > 0
if (target.consumables.protection > 0) {
//take the first timestamp of the protection array and check if it is less than 24 hours ago
if (Date.now() - target.consumables.protection_times[0] < 86400000) {
//send webhook stating target is has protection inc version
await collection.updateOne({ username: username }, { $inc: { attacks: -1 , version: 1 } });
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, dodged:false, timestamp: Date.now()});
webhook("Protection Potion Active!", "User " + username + " tried to attack " + _target + " but they have protection", '#ff6eaf')
return true;
}
}
//check if target.lastBattle does not exist
if (!target.lastBattle) {
//set to now - 60 seconds
target.lastBattle = Date.now() - 60000;
//inv version
await collection.updateOne({ username: _target }, { $set: { lastBattle: target.lastBattle }, $inc: { version: 1 } });
}
//make sure target is not getting attacked withing 60 seconds of last payout
if (Date.now() - target.lastBattle < 60000) {
await collection.updateOne({ username: username }, { $inc: { attacks: -1 , version: 1 } });
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, dodged:false, timestamp: Date.now()});
//webhook("Unable to attack target", "User " + username + " tried to attack " + _target + " but they are not back at the base yet...", '#ff6eaf')
return true;
}
//check if user has more damage than target defense and attacks > 0 and has defense > 10 or if consumables.focus > 0
if (user.stats.damage > target.stats.defense && user.attacks > 0 || user.consumables.focus > 0 && user.attacks > 0) {
//check the amount of scrap users has staked
var staked = await scrapStaked(username);
var seed = await createSeed(blockId, trxId, hash);
var roll = await rollAttack(user, seed);
var scrapToSteal = target.scrap * (roll / 100);
//give target a chance to ddodge based on toughness
if (checkDodge(target) && user.consumables.focus == 0) {
//send webhook stating target dodged attack
await collection.updateOne({ username: username }, { $inc: { attacks: -1 , version: 1 } });
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, seed: seed, roll: roll, dodged:true, timestamp: Date.now()});
webhook("Attack Dodged", "User " + username + " tried to attack " + _target + " but they dodged the attack", '#ff6eaf')
return true;
}
//check if user has focus if so remove it as it is used for this attack
if (user.consumables.focus > 0) {
await collection.updateOne({ username: username }, { $inc: { 'consumables.focus': -1 , version: 1 } });
}
//check if scrap to steal is more than target scrap if so set scrap to steal to target scrap
if (scrapToSteal > target.scrap) {
scrapToSteal = target.scrap;
}
//check if current scrap of user + scrap to steal is more than staked scrap
if (user.scrap + scrapToSteal > staked + 1) {
scrapToSteal = (staked + 1) - user.scrap;
}
//make sure scrapToSteal is not NaN
if (isNaN(scrapToSteal)) {
//shoot error webhook
webhook("New Error", "User " + username + " tried to attack " + _target + " but scrapToSteal is NaN, please try again", '#6385ff')
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, dodged:false, timestamp: Date.now()});
return true;
}
//make sure scrapToSteal is not less than 0
if (scrapToSteal <= 0) {
//shoot error webhook
webhook("New Error", "User " + username + " tried to attack " + _target + " but scrapToSteal is less than or = 0, please try again", '#6385ff')
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: 0, dodged:false, timestamp: Date.now()});
return true;
}
try{
let newScrap = user.scrap + scrapToSteal;
let newTargetScrap = target.scrap - scrapToSteal;
let newAttacks = user.attacks - 1;
//modify target scrap & add to user scrap
let maxAttempts = 3;
let delay = 700;
for (let i = 0; i < maxAttempts; i++) {
//inc versions update lastClaim for t
const bulkOps = [
{ updateOne: { filter: { username: _target }, update: { $set: { scrap: newTargetScrap }, $inc: { version: 1 } } } },
{ updateOne: { filter: { username: username }, update: { $set: { scrap: newScrap, attacks: newAttacks, lastBattle: Date.now() } , $inc: { version: 1 } } } }
];
const result = await collection.bulkWrite(bulkOps);
//check if update was successful frim above result
if (result.modifiedCount == 2) {
await db.collection('battle_logs').insertOne({username: username, attacked: _target, scrap: scrapToSteal, seed: seed, roll: roll, timestamp: Date.now()});
webhook("New Battle Log", 'User ' + username + ' stole ' + scrapToSteal.toString() + ' scrap from ' + _target + ' with a ' + roll.toFixed(2).toString() + '% roll chance', '#f55a42');
return true;
}
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 1.2; // exponential backoff
}
//if we get here then we failed to update the database return
return true;
}
catch (e) {
//send webhook with red color
webhook("New Error", " Error: " + e, '#6385ff');
return true;
}
}
else {
return true;
}
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
webhook("New Error", " Line: 681 Error: " + err, '#6385ff');
return true;
}
}
}
function checkDodge(_target) {
// Check if attack is dodged
var roll = Math.floor(Math.random() * 100) + 1;
if (roll < _target.stats.dodge) {
return true;
}
else {
return false;
}
}
function rollAttack(_player, seed) {
var rng = seedrandom(seed);
var roll = rng();
// Generate a random number let steal = Math.floor(Math.random() * (100 - _player.stats.crit + 1)) + _player.stats.crit; //dont floor
var steal = roll * (100 - _player.stats.crit + 1) + _player.stats.crit;
if (steal > 100) {
steal = 100;
}
return steal;
}
////////////////////////////////////////////////////
////////////
/////////// Quest Functions
//////////
///////////////////////////////////////////////////
//function to create a seed from blockId & trxId to make verifiable random number using the Hive blockchain
async function createSeed(blockId, trxId, hash) {
//create seed from blockId & trxId
var seed = blockId + '@' + trxId + '@' + hash;
//return seed
return seed;
}
async function rollDice(index, seed = null) {
//if there is a seed value then use it to generate a random number
if (seed !== null) {
const rng = seedrandom(seed.toString(), {state: true});
//roll a number using rng that can be reproduced using the seed
const result = rng() * (index - 0.01 * index) + 0.01 * index;
return result;
}
const result = Math.random() * (index - 0.01 * index) + 0.01 * index;
return result;
}
async function progressQuest(username, blockId, trxId) {
//check if user has a quest already
//if so return false else insert quest into active-quests collection
try{
//check if user is in active-quests collection
let collection = db.collection('active-quests');
let quest = await collection.findOne({ username: username });
//get username from players collection
let _username = await db.collection('players').findOne({ username: username });
if (quest) {
//check if quest has time if not add time
if (!quest.time) {
//create unix timestamp
console.log('Quest does not have time');
quest.time = Date.now();
//update quest with time
await collection.updateOne({ username: username }, { $set: { time: quest.time } });
}
//make sure more 3 sec
if (quest.time + 3000 < Date.now()) {
//before progressing quest let's make a roll to see if the quest is successful
var seed = await createSeed(blockId, trxId, quest.round.toString());
var roll = await rollDice(1, seed);
if(roll < quest.success_chance) {
console.log('Quest was successful for user ' + username, ' with a roll of ' + roll.toFixed(2).toString() + ' and a success chance of ' + quest.success_chance.toFixed(2).toString());
//quest was successful
if(_username) {
var activeQuest;
//user already has a quest lets start from the current round
activeQuest = await selectQuest(quest.round + 1, _username);
//take the rewards from the quest and add them to values in activeQuest
activeQuest.common_relics += quest.common_relics;
activeQuest.uncommon_relics += quest.uncommon_relics;
activeQuest.rare_relics += quest.rare_relics;
activeQuest.epic_relics += quest.epic_relics;
activeQuest.legendary_relics += quest.legendary_relics;
//replace current quest with new quest
collection.replaceOne({ username: username }, activeQuest);
//log quest progress
await db.collection('quest-log').insertOne({username: username, action: 'progress', quest: activeQuest, roll: roll, success_chance: quest.success_chance, seed: seed, time: new Date()});
return true;
}
else {
console.log('User ' + username + ' does not exist');
return false;
}
}
else {
//quest failed
//remove quest from active-quests collection
console.log('Quest failed for user ' + username, ' with a roll of ' + roll.toFixed(2).toString() + ' and a success chance of ' + quest.success_chance.toFixed(2).toString());
await db.collection('quest-log').insertOne({username: username, action: 'failed', quest: quest, roll: roll, success_chance: quest.success_chance, seed: seed, time: new Date()});
await collection.deleteOne({ username: username });
webhook4("Quest Failed", "Quest Failed for " + username + " with a roll of " + roll.toFixed(2).toString() + " and a success chance of " + quest.success_chance.toFixed(2).toString());
return false;
}
}
else {
console.log('Quest for user ' + username + ' has not been 3 seconds since last progress');
return false;
}
}
else {
console.log('User ' + username + ' does not have a quest yet please use startQuest');
return false;
}
}
catch (err) {
if(err instanceof MongoTopologyClosedError) {
console.log('MongoDB connection closed');
client.close();
process.exit(1);
}
else {
console.log(err);
return false;
}
}
}
async function selectQuest(round, user) {
//go into quest-template collection and select a random quest then add it to users current quest
try{
let collection = db.collection('quest-template');
let quests = await collection.find({}).toArray();
//select a random quest
var random_quest = quests[Math.floor(Math.random() * quests.length)];
//choose a random attribute based on round
var availableAttributes = ["damage", "defense", "engineering", "dodge", "crit", "luck"];
var attribute_one = availableAttributes[Math.floor(Math.random() * availableAttributes.length)];
availableAttributes = availableAttributes.filter(item => item !== attribute_one);
var attribute_two = availableAttributes[Math.floor(Math.random() * availableAttributes.length)];
//come up with base stats for the quest these should scale based on the round
var base_stats = {
"damage": 20 * round,
"defense": 20 * round,
"engineering": 2 * round,
"dodge": round,
"crit": round,
"luck": round
};
//base success chance
var success_chance = 0.80;
//for every round remove 1% chance of success
for (let i = 1; i < round; i++) {
success_chance -= 0.01;
}
//create multiplier that can be used to scale the stats based on the round
var multiplier = round * 2;
//go through each stat and add to success chance
for(var key in user.stats) {
if(key == attribute_one || key == attribute_two) {
//check of stat is greater than base stat
if(user.stats[key] > base_stats[key]) {
//add to success chance
success_chance += 0.1;
}
}
}
var common_relics = 0;
var uncommon_relics = 0;
var rare_relics = 0;
var epic_relics = 0;
var legendary_relics = 0;
//if round is greater than 1 roll for rewards, rewards should scale based on round
if (round > 0) {
//roll float for rewards between 0 and 1
var roll = await rollDice(1);
var common_relics = 0;
var uncommon_relics = 0;
var rare_relics = 0;
var epic_relics = 0;
var legendary_relics = 0;
var relic_types = 1;
if (round > 4) {
if (roll < 0.5) {
relic_types = 2;
}
var floor_roll = 192;
for (let i = 0; i < relic_types; i++) {
//make roll for relics
roll = await rollDice(1);
//4% chance for epic relic
if (roll <= 0.04) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 128 + 1)) + 128;
epic_relics = (roll * 10) * multiplier/divisor;
}
//15% chance for rare relic
else if (roll <= 0.19) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 128 + 1)) + 128;
rare_relics = (roll * 10) * multiplier/divisor;
}
//22% chance for uncommon relic
else if (roll <= 0.41) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 128 + 1)) + 128;
uncommon_relics = (roll * 10) * multiplier/divisor;
}
else {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 128 + 1)) + 128;
common_relics = (roll * 10) * multiplier/divisor;
}
}
}
if (round > 9) {
if (roll < 0.75) {
relic_types = 1
}
else if (roll < 0.5) {
relic_types = 2;
}
var floor_roll = 500;
for (let i = 0; i < relic_types; i++) {
roll = await rollDice(1);
//2.5% chance for legendary relic
if (roll <= 0.025) {
var divisor = Math.floor(Math.random() * (floor_roll - 256 + 1)) + 256;
legendary_relics = (roll * 10) * multiplier/divisor;
}
//7.5% chance for epic relic
else if (roll <= 0.1) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 256 + 1)) + 256;
epic_relics = (roll * 10) * multiplier/divisor;
}
//15% chance for rare relic
else if (roll <= 0.25) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 256 + 1)) + 256;
rare_relics = (roll * 10) * multiplier/divisor;
}
//25% chance for uncommon relic
else if (roll <= 0.525) {
roll = await rollDice(1);
var divisor = Math.floor(Math.random() * (floor_roll - 256 + 1)) + 256;
uncommon_relics = (roll * 10) * multiplier/divisor;
}
else {