UtilitiesMath

WAD Fixed-Point Math

High-precision decimal arithmetic

Source Code

Overview

The WAD library provides fixed-point decimal arithmetic for Soroban smart contracts with 18 decimal places of precision. It's designed specifically for DeFi applications where precise decimal calculations are critical, such as interest rates, exchange rates, and token pricing.

It is a fixed-point representation where:

  • 1.0 is represented as 1_000_000_000_000_000_000 (10^18)
  • 0.5 is represented as 500_000_000_000_000_000
  • 123.456 is represented as 123_456_000_000_000_000_000

This allows precise decimal arithmetic using only integer operations, avoiding the pitfalls of floating-point arithmetic in smart contracts.

For x * y / denominator on raw i128 or I256 values with an explicit rounding direction, see Fixed-Point Math.

Why WAD?

Shortcomings of Integers and Float Numbers

Native Integers (i128, u64):

  • No decimal support - 1/2 = 0 instead of 0.5
  • Loss of precision in financial calculations
  • Requires manual scaling for each operation

Floating-Point (f64, f32):

  • Non-deterministic behavior across platforms
  • Rounding errors that compound in financial calculations
  • Security vulnerabilities from precision loss

Why WAD is Better

  • High Precision: 18 decimals is more than sufficient for financial calculations
  • Deterministic: Same inputs always produce same outputs
  • Efficient: Uses native i128 arithmetic under the hood
  • Battle-Tested: Used in production by MakerDAO, Uniswap, Aave, and others
  • Ergonomic: Operator overloading makes code readable: a + b * c
  • Type Safe: NewType pattern prevents mixing scaled and unscaled values

Design Decisions

1. NewType Pattern

We use a NewType struct Wad(i128) instead of a type alias:

// Type alias
type Wad = i128;

// NewType
pub struct Wad(i128);

Benefits:

  • Type Safety: Cannot accidentally mix scaled and unscaled values
  • Operator Overloading: Can implement +, -, *, / with correct semantics
  • Semantic Clarity: Makes intent explicit in function signatures

2. No From/Into Traits

We deliberately DID NOT implement From<i128> or Into<i128> because it's ambiguous:

// What should this mean?
let wad = Wad::from(5);
// Is it 5.0 (scaled to 5 * 10^18)?
// Or 0.000000000000000005 (raw value 5)?

Instead, we provide explicit constructors:

  • Wad::from_integer(e, 5) - Creates 5.0 (scaled)
  • Wad::from_raw(5) - Creates raw value 5 (0.000000000000000005)

3. Truncation vs Rounding

All operations truncate toward zero rather than rounding:

