Solidity Guide – Calculate Staking Rewards in Solidity

solidity

In my use-case, the staking reward is on per-day basis. For example, by staking a PFP for a day, it should get 10 ERC20 tokens.

I am using the following function to calculate the reward but I doubt if it is correct.

How can I calculate the rewards on per hour or per minute basis?

Thanks.

function calculateReward(uint256 _PFP) public view returns (uint256) {
   Stake memory st = getStakingInfo(_PFP);
   uint256 duration = block.timestamp - st.since;
   duration = SafeMath.div(duration, 1 days);
   return SafeMath.mul(duration, st.ratePerDay);
}

Best Answer

Staking rewards is a common pattern which is almost always solved using the Synthetix Rewards algorithm AKA Masterchef.

This pattern has several delicate issues needed to be dealt with in order to implement it correctly.

See here for a simple implementation of it. In your scenario, your rewardRate would be 10*1e18/1 days (assuming your ERC20 token has 18 decimals). That's because the rewardRate is per second.

You can search online for explanations of the Masterchef algorithm to further understand how it works.

Related Topic