moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Token-wise imbalance tracking for the balancer.
//!
//! An imbalance is `inputs_so_far - outputs_so_far` per token. The balancer
//! drives all imbalances to their target (usually `0`) by adding inputs or
//! change outputs. We use `IndexMap` so iteration order is insertion order
//! — deterministic iteration keeps tx building reproducible for tests and
//! snapshot comparisons.

use indexmap::IndexMap;

use crate::types::{Amount, TokenType};

/// Map of token-type → signed imbalance. Positive = excess (we received more
/// than we've committed to send), negative = deficit.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Imbalances(IndexMap<TokenType, Amount>);

impl Imbalances {
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Build from a single (token, value) pair.
    #[must_use]
    pub fn from_entry(token: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
        let mut m = IndexMap::with_capacity(1);
        m.insert(token.into(), value.into());
        Self(m)
    }

    /// Build by summing values per token (duplicates accumulate).
    pub fn from_entries<I, K, V>(entries: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<TokenType>,
        V: Into<Amount>,
    {
        let mut m: IndexMap<TokenType, Amount> = IndexMap::new();
        for (k, v) in entries {
            let key = k.into();
            *m.entry(key).or_insert(Amount::ZERO) += v.into();
        }
        Self(m)
    }

    /// Read the current imbalance for `token`, defaulting to `0`.
    #[inline]
    #[must_use]
    pub fn get(&self, token: &TokenType) -> Amount {
        self.0.get(token).copied().unwrap_or(Amount::ZERO)
    }

    /// Write the imbalance for `token`, replacing any previous value.
    #[inline]
    pub fn set(&mut self, token: TokenType, value: impl Into<Amount>) {
        self.0.insert(token, value.into());
    }

    /// Ensure each token in `tokens` has an entry (value unchanged if present,
    /// `0` if absent). Used to make sure target tokens are visited by
    /// `find_non_native_imbalance` even when they start at zero.
    pub fn ensure_zeros_for<'a, I>(&mut self, tokens: I)
    where
        I: IntoIterator<Item = &'a TokenType>,
    {
        for t in tokens {
            self.0.entry(t.clone()).or_insert(Amount::ZERO);
        }
    }

    /// Iterate `(token, value)` pairs in insertion order.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = (&TokenType, Amount)> {
        self.0.iter().map(|(k, v)| (k, *v))
    }

    /// Borrow the set of token types present in this map.
    #[inline]
    pub fn token_types(&self) -> impl Iterator<Item = &TokenType> {
        self.0.keys()
    }

    /// Number of distinct tokens tracked.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether the map has no tokens tracked.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Sum the imbalances from `other` into `self`. Tokens present only in
    /// `other` are inserted; shared tokens are added; resulting zeros are
    /// pruned for a cleaner state.
    pub fn merge_in(&mut self, other: &Imbalances) {
        for (k, v) in &other.0 {
            let slot = self.0.entry(k.clone()).or_insert(Amount::ZERO);
            *slot += *v;
        }
        self.0.retain(|_, v| !v.is_zero());
    }
}