What are reward accounting errors?

Reward accounting errors are bugs in the code that tracks how much of a reward stream each user has earned, usually a global reward-per-token index and a per-user checkpoint. When a balance changes before the index and the checkpoint are updated, or a stake moves to another address without settling either side, users earn for time they weren't staked or claim the same rewards twice. Settle the index and every affected account before any balance changes, transfers included.

Last updated . 6 minute read. By the QuillAudits Team.

How does reward accounting work?

Most staking and liquidity mining contracts follow the same pattern:

  • A global index, rewardPerTokenStored, grows by the rewards emitted per staked token since the last update.
  • Each account stores the index value at its own last update, userRewardPerTokenPaid.
  • An account has earned its balance times the difference between the current index and its stored one, plus anything already settled.

The pattern is only correct if every change to a balance, or to the total staked, happens after the index and the checkpoint of every account involved have been brought up to date. Each way of skipping that step is a bug of its own:

  • Transfers without settlement. Stake receipts move to an address whose checkpoint is zero, and that address is paid for the whole history of the pool.
  • One path without the update. A new function that changes balances, such as an emergency withdrawal or a migration, skips the update.
  • Rate changes without the update. Changing rewardRate before bringing the index up to date pays the new rate for past time.
  • Empty periods. While nothing is staked, rewards accrue with no one to pay, and depending on the code they stay stuck or go to the first staker.
  • Precision. rewardRate * elapsed * 1e18 / totalStaked rounds down to 0 when the total is large and the rate is small, and the rewards are lost.
  • Funding. A rate that promises more than the contract holds leaves the last claimers unpaid.

What does vulnerable code look like?

Vulnerable: transferable stake receipts that move without settling rewards (illustrative, not audited code) UnsettledRewards.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract UnsettledRewards {
    uint256 public immutable rewardRate; // reward tokens paid per second, shared by all stakers
    uint256 public lastUpdate;
    uint256 public rewardPerTokenStored;
    uint256 public totalStaked;
    mapping(address => uint256) public balanceOf; // transferable stake receipts
    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    constructor(uint256 rewardRate_) {
        rewardRate = rewardRate_;
        lastUpdate = block.timestamp;
    }

    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdate = block.timestamp;
        rewards[account] = earned(account);
        userRewardPerTokenPaid[account] = rewardPerTokenStored;
        _;
    }

    function rewardPerToken() public view returns (uint256) {
        if (totalStaked == 0) return rewardPerTokenStored;
        return rewardPerTokenStored + (block.timestamp - lastUpdate) * rewardRate * 1e18 / totalStaked;
    }

    function earned(address account) public view returns (uint256) {
        return balanceOf[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account];
    }

    function stake(uint256 amount) external updateReward(msg.sender) {
        balanceOf[msg.sender] += amount;
        totalStaked += amount;
        // ... pull `amount` staking tokens from msg.sender
    }

    function claim() external updateReward(msg.sender) returns (uint256 paid) {
        paid = rewards[msg.sender];
        rewards[msg.sender] = 0;
        // ... send `paid` reward tokens to msg.sender
    }

    // Moves the receipt without settling either side. A fresh address has never
    // been checkpointed, so it is paid for all rewards since the start, again.
    function transfer(address to, uint256 amount) external returns (bool) {
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        return true;
    }
}

Alice stakes 100 and, at 1 token per second, earns 100 in 100 seconds, which she claims. She transfers her 100 receipts to a fresh address that has never been checkpointed, so earned counts its whole balance against the index from zero: another 100. In a Foundry test the fresh address claimed the same 100 again, and a loop of fresh addresses repeats it until the reward pool is empty.

How do you fix it?

