• Stars
    star
    118
  • Rank 299,923 (Top 6 %)
  • Language
    Solidity
  • License
    GNU Affero Genera...
  • Created over 2 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Math library written in solidity for statistical function approximations like the Normal Cumulative Distribution Function.

Beta

This library is in beta. It's not ready for production.

Twitter Badge

SolStat

SolStat is a Math library written in solidity for statistical function approximations. The library is composed of two core libraries; Gaussian.sol, and Invariant.sol. We will go over each of these libraries and their testing suites. We at Primitive use these libraries to support development with RMM-01s unique trading function, which utilizes the cumulative distribution function (CDF) of the normal distribution denoted by the greek capital letter Phi($\Phi$) in the literature [1,2]. You may recognize the normal or Gaussian distribution as the bell curve. This distribution is significant in modeling real-valued random numbers of unknown distributions. Within the RMM-01 trading function and options pricing, the CDF is used to model random price movement of a Markov process. Since price paths are commonly modeled with markovian proccesses, we believe that the greater community will find value in this library.

How to use

Requirements: forge, node >=v16.0.0

yarn install
forge install
yarn build
forge test

To compute values using the gaussian.js library, you can use this commmand in the cli:

yarn cli --cdf {value}
yarn cli --pdf {value}
yarn cli --ppf {value}

Irrational Functions

The primary reason for utilizing these approximation algorithms is that computers have trouble expressing irrational functions. This is because irrational numbers have an infinite number of decimals. Some examples of irrational numbers are $\pi$ and $\sqrt(2)$. This only becomes a challenge when we try to compute these numbers. This is because computers don't have an infinite amount of memory. Thus mathematicians and computer scientists have developed a variety of approximation algorithms to achieve varying degrees of speed and accuracy when approximating these irrational functions. These algorithms are commonly iterative and achieve greater accuracy with more iterations.

Computational Constraints

In classical computing, our computational resources have become abundant, allowing us the liberty to iterate these algorithms to achieve our desired accuracy. However, the Ethereum Virtual Machine (EVM) has a necessary monetary cost of computation. This computational environment has monetarily motivated developers to find efficient algorithms and hacks to reduce their applications' computational overhead (and thus the cost of computation).

Gaussian.sol

This contract implements a number of functions important to the gaussian distributions. Importantly all these implementations are only for a mean $\mu = 0$ and variance $\sigma = 1$. These implementations are based on the Numerical Recipes textbook and its C implementation. Numerical Recipes cites the original text by Abramowitz and Stegun, "Handbook of Mathematical Functions," which should be read to understand these unique functions and the implications of their numerical approximations. This implementation was also inspired by the javascript Gausian library, which implements the same algorithm.

Cumulative Distribution Function

The implementation of the CDF aproximation algorithm takes in a random variable $x$ as a single parameter. The function depends on a special helper functions known as the error function erf. The error functionโ€™s identity is erfc(-x) = 2 - erfc(x) and has a small collection of unique properties:

erfc(-infinity) = 2

erfc(0) = 1

erfc(infinity) = 0

The reference implementation for the error function is on p221 of Numerical Recipes in section C 2e. A helpful resource is this wolfram notebook.

Probability Density Function

