Bin Math
Introduction
As you dive into the contracts, you will find a lot of bin math that can be terribly confusing. This section aims to resolve any confusion.
Bin Pricing
Even though price of any given asset can range from 0 to infinity, we are constrained to 256 bits and the largest number a u256
can hold is .
However, we also need to account for very small fractions, so we use 128.128 binary fixed-point numbers instead. These numbers use the left 128 bits for all numbers to the left of the decimal (i.e. the integers) and the right 128 bits for all numbers to the right of the decimal (i.e. the fractions). Thus the price range of every asset is now constrained to instead; the maximum of which is already very, very large and the minimum of which is already very, very small. Not quite 0 and infinity, but pretty much close to it.
Bin Limits
Now that we have the lower and upper bounds of price and we discretized the entire price curve into bins, how many bins could we possibly have?
Remember how the price of each bin was basically a geometric sequence . We now need to find the maximum integer for such that the entire value is less than the upper limit of price, .
In the whitepaper this is expressed as .
Taking the smallest possible value of which is 1 basis point, we can solve this as follows:
The above equation shows how many bins are needed to cover the entire range when is a positive integer, so we account for when it is negative by doubling it which equals to bins.
However, remember that can also be negative, so the smallest signed integer that can fit this many bins is an i24
. A quick sanity check shows that the largest integer for an i24
is which is still plenty large enough to hold the largest , which is .
So even though we previously said the upper and lower limits of price was , we can also define the limits using how many bins there could possibly be, which comes to . However, if we are to be extremely technical, the actual limits will be the minimum of the two.