Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Math

Rust's primitive number types are insufficient for smart contract use cases, for three main reasons:

  1. Rust only provides up to 128-bit integers, while developers often have to deal with 256- or even 512-bit integers. For example, Ethereum uses 256-bit integers to store ETH and ERC-20 balances, so if a chain has bridged assets from Ethereum, their amounts may need to be expressed in 256-bit integers. If the amounts of two such asset are to be multiplied together (which is common in AMMs), 512-bit integers may be necessary.

  2. Rust does not provide fixed-point decimal types, which are commonly used in financial applications (we don't want to deal with precision issues with floating-point numbers such as 0.1 + 0.2 = 0.30000000000000004). Additionally, there are concerns over floating-point non-determinism, hence it's often disabled in blockchains.

  3. Grug uses JSON encoding for data that go in or out of contracts. However, JSON specification (RFC 7159) only guarantees support for integer numbers up to (2**53)-1. Any number type that may go beyond this limit needs to be serialized to JSON strings instead.

Numbers in Grug

Grug provides a number of number types for use in smart contracts. They are built with the following two primitive types:

typedescription
Int<U>integer
Dec<U>fixed-point decimal

It is, however, not recommended to use these types directly. Instead, Grug exports the following type alises:

aliastypedescription
Uint64Int<u64>64-bit unsigned integer
Uint128Int<u128>128-bit unsigned integer
Uint256Int<U256>256-bit unsigned integer
Uint512Int<U512>512-bit unsigned integer
Int64Int<i64>>64-bit signed integer
Int128Int<i128>>128-bit signed integer
Int256Int<I256>>256-bit signed integer
Int512Int<I512>>512-bit signed integer
Udec128Dec<i128>128-bit unsigned fixed-point number with 18 decimal places
Udec256Dec<I256>256-bit unsigned fixed-point number with 18 decimal places
Dec128Dec<i128>>128-bit signed fixed-point number with 18 decimal places
Dec256Dec<I256>>256-bit signed fixed-point number with 18 decimal places

where {U,I}{256,512} are from the bnum library.

Traits

Uint64Uint128Uint256Uint512Int64Int128Int256Int512Udec128Udec256Dec128Dec256
Bytable
Decimal
FixedPoint
Fraction
Inner
Integer
IntoDec
IntoInt
IsZero
MultiplyFraction
MultiplyRatio
NextNumber
Number
NumberConst
PrevNumber
Sign
Signed
Unsigned