-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathEpochManager.sol
More file actions
861 lines (756 loc) · 29.8 KB
/
EpochManager.sol
File metadata and controls
861 lines (756 loc) · 29.8 KB
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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.8.7 <0.8.20;
import "@openzeppelin/contracts8/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts8/access/Ownable.sol";
import "./interfaces/IOracle.sol";
import "../common/UsingRegistry.sol";
import "../../contracts/common/FixidityLib.sol";
import "../../contracts/common/Initializable.sol";
import "../../contracts/common/interfaces/IEpochManager.sol";
import "../../contracts/common/interfaces/ICeloVersionedContract.sol";
import "./interfaces/IEpochManagerInitializer.sol";
import "./libraries/ReentrancyGuard08.sol";
/**
* @title Contract used for managing CELO L2 epoch and elections.
* @dev DESIGN_DECISION: we assume that the first epoch on the L2 starts as soon as the system is initialized
* to minimize amount of "limbo blocks" the network should stop relatively close to an epoch number (but with enough time)
* to have time to call the function `EpochInitializer.migrateEpochAndValidators()`
*/
contract EpochManager is
Initializable,
UsingRegistry,
IEpochManager,
ReentrancyGuard08,
ICeloVersionedContract,
IEpochManagerInitializer
{
using FixidityLib for FixidityLib.Fraction;
struct Epoch {
uint256 firstBlock;
uint256 lastBlock;
uint256 startTimestamp;
uint256 rewardsBlock;
}
enum EpochProcessStatus {
NotStarted,
Started,
IndivudualGroupsProcessing
}
struct EpochProcessState {
EpochProcessStatus status;
uint256 perValidatorReward; // The per validator epoch reward.
uint256 totalRewardsVoter; // The total rewards to voters.
uint256 totalRewardsCommunity; // The total community reward.
uint256 totalRewardsCarbonFund; // The total carbon offsetting partner reward.
}
bool public isSystemInitialized;
// the length of an epoch in seconds
uint256 public epochDuration;
uint256 public firstKnownEpoch;
uint256 internal currentEpochNumber;
address public oracleAddress;
address[] public electedAccounts;
mapping(address => uint256) public processedGroups;
EpochProcessState public epochProcessing;
mapping(uint256 => Epoch) internal epochs;
mapping(address => uint256) public validatorPendingPayments;
// Electeds in the L1 assumed signers can not change during the epoch
// so we keep a copy
address[] public electedSigners;
uint256 public toProcessGroups = 0;
// Sum of voter rewards actually distributed to elected groups during the
// current epoch. May be less than `epochProcessing.totalRewardsVoter` due to
// per-group score, slashing multipliers, and integer rounding in
// `Election.getGroupEpochRewardsBasedOnScore`.
// NOTE: declared after all pre-existing state variables to preserve the
// proxy storage layout on in-place upgrades.
uint256 public totalDistributedVoterRewards;
/**
* @notice Event emitted when epochProcessing has begun.
* @param epochNumber The epoch number that is being processed.
*/
event EpochProcessingStarted(uint256 indexed epochNumber);
/**
* @notice Event emitted when epochProcessing has ended.
* @param epochNumber The epoch number that is finished being processed.
*/
event EpochProcessingEnded(uint256 indexed epochNumber);
/**
* @notice Event emited when a new epoch duration is set.
* @param newEpochDuration The new epoch duration.
*/
event EpochDurationSet(uint256 indexed newEpochDuration);
/**
* @notice Event emited when a new oracle address is set.
* @param newOracleAddress The new oracle address.
*/
event OracleAddressSet(address indexed newOracleAddress);
/**
* @notice Emitted when an epoch payment is sent.
* @param validator Address of the validator.
* @param validatorPayment Amount of cUSD sent to the validator.
* @param group Address of the validator's group.
* @param groupPayment Amount of cUSD sent to the group.
*/
event ValidatorEpochPaymentDistributed(
address indexed validator,
uint256 validatorPayment,
address indexed group,
uint256 groupPayment,
address indexed beneficiary,
uint256 delegatedPayment
);
/**
* @notice Emitted when group is marked for processing.
* @param group Address of the group to be processed.
* @param epochNumber The epoch number for which the group gets marked for processing.
*/
event GroupMarkedForProcessing(address indexed group, uint256 indexed epochNumber);
/**
* @notice Emitted when group is processed.
* @param group Address of the processed group.
* @param epochNumber The epoch number for which the group gets processed.
*/
event GroupProcessed(address indexed group, uint256 indexed epochNumber);
/**
* @notice Emitted when validator epoch reward is allocated (before claiming).
* @param validator Address of the validator.
* @param validatorReward Amount of cUSD allocated to the validator.
* @param group Address of the validator's group.
* @param epochNumber The epoch number for which the reward is allocated.
*/
event ValidatorEpochRewardAllocated(
address indexed validator,
uint256 validatorReward,
address indexed group,
uint256 indexed epochNumber
);
/**
* @notice Throws if called by other than EpochManagerEnabler contract.
*/
modifier onlyEpochManagerEnabler() {
require(
msg.sender == registry.getAddressForOrDie(EPOCH_MANAGER_ENABLER_REGISTRY_ID),
"msg.sender is not Enabler"
);
_;
}
/**
* @notice Throws if called when EpochManager system has not yet been initialized.
*/
modifier onlySystemAlreadyInitialized() {
require(systemAlreadyInitialized(), "Epoch system not initialized");
_;
}
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) Initializable(test) {}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
* @param newEpochDuration The duration of an epoch in seconds.
*/
function initialize(address registryAddress, uint256 newEpochDuration) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setEpochDuration(newEpochDuration);
setOracleAddress(registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID));
}
/**
* @notice Initializes the EpochManager system, allowing it to start processing epoch
* and distributing the epoch rewards.
* @dev Can only be called by the EpochManagerEnabler contract.
*/
function initializeSystem(
uint256 firstEpochNumber,
uint256 firstEpochBlock,
address[] memory firstElected
) external onlyEpochManagerEnabler {
require(
getCeloToken().balanceOf(registry.getAddressForOrDie(CELO_UNRELEASED_TREASURY_REGISTRY_ID)) >
0,
"CeloUnreleasedTreasury not yet funded."
);
require(!systemAlreadyInitialized(), "Epoch system already initialized");
require(firstEpochNumber > 0, "First epoch number must be greater than 0");
require(firstEpochBlock > 0, "First epoch block must be greater than 0");
require(
firstEpochBlock <= block.number,
"First epoch block must be less or equal than current block"
);
require(firstElected.length > 0, "First elected validators must be greater than 0");
isSystemInitialized = true;
firstKnownEpoch = firstEpochNumber;
currentEpochNumber = firstEpochNumber;
Epoch storage _currentEpoch = epochs[currentEpochNumber];
_currentEpoch.firstBlock = firstEpochBlock;
_currentEpoch.startTimestamp = block.timestamp;
electedAccounts = firstElected;
_setElectedSigners(firstElected);
}
/**
* @notice Starts processing an epoch and allocates funds to the beneficiaries.
* @dev Epoch rewards are frozen at the time of execution.
* @dev Can only be called once the system is initialized.
*/
function startNextEpochProcess() external nonReentrant onlySystemAlreadyInitialized {
require(isTimeForNextEpoch(), "Epoch is not ready to start");
require(
epochProcessing.status == EpochProcessStatus.NotStarted,
"Epoch process is already started"
);
require(!isEpochProcessingStarted(), "Epoch process is already started");
epochProcessing.status = EpochProcessStatus.Started;
epochs[currentEpochNumber].rewardsBlock = block.number;
// calculate rewards
getEpochRewards().updateTargetVotingYield();
(
uint256 perValidatorReward,
uint256 totalRewardsVoter,
uint256 totalRewardsCommunity,
uint256 totalRewardsCarbonFund
) = getEpochRewards().calculateTargetEpochRewards();
epochProcessing.perValidatorReward = perValidatorReward;
epochProcessing.totalRewardsVoter = totalRewardsVoter;
epochProcessing.totalRewardsCommunity = totalRewardsCommunity;
epochProcessing.totalRewardsCarbonFund = totalRewardsCarbonFund;
allocateValidatorsRewards();
emit EpochProcessingStarted(currentEpochNumber);
}
/**
* @notice Starts individual processing of the elected groups.
* As second step it is necessary to call processGroup
*/
function setToProcessGroups() external {
require(isOnEpochProcess(), "Epoch process is not started");
EpochProcessState storage _epochProcessing = epochProcessing;
_epochProcessing.status = EpochProcessStatus.IndivudualGroupsProcessing;
IValidators validators = getValidators();
IElection election = getElection();
IScoreReader scoreReader = getScoreReader();
require(
electedAccounts.length == electedSigners.length,
"Elected accounts and signers of different lengths."
);
for (uint i = 0; i < electedAccounts.length; i++) {
address group = validators.getMembershipInLastEpoch(electedAccounts[i]);
if (processedGroups[group] == 0) {
toProcessGroups++;
uint256 groupScore = scoreReader.getGroupScore(group);
// We need to precompute epoch rewards for each group since computation depends on total active votes for all groups.
uint256 epochRewards = election.getGroupEpochRewardsBasedOnScore(
group,
_epochProcessing.totalRewardsVoter,
groupScore
);
processedGroups[group] = epochRewards == 0 ? type(uint256).max : epochRewards;
emit GroupMarkedForProcessing(group, currentEpochNumber);
}
}
}
/**
* @notice Processes the rewards for a list of groups. For last group it will also finalize the epoch.
* @param groups List of validator groups to be processed.
* @param lessers List of validator groups that hold less votes that indexed group.
* @param greaters List of validator groups that hold more votes that indexed group.
*/
function processGroups(
address[] calldata groups,
address[] calldata lessers,
address[] calldata greaters
) external {
for (uint i = 0; i < groups.length; i++) {
processGroup(groups[i], lessers[i], greaters[i]);
}
}
/**
* @notice Processes the rewards for a group. For last group it will also finalize the epoch.
* @param group The group to process.
* @param lesser The group with less votes than the indexed group.
* @param greater The group with more votes than the indexed group.
*/
function processGroup(address group, address lesser, address greater) public {
EpochProcessState storage _epochProcessing = epochProcessing;
require(isIndividualProcessing(), "Individual epoch process is not started");
require(toProcessGroups > 0, "no more groups to process");
uint256 epochRewards = processedGroups[group];
// checks that group is actually from elected group
require(epochRewards > 0, "group not from current elected set");
IElection election = getElection();
if (epochRewards != type(uint256).max) {
election.distributeEpochRewards(group, epochRewards, lesser, greater);
totalDistributedVoterRewards += epochRewards;
}
delete processedGroups[group];
toProcessGroups--;
emit GroupProcessed(group, currentEpochNumber);
if (toProcessGroups == 0) {
_finishEpochHelper(_epochProcessing, election);
}
}
/**
* @notice Finishes processing an epoch and releasing funds to the beneficiaries.
* @param groups List of validator groups to be processed.
* @param lessers List of validator groups that hold less votes that indexed group.
* @param greaters List of validator groups that hold more votes that indexed group.
*/
function finishNextEpochProcess(
address[] calldata groups,
address[] calldata lessers,
address[] calldata greaters
) external virtual nonReentrant {
require(isOnEpochProcess(), "Epoch process is not started");
require(toProcessGroups == 0, "Can't finish epoch while individual groups are being processed");
EpochProcessState storage _epochProcessing = epochProcessing;
uint256 _toProcessGroups = 0;
IValidators validators = getValidators();
IElection election = getElection();
IScoreReader scoreReader = getScoreReader();
require(
electedAccounts.length == electedSigners.length,
"Elected accounts and signers of different lengths."
);
for (uint i = 0; i < electedAccounts.length; i++) {
address group = validators.getMembershipInLastEpoch(electedAccounts[i]);
if (processedGroups[group] == 0) {
_toProcessGroups++;
uint256 groupScore = scoreReader.getGroupScore(group);
// We need to precompute epoch rewards for each group since computation depends on total active votes for all groups.
uint256 epochRewards = election.getGroupEpochRewardsBasedOnScore(
group,
_epochProcessing.totalRewardsVoter,
groupScore
);
processedGroups[group] = epochRewards == 0 ? type(uint256).max : epochRewards;
}
delete electedAccounts[i];
delete electedSigners[i];
}
require(_toProcessGroups == groups.length, "number of groups does not match");
for (uint i = 0; i < groups.length; i++) {
uint256 epochRewards = processedGroups[groups[i]];
// checks that group is actually from elected group
require(epochRewards > 0, "group not from current elected set");
if (epochRewards != type(uint256).max) {
election.distributeEpochRewards(groups[i], epochRewards, lessers[i], greaters[i]);
totalDistributedVoterRewards += epochRewards;
}
delete processedGroups[groups[i]];
emit GroupProcessed(groups[i], currentEpochNumber);
}
_finishEpochHelper(_epochProcessing, election);
}
/**
* @notice Sends the allocated epoch payment to a validator, their group, and
* delegation beneficiary.
* @param validator Account of the validator.
* @dev Can only be called once the system is initialized.
*/
function sendValidatorPayment(address validator) external onlySystemAlreadyInitialized {
FixidityLib.Fraction memory totalPayment = FixidityLib.newFixed(
validatorPendingPayments[validator]
);
validatorPendingPayments[validator] = 0;
IValidators validators = getValidators();
address group = validators.getValidatorsGroup(validator);
(, uint256 commissionUnwrapped, , , , , ) = validators.getValidatorGroup(group);
uint256 groupPayment = totalPayment.multiply(FixidityLib.wrap(commissionUnwrapped)).fromFixed();
FixidityLib.Fraction memory remainingPayment = FixidityLib.newFixed(
totalPayment.fromFixed() - groupPayment
);
(address beneficiary, uint256 delegatedFraction) = getAccounts().getPaymentDelegation(
validator
);
uint256 delegatedPayment = remainingPayment
.multiply(FixidityLib.wrap(delegatedFraction))
.fromFixed();
uint256 validatorPayment = remainingPayment.fromFixed() - delegatedPayment;
IERC20 stableToken = IERC20(getStableToken());
if (validatorPayment > 0) {
require(stableToken.transfer(validator, validatorPayment), "transfer failed to validator");
}
if (groupPayment > 0) {
require(stableToken.transfer(group, groupPayment), "transfer failed to validator group");
}
if (delegatedPayment > 0) {
require(stableToken.transfer(beneficiary, delegatedPayment), "transfer failed to delegatee");
}
emit ValidatorEpochPaymentDistributed(
validator,
validatorPayment,
group,
groupPayment,
beneficiary,
delegatedPayment
);
}
/**
* @notice Returns the epoch info for the current epoch.
* @return firstEpoch The first block of the current epoch.
* @return lastBlock The last block of the current epoch.
* @return startTimestamp The starting timestamp of the current epoch.
* @return rewardsBlock The reward block of the current epoch.
*/
function getCurrentEpoch()
external
view
onlySystemAlreadyInitialized
returns (uint256, uint256, uint256, uint256)
{
return getEpochByNumber(currentEpochNumber);
}
/**
* @return The current epoch number.
* @dev Can only be called once the system is initialized.
*/
function getCurrentEpochNumber() external view onlySystemAlreadyInitialized returns (uint256) {
return currentEpochNumber;
}
/**
* @return The latest epoch processing state.
*/
function getEpochProcessingState()
external
view
returns (uint256, uint256, uint256, uint256, uint256)
{
EpochProcessState storage _epochProcessing = epochProcessing;
return (
uint256(_epochProcessing.status),
_epochProcessing.perValidatorReward,
_epochProcessing.totalRewardsVoter,
_epochProcessing.totalRewardsCommunity,
_epochProcessing.totalRewardsCarbonFund
);
}
/**
* @notice Used to block select functions in blockable contracts.
* @return Whether or not the blockable functions are blocked.
*/
function isBlocked() external view returns (bool) {
return isEpochProcessingStarted();
}
/**
* @return The number of elected accounts in the current set.
*/
function numberOfElectedInCurrentSet()
external
view
onlySystemAlreadyInitialized
returns (uint256)
{
return electedAccounts.length;
}
/**
* @return The list of currently elected validators.
*/
function getElectedAccounts()
external
view
onlySystemAlreadyInitialized
returns (address[] memory)
{
return electedAccounts;
}
/**
* @notice Returns the currently elected account at a specified index.
* @param index The index of the currently elected account.
*/
function getElectedAccountByIndex(
uint256 index
) external view onlySystemAlreadyInitialized returns (address) {
return electedAccounts[index];
}
/**
* @return The list of the validator signers of elected validators.
*/
function getElectedSigners()
external
view
onlySystemAlreadyInitialized
returns (address[] memory)
{
return electedSigners;
}
/**
* @notice Returns the currently elected signer address at a specified index.
* @param index The index of the currently elected signer.
*/
function getElectedSignerByIndex(
uint256 index
) external view onlySystemAlreadyInitialized returns (address) {
return electedSigners[index];
}
/**
* @param epoch The epoch number of interest.
* @return The First block of the specified epoch.
*/
function getFirstBlockAtEpoch(uint256 epoch) external view returns (uint256) {
require(epoch >= firstKnownEpoch, "Epoch not known");
require(epoch <= currentEpochNumber, "Epoch not created yet");
return epochs[epoch].firstBlock;
}
/**
* @param epoch The epoch number of interest.
* @return The last block of the specified epoch.
*/
function getLastBlockAtEpoch(uint256 epoch) external view returns (uint256) {
require(epoch >= firstKnownEpoch, "Epoch not known");
require(epoch < currentEpochNumber, "Epoch not finished yet");
return epochs[epoch].lastBlock;
}
/**
* @notice Returns the epoch number of a specified blockNumber.
* @param _blockNumber Block number of the epoch info is retrieved.
*/
function getEpochNumberOfBlock(
uint256 _blockNumber
) external view onlySystemAlreadyInitialized returns (uint256) {
(uint256 _epochNumber, , , , ) = _getEpochByBlockNumber(_blockNumber);
return _epochNumber;
}
/**
* @notice Returns the epoch info of a specified blockNumber.
* @param _blockNumber Block number of the epoch info is retrieved.
* @return firstEpoch The first block of the given block number.
* @return lastBlock The first block of the given block number.
* @return startTimestamp The starting timestamp of the given block number.
* @return rewardsBlock The reward block of the given block number.
*/
function getEpochByBlockNumber(
uint256 _blockNumber
) external view onlySystemAlreadyInitialized returns (uint256, uint256, uint256, uint256) {
(
,
uint256 _firstBlock,
uint256 _lastBlock,
uint256 _startTimestamp,
uint256 _rewardsBlock
) = _getEpochByBlockNumber(_blockNumber);
return (_firstBlock, _lastBlock, _startTimestamp, _rewardsBlock);
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return Storage version of the contract.
* @return Major version of the contract.
* @return Minor version of the contract.
* @return Patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 0, 3);
}
/**
* @notice Sets the time duration of an epoch.
* @param newEpochDuration The duration of an epoch in seconds.
* @dev Can only be set by owner.
*/
function setEpochDuration(uint256 newEpochDuration) public onlyOwner {
require(newEpochDuration > 0, "New epoch duration must be greater than zero.");
require(!isOnEpochProcess(), "Cannot change epoch duration during processing.");
epochDuration = newEpochDuration;
emit EpochDurationSet(newEpochDuration);
}
/**
* @notice Sets the address of the Oracle used by this contract.
* @param newOracleAddress The address of the new oracle.
* @dev Can only be set by owner.
*/
function setOracleAddress(address newOracleAddress) public onlyOwner {
require(newOracleAddress != address(0), "Cannot set address zero as the Oracle.");
require(newOracleAddress != oracleAddress, "Oracle address cannot be the same.");
require(!isOnEpochProcess(), "Cannot change oracle address during epoch processing.");
oracleAddress = newOracleAddress;
emit OracleAddressSet(newOracleAddress);
}
/**
* @return Whether the epoch is being processed individually, group by group.
*/
function isIndividualProcessing() public view returns (bool) {
return epochProcessing.status == EpochProcessStatus.IndivudualGroupsProcessing;
}
/**
* @return Whether epoch process has been started.
*/
function isEpochProcessingStarted() public view returns (bool) {
return isOnEpochProcess() || isIndividualProcessing();
}
/**
* @return Whether or not the next epoch can be processed.
*/
function isTimeForNextEpoch() public view returns (bool) {
return block.timestamp >= epochs[currentEpochNumber].startTimestamp + epochDuration;
}
/**
* @return Whether or not the current epoch is being processed.
*/
function isOnEpochProcess() public view returns (bool) {
return epochProcessing.status == EpochProcessStatus.Started;
}
/**
* @return Whether or not the EpochManager contract has been activated to start processing epochs.
*/
function systemAlreadyInitialized() public view returns (bool) {
return initialized && isSystemInitialized;
}
/**
* @notice Returns the epoch info of a specified epoch.
* @param epochNumber Epoch number where the epoch info is retrieved.
* @return firstEpoch The first block of the given epoch.
* @return lastBlock The first block of the given epoch.
* @return startTimestamp The starting timestamp of the given epoch.
* @return rewardsBlock The reward block of the given epoch.
*/
function getEpochByNumber(
uint256 epochNumber
) public view onlySystemAlreadyInitialized returns (uint256, uint256, uint256, uint256) {
Epoch memory _epoch = epochs[epochNumber];
return (_epoch.firstBlock, _epoch.lastBlock, _epoch.startTimestamp, _epoch.rewardsBlock);
}
/**
* @notice Allocates rewards to elected validator accounts.
*/
function allocateValidatorsRewards() internal {
uint256 totalRewards = 0;
IScoreReader scoreReader = getScoreReader();
IValidators validators = getValidators();
EpochProcessState storage _epochProcessing = epochProcessing;
for (uint i = 0; i < electedAccounts.length; i++) {
address validator = electedAccounts[i];
uint256 validatorScore = scoreReader.getValidatorScore(validator);
uint256 validatorReward = validators.computeEpochReward(
validator,
validatorScore,
_epochProcessing.perValidatorReward
);
validatorPendingPayments[validator] += validatorReward;
totalRewards += validatorReward;
if (validatorReward > 0) {
address group = validators.getMembershipInLastEpoch(validator);
emit ValidatorEpochRewardAllocated(validator, validatorReward, group, currentEpochNumber);
}
}
if (totalRewards == 0) {
return;
}
// Mint all cUSD required for payment and the corresponding CELO
validators.mintStableToEpochManager(totalRewards);
(uint256 numerator, uint256 denominator) = IOracle(oracleAddress).getExchangeRate(
address(getStableToken())
);
uint256 CELOequivalent = (denominator * totalRewards) / numerator;
getCeloUnreleasedTreasury().release(
registry.getAddressForOrDie(RESERVE_REGISTRY_ID),
CELOequivalent
);
}
/**
* @notice Updates the list of elected validator signers.
*/
function _setElectedSigners(address[] memory _elected) internal {
require(electedAccounts.length > 0, "Elected list length cannot be zero.");
IAccounts accounts = getAccounts();
electedSigners = new address[](_elected.length);
for (uint i = 0; i < _elected.length; i++) {
electedSigners[i] = accounts.getValidatorSigner(_elected[i]);
}
}
/**
* @notice Finishes processing an epoch and releasing funds to the beneficiaries.
* @param _epochProcessing The current epoch processing state.
* @param election The Election contract.
*/
function _finishEpochHelper(
EpochProcessState storage _epochProcessing,
IElection election
) internal {
// finalize epoch
// last block should be the block before and timestamp from previous block
epochs[currentEpochNumber].lastBlock = block.number - 1;
currentEpochNumber++;
// start new epoch
epochs[currentEpochNumber].firstBlock = block.number;
epochs[currentEpochNumber].startTimestamp = block.timestamp;
// run elections
address[] memory _newlyElected = election.electValidatorAccounts();
electedAccounts = _newlyElected;
_setElectedSigners(_newlyElected);
ICeloUnreleasedTreasury celoUnreleasedTreasury = getCeloUnreleasedTreasury();
// Release only the voter rewards that were actually distributed to groups
// (post score, slashing multiplier, and rounding) to avoid stranding excess
// CELO in LockedGold without matching vote units.
celoUnreleasedTreasury.release(
registry.getAddressForOrDie(LOCKED_GOLD_REGISTRY_ID),
totalDistributedVoterRewards
);
celoUnreleasedTreasury.release(
registry.getAddressForOrDie(GOVERNANCE_REGISTRY_ID),
_epochProcessing.totalRewardsCommunity
);
celoUnreleasedTreasury.release(
getEpochRewards().carbonOffsettingPartner(),
_epochProcessing.totalRewardsCarbonFund
);
_epochProcessing.status = EpochProcessStatus.NotStarted;
_epochProcessing.perValidatorReward = 0;
_epochProcessing.totalRewardsVoter = 0;
_epochProcessing.totalRewardsCommunity = 0;
_epochProcessing.totalRewardsCarbonFund = 0;
totalDistributedVoterRewards = 0;
emit EpochProcessingEnded(currentEpochNumber - 1);
}
/**
* @notice Returns the epoch info of a specified blockNumber.
* @dev This function is here for backward compatibility. It is rather gas heavy and can run out of gas.
* @param _blockNumber Block number of the epoch info is retrieved.
* @return firstEpoch The first block of the given block number.
* @return lastBlock The first block of the given block number.
* @return startTimestamp The starting timestamp of the given block number.
* @return rewardsBlock The reward block of the given block number.
*/
function _getEpochByBlockNumber(
uint256 _blockNumber
)
internal
view
onlySystemAlreadyInitialized
returns (uint256, uint256, uint256, uint256, uint256)
{
require(_blockNumber <= block.number, "Invalid blockNumber. Value too high.");
(uint256 _firstBlockOfFirstEpoch, , , ) = getEpochByNumber(firstKnownEpoch);
require(_blockNumber >= _firstBlockOfFirstEpoch, "Invalid blockNumber. Value too low.");
uint256 _firstBlockOfCurrentEpoch = epochs[currentEpochNumber].firstBlock;
if (_blockNumber >= _firstBlockOfCurrentEpoch) {
(
uint256 _firstBlock,
uint256 _lastBlock,
uint256 _startTimestamp,
uint256 _rewardsBlock
) = getEpochByNumber(currentEpochNumber);
return (currentEpochNumber, _firstBlock, _lastBlock, _startTimestamp, _rewardsBlock);
}
uint256 left = firstKnownEpoch;
uint256 right = currentEpochNumber - 1;
while (left <= right) {
uint256 mid = (left + right) / 2;
uint256 _epochFirstBlock = epochs[mid].firstBlock;
uint256 _epochLastBlock = epochs[mid].lastBlock;
if (_blockNumber >= _epochFirstBlock && _blockNumber <= _epochLastBlock) {
Epoch memory _epoch = epochs[mid];
return (
mid,
_epoch.firstBlock,
_epoch.lastBlock,
_epoch.startTimestamp,
_epoch.rewardsBlock
);
} else if (_blockNumber < _epochFirstBlock) {
right = mid - 1;
} else {
left = mid + 1;
}
}
revert("No matching epoch found for the given block number.");
}
}