Fixed Point Math

Fixed point math is important for DeFi applications that must perform bookkeeping with many repeated divisions while maintaining a reasonable bound on rounding errors. Ethereum has struggled with this, with several immature Solidity libraries filling the void.

One exciting Ethereum application that uses fixed point math is Balancer, an automated market maker that we hope to port to Tezos. Balancer works by self-balancing pools of tokens by computing a weighted geometric mean. This is fairly simple. The difficulty comes in bounding rounding error while maintaining gas efficiency and Balancer’s main innovation is some fancy math to do this using spline interpolation. This is impossible to implement in Michelson because it depends on bit length and Michelson numbers are arbitrary-precision. This is also why Balancer restricts pools to eight tokens.

One could use Michelson integers to represent rationals, but in addition to the repeated calls to GCD the bit length would quickly grow so large as to make the gas usage infeasible. A better solution is to add support for a native library with limited-precision fixed point numbers: libfixmath. This would allow a Tezos version of Balancer to both be much simpler and more performant than the Ethereum one as well as allowing an unlimited number of tokens per pool.

A fix16 type would represent Q16.16 numbers. Most operations would be covered under standard arithmetic, except would return fix16 option to handle overflow and underflow. Additional instructions one would want include exponentiation and some way to compute logarithms, which is included in libfixmath using Newton’s method and an implementation of the exponential function with Taylor series approximation. Rather than computing logarithms directly, it would be sufficient for Balancer to have a function that takes a list of pairs and computes a weighted version of the log-average formulation of the geometric mean.

I’ve coded up a proof of concept here: https://gitlab.com/labnet/tezos/-/tree/libfixmath. Have feedback? Working on a contract that could use fixed point math? I’d love to hear from you.

7 Likes