DeFiMath is a pure-Solidity library of gas-optimized DeFi math primitives — 40+ functions spanning six modules: math, options, binary options, futures, rates, and statistics. MIT-licensed, no runtime dependencies.
Latest version of DeFiMath is 3.3.0.
2,729 gas
Black-Scholes option pricing
< 1e-12
Max abs. error on options pricing
100%
Test coverage · Solidity 0.8.35
0
Runtime dependencies
DeFiMath is published on npm as defimath-lib.
npm install defimath-lib
Compiler requirements
^0.8.31osaka (Fusaka)The library uses the clz Yul builtin (Solidity 0.8.31+) which emits the CLZ opcode introduced in Osaka — both the compiler version and EVM target are hard requirements.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.31;
import "defimath-lib/contracts/derivatives/Options.sol";
contract OptionsExchange {
function quote(
uint128 spot, uint128 strike, uint32 timeToExp,
uint64 vol, uint64 rate
) external pure returns (uint256 callPx, uint256 putPx) {
callPx = DeFiMathOptions.callOptionPrice(spot, strike, timeToExp, vol, rate);
putPx = DeFiMathOptions.putOptionPrice(spot, strike, timeToExp, vol, rate);
}
}All values use 18-decimal fixed-point (1e18 = 1.0). Time is in seconds. See module docs for full parameter conventions.
Every function is benchmarked against existing on-chain implementations. A representative comparison:
| Function | DeFiMath | Next best | Multiple |
|---|---|---|---|
| callOptionPrice | 2,729 | 13,360 (Derivexyz) | 4.9× |
| putOptionPrice | 2,739 | 13,363 (Derivexyz) | 4.9× |
| binaryCallPrice | 2,018 | 16,218 (Haptic) | 8.0× |
| delta | 1,724 | 8,621 (Derivexyz) | 5.0× |
| vega | 1,439 | 7,490 (Derivexyz) | 5.2× |
| ln | 375 | 518 (Solady) | 1.4× |
| sqrt | 245 | 341 (Solady) | 1.4× |
| cbrt | 368 | 550 (Solady) | 1.5× |
| stdNormCDF | 660 | 2,794 (SolStat) | 4.2× |
Full per-function tables in the defimath-compare README.
Low-level fixed-point primitives — exponential, logarithm, square root, power, standard normal CDF, error function, and more.
Black-Scholes pricing, full Greeks, and an iterative implied-volatility solver.
Cash-or-nothing call and put pricing with full Greeks.
Continuous-compounding futures price.
Compound interest, present value, log returns, YTM, IRR.
Mean, std dev, historical volatility, Sharpe, max drawdown, VaR, CVaR.