The variance
and stddev
functions in the Statistics
library risk reverting due to an underflow error when calculating differences between array elements and the mean. This occurs because the diff
calculation does not account for cases where an element is less than the mean, causing issues when using unsigned integers. Implementing absolute difference handling prevents these reverts, ensuring smooth execution of both functions.
In the variance
function, the line uint256 diff = data[i] - mean
assumes data[i]
is always greater than or equal to mean
, which may not be true. When data[i] < mean
, the subtraction causes an underflow, reverting the transaction. This issue also affects the stddev
function, as it relies on variance
for its calculations. Since uint256
types cannot represent negative values, using absolute values is necessary to avoid this underflow.
In
stddev
function is used.
Reverted Transactions: Without the fix, both variance
and stddev
will revert if any data point is less than the mean, leading to unusable functions in this library.
Poor User Experience: Developers and users may experience unexpected failures when calling these functions, potentially leading to confusion and disrupted contract logic.
To prevent the underflow error, update the variance
function to calculate the absolute difference between data[i]
and mean
. Here is the revised function:
This change ensures variance
and, by extension, stddev
can handle any valid uint256
inputs without risking underflow, providing a robust and predictable experience.
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.