error ZeroAddress();
error ZeroAmount();
error Forbidden(address sender);
error RewardPeriodNotFinished();
error InsufficientRewards();
/* ========== STATE VARIABLES ========== */
address public rewardsDistribution;
address public operator;
address public immutable rewardsToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration = 7 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/* ========== MODIFIERS ========== */
modifier onlyRewardsDistribution() {
if (msg.sender != rewardsDistribution) {
revert Forbidden(msg.sender);
}
_;
}
modifier onlyOperator() {
if (msg.sender != operator) {
revert Forbidden(msg.sender);
}
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(address _rewardsDistribution, address _rewardsToken) {
if (_rewardsToken == address(0) || _rewardsDistribution == address(0)) {
revert ZeroAddress();
}
rewardsToken = _rewardsToken;
rewardsDistribution = _rewardsDistribution;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored + (((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / _totalSupply);
}
function earned(address account) public view returns (uint256) {
return (_balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18 + rewards[account];
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate * rewardsDuration;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(address user, uint256 amount) external updateReward(user) onlyOperator {
if (amount == 0) {
revert ZeroAmount();
}
if (user == address(0)) {
revert ZeroAddress();
}
_totalSupply += amount;
_balances[user] += amount;
emit Staked(user, amount);
}
function withdraw(address user, uint256 amount) public updateReward(user) onlyOperator {
if (amount == 0) {
revert ZeroAmount();
}
_totalSupply -= amount;
_balances[user] -= amount;
emit Withdrawn(user, amount);
}
function getReward(address user) public updateReward(user) returns (uint256 reward) {
reward = rewards[user];
if (reward != 0) {
rewards[user] = 0;
IERC20(rewardsToken).safeTransfer(user, reward);
emit RewardPaid(user, reward);
}
}
function exit(address user) external {
if (_balances[user] != 0) {
withdraw(user, _balances[user]);
}
getReward(user);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = IERC20(rewardsToken).balanceOf(address(this));
if (rewardRate > balance / rewardsDuration) {
revert InsufficientRewards();
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
if (block.timestamp <= periodFinish) {
revert RewardPeriodNotFinished();
}
if (_rewardsDuration == 0) {
revert ZeroAmount();
}
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(_rewardsDuration);
}
function setRewardsDistribution(address _rewardsDistribution) external onlyOwner {
if (_rewardsDistribution == address(0)) {
revert ZeroAddress();
}
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionUpdated(_rewardsDistribution);
}
function setOperator(address _operator) external onlyOwner {
if (_operator == address(0)) {
revert ZeroAddress();
}
operator = _operator;
emit OperatorUpdated(_operator);
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event RewardsDistributionUpdated(address indexed rewardsDistribution);
event OperatorUpdated(address indexed operator);
As an AI language model, I'm not able to perform a full legal review that a licensed attorney would conduct. However, I can provide a general code review that identifies potential vulnerabilities or points of concern in this Solidity contract as of my knowledge cutoff in early 2023. Remember that a thorough code review involves both static analysis and dynamic testing to ensure security. Here are some observations based on the provided code:
-
Contract Composition:
- The contract imports OpenZeppelin's Ownable, IERC20, and SafeERC20 contracts. OpenZeppelin libraries are industry-standard and well-audited, which is a positive sign for the safety of the contract.
- The contract implements the
IVirtualStakingRewards interface, which is not provided but is assumed to define function signatures that this contract must implement.
-
Custom Errors:
- The use of custom errors is a practice that could save gas compared to using revert strings.
-
State Variables:
- The
rewardsToken is immutable, which is good practice as it prevents changes after deployment.
- The
periodFinish, rewardRate, rewardsDuration, and lastUpdateTime are variables that are critical for the reward mechanism.
rewardPerTokenStored is used for calculating earnings which could be susceptible to rounding errors, but the use of 1e18 helps mitigate this.
-
Modifiers:
onlyRewardsDistribution and onlyOperator are access control modifiers that restrict function execution to designated addresses. Ensure that roles are set correctly to avoid unauthorized access.
-
Staking Logic:
- The
stake and withdraw functions can only be called by the operator, which introduces centralization concerns. The operator has significant control over user balances, so the operator must be a trusted address.
updateReward modifier ensures rewards are updated before staking or withdrawing. This is good as it aligns reward distribution with these actions.
-
Rewards Distribution Logic:
- The
notifyRewardAmount function allows the rewardsDistribution address to set a new reward rate for the next period.
- There are checks to prevent overflow and ensure the contract has enough funds to pay for the notified reward amount.
-
Time Handling:
- The contract relies on block timestamps (
block.timestamp). Be aware that miners can manipulate block timestamps slightly, but this is generally not a significant concern for durations measured in days.
-
Potential Vulnerabilities:
- No obvious reentrancy vulnerabilities are seen since all external calls are made after state changes.
- No obvious overflow/underflow vulnerabilities since the code uses Solidity 0.8.x, which has built-in overflow checks, and OpenZeppelin's SafeERC20 library.
- Permission controls for the
notifyRewardAmount, setRewardsDuration, setRewardsDistribution, and setOperator functions prevent unauthorized users from calling them, but rely on the security of the Ownable contract and proper management of owner and designated addresses.
-
Events:
- Events are properly declared and emitted for key state changes. This is good for transparency and off-chain tracking.
It is essential that you continuously monitor the contracts for new discoveries related to vulnerabilities and follow the best practices for security. Additionally, for a full audit, ensure that this contract is reviewed by qualified security professionals and that the contracts it interfaces with (such as the unstated IVirtualStakingRewards) are also scrutinized for security guarantees.