In Statistics.sol::variance
the variance calculation may incorrectly revert if any data points are below the average (mean). This happens because when you subtract the average (mean) from a smaller number, you get a negative result.
However, since we’re using unsigned integers (which can’t be negative), the program tries to use a negative value, causing it to fail.
This is because Solidity reverts (or stops) the transaction whenever an unsigned integer (like uint256) tries to go negative.
Failed Transactions
The variance function will fail entirely (reverting the transaction) if any element in the dataset is smaller than the mean. This is problematic for datasets where values may naturally be lower than the average, preventing it from calculating valid variance.
IMPACT : HIGH
LIKELIHOOD : LOW
Set up an Array with Values and a Calculated Mean:
Create an array of unsigned integers, data = [6, 8, 3].
Calculate the mean of this array, which will be a value greater than some of the numbers in data:
mean = (6 + 8 + 3) / 3 = 5.
Attempt to Compute the Difference Between Each Array Element and the Mean:
Loop through each value in the array. For each element, compute the difference as diff = data[i] - mean.
where the Issue occurs:
In this case:
For data[0] = 6, diff = 6 - 5 = 1 (no issue).
For data[1] = 8, diff = 8 - 5 = 3 (no issue).
when
For data[2] = 3, diff = 3 - 5.
Here, 3 - 5 results in -2, but Solidity doesn’t allow negative numbers for uint256, ultimately resulting in a revert.
Super Mind and School Maths combo
Using absolute differences when calculating variance will allow the function to run smoothly, even when some data elements are smaller than the mean. Like the below one can also solve the issue :
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.