-
Notifications
You must be signed in to change notification settings - Fork 200
/
FraxCrossChainFarm.sol
executable file
·772 lines (627 loc) · 30.8 KB
/
FraxCrossChainFarm.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
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================== FraxCrossChainFarm ========================
// ====================================================================
// No veFXS logic
// Because of lack of cross-chain reading of the gauge controller's emission rate,
// the contract sets its reward based on its token balance(s)
// Rolling 7 day reward period idea credit goes to denett
// rewardRate0 and rewardRate1 will look weird as people claim, but if you track the rewards actually emitted,
// the numbers do check out
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Dennis: github.com/denett
// Originally inspired by Synthetix.io, but heavily modified by the Frax team
// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
import "../Math/Math.sol";
import "../Math/SafeMath.sol";
import "../Curve/IveFXS.sol";
import "../Curve/FraxCrossChainRewarder.sol";
import "../ERC20/ERC20.sol";
import '../Uniswap/TransferHelper.sol';
import "../ERC20/SafeERC20.sol";
// import '../Misc_AMOs/impossible/IStableXPair.sol'; // Impossible
// import '../Misc_AMOs/mstable/IFeederPool.sol'; // mStable
import '../Misc_AMOs/snowball/ILPToken.sol'; // Snowball S4D - [Part 1]
import '../Misc_AMOs/snowball/ISwapFlashLoan.sol'; // Snowball S4D - [Part 2]
// import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; // Uniswap V2
import "../Utils/ReentrancyGuard.sol";
// Inheritance
import "./Owned.sol";
contract FraxCrossChainFarm is Owned, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/* ========== STATE VARIABLES ========== */
// Instances
IveFXS public veFXS;
ERC20 public rewardsToken0;
ERC20 public rewardsToken1;
// IStableXPair public stakingToken; // Impossible
// IFeederPool public stakingToken; // mStable
ILPToken public stakingToken; // Snowball S4D
// IUniswapV2Pair public stakingToken; // Uniswap V2
FraxCrossChainRewarder public rewarder;
// FRAX
address public frax_address;
// Constant for various precisions
uint256 private constant MULTIPLIER_PRECISION = 1e18;
// Admin addresses
address public timelock_address; // Governance timelock address
address public controller_address; // Gauge controller
// Time tracking
uint256 public periodFinish;
uint256 public lastUpdateTime;
// Lock time and multiplier settings
uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18
uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years
uint256 public lock_time_min = 86400; // 1 * 86400 (1 day)
// veFXS related
uint256 public vefxs_per_frax_for_max_boost = uint256(4e18); // E18. 4e18 means 4 veFXS must be held by the staker per 1 FRAX
uint256 public vefxs_max_multiplier = uint256(2e18); // E18. 1x = 1e18
mapping(address => uint256) private _vefxsMultiplierStored;
// Max reward per second
uint256 public rewardRate0;
uint256 public rewardRate1;
// Reward period
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days).
// Reward tracking
uint256 public ttlRew0Owed;
uint256 public ttlRew1Owed;
uint256 public ttlRew0Paid;
uint256 public ttlRew1Paid;
uint256 private rewardPerTokenStored0;
uint256 private rewardPerTokenStored1;
mapping(address => uint256) public userRewardPerTokenPaid0;
mapping(address => uint256) public userRewardPerTokenPaid1;
mapping(address => uint256) public rewards0;
mapping(address => uint256) public rewards1;
uint256 public lastRewardPull;
// Balance tracking
uint256 private _total_liquidity_locked;
uint256 private _total_combined_weight;
mapping(address => uint256) private _locked_liquidity;
mapping(address => uint256) private _combined_weights;
// Uniswap V2 / Impossible ONLY
bool frax_is_token0;
// Stake tracking
mapping(address => LockedStake[]) private lockedStakes;
// List of valid migrators (set by governance)
mapping(address => bool) public valid_migrators;
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) public staker_allowed_migrators;
// Greylisting of bad addresses
mapping(address => bool) public greylist;
// Administrative booleans
bool public migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public stakesUnlocked; // Release locked stakes in case of system migration or emergency
bool public withdrawalsPaused; // For emergencies
bool public rewardsCollectionPaused; // For emergencies
bool public stakingPaused; // For emergencies
bool public isInitialized;
/* ========== STRUCTS ========== */
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 liquidity;
uint256 ending_timestamp;
uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCtrlr() {
require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "Not own, tlk, or ctrlr");
_;
}
modifier isMigrating() {
require(migrationsOn == true, "Not in migration");
_;
}
modifier notStakingPaused() {
require(!stakingPaused, "Staking paused");
_;
}
modifier updateRewardAndBalance(address account, bool sync_too) {
_updateRewardAndBalance(account, sync_too);
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner,
address _rewardsToken0,
address _rewardsToken1,
address _stakingToken,
address _frax_address,
address _timelock_address,
address _rewarder_address
) Owned(_owner){
frax_address = _frax_address;
rewardsToken0 = ERC20(_rewardsToken0);
rewardsToken1 = ERC20(_rewardsToken1);
// stakingToken = IStableXPair(_stakingToken);
// stakingToken = IFeederPool(_stakingToken);
stakingToken = ILPToken(_stakingToken);
// stakingToken = IUniswapV2Pair(_stakingToken);
timelock_address = _timelock_address;
rewarder = FraxCrossChainRewarder(_rewarder_address);
// // Uniswap V2 / Impossible ONLY
// // Need to know which token FRAX is (0 or 1)
// address token0 = stakingToken.token0();
// if (token0 == frax_address) frax_is_token0 = true;
// else frax_is_token0 = false;
// Other booleans
migrationsOn = false;
stakesUnlocked = false;
// For initialization
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
}
/* ========== VIEWS ========== */
// Total locked liquidity tokens
function totalLiquidityLocked() external view returns (uint256) {
return _total_liquidity_locked;
}
// Locked liquidity for a given account
function lockedLiquidityOf(address account) external view returns (uint256) {
return _locked_liquidity[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier and veFXS multiplier
function totalCombinedWeight() external view returns (uint256) {
return _total_combined_weight;
}
// Combined weight for a specific account
function combinedWeightOf(address account) external view returns (uint256) {
return _combined_weights[account];
}
// All the locked stakes for a given account
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function lockMultiplier(uint256 secs) public view returns (uint256) {
uint256 lock_multiplier =
uint256(MULTIPLIER_PRECISION).add(
secs
.mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION))
.div(lock_time_for_max_multiplier)
);
if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier;
return lock_multiplier;
}
function lastTimeRewardApplicable() internal view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function fraxPerLPToken() public view returns (uint256) {
// Get the amount of FRAX 'inside' of the lp tokens
uint256 frax_per_lp_token;
// mStable
// ============================================
// {
// uint256 total_frax_reserves;
// (, IFeederPool.BassetData memory vaultData) = (stakingToken.getBasset(frax_address));
// total_frax_reserves = uint256(vaultData.vaultBalance);
// frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply());
// }
// Snowball S4D
// ============================================
{
ISwapFlashLoan ISFL = ISwapFlashLoan(0xA0bE4f05E37617138Ec212D4fB0cD2A8778a535F);
uint256 total_frax = ISFL.getTokenBalance(ISFL.getTokenIndex(frax_address));
frax_per_lp_token = total_frax.mul(1e18).div(stakingToken.totalSupply());
}
// Uniswap V2 & Impossible
// ============================================
// {
// uint256 total_frax_reserves;
// (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves());
// if (frax_is_token0) total_frax_reserves = reserve0;
// else total_frax_reserves = reserve1;
// frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply());
// }
return frax_per_lp_token;
}
function userStakedFrax(address account) public view returns (uint256) {
return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18);
}
function minVeFXSForMaxBoost(address account) public view returns (uint256) {
return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION);
}
function veFXSMultiplier(address account) public view returns (uint256) {
if (address(veFXS) != address(0)){
// The claimer gets a boost depending on amount of veFXS they have relative to the amount of FRAX 'inside'
// of their locked LP tokens
uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account);
if (veFXS_needed_for_max_boost > 0){
uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost);
uint256 vefxs_multiplier = ((user_vefxs_fraction).mul(vefxs_max_multiplier)).div(MULTIPLIER_PRECISION);
// Cap the boost to the vefxs_max_multiplier
if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier;
return vefxs_multiplier;
}
else return 0; // This will happen with the first stake, when user_staked_frax is 0
}
else return 0;
}
function calcCurCombinedWeight(address account) public view
returns (
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
)
{
// Get the old combined weight
old_combined_weight = _combined_weights[account];
// Get the veFXS multipliers
// For the calculations, use the midpoint (analogous to midpoint Riemann sum)
new_vefxs_multiplier = veFXSMultiplier(account);
uint256 midpoint_vefxs_multiplier;
if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) {
// This is only called for the first stake to make sure the veFXS multiplier is not cut in half
midpoint_vefxs_multiplier = new_vefxs_multiplier;
}
else {
midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2);
}
// Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion
new_combined_weight = 0;
for (uint256 i = 0; i < lockedStakes[account].length; i++) {
LockedStake memory thisStake = lockedStakes[account][i];
uint256 lock_multiplier = thisStake.lock_multiplier;
// If the lock period is over, drop the lock multiplier down to 1x for the weight calculations
if (thisStake.ending_timestamp <= block.timestamp){
lock_multiplier = MULTIPLIER_PRECISION;
}
uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION);
new_combined_weight = new_combined_weight.add(combined_boosted_amount);
}
}
function rewardPerToken() public view returns (uint256, uint256) {
if (_total_liquidity_locked == 0 || _total_combined_weight == 0) {
return (rewardPerTokenStored0, rewardPerTokenStored1);
}
else {
return (
rewardPerTokenStored0.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_total_combined_weight)
),
rewardPerTokenStored1.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_total_combined_weight)
)
);
}
}
function earned(address account) public view returns (uint256, uint256) {
(uint256 rew_per_token0, uint256 rew_per_token1) = rewardPerToken();
if (_combined_weights[account] == 0){
return (0, 0);
}
return (
(_combined_weights[account].mul(rew_per_token0.sub(userRewardPerTokenPaid0[account]))).div(1e18).add(rewards0[account]),
(_combined_weights[account].mul(rew_per_token1.sub(userRewardPerTokenPaid1[account]))).div(1e18).add(rewards1[account])
);
}
function getRewardForDuration() external view returns (uint256, uint256) {
return (
rewardRate0.mul(rewardsDuration),
rewardRate1.mul(rewardsDuration)
);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _updateRewardAndBalance(address account, bool sync_too) internal {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
if (sync_too){
sync();
}
if (account != address(0)) {
// To keep the math correct, the user's combined weight must be recomputed to account for their
// ever-changing veFXS balance.
(
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
) = calcCurCombinedWeight(account);
// Calculate the earnings first
_syncEarned(account);
// Update the user's stored veFXS multipliers
_vefxsMultiplierStored[account] = new_vefxs_multiplier;
// Update the user's and the global combined weights
if (new_combined_weight >= old_combined_weight) {
uint256 weight_diff = new_combined_weight.sub(old_combined_weight);
_total_combined_weight = _total_combined_weight.add(weight_diff);
_combined_weights[account] = old_combined_weight.add(weight_diff);
} else {
uint256 weight_diff = old_combined_weight.sub(new_combined_weight);
_total_combined_weight = _total_combined_weight.sub(weight_diff);
_combined_weights[account] = old_combined_weight.sub(weight_diff);
}
}
}
function _syncEarned(address account) internal {
if (account != address(0)) {
// Calculate the earnings
(uint256 earned0, uint256 earned1) = earned(account);
rewards0[account] = earned0;
rewards1[account] = earned1;
userRewardPerTokenPaid0[account] = rewardPerTokenStored0;
userRewardPerTokenPaid1[account] = rewardPerTokenStored1;
}
}
// Staker can allow a migrator
function stakerAllowMigrator(address migrator_address) external {
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
// Staker can disallow a previously-allowed migrator
function stakerDisallowMigrator(address migrator_address) external {
// Delete from the mapping
delete staker_allowed_migrators[msg.sender][migrator_address];
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant public {
_stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stakeLocked(
address staker_address,
address source_address,
uint256 liquidity,
uint256 secs,
uint256 start_timestamp
) internal updateRewardAndBalance(staker_address, true) {
require(!stakingPaused || valid_migrators[msg.sender] == true, "Staking paused or in migration");
require(liquidity > 0, "Must stake more than zero");
require(greylist[staker_address] == false, "Address has been greylisted");
require(secs >= lock_time_min, "Minimum stake time not met");
require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long");
uint256 lock_multiplier = lockMultiplier(secs);
bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address]));
lockedStakes[staker_address].push(LockedStake(
kek_id,
start_timestamp,
liquidity,
start_timestamp.add(secs),
lock_multiplier
));
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity);
// Update liquidities
_total_liquidity_locked = _total_liquidity_locked.add(liquidity);
_locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity);
// Need to call to update the combined weights
_updateRewardAndBalance(staker_address, true);
emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address);
}
// Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdrawLocked(bytes32 kek_id) nonReentrant public {
require(withdrawalsPaused == false, "Withdrawals paused");
_withdrawLocked(msg.sender, msg.sender, kek_id);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal {
// Collect rewards first and then update the balances
_getReward(staker_address, destination_address);
LockedStake memory thisStake;
thisStake.liquidity = 0;
uint theArrayIndex;
for (uint i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
thisStake = lockedStakes[staker_address][i];
theArrayIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!");
uint256 liquidity = thisStake.liquidity;
if (liquidity > 0) {
// Update liquidities
_total_liquidity_locked = _total_liquidity_locked.sub(liquidity);
_locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity);
// Remove the stake from the array
delete lockedStakes[staker_address][theArrayIndex];
// Need to call to update the combined weights
_updateRewardAndBalance(staker_address, false);
// Give the tokens to the destination_address
// Should throw if insufficient balance
stakingToken.transfer(destination_address, liquidity);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
}
}
// Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() external nonReentrant returns (uint256, uint256) {
require(rewardsCollectionPaused == false,"Rewards collection paused");
return _getReward(msg.sender, msg.sender);
}
// No withdrawer == msg.sender check needed since this is only internally callable
// This distinction is important for the migrator
function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256 reward0, uint256 reward1) {
reward0 = rewards0[rewardee];
reward1 = rewards1[rewardee];
if (reward0 > 0) {
rewards0[rewardee] = 0;
rewardsToken0.transfer(destination_address, reward0);
ttlRew0Paid += reward0;
emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address);
}
if (reward1 > 0) {
rewards1[rewardee] = 0;
rewardsToken1.transfer(destination_address, reward1);
ttlRew1Paid += reward1;
emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address);
}
}
// Quasi-notifyRewardAmount() logic
function syncRewards() internal {
// Bring in rewards, if applicable
if ((address(rewarder) != address(0)) && ((block.timestamp).sub(lastRewardPull) >= rewardsDuration)){
rewarder.distributeReward();
lastRewardPull = block.timestamp;
}
// Get the current reward token balances
uint256 curr_bal_0 = rewardsToken0.balanceOf(address(this));
uint256 curr_bal_1 = rewardsToken1.balanceOf(address(this));
// Update the owed amounts based off the old reward rates
// Anything over a week is zeroed
{
uint256 eligible_elapsed_time = Math.min((block.timestamp).sub(lastUpdateTime), rewardsDuration);
ttlRew0Owed += rewardRate0.mul(eligible_elapsed_time);
ttlRew1Owed += rewardRate1.mul(eligible_elapsed_time);
}
// Update the stored amounts too
{
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
}
// Set the reward rates based on the free amount of tokens
{
// Don't count unpaid rewards as free
uint256 unpaid0 = ttlRew0Owed.sub(ttlRew0Paid);
uint256 unpaid1 = ttlRew1Owed.sub(ttlRew1Paid);
// Handle reward token0
if (curr_bal_0 <= unpaid0){
// token0 is depleted, so stop emitting
rewardRate0 = 0;
}
else {
uint256 free0 = curr_bal_0.sub(unpaid0);
rewardRate0 = (free0).div(rewardsDuration);
}
// Handle reward token1
if (curr_bal_1 <= unpaid1){
// token1 is depleted, so stop emitting
rewardRate1 = 0;
}
else {
uint256 free1 = curr_bal_1.sub(unpaid1);
rewardRate1 = (free1).div(rewardsDuration);
}
}
}
function sync() public {
require(isInitialized, "Contract not initialized");
// Make sure the rewardRates are synced to the current FXS balance
syncRewards();
// Rolling 8 days rewards period
lastUpdateTime = block.timestamp;
periodFinish = (block.timestamp).add(rewardsDuration);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Needed when first deploying the farm
// Make sure rewards are present
function initializeDefault() external onlyByOwnGovCtrlr {
require(!isInitialized, "Already initialized");
isInitialized = true;
// Bring in rewards, if applicable
if (address(rewarder) != address(0)){
rewarder.distributeReward();
lastRewardPull = block.timestamp;
}
emit DefaultInitialization();
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can).
function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating {
require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved");
_stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp);
}
// Used for migrations
function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating {
require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved");
_withdrawLocked(staker_address, msg.sender, kek_id);
}
// Adds supported migrator address
function addMigrator(address migrator_address) external onlyByOwnGov {
valid_migrators[migrator_address] = true;
}
// Remove a migrator address
function removeMigrator(address migrator_address) external onlyByOwnGov {
require(valid_migrators[migrator_address] == true, "Address nonexistent");
// Delete from the mapping
delete valid_migrators[migrator_address];
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Admin cannot withdraw the staking token from the contract unless currently migrating
if(!migrationsOn){
require(tokenAddress != address(stakingToken), "Not in migration"); // Only Governance / Timelock can trigger a migration
}
// Only the owner address can ever receive the recovery withdrawal
ERC20(tokenAddress).transfer(owner, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwnGov {
require(_lock_max_multiplier >= MULTIPLIER_PRECISION, "Mult must be >= MULTIPLIER_PRECISION");
require(_vefxs_max_multiplier >= 0, "veFXS mul must be >= 0");
require(_vefxs_per_frax_for_max_boost > 0, "veFXS pct max must be >= 0");
lock_max_multiplier = _lock_max_multiplier;
vefxs_max_multiplier = _vefxs_max_multiplier;
vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost;
emit MaxVeFXSMultiplier(vefxs_max_multiplier);
emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier);
emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost);
}
function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwnGov {
require(_lock_time_for_max_multiplier >= 1, "Mul max time must be >= 1");
require(_lock_time_min >= 1, "Mul min time must be >= 1");
lock_time_for_max_multiplier = _lock_time_for_max_multiplier;
lock_time_min = _lock_time_min;
emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier);
emit LockedStakeMinTime(_lock_time_min);
}
function greylistAddress(address _address) external onlyByOwnGov {
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnGov {
stakesUnlocked = !stakesUnlocked;
}
function toggleMigrations() external onlyByOwnGov {
migrationsOn = !migrationsOn;
}
function toggleStaking() external onlyByOwnGov {
stakingPaused = !stakingPaused;
}
function toggleWithdrawals() external onlyByOwnGov {
withdrawalsPaused = !withdrawalsPaused;
}
function toggleRewardsCollection() external onlyByOwnGov {
rewardsCollectionPaused = !rewardsCollectionPaused;
}
function setTimelock(address _new_timelock) external onlyByOwnGov {
timelock_address = _new_timelock;
}
function setController(address _controller_address) external onlyByOwnGov {
controller_address = _controller_address;
}
function setVeFXS(address _vefxs_address) external onlyByOwnGov {
veFXS = IveFXS(_vefxs_address);
}
/* ========== EVENTS ========== */
event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address);
event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address);
event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address);
event DefaultInitialization();
event Recovered(address token, uint256 amount);
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
event MaxVeFXSMultiplier(uint256 multiplier);
event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor);
}