Skip to main content

moonproof_wallet/balancer/
counter_offer.rs

1//! `CounterOffer` — the mutable state the balancer drives toward target.
2//!
3//! Tracks selected inputs, produced outputs, and running per-token
4//! imbalances with fee accounting. Ported 1:1 from the TS reference; the
5//! `add_input` / `add_output` arithmetic matches exactly so behavior is
6//! observable-identical.
7
8use crate::balancer::imbalances::Imbalances;
9use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
10
11/// Output specification the balancer has decided to produce. The eventual
12/// tx-level output type is produced by the caller's `create_output`
13/// callback; this type is just the (token, value) handshake between the
14/// balancer and that callback.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct OutputRecipe {
17    pub token_type: TokenType,
18    pub value: Amount,
19}
20
21impl CoinRecipe for OutputRecipe {
22    #[inline]
23    fn token_type(&self) -> &TokenType {
24        &self.token_type
25    }
26    #[inline]
27    fn value(&self) -> Amount {
28        self.value
29    }
30}
31
32/// Non-native imbalance returned by [`CounterOffer::find_non_native_imbalance`].
33/// Borrowed from the map so iteration is allocation-free.
34pub struct ImbalanceView<'a> {
35    pub token: &'a TokenType,
36    pub value: Amount,
37}
38
39/// Running state of a balance operation.
40#[derive(Debug, Clone)]
41pub struct CounterOffer<TInput, TOutput> {
42    imbalances: Imbalances,
43    target_imbalances: Imbalances,
44    cost_model: TransactionCostModel,
45    fee_token: TokenType,
46    inputs: Vec<TInput>,
47    outputs: Vec<TOutput>,
48}
49
50impl<TInput, TOutput> CounterOffer<TInput, TOutput>
51where
52    TInput: CoinRecipe,
53    TOutput: CoinRecipe,
54{
55    #[must_use]
56    pub fn new(
57        mut imbalances: Imbalances,
58        target_imbalances: Imbalances,
59        cost_model: TransactionCostModel,
60        fee_token: TokenType,
61    ) -> Self {
62        // Make sure every token mentioned in the target is represented in
63        // the live imbalance map (even at zero), so find_non_native_imbalance
64        // will visit it.
65        imbalances.ensure_zeros_for(target_imbalances.token_types());
66
67        Self {
68            imbalances,
69            target_imbalances,
70            cost_model,
71            fee_token,
72            inputs: Vec::new(),
73            outputs: Vec::new(),
74        }
75    }
76
77    #[inline]
78    #[must_use]
79    pub fn fee_token(&self) -> &TokenType {
80        &self.fee_token
81    }
82
83    #[inline]
84    #[must_use]
85    pub fn cost_model(&self) -> &TransactionCostModel {
86        &self.cost_model
87    }
88
89    #[inline]
90    #[must_use]
91    pub fn target_for(&self, token: &TokenType) -> Amount {
92        self.target_imbalances.get(token)
93    }
94
95    #[inline]
96    #[must_use]
97    pub fn imbalance_for(&self, token: &TokenType) -> Amount {
98        self.imbalances.get(token)
99    }
100
101    /// First non-fee token whose imbalance != target, or `None` if all
102    /// non-fee tokens are balanced. Iteration order is the insertion order
103    /// of the underlying `IndexMap`, making selection deterministic.
104    #[must_use]
105    pub fn find_non_native_imbalance(&self) -> Option<ImbalanceView<'_>> {
106        for (token, value) in self.imbalances.iter() {
107            if token == &self.fee_token {
108                continue;
109            }
110            if value != self.target_imbalances.get(token) {
111                return Some(ImbalanceView { token, value });
112            }
113        }
114        None
115    }
116
117    /// Fee-token imbalance if != target, else `None`.
118    #[must_use]
119    pub fn find_native_imbalance(&self) -> Option<ImbalanceView<'_>> {
120        let value = self.imbalances.get(&self.fee_token);
121        if value == self.target_imbalances.get(&self.fee_token) {
122            None
123        } else {
124            Some(ImbalanceView {
125                token: &self.fee_token,
126                value,
127            })
128        }
129    }
130
131    /// Record a selected input: accrues its value to its token's imbalance
132    /// and charges the input fee overhead against the native token.
133    pub fn add_input(&mut self, input: TInput) {
134        let token = input.token_type().clone();
135        let val = input.value();
136        let cur = self.imbalances.get(&token);
137        self.imbalances.set(token, cur + val);
138
139        let native = self.imbalances.get(&self.fee_token);
140        self.imbalances.set(
141            self.fee_token.clone(),
142            native - self.cost_model.input_fee_overhead,
143        );
144
145        self.inputs.push(input);
146    }
147
148    /// Record a produced change output.
149    ///
150    /// `face_value` is the absolute amount being subtracted from our side of
151    /// the tx (post-abs so callers can pass a signed excess without worrying
152    /// about the sign). For fee-token outputs, the `make_output` callback
153    /// receives `face_value - output_fee_overhead` — i.e. the net value the
154    /// recipient actually gets — so the fee is transparently "baked in".
155    /// For non-fee tokens, the callback receives `face_value` and the
156    /// `output_fee_overhead` is debited from the native imbalance instead.
157    ///
158    /// This matches the TS reference's `addOutput` behavior exactly.
159    pub fn add_output<F>(&mut self, token: &TokenType, face_value: Amount, make_output: F)
160    where
161        F: FnOnce(TokenType, Amount) -> TOutput,
162    {
163        let absolute = face_value.abs();
164        let is_fee = token == &self.fee_token;
165
166        let recipient_value = if is_fee {
167            absolute - self.cost_model.output_fee_overhead
168        } else {
169            absolute
170        };
171        let output = make_output(token.clone(), recipient_value);
172
173        let imbalance = self.imbalances.get(token);
174        self.imbalances.set(token.clone(), imbalance - absolute);
175
176        if !is_fee {
177            let native = self.imbalances.get(&self.fee_token);
178            self.imbalances.set(
179                self.fee_token.clone(),
180                native - self.cost_model.output_fee_overhead,
181            );
182        }
183
184        self.outputs.push(output);
185    }
186
187    #[inline]
188    #[must_use]
189    pub fn inputs(&self) -> &[TInput] {
190        &self.inputs
191    }
192
193    #[inline]
194    #[must_use]
195    pub fn outputs(&self) -> &[TOutput] {
196        &self.outputs
197    }
198
199    /// Consume the counter-offer and return its selected inputs + produced
200    /// outputs. Use this once the balance loop has settled.
201    #[must_use]
202    pub fn into_recipe(self) -> (Vec<TInput>, Vec<TOutput>) {
203        (self.inputs, self.outputs)
204    }
205}