polywrap / wrap-cli

Used to create, build, and integrate wraps.
https://polywrap.io
MIT License
169 stars 54 forks source link

Base Schema Types: BigDecimal, BigNumber, Fraction #558

Open krisbitney opened 2 years ago

krisbitney commented 2 years ago

dApps commonly require math with large numbers. We currently have the BigInt base schema type for math with large integers, but we do not have a base schema type to facilitate arbitrary-precision math with large decimal numbers.

BigNumber and BigDecimal classes are desirable when precision matters, such as for chained operations wherein rounding errors could accrue with each operation. It is sometimes possible to use a Fraction class as a workaround. Fractions may be especially useful when it is necessary to emulate on-chain arithmetic where decimal numbers are not supported.

A BigNumber base schema type should be able to handle arbitrary-precision math with large decimal or integer numbers, including support for algebraic operations like exponentiation and square root. Other desirable operations include those found in standard Math libraries, such as ceil, floor and log operations. The type should also be capable of returning formatted string representations with functions that support printing to a fixed number of decimal places or a fixed number of significant digits. Importantly, BigNumber operations should be based on performant algorithms.

It would be desirable (but not necessary) for BigNumber, Fraction, and BigInt classes to have similar syntax and to have means for typecasting between them. For example, a BigNumber class might have a toBigInt() function and BigInt might have toBigNumber().

Example Fraction implementations Uniswap SDK AssemblyScript port: https://github.com/polywrap/integrations/blob/main/uniswapv3/wrapper/src/utils/Fraction.ts Python standard library: https://docs.python.org/3/library/fractions.html

Example BigDecimal and BigNumber implementations in JavaScript bn.js: https://github.com/indutny/bn.js/ bignumber.js: https://github.com/MikeMcl/bignumber.js big.js: https://github.com/MikeMcl/big.js/ decimal.js: https://github.com/MikeMcl/decimal.js/ js-big-decimal: https://github.com/royNiladri/js-big-decimal

Example BigDecimal and BigNumber implementations in AssemblyScript as-big: https://github.com/ttulka/as-big as-bigfloat: https://github.com/polywrap/as-bigfloat/blob/main/assembly/BigFloat.ts

Tasks

krisbitney commented 2 years ago

BigNumber is complete. See https://github.com/polywrap/monorepo/pull/697

Fraction type is in progress. It needs to be made generic and implemented as a generic schema type.