The sqrt()
function in the Statistics library implements the Babylonian method for square root calculation, which can be highly gas-intensive when processing large numbers in the range of 0-1e18. This is particularly problematic as the function is called by stddev()
which in turn processes variance calculations.
The current implementation uses an iterative approach that, while mathematically sound, becomes increasingly expensive in terms of gas consumption as the input numbers grow larger. This is especially concerning in the context of financial calculations where precision is required and numbers commonly reach large magnitudes.
The root cause lies in the while loop implementation which may require multiple iterations for convergence with large numbers. Each iteration involves multiple arithmetic operations (division
, addition
) which compound the gas costs.
The impact is most severe when processing statistical calculations on large datasets with high variance values, potentially making certain protocol operations prohibitively expensive or even causing them to hit block gas limits in extreme cases.
Replace the current implementation with an optimized square root calculation from an established and audited library. Specifically, the Solady library provides a highly gas-optimized implementation of square root calculations that has undergone extensive testing and optimization.
To implement this change:
Import the Solady FixedPointMathLib
Replace the current sqrt()
implementation with Solady's version
This change will significantly reduce gas costs while maintaining calculation accuracy and has the added benefit of using battle-tested code.
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.