Wad

Struct Wad 

Source
pub struct Wad(/* private fields */);
Expand description

Fixed-point decimal number with 18 decimal places of precision.

Wad represents decimal numbers using a fixed-point representation where 1.0 is stored as 1_000_000_000_000_000_000 (10^18). This provides precise decimal arithmetic suitable for financial calculations in smart contracts.

§Truncation

All arithmetic operations truncate toward zero rather than rounding:

  • 5 / 2 = 2 (not 2.5 or 3)
  • -5 / 2 = -2 (not -2.5 or -3)

§Precision

Due to truncation on each multiplication/division, the order of operations can affect 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 ~10^-16 due to different truncation points

Typical precision loss: ~10^-15 to 10^-16 in relative terms, which is negligible when converting to typical token precision (6-8 decimals).

§Examples

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

let e = Env::default();

// Creating Wad values
let five = Wad::from_integer(&e, 5);           // 5.0
let half = Wad::from_ratio(&e, 1, 2);          // 0.5
let price = Wad::from_token_amount(&e, 1_500_000, 6); // 1.5 (from USDC)

// Arithmetic
let sum = five + half;                          // 5.5
let product = five * half;                      // 2.5
let quotient = five / half;                     // 10.0

// Converting back to token amounts
let usdc_amount = product.to_token_amount(&e, 6); // 2_500_000 (2.5 USDC)

Implementations§

Source§

impl Wad

Source

pub fn from_integer(e: &Env, n: i128) -> Self

Creates a Wad from an integer by applying WAD scaling.

Treats the input as a whole number and scales it to WAD precision (18 decimals).

§Arguments
  • e - Access to the Soroban environment.
  • n - The integer value to convert to WAD representation.
§Errors
§Examples
let wad = Wad::from_integer(&e, 5);
assert_eq!(wad.raw(), 5_000_000_000_000_000_000);
§Notes

Compare with Wad::from_raw which does NOT apply WAD scaling.

Source

pub fn to_integer(self) -> i128

Converts Wad back to an integer by removing WAD scaling.

Truncates toward zero, discarding any fractional part.

§Examples
let wad = Wad::from_raw(5_000_000_000_000_000_000);
assert_eq!(wad.to_integer(), 5);
Source

pub fn from_ratio(e: &Env, num: i128, den: i128) -> Self

Creates a Wad from a ratio (num / den).

§Arguments
  • e - Access to the Soroban environment.
  • num - The numerator of the ratio.
  • den - The denominator of the ratio.
§Errors
§Examples
let wad = Wad::from_ratio(&e, 5, 10);
assert_eq!(wad.raw(), 500_000_000_000_000_000); // 0.5 in WAD
Source

pub fn from_token_amount(e: &Env, amount: i128, token_decimals: u8) -> Self

Creates a Wad from a token amount with specified decimals.

Converts a token’s native representation to WAD (18 decimals). Truncates toward zero when scaling down (token_decimals > 18).

§Arguments
  • e - Access to the Soroban environment.
  • amount - The token amount in its smallest unit.
  • token_decimals - The number of decimals the token uses.
§Errors
§Examples
// USDC has 2 decimals, so 1 USDC = 100 units
let wad = Wad::from_token_amount(&e, 100, 2);
assert_eq!(wad.raw(), 1_000_000_000_000_000_000); // 1.0 in WAD
§Notes

amount must be in the token’s smallest unit. For example, to represent 1 USDC (2 decimals), pass 100, not 1.

Source

pub fn to_token_amount(self, e: &Env, token_decimals: u8) -> i128

Converts Wad to a token amount with specified decimals.

Converts from WAD (18 decimals) back to a token’s native representation. Truncates toward zero when scaling down (token_decimals < 18).

§Arguments
  • e - Access to the Soroban environment.
  • token_decimals - The number of decimals the target token uses.
§Errors
§Examples
let wad = Wad::from_raw(1_000_000_000_000_000_000); // 1.0 in WAD
let usdc_amount = wad.to_token_amount(&e, 2);
assert_eq!(usdc_amount, 100); // 1 USDC = 100 units
Source

pub fn from_price(e: &Env, price_integer: i128, price_decimals: u8) -> Self

Creates a Wad from a price with specified decimals.

This is an alias for Wad::from_token_amount.