Fixed: every balance change settles every account it touches first (illustrative, not audited code) SettledRewards.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract SettledRewards {
    uint256 public immutable rewardRate;
    uint256 public lastUpdate;
    uint256 public rewardPerTokenStored;
    uint256 public totalStaked;
    mapping(address => uint256) public balanceOf;
    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    constructor(uint256 rewardRate_) {
        rewardRate = rewardRate_;
        lastUpdate = block.timestamp;
    }

    function rewardPerToken() public view returns (uint256) {
        if (totalStaked == 0) return rewardPerTokenStored;
        return rewardPerTokenStored + (block.timestamp - lastUpdate) * rewardRate * 1e18 / totalStaked;
    }

    function earned(address account) public view returns (uint256) {
        return balanceOf[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account];
    }

    // Brings the global index up to now, then pays `account` up to it.
    // Every function that changes a balance calls this first, for every account it touches.
    function _settle(address account) private {
        rewardPerTokenStored = rewardPerToken();
        lastUpdate = block.timestamp;
        rewards[account] = earned(account);
        userRewardPerTokenPaid[account] = rewardPerTokenStored;
    }

    function stake(uint256 amount) external {
        _settle(msg.sender);
        balanceOf[msg.sender] += amount;
        totalStaked += amount;
        // ... pull `amount` staking tokens from msg.sender
    }

    function claim() external returns (uint256 paid) {
        _settle(msg.sender);
        paid = rewards[msg.sender];
        rewards[msg.sender] = 0;
        // ... send `paid` reward tokens to msg.sender
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _settle(msg.sender);
        _settle(to); // the receiver starts from the current index, not from zero
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        return true;
    }
}
  • Settle both sides of a transfer. The fixed transfer updates the sender and the receiver before moving the balance, so the receiver starts from the current index. In the same test the fresh address earned nothing for the past and 10 tokens for the next 10 seconds.
  • Keep the update in one function. _settle is the only place the index moves, and every function that changes a balance calls it first, emergency paths included.
  • Update before changing the rate. Bring the index up to now at the old rate, then set the new one.
  • Scale for precision. Keep the 1e18 factor, or a larger one for tokens with few decimals, and check that small rates on large totals don't round to 0.
  • Fund before promising. When setting a rate, check that the contract holds enough to pay it for the whole period.

How has reward accounting been exploited?

Protocol Compound COMP distribution
Date 29 September 2021
Chain Ethereum
Loss about $80M of COMP paid out in excess
What happened Compound's Proposal 62 upgraded its Comptroller, the contract that pays COMP rewards to suppliers and borrowers. According to rekt.news, the updated Comptroller had a vulnerability and about $80M of COMP was wrongly distributed, and a later proposal, 64, carried the fix. Anyone could call drip() on Compound's Reservoir to refill the Comptroller, so more COMP kept flowing into the vulnerable contract, and rekt cites a tally of $147M in all.
Sources rekt.news, rekt.news

Compound's bug arrived in an upgrade, not at launch, and once it was live the contract kept paying until a second proposal fixed it. Review every change to reward code as carefully as the original, and keep a way to pause distribution while a fix is prepared.

What invariants should reward code keep?

Invariant Broken by
Rewards paid plus rewards owed never exceed rewards funded Double claims, unsettled transfers, rate changes without an update
The sum of user balances equals the total staked A path that changes one without the other
An account's checkpoint equals the index whenever its balance changes Any balance change before settlement
An account earns only for time it held the stake Receipts that arrive with an old or zero checkpoint

Each line works as a Foundry invariant test: let the fuzzer stake, withdraw, transfer and claim from many addresses in random order, and assert the line after every call.

What should a reviewer check?

  • List every function that changes a staked balance or the total, including transfers, emergency withdrawals and migrations. Does each one settle every account it touches first?
  • Are stake receipts transferable, and if so, is the receiver settled before its balance grows?
  • Is the index brought up to date before rewardRate, the reward period or the reward token changes?
  • What happens to rewards emitted while nothing is staked?
  • Can rewardRate * elapsed * 1e18 / totalStaked round to 0 at realistic sizes?
  • Does the contract hold enough reward tokens for the rate it promises, and is the reward token kept apart from the staked token?
  • Is there an invariant test that rewards paid plus rewards owed never exceed rewards funded?

How does QuillShield check for reward accounting errors?

Reward bugs hide in the function nobody thought of as a reward function: a transfer, a migration, an emergency exit. QuillShield runs a full audit of a Solidity codebase in a Foundry project. It builds a security graph of the code and lists the invariants the code must keep. The table above is a good start for writing your own.

A separate reviewer agent tries to disprove every finding before you see it, and each finding that holds up comes with the exact lines, the impact, a recommended fix and, on full audits, a proof of concept. It then checks every pull request on GitHub or GitLab.com against that graph, and reward code needs that, because new reward tokens, boosts and migrations keep arriving after launch.

Run a full audit on your staking and gauge contracts. New accounts get $50 in credit, good for up to half of an order.

FAQ

Why do stake receipts need settlement on transfer?

Because what an account has earned depends on its checkpoint. A receiver with an old or zero checkpoint is paid as if it had held the stake all along, and a sender that isn't settled first can lose what it earned.

What happens to rewards when nobody is staked?

In the reward-per-token pattern shown here, the index doesn't move while the total is zero, so those rewards are never assigned. Decide on purpose: pause emissions, send them to a treasury or carry them forward.

How do I test reward accounting in Foundry?

Write an invariant test with a handler that stakes, withdraws, transfers and claims from many addresses, and assert that rewards paid plus rewards owed never exceed what was funded.

Is rounding in reward math a real risk?

Yes, in both directions. Rounding down loses small rewards when the total staked is large, and rounding in users' favor lets the contract promise more than it holds, so the last claimer comes up short. The page on rounding and precision errors covers the general case.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts