moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Balance aggregation over the unshielded UTXO state.
//!
//! Pure functions over [`UnshieldedState`] — no ledger calls. These power
//! the facade's "how much do I have" surface without needing to construct or
//! submit transactions.

use indexmap::IndexMap;

use crate::types::TokenType;
use crate::unshielded::state::{UnshieldedState, UtxoWithMeta};

/// Per-token balance summary.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BalanceSummary {
    /// Confirmed on chain, not yet locally marked as spent.
    pub available: u128,
    /// Locally marked as spent (tx broadcast) but not yet confirmed on chain.
    /// These values are NOT spendable but tracked for UI purposes.
    pub pending: u128,
}

impl BalanceSummary {
    /// Gross total = available + pending. Does not imply spendability.
    #[inline]
    #[must_use]
    pub fn total(self) -> u128 {
        self.available.saturating_add(self.pending)
    }
}

/// Sum values of all UTXOs in `utxos` that match `token`.
///
/// Uses `saturating_add` — realistic Midnight supplies never approach `u128::MAX`,
/// but a malformed input shouldn't panic.
#[must_use]
pub fn sum_by_token<'a>(
    utxos: impl IntoIterator<Item = &'a UtxoWithMeta>,
    token: &TokenType,
) -> u128 {
    utxos
        .into_iter()
        .filter(|u| u.utxo.token_type == *token)
        .fold(0u128, |acc, u| acc.saturating_add(u.utxo.value))
}

/// Filter UTXOs down to those matching `token`.
pub fn filter_by_token<'a>(
    utxos: impl IntoIterator<Item = &'a UtxoWithMeta>,
    token: &'a TokenType,
) -> impl Iterator<Item = &'a UtxoWithMeta> {
    utxos
        .into_iter()
        .filter(move |u| u.utxo.token_type == *token)
}

impl UnshieldedState {
    /// Available balance for one token.
    #[must_use]
    pub fn available_balance(&self, token: &TokenType) -> u128 {
        sum_by_token(self.available(), token)
    }

    /// Pending balance (in-flight spends) for one token.
    #[must_use]
    pub fn pending_balance(&self, token: &TokenType) -> u128 {
        sum_by_token(self.pending(), token)
    }

    /// `{available, pending}` for one token.
    #[must_use]
    pub fn balance_for(&self, token: &TokenType) -> BalanceSummary {
        BalanceSummary {
            available: self.available_balance(token),
            pending: self.pending_balance(token),
        }
    }

    /// Per-token balance summary across every token the wallet has touched.
    /// Deterministic iteration order: first appearance of each token in
    /// `available`, then tokens that only appeared in `pending`.
    #[must_use]
    pub fn balances(&self) -> IndexMap<TokenType, BalanceSummary> {
        let mut out: IndexMap<TokenType, BalanceSummary> = IndexMap::new();
        for u in self.available() {
            out.entry(u.utxo.token_type.clone()).or_default().available = out
                .get(&u.utxo.token_type)
                .map_or(0u128, |s| s.available)
                .saturating_add(u.utxo.value);
        }
        for u in self.pending() {
            out.entry(u.utxo.token_type.clone()).or_default().pending = out
                .get(&u.utxo.token_type)
                .map_or(0u128, |s| s.pending)
                .saturating_add(u.utxo.value);
        }
        out
    }

    /// Select available UTXOs of one token, in insertion order.
    pub fn available_of_token<'a>(
        &'a self,
        token: &'a TokenType,
    ) -> impl Iterator<Item = &'a UtxoWithMeta> {
        filter_by_token(self.available(), token)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unshielded::state::{
        UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta,
    };

    fn tok(s: &str) -> TokenType {
        TokenType::new(s)
    }

    fn utxo(token: &str, value: u128, byte: u8) -> UtxoWithMeta {
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([byte; 32], u32::from(byte)),
                value,
                tok(token),
                [byte; 32],
            ),
            UtxoMeta::new(0, false),
        )
    }

    #[allow(clippy::needless_pass_by_value)] // test helper: caller hands off ownership
    fn seed_state(available: Vec<UtxoWithMeta>, pending: Vec<UtxoWithMeta>) -> UnshieldedState {
        let mut s = UnshieldedState::empty();
        if !available.is_empty() {
            s = s
                .apply_update(&UnshieldedUpdate::success(available.clone(), vec![]))
                .unwrap();
        }
        for p in &pending {
            // To move a utxo into `pending`, first put it into `available`, then spend it.
            s = s
                .apply_update(&UnshieldedUpdate::success(vec![p.clone()], vec![]))
                .unwrap();
            s = s.spend(p).unwrap();
        }
        s
    }

    #[test]
    fn empty_state_has_zero_balance() {
        let s = UnshieldedState::empty();
        assert_eq!(s.available_balance(&tok("native")), 0);
        assert_eq!(s.pending_balance(&tok("native")), 0);
    }

    #[test]
    fn sums_available_by_token() {
        let s = seed_state(
            vec![
                utxo("native", 100, 1),
                utxo("native", 250, 2),
                utxo("custom", 50, 3),
            ],
            vec![],
        );
        assert_eq!(s.available_balance(&tok("native")), 350);
        assert_eq!(s.available_balance(&tok("custom")), 50);
        assert_eq!(s.available_balance(&tok("unknown")), 0);
    }

    #[test]
    fn sums_pending_separately_from_available() {
        let s = seed_state(
            vec![utxo("native", 100, 1)],
            vec![utxo("native", 10, 2), utxo("native", 20, 3)],
        );
        assert_eq!(s.available_balance(&tok("native")), 100);
        assert_eq!(s.pending_balance(&tok("native")), 30);
    }

    #[test]
    fn balance_for_pairs_available_and_pending() {
        let s = seed_state(vec![utxo("native", 100, 1)], vec![utxo("native", 25, 2)]);
        let summary = s.balance_for(&tok("native"));
        assert_eq!(summary.available, 100);
        assert_eq!(summary.pending, 25);
        assert_eq!(summary.total(), 125);
    }

    #[test]
    fn balances_map_covers_all_tokens_deterministically() {
        let s = seed_state(
            vec![
                utxo("native", 100, 1),
                utxo("custom", 50, 2),
                utxo("native", 200, 3),
            ],
            vec![utxo("third", 7, 4)],
        );
        let all = s.balances();
        assert_eq!(all.get(&tok("native")).unwrap().available, 300);
        assert_eq!(all.get(&tok("native")).unwrap().pending, 0);
        assert_eq!(all.get(&tok("custom")).unwrap().available, 50);
        assert_eq!(all.get(&tok("third")).unwrap().pending, 7);
    }

    #[test]
    fn available_of_token_respects_insertion_order() {
        let s = seed_state(
            vec![
                utxo("native", 100, 1),
                utxo("custom", 50, 2),
                utxo("native", 200, 3),
                utxo("custom", 25, 4),
            ],
            vec![],
        );
        let native = tok("native");
        let natives: Vec<_> = s.available_of_token(&native).collect();
        assert_eq!(natives.len(), 2);
        assert_eq!(natives[0].utxo.value, 100);
        assert_eq!(natives[1].utxo.value, 200);
    }

    #[test]
    fn balance_total_saturates_on_overflow() {
        // Hard-wire two u128::MAX values into a BalanceSummary to prove the
        // saturating arithmetic — realistic Midnight supplies never hit this,
        // but the helper shouldn't panic on malformed state.
        let s = BalanceSummary {
            available: u128::MAX,
            pending: 1,
        };
        assert_eq!(s.total(), u128::MAX);
    }
}