Jump to content

[ANN] Introducing DefiMath: gas-optimized Math & Derivatives Solidity Library


TokenMint

Recommended Posts

Posted

Hi everyone,

I've been building DeFiMath over the past several months — an open-source Solidity library focused on gas-optimized math and DeFi primitives. v3.1.0 just shipped to npm, fully tested, fully benchmarked against every comparable on-chain library I could find.

What it is

A pure-Solidity library covering six modules: math primitives, options pricing, binary options, futures, interest rates, and portfolio statistics. MIT-licensed, no runtime dependencies, ~16 KB published.

Why I built it

On-chain derivatives, implied-volatility solving on every quote, vault risk fees, real-time options pricing — these all need fast and precise math. The existing libraries (PRBMath, ABDK, Solady, SolStat) either don't cover derivatives at all, or are 5–30× more expensive per call. I wanted to make those use cases economically viable in a single transaction.

Headline gas numbers (lower is better)

  • callOptionPrice (Black-Scholes): 2,876 gas — 4.6× cheaper than Derivexyz (13,360), 31× cheaper than Dopex (88,969)
  • binaryCallPrice: 2,092 gas — 7.8× cheaper than Haptic (16,218)
  • sqrt: 245 gas vs Solady 341, PRBMath 959, ABDK 808
  • cbrt: 368 gas vs Solady's cbrtWad 550
  • ln: 375 gas vs Solady 518, PRBMath 6,901, ABDK 12,695
  • stdNormCDF (Φ(x)): 731 gas vs SolStat 2,794
  • IV solver included, converges in 5–10 Newton-Raphson iterations
  • Full Greeks (delta, gamma, theta, vega) at 1.5–3.5K gas each

Key tech

  • Uses the new clz opcode (EIP-7939, EVM Osaka) for ~30% gas savings on sqrt, cbrt, ln — savings cascade upward through every function that uses them (option pricing is ~10% cheaper as a side effect).
  • 100% test branch coverage
  • Validated against simple-statistics, black-scholes, greeks, math-erf JS reference libraries

Requirements

  • Solidity ^0.8.31
  • evmVersion: "osaka" (Fusaka)

Install

 

npm install defimath-lib

Quick example

 

import "defimath-lib/contracts/derivatives/Options.sol";

 

uint256 price = DeFiMathOptions.callOptionPrice(

    1000e18,    // spot

    980e18,     // strike

    60 days,    // time to expiration

    0.6e18,     // 60% volatility

    0.05e18     // 5% risk-free rate

);

Links

Happy to answer questions about implementation choices, benchmark methodology, or how to integrate it into specific use cases. All benchmark numbers above are reproducible from defimath-compare — just npm install && npx hardhat test.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Topics

    • Unichain: проходим тестнет L2 от Uniswap - blog.uniswap.org/introducing-unichain

      Всем известна новость о том, что Uniswap планирует запуск собственной сети второго уровня Unichain. Рабочую сеть планируют запустить к концу года, а сейчас проходит тестнет. Поскольку это известный проект и он может привлечь большое количество охотников за дропами, нужно понимать, что отбор может быть тщательный, поэтому задания нужно выполнять основательно.   Как проходить тестнет от Unichain?   1. Нам нужны тестовые монеты Sepolia, которые нужно получить в кранах. Кра

      in Раздачи монет

    • Stable Bank [ANN] SBUSD Stable Bank. Стейблкоин, который можно майнить PoS (название сайта скрывают)

      Доброго времени! Предлагаю ознакомится с анонсом стартующего в ближайшие 30-45 дней проекта. У проекта громкое название «Stable Bank”. Но это не значит, что проект не стоит вашего внимания. Итак, по порядку. Миссия проекта, это ввести в оборот такое понятие как майнинг стабильной монеты. На данный момент, ни одна стабильная монета не предлагает майнинг своих монет (во всяком случае, напрямую, на своем блокчейне.) Что мы предлагаем: 1. Обеспечение курса монеты. Мы ре

      in Флейм

    • [ANN] $ZCOIN - Crypto URL shortener with its own token

      ZCoin — это новый криптовалютный сокращатель URL-адресов с собственным токеном — ZCoin. ZCoin позволяет сокращать длинные ссылки из Telegram, YouTube, TikTok, блогов и сайтов. Просто вставьте длинный URL и нажмите кнопку «Сократить URL». Первые 1000 пользователей получат бонус за вход в размере 10 000 ZCoin! Как это работает?   Сократите ссылку в мини-приложении Скопируйте сокращенный URL-адрес и поделитесь им на сайтах, форумах, в чатах и электронных письмах

      in Флейм

    • [ANN] Ymakanic Labs & Y-Chain | Официальная тема

      Официальный сайт | Исходный код     В Н И М А Н И Е ! ПРОЕКТ ЗАКРЫТ ПО РЕШЕНИЮ ГЛАВНОГО РАЗРАБОТЧИКА: https://t.me/ymakanic/356.   Описание:   Команда:   Токеномика:   Кошелек:   Соцсети:   Биржи:   Инфраструктура:   Пресса о Y-Chain и YKC:      

      in PoS криптовалюты

    • [ANN] Block Sailor ICO - Announces the start of the $BLOCK token presale.

      A innovative BEP20 coin called Block Sailor (BLOCK) seeks to make investing in the cryptocurrency market safer and more profitable. BLOCK stands out as the smartest token in the world thanks to its cutting-edge features and OpenAI-powered advanced AI algorithm. It offers original answers to the problems that other cryptocurrencies frequently encounter.   First, for a minimum investment of $1,000, BLOCK offers its holders a weekly interest rate of 2% in BNB. Even after the presale, this

      in ICO, IEO, STO, IFO, IAO

×
×
  • Create New...