Staking and rewards
Staking means locking funds in a contract to earn rewards over time. The contract must work out how much each staker has earned without looping over every user, because loops cost gas and can grow without limit.
The standard trick is a reward-per-token counter. It tracks how much reward has been earned for each staked unit since the start. Each user stores a snapshot of that counter. Their pending reward is their staked amount times the difference between the current counter and their snapshot.
Update the counter and the user's pending reward before changing any balance. If you change the stake first, the math uses the wrong amount. This is the same idea as updating state before interacting with the outside.
The example uses plain ETH to keep the focus on the accounting. Real staking contracts use ERC-20 tokens, safe transfer helpers and reentrancy guards. Check the rounding of divisions too, because small errors can add up.
contract EthStaking { uint256 public totalStaked; uint256 public rewardPerToken; // scaled by 1e18 mapping(address => uint256) public staked; mapping(address => uint256) public snapshot; mapping(address => uint256) public pending; function _update(address who) internal { pending[who] += staked[who] * (rewardPerToken - snapshot[who]) / 1e18; snapshot[who] = rewardPerToken; } function stake() external payable { _update(msg.sender); staked[msg.sender] += msg.value; totalStaked += msg.value; } function addRewards() external payable { require(totalStaked > 0, "No stakers"); rewardPerToken += msg.value * 1e18 / totalStaked; } function claim() external { _update(msg.sender); uint256 amount = pending[msg.sender]; pending[msg.sender] = 0; (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "Failed"); } function unstake(uint256 amount) external { require(staked[msg.sender] >= amount, "Too much"); _update(msg.sender); staked[msg.sender] -= amount; totalStaked -= amount; (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "Failed"); } }
Try it yourself
Add events Staked and Claimed and emit them. Then add a view function earned(address who) that returns the pending reward plus the reward not yet recorded.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.