Overview

v3.1.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.1.0.

2,876 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

  • Mathexp, ln, sqrt, pow, stdNormCDF, erf 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.

Modules