-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCashier.js
1373 lines (1246 loc) · 67.4 KB
/
Cashier.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
const Utils = require('./Utils');
const ContractMachine = require('./SmartContracts');
const Substate = require('./Substate').Substate;
const {ContractError} = require('./errors');
class Cashier {
constructor(config, db){
this.config = config;
this.db = db;
this.mrewards = BigInt(0);
this.refrewards = BigInt(0);
this.srewards = BigInt(0);
this.krewards = BigInt(0);
}
eindex_entry(arr, type, id, hash, value) {
if(this.config.indexer_mode !== 1)
return;
arr.push({type : type, id : id, hash : hash, value : value });
}
processTransfer(tx, substate){
let token = substate.tokens.find(tok => ((tok.hash === tx.ticker)));
if (token === undefined) {
throw new ContractError("Token not found");
}
let token_enq = substate.tokens.find(tok => ((tok.hash === Utils.ENQ_TOKEN_NAME)));
let token_fee = BigInt(Utils.calc_fee(token, tx.amount));
let native_fee = BigInt(Utils.calc_fee(token_enq, 0));
tx.amount = BigInt(tx.amount);
if ((tx.amount - token_fee) >= BigInt(0)) {
// Take amount from `from`
substate.accounts_change(
{
id : tx.from,
token : tx.ticker,
amount : BigInt(-1) * tx.amount
}
);
// Take native fee amount from token owner
substate.accounts_change(
{
id : token.owner,
token : Utils.ENQ_TOKEN_NAME,
amount : BigInt(-1) * native_fee
}
);
if(token.fee_type === 2){
// Take token fee as native from `from`
substate.accounts_change(
{
id : tx.from,
token : Utils.ENQ_TOKEN_NAME,
amount : BigInt(-1) * token.fee_value
}
);
// Give token fee as native to token owner
substate.accounts_change(
{
id : token.owner,
token : Utils.ENQ_TOKEN_NAME,
amount : token.fee_value
}
);
}
else{
// Give token fee to token owner
substate.accounts_change(
{
id : token.owner,
token : tx.ticker,
amount : token_fee
}
);
}
// Give amount to `to`
substate.accounts_change(
{
id : tx.to,
token : tx.ticker,
amount : BigInt(tx.amount - token_fee)
}
);
}
else
throw new ContractError("Negative ledger state");
}
status_entry(status, tx) {
if(this.config.indexer_mode === 1)
return {
hash: tx.hash,
mblocks_hash: tx.mblocks_hash,
status: status,
ticker : tx.ticker,
amount : tx.amount,
from : tx.from,
to : tx.to
};
return {
hash: tx.hash,
mblocks_hash: tx.mblocks_hash,
status: status
};
}
async ledger_update_002(kblock, limit) {
let hash = kblock.hash;
let accounts = [];
let statuses = [];
let post_action = [];
let contracts = {};
let total_pos_stake = BigInt(0);
let time = process.hrtime();
let rewards = [];
//console.debug(`cashier processing macroblock ${hash}`);
console.trace(`cashier processing macroblock ${JSON.stringify(kblock)}`);
let chunk = await this.db.get_new_microblocks(hash, limit);
let CMachine = ContractMachine.getContractMachine(this.config.FORKS, kblock.n);
let CFactory = new ContractMachine.ContractFactory(this.config);
console.silly('cashier chunk = ', JSON.stringify(chunk));
console.debug(`cashier is processing chunk ${hash} of ${chunk.mblocks.length} mblocks with ${chunk.txs ? chunk.txs.length : "NaN"} txs`);
/**
* No mblocs means that all mblocks in kblock were calculated, time to close kblock
* or
* empty kblock
*/
if (chunk.mblocks.length === 0) {
console.debug(`No more blocks in kblock ${hash}, terminating`);
let mblocks = await this.db.get_included_microblocks(kblock.hash);
let sblocks = await this.db.get_new_statblocks(hash);
let mblock_tokens = [];
let mblock_pubs = {};
let tok_obj = {};
let supply_change = {};
let total_reward = BigInt(0);
accounts.push(this.db.ORIGIN.publisher);
accounts.push(kblock.publisher);
accounts = accounts.concat(mblocks.map(m => m.publisher));
accounts = accounts.concat(mblocks.map(m => m.referrer));
// Add pos owners to sblocks and accounts array
if (sblocks.length !== 0) {
let poses = await this.db.get_pos_contract_all();
for(let sb of sblocks){
let pos = poses.find(p => p.id === sb.publisher);
if(pos){
sb.pos_owner = pos.owner;
accounts.push(sb.pos_owner);
}
}
}
/**
* 1. Get all mblocks from database
* 2. Get all involved tokens
* 3. Get all token info - create tokens array with block rewards & refrewards
* 4. Filter mblocks by only existing & minable tokens
* 4. Add all token owners to accounts
* 5. Build object :
* {
* "token_hash_1" : {
* block_reward : 15,
* ref_share : 1000,
* total_poa_stake : 0,
* total_poa_rew : 0,
* min_stake : 25,
* max_stake : 1000,
* referrer_stake : 1000
* }
* }
* 6. Create object with pub stakes
*
*/
mblock_tokens = mblock_tokens.concat(mblocks.map(m => m.token));
let tokens = await this.db.get_tokens(mblock_tokens);
let token_enq = (await this.db.get_tokens([Utils.ENQ_TOKEN_NAME]))[0];
accounts = accounts.concat(tokens.map(tok => tok.owner));
accounts = accounts.filter((v, i, a) => a.indexOf(v) === i);
accounts = accounts.filter(v => v !== null);
accounts = await this.db.get_accounts_all(accounts);
/**
* mblocks & refrewards calculation
*/
for(let tok of tokens){
tok_obj[tok.hash] = tok;
tok_obj[tok.hash].total_poa_stake = BigInt(0);
if(tok.hash === Utils.ENQ_TOKEN_NAME){
tok_obj[tok.hash].total_poa_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.poa) / Utils.PERCENT_FORMAT_SIZE;
tok_obj[tok.hash].max_stake = BigInt(this.config.stake_limits.max_stake);
}
else{
// Check token emission.
if(tok.block_reward > (tok.max_supply - tok.total_supply)){
tok.block_reward = BigInt(0);
console.info(`${tok.ticker} token emission is over, setting mreward to 0`)
}
tok_obj[tok.hash].total_poa_reward = BigInt(tok.block_reward) * BigInt(Utils.PERCENT_FORMAT_SIZE) / (BigInt(Utils.PERCENT_FORMAT_SIZE) + BigInt(tok.ref_share));
}
}
let total_pos_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.pos) / Utils.PERCENT_FORMAT_SIZE;
let org = accounts.findIndex(a => ((a.id === this.db.ORIGIN.publisher) && (a.token === Utils.ENQ_TOKEN_NAME)));
for(let i = 0; i < mblocks.length; i++){
let block = mblocks[i];
let pub = accounts.findIndex(a => ((a.id === block.publisher) && (a.token === block.token)));
mblock_pubs[block.hash] = {};
if(block.token === Utils.ENQ_TOKEN_NAME){
let stake = BigInt(0);
if (pub > -1) {
stake = (accounts[pub].amount > stake) ? accounts[pub].amount : stake;
stake = (stake > tok_obj[block.token].max_stake) ? tok_obj[block.token].max_stake : stake;
}
tok_obj[block.token].total_poa_stake += BigInt(stake);
mblock_pubs[block.hash].stake = BigInt(stake);
}
else{
tok_obj[block.token].total_poa_stake += BigInt(accounts[pub].amount);
mblock_pubs[block.hash].stake = BigInt(accounts[pub].amount);
}
}
for(let i = 0; i < mblocks.length; i++){
let total_mblock_reward = BigInt(0);
let m = mblocks[i];
if(!supply_change.hasOwnProperty(m.token))
supply_change[m.token] = BigInt(0);
let pub = accounts.findIndex(a => ((a.id === m.publisher) && (a.token === m.token)));
let owner = accounts.findIndex(a => ((a.id === tok_obj[m.token].owner) && (a.token === m.token)));
let stake = mblock_pubs[m.hash].stake;
if (pub > -1 && tok_obj[m.token].total_poa_stake > BigInt(0)) {
m.reward = BigInt(stake) * tok_obj[m.token].total_poa_reward / tok_obj[m.token].total_poa_stake;
accounts[pub].amount = BigInt(accounts[pub].amount) + m.reward;
total_mblock_reward += m.reward;
this.mrewards += m.reward;
this.eindex_entry(rewards, 'im', accounts[pub].id, m.hash, m.reward);
} else {
console.warn(`PoA miner with low-stake detected at mblock ${JSON.stringify(m)}`);
m.reward = BigInt(0);
total_mblock_reward += m.reward;
if(pub < 0){
accounts.push({id: m.publisher, amount: m.reward, token: m.token});
pub = accounts.findIndex(a => ((a.id === m.publisher) && (a.token === m.token)));
}
this.mrewards += m.reward;
}
let ref = accounts.findIndex(a => ((a.id === m.referrer) && (a.token === m.token)));
//let ref_reward = BigInt(m.reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref);
let ref_reward = BigInt(m.reward) * BigInt(tok_obj[m.token].ref_share) / BigInt(Utils.PERCENT_FORMAT_SIZE);
if (ref > -1) {
let real_ref;
if (accounts[ref].amount >= tok_obj[m.token].referrer_stake) {
real_ref = ref;
} else {
real_ref = owner;
}
accounts[pub].amount = BigInt(accounts[pub].amount) + ref_reward / BigInt(2);
accounts[real_ref].amount = BigInt(accounts[real_ref].amount) + ref_reward / BigInt(2);
total_mblock_reward += ((ref_reward / BigInt(2)) * BigInt(2));
this.refrewards += ref_reward;
this.eindex_entry(rewards, 'iref', accounts[pub].id, m.hash, ref_reward / BigInt(2));
this.eindex_entry(rewards, 'iref', accounts[real_ref].id, m.hash, ref_reward / BigInt(2));
} else {
accounts[owner].amount = BigInt(accounts[owner].amount) + ref_reward;
this.eindex_entry(rewards, 'iref', accounts[owner].id, m.hash, ref_reward);
total_mblock_reward += ref_reward;
this.refrewards += ref_reward;
}
if(m.token === Utils.ENQ_TOKEN_NAME){
total_reward += total_mblock_reward;
}
else{
// Token dust collecting
let mref = m.reward + ref_reward;
accounts[owner].amount = BigInt(accounts[owner].amount) + (mref - total_mblock_reward);
// In this cycle we change supply_change object only for minable tokens
// ENQ supply change will be made before block termination call
supply_change[m.token] += total_mblock_reward;
}
}
// calc total poa stake
//if(total_poa_stake > 0 && mblocks.length !== 0){
// }
// else {
// // TODO: this code handle reward leakage on zero-stake mblock publisher (bad thing)
// // TODO: this code handle reward leakage on empty kblock with no mblocks (bad thing)
// if(kblock.n !== 0){
// accounts[org].amount = BigInt(accounts[org].amount) + BigInt(total_poa_reward) + (BigInt(total_poa_reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref));
// this.mrewards += total_poa_reward;
// this.refrewards += (BigInt(total_poa_reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref));
// }
// }
/**
* Kblock reward
*/
let total_pow_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.pow) / Utils.PERCENT_FORMAT_SIZE;
kblock.reward = BigInt(total_pow_reward);
let k_pub = accounts.findIndex(a => ((a.id === kblock.publisher) && (a.token === Utils.ENQ_TOKEN_NAME)));
if (k_pub > -1) {
accounts[k_pub].amount = BigInt(accounts[k_pub].amount) + BigInt(kblock.reward);
total_reward += BigInt(kblock.reward);
this.krewards += kblock.reward;
} else {
accounts.push({id: kblock.publisher, amount: kblock.reward, token: Utils.ENQ_TOKEN_NAME});
total_reward += BigInt(kblock.reward);
this.krewards += kblock.reward;
}
this.eindex_entry(rewards, 'ik', kblock.publisher, kblock.hash, kblock.reward);
/**
* POS rewards
*
* - Total reward for all POS-contracts:
* pos_reward = block_reward * pos_ratio
*
* - Total reward for single POS-contract:
* contract_reward = pos_reward * contract_stake / total_pos_stake
*
* - Total reward splits between pos_owner and delegators
* pos_owner_reward = fee * contract_reward
* delegates_reward = contract_reward - owner_reward
*
* - Single delegator reward:
* delegate_reward = delegate_stake * delegates_reward / contract_stake
*/
let pos_info = await this.db.get_pos_info(sblocks.map(s => s.publisher));
//Sum total pos stake
sblocks = sblocks.filter(s => {
let pub = pos_info.findIndex(a => a.pos_id === s.publisher);
if (pub > -1){
total_pos_stake += BigInt(pos_info[pub].stake);
return true;
}
else
return false;
});
//Calc pos rewards
if((total_pos_stake > 0) && (sblocks.length > 0)){
let cont = new CMachine.Contract();
for(let s of sblocks) {
let pub = accounts.findIndex(a => ((a.id === s.pos_owner) && (a.token === Utils.ENQ_TOKEN_NAME)));
let delegate = pos_info.findIndex(a => a.pos_id === s.publisher);
let contract_reward = total_pos_reward * BigInt(pos_info[delegate].stake) / total_pos_stake;
let pos_owner_reward = BigInt(pos_info[delegate].fee) * contract_reward / Utils.PERCENT_FORMAT_SIZE;
let delegates_reward = contract_reward - pos_owner_reward;
s.reward = contract_reward;
// calc for all delegators
let delegators = await this.db.get_pos_delegators(s.publisher);
for(let del of delegators){
// Add new reward to old for post_action
if(pos_info[delegate].stake > 0){
// TODO: possible reward leakage SET reward = ?
let del_reward = BigInt(del.amount) * delegates_reward / BigInt(pos_info[delegate].stake);
if(del_reward > BigInt(0)) {
total_reward += BigInt(del_reward);
let sql = cont.mysql.format(`(?, ?, ?)`,
[del.pos_id, del.delegator, del_reward]);
post_action = post_action.concat([sql]);
}
}
}
accounts[pub].amount = BigInt(accounts[pub].amount) + pos_owner_reward;
total_reward += BigInt(pos_owner_reward);
this.eindex_entry(rewards,'iv', accounts[pub].id, s.hash, pos_owner_reward);
this.eindex_entry(rewards,'istat', s.publisher, s.hash, s.reward);
this.srewards += pos_owner_reward;
this.srewards += delegates_reward;
}
}
else{
if(kblock.n !== 0){
accounts[org].amount = BigInt(accounts[org].amount) + total_pos_reward;
this.srewards += total_pos_reward;
}
}
/**
* Fee distribution
*/
// Now we can't define LPoS so we set ldr_share to 0
let ldr_acc;
let total_fee = BigInt(0);
let kblock_tx_count = await this.db.get_kblock_txs_count(kblock.hash);
let native_fee = BigInt(Utils.calc_fee(token_enq, 0));
let kblock_fees = BigInt(kblock_tx_count) * native_fee;
//accounts[org].amount = BigInt(accounts[org].amount) + BigInt(kblock_fees);
let fee_shares = this.config.fee_shares;
let pow_fee_share = kblock_fees * BigInt(fee_shares.pow_share) / Utils.PERCENT_FORMAT_SIZE;
let org_fee_share = kblock_fees * BigInt(fee_shares.gen_share) / Utils.PERCENT_FORMAT_SIZE;
let ldr_fee_share = kblock_fees * BigInt(fee_shares.ldr_share) / Utils.PERCENT_FORMAT_SIZE;
let pos_fee_share = kblock_fees * BigInt(fee_shares.pos_share) / Utils.PERCENT_FORMAT_SIZE;
if (k_pub > -1) {
accounts[k_pub].amount = BigInt(accounts[k_pub].amount) + BigInt(pow_fee_share);
this.eindex_entry(rewards, 'ifk', accounts[k_pub].id, kblock.hash, BigInt(pow_fee_share));
total_fee += BigInt(pow_fee_share);
} else
org_fee_share += pow_fee_share;
if (org > -1) {
accounts[org].amount = BigInt(accounts[org].amount) + BigInt(org_fee_share);
this.eindex_entry(rewards, 'ifg', accounts[org].id, kblock.hash, BigInt(org_fee_share));
total_fee += BigInt(org_fee_share);
}
if((total_pos_stake > 0) && (sblocks.length > 0)){
let cont = new CMachine.Contract();
for(let s of sblocks) {
let pub = accounts.findIndex(a => ((a.id === s.pos_owner) && (a.token === Utils.ENQ_TOKEN_NAME)));
let delegate = pos_info.findIndex(a => a.pos_id === s.publisher);
let contract_fee_reward = pos_fee_share * BigInt(pos_info[delegate].stake) / total_pos_stake;
let pos_owner_fee_reward = BigInt(pos_info[delegate].fee) * contract_fee_reward / Utils.PERCENT_FORMAT_SIZE;
let delegates_fee_reward = contract_fee_reward - pos_owner_fee_reward;
// calc for all delegators
let delegators = await this.db.get_pos_delegators(s.publisher);
for (let del of delegators) {
// Add new reward to old for post_action
if (pos_info[delegate].stake > 0) {
let del_reward = BigInt(del.amount) * delegates_fee_reward / BigInt(pos_info[delegate].stake);
if(del_reward > BigInt(0)){
total_fee += BigInt(del_reward);
let sql = cont.mysql.format(`(?, ?, ?)`,
[del.pos_id, del.delegator, del_reward]);
post_action = post_action.concat([sql]);
}
}
}
accounts[pub].amount = BigInt(accounts[pub].amount) + pos_owner_fee_reward;
this.eindex_entry(rewards, 'iv', accounts[pub].id, kblock.hash, BigInt(pos_owner_fee_reward));
total_fee += BigInt(pos_owner_fee_reward);
}
}
else {
accounts[org].amount = BigInt(accounts[org].amount) + pos_fee_share;
total_fee += BigInt(pos_fee_share);
}
let dust_block = BigInt(token_enq.block_reward) - BigInt(total_reward);
let dust_fees = BigInt(kblock_fees) - BigInt(total_fee);
accounts[org].amount += dust_block + dust_fees;
this.eindex_entry(rewards, 'idust', accounts[org].id, kblock.hash, BigInt(dust_block + dust_fees));
supply_change[Utils.ENQ_TOKEN_NAME] = token_enq.block_reward;
let group_update_delegates = `DROP TEMPORARY TABLE IF EXISTS tmp_delegates;
CREATE TEMPORARY TABLE tmp_delegates (
tmp_pos_id VARCHAR(64),
tmp_delegator VARCHAR(66),
tmp_reward BIGINT(20),
PRIMARY KEY (tmp_pos_id, tmp_delegator));
INSERT INTO tmp_delegates (tmp_pos_id, tmp_delegator, tmp_reward) VALUES
${post_action.join(',')}
ON DUPLICATE KEY UPDATE tmp_reward = tmp_reward + VALUES(tmp_reward);
UPDATE delegates RIGHT JOIN tmp_delegates ON pos_id = tmp_pos_id AND delegator = tmp_delegator SET reward = reward + tmp_reward;
DROP TEMPORARY TABLE IF EXISTS tmp_delegates`;
time = process.hrtime(time);
console.debug(`cashier_timing: kblock termination ${hash} prepared in`, Utils.format_time(time));
time = process.hrtime();
await this.db.terminate_ledger_kblock(accounts, kblock, mblocks, sblocks, [group_update_delegates], supply_change, rewards);
time = process.hrtime(time);
console.debug(`cashier_timing: kblock termination ${hash} saved in`, Utils.format_time(time));
console.info(`---------------------------------`);
// console.log(this.mrewards, this.refrewards, this.srewards, this.krewards);
// console.log(`Total: ${this.mrewards + this.refrewards + this.srewards + this.krewards}`)
// console.log(`Formule: ${BigInt(token_enq.block_reward * (kblock.n)) }`)
let ledger = BigInt((await this.db.get_total_supply()).amount);
let formula = BigInt(this.config.ORIGIN.reward) + (BigInt(token_enq.block_reward) * BigInt(kblock.n + 1));
console.log(`n: ${kblock.n}`);
console.log(`Ledger: ${ledger}`);
console.log(`Formula: ${formula}`);
console.log(`Dust: ${dust_block + dust_fees}`);
console.log(`Diff: ${formula - ledger} \r\n`);
//if(formula - ledger !== BigInt(0))
// throw new Error(`There is a diff after block calculation, cashier stopped`);
return;
}
let substate = new Substate(this.config, this.db);
substate.accounts.push(this.db.ORIGIN.publisher);
if (chunk.mblocks.length !== 0) {
substate.accounts = substate.accounts.concat(chunk.txs.map(tx => tx.from));
substate.accounts = substate.accounts.concat(chunk.txs.map(tx => tx.to));
substate.accounts.push(kblock.publisher);
}
// TODO: костыль. Вынести валидацию в explorer. Ужадить из кассира после вайпа истории
let filtered_tickers = chunk.txs.map(function (tx) {
let hash_regexp = /^[0-9a-fA-F]{64}$/i;
if (hash_regexp.test(tx.ticker))
return tx.ticker;
});
let tokens = await this.db.get_tokens(filtered_tickers);
let token_enq = (await this.db.get_tokens([Utils.ENQ_TOKEN_NAME]))[0];
substate.accounts = substate.accounts.concat(tokens.map(token => token.owner));
substate.tokens.push(Utils.ENQ_TOKEN_NAME);
substate.tokens = substate.tokens.concat(filtered_tickers);
let duplicates = await this.db.get_duplicates(chunk.txs.map(tx => tx.hash));
console.silly(`duplicates = ${JSON.stringify(duplicates)}`);
console.debug(`duplicates.length = ${duplicates.length}`);
// Remove duplicates
for(let i = 0; i < chunk.txs.length; i++) {
let tx = chunk.txs[i];
if (duplicates.some(d => d.hash === tx.hash) || (i !== chunk.txs.findIndex(t => t.hash === tx.hash))) {
statuses.push(this.status_entry(Utils.TX_STATUS.DUPLICATE, tx));
console.debug(`duplicate tx ${JSON.stringify(tx)}`);
// remove this tx from array
chunk.txs.splice(i, 1);
i--;
}
}
// Parse all contracts to get involved accounts
// Also get all involved POS contracts and delegators
// Also reject all TXs with incorrect contracts
for(let i = 0; i < chunk.txs.length; i++){
let tx = chunk.txs[i];
if (CFactory.isContract(tx.data, kblock.n)) {
try {
// Clone tx object so we can pass amount without fee
let _tx = Object.assign({}, tx);
_tx.amount -= token_enq.fee_value;
// Create contract to get it's params. Without execution
contracts[tx.hash] = await CFactory.create(_tx, this.db, kblock);
// Pass contract's params to substate to add data
substate.fillByContract(contracts[tx.hash], tx);
} catch (err) {
//if(err instanceof ContractError)
// TODO: logger-style errors
console.log(err);
statuses.push(this.status_entry(Utils.TX_STATUS.REJECTED, tx));
console.debug(`rejected tx ${JSON.stringify(tx)}. Reason: ${err}`);
// remove this tx from array
chunk.txs.splice(i, 1);
i--;
}
}
}
console.trace(`cashier ${substate.accounts.length} accounts: ${Utils.JSON_stringify(substate.accounts)}`);
console.silly(`accounts = ${JSON.stringify(substate.accounts)}`);
await substate.loadState();
let substate_copy = new Substate(this.config, this.db);
for(let i = 0; i < chunk.txs.length; i++){
let tx = chunk.txs[i];
substate_copy.setState(substate);
tx.amount = BigInt(tx.amount);
try {
this.processTransfer(tx, substate_copy);
// Check if tx has contract
let contract = contracts[tx.hash] || null;
if (contract) {
let res = await contract.execute(tx, substate_copy, kblock, this.config);
// add eindex entry for claims
if(contract.type === 'pos_reward')
this.eindex_entry(rewards, 'ic', substate_copy.claims[tx.hash].delegator, tx.hash, substate_copy.claims[tx.hash].reward);
if(res.hasOwnProperty("dex_swap"))
this.eindex_entry(rewards, 'iswapout', tx.from, tx.hash, res.dex_swap.out);
if(res.hasOwnProperty("farm_reward"))
this.eindex_entry(rewards, 'ifrew', tx.from, tx.hash, res.farm_reward);
if(res.hasOwnProperty("pool_create_lt"))
this.eindex_entry(rewards, 'ipcreatelt', tx.from, tx.hash, res.pool_create_lt);
if(res.hasOwnProperty("liq_add_lt"))
this.eindex_entry(rewards, 'iliqaddlt', tx.from, tx.hash, res.liq_add_lt);
if(res.hasOwnProperty("liq_remove")){
this.eindex_entry(rewards, 'iliqrmv1', tx.from, tx.hash, res.liq_remove.liq_remove1);
this.eindex_entry(rewards, 'iliqrmv2', tx.from, tx.hash, res.liq_remove.liq_remove2);
}
if(res.hasOwnProperty("farm_close_reward"))
this.eindex_entry(rewards, 'ifcloserew', tx.from, tx.hash, res.farm_close_reward);
if(res.hasOwnProperty("farm_decrease_reward"))
this.eindex_entry(rewards, 'ifdecrew', tx.from, tx.hash, res.farm_decrease_reward);
}
statuses.push(this.status_entry(Utils.TX_STATUS.CONFIRMED, tx));
console.silly(`approved tx `, Utils.JSON_stringify(tx));
substate.setState(substate_copy);
}
catch(err) {
statuses.push(this.status_entry(Utils.TX_STATUS.REJECTED, tx));
console.debug(`rejected tx ${JSON.stringify(tx)}. Reason: ${err}`);
}
}
time = process.hrtime(time);
console.debug(`cashier_timing: mblocks chunk ${hash} prepared in`, Utils.format_time(time));
let tokens_counts = {};
if(this.config.indexer_mode === 1){
for(let st of statuses){
if ((st.status === Utils.TX_STATUS.REJECTED) || (st.status === Utils.TX_STATUS.CONFIRMED)) {
this.eindex_entry(rewards, 'iin', st.to, st.hash, st.amount);
this.eindex_entry(rewards, 'iout', st.from, st.hash, st.amount);
}
if (st.status === Utils.TX_STATUS.CONFIRMED) {
if(tokens_counts[st.ticker] === undefined)
tokens_counts[st.ticker] = 0;
tokens_counts[st.ticker]++;
}
}
}
//return;
time = process.hrtime();
await this.db.process_ledger_mblocks_002(statuses, chunk.mblocks, rewards, kblock, tokens_counts, substate);
time = process.hrtime(time);
console.debug(`cashier_timing: mblocks chunk ${hash} saved in`, Utils.format_time(time));
}
async ledger_update_000(kblock, limit) {
let hash = kblock.hash;
let accounts = [];
let statuses = [];
let post_action = [];
let tickers = [];
let token_changes = {};
let contracts = {};
let delegation_ledger = {};
let transfer_ledger = {};
let block_fees = BigInt(0);
let total_pos_stake = BigInt(0);
let time = process.hrtime();
let rewards = [];
//console.debug(`cashier processing macroblock ${hash}`);
console.trace(`cashier processing macroblock ${JSON.stringify(kblock)}`);
let chunk = await this.db.get_new_microblocks(hash, limit);
let CMachine = ContractMachine.getContractMachine(this.config.FORKS, kblock.n);
let CFactory = new ContractMachine.ContractFactory(this.config);
console.silly('cashier chunk = ', JSON.stringify(chunk));
console.debug(`cashier is processing chunk ${hash} of ${chunk.mblocks.length} mblocks with ${chunk.txs ? chunk.txs.length : "NaN"} txs`);
/**
* No mblocs means that all mblocks in kblock were calculated, time to close kblock
* or
* empty kblock
*/
if (chunk.mblocks.length === 0) {
console.debug(`No more blocks in kblock ${hash}, terminating`);
let mblocks = await this.db.get_included_microblocks(kblock.hash);
let sblocks = await this.db.get_new_statblocks(hash);
let mblock_tokens = [];
let mblock_pubs = {};
let tok_obj = {};
let supply_change = {};
let total_reward = BigInt(0);
accounts.push(this.db.ORIGIN.publisher);
accounts.push(kblock.publisher);
accounts = accounts.concat(mblocks.map(m => m.publisher));
accounts = accounts.concat(mblocks.map(m => m.referrer));
// Add pos owners to sblocks and accounts array
if (sblocks.length !== 0) {
let poses = await this.db.get_pos_contract_all();
for(let sb of sblocks){
let pos = poses.find(p => p.id === sb.publisher);
if(pos){
sb.pos_owner = pos.owner;
accounts.push(sb.pos_owner);
}
}
}
/**
* 1. Get all mblocks from database
* 2. Get all involved tokens
* 3. Get all token info - create tokens array with block rewards & refrewards
* 4. Filter mblocks by only existing & minable tokens
* 4. Add all token owners to accounts
* 5. Build object :
* {
* "token_hash_1" : {
* block_reward : 15,
* ref_share : 1000,
* total_poa_stake : 0,
* total_poa_rew : 0,
* min_stake : 25,
* max_stake : 1000,
* referrer_stake : 1000
* }
* }
* 6. Create object with pub stakes
*
*/
mblock_tokens = mblock_tokens.concat(mblocks.map(m => m.token));
let tokens = await this.db.get_tokens(mblock_tokens);
let token_enq = (await this.db.get_tokens([Utils.ENQ_TOKEN_NAME]))[0];
accounts = accounts.concat(tokens.map(tok => tok.owner));
accounts = accounts.filter((v, i, a) => a.indexOf(v) === i);
accounts = accounts.filter(v => v !== null);
accounts = await this.db.get_accounts_all(accounts);
/**
* mblocks & refrewards calculation
*/
for(let tok of tokens){
tok_obj[tok.hash] = tok;
tok_obj[tok.hash].total_poa_stake = BigInt(0);
if(tok.hash === Utils.ENQ_TOKEN_NAME){
tok_obj[tok.hash].total_poa_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.poa) / Utils.PERCENT_FORMAT_SIZE;
tok_obj[tok.hash].max_stake = BigInt(this.config.stake_limits.max_stake);
}
else{
// Check token emission.
if(tok.block_reward > (tok.max_supply - tok.total_supply)){
tok.block_reward = BigInt(0);
console.info(`${tok.ticker} token emission is over, setting mreward to 0`)
}
tok_obj[tok.hash].total_poa_reward = BigInt(tok.block_reward) * BigInt(Utils.PERCENT_FORMAT_SIZE) / (BigInt(Utils.PERCENT_FORMAT_SIZE) + BigInt(tok.ref_share));
}
}
let total_pos_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.pos) / Utils.PERCENT_FORMAT_SIZE;
let org = accounts.findIndex(a => ((a.id === this.db.ORIGIN.publisher) && (a.token === Utils.ENQ_TOKEN_NAME)));
for(let i = 0; i < mblocks.length; i++){
let block = mblocks[i];
let pub = accounts.findIndex(a => ((a.id === block.publisher) && (a.token === block.token)));
mblock_pubs[block.hash] = {};
if(block.token === Utils.ENQ_TOKEN_NAME){
let stake = BigInt(0);
if (pub > -1) {
stake = (accounts[pub].amount > stake) ? accounts[pub].amount : stake;
stake = (stake > tok_obj[block.token].max_stake) ? tok_obj[block.token].max_stake : stake;
}
tok_obj[block.token].total_poa_stake += BigInt(stake);
mblock_pubs[block.hash].stake = BigInt(stake);
}
else{
tok_obj[block.token].total_poa_stake += BigInt(accounts[pub].amount);
mblock_pubs[block.hash].stake = BigInt(accounts[pub].amount);
}
}
for(let i = 0; i < mblocks.length; i++){
let total_mblock_reward = BigInt(0);
let m = mblocks[i];
if(!supply_change.hasOwnProperty(m.token))
supply_change[m.token] = BigInt(0);
let pub = accounts.findIndex(a => ((a.id === m.publisher) && (a.token === m.token)));
let owner = accounts.findIndex(a => ((a.id === tok_obj[m.token].owner) && (a.token === m.token)));
let stake = mblock_pubs[m.hash].stake;
if (pub > -1 && tok_obj[m.token].total_poa_stake > BigInt(0)) {
m.reward = BigInt(stake) * tok_obj[m.token].total_poa_reward / tok_obj[m.token].total_poa_stake;
accounts[pub].amount = BigInt(accounts[pub].amount) + m.reward;
total_mblock_reward += m.reward;
this.mrewards += m.reward;
this.eindex_entry(rewards, 'im', accounts[pub].id, m.hash, m.reward);
} else {
console.warn(`PoA miner with low-stake detected at mblock ${JSON.stringify(m)}`);
m.reward = BigInt(0);
total_mblock_reward += m.reward;
if(pub < 0){
accounts.push({id: m.publisher, amount: m.reward, token: m.token});
pub = accounts.findIndex(a => ((a.id === m.publisher) && (a.token === m.token)));
}
this.mrewards += m.reward;
}
let ref = accounts.findIndex(a => ((a.id === m.referrer) && (a.token === m.token)));
//let ref_reward = BigInt(m.reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref);
let ref_reward = BigInt(m.reward) * BigInt(tok_obj[m.token].ref_share) / BigInt(Utils.PERCENT_FORMAT_SIZE);
if (ref > -1) {
let real_ref;
if (accounts[ref].amount >= tok_obj[m.token].referrer_stake) {
real_ref = ref;
} else {
real_ref = owner;
}
accounts[pub].amount = BigInt(accounts[pub].amount) + ref_reward / BigInt(2);
accounts[real_ref].amount = BigInt(accounts[real_ref].amount) + ref_reward / BigInt(2);
total_mblock_reward += ((ref_reward / BigInt(2)) * BigInt(2));
this.refrewards += ref_reward;
this.eindex_entry(rewards, 'iref', accounts[pub].id, m.hash, ref_reward / BigInt(2));
this.eindex_entry(rewards, 'iref', accounts[real_ref].id, m.hash, ref_reward / BigInt(2));
} else {
accounts[owner].amount = BigInt(accounts[owner].amount) + ref_reward;
this.eindex_entry(rewards, 'iref', accounts[owner].id, m.hash, ref_reward);
total_mblock_reward += ref_reward;
this.refrewards += ref_reward;
}
if(m.token === Utils.ENQ_TOKEN_NAME){
total_reward += total_mblock_reward;
}
else{
// Token dust collecting
let mref = m.reward + ref_reward;
accounts[owner].amount = BigInt(accounts[owner].amount) + (mref - total_mblock_reward);
// In this cycle we change supply_change object only for minable tokens
// ENQ supply change will be made before block termination call
supply_change[m.token] += total_mblock_reward;
}
}
// calc total poa stake
//if(total_poa_stake > 0 && mblocks.length !== 0){
// }
// else {
// // TODO: this code handle reward leakage on zero-stake mblock publisher (bad thing)
// // TODO: this code handle reward leakage on empty kblock with no mblocks (bad thing)
// if(kblock.n !== 0){
// accounts[org].amount = BigInt(accounts[org].amount) + BigInt(total_poa_reward) + (BigInt(total_poa_reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref));
// this.mrewards += total_poa_reward;
// this.refrewards += (BigInt(total_poa_reward) / BigInt(this.config.reward_ratio.poa) * BigInt(this.config.reward_ratio.ref));
// }
// }
/**
* Kblock reward
*/
let total_pow_reward = BigInt(token_enq.block_reward) * BigInt(this.config.reward_ratio.pow) / Utils.PERCENT_FORMAT_SIZE;
kblock.reward = BigInt(total_pow_reward);
let k_pub = accounts.findIndex(a => ((a.id === kblock.publisher) && (a.token === Utils.ENQ_TOKEN_NAME)));
if (k_pub > -1) {
accounts[k_pub].amount = BigInt(accounts[k_pub].amount) + BigInt(kblock.reward);
total_reward += BigInt(kblock.reward);
this.krewards += kblock.reward;
} else {
accounts.push({id: kblock.publisher, amount: kblock.reward, token: Utils.ENQ_TOKEN_NAME});
total_reward += BigInt(kblock.reward);
this.krewards += kblock.reward;
}
this.eindex_entry(rewards, 'ik', kblock.publisher, kblock.hash, kblock.reward);
/**
* POS rewards
*
* - Total reward for all POS-contracts:
* pos_reward = block_reward * pos_ratio
*
* - Total reward for single POS-contract:
* contract_reward = pos_reward * contract_stake / total_pos_stake
*
* - Total reward splits between pos_owner and delegators
* pos_owner_reward = fee * contract_reward
* delegates_reward = contract_reward - owner_reward
*
* - Single delegator reward:
* delegate_reward = delegate_stake * delegates_reward / contract_stake
*/
let pos_info = await this.db.get_pos_info(sblocks.map(s => s.publisher));
//Sum total pos stake
sblocks = sblocks.filter(s => {
let pub = pos_info.findIndex(a => a.pos_id === s.publisher);
if (pub > -1){
total_pos_stake += BigInt(pos_info[pub].stake);
return true;
}
else
return false;
});
//Calc pos rewards
if((total_pos_stake > 0) && (sblocks.length > 0)){
let cont = new CMachine.Contract();
for(let s of sblocks) {
let pub = accounts.findIndex(a => ((a.id === s.pos_owner) && (a.token === Utils.ENQ_TOKEN_NAME)));
let delegate = pos_info.findIndex(a => a.pos_id === s.publisher);
let contract_reward = total_pos_reward * BigInt(pos_info[delegate].stake) / total_pos_stake;
let pos_owner_reward = BigInt(pos_info[delegate].fee) * contract_reward / Utils.PERCENT_FORMAT_SIZE;
let delegates_reward = contract_reward - pos_owner_reward;
s.reward = contract_reward;
// calc for all delegators
let delegators = await this.db.get_pos_delegators(s.publisher);
for(let del of delegators){
// Add new reward to old for post_action
if(pos_info[delegate].stake > 0){
// TODO: possible reward leakage SET reward = ?
let del_reward = BigInt(del.amount) * delegates_reward / BigInt(pos_info[delegate].stake);
if(del_reward > BigInt(0)) {
total_reward += BigInt(del_reward);
let sql = cont.mysql.format(`(?, ?, ?)`,
[del.pos_id, del.delegator, del_reward]);
post_action = post_action.concat([sql]);
}
}
}
accounts[pub].amount = BigInt(accounts[pub].amount) + pos_owner_reward;
total_reward += BigInt(pos_owner_reward);
this.eindex_entry(rewards,'iv', accounts[pub].id, s.hash, pos_owner_reward);
this.eindex_entry(rewards, 'istat', s.publisher, s.hash, s.reward);
this.srewards += pos_owner_reward;
this.srewards += delegates_reward;
}
}
else{
if(kblock.n !== 0){
accounts[org].amount = BigInt(accounts[org].amount) + total_pos_reward;
this.srewards += total_pos_reward;
}
}
/**
* Fee distribution
*/
// Now we can't define LPoS so we set ldr_share to 0
let ldr_acc;
let total_fee = BigInt(0);
let kblock_tx_count = await this.db.get_kblock_txs_count(kblock.hash);
let native_fee = BigInt(Utils.calc_fee(token_enq, 0));
let kblock_fees = BigInt(kblock_tx_count) * native_fee;
//accounts[org].amount = BigInt(accounts[org].amount) + BigInt(kblock_fees);
let fee_shares = this.config.fee_shares;
let pow_fee_share = kblock_fees * BigInt(fee_shares.pow_share) / Utils.PERCENT_FORMAT_SIZE;
let org_fee_share = kblock_fees * BigInt(fee_shares.gen_share) / Utils.PERCENT_FORMAT_SIZE;
let ldr_fee_share = kblock_fees * BigInt(fee_shares.ldr_share) / Utils.PERCENT_FORMAT_SIZE;
let pos_fee_share = kblock_fees * BigInt(fee_shares.pos_share) / Utils.PERCENT_FORMAT_SIZE;
if (k_pub > -1) {
accounts[k_pub].amount = BigInt(accounts[k_pub].amount) + BigInt(pow_fee_share);
this.eindex_entry(rewards, 'ifk', accounts[k_pub].id, kblock.hash, BigInt(pow_fee_share));
total_fee += BigInt(pow_fee_share);
} else
org_fee_share += pow_fee_share;
if (org > -1) {
accounts[org].amount = BigInt(accounts[org].amount) + BigInt(org_fee_share);
this.eindex_entry(rewards, 'ifg', accounts[org].id, kblock.hash, BigInt(org_fee_share));
total_fee += BigInt(org_fee_share);
}
if((total_pos_stake > 0) && (sblocks.length > 0)){
let cont = new CMachine.Contract();
for(let s of sblocks) {
let pub = accounts.findIndex(a => ((a.id === s.pos_owner) && (a.token === Utils.ENQ_TOKEN_NAME)));
let delegate = pos_info.findIndex(a => a.pos_id === s.publisher);
let contract_fee_reward = pos_fee_share * BigInt(pos_info[delegate].stake) / total_pos_stake;
let pos_owner_fee_reward = BigInt(pos_info[delegate].fee) * contract_fee_reward / Utils.PERCENT_FORMAT_SIZE;
let delegates_fee_reward = contract_fee_reward - pos_owner_fee_reward;
// calc for all delegators
let delegators = await this.db.get_pos_delegators(s.publisher);
for (let del of delegators) {
// Add new reward to old for post_action
if (pos_info[delegate].stake > 0) {
let del_reward = BigInt(del.amount) * delegates_fee_reward / BigInt(pos_info[delegate].stake);
if(del_reward > BigInt(0)){
total_fee += BigInt(del_reward);
let sql = cont.mysql.format(`(?, ?, ?)`,
[del.pos_id, del.delegator, del_reward]);
post_action = post_action.concat([sql]);
}
}
}
accounts[pub].amount = BigInt(accounts[pub].amount) + pos_owner_fee_reward;
this.eindex_entry(rewards, 'iv', accounts[pub].id, kblock.hash, BigInt(pos_owner_fee_reward));
total_fee += BigInt(pos_owner_fee_reward);
}
}
else {
accounts[org].amount = BigInt(accounts[org].amount) + pos_fee_share;
total_fee += BigInt(pos_fee_share);
}
let dust_block = BigInt(token_enq.block_reward) - BigInt(total_reward);
let dust_fees = BigInt(kblock_fees) - BigInt(total_fee);
accounts[org].amount += dust_block + dust_fees;