/
utils.js
3026 lines (2656 loc) · 92.8 KB
/
utils.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 fs = require("fs");
const steem = require('steem');
const hive = require('@hiveio/hive-js');
const blurt = require('@blurtfoundation/blurtjs');
getConfig();
const fbadmin = require('firebase-admin');
let serviceAccount = require(config.GOOGLE_APPLICATION_CREDENTIALS);
fbadmin.initializeApp({
credential: fbadmin.credential.cert(serviceAccount),
databaseURL: config.databaseURL
});
var _ = require('lodash');
const axios = require('axios');
const dsteem = require('dsteem');
const dhive = require('@hiveio/dhive');
const dblurt = require('dblurt');
const moment = require('moment')
const client = new dsteem.Client(config.active_node);
const hiveClient = new dhive.Client(config.alt_hive_nodes);
const blurtClient = new dblurt.Client(config.blurt_node);
/*
testHistory();
async function testHistory(){
let transactions = await hiveClient.database.call('get_account_history', [config.signup_account, -1, 200]);
console.log(transactions);
}
*/
//hiveClient.updateOperations(true);
var config;
let th_id = -1;
steem.api.setOptions({ url: config.active_node });
//useless now with newer version of hive-js
//hive.config.set('rebranded_api', true)
//hive.broadcast.updateOperations()
hive.config.set('alternative_api_endpoints', config.alt_hive_nodes);
//hive.config.set('chain_id', '4200000000000000000000000000000000000000000000000000000000000000');
hive.api.setOptions({ url: config.active_hive_node});
blurt.api.setOptions({ url: config.blurt_node});
var STEEMIT_100_PERCENT = 10000;
var STEEMIT_VOTE_REGENERATION_SECONDS = (5 * 60 * 60 * 24);
var HOURS = 60 * 60;
var steemPrice;
var rewardBalance;
var recentClaims;
var currentUserAccount;
var votePowerReserveRate;
var totalVestingFund;
var totalVestingShares;
var steem_per_mvests;
var sbd_print_percentage;
var botNames;
let properties
let totalVests
let totalSteem
let hiveProps
let totalHive
let totalHiveVests
function setProperNode(bchain){
if (bchain == "STEEM"){
return steem
}else if (bchain == "BLURT"){
return blurt
}else{
return hive
}
}
function setProperDNode(bchain){
if (bchain == "STEEM"){
return client
}else if (bchain == "BLURT"){
return blurtClient
}else{
return hiveClient
}
}
async function getChainInfo(bchain){
let data = {};
if (!bchain || bchain == ''){
let chain_info = await hive.api.getDynamicGlobalPropertiesAsync();
data['HIVE']=chain_info;
chain_info = await steem.api.getDynamicGlobalPropertiesAsync();
data['STEEM']=chain_info;
chain_info = await blurt.api.getDynamicGlobalPropertiesAsync();
data['BLURT']=chain_info;
}else{
let chainLnk = await setProperNode(bchain);
let chain_info = await chainLnk.api.getDynamicGlobalPropertiesAsync();
data[bchain]=chain_info;
}
return data;
}
async function getAccountData(account_name, bchain){
let account = {};
if (!bchain || bchain == ''){
let account_res = await hive.api.getAccountsAsync([account_name]);
account['HIVE']=account_res[0];
account_res = await steem.api.getAccountsAsync([account_name]);
account['STEEM']=account_res[0];
account_res = await blurt.api.getAccountsAsync([account_name]);
account['BLURT']=account_res[0];
}else{
let chainLnk = await setProperNode(bchain);
//attempt to load account data
try{
let account_res = await chainLnk.api.getAccountsAsync([account_name]);
account[bchain]=account_res[0];
}catch(err){
console.log(err);
}
}
return account;
}
async function validateAccountLogin(username, priv_pkey, bchain){
let chainLnk = await setProperNode(bchain);
console.log('validateAccountLogin');
let account_res = await chainLnk.api.getAccountsAsync([username]);
console.log(account_res[0]);
let pub_pkey = account_res[0].posting.key_auths[0][0];
try{
let res = await chainLnk.auth.wifIsValid(priv_pkey, pub_pkey);
console.log(res);
return {result: res, account: account_res[0]};
}catch(err){
console.log(err);
return {result:false};
}
}
async function encodeMemo(memo, userPubKey, bchain){
let chainLnk = await setProperNode(bchain);
console.log('utils decodememo')
memo = '#'+memo;
let encoded_msg = await chainLnk.memo.encode(config.full_pay_ac_key, userPubKey, memo);
console.log(encoded_msg);
return encoded_msg;
}
async function decodeMemo(memo, userKey, bchain){
let chainLnk = await setProperNode(bchain);
console.log('utils decodememo')
let decrypted = await chainLnk.memo.decode(userKey, memo);
console.log(decrypted);
return decrypted;
}
async function processSteemTrx(ops, userKey, bchain, db, active){
console.log('utils processSteemTrx');
//console.log(operation);
//const ops = [ operation ];
console.log('>>>>>>>>>>>> selected bchain <<<<<<<<<<');
console.log(ops);
let chainLnk = await setProperNode(bchain);
let tx;
//console.log('using active:'+active);
console.log(userKey);
if (active){
console.log('active key')
tx = await chainLnk.broadcast.sendAsync(
{ operations: ops, extensions: [] },
{ active: active }
).catch(err => {
console.log(err.message);
return {error: err.message};
});
}else{
console.log('posting')
tx = await chainLnk.broadcast.sendAsync(
{ operations: ops, extensions: [] },
{ posting: userKey }
).catch(err => {
console.log(err.message);
return {error: err.message};
});
}
//store the trx also to actifit as verified
//console.log(tx);
if (tx && tx.ref_block_num){
let tx_entry = {
tx_id: tx.id,
ref_block_num: tx.ref_block_num,
tx: tx,
date: new Date(),
};
try{
let transaction = await db.collection('verified_tx').insert(tx_entry);
console.log('success inserting transaction details');
}catch(err){
console.log(err);
}
}
console.log(tx);
return {tx: tx};
}
async function purchaseRealProd(req){
console.log('performing purchase on blockchain');
//broadcast trx to blockchain
let cstm_params = {
required_auths: [],
required_posting_auths: [req.query.user],
id: 'actifit',
json: "{ \"buy_product\": \""+req.body.product_id+"\", \"afit_paid\": "+req.body.afit_amount+", \"hive_paid\": "+req.body.hive_amount+"}"
};
let keys = { posting: req.query.userKey };
let ops = [
[ 'custom_json', cstm_params ],
];
let payAmount = parseFloat(req.body.hive_amount).toFixed(3);//
if (payAmount > 0){
let memo = 'actifit buy_real_product '+req.body.product_id;
let trans_params = {
from: req.query.user,
to: config.escrow_account,
amount: payAmount+' HIVE',//"{ \"amount\": \""+ payAmount + " HIVE\", \"precision\": \"3\", \"nai\": \"@@000000021\"}",
memo: memo
}
//no need for posting key, just auth key, otherwise it would fail
cstm_params.required_auths = [req.query.user];
cstm_params.required_posting_auths = [];
ops = [
[ 'custom_json', cstm_params ],
[ 'transfer', trans_params]
];
keys = { active: req.body.active_key };
}
let chainLnk = await setProperNode(req.query.bchain);
//console.log(keys);
let tx = await chainLnk.broadcast.sendAsync(
{ operations: ops, extensions: [] },
keys
).catch(err => {
console.log(err.message);
return {error: err.message};
});
console.log('result');
console.log(tx);
/*let transfer_trx =
*/
return {tx: tx};
}
function updateSteemVariables(bchain) {
let chainLnk = setProperNode(bchain);
chainLnk.api.getRewardFund("post", function (e, t) {
console.log(e,t);
rewardBalance = parseFloat(t.reward_balance.replace(" STEEM", "").replace(" HIVE", ""));
recentClaims = t.recent_claims;
});
chainLnk.api.getCurrentMedianHistoryPrice(function (e, t) {
steemPrice = parseFloat(t.base.replace(" SBD", "")) / parseFloat(t.quote.replace(" STEEM", "").replace(" HIVE", ""));
});
chainLnk.api.getDynamicGlobalProperties(function (e, t) {
votePowerReserveRate = t.vote_power_reserve_rate;
totalVestingFund = parseFloat(t.total_vesting_fund_steem.replace(" STEEM", "").replace(" HIVE", ""));
totalVestingShares = parseFloat(t.total_vesting_shares.replace(" VESTS", ""));
steem_per_mvests = ((totalVestingFund / totalVestingShares) * 1000000);
sbd_print_percentage = t.sbd_print_rate / 10000
console.log(steem_per_mvests);
console.log(sbd_print_percentage);
});
setTimeout(updateSteemVariables, 180 * 1000, bchain)
}
// updateSteemVariables();
/*function getVotingPower(account) {
var voting_power = account.voting_power;
var last_vote_time = new Date((account.last_vote_time) + 'Z');
var elapsed_seconds = (new Date() - last_vote_time) / 1000;
var regenerated_power = Math.round((STEEMIT_100_PERCENT * elapsed_seconds) / STEEMIT_VOTE_REGENERATION_SECONDS);
var current_power = Math.min(voting_power + regenerated_power, STEEMIT_100_PERCENT);
return current_power;
}*/
//fixed implementation of proper voting power calculation
function getVotingPower(account) {
const totalShares = parseFloat(account.vesting_shares) + parseFloat(account.received_vesting_shares) - parseFloat(account.delegated_vesting_shares) - parseFloat(account.vesting_withdraw_rate);
const elapsed = Math.floor(Date.now() / 1000) - account.voting_manabar.last_update_time;
const maxMana = totalShares * 1000000;
// 432000 sec = 5 days
let currentMana = parseFloat(account.voting_manabar.current_mana) + elapsed * maxMana / 432000;
if (currentMana > maxMana) {
currentMana = maxMana;
}
const currentManaPerc = currentMana * 100 / maxMana;
console.log(currentManaPerc);
console.log(account.name);
return currentManaPerc;
}
async function getNewRC(account_name, chain){
let chainLnk = await setProperDNode(chain);
console.log(chainLnk);
let rcComponent = await chainLnk.rc.getRCMana(account_name);
let currentRC = rcComponent.percentage/100;
let currentRCPercent = currentRC + '%';
return {account: account_name, currentRC: currentRC, currentRCPercent: currentRCPercent}
}
//implement a get current Resource Credits function for normal operations consumption
async function getRC(account_name){
var data={"jsonrpc":"2.0","id":1,"method":"condenser_api.get_account_count","params":{}};
//return new Promise(function(fulfill,reject){
//var request = require("request");
let location = config.active_node;
var response = await axios.post(location, {"jsonrpc":"2.0","id":1,"method":"rc_api.find_rc_accounts","params":{"accounts":[account_name]}});
console.log(response.data.result.rc_accounts);
const STEEM_RC_MANA_REGENERATION_SECONDS =432000;
const estimated_max = parseFloat(response.data.result.rc_accounts["0"].max_rc);
const current_mana = parseFloat(response.data.result.rc_accounts["0"].rc_manabar.current_mana);
const last_update_time = parseFloat(response.data.result.rc_accounts["0"].rc_manabar.last_update_time);
const diff_in_seconds = Math.round(Date.now()/1000-last_update_time);
let estimated_mana = (current_mana + diff_in_seconds * estimated_max / STEEM_RC_MANA_REGENERATION_SECONDS);
if (estimated_mana > estimated_max)
estimated_mana = estimated_max;
const estimated_pct = estimated_mana / estimated_max * 100;
const res= {"current_mana": current_mana, "last_update_time": last_update_time,
"estimated_mana": estimated_mana, "estimated_max": estimated_max, "estimated_pct": estimated_pct.toFixed(2),"fullin":timeTilFullPower(estimated_pct*100)};
return res;
//});
}
//function handles confirming if AFIT from SE were received
async function confirmAFITXTransition (targetUser, txid, amount, bchain, standardAfit) {
getConfig();
//track attempts for timeout
let attempts = 1;
let max_attempts = 15;
return new Promise((resolve, reject) => {
th_id = setInterval(async function(){
if (attempts < max_attempts){
attempts += 1;
console.log('Check Move');
//let's call the service by S-E
let url = new URL(config.hive_engine_afitx_trx);
if (standardAfit == 1){
url = new URL(config.hive_engine_afit_trx);
}
if (bchain == 'STEEM'){
url = new URL(config.steem_engine_afitx_trx);
if (standardAfit == 1){
url = new URL(config.steem_engine_afit_trx);
}
}
//connect with our service to confirm AFIT received to proper wallet
try{
let se_connector = await fetch(url);
let trx_entries = await se_connector.json();
console.log(trx_entries);
let match_trx;
//check if we have a proper entry matching user transfer
if (match_trx = trx_entries.find(trx => (trx.from == targetUser && parseFloat(trx.quantity) == parseFloat(amount) && trx.transactionId == txid))) {
//found match, let's make sure transaction is recent enough
console.log('found match');
paymentFound = true;
if (paymentFound){
//need to look again
console.log('found');
clearInterval(th_id);
resolve(match_trx);
}
}
}catch(err){
console.log(err);
}
}else{
//return error
resolve(null);
}
}, 5000);
});
}
async function proceedAfitxMove (targetAcct, amount, chain, standardAfit){
let transId = 'ssc-mainnet-hive';
//let targetBchain = 'STEEM';
//other option is moving tokens from H-E to S-E
if (chain == 'STEEM'){
//if (this.cur_bchain == 'STEEM'){
transId = 'ssc-mainnet1';
//targetBchain = 'HIVE';
}
let tokenSymbol = 'AFITX';
if (standardAfit == 1){
tokenSymbol = 'AFIT';
}
let json_data = {
contractName: 'tokens',
contractAction: 'transfer',
contractPayload: {
symbol: tokenSymbol,
to: targetAcct,
quantity: amount.toFixed(6),//needs to be string and a max of 6 digits supported
memo: ''
}
}
//send out transaction to blockchain
let chainLnk = await setProperNode(chain);
let tx = await chainLnk.broadcast.customJsonAsync(
config.active_key,
[ config.account ] ,
[],
transId,
JSON.stringify(json_data)
).catch(err => {
console.log(err.message);
});
}
//function handles fetching tip transactions
async function verifyTipTransactions(db){
let url = new URL(config.hive_engine_tip_trans_his);
//connect with our service to confirm AFIT received to proper wallet
try{
let he_connector = await fetch(url);
let trx_entries = await he_connector.json();
for (const entry of trx_entries){
//trx_entries.forEach(async function (entry){
let quant = parseFloat(entry.quantity);
let user = entry.from
//if this is a send transaction, need to decrease balance
if (entry.from == config.tip_account){
quant = -1 * quant;
//validate this is a proper tipping transaction
if (entry.memo != null){
user = entry.memo;
}
}
if (entry.symbol != 'AFIT' ){
//skip as currently we only support AFIT tipping
continue;
}
//query to see if entry already stored
let tokenTransQuery = {
user: user,
timestamp: entry.timestamp,
operation: "tokens_transfer",
symbol: entry.symbol,
quantity: quant
}
//store the transaction to the user's profile
let newTokenTrans = {
user: user,
timestamp: entry.timestamp,
operation: "tokens_transfer",
symbol: entry.symbol,
quantity: quant
}
try{
//console.log(newTokenTrans);
//insert the query ensuring we do not write it twice
let transaction = await db.collection('tip_transfers').update(tokenTransQuery, newTokenTrans, { upsert: true });
let trans_res = transaction.result;
//console.log(trans_res);
//transaction inserted
//if (trans_res.upserted){
// console.log('success');
//}
}catch(erra){
console.log(erra);
}
};
return "{success: true}";
//let match_trx;
}catch(err){
console.log(err);
return "{success: false, err:"+err+"}";
}
}
async function updateTipBalances (db){
try{
//group all token transactions per user, and sum them to generate new total count
let query = await db.collection('tip_transfers').aggregate([
{ $group: { _id: "$user", tip_balance: { $sum: "$quantity" } } },
{ $sort: { tokens: -1 } },
{ $project: {
_id: "$_id",
user: "$_id",
tip_balance: "$tip_balance",
}
}
])
let user_tokens = await query.toArray();
//remove old token count per user
await db.collection('tip_balance').remove({});
//insert new count per user
await db.collection('tip_balance').insert(user_tokens);
console.log('---- Updating User Tip Balances Complete ----');
return "{success: true}";
}catch(err){
console.log('>>save data error:'+err.message);
return "{success:false, err: "+err+"}";
}
}
//function handles confirming if AFIT from SE were received
async function confirmSEAFITReceived (targetUser, bchain) {
getConfig();
//track attempts for timeout
let attempts = 1;
let max_attempts = 15;
return new Promise((resolve, reject) => {
th_id = setInterval(async function(){
if (attempts < max_attempts){
attempts += 1;
console.log('Check AFIT Power Up');
//let's call the service by S-E
let url = new URL(config.hive_engine_trans_acct_his);
if (bchain == 'STEEM'){
url = new URL(config.steem_engine_trans_acct_his);
}
//connect with our service to confirm AFIT received to proper wallet
try{
let se_connector = await fetch(url);
let trx_entries = await se_connector.json();
let match_trx;
//check if we have a proper entry matching user transfer
if (match_trx = trx_entries.find(trx => trx.from == targetUser)) {
//found match, let's make sure transaction is recent enough
console.log('found match');
paymentFound = true;
if (paymentFound){
//need to look again
console.log('found');
clearInterval(th_id);
resolve(match_trx);
}
}
}catch(err){
console.log(err);
}
}else{
//return error
resolve(null);
}
}, 5000);
});
}
function customArraysEqual(op1, op2){
try{
return _.isEqual(op1, op2);/*
//console.log('op1')
//console.log(op1)
//console.log('op2')
//console.log(op2)
let leftEntry = op1[0][1];//JSON.parse(op1[0][1]);
let rightEntry = op2[0][1];//JSON.parse(op2[0][1]);
console.log(leftEntry);
console.log(rightEntry);
if (op1[0][0] == op2[0][0]){
if (leftEntry['required_auths'] == rightEntry['required_auths']
&& leftEntry['required_posting_auths'] == rightEntry['required_posting_auths']
&& leftEntry['id'] == rightEntry['id']
&& _.isEqual(leftEntry['json'], rightEntry['json'])){
return true;
}else{
console.log('non matching subs')
}
}else{
console.log(op1[0][0])
console.log(op2[0][0])
console.log('different op');
}
return false;*/
}catch(err){
console.log(err);
console.log('error matching')
return false;
}
}
function arraysEqual(array1, array2) {
if (array1.length !== array2.length) return false;
for (let i = 0; i < array1.length; i++) {
if (Array.isArray(array1[i]) && Array.isArray(array2[i])) {
if (!arraysEqual(array1[i], array2[i])) return false;
} else if (typeof array1[i] === 'object') {
if (JSON.stringify(array1[i]) !== JSON.stringify(array2[i])) return false;
} else {
if (array1[i] !== array2[i]) return false;
}
}
return true;
}
/*testAs();
async function testAs(){
let chainLnk = await setProperNode('HIVE');
let txid = '611417a631ff7f55922bf00e22e3358f46e04d78'
transactions = await chainLnk.api.getTransactionAsync(txid);
console.log(transactions);
}*/
async function storeVerifiedTrx(tx, db){
console.log('store transaction')
console.log(tx);
if (tx && tx.ref_block_num){
let tx_entry = {
tx_id: tx.transaction_id,
ref_block_num: tx.ref_block_num,
tx: tx,
date: new Date(),
};
try{
let transaction = await db.collection('verified_tx').insert(tx_entry);
console.log('success inserting transaction details');
}catch(err){
console.log(err);
}
}
}
async function findVerifyTrx (req, db, nostore){
getConfig();
console.log('findverify')
let bchain = req.query.bchain?req.query.bchain:'HIVE'
//first check trx to see if it has been processed
let trx = await db.collection('verified_tx').findOne({tx_id: req.params.trxID});
//this shouldnt be there, so if it is skip
if (trx){
return ({error: 'trx already exists'});
}
//track attempts for timeout
let attempts = 1;
let max_attempts = 30;
let fv_th_id;
let matchFound = false;
let matchTrx;
return new Promise((resolve, reject) => {
fv_th_id = setInterval(async function(){
if (attempts < max_attempts){
attempts += 1;
let chainLnk = await setProperNode(bchain);
console.log('check trx');
if (bchain == 'STEEM'){
matchTrx = await client.database.call('get_transaction', req.params.trxID);
}else{
//transactions = await hiveClient.database.call('get_transaction', req.query.txid);
matchTrx = await chainLnk.api.getTransactionAsync(req.params.trxID);
console.log(matchTrx);
}
//chainLnk.api.getAccountHistory(config.signup_account, -1, 1000, (err, transactions) => {
if (matchTrx && matchTrx.transaction_id && Array.isArray(matchTrx.operations)){
console.log('potential match')
//need to stringify first part as the second is already stringified
if (customArraysEqual(matchTrx.operations, JSON.parse(req.query.operation))){
//if (customArraysEqual(JSON.stringify(matchTrx.operations), req.query.operation)){
//if (arraysEqual(JSON.stringify(matchTrx.operations), req.query.operation)){
console.log('GOOOOD')
let now = moment(new Date()); //todays date
let end = moment(matchTrx.expiration); // last update date
let duration = moment.duration(now.diff(end));
let hrs = duration.asHours();
//transaction needs to have been concluded within 7 hours.
console.log(hrs);
if (hrs < 7){
matchFound = true;
//break;
if (nostore){
}else{
//store transaction
await storeVerifiedTrx(matchTrx, db);
}
}
}
}
}else{
console.log('not found after '+attempts+' attempts');
clearInterval(fv_th_id);
resolve(false);
}
if (matchFound){
//need to look again
console.log('found');
clearInterval(fv_th_id);
resolve(matchTrx);
}
//});
}, 5000);
});
}
//function handles confirming if payment was received
async function confirmPaymentReceived (req, bchain) {
getConfig();
return new Promise((resolve, reject) => {
th_id = setInterval(async function(){
//let chainLnk = await setProperNode(bchain);
console.log('check funds');
let transactions;
//transactions.reverse()
if (bchain == 'STEEM'){
transactions = await client.database.call('get_account_history', [config.signup_account, -1, 20]);
}else{
transactions = await hiveClient.database.call('get_account_history', [config.signup_account, -1, 20]);
}
//chainLnk.api.getAccountHistory(config.signup_account, -1, 1000, (err, transactions) => {
let tx_id = '';
let paymentFound = false;
for (let txs of transactions) {
let op = txs[1].op
//check if we received a transfer to our target account
//if we found a transfer operation sent to our target account, with the correct memo and the proper amount, proceed
if (op[0] === 'transfer'){
let sentAmount = op[1].amount.split(' ')[0];
let sentCur = op[1].amount.split(' ')[1];
/*if (op[1].to === config.signup_account
&& sentAmount >= (parseFloat(req.query.steem_invest)-0.1)
&& sentCur === req.query.sent_cur){
console.log(sentAmount);
console.log(op[1].memo);
console.log(req.query.memo );
console.log('>>>>>');
}*/
if (op[1].to === config.signup_account
&& op[1].memo === req.query.memo
&& sentAmount >= (parseFloat(req.query.steem_invest)-0.1)
&& sentCur === req.query.sent_cur){
console.log('in');
console.log(op[1]);
let now = moment(new Date()); //todays date
let end = moment(txs[1].timestamp); // last update date
let duration = moment.duration(now.diff(end));
let hrs = duration.asHours();
//transaction needs to have been concluded within 5 hours.
if (hrs < 5){
tx_id = txs[1].trx_id;
paymentFound = true;
break;
}
}
}
}
if (paymentFound){
//need to look again
console.log('found');
clearInterval(th_id);
resolve(tx_id);
}
//});
}, 5000);
});
}
//function handles confirming if payment was received
async function confirmPaymentReceivedPassword (req, bchain) {
getConfig();
console.log('confirmPaymentReceivedPassword');
return new Promise((resolve, reject) => {
let th_id = setInterval(async function(){
console.log('check funds');
console.log(bchain);
//let chainLnk = await setProperNode(bchain);
let transactions;
//transactions.reverse()
if (bchain == 'STEEM'){
transactions = await client.database.call('get_account_history', [config.exchange_account, -1, 300]);
}else{
transactions = await hiveClient.database.call('get_account_history', [config.exchange_account, -1, 300]);
}
console.log("newestTxId:"+transactions[0][0]);
// for (let txs of transactions) {
//chainLnk.api.getAccountHistory(config.exchange_account, -1, 300, (err, transactions) => {
let tx_id = '';
let paymentFound = false;
for (let txs of transactions) {
let op = txs[1].op
//check if we received a transfer to our target account
//if we found a transfer operation sent to our target account, with the correct memo and the proper amount, proceed
if (op[0] === 'transfer'){
//console.log('transfer op ');
//console.log(op[1]);
let sentAmount = op[1].amount.split(' ')[0];
if (op[1].to === config.exchange_account && op[1].from === req.query.from && sentAmount >= 1){
console.log('in');
console.log(op[1]);
//console.log(txs);
/*let now = moment(new Date()); //todays date
let end = moment(txs[1].timestamp); // last update date
let duration = moment.duration(now.diff(end));
let hrs = duration.asHours();
//transaction needs to have been concluded within 5 hours.
if (hrs < 24){*/
tx_id = txs[1].trx_id;
paymentFound = true;
break;
//}
}
}
}
if (paymentFound){
//need to look again
console.log('found');
clearInterval(th_id);
resolve(tx_id);
}
//});
}, 5000);
});
}
//function handles confirming if payment was received
async function confirmPaymentReceivedBuy (req, bchain) {
getConfig();
console.log('confirmPaymentReceivedBuy');
return new Promise((resolve, reject) => {
let th_id = setInterval(async function(){
console.log('check buy funds');
//let chainLnk = await setProperNode(bchain);
let transactions;
if (bchain == 'STEEM'){
transactions = await client.database.call('get_account_history', [config.buy_account, -1, 800]);
}else{
transactions = await hiveClient.database.call('get_account_history', [config.buy_account, -1, 800]);
}
console.log("newestTxId:"+transactions[0][0]);
//chainLnk.api.getAccountHistory(config.buy_account, -1, 800, (err, transactions) => {
let tx_id = '';
let paymentFound = false;
for (let txs of transactions) {
let op = txs[1].op
//check if we received a transfer to our target account
//if we found a transfer operation sent to our target account, with the correct sender and the proper amount, proceed
if (op[0] === 'transfer'){
let sentAmount = op[1].amount.split(' ')[0];
if (op[1].to === config.buy_account && op[1].from === req.query.from && sentAmount === req.query.steem_amount){
console.log('in');
console.log(op[1]);
//console.log(txs);
let now = moment(new Date()); //todays date
let end = moment(txs[1].timestamp); // last update date
let duration = moment.duration(now.diff(end));
let hrs = duration.asHours();
//transaction needs to have been concluded within 5 hours.
if (hrs < 5){
tx_id = txs[1].trx_id;
paymentFound = true;
break;
}
}
}
}
if (paymentFound){
//need to look again
console.log('found');
clearInterval(th_id);
resolve(tx_id);
}
//});
}, 5000);
});
}
//function handles claiming spots for accounts
async function claimDiscountedAccount(chain){
console.log('claimDiscountedAccount');
if (typeof config == 'undefined' || config == null){
getConfig();
}
const claim_op = [
'claim_account',
{
creator: config.account,
fee: '0.000 STEEM',
extensions: [],
}
];
const ops = [claim_op];
let result = '';
let outcSteem = false;
let outcHive = false;
if (!chain || chain.includes('STEEM')){
try{
const privateKey = dsteem.PrivateKey.fromString(
config.active_key
);
result = await client.broadcast.sendOperations(ops, privateKey);
console.log('success');
outcSteem = true;
}catch(err){
console.log(err);
outcSteem = false;
}
}
if (!chain || chain.includes('HIVE')){
try{
const privateKey = dhive.PrivateKey.fromString(
config.active_key
);
result = await hiveClient.broadcast.sendOperations(ops, privateKey);
console.log('success');
outcHive = true;
}catch(err){
console.log(err);
outcHive = false;
}
}
return (outcSteem || outcHive);
}
//function handles creating accounts via discounted claimed spots or normal paid method
async function createAccount (username, password, chain){
if (typeof config == 'undefined' || config == null){
getConfig();