Zealynx AcademyZealynx Academy
ZLX-Check

Spot the Bug: divide before multiply

Question 1 of 3Score 0/3

A staking contract pays a reward as uint r = a / total * rate, where total is far larger than a single stake a. The formula matches the whitepaper. What is still wrong?

Review and apply

Worked answers

Try the quiz above first, then open an answer to compare your reasoning. These notes are also available to read without completing an attempt.

  1. 1. A staking contract pays a reward as uint r = a / total * rate, where total is far larger than a single stake a. The formula matches the whitepaper. What is still wrong?

    • A.Nothing, amount over total times rate is the right formula
    • B.a / total is evaluated first and truncates to zero, so r is zero no matter the rate
    • C.rate should be stored as a uint256 instead of a uint
    • D.pay() should be called before computing r
    Answer and explanation

    B. a / total is evaluated first and truncates to zero, so r is zero no matter the rate

    Solidity evaluates left to right, so a / total runs before the multiply. When a is small and total is large, integer division rounds that quotient down to zero, and zero times rate is zero. Small stakers earn nothing while the code looks correct.

  2. 2. Why does dividing before multiplying destroy the result in integer math?

    • A.Multiplication silently overflows and wraps to zero
    • B.Integer division discards the fractional remainder, so a quotient below one becomes zero before it can be scaled back up
    • C.The compiler reorders the operations at random
    • D.Solidity rounds division to the nearest whole number, up or down
    Answer and explanation

    B. Integer division discards the fractional remainder, so a quotient below one becomes zero before it can be scaled back up

    Solidity has no decimals. Every division rounds toward zero and throws the fraction away. Once a / total truncates to zero, that lost precision can never be recovered, and the later multiply just scales zero. On a hot path the same truncation repeats and the loss compounds.

  3. 3. Which change keeps the reward correct for small stakers?

    • A.uint r = a * rate / total, multiply before dividing so the division runs on a large numerator
    • B.Add a require(a > total) so tiny stakes revert
    • C.Cache total in a local variable before the division
    • D.Emit an event with r so the loss is at least logged
    Answer and explanation

    A. uint r = a * rate / total, multiply before dividing so the division runs on a large numerator

    Multiply before you divide. Computing a * rate first builds a large numerator, so the single final division keeps full precision and only rounds once, at the end. Use a fixed point library for deeper math and audit the rounding direction so any remainder favors the protocol, not the caller.

Read alongside: See it in real audits