The library also supports an approximation of the Probability Density Function(PPF) which is mathematically interpeted as $Z(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{\frac{-(x - \mu)^2}{2\sigma^2}}$. This implementation has a maximum error bound of of $1.2e-7$ and can be refrenced in this wofram notebook.

Percent Point Function / Quantile Function

Furthermore we implemented aproximation algorithms for the Percent Point Function(PPF) sometimes known as the inverse CDF or the quantile function. The function is mathmatically defined as $D(x) = \mu - \sigma\sqrt{2}(ierfc(2x))$, has a maximum error of 1.2e-7, and depends on the inverse error function ierf which satisfies ierfc(erfc(x)) = erfc(ierfc(x)). The invers error function, defined as ierfc(1 - x) = ierf(x), has a domain of in the interval $0 < x < 2$ and has some unique properties:

ierfc(0) = infinity

ierfc(1) = 0

ierfc(2) = - infinity

Invariant.sol

Invariant.sol is a contract used to compute the invariant of the RMM-01 trading function such that we compute $y$ in $y = K\Phi(\Phi^{โปยน}(1-x) - \sigma\sqrt(\tau)) + k$. Notice how we need to compute the normal CDF of a quantity. For a more detailed perspective on the trading function, please see the whitepaper. This is an example of how we have used this library for our research, development, and testing of RMM-01. The function reverts if $x$ is greater than one and simplifies to $K(1+x) + k$ when $\tau$ is zero (at expiry). The function takes in five parameters R_x: The reserves of token $x$ per unit of liquidity, always within the bounds of $[0,1]$. stk: The strike price of the pool. vol: the implied volatility of the pool denoted by the lowercase greek letter sigma in finance literature. tau: The time until the pool expires. Once expired, there can be no swaps. inv: The current invariant given R_x. The function then returns the quantity of token y per unit of liquidity denoted R_y, which is always within the bounds of $[0, stk]$. This is a clear example of how one would use this library.

Differential Testing with Foundry

We leveraged foundry's support of differential testing for this library. Differential testing is a popular technique that seeds inputs to different implementations of the same application and detects differences in their execution. Differential testing is an excellent complement to traditional software testing as it is well suited to detect semantic errors. This library used differential testing against the javascript gaussian library to detect anomalies and varying bugs. This helped us to be confident in the performance and implementation of the library.

[1]: Replicating Market Makers

[2]: Replicating Portfolios: Contstructing Permissionless Derivatives

More Repositories

1

arbiter

A blazing-fast Ethereum sandbox that lets developers orchestrate event-driven simulations.
Rust
669
star
2

hardhat-marmite

๐Ÿฅ˜ Hassle-free Hardhat plugin to compare gas cost among different Solidity code snippets.
TypeScript
196
star
3

primitive-dodoc

โ˜„๏ธ Zero-config Hardhat plugin to generate documentation for all your Solidity contracts.
TypeScript
135
star
4

rmm-core

Primitive Replicating Market Maker smart contracts
Solidity
131
star
5

portfolio

Portfolio is an automated market making protocol for implementing custom strategies at the lowest cost possible.
Solidity
113
star
6

hardhat-foundry

Forkable hardhat & foundry template for thorough evm development.
Solidity
87
star
7

soulbound

Implementation of a non-transferrable NFT using non-financial incentivization.
Solidity
85
star
8

rmms-py

Python simulator to test implementation of the RMMS paper results.
Python
55
star
9

RMM01-Simulations

RMM-01 Simulations
Python
50
star
10

arbiter-template

Minimal template for simulating contracts with arbiter.
Rust
45
star
11

v1-contracts

Primitive protocol solidity contracts.
Solidity
43
star
12

rmm-manager

Manager and Routing smart contracts for Primitive RMM
Solidity
34
star
13

univ3-kit

An open simulation for Uniswap V3 contracts
Rust
34
star
14

sybil-detection

Python
31
star
15

open-research-questions

This is a collection of open research questions in the DeFi mechanism design space pertinent to the Primitive R&D Team. This serves as a public forum and is open to discussion and changes amongst the broader DeFi research and development community.
26
star
16

excalibur

Excalibur
Rust
21
star
17

rmm-math

Typescript math library for cumulative distributions, black-scholes, and the RMM trading function.
TypeScript
21
star
18

proto-sim-portfolio

Prototype risk modeling simulation for Portfolio using Arbiter.
Rust
20
star
19

DFMM

Smart contracts of the DFMM protocol
Rust
18
star
20

rmm-ethers

Library for interacting with RMM protocol through ethers.js.
TypeScript
15
star
21

aika

Discrete event simulator built in Rust ๐Ÿฆ€
Rust
13
star
22

Topological-Data-Analysis

This repository is for topologic and geometric data analysis.
Python
13
star
23

m3-rs

Simple rust interface to get derived analytical information of algorithmic market making models (M3).
Rust
12
star
24

portfolio_simulations

Moving to the new Arbiter framework to test Portfolio.
Rust
10
star
25

rmm-sdk

Typescript based entity classes and transaction builders for the rmm-core and rmm-periphery smart contracts.
TypeScript
10
star
26

rmm-examples

Solidity
10
star
27

portfolio-rs

SDK for the Portfolio protocol written in rust.
Rust
9
star
28

DisputeGameSimulations

Rust
9
star
29

v1-connectors

Smart contracts that connect Primitive V1 to other Ethereum protocols and standards.
Solidity
9
star
30

CFMMRouter.py

Python implementation of CFMMRouter.jl
Python
9
star
31

visualization-rs

This is a collection of math and plotting tools for us to use for visualizing data.
Rust
8
star
32

rmm-docs

Primitive and RMM Protocol Documentation - Crypto Derivatives without Counterparties
JavaScript
7
star
33

fvm.ts

TypeScript
4
star
34

pool-analytics

Jupyter Notebook
4
star
35

v1-interface

An open-source interface for the Primitive protocol.
TypeScript
4
star
36

dagger

A lightweight interface for the DFMM smart contracts
TypeScript
4
star
37

Research

Research papers and repository directory
3
star
38

v1-sdk

An SDK for the Primitive Protocol.
TypeScript
3
star
39

portfolio-ts

Minimal toolkit for building TypeScript based applications for Portfolio by Primitive.
TypeScript
3
star
40

Arbitrum-Transaction-Data-Analysis

This repository is for transaction data analysis on the the Arbitrum Network
3
star
41

amm-auction

Solidity
3
star
42

portfolio-examples-solidity

Solidity
3
star
43

arbmod

git submodule for arbiter
Solidity
3
star
44

v1-subgraph

A graph for the Primitive Protocol.
TypeScript
3
star
45

dfmm-indexer

Indexer for the DFMM protocol
TypeScript
3
star
46

security

All security reports for Primitive products and protocols.
2
star
47

discord-bot

TypeScript
2
star
48

rmm-core-dapptools

Rmm protocol core contracts in dapptools testing environment.
Solidity
2
star
49

arbiter-dispute-game

TeX
2
star
50

brand

Primitive's brand assets.
2
star
51

v1-amm-spec

Derivative focused AMM for the Primitive Protocol.
Solidity
2
star
52

arbiter-portfolio-sim

Migration from old middleware to new.
Solidity
1
star
53

rmm

Solidity
1
star
54

nugu

Solidity
1
star
55

fee-generation-py

Python
1
star