Skip to content

Commit

Permalink
contracts/refactor: Update alpha directly within _updateReward
Browse files Browse the repository at this point in the history
Earlier alpha was being updated in its own function `_updateAlpha`. This
was made a view function `_calculateAccruedAlpha`, and the actual
updating of alpha was done within the `_updateReward` function. This
makes the logic within it clean - It calls other view functions for the
calculation, and handles the events and storage variable updates within
itself.
  • Loading branch information
sayandcode committed Jan 26, 2024
1 parent 6f29bce commit 001c011
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions contracts/src/FinthetixStakingContract.sol
Original file line number Diff line number Diff line change
Expand Up @@ -142,27 +142,25 @@ contract FinthetixStakingContract is FSCEvents, FSCErrors {
}

function _updateReward() private {
_updateAlpha();
alphaNow += _calculateAccruedAlpha();
emit AlphaUpdated(alphaNow);
mapAddrToPublishedReward[msg.sender] += _calculateAccruedRewards();
emit RewardUpdated(msg.sender, mapAddrToPublishedReward[msg.sender]);
lastUpdatedRewardAt = block.timestamp;
mapAddrToAlphaAtLastUserInteraction[msg.sender] = alphaNow;
}

function _updateAlpha() private {
if (totalStakedAmt > 0) {
// unless time > 1e57 (>3x age of universe!), we are safe from overflow
// [Why 1e57? type(uint256).max / COOLDOWN_CONSTANT]
uint256 numerator = (block.timestamp - lastUpdatedRewardAt) * COOLDOWN_CONSTANT;
if (numerator < totalStakedAmt) revert CannotInteractWhenCoolingDown(block.timestamp, lastUpdatedRewardAt);
function _calculateAccruedAlpha() private view returns (uint256) {
if (totalStakedAmt == 0) return 0;

uint256 alphaAccrued = numerator / totalStakedAmt;
alphaNow = alphaNow + alphaAccrued;
emit AlphaUpdated(alphaNow);
}
// unless time > 1e57 (>3x age of universe!), we are safe from overflow
// [Why 1e57? type(uint256).max / COOLDOWN_CONSTANT]
uint256 numerator = (block.timestamp - lastUpdatedRewardAt) * COOLDOWN_CONSTANT;
if (numerator < totalStakedAmt) revert CannotInteractWhenCoolingDown(block.timestamp, lastUpdatedRewardAt);
return numerator / totalStakedAmt;
}

function _calculateAccruedRewards() private view returns (uint256 result) {
function _calculateAccruedRewards() private view returns (uint256) {
uint256 userStakedAmt = mapAddrToStakedAmt[msg.sender];

(bool isProd1Safe, uint256 prod1) = Math.tryMul(userStakedAmt, TOTAL_REWARDS_PER_SECOND);
Expand Down

0 comments on commit 001c011

Please sign in to comment.