§Arguments
  • e - Access to the Soroban environment.
  • price_integer - The price in its smallest unit.
  • price_decimals - The number of decimals the price uses.
§Errors

refer to Wad::from_token_amount errors.

Source

pub fn raw(self) -> i128

Returns the raw i128 value without applying WAD scaling.

Returns the internal representation directly.

§Examples
let wad = Wad::from_integer(5);
assert_eq!(wad.raw(), 5_000_000_000_000_000_000);
Source

pub fn from_raw(raw: i128) -> Self

Creates a Wad from a raw i128 value without applying WAD scaling.

Interprets the input as the internal representation directly.

§Arguments
  • raw - The raw internal value.
§Examples
let wad = Wad::from_raw(5);
// Represents 0.000000000000000005 in decimal
assert_eq!(wad.raw(), 5);
§Notes

Compare with Wad::from_integer which applies WAD scaling.

Source

pub fn min(self, other: Self) -> Self

Returns the minimum of two Wad values.

§Arguments
  • other - The other Wad value to compare.
Source

pub fn max(self, other: Self) -> Self

Returns the maximum of two Wad values.

§Arguments
  • other - The other Wad value to compare.
Source

pub fn checked_add(self, rhs: Wad) -> Option<Wad>

Checked addition. Returns None on overflow.

Source

pub fn checked_sub(self, rhs: Wad) -> Option<Wad>

Checked subtraction. Returns None on overflow.

Source

pub fn checked_mul(self, e: &Env, rhs: Wad) -> Option<Wad>

Checked multiplication (Wad * Wad).

Returns None on overflow. Handles phantom overflow by scaling to I256 when intermediate multiplication overflows i128 but the final result fits. Result is truncated toward zero after division by WAD_SCALE.

Source

pub fn checked_div(self, e: &Env, rhs: Wad) -> Option<Wad>

Checked division (Wad / Wad). Returns None on overflow or division by zero.

Result is truncated toward zero.

Source

pub fn checked_mul_int(self, n: i128) -> Option<Wad>

Checked multiplication by integer. Returns None on overflow.

Source

pub fn checked_div_int(self, n: i128) -> Option<Wad>

Checked division by integer. Returns None on division by zero.

Source

pub fn abs(self) -> Self

Returns the absolute value of the Wad.

§Examples
let e = Env::default();
let negative = Wad::from_integer(&e, -5);
assert_eq!(negative.abs(), Wad::from_integer(&e, 5));
Source

pub fn pow(self, e: &Env, exponent: u32) -> Self

Raises Wad to an unsigned integer power using exponentiation by squaring.

This method is optimized for efficiency, computing the result in O(log n) multiplications where n is the exponent. Each multiplication maintains fixed-point precision by dividing by WAD_SCALE, with truncation toward zero.

§Arguments
  • e - Access to the Soroban environment for error handling.
  • exponent - The unsigned integer exponent (0 to 2^32-1).
§Errors
§Examples
// Compound interest: (1.05)^10
let rate = Wad::from_ratio(&e, 105, 100);  // 1.05
let final_multiplier = rate.pow(&e, 10);
let final_amount = principal * final_multiplier;

// Quadratic bonding curve: price = supply^2
let supply = Wad::from_integer(&e, 1000);
let price = supply.pow(&e, 2);
Source

pub fn checked_pow(self, e: &Env, exponent: u32) -> Option<Self>

Checked version of Wad::pow.

Returns None instead of panicking on overflow. Handles phantom overflow transparently by scaling to I256 when intermediate multiplications overflow i128 but the final result fits.

§Arguments
  • e - Access to the Soroban environment for i256 operations.
  • exponent - The unsigned integer exponent.
§Examples
let e = Env::default();
let small = Wad::from_integer(&e, 2);
assert_eq!(small.checked_pow(&e, 10), Some(Wad::from_integer(&e, 1024)));

let large = Wad::from_integer(&e, i128::MAX / WAD_SCALE);
assert_eq!(large.checked_pow(&e, 2), None); // Overflows
§Notes

Phantom overflow is handled internally.

Trait Implementations§

Source§

impl Add for Wad

Source§

type Output = Wad

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Wad) -> Wad

Performs the + operation. Read more
Source§

impl Clone for Wad

Source§

fn clone(&self) -> Wad

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Wad

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Div<i128> for Wad

Source§

type Output = Wad

The resulting type after applying the / operator.
Source§

