-
Notifications
You must be signed in to change notification settings - Fork 47
/
FeeSharingCollector.sol
1264 lines (1126 loc) · 49.9 KB
/
FeeSharingCollector.sol
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
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "../Staking/SafeMath96.sol";
import "../../openzeppelin/SafeMath.sol";
import "../../openzeppelin/SafeERC20.sol";
import "../../openzeppelin/Ownable.sol";
import "../IFeeSharingCollector.sol";
import "../../openzeppelin/Address.sol";
import "./FeeSharingCollectorStorage.sol";
import "../../interfaces/IConverterAMM.sol";
/**
* @title The FeeSharingCollector contract.
* @notice This contract withdraws fees to be paid to SOV Stakers from the protocol.
* Stakers call withdraw() to get their share of the fees.
*
* @notice Staking is not only granting voting rights, but also access to fee
* sharing according to the own voting power in relation to the total. Whenever
* somebody decides to collect the fees from the protocol, they get transferred
* to a proxy contract which invests the funds in the lending pool and keeps
* the pool tokens.
*
* The fee sharing proxy will be set as feesController of the protocol contract.
* This allows the fee sharing proxy to withdraw the fees. The fee sharing
* proxy holds the pool tokens and keeps track of which user owns how many
* tokens. In order to know how many tokens a user owns, the fee sharing proxy
* needs to know the user’s weighted stake in relation to the total weighted
* stake (aka total voting power).
*
* Because both values are subject to change, they may be different on each fee
* withdrawal. To be able to calculate a user’s share of tokens when he wants
* to withdraw, we need checkpoints.
*
* This contract is intended to be set as the protocol fee collector.
* Anybody can invoke the withdrawFees function which uses
* protocol.withdrawFees to obtain available fees from operations on a
* certain token. These fees are deposited in the corresponding loanPool.
* Also, the staking contract sends slashed tokens to this contract.
* When a user calls the withdraw function, the contract transfers the fee sharing
* rewards in proportion to the user’s weighted stake since the last withdrawal.
*
* The protocol initially collects fees in all tokens.
* Then the FeeSharingCollector wihtdraws fees from the protocol.
* When the fees are withdrawn all the tokens except SOV will be converted to wRBTC
* and then transferred to wRBTC loan pool.
* For SOV, it will be directly deposited into the feeSharingCollector from the protocol.
* */
contract FeeSharingCollector is
SafeMath96,
IFeeSharingCollector,
Ownable,
FeeSharingCollectorStorage
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant ZERO_ADDRESS = address(0);
address public constant RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT =
address(uint160(uint256(keccak256("RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT"))));
/* Events */
/// @notice Deprecated event after the unification between wrbtc & rbtc
// event FeeWithdrawn(address indexed sender, address indexed token, uint256 amount);
event FeeWithdrawnInRBTC(address indexed sender, uint256 amount);
/// @notice An event emitted when tokens transferred.
event TokensTransferred(address indexed sender, address indexed token, uint256 amount);
/// @notice An event emitted when checkpoint added.
event CheckpointAdded(address indexed sender, address indexed token, uint256 amount);
/// @notice An event emitted when user fee get withdrawn.
event UserFeeWithdrawn(
address indexed sender,
address indexed receiver,
address indexed token,
uint256 amount
);
/// @notice An event emitted when user fee get withdrawn.
event UserFeeProcessedNoWithdraw(
address indexed sender,
address indexed token,
uint256 prevProcessedCheckpoints,
uint256 newProcessedCheckpoints
);
/**
* @notice An event emitted when fee from AMM get withdrawn.
*
* @param sender sender who initiate the withdrawn amm fees.
* @param converter the converter address.
* @param amount total amount of fee (Already converted to WRBTC).
*/
event FeeAMMWithdrawn(address indexed sender, address indexed converter, uint256 amount);
/// @notice An event emitted when converter address has been registered to be whitelisted.
event WhitelistedConverter(address indexed sender, address converter);
/// @notice An event emitted when converter address has been removed from whitelist.
event UnwhitelistedConverter(address indexed sender, address converter);
event RBTCWithdrawn(address indexed sender, address indexed receiver, uint256 amount);
event SetWrbtcToken(
address indexed sender,
address indexed oldWrbtcToken,
address indexed newWrbtcToken
);
event SetLoanTokenWrbtc(
address indexed sender,
address indexed oldLoanTokenWrbtc,
address indexed newLoanTokenWrbtc
);
/* Modifier */
modifier oneTimeExecution(bytes4 _funcSig) {
require(
!isFunctionExecuted[_funcSig],
"FeeSharingCollector: function can only be called once"
);
_;
isFunctionExecuted[_funcSig] = true;
}
/* Functions */
/// @dev fallback function to support rbtc transfer when unwrap the wrbtc.
function() external payable {}
/**
* @dev initialize function for fee sharing collector proxy
* @param wrbtcToken wrbtc token address
* @param loanWrbtcToken address of loan token wrbtc (IWrbtc)
*/
function initialize(
address wrbtcToken,
address loanWrbtcToken
) external onlyOwner oneTimeExecution(this.initialize.selector) {
require(
wrbtcTokenAddress == address(0) && loanTokenWrbtcAddress == address(0),
"wrbtcToken or loanWrbtcToken has been initialized"
);
setWrbtcToken(wrbtcToken);
setLoanTokenWrbtc(loanWrbtcToken);
}
/**
* @notice Set the wrbtc token address of fee sharing collector.
*
* only owner can perform this action.
*
* @param newWrbtcTokenAddress The new address of the wrbtc token.
* */
function setWrbtcToken(address newWrbtcTokenAddress) public onlyOwner {
require(Address.isContract(newWrbtcTokenAddress), "newWrbtcTokenAddress not a contract");
emit SetWrbtcToken(msg.sender, wrbtcTokenAddress, newWrbtcTokenAddress);
wrbtcTokenAddress = newWrbtcTokenAddress;
}
/**
* @notice Set the loan wrbtc token address of fee sharing collector.
*
* only owner can perform this action.
*
* @param newLoanTokenWrbtcAddress The new address of the loan wrbtc token.
* */
function setLoanTokenWrbtc(address newLoanTokenWrbtcAddress) public onlyOwner {
require(
Address.isContract(newLoanTokenWrbtcAddress),
"newLoanTokenWrbtcAddress not a contract"
);
emit SetLoanTokenWrbtc(msg.sender, loanTokenWrbtcAddress, newLoanTokenWrbtcAddress);
loanTokenWrbtcAddress = newLoanTokenWrbtcAddress;
}
/**
* @notice Withdraw fees for the given token:
* lendingFee + tradingFee + borrowingFee
* the fees (except SOV) will be converted in wRBTC form, and then will be transferred to wRBTC loan pool.
* For SOV, it will be directly deposited into the feeSharingCollector from the protocol.
*
* @param _tokens array address of the token
* */
function withdrawFees(address[] calldata _tokens) external {
for (uint256 i = 0; i < _tokens.length; i++) {
require(
Address.isContract(_tokens[i]),
"FeeSharingCollector::withdrawFees: token is not a contract"
);
}
uint256 wrbtcAmountWithdrawn = protocol.withdrawFees(_tokens, address(this));
IWrbtcERC20 wrbtcToken = IWrbtcERC20(wrbtcTokenAddress);
if (wrbtcAmountWithdrawn > 0) {
// unwrap the wrbtc to rbtc, and hold the rbtc.
wrbtcToken.withdraw(wrbtcAmountWithdrawn);
/// @notice Update unprocessed amount of tokens
uint96 amount96 = safe96(
wrbtcAmountWithdrawn,
"FeeSharingCollector::withdrawFees: wrbtc token amount exceeds 96 bits"
);
_addCheckpoint(RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT, amount96);
}
// note deprecated event since we unify the wrbtc & rbtc
// emit FeeWithdrawn(msg.sender, RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT, poolTokenAmount);
// note new emitted event
emit FeeWithdrawnInRBTC(msg.sender, wrbtcAmountWithdrawn);
}
/**
* @notice Withdraw amm fees for the given converter addresses:
* protocolFee from the conversion
* the fees will be converted in wRBTC form, and then will be transferred to wRBTC loan pool
*
* @param _converters array addresses of the converters
* */
function withdrawFeesAMM(address[] memory _converters) public {
IWrbtcERC20 wrbtcToken = IWrbtcERC20(wrbtcTokenAddress);
// Validate
_validateWhitelistedConverter(_converters);
uint96 totalPoolTokenAmount;
for (uint256 i = 0; i < _converters.length; i++) {
uint256 wrbtcAmountWithdrawn = IConverterAMM(_converters[i]).withdrawFees(
address(this)
);
if (wrbtcAmountWithdrawn > 0) {
// unwrap wrbtc to rbtc, and hold the rbtc
wrbtcToken.withdraw(wrbtcAmountWithdrawn);
/// @notice Update unprocessed amount of tokens
uint96 amount96 = safe96(
wrbtcAmountWithdrawn,
"FeeSharingCollector::withdrawFeesAMM: wrbtc token amount exceeds 96 bits"
);
totalPoolTokenAmount = add96(
totalPoolTokenAmount,
amount96,
"FeeSharingCollector::withdrawFeesAMM: total wrbtc token amount exceeds 96 bits"
);
emit FeeAMMWithdrawn(msg.sender, _converters[i], wrbtcAmountWithdrawn);
}
}
if (totalPoolTokenAmount > 0) {
_addCheckpoint(RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT, totalPoolTokenAmount);
}
}
/**
* @notice Transfer tokens to this contract.
* @dev We just update amount of tokens here and write checkpoint in a separate methods
* in order to prevent adding checkpoints too often.
* @param _token Address of the token.
* @param _amount Amount to be transferred.
* */
function transferTokens(address _token, uint96 _amount) public {
require(_token != ZERO_ADDRESS, "FeeSharingCollector::transferTokens: invalid address");
require(_amount > 0, "FeeSharingCollector::transferTokens: invalid amount");
/// @notice Transfer tokens from msg.sender
bool success = IERC20(_token).transferFrom(address(msg.sender), address(this), _amount);
require(success, "Staking::transferTokens: token transfer failed");
// if _token is wrbtc, need to unwrap it to rbtc
IWrbtcERC20 wrbtcToken = IWrbtcERC20(wrbtcTokenAddress);
if (_token == address(wrbtcToken)) {
wrbtcToken.withdraw(_amount);
_token = RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT;
}
_addCheckpoint(_token, _amount);
emit TokensTransferred(msg.sender, _token, _amount);
}
/**
* @notice Transfer RBTC / native tokens to this contract.
* @dev We just write checkpoint here (based on the rbtc value that is sent) in a separate methods
* in order to prevent adding checkpoints too often.
* */
function transferRBTC() external payable {
uint96 _amount = uint96(msg.value);
require(_amount > 0, "FeeSharingCollector::transferRBTC: invalid value");
_addCheckpoint(RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT, _amount);
emit TokensTransferred(msg.sender, ZERO_ADDRESS, _amount);
}
/**
* @notice Add checkpoint with accumulated amount by function invocation.
* @param _token Address of the token.
* */
function _addCheckpoint(address _token, uint96 _amount) internal {
if (block.timestamp - lastFeeWithdrawalTime[_token] >= FEE_WITHDRAWAL_INTERVAL) {
lastFeeWithdrawalTime[_token] = block.timestamp;
uint96 amount = add96(
unprocessedAmount[_token],
_amount,
"FeeSharingCollector::_addCheckpoint: amount exceeds 96 bits"
);
/// @notice Reset unprocessed amount of tokens to zero.
unprocessedAmount[_token] = 0;
/// @notice Write a regular checkpoint.
_writeTokenCheckpoint(_token, amount);
} else {
unprocessedAmount[_token] = add96(
unprocessedAmount[_token],
_amount,
"FeeSharingCollector::_addCheckpoint: unprocessedAmount exceeds 96 bits"
);
}
}
function _withdraw(
address _token,
uint32 _maxCheckpoints,
address _receiver
) internal returns (uint256 totalAmount, uint256 endTokenCheckpoint) {
/// @dev Prevents block gas limit hit when processing checkpoints
require(
_maxCheckpoints > 0,
"FeeSharingCollector::withdraw: _maxCheckpoints should be positive"
);
address user = msg.sender;
if (_receiver == ZERO_ADDRESS) {
_receiver = msg.sender;
}
uint256 processedUserCheckpoints = processedCheckpoints[user][_token];
(uint256 amount, uint256 end) = _getAccumulatedFees(
user,
_token,
processedUserCheckpoints,
_maxCheckpoints
);
if (amount == 0) {
if (end > processedUserCheckpoints) {
emit UserFeeProcessedNoWithdraw(msg.sender, _token, processedUserCheckpoints, end);
processedCheckpoints[user][_token] = end;
return (0, end);
} else {
// getting here most likely means smth wrong with the state
revert("FeeSharingCollector::withdrawFees: no tokens for withdrawal");
}
}
processedCheckpoints[user][_token] = end;
if (loanTokenWrbtcAddress == _token) {
// We will change, so that feeSharingCollector will directly burn then loanToken (IWRBTC) to rbtc and send to the user --- by call burnToBTC function
ILoanTokenWRBTC(_token).burnToBTC(_receiver, amount, false);
} else {
// Previously it directly send the loanToken to the user
require(
IERC20(_token).transfer(_receiver, amount),
"FeeSharingCollector::withdraw: withdrawal failed"
);
}
emit UserFeeWithdrawn(msg.sender, _receiver, _token, amount);
return (amount, end);
}
/**
* @notice Withdraw accumulated fee to the message sender.
*
* The Sovryn protocol collects fees on every trade/swap and loan.
* These fees will be distributed to SOV stakers based on their voting
* power as a percentage of total voting power. Therefore, staking more
* SOV and/or staking for longer will increase your share of the fees
* generated, meaning you will earn more from staking.
*
* This function will directly burnToBTC and use the msg.sender (user) as the receiver
*
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _maxCheckpoints Maximum number of checkpoints to be processed. Must be positive value.
* @param _receiver The receiver of tokens or msg.sender
* */
function withdraw(
address _token,
uint32 _maxCheckpoints,
address _receiver
) public nonReentrant {
_withdraw(_token, _maxCheckpoints, _receiver);
}
/// @notice Validates if the checkpoint is payable for the user
function validFromCheckpointsParam(
TokenWithSkippedCheckpointsWithdraw[] memory _tokens,
address _user
) private view {
for (uint256 i = 0; i < _tokens.length; i++) {
TokenWithSkippedCheckpointsWithdraw memory tokenData = _tokens[i];
// _fromCheckpoint is checkpoint number, not array index, so should be > 1
require(tokenData.fromCheckpoint > 1, "_fromCheckpoint param must be > 1");
uint256 fromCheckpointIndex = tokenData.fromCheckpoint - 1;
require(
tokenData.fromCheckpoint > processedCheckpoints[_user][tokenData.tokenAddress],
"_fromCheckpoint param must be > userProcessedCheckpoints"
);
require(
tokenData.fromCheckpoint <= totalTokenCheckpoints[tokenData.tokenAddress],
"_fromCheckpoint should be <= totalTokenCheckpoints"
);
Checkpoint memory prevCheckpoint = tokenCheckpoints[tokenData.tokenAddress][
fromCheckpointIndex - 1
];
uint96 weightedStake = staking.getPriorWeightedStake(
_user,
prevCheckpoint.blockNumber - 1,
prevCheckpoint.timestamp
);
require(
weightedStake == 0,
"User weighted stake should be zero at previous checkpoint"
);
Checkpoint memory fromCheckpoint = tokenCheckpoints[tokenData.tokenAddress][
fromCheckpointIndex
];
weightedStake = staking.getPriorWeightedStake(
_user,
fromCheckpoint.blockNumber - 1,
fromCheckpoint.timestamp
);
require(weightedStake > 0, "User weighted stake should be > 0 at _fromCheckpoint");
}
}
function validRBTCBasedTokens(address[] memory _tokens) private view {
for (uint256 i = 0; i < _tokens.length; i++) {
address _token = _tokens[i];
if (
_token != RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT &&
_token != wrbtcTokenAddress &&
_token != loanTokenWrbtcAddress
) {
revert("only rbtc-based tokens are allowed");
}
}
}
/**
* @notice Withdraw accumulated fee to the message sender/receiver.
*
* The Sovryn protocol collects fees on every trade/swap and loan.
* These fees will be distributed to SOV stakers based on their voting
* power as a percentage of total voting power.
*
* This function will directly burnToBTC and use the msg.sender (user) as the receiver
*
* @dev WARNING! This function skips all the checkpoints before '_fromCheckpoint' irreversibly, use with care
*
* @param _tokens Array of TokenWithSkippedCheckpointsWithdraw struct, which contains the token address, and fromCheckpoiint
* fromCheckpoints Skips all the checkpoints before '_fromCheckpoint'
* should be calculated offchain with getNextPositiveUserCheckpoint function
* @param _maxCheckpoints Maximum number of checkpoints to be processed.
* @param _receiver The receiver of tokens or msg.sender
*
* @return total processed checkpoints
* */
function _withdrawStartingFromCheckpoints(
TokenWithSkippedCheckpointsWithdraw[] memory _tokens,
uint32 _maxCheckpoints,
address _receiver
) internal returns (uint256 totalProcessedCheckpoints) {
validFromCheckpointsParam(_tokens, msg.sender);
if (_receiver == ZERO_ADDRESS) {
_receiver = msg.sender;
}
uint256 rbtcAmountToSend;
for (uint256 i = 0; i < _tokens.length; i++) {
TokenWithSkippedCheckpointsWithdraw memory tokenData = _tokens[i];
if (_maxCheckpoints == 0) break;
uint256 endToken;
uint256 totalAmount;
uint256 previousProcessedUserCheckpoints = processedCheckpoints[msg.sender][
tokenData.tokenAddress
];
uint256 startingCheckpoint = tokenData.fromCheckpoint >
previousProcessedUserCheckpoints
? tokenData.fromCheckpoint
: previousProcessedUserCheckpoints;
if (
tokenData.tokenAddress == wrbtcTokenAddress ||
tokenData.tokenAddress == loanTokenWrbtcAddress ||
tokenData.tokenAddress == RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT
) {
(totalAmount, endToken) = _withdrawRbtcTokenStartingFromCheckpoint(
tokenData.tokenAddress,
tokenData.fromCheckpoint,
_maxCheckpoints,
_receiver
);
rbtcAmountToSend = rbtcAmountToSend.add(totalAmount);
} else {
(, endToken) = _withdrawStartingFromCheckpoint(
tokenData.tokenAddress,
tokenData.fromCheckpoint,
_maxCheckpoints,
_receiver
);
}
uint256 _previousUsedCheckpoint = endToken.sub(startingCheckpoint).add(1);
totalProcessedCheckpoints += _previousUsedCheckpoint;
_maxCheckpoints = safe32(
_maxCheckpoints - _previousUsedCheckpoint,
"FeeSharingCollector: maxCheckpoint iteration exceeds 32 bits"
);
}
if (rbtcAmountToSend > 0) {
// send all rbtc withdrawal
(bool success, ) = _receiver.call.value(rbtcAmountToSend)("");
require(success, "FeeSharingCollector::withdrawRBTC: Withdrawal failed");
emit RBTCWithdrawn(msg.sender, _receiver, rbtcAmountToSend);
}
}
/**
* @dev Function to wrap:
* 1. regular withdrawal for both rbtc & non-rbtc token
* 2. skipped checkpoints withdrawal for both rbtc & non-rbtc token
*
* @param _nonRbtcTokensRegularWithdraw array of non-rbtc token address with no skipped checkpoints that will be withdrawn
* @param _rbtcTokensRegularWithdraw array of rbtc token address with no skipped checkpoints that will be withdrawn
* @param _tokensWithSkippedCheckpoints array of rbtc & non-rbtc TokenWithSkippedCheckpointsWithdraw struct, which has skipped checkpoints that will be withdrawn
*
*/
function claimAllCollectedFees(
address[] calldata _nonRbtcTokensRegularWithdraw,
address[] calldata _rbtcTokensRegularWithdraw,
TokenWithSkippedCheckpointsWithdraw[] calldata _tokensWithSkippedCheckpoints,
uint32 _maxCheckpoints,
address _receiver
) external nonReentrant {
uint256 totalProcessedCheckpoints;
/** Process normal multiple withdrawal for RBTC based tokens */
if (_rbtcTokensRegularWithdraw.length > 0) {
totalProcessedCheckpoints = _withdrawRbtcTokens(
_rbtcTokensRegularWithdraw,
_maxCheckpoints,
_receiver
);
_maxCheckpoints = safe32(
_maxCheckpoints - totalProcessedCheckpoints,
"FeeSharingCollector: maxCheckpoint iteration exceeds 32 bits"
);
}
/** Process normal non-rbtc token withdrawal */
for (uint256 i = 0; i < _nonRbtcTokensRegularWithdraw.length; i++) {
if (_maxCheckpoints == 0) break;
uint256 endTokenCheckpoint;
address _nonRbtcTokenAddress = _nonRbtcTokensRegularWithdraw[i];
/** starting checkpoint is the previous processedCheckpoints for token */
uint256 startingCheckpoint = processedCheckpoints[msg.sender][_nonRbtcTokenAddress];
(, endTokenCheckpoint) = _withdraw(_nonRbtcTokenAddress, _maxCheckpoints, _receiver);
uint256 _previousUsedCheckpoint = endTokenCheckpoint.sub(startingCheckpoint);
if (startingCheckpoint > 0) {
_previousUsedCheckpoint.add(1);
}
_maxCheckpoints = safe32(
_maxCheckpoints - _previousUsedCheckpoint,
"FeeSharingCollector: maxCheckpoint iteration exceeds 32 bits"
);
}
/** Process token with skipped checkpoints withdrawal */
if (_tokensWithSkippedCheckpoints.length > 0) {
totalProcessedCheckpoints = _withdrawStartingFromCheckpoints(
_tokensWithSkippedCheckpoints,
_maxCheckpoints,
_receiver
);
_maxCheckpoints = safe32(
_maxCheckpoints - totalProcessedCheckpoints,
"FeeSharingCollector: maxCheckpoint iteration exceeds 32 bits"
);
}
}
function _withdrawStartingFromCheckpoint(
address _token,
uint256 _fromCheckpoint,
uint32 _maxCheckpoints,
address _receiver
) internal returns (uint256 totalAmount, uint256 endTokenCheckpoint) {
// @dev e.g. _fromCheckpoint == 10 meaning we should set 9 user's processed checkpoints
// after _withdraw() the user's processedCheckpoints should be 10
uint256 prevFromCheckpoint = _fromCheckpoint.sub(1);
if (prevFromCheckpoint > processedCheckpoints[msg.sender][_token]) {
processedCheckpoints[msg.sender][_token] = prevFromCheckpoint;
}
(totalAmount, endTokenCheckpoint) = _withdraw(_token, _maxCheckpoints, _receiver);
}
function _withdrawRbtcToken(
address _token,
uint32 _maxCheckpoints
) internal returns (uint256 totalAmount, uint256 endTokenCheckpoint) {
address user = msg.sender;
IWrbtcERC20 wrbtcToken = IWrbtcERC20(wrbtcTokenAddress);
(totalAmount, endTokenCheckpoint) = _getRBTCBalance(_token, user, _maxCheckpoints);
if (totalAmount > 0) {
processedCheckpoints[user][_token] = endTokenCheckpoint;
if (_token == address(wrbtcToken)) {
// unwrap the wrbtc
wrbtcToken.withdraw(totalAmount);
} else if (_token == loanTokenWrbtcAddress) {
// pull out the iWRBTC to rbtc to this feeSharingCollector contract
/** @dev will use the burned result from IWRBTC to RBTC as return total amount */
totalAmount = ILoanTokenWRBTC(loanTokenWrbtcAddress).burnToBTC(
address(this),
totalAmount,
false
);
}
}
}
/**
* @dev withdraw all of the RBTC balance based on particular checkpoints
*
* This function will withdraw RBTC balance which is passed as _token param, so it could be either of these:
* - rbtc balance or
* - wrbtc balance which will be unwrapped to rbtc or
* - iwrbtc balance which will be unwrapped to rbtc or
*
*
* @param _tokens array of either RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT or wrbtc address or iwrbtc address
* @param _maxCheckpoints Maximum number of checkpoints to be processed to workaround block gas limit
* @param _receiver An optional tokens receiver (msg.sender used if 0)
*/
function _withdrawRbtcTokens(
address[] memory _tokens,
uint32 _maxCheckpoints,
address _receiver
) internal returns (uint256 totalProcessedCheckpoints) {
validRBTCBasedTokens(_tokens);
if (_receiver == ZERO_ADDRESS) {
_receiver = msg.sender;
}
uint256 rbtcAmountToSend;
for (uint256 i = 0; i < _tokens.length; i++) {
if (_maxCheckpoints == 0) break;
address _token = _tokens[i];
uint256 startingCheckpoint = processedCheckpoints[msg.sender][_token];
(uint256 totalAmount, uint256 endToken) = _withdrawRbtcToken(
_tokens[i],
_maxCheckpoints
);
rbtcAmountToSend = rbtcAmountToSend.add(totalAmount);
uint256 _previousUsedCheckpoint = endToken.sub(startingCheckpoint);
if (startingCheckpoint > 0) {
// we only need to add used checkpoint by 1 only if starting checkpoint > 0
_previousUsedCheckpoint.add(1);
}
totalProcessedCheckpoints += _previousUsedCheckpoint;
_maxCheckpoints = safe32(
_maxCheckpoints - _previousUsedCheckpoint,
"FeeSharingCollector: maxCheckpoint iteration exceeds 32 bits"
);
}
// send all rbtc
if (rbtcAmountToSend > 0) {
(bool success, ) = _receiver.call.value(rbtcAmountToSend)("");
require(success, "FeeSharingCollector::withdrawRBTC: Withdrawal failed");
emit RBTCWithdrawn(msg.sender, _receiver, rbtcAmountToSend);
}
}
/**
* @dev Withdraw either specific RBTC related token balance or all RBTC related tokens balances.
* RBTC related here means, it could be either rbtc, wrbtc, or iwrbtc, depends on the _token param.
*/
function _withdrawRbtcTokenStartingFromCheckpoint(
address _token,
uint256 _fromCheckpoint,
uint32 _maxCheckpoints,
address _receiver
) private returns (uint256 totalAmount, uint256 endTokenCheckpoint) {
// @dev e.g. _fromCheckpoint == 10
// after _withdraw() user's processedCheckpoints should be 10 =>
// set processed checkpoints = 9, next maping index = 9 (10th checkpoint)
uint256 prevFromCheckpoint = _fromCheckpoint.sub(1);
if (prevFromCheckpoint > processedCheckpoints[msg.sender][_token]) {
processedCheckpoints[msg.sender][_token] = prevFromCheckpoint;
}
return _withdrawRbtcToken(_token, _maxCheckpoints);
}
/**
* @dev Returns first user's checkpoint with weighted stake > 0
*
* @param _user The address of the user or contract.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _startFrom Checkpoint number to start from. If _startFrom < processedUserCheckpoints then starts from processedUserCheckpoints.
* @param _maxCheckpoints Max checkpoints to process in a row to avoid timeout error
* @return [checkpointNum: checkpoint number where user's weighted stake > 0, hasSkippedCheckpoints, hasFees]
*/
function getNextPositiveUserCheckpoint(
address _user,
address _token,
uint256 _startFrom,
uint256 _maxCheckpoints
) external view returns (uint256 checkpointNum, bool hasSkippedCheckpoints, bool hasFees) {
return _getNextPositiveUserCheckpoint(_user, _token, _startFrom, _maxCheckpoints);
}
/**
* @dev Returns first user's checkpoint with weighted stake > 0
*
* @param _user The address of the user or contract.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _startFrom Checkpoint number to start from. If _startFrom < processedUserCheckpoints then starts from processedUserCheckpoints.
* @param _maxCheckpoints Max checkpoints to process in a row to avoid timeout error
* @return [checkpointNum: checkpoint number where user's weighted stake > 0, hasSkippedCheckpoints, hasFees]
*/
function _getNextPositiveUserCheckpoint(
address _user,
address _token,
uint256 _startFrom,
uint256 _maxCheckpoints
) internal view returns (uint256 checkpointNum, bool hasSkippedCheckpoints, bool hasFees) {
if (staking.isVestingContract(_user)) {
return (0, false, false);
}
require(_maxCheckpoints > 0, "_maxCheckpoints must be > 0");
uint256 totalCheckpoints = totalTokenCheckpoints[_token];
uint256 processedUserCheckpoints = processedCheckpoints[_user][_token];
if (processedUserCheckpoints >= totalCheckpoints || totalCheckpoints == 0) {
return (totalCheckpoints, false, false);
}
uint256 startFrom = _startFrom > processedUserCheckpoints
? _startFrom
: processedUserCheckpoints;
uint256 end = startFrom.add(_maxCheckpoints);
if (end >= totalCheckpoints) {
end = totalCheckpoints;
}
// @note here processedUserCheckpoints is a number of processed checkpoints and
// also an index for the next checkpoint because an array index starts wtih 0
for (uint256 i = startFrom; i < end; i++) {
Checkpoint storage tokenCheckpoint = tokenCheckpoints[_token][i];
uint96 weightedStake = staking.getPriorWeightedStake(
_user,
tokenCheckpoint.blockNumber - 1,
tokenCheckpoint.timestamp
);
if (weightedStake > 0) {
// i is the index and we need to return checkpoint num which is i + 1
return (i + 1, i > processedUserCheckpoints, true);
}
}
return (end, end > processedUserCheckpoints, false);
}
/**
* @notice Get the accumulated loan pool fee of the message sender.
* @param _user The address of the user or contract.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @return The accumulated fee for the message sender.
* */
function getAccumulatedFees(address _user, address _token) public view returns (uint256) {
uint256 amount;
(amount, ) = _getAccumulatedFees({
_user: _user,
_token: _token,
_startFrom: 0,
_maxCheckpoints: 0
});
return amount;
}
/**
* @notice Get the accumulated fee rewards for the message sender for a checkpoints range
*
* @dev This function is required to keep consistent with caching of weighted voting power when claiming fees
*
* @param _user The address of a user (staker) or contract.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _startFrom Checkpoint to start calculating fees from.
* @param _maxCheckpoints maxCheckpoints to get accumulated fees for the _user
* @return The accumulated fees rewards for the _user in the given checkpoints interval: [_startFrom, _startFrom + maxCheckpoints].
* */
function getAccumulatedFeesForCheckpointsRange(
address _user,
address _token,
uint256 _startFrom,
uint32 _maxCheckpoints
) external view returns (uint256) {
uint256 amount;
(amount, ) = _getAccumulatedFees(_user, _token, _startFrom, _maxCheckpoints);
return amount;
}
/**
* @dev Get all user fees reward per maxCheckpoint starting from latest processed checkpoint
*
* @dev e.g: Total user checkpoint for the particualar token = 300,
* when we call this function with 50 maxCheckpoint, it will return 6 fee values in array form.
* if there is no more fees, it will return empty array.
*
* @param _user The address of a user (staker) or contract.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _startFrom Checkpoint to start calculating fees from.
* @param _maxCheckpoints maxCheckpoints to get accumulated fees for the _user
* @return The next checkpoint num which is the starting point to fetch all of the fees, array of calculated fees.
* */
function getAllUserFeesPerMaxCheckpoints(
address _user,
address _token,
uint256 _startFrom,
uint32 _maxCheckpoints
) external view returns (uint256[] memory fees) {
require(_maxCheckpoints > 0, "_maxCheckpoints must be > 0");
uint256 totalCheckpoints = totalTokenCheckpoints[_token];
uint256 totalTokensCheckpointsIndex = totalCheckpoints > 0 ? totalCheckpoints - 1 : 0;
if (totalTokensCheckpointsIndex < _startFrom) return fees;
uint256 arrSize = totalTokensCheckpointsIndex.sub(_startFrom).div(_maxCheckpoints) + 1;
fees = new uint256[](arrSize);
for (uint256 i = 0; i < fees.length; i++) {
(uint256 fee, ) = _getAccumulatedFees(
_user,
_token,
_startFrom + i * _maxCheckpoints,
_maxCheckpoints
);
fees[i] = fee;
}
return fees;
}
/**
* @notice Gets accumulated fees for a user starting from a given checkpoint
*
* @param _user Address of the user's account.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.
* @param _maxCheckpoints Max checkpoints to process at once to fit into block gas limit
* @param _startFrom Checkpoint num to start calculations from
*
* @return feesAmount - accumulated fees amount
* @return endCheckpoint - last checkpoint of fees calculation
* */
function _getAccumulatedFees(
address _user,
address _token,
uint256 _startFrom,
uint32 _maxCheckpoints
) internal view returns (uint256 feesAmount, uint256 endCheckpoint) {
if (staking.isVestingContract(_user)) {
return (0, 0);
}
uint256 processedUserCheckpoints = processedCheckpoints[_user][_token];
uint256 startOfRange = _startFrom > processedUserCheckpoints
? _startFrom
: processedUserCheckpoints;
endCheckpoint = _maxCheckpoints > 0
? _getEndOfRange(startOfRange, _token, _maxCheckpoints)
: totalTokenCheckpoints[_token];
if (startOfRange >= totalTokenCheckpoints[_token]) {
return (0, endCheckpoint);
}
uint256 cachedLockDate = 0;
uint96 cachedWeightedStake = 0;
// @note here processedUserCheckpoints is a number of processed checkpoints and
// also an index for the next checkpoint because an array index starts wtih 0
for (uint256 i = startOfRange; i < endCheckpoint; i++) {
Checkpoint memory checkpoint = tokenCheckpoints[_token][i];
uint256 lockDate = staking.timestampToLockDate(checkpoint.timestamp);
uint96 weightedStake;
if (lockDate == cachedLockDate) {
weightedStake = cachedWeightedStake;
} else {
/// @dev We need to use "checkpoint.blockNumber - 1" here to calculate weighted stake
/// For the same block like we did for total voting power in _writeTokenCheckpoint
weightedStake = staking.getPriorWeightedStake(
_user,
checkpoint.blockNumber - 1,
checkpoint.timestamp
);
cachedWeightedStake = weightedStake;
cachedLockDate = lockDate;
}
uint256 share = uint256(checkpoint.numTokens).mul(weightedStake).div(
uint256(checkpoint.totalWeightedStake)
);
feesAmount = feesAmount.add(share);
}
return (feesAmount, endCheckpoint);
}
/**
* @notice Withdrawal should only be possible for blocks which were already
* mined. If the fees are withdrawn in the same block as the user withdrawal
* they are not considered by the withdrawing logic (to avoid inconsistencies).
*
* @param _start Start of the range.
* @param _token RBTC dummy to fit into existing data structure or SOV. Former address of a pool token.
* @param _maxCheckpoints Checkpoint index incremental.
* */
function _getEndOfRange(
uint256 _start,
address _token,
uint32 _maxCheckpoints
) internal view returns (uint256) {
uint256 nextCheckpointIndex = totalTokenCheckpoints[_token];
if (nextCheckpointIndex == 0) {
return 0;
}
uint256 end;
if (_maxCheckpoints == 0) {
/// @dev All checkpoints will be processed (only for getter outside of a transaction).
end = nextCheckpointIndex;
} else {
end = safe32(
_start + _maxCheckpoints,
"FeeSharingCollector::withdraw: checkpoint index exceeds 32 bits"
);
if (end > nextCheckpointIndex) {
end = nextCheckpointIndex;
}
}
/// @dev Withdrawal should only be possible for blocks which were already mined.
uint32 lastBlockNumber = tokenCheckpoints[_token][end - 1].blockNumber;
if (block.number == lastBlockNumber) {
end--;
}
return end;
}
/**
* @notice Write a regular checkpoint w/ the foolowing data:
* block number, block timestamp, total weighted stake and num of tokens.
* @param _token The pool token address.
* @param _numTokens The amount of pool tokens.
* */
function _writeTokenCheckpoint(address _token, uint96 _numTokens) internal {
uint32 blockNumber = safe32(
block.number,