Overview

v3.3.0

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

What's inside

  • Math — exponential, logarithm, square root, power, standard normal CDF, error function, and more.
  • Options — Black-Scholes pricing, full Greeks (delta, gamma, theta, vega), and an iterative implied-volatility solver.
  • Binary options — cash-or-nothing call and put pricing with full Greeks.
  • Futures — continuous-compounding futures price.
  • Rates — compound interest, present value, log returns, APR↔APY, yield to maturity, IRR.
  • Statistics — mean, std dev, historical volatility, Sharpe ratio, max drawdown, VaR, CVaR.

Getting started

DeFiMath is published on npm as defimath-lib.

npm install defimath-lib

Compiler requirements

  • Solidity ^0.8.31
  • EVM target osaka (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.

Import and use

solidity
// 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.

Benchmarks

Every function is benchmarked against existing on-chain implementations. A representative comparison:

FunctionDeFiMathNext bestMultiple
callOptionPrice2,72913,360 (Derivexyz)4.9×
putOptionPrice2,73913,363 (Derivexyz)4.9×
binaryCallPrice2,01816,218 (Haptic)8.0×
delta1,7248,621 (Derivexyz)5.0×
vega1,4397,490 (Derivexyz)5.2×
ln375518 (Solady)1.4×
sqrt245341 (Solady)1.4×
cbrt368550 (Solady)1.5×
stdNormCDF6602,794 (SolStat)4.2×

Full per-function tables in the defimath-compare README.

Modules