Skip to content
Smart contracts Audit finding Intermediate

Unsafe casting from uint256 to uint16 could cause ticket prizes to become much smaller than intended

The lottery setup code packs each non-jackpot prize into a 16-bit slot using an unchecked cast from a larger integer type, so any prize above roughly 6553.5 tokens silently wraps to a much smaller value. A deployer configuring large prizes would end up with a lottery that pays out far less than intended.

MiloTruck Follow with anodaram, d3e4 and 3 others

Originally disclosed on Code4rena

Submitted by MiloTruck, also found by anodaram, d3e4, adriro, kaden, and nomoi

In LotterySetup.sol, the packFixedRewards() function packs a uint256 array into a uint256 through bitwise arithmetic:

LotterySetup.sol#L164-L176:

function packFixedRewards(uint256[] memory rewards) private view returns (uint256 packed) {
    if (rewards.length != (selectionSize) || rewards[0] != 0) {
        revert InvalidFixedRewardSetup();
    }
    uint256 divisor = 10 ** (IERC20Metadata(address(rewardToken)).decimals() - 1);
    for (uint8 winTier = 1; winTier < selectionSize; ++winTier) {
        uint16 reward = uint16(rewards[winTier] / divisor);
        if ((rewards[winTier] % divisor) != 0) {
            revert InvalidFixedRewardSetup();
        }
        packed |= uint256(reward) << (winTier * 16);
    }
}

The rewards[] parameter stores the prize amount per each winTier, where winTier is the number of matching numbers a ticket has. packFixedRewards() is used when the lottery is first initialized to store the prize for each non-jackpot winTier.

The vulnerability lies in the following line:

uint16 reward = uint16(rewards[winTier] / divisor);

It casts rewards[winTier] / divisor, which is a uint256, to a uint16. If rewards[winTier] / divisor is larger than 2 ** 16 - 1, the unsafe cast will only keep its rightmost bits, causing the result to be much smaller than defined in rewards[].

As divisor is defined as 10 ** (tokenDecimals - 1), the upperbound of rewards[winTier] evaluates to 6553.5 * 10 ** tokenDecimals. This means that the prize of any winTier must not be larger than 6553.5 tokens, otherwise the unsafe cast causes it to become smaller than expected.

Impact

If a deployer is unaware of this upper limit, he could deploy the lottery with ticket prizes larger than 6553.5 tokens, causing non-jackpot ticket prizes to become significantly smaller. The likelihood of this occuring is increased as:

  1. The upper limit is not mentioned anywhere in the documentation.
  2. The upper limit is not immediately obvious when looking at the code.

This upper limit also restricts the protocol from using low price tokens. For example, if the protocol uses SHIB ($0.00001087 per token), the highest possible prize with 6553.5 tokens is worth only $0.071236545.

Proof of Concept

If the lottery is initialized with rewards = [0, 6500, 7000], the prize for each winTier would become the following:

winTier | Token Amount (in tokenDecimals) |

0 | 0 |

1 | 6500 |

2 | 446 |

The prize for winTier = 2 can be derived as such:

(tokenAmount * 10) & type(uint16).max = (7000 * 10) & (2 ** 16 - 1) = 4464
4464 / 10 = 446

The following test demonstrates the above:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import "../src/LotterySetup.sol";
import "./TestToken.sol";

contract RewardUnsafeCastTest is Test {
    ERC20 public rewardToken;

    uint8 public constant SELECTION_SIZE = 3;
    uint8 public constant SELECTION_MAX = 10;

    function setUp() public {
        rewardToken = new TestToken();
    }

    function testRewardIsSmallerThanExpected() public {
        // Get 1 token unit
        uint256 tokenUnit = 10 ** rewardToken.decimals();

        // Define fixedRewards as [0, 6500, 7000]
        uint256[] memory fixedRewards = new uint256[](SELECTION_SIZE);
        fixedRewards[1] = 6500 * tokenUnit;
        fixedRewards[2] = 7000 * tokenUnit;

        // Initialize LotterySetup contract
        LotterySetup lotterySetup = new LotterySetup(
            LotterySetupParams(
                rewardToken,
                LotteryDrawSchedule(block.timestamp + 2*100, 100, 60),
                5 ether,
                SELECTION_SIZE,
                SELECTION_MAX,
                38e16,
                fixedRewards
            )
        );

        // Reward for winTier 1 is 6500
        assertEq(lotterySetup.fixedReward(1) / tokenUnit, 6500);

        // Reward for winTier 2 is 446 instead of 7000
        assertEq(lotterySetup.fixedReward(2) / tokenUnit, 446);
    }
}

Recommended Mitigation Steps

Consider storing the prize amount of each winTier in a mapping instead of packing them into a uint256 using bitwise arithmetic. This approach removes the upper limit (6553.5) and lower limit (0.1) for prizes, which would allow the protocol to use tokens with extremely high or low prices.

Alternatively, check if rewards[winTier] > type(uint256).max and revert if so. This can be done through OpenZeppelin’s SafeCast.

rand0c0des (Wenwin) confirmed


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

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

Root cause

Likely the code casts a uint256 prize value to uint16 without checking that it fits, so values above 65535 (after scaling) are truncated.

Impact

Non-jackpot prizes above about 6553.5 tokens are stored as much smaller amounts, so winners could receive far less than the deployer intended; the text does not describe any external attacker exploiting this, only a misconfiguration risk.

What the attacker needed

Deployer sets a prize above 6553.5 tokens; reward token has standard decimals

The fix

The prize amounts should be stored in a mapping rather than packed with bitwise arithmetic, or the cast should be checked with a safe-cast helper that reverts on overflow.

How it was found

  1. Deploy the lottery with a reward token and a fixed rewards array where a non-jackpot tier exceeds the 16-bit limit.
  2. The setup function divides each prize by a scaling divisor and casts the result to uint16.
  3. The cast keeps only the low bits, so the stored prize is smaller than the configured amount.
  4. Read the fixed reward for that tier and observe the reduced value.

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.

A smart contract stores prize amounts in a compact format by squeezing each one into a small fixed-size slot. When a number is too big for that slot, the code quietly chops off the high part instead of complaining, so a 7000-token prize can be stored as 446. The result is that winners get much less than the lottery operator meant to give them.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by MiloTruck

View all

35 more disclosed reports, best first.

More from Wenwin contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.