generated from bgd-labs/bgd-forge-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
StakedTokenV3.sol
582 lines (502 loc) · 16.2 KB
/
StakedTokenV3.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
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import {IERC20} from '../interfaces/IERC20.sol';
import {DistributionTypes} from '../lib/DistributionTypes.sol';
import {SafeERC20} from '../lib/SafeERC20.sol';
import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol';
import {IERC20Metadata} from '../interfaces/IERC20Metadata.sol';
import {IStakedTokenV2} from '../interfaces/IStakedTokenV2.sol';
import {StakedTokenV2} from './StakedTokenV2.sol';
import {IStakedTokenV3} from '../interfaces/IStakedTokenV3.sol';
import {PercentageMath} from '../lib/PercentageMath.sol';
import {RoleManager} from '../utils/RoleManager.sol';
import {SafeCast} from '../lib/SafeCast.sol';
/**
* @title StakedTokenV3
* @notice Contract to stake Aave token, tokenize the position and get rewards, inheriting from a distribution manager contract
* @author BGD Labs
*/
contract StakedTokenV3 is
StakedTokenV2,
IStakedTokenV3,
RoleManager,
IAaveDistributionManager
{
using SafeERC20 for IERC20;
using PercentageMath for uint256;
using SafeCast for uint256;
uint256 public constant SLASH_ADMIN_ROLE = 0;
uint256 public constant COOLDOWN_ADMIN_ROLE = 1;
uint256 public constant CLAIM_HELPER_ROLE = 2;
uint216 public constant INITIAL_EXCHANGE_RATE = 1e18;
uint256 public constant EXCHANGE_RATE_UNIT = 1e18;
/// @notice lower bound to prevent spam & avoid exchangeRate issues
// as returnFunds can be called permissionless an attacker could spam returnFunds(1) to produce exchangeRate snapshots making voting expensive
uint256 public immutable LOWER_BOUND;
// Reserved storage space to allow for layout changes in the future.
uint256[8] private ______gap;
/// @notice Seconds between starting cooldown and being able to withdraw
uint256 internal _cooldownSeconds;
/// @notice The maximum amount of funds that can be slashed at any given time
uint256 internal _maxSlashablePercentage;
/// @notice Mirror of latest snapshot value for cheaper access
uint216 internal _currentExchangeRate;
/// @notice Flag determining if there's an ongoing slashing event that needs to be settled
bool public inPostSlashingPeriod;
modifier onlySlashingAdmin() {
require(
msg.sender == getAdmin(SLASH_ADMIN_ROLE),
'CALLER_NOT_SLASHING_ADMIN'
);
_;
}
modifier onlyCooldownAdmin() {
require(
msg.sender == getAdmin(COOLDOWN_ADMIN_ROLE),
'CALLER_NOT_COOLDOWN_ADMIN'
);
_;
}
modifier onlyClaimHelper() {
require(
msg.sender == getAdmin(CLAIM_HELPER_ROLE),
'CALLER_NOT_CLAIM_HELPER'
);
_;
}
constructor(
IERC20 stakedToken,
IERC20 rewardToken,
uint256 unstakeWindow,
address rewardsVault,
address emissionManager,
uint128 distributionDuration
)
StakedTokenV2(
stakedToken,
rewardToken,
unstakeWindow,
rewardsVault,
emissionManager,
distributionDuration
)
{
// brick initialize
lastInitializedRevision = REVISION();
uint256 decimals = IERC20Metadata(address(stakedToken)).decimals();
LOWER_BOUND = 10**decimals;
}
/**
* @dev returns the revision of the implementation contract
* @return The revision
*/
function REVISION() public pure virtual returns (uint256) {
return 3;
}
/**
* @dev returns the revision of the implementation contract
* @return The revision
*/
function getRevision() internal pure virtual override returns (uint256) {
return REVISION();
}
/**
* @dev Called by the proxy contract
*/
function initialize(
address slashingAdmin,
address cooldownPauseAdmin,
address claimHelper,
uint256 maxSlashablePercentage,
uint256 cooldownSeconds
) external virtual initializer {
_initialize(
slashingAdmin,
cooldownPauseAdmin,
claimHelper,
maxSlashablePercentage,
cooldownSeconds
);
}
function _initialize(
address slashingAdmin,
address cooldownPauseAdmin,
address claimHelper,
uint256 maxSlashablePercentage,
uint256 cooldownSeconds
) internal {
InitAdmin[] memory initAdmins = new InitAdmin[](3);
initAdmins[0] = InitAdmin(SLASH_ADMIN_ROLE, slashingAdmin);
initAdmins[1] = InitAdmin(COOLDOWN_ADMIN_ROLE, cooldownPauseAdmin);
initAdmins[2] = InitAdmin(CLAIM_HELPER_ROLE, claimHelper);
_initAdmins(initAdmins);
_setMaxSlashablePercentage(maxSlashablePercentage);
_setCooldownSeconds(cooldownSeconds);
_updateExchangeRate(INITIAL_EXCHANGE_RATE);
}
/// @inheritdoc IAaveDistributionManager
function configureAssets(
DistributionTypes.AssetConfigInput[] memory assetsConfigInput
) external override {
require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER');
for (uint256 i = 0; i < assetsConfigInput.length; i++) {
assetsConfigInput[i].totalStaked = totalSupply();
}
_configureAssets(assetsConfigInput);
}
/// @inheritdoc IStakedTokenV3
function previewStake(uint256 assets) public view returns (uint256) {
return (assets * _currentExchangeRate) / EXCHANGE_RATE_UNIT;
}
/// @inheritdoc IStakedTokenV2
function stake(address to, uint256 amount)
external
override(IStakedTokenV2, StakedTokenV2)
{
_stake(msg.sender, to, amount);
}
/// @inheritdoc IStakedTokenV2
function cooldown() external override(IStakedTokenV2, StakedTokenV2) {
_cooldown(msg.sender);
}
/// @inheritdoc IStakedTokenV3
function cooldownOnBehalfOf(address from) external override onlyClaimHelper {
_cooldown(from);
}
function _cooldown(address from) internal {
uint256 amount = balanceOf(from);
require(amount != 0, 'INVALID_BALANCE_ON_COOLDOWN');
stakersCooldowns[from] = CooldownSnapshot({
timestamp: uint40(block.timestamp),
amount: uint216(amount)
});
emit Cooldown(from, amount);
}
/// @inheritdoc IStakedTokenV2
function redeem(address to, uint256 amount)
external
override(IStakedTokenV2, StakedTokenV2)
{
_redeem(msg.sender, to, amount);
}
/// @inheritdoc IStakedTokenV3
function redeemOnBehalf(
address from,
address to,
uint256 amount
) external override onlyClaimHelper {
_redeem(from, to, amount);
}
/// @inheritdoc IStakedTokenV2
function claimRewards(address to, uint256 amount)
external
override(IStakedTokenV2, StakedTokenV2)
{
_claimRewards(msg.sender, to, amount);
}
/// @inheritdoc IStakedTokenV3
function claimRewardsOnBehalf(
address from,
address to,
uint256 amount
) external override onlyClaimHelper returns (uint256) {
return _claimRewards(from, to, amount);
}
/// @inheritdoc IStakedTokenV3
function claimRewardsAndRedeem(
address to,
uint256 claimAmount,
uint256 redeemAmount
) external override {
_claimRewards(msg.sender, to, claimAmount);
_redeem(msg.sender, to, redeemAmount);
}
/// @inheritdoc IStakedTokenV3
function claimRewardsAndRedeemOnBehalf(
address from,
address to,
uint256 claimAmount,
uint256 redeemAmount
) external override onlyClaimHelper {
_claimRewards(from, to, claimAmount);
_redeem(from, to, redeemAmount);
}
/// @inheritdoc IStakedTokenV3
function getExchangeRate() public view override returns (uint216) {
return _currentExchangeRate;
}
/// @inheritdoc IStakedTokenV3
function previewRedeem(uint256 shares)
public
view
override
returns (uint256)
{
return (EXCHANGE_RATE_UNIT * shares) / _currentExchangeRate;
}
/// @inheritdoc IStakedTokenV3
function slash(address destination, uint256 amount)
external
override
onlySlashingAdmin
returns (uint256)
{
require(!inPostSlashingPeriod, 'PREVIOUS_SLASHING_NOT_SETTLED');
require(amount > 0, 'ZERO_AMOUNT');
uint256 currentShares = totalSupply();
uint256 balance = previewRedeem(currentShares);
uint256 maxSlashable = balance.percentMul(_maxSlashablePercentage);
if (amount > maxSlashable) {
amount = maxSlashable;
}
require(balance - amount >= LOWER_BOUND, 'REMAINING_LT_MINIMUM');
inPostSlashingPeriod = true;
_updateExchangeRate(_getExchangeRate(balance - amount, currentShares));
STAKED_TOKEN.safeTransfer(destination, amount);
emit Slashed(destination, amount);
return amount;
}
/// @inheritdoc IStakedTokenV3
function returnFunds(uint256 amount) external override {
require(amount >= LOWER_BOUND, 'AMOUNT_LT_MINIMUM');
uint256 currentShares = totalSupply();
require(currentShares >= LOWER_BOUND, 'SHARES_LT_MINIMUM');
uint256 assets = previewRedeem(currentShares);
_updateExchangeRate(_getExchangeRate(assets + amount, currentShares));
STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount);
emit FundsReturned(amount);
}
/// @inheritdoc IStakedTokenV3
function settleSlashing() external override onlySlashingAdmin {
inPostSlashingPeriod = false;
emit SlashingSettled();
}
/// @inheritdoc IStakedTokenV3
function setMaxSlashablePercentage(uint256 percentage)
external
override
onlySlashingAdmin
{
_setMaxSlashablePercentage(percentage);
}
/// @inheritdoc IStakedTokenV3
function getMaxSlashablePercentage()
external
view
override
returns (uint256)
{
return _maxSlashablePercentage;
}
/// @inheritdoc IStakedTokenV3
function setCooldownSeconds(uint256 cooldownSeconds)
external
onlyCooldownAdmin
{
_setCooldownSeconds(cooldownSeconds);
}
/// @inheritdoc IStakedTokenV3
function getCooldownSeconds() external view returns (uint256) {
return _cooldownSeconds;
}
/// @inheritdoc IStakedTokenV3
function COOLDOWN_SECONDS() external view returns (uint256) {
return _cooldownSeconds;
}
/**
* @dev sets the max slashable percentage
* @param percentage must be strictly lower 100% as otherwise the exchange rate calculation would result in 0 division
*/
function _setMaxSlashablePercentage(uint256 percentage) internal {
require(
percentage < PercentageMath.PERCENTAGE_FACTOR,
'INVALID_SLASHING_PERCENTAGE'
);
_maxSlashablePercentage = percentage;
emit MaxSlashablePercentageChanged(percentage);
}
/**
* @dev sets the cooldown seconds
* @param cooldownSeconds the new amount of cooldown seconds
*/
function _setCooldownSeconds(uint256 cooldownSeconds) internal {
_cooldownSeconds = cooldownSeconds;
emit CooldownSecondsChanged(cooldownSeconds);
}
/**
* @dev claims the rewards for a specified address to a specified address
* @param from The address of the from from which to claim
* @param to Address to receive the rewards
* @param amount Amount to claim
* @return amount claimed
*/
function _claimRewards(
address from,
address to,
uint256 amount
) internal returns (uint256) {
require(amount != 0, 'INVALID_ZERO_AMOUNT');
uint256 newTotalRewards = _updateCurrentUnclaimedRewards(
from,
balanceOf(from),
false
);
uint256 amountToClaim = (amount > newTotalRewards)
? newTotalRewards
: amount;
require(amountToClaim != 0, 'INVALID_ZERO_AMOUNT');
stakerRewardsToClaim[from] = newTotalRewards - amountToClaim;
REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim);
emit RewardsClaimed(from, to, amountToClaim);
return amountToClaim;
}
/**
* @dev Claims an `amount` of `REWARD_TOKEN` and stakes.
* @param from The address of the from from which to claim
* @param to Address to stake to
* @param amount Amount to claim
* @return amount claimed
*/
function _claimRewardsAndStakeOnBehalf(
address from,
address to,
uint256 amount
) internal returns (uint256) {
require(REWARD_TOKEN == STAKED_TOKEN, 'REWARD_TOKEN_IS_NOT_STAKED_TOKEN');
uint256 userUpdatedRewards = _updateCurrentUnclaimedRewards(
from,
balanceOf(from),
true
);
uint256 amountToClaim = (amount > userUpdatedRewards)
? userUpdatedRewards
: amount;
if (amountToClaim != 0) {
_claimRewards(from, address(this), amountToClaim);
_stake(address(this), to, amountToClaim);
}
return amountToClaim;
}
/**
* @dev Allows staking a specified amount of STAKED_TOKEN
* @param to The address to receiving the shares
* @param amount The amount of assets to be staked
*/
function _stake(
address from,
address to,
uint256 amount
) internal {
require(!inPostSlashingPeriod, 'SLASHING_ONGOING');
require(amount != 0, 'INVALID_ZERO_AMOUNT');
uint256 balanceOfTo = balanceOf(to);
uint256 accruedRewards = _updateUserAssetInternal(
to,
address(this),
balanceOfTo,
totalSupply()
);
if (accruedRewards != 0) {
stakerRewardsToClaim[to] = stakerRewardsToClaim[to] + accruedRewards;
emit RewardsAccrued(to, accruedRewards);
}
uint256 sharesToMint = previewStake(amount);
STAKED_TOKEN.safeTransferFrom(from, address(this), amount);
_mint(to, sharesToMint);
emit Staked(from, to, amount, sharesToMint);
}
/**
* @dev Redeems staked tokens, and stop earning rewards
* @param from Address to redeem from
* @param to Address to redeem to
* @param amount Amount to redeem
*/
function _redeem(
address from,
address to,
uint256 amount
) internal {
require(amount != 0, 'INVALID_ZERO_AMOUNT');
CooldownSnapshot memory cooldownSnapshot = stakersCooldowns[from];
if (!inPostSlashingPeriod) {
require(
(block.timestamp >= cooldownSnapshot.timestamp + _cooldownSeconds),
'INSUFFICIENT_COOLDOWN'
);
require(
(block.timestamp - (cooldownSnapshot.timestamp + _cooldownSeconds) <=
UNSTAKE_WINDOW),
'UNSTAKE_WINDOW_FINISHED'
);
}
uint256 balanceOfFrom = balanceOf(from);
uint256 maxRedeemable = inPostSlashingPeriod
? balanceOfFrom
: cooldownSnapshot.amount;
require(maxRedeemable != 0, 'INVALID_ZERO_MAX_REDEEMABLE');
uint256 amountToRedeem = (amount > maxRedeemable) ? maxRedeemable : amount;
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
uint256 underlyingToRedeem = previewRedeem(amountToRedeem);
_burn(from, amountToRedeem);
if (cooldownSnapshot.timestamp != 0) {
if (cooldownSnapshot.amount - amountToRedeem == 0) {
delete stakersCooldowns[from];
} else {
stakersCooldowns[from].amount =
stakersCooldowns[from].amount -
amountToRedeem.toUint184();
}
}
IERC20(STAKED_TOKEN).safeTransfer(to, underlyingToRedeem);
emit Redeem(from, to, underlyingToRedeem, amountToRedeem);
}
/**
* @dev Updates the exchangeRate and emits events accordingly
* @param newExchangeRate the new exchange rate
*/
function _updateExchangeRate(uint216 newExchangeRate) internal virtual {
require(newExchangeRate != 0, 'ZERO_EXCHANGE_RATE');
_currentExchangeRate = newExchangeRate;
emit ExchangeRateChanged(newExchangeRate);
}
/**
* @dev calculates the exchange rate based on totalAssets and totalShares
* @dev always rounds up to ensure 100% backing of shares by rounding in favor of the contract
* @param totalAssets The total amount of assets staked
* @param totalShares The total amount of shares
* @return exchangeRate as 18 decimal precision uint216
*/
function _getExchangeRate(uint256 totalAssets, uint256 totalShares)
internal
pure
returns (uint216)
{
return
(((totalShares * EXCHANGE_RATE_UNIT) + totalAssets - 1) / totalAssets)
.toUint216();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 balanceOfFrom = balanceOf(from);
// Sender
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
// Recipient
if (from != to) {
uint256 balanceOfTo = balanceOf(to);
_updateCurrentUnclaimedRewards(to, balanceOfTo, true);
CooldownSnapshot memory previousSenderCooldown = stakersCooldowns[from];
if (previousSenderCooldown.timestamp != 0) {
// if cooldown was set and whole balance of sender was transferred - clear cooldown
if (balanceOfFrom == amount) {
delete stakersCooldowns[from];
} else if (balanceOfFrom - amount < previousSenderCooldown.amount) {
stakersCooldowns[from].amount = uint216(balanceOfFrom - amount);
}
}
}
super._transfer(from, to, amount);
}
}