DeFiMath v3.6.0: sqrt and cbrt handle full uint256
Two changes:
sqrtandcbrtaccept the fulluint256domain. Both errors and their upper-bound constants (SqrtUpperBoundError,CbrtUpperBoundError,SQRT_UPPER_BOUND,CBRT_UPPER_BOUND) are removed. Any input in[0, uint256.max]returns a valid FP18 result.powoverflow bugfix. The internala · ln(x)multiplication insideuncheckedcould silently overflowint256for adversarial exponents (|a| ≳ 3.25 × 10⁵⁶), lettingpowreturn plausible-looking garbage. NewMAX_POW_EXPONENT = 1e54bound with a typedPowExponentOutOfBoundsErrorrevert — well below the overflow point and ~18 orders of magnitude above any realistic financial exponent (real value 10³⁶).
For a deep dive into the new sqrt — the CLZ seed, the five Newton iterations, and how it lands at 197 gas — see the companion post: How I wrote a fixed-point Solidity sqrt that runs in 197 gas.
Gas changes
Beyond sqrt and cbrt, sqrtTime also picked up the new CLZ-derived seed
algorithm — its savings cascade through every Black-Scholes function that
computes an annualized time term. expm1 and log1p shed a few gas each,
which propagates into continuousToDiscrete and discreteToContinuous in
the Rates module. The sqrt savings compound into every statistics function
that calls it — geometricMean, stdDev, historicalVolatility,
sharpeRatio. Options and Binary options both benefit — every function that
depends on sqrtTime (all Greeks, IV, both pricing functions) drops ~15 gas.
pow is the only row that went up: the new MAX_POW_EXPONENT check costs
~40 gas — the price of catching the silent overflow bug.
| Function | v3.5.0 gas | v3.6.0 gas | Saved |
|---|---|---|---|
| sqrt | 245 | 197 | −48 (−20%) |
| cbrt | 368 | 340 | −28 (−8%) |
| sqrtTime | 184 | 163 | −21 (−11%) |
| callOptionPrice | 2,729 | 2,708 | −21 (−0.8%) |
| binaryCallPrice | 2,018 | 1,997 | −21 (−1%) |
| pow | 763 | 803 | +40 (safety) |
| expm1 | 415 | 407 | −8 |
| log1p | 487 | 476 | −11 |
| continuousToDiscrete | 507 | 491 | −16 |
| discreteToContinuous | 589 | 574 | −15 |
| geometricMean | 330 | 284 | −46 |
| stdDev (N=100) | 49,811 | 49,765 | −46 |
| historicalVolatility (N=100) | 86,595 | 86,500 | −95 |
| sharpeRatio (N=100) | 86,733 | 86,638 | −95 |
API removed
SqrtUpperBoundError()andCbrtUpperBoundError()errors deleted.SQRT_UPPER_BOUNDandCBRT_UPPER_BOUNDconstants deleted.- New:
PowExponentOutOfBoundsError()andMAX_POW_EXPONENTfor the pow bugfix.
Callers who caught SqrtUpperBoundError or CbrtUpperBoundError need to
remove those handlers — those code paths no longer exist. Callers who pass
finite exponents to pow see no behavior change.
Get it
npm install defimath-lib
- Release notes: github.com/MerkleBlue/defimath/releases/tag/v3.6.0
- Package: npmjs.com/package/defimath-lib