moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Human-readable formatting of on-chain atomic amounts.
//!
//! NIGHT is denominated in Stars (`STARS_PER_NIGHT` = 1e6) and DUST in
//! Specks (`SPECKS_PER_DUST` = 1e15); the ledger and indexer report raw
//! atomic integers. These helpers scale to the display unit so the CLI
//! shows `5000 NIGHT`, not `5000000000`. Scaling factors come straight
//! from the ledger constants so they can never drift from consensus.

use moonproof_ledger::ledger::structure::{SPECKS_PER_DUST, STARS_PER_NIGHT};

/// Format a NIGHT amount given in Stars (1 NIGHT = 1e6 Stars).
#[must_use]
pub fn format_night(stars: u128) -> String {
    format_scaled(stars, STARS_PER_NIGHT)
}

/// Format a DUST amount given in Specks (1 DUST = 1e15 Specks).
#[must_use]
pub fn format_dust(specks: u128) -> String {
    format_scaled(specks, SPECKS_PER_DUST)
}

/// Render `raw` atomic units scaled by `per_unit` (a power of ten):
/// the whole part, then the fractional digits with trailing zeros
/// trimmed, and no decimal point at all when the amount is whole.
fn format_scaled(raw: u128, per_unit: u128) -> String {
    let whole = raw / per_unit;
    let frac = raw % per_unit;
    if frac == 0 {
        return whole.to_string();
    }
    let decimals = per_unit.ilog10() as usize;
    let mut frac_str = format!("{frac:0>decimals$}");
    while frac_str.ends_with('0') {
        frac_str.pop();
    }
    format!("{whole}.{frac_str}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn night_scales_by_one_million() {
        assert_eq!(STARS_PER_NIGHT, 1_000_000);
        assert_eq!(format_night(5_000_000_000), "5000"); // faucet drip
        assert_eq!(format_night(0), "0");
        assert_eq!(format_night(1_500_000), "1.5");
        assert_eq!(format_night(1), "0.000001"); // one Star
        assert_eq!(format_night(50_000 * 1_000_000), "50000");
    }

    #[test]
    fn dust_scales_by_ten_to_the_fifteenth() {
        assert_eq!(SPECKS_PER_DUST, 1_000_000_000_000_000);
        assert_eq!(format_dust(1_000_000_000_000_000), "1");
        assert_eq!(format_dust(1_500_000_000_000_000), "1.5");
        assert_eq!(format_dust(0), "0");
        assert_eq!(format_dust(1), "0.000000000000001"); // one Speck
    }
}