-
Notifications
You must be signed in to change notification settings - Fork 122
/
validation.cpp
2373 lines (1955 loc) · 102 KB
/
validation.cpp
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
// Copyright (c) DeFi Blockchain Developers
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <masternodes/accountshistory.h>
#include <masternodes/govvariables/attributes.h>
#include <masternodes/govvariables/loan_daily_reward.h>
#include <masternodes/govvariables/lp_daily_dfi_reward.h>
#include <masternodes/govvariables/lp_splits.h>
#include <masternodes/govvariables/loan_splits.h>
#include <masternodes/masternodes.h>
#include <masternodes/mn_checks.h>
#include <masternodes/mn_rpc.h>
#include <masternodes/validation.h>
#include <masternodes/vaulthistory.h>
#include <validation.h>
#include <boost/asio.hpp>
#define MILLI 0.001
template<typename GovVar>
static void UpdateDailyGovVariables(const std::map<CommunityAccountType, uint32_t>::const_iterator& incentivePair, CCustomCSView& cache, int nHeight) {
if (incentivePair != Params().GetConsensus().newNonUTXOSubsidies.end())
{
CAmount subsidy = CalculateCoinbaseReward(GetBlockSubsidy(nHeight, Params().GetConsensus()), incentivePair->second);
subsidy *= Params().GetConsensus().blocksPerDay();
// Change daily LP reward if it has changed
auto var = cache.GetVariable(GovVar::TypeName());
if (var) {
// Cast to avoid UniValue in GovVariable Export/ImportserliazedSplits.emplace(it.first.v, it.second);
auto lpVar = dynamic_cast<GovVar*>(var.get());
if (lpVar && lpVar->dailyReward != subsidy) {
lpVar->dailyReward = subsidy;
lpVar->Apply(cache, nHeight);
cache.SetVariable(*lpVar);
}
}
}
}
static void ProcessRewardEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams) {
// Hard coded LP_DAILY_DFI_REWARD change
if (pindex->nHeight >= chainparams.GetConsensus().EunosHeight)
{
const auto& incentivePair = chainparams.GetConsensus().newNonUTXOSubsidies.find(CommunityAccountType::IncentiveFunding);
UpdateDailyGovVariables<LP_DAILY_DFI_REWARD>(incentivePair, cache, pindex->nHeight);
}
// Hard coded LP_DAILY_LOAN_TOKEN_REWARD change
if (pindex->nHeight >= chainparams.GetConsensus().FortCanningHeight)
{
const auto& incentivePair = chainparams.GetConsensus().newNonUTXOSubsidies.find(CommunityAccountType::Loan);
UpdateDailyGovVariables<LP_DAILY_LOAN_TOKEN_REWARD>(incentivePair, cache, pindex->nHeight);
}
// hardfork commissions update
const auto distributed = cache.UpdatePoolRewards(
[&](CScript const & owner, DCT_ID tokenID) {
cache.CalculateOwnerRewards(owner, pindex->nHeight);
return cache.GetBalance(owner, tokenID);
},
[&](CScript const & from, CScript const & to, CTokenAmount amount) {
if (!from.empty()) {
auto res = cache.SubBalance(from, amount);
if (!res) {
LogPrintf("Custom pool rewards: can't subtract balance of %s: %s, height %ld\n", from.GetHex(), res.msg, pindex->nHeight);
return res;
}
}
if (!to.empty()) {
auto res = cache.AddBalance(to, amount);
if (!res) {
LogPrintf("Can't apply reward to %s: %s, %ld\n", to.GetHex(), res.msg, pindex->nHeight);
return res;
}
cache.UpdateBalancesHeight(to, pindex->nHeight + 1);
}
return Res::Ok();
},
pindex->nHeight
);
auto res = cache.SubCommunityBalance(CommunityAccountType::IncentiveFunding, distributed.first);
if (!res.ok) {
LogPrintf("Pool rewards: can't update community balance: %s. Block %ld (%s)\n", res.msg, pindex->nHeight, pindex->phashBlock->GetHex());
} else {
if (distributed.first != 0)
LogPrint(BCLog::ACCOUNTCHANGE, "AccountChange: event=ProcessRewardEvents fund=%s change=%s\n", GetCommunityAccountName(CommunityAccountType::IncentiveFunding), (CBalances{{{{0}, -distributed.first}}}.ToString()));
}
if (pindex->nHeight >= chainparams.GetConsensus().FortCanningHeight) {
res = cache.SubCommunityBalance(CommunityAccountType::Loan, distributed.second);
if (!res.ok) {
LogPrintf("Pool rewards: can't update community balance: %s. Block %ld (%s)\n", res.msg, pindex->nHeight, pindex->phashBlock->GetHex());
} else {
if (distributed.second != 0)
LogPrint(BCLog::ACCOUNTCHANGE, "AccountChange: event=ProcessRewardEvents fund=%s change=%s\n", GetCommunityAccountName(CommunityAccountType::Loan), (CBalances{{{{0}, -distributed.second}}}.ToString()));
}
}
}
static void ProcessICXEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams) {
if (pindex->nHeight < chainparams.GetConsensus().EunosHeight) {
return;
}
bool isPreEunosPaya = pindex->nHeight < chainparams.GetConsensus().EunosPayaHeight;
cache.ForEachICXOrderExpire([&](CICXOrderView::StatusKey const& key, uint8_t status) {
if (static_cast<int>(key.first) != pindex->nHeight)
return false;
auto order = cache.GetICXOrderByCreationTx(key.second);
if (!order)
return true;
if (order->orderType == CICXOrder::TYPE_INTERNAL) {
CTokenAmount amount{order->idToken, order->amountToFill};
CScript txidaddr(order->creationTx.begin(), order->creationTx.end());
auto res = cache.SubBalance(txidaddr, amount);
if (!res)
LogPrintf("Can't subtract balance from order (%s) txidaddr: %s\n", order->creationTx.GetHex(), res.msg);
else {
cache.CalculateOwnerRewards(order->ownerAddress, pindex->nHeight);
cache.AddBalance(order->ownerAddress, amount);
}
}
cache.ICXCloseOrderTx(*order, status);
return true;
}, pindex->nHeight);
cache.ForEachICXMakeOfferExpire([&](CICXOrderView::StatusKey const& key, uint8_t status) {
if (static_cast<int>(key.first) != pindex->nHeight)
return false;
auto offer = cache.GetICXMakeOfferByCreationTx(key.second);
if (!offer)
return true;
auto order = cache.GetICXOrderByCreationTx(offer->orderTx);
if (!order)
return true;
CScript txidAddr(offer->creationTx.begin(), offer->creationTx.end());
CTokenAmount takerFee{DCT_ID{0}, offer->takerFee};
if ((order->orderType == CICXOrder::TYPE_INTERNAL && !cache.ExistedICXSubmitDFCHTLC(offer->creationTx, isPreEunosPaya)) ||
(order->orderType == CICXOrder::TYPE_EXTERNAL && !cache.ExistedICXSubmitEXTHTLC(offer->creationTx, isPreEunosPaya))) {
auto res = cache.SubBalance(txidAddr, takerFee);
if (!res)
LogPrintf("Can't subtract takerFee from offer (%s) txidAddr: %s\n", offer->creationTx.GetHex(), res.msg);
else {
cache.CalculateOwnerRewards(offer->ownerAddress, pindex->nHeight);
cache.AddBalance(offer->ownerAddress, takerFee);
}
}
cache.ICXCloseMakeOfferTx(*offer, status);
return true;
}, pindex->nHeight);
cache.ForEachICXSubmitDFCHTLCExpire([&](CICXOrderView::StatusKey const& key, uint8_t status) {
if (static_cast<int>(key.first) != pindex->nHeight)
return false;
auto dfchtlc = cache.GetICXSubmitDFCHTLCByCreationTx(key.second);
if (!dfchtlc)
return true;
auto offer = cache.GetICXMakeOfferByCreationTx(dfchtlc->offerTx);
if (!offer)
return true;
auto order = cache.GetICXOrderByCreationTx(offer->orderTx);
if (!order)
return true;
bool refund = false;
if (status == CICXSubmitDFCHTLC::STATUS_EXPIRED && order->orderType == CICXOrder::TYPE_INTERNAL) {
if (!cache.ExistedICXSubmitEXTHTLC(dfchtlc->offerTx, isPreEunosPaya)) {
CTokenAmount makerDeposit{DCT_ID{0}, offer->takerFee};
cache.CalculateOwnerRewards(order->ownerAddress, pindex->nHeight);
cache.AddBalance(order->ownerAddress, makerDeposit);
refund = true;
}
} else if (status == CICXSubmitDFCHTLC::STATUS_REFUNDED)
refund = true;
if (refund) {
CScript ownerAddress;
if (order->orderType == CICXOrder::TYPE_INTERNAL)
ownerAddress = CScript(order->creationTx.begin(), order->creationTx.end());
else if (order->orderType == CICXOrder::TYPE_EXTERNAL)
ownerAddress = offer->ownerAddress;
CTokenAmount amount{order->idToken, dfchtlc->amount};
CScript txidaddr = CScript(dfchtlc->creationTx.begin(), dfchtlc->creationTx.end());
auto res = cache.SubBalance(txidaddr, amount);
if (!res)
LogPrintf("Can't subtract balance from dfc htlc (%s) txidaddr: %s\n", dfchtlc->creationTx.GetHex(), res.msg);
else {
cache.CalculateOwnerRewards(ownerAddress, pindex->nHeight);
cache.AddBalance(ownerAddress, amount);
}
cache.ICXCloseDFCHTLC(*dfchtlc, status);
}
return true;
}, pindex->nHeight);
cache.ForEachICXSubmitEXTHTLCExpire([&](CICXOrderView::StatusKey const& key, uint8_t status) {
if (static_cast<int>(key.first) != pindex->nHeight)
return false;
auto exthtlc = cache.GetICXSubmitEXTHTLCByCreationTx(key.second);
if (!exthtlc)
return true;
auto offer = cache.GetICXMakeOfferByCreationTx(exthtlc->offerTx);
if (!offer)
return true;
auto order = cache.GetICXOrderByCreationTx(offer->orderTx);
if (!order)
return true;
if (status == CICXSubmitEXTHTLC::STATUS_EXPIRED && order->orderType == CICXOrder::TYPE_EXTERNAL) {
if (!cache.ExistedICXSubmitDFCHTLC(exthtlc->offerTx, isPreEunosPaya)) {
CTokenAmount makerDeposit{DCT_ID{0}, offer->takerFee};
cache.CalculateOwnerRewards(order->ownerAddress, pindex->nHeight);
cache.AddBalance(order->ownerAddress, makerDeposit);
cache.ICXCloseEXTHTLC(*exthtlc, status);
}
}
return true;
}, pindex->nHeight);
}
static uint32_t GetNextBurnPosition() {
return nPhantomBurnTx++;
}
// Burn non-transaction amounts, that is burns that are not sent directly to the burn address
// in a account or UTXO transaction. When parsing TXs via ConnectBlock that result in a burn
// from an account in this way call the function below. This will add the burn to the map to
// be added to the burn index as a phantom TX appended to the end of the connecting block.
Res AddNonTxToBurnIndex(const CScript& from, const CBalances& amounts)
{
return mapBurnAmounts[from].AddBalances(amounts.balances);
}
static void ProcessEunosEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams) {
if (pindex->nHeight != chainparams.GetConsensus().EunosHeight) {
return;
}
// Move funds from old burn address to new one
CBalances burnAmounts;
cache.ForEachBalance([&burnAmounts](CScript const & owner, CTokenAmount balance) {
if (owner != Params().GetConsensus().retiredBurnAddress) {
return false;
}
burnAmounts.Add({balance.nTokenId, balance.nValue});
return true;
}, BalanceKey{chainparams.GetConsensus().retiredBurnAddress, DCT_ID{}});
AddNonTxToBurnIndex(chainparams.GetConsensus().retiredBurnAddress, burnAmounts);
// Zero foundation balances
for (const auto& script : chainparams.GetConsensus().accountDestruction)
{
CBalances zeroAmounts;
cache.ForEachBalance([&zeroAmounts, script](CScript const & owner, CTokenAmount balance) {
if (owner != script) {
return false;
}
zeroAmounts.Add({balance.nTokenId, balance.nValue});
return true;
}, BalanceKey{script, DCT_ID{}});
cache.SubBalances(script, zeroAmounts);
}
// Add any non-Tx burns to index as phantom Txs
for (const auto& item : mapBurnAmounts)
{
for (const auto& subItem : item.second.balances)
{
// If amount cannot be deducted then burn skipped.
auto result = cache.SubBalance(item.first, {subItem.first, subItem.second});
if (result.ok)
{
cache.AddBalance(chainparams.GetConsensus().burnAddress, {subItem.first, subItem.second});
// Add transfer as additional TX in block
pburnHistoryDB->WriteAccountHistory({Params().GetConsensus().burnAddress, static_cast<uint32_t>(pindex->nHeight), GetNextBurnPosition()},
{uint256{}, static_cast<uint8_t>(CustomTxType::AccountToAccount), {{subItem.first, subItem.second}}});
}
else // Log burn failure
{
CTxDestination dest;
ExtractDestination(item.first, dest);
LogPrintf("Burn failed: %s Address: %s Token: %d Amount: %d\n", result.msg, EncodeDestination(dest), subItem.first.v, subItem.second);
}
}
}
mapBurnAmounts.clear();
}
static void ProcessOracleEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams){
if (pindex->nHeight < chainparams.GetConsensus().FortCanningHeight) {
return;
}
auto blockInterval = cache.GetIntervalBlock();
if (pindex->nHeight % blockInterval != 0) {
return;
}
cache.ForEachFixedIntervalPrice([&](const CTokenCurrencyPair&, CFixedIntervalPrice fixedIntervalPrice){
// Ensure that we update active and next regardless of state of things
// And SetFixedIntervalPrice on each evaluation of this block.
// As long as nextPrice exists, move the buffers.
// If nextPrice doesn't exist, active price is retained.
// nextPrice starts off as empty. Will be replaced by the next
// aggregate, as long as there's a new price available.
// If there is no price, nextPrice will remain empty.
// This guarantees that the last price will continue to exists,
// while the overall validity check still fails.
// Furthermore, the time stamp is always indicative of the
// last price time.
auto nextPrice = fixedIntervalPrice.priceRecord[1];
if (nextPrice > 0) {
fixedIntervalPrice.priceRecord[0] = fixedIntervalPrice.priceRecord[1];
}
// keep timestamp updated
fixedIntervalPrice.timestamp = pindex->nTime;
// Use -1 to indicate empty price
fixedIntervalPrice.priceRecord[1] = -1;
auto aggregatePrice = GetAggregatePrice(cache,
fixedIntervalPrice.priceFeedId.first,
fixedIntervalPrice.priceFeedId.second,
pindex->nTime);
if (aggregatePrice) {
fixedIntervalPrice.priceRecord[1] = aggregatePrice;
} else {
LogPrint(BCLog::ORACLE,"ProcessOracleEvents(): No aggregate price available: %s\n", aggregatePrice.msg);
}
auto res = cache.SetFixedIntervalPrice(fixedIntervalPrice);
if (!res) {
LogPrintf("Error: SetFixedIntervalPrice failed: %s\n", res.msg);
}
return true;
});
}
std::vector<CAuctionBatch> CollectAuctionBatches(const CCollateralLoans& collLoan, const TAmounts& collBalances, const TAmounts& loanBalances)
{
constexpr const uint64_t batchThreshold = 10000 * COIN; // 10k USD
auto totalCollateralsValue = collLoan.totalCollaterals;
auto totalLoansValue = collLoan.totalLoans;
auto maxCollateralsValue = totalCollateralsValue;
auto maxLoansValue = totalLoansValue;
auto maxCollBalances = collBalances;
auto CreateAuctionBatch = [&maxCollBalances, &collBalances](CTokenAmount loanAmount, CAmount chunk) {
CAuctionBatch batch{};
batch.loanAmount = loanAmount;
for (const auto& tAmount : collBalances) {
auto& maxCollBalance = maxCollBalances[tAmount.first];
auto collValue = std::min(MultiplyAmounts(tAmount.second, chunk), maxCollBalance);
batch.collaterals.Add({tAmount.first, collValue});
maxCollBalance -= collValue;
}
return batch;
};
std::vector<CAuctionBatch> batches;
for (const auto& loan : collLoan.loans) {
auto maxLoanAmount = loanBalances.at(loan.nTokenId);
auto loanChunk = std::min(uint64_t(DivideAmounts(loan.nValue, totalLoansValue)), maxLoansValue);
auto collateralChunkValue = std::min(uint64_t(MultiplyAmounts(loanChunk, totalCollateralsValue)), maxCollateralsValue);
if (collateralChunkValue > batchThreshold) {
auto chunk = DivideAmounts(batchThreshold, collateralChunkValue);
auto loanAmount = MultiplyAmounts(maxLoanAmount, chunk);
for (auto chunks = COIN; chunks > 0; chunks -= chunk) {
chunk = std::min(chunk, chunks);
loanAmount = std::min(loanAmount, maxLoanAmount);
auto collateralChunk = MultiplyAmounts(chunk, loanChunk);
batches.push_back(CreateAuctionBatch({loan.nTokenId, loanAmount}, collateralChunk));
maxLoanAmount -= loanAmount;
}
} else {
auto loanAmount = CTokenAmount{loan.nTokenId, maxLoanAmount};
batches.push_back(CreateAuctionBatch(loanAmount, loanChunk));
}
maxLoansValue -= loan.nValue;
maxCollateralsValue -= collateralChunkValue;
}
// return precision loss balanced
for (auto& collateral : maxCollBalances) {
auto it = batches.begin();
auto lastValue = collateral.second;
while (collateral.second > 0) {
if (it == batches.end()) {
it = batches.begin();
if (lastValue == collateral.second) {
// we fail to update any batch
// extreme small collateral going to first batch
it->collaterals.Add({collateral.first, collateral.second});
break;
}
lastValue = collateral.second;
}
if (it->collaterals.balances.count(collateral.first) > 0) {
it->collaterals.Add({collateral.first, 1});
--collateral.second;
}
++it;
}
}
return batches;
}
static void ProcessLoanEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams)
{
if (pindex->nHeight < chainparams.GetConsensus().FortCanningHeight) {
return;
}
std::vector<CLoanSchemeMessage> loanUpdates;
cache.ForEachDelayedLoanScheme([&pindex, &loanUpdates](const std::pair<std::string, uint64_t>& key, const CLoanSchemeMessage& loanScheme) {
if (key.second == static_cast<uint64_t>(pindex->nHeight)) {
loanUpdates.push_back(loanScheme);
}
return true;
});
for (const auto& loanScheme : loanUpdates) {
// Make sure loan still exist, that it has not been destroyed in the mean time.
if (cache.GetLoanScheme(loanScheme.identifier)) {
cache.StoreLoanScheme(loanScheme);
}
cache.EraseDelayedLoanScheme(loanScheme.identifier, pindex->nHeight);
}
std::vector<std::string> loanDestruction;
cache.ForEachDelayedDestroyScheme([&pindex, &loanDestruction](const std::string& key, const uint64_t& height) {
if (height == static_cast<uint64_t>(pindex->nHeight)) {
loanDestruction.push_back(key);
}
return true;
});
for (const auto& loanDestroy : loanDestruction) {
cache.EraseLoanScheme(loanDestroy);
cache.EraseDelayedDestroyScheme(loanDestroy);
}
if (!loanDestruction.empty()) {
CCustomCSView viewCache(cache);
auto defaultLoanScheme = cache.GetDefaultLoanScheme();
cache.ForEachVault([&](const CVaultId& vaultId, CVaultData vault) {
if (!cache.GetLoanScheme(vault.schemeId)) {
vault.schemeId = *defaultLoanScheme;
viewCache.UpdateVault(vaultId, vault);
}
return true;
});
viewCache.Flush();
}
if (pindex->nHeight % chainparams.GetConsensus().blocksCollateralizationRatioCalculation() == 0) {
bool useNextPrice = false, requireLivePrice = true;
cache.ForEachVaultCollateral([&](const CVaultId& vaultId, const CBalances& collaterals) {
auto collateral = cache.GetLoanCollaterals(vaultId, collaterals, pindex->nHeight, pindex->nTime, useNextPrice, requireLivePrice);
if (!collateral) {
return true;
}
auto vault = cache.GetVault(vaultId);
assert(vault);
auto scheme = cache.GetLoanScheme(vault->schemeId);
assert(scheme);
if (scheme->ratio <= collateral.val->ratio()) {
// All good, within ratio, nothing more to do.
return true;
}
// Time to liquidate vault.
vault->isUnderLiquidation = true;
cache.StoreVault(vaultId, *vault);
auto loanTokens = cache.GetLoanTokens(vaultId);
assert(loanTokens);
// Get the interest rate for each loan token in the vault, find
// the interest value and move it to the totals, removing it from the
// vault, while also stopping the vault from accumulating interest
// further. Note, however, it's added back so that it's accurate
// for auction calculations.
CBalances totalInterest;
for (auto it = loanTokens->balances.begin(); it != loanTokens->balances.end();) {
const auto &[tokenId, tokenValue] = *it;
auto rate = cache.GetInterestRate(vaultId, tokenId, pindex->nHeight);
assert(rate);
auto subInterest = TotalInterest(*rate, pindex->nHeight);
if (subInterest > 0) {
totalInterest.Add({tokenId, subInterest});
}
// Remove loan from the vault
cache.SubLoanToken(vaultId, {tokenId, tokenValue});
if (const auto token = cache.GetToken("DUSD"); token && token->first == tokenId) {
TrackDUSDSub(cache, {tokenId, tokenValue});
}
// Remove interest from the vault
cache.DecreaseInterest(pindex->nHeight, vaultId, vault->schemeId, tokenId, tokenValue,
subInterest < 0 || (!subInterest && rate->interestPerBlock.negative) ? std::numeric_limits<CAmount>::max() : subInterest);
// Putting this back in now for auction calculations.
it->second += subInterest;
// If loan amount fully negated then remove it
if (it->second < 0) {
TrackNegativeInterest(cache, {tokenId, tokenValue});
it = loanTokens->balances.erase(it);
} else {
if (subInterest < 0) {
TrackNegativeInterest(cache, {tokenId, std::abs(subInterest)});
}
++it;
}
}
// Remove the collaterals out of the vault.
// (Prep to get the auction batches instead)
for (const auto& col : collaterals.balances) {
auto tokenId = col.first;
auto tokenValue = col.second;
cache.SubVaultCollateral(vaultId, {tokenId, tokenValue});
}
auto batches = CollectAuctionBatches(*collateral.val, collaterals.balances, loanTokens->balances);
// Now, let's add the remaining amounts and store the batch.
CBalances totalLoanInBatches{};
for (auto i = 0u; i < batches.size(); i++) {
auto& batch = batches[i];
totalLoanInBatches.Add(batch.loanAmount);
auto tokenId = batch.loanAmount.nTokenId;
auto interest = totalInterest.balances[tokenId];
if (interest > 0) {
auto balance = loanTokens->balances[tokenId];
auto interestPart = DivideAmounts(batch.loanAmount.nValue, balance);
batch.loanInterest = MultiplyAmounts(interestPart, interest);
totalLoanInBatches.Sub({tokenId, batch.loanInterest});
}
cache.StoreAuctionBatch({vaultId, i}, batch);
}
// Check if more than loan amount was generated.
CBalances balances;
for (const auto& [tokenId, amount] : loanTokens->balances) {
if (totalLoanInBatches.balances.count(tokenId)) {
const auto interest = totalInterest.balances.count(tokenId) ? totalInterest.balances[tokenId] : 0;
if (totalLoanInBatches.balances[tokenId] > amount - interest) {
balances.Add({tokenId, totalLoanInBatches.balances[tokenId] - (amount - interest)});
}
}
}
// Only store to attributes if there has been a rounding error.
if (!balances.balances.empty()) {
TrackLiveBalances(cache, balances, EconomyKeys::BatchRoundingExcess);
}
// All done. Ready to save the overall auction.
cache.StoreAuction(vaultId, CAuctionData{
uint32_t(batches.size()),
pindex->nHeight + chainparams.GetConsensus().blocksCollateralAuction(),
cache.GetLoanLiquidationPenalty()
});
// Store state in vault DB
if (pvaultHistoryDB) {
pvaultHistoryDB->WriteVaultState(cache, *pindex, vaultId, collateral.val->ratio());
}
return true;
});
}
CHistoryWriters writers{nullptr, pburnHistoryDB.get(), pvaultHistoryDB.get()};
CAccountsHistoryWriter view(cache, pindex->nHeight, ~0u, {}, uint8_t(CustomTxType::AuctionBid), &writers);
view.ForEachVaultAuction([&](const CVaultId& vaultId, const CAuctionData& data) {
if (data.liquidationHeight != uint32_t(pindex->nHeight)) {
return false;
}
auto vault = view.GetVault(vaultId);
assert(vault);
CBalances balances;
for (uint32_t i = 0; i < data.batchCount; i++) {
auto batch = view.GetAuctionBatch({vaultId, i});
assert(batch);
if (auto bid = view.GetAuctionBid({vaultId, i})) {
auto bidOwner = bid->first;
auto bidTokenAmount = bid->second;
auto penaltyAmount = MultiplyAmounts(batch->loanAmount.nValue, COIN + data.liquidationPenalty);
if (bidTokenAmount.nValue < penaltyAmount) {
LogPrintf("WARNING: bidTokenAmount.nValue(%d) < penaltyAmount(%d)\n",
bidTokenAmount.nValue, penaltyAmount);
}
// penaltyAmount includes interest, batch as well, so we should put interest back
// in result we have 5% penalty + interest via DEX to DFI and burn
auto amountToBurn = penaltyAmount - batch->loanAmount.nValue + batch->loanInterest;
if (amountToBurn > 0) {
CScript tmpAddress(vaultId.begin(), vaultId.end());
view.AddBalance(tmpAddress, {bidTokenAmount.nTokenId, amountToBurn});
SwapToDFIorDUSD(view, bidTokenAmount.nTokenId, amountToBurn, tmpAddress,
chainparams.GetConsensus().burnAddress, pindex->nHeight);
}
view.CalculateOwnerRewards(bidOwner, pindex->nHeight);
for (const auto& col : batch->collaterals.balances) {
auto tokenId = col.first;
auto tokenAmount = col.second;
view.AddBalance(bidOwner, {tokenId, tokenAmount});
}
auto amountToFill = bidTokenAmount.nValue - penaltyAmount;
if (amountToFill > 0) {
// return the rest as collateral to vault via DEX to DFI
CScript tmpAddress(vaultId.begin(), vaultId.end());
view.AddBalance(tmpAddress, {bidTokenAmount.nTokenId, amountToFill});
SwapToDFIorDUSD(view, bidTokenAmount.nTokenId, amountToFill, tmpAddress, tmpAddress, pindex->nHeight);
auto amount = view.GetBalance(tmpAddress, DCT_ID{0});
view.SubBalance(tmpAddress, amount);
view.AddVaultCollateral(vaultId, amount);
}
auto res = view.SubMintedTokens(batch->loanAmount.nTokenId, batch->loanAmount.nValue - batch->loanInterest);
if (!res) {
LogPrintf("AuctionBid: SubMintedTokens failed: %s\n", res.msg);
}
if (paccountHistoryDB) {
AuctionHistoryKey key{data.liquidationHeight, bidOwner, vaultId, i};
AuctionHistoryValue value{bidTokenAmount, batch->collaterals.balances};
paccountHistoryDB->WriteAuctionHistory(key, value);
}
} else {
// we should return loan including interest
view.AddLoanToken(vaultId, batch->loanAmount);
balances.Add({batch->loanAmount.nTokenId, batch->loanInterest});
// When tracking loan amounts remove interest.
if (const auto token = view.GetToken("DUSD"); token && token->first == batch->loanAmount.nTokenId) {
TrackDUSDAdd(view, {batch->loanAmount.nTokenId, batch->loanAmount.nValue - batch->loanInterest});
}
if (auto token = view.GetLoanTokenByID(batch->loanAmount.nTokenId)) {
view.IncreaseInterest(pindex->nHeight, vaultId, vault->schemeId, batch->loanAmount.nTokenId, token->interest, batch->loanAmount.nValue);
}
for (const auto& col : batch->collaterals.balances) {
auto tokenId = col.first;
auto tokenAmount = col.second;
view.AddVaultCollateral(vaultId, {tokenId, tokenAmount});
}
}
}
// Only store to attributes if there has been a rounding error.
if (!balances.balances.empty()) {
TrackLiveBalances(view, balances, EconomyKeys::ConsolidatedInterest);
}
vault->isUnderLiquidation = false;
view.StoreVault(vaultId, *vault);
view.EraseAuction(vaultId, pindex->nHeight);
// Store state in vault DB
if (pvaultHistoryDB) {
pvaultHistoryDB->WriteVaultState(view, *pindex, vaultId);
}
return true;
}, pindex->nHeight);
view.Flush();
pburnHistoryDB->Flush();
if (paccountHistoryDB) {
paccountHistoryDB->Flush();
}
}
static void ProcessFutures(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams)
{
if (pindex->nHeight < chainparams.GetConsensus().FortCanningRoadHeight) {
return;
}
auto attributes = cache.GetAttributes();
if (!attributes) {
return;
}
CDataStructureV0 activeKey{AttributeTypes::Param, ParamIDs::DFIP2203, DFIPKeys::Active};
CDataStructureV0 blockKey{AttributeTypes::Param, ParamIDs::DFIP2203, DFIPKeys::BlockPeriod};
CDataStructureV0 rewardKey{AttributeTypes::Param, ParamIDs::DFIP2203, DFIPKeys::RewardPct};
if (!attributes->GetValue(activeKey, false) ||
!attributes->CheckKey(blockKey) ||
!attributes->CheckKey(rewardKey)) {
return;
}
CDataStructureV0 startKey{AttributeTypes::Param, ParamIDs::DFIP2203, DFIPKeys::StartBlock};
const auto startBlock = attributes->GetValue(startKey, CAmount{});
if (pindex->nHeight < startBlock) {
return;
}
const auto blockPeriod = attributes->GetValue(blockKey, CAmount{});
if ((pindex->nHeight - startBlock) % blockPeriod != 0) {
return;
}
auto time = GetTimeMillis();
LogPrintf("Future swap settlement in progress.. (height: %d)\n", pindex->nHeight);
const auto rewardPct = attributes->GetValue(rewardKey, CAmount{});
const auto discount{COIN - rewardPct};
const auto premium{COIN + rewardPct};
std::map<DCT_ID, CFuturesPrice> futuresPrices;
CDataStructureV0 tokenKey{AttributeTypes::Token, 0, TokenKeys::DFIP2203Enabled};
std::vector<std::pair<DCT_ID, CLoanView::CLoanSetLoanTokenImpl>> loanTokens;
cache.ForEachLoanToken([&](const DCT_ID& id, const CLoanView::CLoanSetLoanTokenImpl& loanToken) {
tokenKey.typeId = id.v;
const auto enabled = attributes->GetValue(tokenKey, true);
if (!enabled) {
return true;
}
loanTokens.emplace_back(id, loanToken);
return true;
});
if (loanTokens.empty()) {
attributes->ForEach([&](const CDataStructureV0& attr, const CAttributeValue&) {
if (attr.type != AttributeTypes::Token) {
return false;
}
tokenKey.typeId = attr.typeId;
const auto enabled = attributes->GetValue(tokenKey, true);
if (!enabled) {
return true;
}
if (attr.key == TokenKeys::LoanMintingEnabled) {
auto tokenId = DCT_ID{attr.typeId};
if (auto loanToken = cache.GetLoanTokenFromAttributes(tokenId)) {
loanTokens.emplace_back(tokenId, *loanToken);
}
}
return true;
}, CDataStructureV0{AttributeTypes::Token});
}
for (const auto& [id, loanToken] : loanTokens) {
const auto useNextPrice{false}, requireLivePrice{true};
const auto discountPrice = cache.GetAmountInCurrency(discount, loanToken.fixedIntervalPriceId, useNextPrice, requireLivePrice);
const auto premiumPrice = cache.GetAmountInCurrency(premium, loanToken.fixedIntervalPriceId, useNextPrice, requireLivePrice);
if (!discountPrice || !premiumPrice) {
continue;
}
futuresPrices.emplace(id, CFuturesPrice{*discountPrice, *premiumPrice});
}
CDataStructureV0 burnKey{AttributeTypes::Live, ParamIDs::Economy, EconomyKeys::DFIP2203Burned};
CDataStructureV0 mintedKey{AttributeTypes::Live, ParamIDs::Economy, EconomyKeys::DFIP2203Minted};
auto burned = attributes->GetValue(burnKey, CBalances{});
auto minted = attributes->GetValue(mintedKey, CBalances{});
std::map<CFuturesUserKey, CFuturesUserValue> unpaidContracts;
std::set<CFuturesUserKey> deletionPending;
auto dUsdToTokenSwapsCounter = 0;
auto tokenTodUsdSwapsCounter = 0;
cache.ForEachFuturesUserValues([&](const CFuturesUserKey& key, const CFuturesUserValue& futuresValues){
CHistoryWriters writers{paccountHistoryDB.get(), nullptr, nullptr};
CAccountsHistoryWriter view(cache, pindex->nHeight, GetNextAccPosition(), {}, uint8_t(CustomTxType::FutureSwapExecution), &writers);
deletionPending.insert(key);
const auto source = view.GetLoanTokenByID(futuresValues.source.nTokenId);
assert(source);
if (source->symbol == "DUSD") {
const DCT_ID destId{futuresValues.destination};
const auto destToken = view.GetLoanTokenByID(destId);
assert(destToken);
try {
const auto& premiumPrice = futuresPrices.at(destId).premium;
if (premiumPrice > 0) {
const auto total = DivideAmounts(futuresValues.source.nValue, premiumPrice);
view.AddMintedTokens(destId, total);
CTokenAmount destination{destId, total};
view.AddBalance(key.owner, destination);
burned.Add(futuresValues.source);
minted.Add(destination);
dUsdToTokenSwapsCounter++;
LogPrint(BCLog::FUTURESWAP, "ProcessFutures (): Owner %s source %s destination %s\n",
key.owner.GetHex(), futuresValues.source.ToString(), destination.ToString());
}
} catch (const std::out_of_range&) {
unpaidContracts.emplace(key, futuresValues);
}
} else {
const auto tokenDUSD = view.GetToken("DUSD");
assert(tokenDUSD);
try {
const auto& discountPrice = futuresPrices.at(futuresValues.source.nTokenId).discount;
const auto total = MultiplyAmounts(futuresValues.source.nValue, discountPrice);
view.AddMintedTokens(tokenDUSD->first, total);
CTokenAmount destination{tokenDUSD->first, total};
view.AddBalance(key.owner, destination);
burned.Add(futuresValues.source);
minted.Add(destination);
tokenTodUsdSwapsCounter++;
LogPrint(BCLog::FUTURESWAP, "ProcessFutures (): Payment Owner %s source %s destination %s\n",
key.owner.GetHex(), futuresValues.source.ToString(), destination.ToString());
} catch (const std::out_of_range&) {
unpaidContracts.emplace(key, futuresValues);
}
}
view.Flush();
return true;
}, {static_cast<uint32_t>(pindex->nHeight), {}, std::numeric_limits<uint32_t>::max()});
const auto contractAddressValue = GetFutureSwapContractAddress(SMART_CONTRACT_DFIP_2203);
assert(contractAddressValue);
CDataStructureV0 liveKey{AttributeTypes::Live, ParamIDs::Economy, EconomyKeys::DFIP2203Current};
auto balances = attributes->GetValue(liveKey, CBalances{});
auto failedContractsCounter = unpaidContracts.size();
// Refund unpaid contracts
for (const auto& [key, value] : unpaidContracts) {
CHistoryWriters subWriters{paccountHistoryDB.get(), nullptr, nullptr};
CAccountsHistoryWriter subView(cache, pindex->nHeight, GetNextAccPosition(), {}, uint8_t(CustomTxType::FutureSwapRefund), &subWriters);
subView.SubBalance(*contractAddressValue, value.source);
subView.Flush();
CHistoryWriters addWriters{paccountHistoryDB.get(), nullptr, nullptr};
CAccountsHistoryWriter addView(cache, pindex->nHeight, GetNextAccPosition(), {}, uint8_t(CustomTxType::FutureSwapRefund), &addWriters);
addView.AddBalance(key.owner, value.source);
addView.Flush();
LogPrint(BCLog::FUTURESWAP, "%s: Refund Owner %s value %s\n",
__func__, key.owner.GetHex(), value.source.ToString());
balances.Sub(value.source);
}
for (const auto& key : deletionPending) {
cache.EraseFuturesUserValues(key);
}
attributes->SetValue(burnKey, std::move(burned));
attributes->SetValue(mintedKey, std::move(minted));
if (!unpaidContracts.empty()) {
attributes->SetValue(liveKey, std::move(balances));
}
LogPrintf("Future swap settlement completed: (%d DUSD->Token swaps," /* Continued */
" %d Token->DUSD swaps, %d refunds (height: %d, time: %dms)\n",
dUsdToTokenSwapsCounter, tokenTodUsdSwapsCounter, failedContractsCounter,
pindex->nHeight, GetTimeMillis() - time);
cache.SetVariable(*attributes);
}
static void ProcessGovEvents(const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams) {
if (pindex->nHeight < chainparams.GetConsensus().FortCanningHeight) {
return;
}
// Apply any pending GovVariable changes. Will come into effect on the next block.
auto storedGovVars = cache.GetStoredVariables(pindex->nHeight);
for (const auto& var : storedGovVars) {
if (var) {
CCustomCSView govCache(cache);
// Add to existing ATTRIBUTES instead of overwriting.
if (var->GetName() == "ATTRIBUTES") {
auto govVar = cache.GetAttributes();
govVar->time = pindex->GetBlockTime();
auto newVar = std::dynamic_pointer_cast<ATTRIBUTES>(var);
assert(newVar);
CDataStructureV0 key{AttributeTypes::Param, ParamIDs::Foundation, DFIPKeys::Members};
auto memberRemoval = newVar->GetValue(key, std::set<std::string>{});
if (!memberRemoval.empty()) {
auto existingMembers = govVar->GetValue(key, std::set<CScript>{});
for (auto &member : memberRemoval) {
if (member.empty()) {
continue;
}
if (member[0] == '-') {
auto memberCopy{member};
const auto dest = DecodeDestination(memberCopy.erase(0, 1));
if (!IsValidDestination(dest)) {
continue;
}
existingMembers.erase(GetScriptForDestination(dest));
} else {
const auto dest = DecodeDestination(member);
if (!IsValidDestination(dest)) {
continue;
}
existingMembers.insert(GetScriptForDestination(dest));
}
}
govVar->SetValue(key, existingMembers);
// Remove this key and apply any other changes
newVar->EraseKey(key);
if (govVar->Import(newVar->Export()) && govVar->Validate(govCache) && govVar->Apply(govCache, pindex->nHeight) && govCache.SetVariable(*govVar)) {
govCache.Flush();
}
} else {
if (govVar->Import(var->Export()) && govVar->Validate(govCache) && govVar->Apply(govCache, pindex->nHeight) && govCache.SetVariable(*govVar)) {
govCache.Flush();
}
}
} else if (var->Validate(govCache) && var->Apply(govCache, pindex->nHeight) && govCache.SetVariable(*var)) {
govCache.Flush();
}
}
}
cache.EraseStoredVariables(static_cast<uint32_t>(pindex->nHeight));
}
static bool ApplyGovVars(CCustomCSView& cache, const CBlockIndex& pindex, const std::map<std::string, std::string>& attrs){
if (auto govVar = cache.GetVariable("ATTRIBUTES")) {
if (auto var = dynamic_cast<ATTRIBUTES*>(govVar.get())) {
var->time = pindex.nTime;