moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! `CounterOffer` — the mutable state the balancer drives toward target.
//!
//! Tracks selected inputs, produced outputs, and running per-token
//! imbalances with fee accounting. Ported 1:1 from the TS reference; the
//! `add_input` / `add_output` arithmetic matches exactly so behavior is
//! observable-identical.

use crate::balancer::imbalances::Imbalances;
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};

/// Output specification the balancer has decided to produce. The eventual
/// tx-level output type is produced by the caller's `create_output`
/// callback; this type is just the (token, value) handshake between the
/// balancer and that callback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputRecipe {
    pub token_type: TokenType,
    pub value: Amount,
}

impl CoinRecipe for OutputRecipe {
    #[inline]
    fn token_type(&self) -> &TokenType {
        &self.token_type
    }
    #[inline]
    fn value(&self) -> Amount {
        self.value
    }
}

/// Non-native imbalance returned by [`CounterOffer::find_non_native_imbalance`].
/// Borrowed from the map so iteration is allocation-free.
pub struct ImbalanceView<'a> {
    pub token: &'a TokenType,
    pub value: Amount,
}

/// Running state of a balance operation.
#[derive(Debug, Clone)]
pub struct CounterOffer<TInput, TOutput> {
    imbalances: Imbalances,
    target_imbalances: Imbalances,
    cost_model: TransactionCostModel,
    fee_token: TokenType,
    inputs: Vec<TInput>,
    outputs: Vec<TOutput>,
}

impl<TInput, TOutput> CounterOffer<TInput, TOutput>
where
    TInput: CoinRecipe,
    TOutput: CoinRecipe,
{
    #[must_use]
    pub fn new(
        mut imbalances: Imbalances,
        target_imbalances: Imbalances,
        cost_model: TransactionCostModel,
        fee_token: TokenType,
    ) -> Self {
        // Make sure every token mentioned in the target is represented in
        // the live imbalance map (even at zero), so find_non_native_imbalance
        // will visit it.
        imbalances.ensure_zeros_for(target_imbalances.token_types());

        Self {
            imbalances,
            target_imbalances,
            cost_model,
            fee_token,
            inputs: Vec::new(),
            outputs: Vec::new(),
        }
    }

    #[inline]
    #[must_use]
    pub fn fee_token(&self) -> &TokenType {
        &self.fee_token
    }

    #[inline]
    #[must_use]
    pub fn cost_model(&self) -> &TransactionCostModel {
        &self.cost_model
    }

    #[inline]
    #[must_use]
    pub fn target_for(&self, token: &TokenType) -> Amount {
        self.target_imbalances.get(token)
    }

    #[inline]
    #[must_use]
    pub fn imbalance_for(&self, token: &TokenType) -> Amount {
        self.imbalances.get(token)
    }

    /// First non-fee token whose imbalance != target, or `None` if all
    /// non-fee tokens are balanced. Iteration order is the insertion order
    /// of the underlying `IndexMap`, making selection deterministic.
    #[must_use]
    pub fn find_non_native_imbalance(&self) -> Option<ImbalanceView<'_>> {
        for (token, value) in self.imbalances.iter() {
            if token == &self.fee_token {
                continue;
            }
            if value != self.target_imbalances.get(token) {
                return Some(ImbalanceView { token, value });
            }
        }
        None
    }

    /// Fee-token imbalance if != target, else `None`.
    #[must_use]
    pub fn find_native_imbalance(&self) -> Option<ImbalanceView<'_>> {
        let value = self.imbalances.get(&self.fee_token);
        if value == self.target_imbalances.get(&self.fee_token) {
            None
        } else {
            Some(ImbalanceView {
                token: &self.fee_token,
                value,
            })
        }
    }

    /// Record a selected input: accrues its value to its token's imbalance
    /// and charges the input fee overhead against the native token.
    pub fn add_input(&mut self, input: TInput) {
        let token = input.token_type().clone();
        let val = input.value();
        let cur = self.imbalances.get(&token);
        self.imbalances.set(token, cur + val);

        let native = self.imbalances.get(&self.fee_token);
        self.imbalances.set(
            self.fee_token.clone(),
            native - self.cost_model.input_fee_overhead,
        );

        self.inputs.push(input);
    }

    /// Record a produced change output.
    ///
    /// `face_value` is the absolute amount being subtracted from our side of
    /// the tx (post-abs so callers can pass a signed excess without worrying
    /// about the sign). For fee-token outputs, the `make_output` callback
    /// receives `face_value - output_fee_overhead` — i.e. the net value the
    /// recipient actually gets — so the fee is transparently "baked in".
    /// For non-fee tokens, the callback receives `face_value` and the
    /// `output_fee_overhead` is debited from the native imbalance instead.
    ///
    /// This matches the TS reference's `addOutput` behavior exactly.
    pub fn add_output<F>(&mut self, token: &TokenType, face_value: Amount, make_output: F)
    where
        F: FnOnce(TokenType, Amount) -> TOutput,
    {
        let absolute = face_value.abs();
        let is_fee = token == &self.fee_token;

        let recipient_value = if is_fee {
            absolute - self.cost_model.output_fee_overhead
        } else {
            absolute
        };
        let output = make_output(token.clone(), recipient_value);

        let imbalance = self.imbalances.get(token);
        self.imbalances.set(token.clone(), imbalance - absolute);

        if !is_fee {
            let native = self.imbalances.get(&self.fee_token);
            self.imbalances.set(
                self.fee_token.clone(),
                native - self.cost_model.output_fee_overhead,
            );
        }

        self.outputs.push(output);
    }

    #[inline]
    #[must_use]
    pub fn inputs(&self) -> &[TInput] {
        &self.inputs
    }

    #[inline]
    #[must_use]
    pub fn outputs(&self) -> &[TOutput] {
        &self.outputs
    }

    /// Consume the counter-offer and return its selected inputs + produced
    /// outputs. Use this once the balance loop has settled.
    #[must_use]
    pub fn into_recipe(self) -> (Vec<TInput>, Vec<TOutput>) {
        (self.inputs, self.outputs)
    }
}