Why truncation?

  • Predictable: Same behavior as integer division
  • Conservative: In financial calculations, truncation is often safer (e.g., don't over-calculate interest)
  • Fast: No additional logic needed

When you need to round up or down explicitly (e.g. in favour of a vault), use the fixed-point free functions with a Rounding direction.

4. Operator Overloading

We provide operator overloading (+, -, *, /, -) for convenience:

// Readable arithmetic
let total = price + fee;
let cost = quantity * price;
let ratio = numerator / denominator;

Operator overloading is supported across WAD and native i128 types where unambiguous: WAD * i128, i128 * WAD, WAD / i128.

Explicit methods are available for safety:

  • checked_add(), checked_sub(), etc. return Option<Wad> for overflow handling

Overflow Behavior

Operators work directly on the raw i128 and panic on overflow. With overflow-checks = true, which the standard Stellar release profile sets and stellar contract build enforces, the panic is a native wasm trap (Error(WasmVm, InvalidAction)), not a SorobanFixedPointError. In a build without it, every row below except a / n wraps silently instead.

Unlike the checked_* methods, operators get no phantom overflow handling, because they cannot reach an Env to promote the intermediate product to I256. Their domains are therefore much narrower:

ExpressionPanics once
a + b, a - bthe result's magnitude passes i128::MAX / WAD_SCALE ≈ 1.7014 × 10^20
a * bthe product a * b passes i128::MAX / WAD_SCALE^2 ≈ 170.1412
a / ba alone passes i128::MAX / WAD_SCALE^2 ≈ 170.1412, whatever b is
a * n, n * a (i128)a.raw() * n leaves i128
a / n (i128)n == 0, or a.raw() == i128::MIN && n == -1
-aa.raw() == i128::MIN

The * bound constrains the product rather than either operand: Wad(17) * Wad(10) succeeds while Wad(171) * Wad(1) panics. Values below 1 keep plenty of headroom, but a price of 2000 scaled by a quantity already exceeds the bound.

  • Use checked_mul() / checked_div() wherever an operand can plausibly exceed these bounds, e.g. token amounts or prices. They succeed over the full range in which the result is representable and return Option<Wad>.
  • Use operators only when the operands are known to stay within the bounds above.

How It Works

Internal Representation

pub struct Wad(i128); // Internal representation
pub const WAD_SCALE: i128 = 1_000_000_000_000_000_000; // 10^18

A Wad is simply a wrapper around i128 that interprets the value as having 18 decimal places.

Arithmetic Operations

Addition/Subtraction: Direct on internal values

impl Add for Wad {
    fn add(self, rhs: Wad) -> Wad {
        Wad(self.0 + rhs.0)
    }
}

Multiplication: Scale down by WAD_SCALE

impl Mul for Wad {
    fn mul(self, rhs: Wad) -> Wad {
        // (a * b) / 10^18
        Wad((self.0 * rhs.0) / WAD_SCALE)
    }
}

Division: Scale up by WAD_SCALE

impl Div for Wad {
    fn div(self, rhs: Wad) -> Wad {
        // (a * 10^18) / b
        Wad((self.0 * WAD_SCALE) / rhs.0)
    }
}

Exponentiation

WAD supports raising a value to an unsigned integer exponent via powi.

  • powi(&e, exponent) is optimized using exponentiation by squaring (O(log n) multiplications).
  • Each multiplication keeps WAD semantics (fixed-point multiplication and truncation toward zero).
  • Overflow is reported via Soroban errors.

In addition to powi, WAD also provides checked_powi, which returns None on overflow.

// Compound interest multiplier: (1.05)^10
let rate = Wad::from_ratio(&e, 105, 100); // 1.05
let multiplier = rate.powi(&e, 10);

Notes on powi and Phantom Overflow

powi / checked_powi are implemented using exponentiation by squaring and rely on Soroban fixed-point helpers that can automatically scale intermediate products to I256 when needed.

This avoids phantom overflow cases where an intermediate multiplication would overflow i128, but the final scaled result would still fit in i128. The same handling applies to from_ratio, checked_mul, checked_div and powf, but not to the operators. See Fixed-Point Math for how it works.

Logarithm, Exponential and Fractional Powers

Wad also provides transcendental functions, each in a panicking and a checked variant returning Option<Wad>:

  • ln(&e) / checked_ln(&e): natural logarithm. Panics with InvalidBase when self <= 0.
  • exp(&e) / checked_exp(&e): natural exponential e^self, where e ≈ 2.71828 is Euler's number. This is not a generic power function; use powf for x^y. The result truncates to 0 for inputs below ≈ -41.446. Since the result must fit in i128, it overflows (exp panics with Overflow, checked_exp returns None) once the input exceeds ln(i128::MAX / 10^18) ≈ 46.58, well before the ≈ 135.305 limit of the internal 256-bit computation.
  • powf(&e, exponent) / checked_powf(&e, exponent): raises self to a Wad exponent, computed as exp(exponent * ln(self)). When exponent is an exact non-negative integer that fits in u32, it delegates to powi instead, which is faster, more precise, and also accepts a negative base (e.g. (-2)^3 = -8).

powf special cases:

  • x^0 = 1 for any x, including 0^0 = 1 (the same convention as powi)
  • 0^y = 0 for y > 0
  • 1^y = 1 and x^1 = x

powf panics with DivisionByZero for 0^y with y < 0, with InvalidBase for a negative base unless the exponent is a non-negative integer in the u32 range, and with Overflow when the result does not fit. checked_powf returns None in all of these cases.

// 2^0.5 ≈ √2
let two = Wad::from_integer(&e, 2);
let half = Wad::from_ratio(&e, 1, 2);
let sqrt_two = two.powf(&e, half);

// ln and exp are inverses
let ten = Wad::from_integer(&e, 10);
let roundtrip = ten.ln(&e).exp(&e); // ≈ 10.0

Token Conversions

Different tokens have different decimal places (USDC: 6, XLM: 7, ETH: 18, BTC: 8). WAD handles these conversions:

// Convert from USDC (6 decimals) to WAD
let usdc_amount: i128 = 1_500_000; // 1.5 USDC
let wad = Wad::from_token_amount(&e, usdc_amount, 6);
// wad.raw() = 1_500_000_000_000_000_000 (1.5 in WAD)

// Convert back to USDC
let usdc_back: i128 = wad.to_token_amount(&e, 6);
// usdc_back = 1_500_000

Precision Characteristics

Understanding Fixed-Point Precision

WAD is a fixed-point math library. Like all fixed-point arithmetic systems, precision loss is inherent and unavoidable. The goal is not to eliminate precision errors —that's impossible— but to reduce them to a degree so minimal that they become irrelevant in practical applications.

WAD achieves this goal exceptionally well. With precision loss in the range of 10^-16, the errors are so microscopically small that they have zero practical impact on financial calculations. To put this in perspective: if you're calculating with millions of dollars, the error would be measured in quadrillionths of a cent.

How Precision Loss Manifests

Due to truncation in each operation, operation order can produce slightly different results:

let a = Wad::from_integer(&e, 1000);
let b = Wad::from_raw(55_000_000_000_000_000);  // 0.055
let c = Wad::from_raw(8_333_333_333_333_333);   // ~0.00833

let result1 = a * b * c;      // Truncates after first multiplication
let result2 = a * (b * c);    // Truncates after inner multiplication

// result1 and result2 may differ by ~315 WAD units
// That's 0.000000000000000315 or (3.15 × 10^-16)

Why This Doesn't Matter:

  • Errors are in the 10^-15 to 10^-18 range, far beyond practical significance
  • Token precision (6-8 decimals) completely absorbs these errors when converting back
  • Real-world financial systems round to 2-8 decimal places; WAD's 18 decimals provide a massive safety margin
  • This is orders of magnitude more precise than needed for DeFi applications

Usage Examples

Basic Arithmetic

use soroban_sdk::Env;
use stellar_contract_utils::math::wad::Wad;

fn calculate_interest(e: &Env, principal: i128, rate_bps: u32) -> Option<i128> {
    // Convert principal (assume 6 decimals like USDC)
    let principal_wad = Wad::from_token_amount(e, principal, 6);

    // Rate in basis points (e.g., 550 = 5.5%)
    let rate_wad = Wad::from_ratio(e, rate_bps as i128, 10_000);

    // Calculate interest. `principal_wad * rate_wad` would panic once the
    // product exceeds ~170.14, i.e. for any principal above ~3,093 USDC at 5.5%
    let interest_wad = principal_wad.checked_mul(e, rate_wad)?;

    // Convert back to token amount
    Some(interest_wad.to_token_amount(e, 6))
}

Price Calculations

fn calculate_swap_output(
    e: &Env,
    amount_in: i128,
    reserve_in: i128,
    reserve_out: i128,
) -> Option<i128> {
    // Convert to WAD
    let amount_in_wad = Wad::from_token_amount(e, amount_in, 6);
    let reserve_in_wad = Wad::from_token_amount(e, reserve_in, 6);
    let reserve_out_wad = Wad::from_token_amount(e, reserve_out, 6);

    // Constant product formula: amount_out = (amount_in * reserve_out) / (reserve_in + amount_in)
    // Reserves easily exceed the operator bounds, so use the checked methods
    let numerator = amount_in_wad.checked_mul(e, reserve_out_wad)?;
    let denominator = reserve_in_wad.checked_add(amount_in_wad)?;
    let amount_out_wad = numerator.checked_div(e, denominator)?;

    // Convert back
    Some(amount_out_wad.to_token_amount(e, 6))
}

Compound Interest

fn calculate_compound_interest(
    e: &Env,
    principal: i128,
    annual_rate_bps: u32,
    days: u32,
) -> Option<i128> {
    let principal_wad = Wad::from_token_amount(e, principal, 6);
    let one = Wad::from_integer(e, 1);
    let rate = Wad::from_ratio(e, annual_rate_bps as i128, 10_000);
    let years = Wad::from_ratio(e, days as i128, 365);

    // Annual compounding over a fractional number of years:
    // interest = principal * ((1 + rate)^years - 1)
    let growth = one.checked_add(rate)?.checked_powf(e, years)?;
    let interest = principal_wad.checked_mul(e, growth.checked_sub(one)?)?;

    Some(interest.to_token_amount(e, 6))
}

Safe Arithmetic with Overflow Checks

fn safe_multiply(e: &Env, a: i128, b: i128) -> Result<i128, Error> {
    let a_wad = Wad::from_token_amount(e, a, 6);
    let b_wad = Wad::from_token_amount(e, b, 6);

    // Use checked variant
    let result_wad = a_wad
        .checked_mul(e, b_wad)
        .ok_or(Error::Overflow)?;

    Ok(result_wad.to_token_amount(e, 6))
}

API Reference

Constructors

MethodDescriptionExample
from_integer(e, n)Create from whole numberWad::from_integer(&e, 5) → 5.0
from_ratio(e, num, den)Create from fractionWad::from_ratio(&e, 1, 2) → 0.5
from_token_amount(e, amount, decimals)Create from token amountWad::from_token_amount(&e, 1_500_000, 6) → 1.5
from_price(e, price, decimals)Alias for from_token_amountWad::from_price(&e, 100_000, 6) → 0.1
from_raw(raw)Create from raw i128 valueWad::from_raw(10^18) → 1.0

Converters

MethodDescriptionExample
to_integer()Convert to whole number (truncates)Wad(5.7).to_integer() → 5
to_token_amount(e, decimals)Convert to token amountWad(1.5).to_token_amount(&e, 6) → 1_500_000
raw()Get raw i128 valueWad(1.0).raw() → 10^18

Arithmetic Operators

OperatorDescriptionExample
a + bAdditionWad(1.5) + Wad(2.3) → 3.8
a - bSubtractionWad(5.0) - Wad(3.0) → 2.0
a * bMultiplication (WAD × WAD)Wad(2.0) * Wad(3.0) → 6.0
a / bDivision (WAD ÷ WAD)Wad(6.0) / Wad(2.0) → 3.0
a * nMultiply WAD by integerWad(2.5) * 3 → 7.5
n * aMultiply integer by WAD3 * Wad(2.5) → 7.5
a / nDivide WAD by integerWad(7.5) / 3 → 2.5
-aNegation-Wad(5.0) → -5.0

Operators panic with a native wasm trap on overflow and have narrower bounds than the checked methods; see Operator Overloading.

Checked Arithmetic

MethodReturnsDescription
checked_add(rhs)Option<Wad>Addition with overflow check
checked_sub(rhs)Option<Wad>Subtraction with overflow check
checked_mul(e, rhs)Option<Wad>Multiplication with overflow check (handles phantom overflow internally)
checked_div(e, rhs)Option<Wad>Division with overflow/zero check
checked_mul_int(n)Option<Wad>Integer multiplication with overflow check
checked_div_int(n)Option<Wad>Integer division; None on division by zero or i128::MIN / -1
checked_powi(e, exponent)Option<Wad>Integer exponentiation with overflow check
checked_powf(e, exponent)Option<Wad>Wad exponentiation; None on overflow, 0^y with y < 0, or an invalid base
checked_ln(e)Option<Wad>Natural logarithm; None when self <= 0
checked_exp(e)Option<Wad>Natural exponential e^self; None on overflow

Utility Methods

MethodDescription
abs()Absolute value
min(other)Minimum of two values
max(other)Maximum of two values
powi(e, exponent)Raises WAD to an unsigned integer power (panics with Soroban error on overflow)
powf(e, exponent)Raises WAD to a Wad power via exp(exponent * ln(self)) (panics with Soroban error)
ln(e)Natural logarithm (panics with InvalidBase when self <= 0)
exp(e)Natural exponential e^self (panics with Overflow when the result does not fit)

Error Handling

The panicking methods (from_integer, from_ratio, powi, powf, ln, exp, etc.) use Soroban's contract error system via SorobanFixedPointError:

pub enum SorobanFixedPointError {
    Overflow = 1500,
    DivisionByZero = 1501,
    // `ln(x)` with `x <= 0`, or `powf` with a negative base and an exponent
    // that is not a non-negative integer
    InvalidBase = 1502,
}

The operators (+, -, *, /, unary -) do not raise these errors: they panic with a native arithmetic trap, which surfaces on-chain as Error(WasmVm, InvalidAction).