fn div(self, rhs: i128) -> Wad

Performs the / operation. Read more
Source§

impl Div for Wad

Source§

type Output = Wad

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Wad) -> Wad

Performs the / operation. Read more
Source§

impl Mul<Wad> for i128

Source§

type Output = Wad

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Wad) -> Wad

Performs the * operation. Read more
Source§

impl Mul<i128> for Wad

Source§

type Output = Wad

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: i128) -> Wad

Performs the * operation. Read more
Source§

impl Mul for Wad

Source§

type Output = Wad

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Wad) -> Wad

Performs the * operation. Read more
Source§

impl Neg for Wad

Source§

type Output = Wad

The resulting type after applying the - operator.
Source§

fn neg(self) -> Wad

Performs the unary - operation. Read more
Source§

impl Ord for Wad

Source§

fn cmp(&self, other: &Wad) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Wad

Source§

fn eq(&self, other: &Wad) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Wad

Source§

fn partial_cmp(&self, other: &Wad) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Sub for Wad

Source§

type Output = Wad

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Wad) -> Wad

Performs the - operation. Read more
Source§

impl Copy for Wad

Source§

impl Eq for Wad

Source§

impl StructuralPartialEq for Wad

Auto Trait Implementations§

§

impl Freeze for Wad

§

impl RefUnwindSafe for Wad

§

impl Send for Wad

§

impl Sync for Wad

§

impl Unpin for Wad

§

impl UnwindSafe for Wad

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<T, C> Compare<&T> for C
where C: Compare<T>,

Source§

type Error = <C as Compare<T>>::Error

Source§

fn compare(&self, a: &&T, b: &&T) -> Result<Ordering, <C as Compare<&T>>::Error>

Source§

impl<T, U, E, C> Compare<(T, U)> for C
where C: Compare<T, Error = E, Error = E> + Compare<U>,

Source§

type Error = E

Source§

fn compare( &self, a: &(T, U), b: &(T, U), ) -> Result<Ordering, <C as Compare<(T, U)>>::Error>

Source§

impl<T, U, V, E, C> Compare<(T, U, V)> for C
where C: Compare<T, Error = E, Error = E, Error = E> + Compare<U> + Compare<V>,

Source§

impl<T, U, V, W, E, C> Compare<(T, U, V, W)> for C
where C: Compare<T, Error = E, Error = E, Error = E, Error = E> + Compare<U> + Compare<V> + Compare<W>,

Source§

impl<T, U, V, W, X, E, C> Compare<(T, U, V, W, X)> for C
where C: Compare<T, Error = E, Error = E, Error = E, Error = E, Error = E> + Compare<U> + Compare<V> + Compare<W> + Compare<X>,

Source§

impl<T, C> Compare<Box<T>> for C
where C: Compare<T>,

Source§

type Error = <C as Compare<T>>::Error

Source§

fn compare( &self, a: &Box<T>, b: &Box<T>, ) -> Result<Ordering, <C as Compare<Box<T>>>::Error>

Source§

impl<T, C> Compare<Option<T>> for C
where C: Compare<T>,

Source§

type Error = <C as Compare<T>>::Error

Source§

fn compare( &self, a: &Option<T>, b: &Option<T>, ) -> Result<Ordering, <C as Compare<Option<T>>>::Error>

Source§

impl<T, C> Compare<Rc<T>> for C
where C: Compare<T>,

Source§

type Error = <C as Compare<T>>::Error

Source§

fn compare( &self, a: &Rc<T>, b: &Rc<T>, ) -> Result<Ordering, <C as Compare<Rc<T>>>::Error>

Source§

impl<T, C> Compare<Vec<T>> for C
where C: Compare<T>,

Source§

type Error = <C as Compare<T>>::Error

Source§

fn compare( &self, a: &Vec<T>, b: &Vec<T>, ) -> Result<Ordering, <C as Compare<Vec<T>>>::Error>

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<E, T, U> IntoVal<E, T> for U
where E: Env, T: FromVal<E, U>,

Source§

fn into_val(&self, e: &E) -> T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<E, T, U> TryIntoVal<E, T> for U
where E: Env, T: TryFromVal<E, U>,

Source§

type Error = <T as TryFromVal<E, U>>::Error

Source§

fn try_into_val(&self, env: &E) -> Result<T, <U as TryIntoVal<E, T>>::Error>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V