defimath-lib
v1.0.3
Published
High-performance, gas-efficient Solidity library for DeFi math and derivatives
Downloads
343
Maintainers
Readme
DeFiMath 
DeFiMath is a high-performance, open-source Solidity library designed for Ethereum smart contracts. It provides optimized, gas-efficient implementations of core DeFi primitives and mathematical utilities—built with precision and performance in mind.
Table of Contents
Features
| | | |---|---| | DeFi Primitives | Core building blocks for advanced financial protocols — options, futures, and other on-chain derivatives. | | High-Precision Math | Accurate fixed-point arithmetic essential for financial calculations, with sub-1e-10 absolute error. | | Gas Optimized | Option pricing at ~2,900 gas — orders of magnitude cheaper than comparable implementations. | | Fully Tested | Comprehensive unit tests with verified accuracy against trusted JavaScript reference implementations. | | Modular & Extensible | Import only what you need; extend seamlessly to fit your protocol's requirements. | | Open Source | MIT-licensed — transparent, auditable, and free to use or build upon. |
Installation
Install via npm:
npm install defimath-libRequires Solidity ^0.8.30.
Usage
Import only the modules you need:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.30;
import "defimath/derivatives/Options.sol";All values use 18-decimal fixed-point format (1e18 = 1.0):
| Parameter | Type | Unit | Example |
| :--------------- | :-------- | :------------- | :------------------------ |
| spot | uint128 | price × 1e18 | 1000e18 = $1,000 |
| strike | uint128 | price × 1e18 | 1100e18 = $1,100 |
| timeToExpirySec| uint32 | seconds | 2592000 = 30 days |
| volatility | uint64 | ratio × 1e18 | 0.8e18 = 80% IV |
| rate | uint64 | ratio × 1e18 | 0.05e18 = 5% risk-free |
Inputs outside the supported ranges revert with descriptive errors (e.g., StrikeUpperBoundError, TimeToExpiryUpperBoundError).
contract OptionsExchange {
function getQuote(
uint128 spot, // e.g. 1000e18 for $1,000
uint128 strike, // e.g. 1100e18 for $1,100
uint32 timeToExpirySec, // e.g. 2592000 for 30 days
uint64 volatility, // e.g. 0.8e18 for 80% IV
uint64 rate // e.g. 0.05e18 for 5% risk-free rate
) external pure returns (uint256 callPrice, uint256 putPrice) {
callPrice = DeFiMathOptions.getCallOptionPrice(spot, strike, timeToExpirySec, volatility, rate);
putPrice = DeFiMathOptions.getPutOptionPrice(spot, strike, timeToExpirySec, volatility, rate);
}
}Derivatives
Option Pricing using Black-Scholes
The implementation is based on the original Black-Scholes formula, which is a mathematical model used to calculate the theoretical price of options. The formula is widely used in the financial industry for pricing European-style options.
The Black-Scholes formula is given by:
C = S N(d_1) - K e^{-rT} N(d_2)P = K e^{-rT} N(-d_2) - S N(-d_1)where $C$ is the call option price, $P$ is the put option price, $S$ is the current asset price, $K$ is the strike price, $T$ is the time to expiration (in years), $r$ is the annualized risk-free interest rate, $N(d)$ is the cumulative distribution function of the standard normal distribution, and $d_1$ and $d_2$ are given by:
d_1 = \frac{\ln(S/K) + (r + \sigma^2/2)T}{\sigma \sqrt{T}}, d_2 = d_1 - \sigma \sqrt{T}where $\sigma$ is the volatility of the underlying asset. Learn more about the Black-Scholes model on Wikipedia.
Implied Volatility
Given an observed market price, DeFiMath can solve for the implied volatility — the value of $\sigma$ that makes the Black-Scholes formula match the market price. Implementation uses Newton-Raphson iteration with vega as the derivative:
\sigma_{n+1} = \sigma_n - \frac{BS(\sigma_n) - P_{market}}{\nu(\sigma_n)}where $\nu$ is per-unit-vol vega ($S \cdot \phi(d_1) \cdot \sqrt{T}$). Typical convergence is 4–6 iterations. The market price must lie within the no-arbitrage band $[\max(S - Ke^{-rT}, 0), S]$ for calls (or the analogous put bounds), or the call reverts.
Performance
The maximum absolute error for call or put option pricing is approximately 1.2e-10 at a $1,000 spot price — offering near-perfect precision.
Option pricing computations cost roughly 2,900 gas on average — orders of magnitude cheaper than a typical Uniswap V3 swap (~110,000 gas).
The following table compares gas efficiency of DeFiMath with other implementations over a typical range of parameters.
| Function | DeFiMath | Derivexyz | Premia | Party1983 | Dopex | | :------- | -------: | --------: | -----: | --------: | -----: | | call | 2927 | 13404 | 20831 | 36243 | 89728 | | put | 2941 | 13407 | 22117 | 36424 | 89051 | | delta | 1846 | 8671 | - | 25172 | - | | gamma | 1551 | - | - | - | - | | theta | 3499 | - | - | - | - | | vega | 1491 | 7526 | - | - | - | | IV | 13282 | - | - | - | - |
The table below compares the maximum relative error against a trusted JavaScript reference implementation.
| Function | DeFiMath | Derivexyz | Premia | Party1983 | Dopex | | :------- | -------: | --------: | -----: | --------: | ----: | | call | 5.6e-12 | 6.8e-13 | 1.7e-1 | 3.8e+1 | - | | put | 5.4e-12 | 6.5e-13 | 1.7e-1 | 9.9e+1 | - | | delta | 6.9e-15 | 6.7e-16 | - | 9.2e-1 | - | | gamma | 9.1e-17 | - | - | - | - | | theta | 3.7e-14 | - | - | - | - | | vega | 4.8e-14 | 1.1e-15 | - | - | - |
Limits
The following limitations apply to all option functions. Inputs outside these ranges revert with a descriptive error.
- Strike price: 0.2x to 5x the spot price (e.g., $200–$5,000 for a $1,000 spot).
- Time to expiration: up to 2 years.
- Volatility: up to 1800%.
- Risk-free rate: up to 400%.
Binary Options (Cash-or-Nothing)
DeFiMath includes a gas-efficient binary (digital) option pricing library. A binary cash-or-nothing call pays 1 unit if the underlying expires above the strike, and 0 otherwise; the put pays 1 unit if it expires below the strike. To price options with an arbitrary cash payout Q, simply multiply the result by Q.
import "defimath/derivatives/Binary.sol";The closed-form Black-Scholes prices for unit-payout cash-or-nothing binary options are:
C = e^{-rT} \cdot N(d_2)P = e^{-rT} \cdot N(-d_2)where $d_2$ is the same as in the European Black-Scholes model. The corresponding Delta is:
\Delta_{call} = \frac{e^{-rT} \phi(d_2)}{S \sigma \sqrt{T}}, \quad \Delta_{put} = -\Delta_{call}where $\phi$ is the standard normal probability density function. Gamma is:
\Gamma_{call} = -\frac{e^{-rT} \phi(d_2) \cdot d_1}{S^2 \sigma^2 T}, \quad \Gamma_{put} = -\Gamma_{call}Note that binary gamma is signed: it changes sign at ATM ($d_1 = 0$). Theta (per day) is:
\Theta_{call} = \frac{1}{365}\left[r \cdot e^{-rT} N(d_2) + e^{-rT} \phi(d_2) \left(\frac{d_1}{2T} - \frac{r}{\sigma\sqrt{T}}\right)\right]\Theta_{put} = \frac{1}{365}\left[r \cdot e^{-rT} N(-d_2) - e^{-rT} \phi(d_2) \left(\frac{d_1}{2T} - \frac{r}{\sigma\sqrt{T}}\right)\right]Vega (per 1% vol move) is also signed and changes sign at the strike:
\nu_{call} = -\frac{1}{100} \cdot \frac{e^{-rT} \phi(d_2) \cdot d_1}{\sigma}, \quad \nu_{put} = -\nu_{call}Learn more about binary options on Wikipedia.
Performance
Binary option pricing computations cost roughly 2,100 gas on average — over an order of magnitude cheaper than comparable on-chain implementations.
The following table compares gas efficiency of DeFiMath with other implementations over a typical range of parameters.
| Function | DeFiMath | Haptic | | :------- | -------: | -----: | | call | 2142 | 16272 | | put | 2147 | 16275 | | delta | 1878 | - | | gamma | 2022 | - | | theta | 3556 | - | | vega | 1970 | - |
The table below compares the maximum absolute error against a trusted JavaScript reference implementation.
| Function | DeFiMath | Haptic | | :------- | -------: | ------: | | call | 5.7e-15 | 1.3e-15 | | put | 5.4e-15 | 1.2e-15 | | delta | 1.2e-16 | - | | gamma | 1.0e-15 | - | | theta | 8.2e-16 | - | | vega | 2.7e-16 | - |
Limits
The same input limits apply as for European options (strike, time, volatility, rate). Inputs outside these ranges revert with descriptive errors.
Futures
DeFiMath includes a gas-efficient futures pricing library using continuous compounding:
import "defimath/derivatives/Futures.sol";Math
DeFiMath includes a low-level math library (DeFiMath) with optimized fixed-point implementations of common mathematical functions. All inputs and outputs use 18-decimal fixed-point format (1e18 = 1.0). Available functions: exp, ln, log2, log10, pow, sqrt, stdNormCDF, erf.
import "defimath/math/Math.sol";The following table compares gas efficiency of DeFiMath with other math libraries over a typical range of parameters.
| Function | DeFiMath | PRBMath | ABDKQuad | Solady | SolStat | | :--------- | -------: | ------: | -------: | -----: | ------: | | exp | 335 | 2822 | 5857 | 372 | - | | ln | 508 | 6962 | 12717 | 519 | - | | log2 | 524 | 6889 | 12276 | - | - | | log10 | 524 | 8688 | - | - | - | | pow | 885 | 9857 | - | 978 | - | | sqrt | 344 | 960* | 810 | 341* | - | | stdNormCDF | 732 | - | - | - | 2799 | | erf | 686 | - | - | - | 1735 |
* not a fixed-point function
The table below compares the maximum relative error against a trusted JavaScript reference implementation.
| Function | DeFiMath | PRBMath | ABDKQuad | Solady | SolStat | | :--------- | -------: | -------: | -------: | -------: | ------: | | exp | 5.1e-12 | 1.9e-12 | 1.9e-12 | 1.9e-12 | - | | ln | 1.5e-12 | 1.3e-12 | 1.6e-12 | 1.6e-12 | - | | log2 | 1.5e-12 | 1.3e-12 | 1.6e-12 | - | - | | log10 | 1.4e-12 | 1.3e-12 | - | - | - | | pow | 5.2e-12 | 6.1e-14 | - | 6.1e-14 | - | | sqrt | 2.8e-14 | 2.8e-14 | 2.8e-14 | 2.8e-14 | - | | stdNormCDF | 4.6e-13 | - | - | - | 3.2e-6 | | erf | 7.4e-13 | - | - | - | 5.7e-6 |
Credits
The following libraries were used for comparison:
License
This project is released under the MIT License.
