Skip to content
Audit finding Intermediate

Division precision loss in `createDistribution` function lead to incorrect distribution of rewards in `GammaRewarder.sol`

The createDistribution function divides the reward amount by the number of epochs using integer division, which truncates any remainder. This can cause small amounts of rewards to be lost over time, leading to slightly lower rewards than intended.

0xAadi Follow with 0xhuh2005, 0xpetern and 14 others

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-10-gamma-rewarder-judging/issues/21

Found by

0xAadi, 0xhuh2005, 0xpetern, Greed, MaslarovK, Naresh, PNS, Praise03, X0sauce, dimah7, irresponsible, newspacexyz, safdie, sammy, tmotfl, tpiliposian, yixuan

Summary

The createDistribution function in the contract contains a potential vulnerability related to precision loss during division calculations, which could lead to incorrect distribution of rewards. This occurs because the distribution logic divides _amount by fixed values without taking adequate measures to handle precision loss.

Root Cause

The createDistribution function calculates amountPerEpoch by dividing realAmountToDistribute by the number of epochs. In cases where _amount is large, this division may lead to precision loss because Solidity's integer division discards the fractional component, potentially causing small discrepancies in each epoch's reward distribution. These inaccuracies accumulate over multiple epochs, leading to an overall loss in reward accuracy. The vulnerability is found in this segment of the createDistribution function: https://github.com/sherlock-audit/2024-10-gamma-rewarder/blob/main/GammaRewarder/contracts/GammaRewarder.sol#L108-L147

Solidity
function createDistribution(
        address _hypervisor, 
        address _rewardToken, 
        uint256 _amount, 
        uint64 _startBlockNum, 
        uint64 _endBlockNum
    ) external nonReentrant {
        // Other requirements and checks

        uint256 fee = _amount * protocolFee / BASE_9;
        uint256 realAmountToDistribute = _amount - fee;
        uint256 amountPerEpoch = realAmountToDistribute / ((_endBlockNum - _startBlockNum) / blocksPerEpoch);

        // Further processing
    }

In this code, amountPerEpoch is calculated by dividing realAmountToDistribute by the number of epochs (which is derived from block range). The result may have a fractional part, but Solidity’s integer division will truncate it, leading to precision loss.

Internal pre-conditions

No response

External pre-conditions

No response

Attack Path

No response

Impact

While this vulnerability does not entirely prevent the function’s operation, it introduces inaccuracies in reward distribution that may lead to small amounts being unrewarded over time. This could be noticeable with large distributions or over long durations, where cumulative precision loss can result in rewards lower than anticipated.

PoC

A Hardhat test can demonstrate the impact of precision loss, especially with large distributions where each division results in a truncated value. Setup:

  1. Deploy a mock ERC20 token (MockRewardToken) and mint tokens to msg.sender.
  2. Deploy the distribution contract.
  3. Set large values for _amount and a reasonable range for epochs to see the effect of precision loss.

Create distribution and validate results: Call createDistribution and observe amountPerEpoch to confirm whether the amount lost to precision affects each epoch's accuracy.

JavaScript
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Division Precision Loss in `createDistribution`", function () {
    let rewardToken, distributionContract, owner, addr1;
    const largeAmount = ethers.utils.parseUnits("1000000000", 18); // Large amount for distribution
    const protocolFee = 100; // Simulated fee of 0.01%

    before(async function () {
        [owner, addr1] = await ethers.getSigners();

        // Deploy mock ERC20 reward token
        const MockRewardToken = await ethers.getContractFactory("MockRewardToken");
        rewardToken = await MockRewardToken.deploy("Reward Token", "RTK", 18);
        await rewardToken.deployed();

        // Mint tokens to addr1 for testing
        await rewardToken.mint(addr1.address, largeAmount);

        // Deploy the distribution contract
        const DistributionContract = await ethers.getContractFactory("DistributionContract");
        distributionContract = await DistributionContract.deploy(protocolFee);
        await distributionContract.deployed();
    });

    it("Should exhibit precision loss in `amountPerEpoch` calculation", async function () {
        // Set allowance
        await rewardToken.connect(addr1).approve(distributionContract.address, largeAmount);

        // Calculate expected values manually for comparison
        const epochs = 10; // Example block range divided into 10 epochs
        const realAmountToDistribute = largeAmount.mul(9999).div(10000); // Deduct protocol fee
        const expectedPerEpoch = realAmountToDistribute.div(epochs);

        // Execute createDistribution
        await distributionContract.connect(addr1).createDistribution(
            addr1.address, 
            rewardToken.address, 
            largeAmount, 
            1000, 
            2000
        );

        // Fetch distribution info and validate precision loss
        const distribution = await distributionContract.getDistribution(addr1.address);
        expect(distribution.amountPerEpoch).to.be.lt(expectedPerEpoch);
    });
});

Running this Hardhat test produces output showing that amountPerEpoch is lower than expected due to precision loss.

Mitigation

To mitigate this issue, consider modifying the calculation to use a higher precision mechanism, such as scaling the division before converting it back. For example, consider using a 10**18 multiplier to help retain more precision during the division, or calculate amountPerEpoch in a way that evenly distributes any rounding discrepancies over epochs.

Solidity
uint256 amountPerEpoch = realAmountToDistribute * 10**18 / numberOfEpochs; // Multiplied to retain precision
amountPerEpoch = amountPerEpoch / 10**18; // Convert back after scaling

Alternatively, use a mod function to calculate any remainder and distribute it across epochs to ensure accurate distribution.

Discussion

sherlock-admin2

The protocol team fixed this issue in the following PRs/commits: https://github.com/GammaStrategies/GammaRewarder/pull/2

The original report as published on Sherlock, by 0xAadi. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Impact

This could cause small amounts of rewards to be unrewarded over time, with cumulative precision loss resulting in rewards lower than anticipated, especially with large distributions or long durations.

What the attacker needed

None

The fix

The protocol team fixed this issue in a pull request.

How it was found

  1. Deploy a mock ERC20 token and mint tokens to the sender.
  2. Deploy the distribution contract with a protocol fee.
  3. Approve the distribution contract to spend the tokens.
  4. Call createDistribution with a large amount and a block range.
  5. Observe that the calculated amountPerEpoch is less than the expected value due to truncation.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When a smart contract splits a reward among many time periods, it uses whole numbers only. If the total doesn't divide evenly, the leftover fraction is thrown away, so each period gets a tiny bit less. Over many periods, these tiny losses add up, meaning some rewards are never paid out.

More by 0xAadi

View all

13 more disclosed reports, best first.

More from Gamma Brevis Rewarder

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.