Skip to main content

moonproof_wallet/balancer/
mod.rs

1//! Midnight coin-balancer — the greedy + counter-offer loop used by all
2//! three sub-wallets (shielded, unshielded, dust) to resolve a partially
3//! specified transaction into a concrete (inputs, outputs) recipe.
4//!
5//! Ported from `@midnight-ntwrk/wallet-sdk-capabilities/balancer`. Algorithm:
6//!
7//! 1. Seed a [`CounterOffer`] with the caller's initial imbalances (typically
8//!    negative entries for each intended recipient output).
9//! 2. While any non-fee token is off-target: either produce a change output
10//!    (if excess exceeds target) or pick an input coin via a pluggable
11//!    [`CoinSelector`].
12//! 3. Repeat step 2 for the fee (native) token.
13//! 4. Emit the accumulated `(inputs, outputs)` as a [`BalanceRecipe`].
14//!
15//! **Performance.** The default coin selector is a single-pass
16//! `Iterator::min_by_key` — no intermediate `Vec` allocation, no sort.
17//! Input removal after selection uses `Vec::swap_remove` when the caller
18//! supplies `is_coin_equal` so we avoid `O(n)` shifts from `retain`.
19
20mod counter_offer;
21mod imbalances;
22
23use crate::error::{Result, WalletError};
24use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
25
26pub use counter_offer::{CounterOffer, ImbalanceView, OutputRecipe};
27pub use imbalances::Imbalances;
28
29/// Pluggable coin-selection strategy. The balancer calls this each time it
30/// needs to pull an input to close a deficit.
31///
32/// Callers must return a coin whose `token_type()` matches `token`. Returning
33/// `None` means "no suitable coin available" and will bubble up as
34/// [`WalletError::InsufficientFunds`].
35pub trait CoinSelector<T: CoinRecipe> {
36    fn select(
37        &self,
38        coins: &[T],
39        token: &TokenType,
40        amount_needed: Amount,
41        cost_model: &TransactionCostModel,
42    ) -> Option<usize>;
43}
44
45/// Default coin selector — greedy smallest-first matching `token`.
46///
47/// Returns the index (in `coins`) of the smallest coin of the requested
48/// `token` type, or `None` if none exist. `amount_needed` is ignored: the
49/// outer loop will keep pulling coins until the imbalance closes, which
50/// naturally degenerates into consuming progressively larger coins as
51/// needed without needing a knapsack.
52pub struct SmallestFirstSelector;
53
54impl<T: CoinRecipe> CoinSelector<T> for SmallestFirstSelector {
55    fn select(
56        &self,
57        coins: &[T],
58        token: &TokenType,
59        _amount_needed: Amount,
60        _cost_model: &TransactionCostModel,
61    ) -> Option<usize> {
62        coins
63            .iter()
64            .enumerate()
65            .filter(|(_, c)| c.token_type() == token)
66            .min_by_key(|(_, c)| c.value())
67            .map(|(i, _)| i)
68    }
69}
70
71/// Ledger 9 time-to-dismiss-aware coin selector: minimizes the number
72/// of spent inputs (and therefore signature / proof verification cost
73/// in `cost_to_dismiss`).
74///
75/// - When at least one matching coin covers `amount_needed` on its own,
76///   picks the **smallest** such coin (1 input, minimal change).
77/// - Otherwise picks the **largest** matching coin so the outer balance
78///   loop converges in the fewest possible inputs.
79pub struct FewestCoinsSelector;
80
81impl<T: CoinRecipe> CoinSelector<T> for FewestCoinsSelector {
82    fn select(
83        &self,
84        coins: &[T],
85        token: &TokenType,
86        amount_needed: Amount,
87        _cost_model: &TransactionCostModel,
88    ) -> Option<usize> {
89        if amount_needed > Amount::ZERO {
90            if let Some((idx, _)) = coins
91                .iter()
92                .enumerate()
93                .filter(|(_, c)| c.token_type() == token && c.value() >= amount_needed)
94                .min_by_key(|(_, c)| c.value())
95            {
96                return Some(idx);
97            }
98        }
99        coins
100            .iter()
101            .enumerate()
102            .filter(|(_, c)| c.token_type() == token)
103            .max_by_key(|(_, c)| c.value())
104            .map(|(i, _)| i)
105    }
106}
107
108/// Result of a balancing operation — the concrete inputs to spend and
109/// outputs to produce. Shielded / unshielded / dust wallets each wrap this
110/// into their domain-specific recipe.
111#[derive(Debug, Clone)]
112pub struct BalanceRecipe<TInput, TOutput> {
113    pub inputs: Vec<TInput>,
114    pub outputs: Vec<TOutput>,
115}
116
117/// Arguments to [`balance`]. Grouped into a struct to keep call sites
118/// readable — there's no meaningful default for most of these fields.
119pub struct BalanceRequest<'a, TInput, TOutput, S, F>
120where
121    TInput: CoinRecipe + Clone,
122    TOutput: CoinRecipe,
123    S: CoinSelector<TInput>,
124    F: FnMut(OutputRecipe) -> TOutput,
125{
126    /// Candidate input coins. The balancer removes selected coins from this
127    /// pool (via `swap_remove`) as it goes.
128    pub coins: Vec<TInput>,
129    /// Starting imbalances — typically `-value` for each intended recipient.
130    pub initial_imbalances: Imbalances,
131    /// What each token should end up at. Usually empty (all zeros).
132    pub target_imbalances: Imbalances,
133    /// Per-input / per-output fee overheads in the fee token.
134    pub cost_model: TransactionCostModel,
135    /// Which token pays fees (native / DUST on Midnight mainnet).
136    pub fee_token: TokenType,
137    /// Strategy for choosing the next input.
138    pub selector: &'a S,
139    /// Callback that turns a raw (token, value) into a domain output.
140    pub create_output: F,
141    /// Two inputs are considered the same coin iff this returns true. Used
142    /// to remove selected coins from the candidate pool.
143    pub is_coin_equal: fn(&TInput, &TInput) -> bool,
144}
145
146/// Balance a transaction. Returns selected inputs and produced outputs, or
147/// [`WalletError::InsufficientFunds`] if no coin can close a deficit.
148pub fn balance<TInput, TOutput, S, F>(
149    request: BalanceRequest<'_, TInput, TOutput, S, F>,
150) -> Result<BalanceRecipe<TInput, TOutput>>
151where
152    TInput: CoinRecipe + Clone,
153    TOutput: CoinRecipe,
154    S: CoinSelector<TInput>,
155    F: FnMut(OutputRecipe) -> TOutput,
156{
157    let BalanceRequest {
158        mut coins,
159        initial_imbalances,
160        target_imbalances,
161        cost_model,
162        fee_token,
163        selector,
164        mut create_output,
165        is_coin_equal,
166    } = request;
167
168    let mut counter_offer = CounterOffer::<TInput, TOutput>::new(
169        initial_imbalances,
170        target_imbalances,
171        cost_model,
172        fee_token,
173    );
174
175    // Phase 1: non-native tokens. The fields are copied out so the loop
176    // body can mutate `counter_offer` freely.
177    while let Some((token, value)) = counter_offer
178        .find_non_native_imbalance()
179        .map(|v| (v.token.clone(), v.value))
180    {
181        coins = settle_token(
182            &token,
183            value,
184            coins,
185            &mut counter_offer,
186            selector,
187            &mut create_output,
188            is_coin_equal,
189        )?;
190    }
191
192    // Phase 2: fee (native) token.
193    while let Some((token, value)) = counter_offer
194        .find_native_imbalance()
195        .map(|v| (v.token.clone(), v.value))
196    {
197        coins = settle_token(
198            &token,
199            value,
200            coins,
201            &mut counter_offer,
202            selector,
203            &mut create_output,
204            is_coin_equal,
205        )?;
206    }
207
208    let (inputs, outputs) = counter_offer.into_recipe();
209    Ok(BalanceRecipe { inputs, outputs })
210}
211
212/// One iteration of the outer loop: either add a change output (if we have
213/// enough excess) or pull an input (if we're short).
214fn settle_token<TInput, TOutput, S, F>(
215    token: &TokenType,
216    imbalance_amount: Amount,
217    coins: Vec<TInput>,
218    counter_offer: &mut CounterOffer<TInput, TOutput>,
219    selector: &S,
220    create_output: &mut F,
221    is_coin_equal: fn(&TInput, &TInput) -> bool,
222) -> Result<Vec<TInput>>
223where
224    TInput: CoinRecipe + Clone,
225    TOutput: CoinRecipe,
226    S: CoinSelector<TInput>,
227    F: FnMut(OutputRecipe) -> TOutput,
228{
229    let target = counter_offer.target_for(token);
230    let cost = counter_offer.cost_model().output_fee_overhead;
231    let is_fee_token = token == counter_offer.fee_token();
232
233    let should_add_output = if is_fee_token {
234        imbalance_amount >= target + cost
235    } else {
236        imbalance_amount > target
237    };
238
239    if should_add_output {
240        counter_offer.add_output(token, imbalance_amount - target, |tok, net_value| {
241            (create_output)(OutputRecipe {
242                token_type: tok,
243                value: net_value,
244            })
245        });
246        Ok(coins)
247    } else {
248        let Some(idx) =
249            selector.select(&coins, token, imbalance_amount, counter_offer.cost_model())
250        else {
251            return Err(WalletError::InsufficientFunds {
252                token: token.to_string(),
253            });
254        };
255
256        let mut coins = coins;
257        let picked = coins.swap_remove(idx);
258        // Guard against duplicate entries of the same coin in the source
259        // pool — remove any other copies that match.
260        coins.retain(|c| !is_coin_equal(c, &picked));
261        counter_offer.add_input(picked);
262        Ok(coins)
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use crate::types::SimpleCoin;
270
271    const NATIVE: &str = "native";
272    const OTHER: &str = "other";
273
274    fn native() -> TokenType {
275        TokenType::new(NATIVE)
276    }
277    fn other() -> TokenType {
278        TokenType::new(OTHER)
279    }
280
281    fn coin(token: &str, value: impl Into<Amount>) -> SimpleCoin {
282        SimpleCoin::new(token, value)
283    }
284
285    fn default_cost_model() -> TransactionCostModel {
286        TransactionCostModel::new(19_314, 19_708)
287    }
288
289    fn balance_test(
290        coins: Vec<SimpleCoin>,
291        initial_imbalances: Imbalances,
292        cost_model: TransactionCostModel,
293    ) -> Result<BalanceRecipe<SimpleCoin, SimpleCoin>> {
294        balance(BalanceRequest {
295            coins,
296            initial_imbalances,
297            target_imbalances: Imbalances::new(),
298            cost_model,
299            fee_token: native(),
300            selector: &SmallestFirstSelector,
301            create_output: |rec| SimpleCoin::new(rec.token_type, rec.value),
302            is_coin_equal: |a, b| a == b,
303        })
304    }
305
306    #[test]
307    fn nothing_to_balance() {
308        let recipe = balance_test(vec![], Imbalances::new(), TransactionCostModel::ZERO).unwrap();
309        assert_eq!(recipe.inputs, [] as [SimpleCoin; 0]);
310        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
311    }
312
313    #[test]
314    fn uses_exactly_one_coin_when_value_matches_with_fee() {
315        let cm = default_cost_model();
316        let exact = coin(NATIVE, Amount::from(1_000) + cm.input_fee_overhead);
317        let recipe = balance_test(
318            vec![exact.clone()],
319            Imbalances::from_entry(native(), -1_000),
320            cm,
321        )
322        .unwrap();
323        assert_eq!(recipe.inputs.len(), 1);
324        assert_eq!(recipe.inputs[0], exact);
325        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
326    }
327
328    #[test]
329    fn insufficient_funds_reports_correct_token() {
330        let err = balance_test(
331            vec![coin(NATIVE, 10)],
332            Imbalances::from_entry(native(), -1_000_000),
333            TransactionCostModel::ZERO,
334        )
335        .unwrap_err();
336        match err {
337            WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
338            other => panic!("wrong error: {other:?}"),
339        }
340    }
341
342    #[test]
343    fn no_overspend_when_exact_coin_exists() {
344        // Several large native coins available; deficit is small; only one
345        // should be consumed and the excess returned as change.
346        let cm = TransactionCostModel::ZERO;
347        let coins = vec![coin(NATIVE, 100), coin(NATIVE, 100)];
348        let recipe = balance_test(coins, Imbalances::from_entry(native(), -10), cm).unwrap();
349        assert_eq!(recipe.inputs.len(), 1);
350        assert_eq!(recipe.outputs.len(), 1);
351        assert_eq!(recipe.outputs[0].value, Amount::from(90));
352        assert_eq!(recipe.outputs[0].token_type, native());
353    }
354
355    #[test]
356    fn multi_token_balance_closes_both() {
357        // Need 100 OTHER and 500 NATIVE. Pool has enough of both.
358        let cm = TransactionCostModel::ZERO;
359        let coins = vec![
360            coin(OTHER, 150),  // covers OTHER with change
361            coin(NATIVE, 500), // covers NATIVE exactly
362        ];
363        let initial = Imbalances::from_entries([(other(), -100), (native(), -500)]);
364        let recipe = balance_test(coins, initial, cm).unwrap();
365
366        assert_eq!(recipe.inputs.len(), 2);
367        assert!(recipe.inputs.iter().any(|c| c.token_type == other()));
368        assert!(recipe.inputs.iter().any(|c| c.token_type == native()));
369        // OTHER had 50 excess that must come back as a change output.
370        assert_eq!(recipe.outputs.len(), 1);
371        assert_eq!(recipe.outputs[0].token_type, other());
372        assert_eq!(recipe.outputs[0].value, Amount::from(50));
373    }
374
375    #[test]
376    fn smallest_first_selector_picks_min_coin() {
377        let coins = vec![coin(NATIVE, 100), coin(NATIVE, 5), coin(NATIVE, 50)];
378        let idx = SmallestFirstSelector.select(
379            &coins,
380            &native(),
381            Amount::from(10),
382            &TransactionCostModel::ZERO,
383        );
384        assert_eq!(idx, Some(1));
385    }
386
387    #[test]
388    fn smallest_first_selector_ignores_wrong_tokens() {
389        let coins = vec![coin(OTHER, 1), coin(NATIVE, 100), coin(OTHER, 2)];
390        let idx = SmallestFirstSelector.select(
391            &coins,
392            &native(),
393            Amount::from(10),
394            &TransactionCostModel::ZERO,
395        );
396        assert_eq!(idx, Some(1));
397    }
398
399    #[test]
400    fn fee_token_output_emitted_when_excess_exceeds_overhead() {
401        // Input fee 10, output fee 20. Deficit 100, coin 200.
402        // After input: imbalance = -100 + 200 - 10 = 90. 90 >= 20 → emit output.
403        // Recorded output has face value (absolute - output_fee) = 90 - 20 = 70.
404        let cm = TransactionCostModel::new(10, 20);
405        let coins = vec![coin(NATIVE, 200)];
406        let recipe = balance_test(coins, Imbalances::from_entry(native(), -100), cm).unwrap();
407        assert_eq!(recipe.inputs.len(), 1);
408        assert_eq!(recipe.outputs.len(), 1);
409        assert_eq!(recipe.outputs[0].value, Amount::from(70));
410    }
411
412    #[test]
413    fn excess_below_output_overhead_cannot_be_balanced() {
414        // When a native imbalance is too small to justify a change output
415        // (excess < output_fee_overhead) AND no more coins are available to
416        // absorb it, the balancer must bubble InsufficientFunds — silently
417        // leaking the excess as extra fee would be a correctness bug.
418        let cm = TransactionCostModel::new(10, 20);
419        // Coin(115): after input fee, credit = 105. Deficit 100 → excess 5.
420        // 5 < 20 (output overhead) and no other coins → error.
421        let err = balance_test(
422            vec![coin(NATIVE, 115)],
423            Imbalances::from_entry(native(), -100),
424            cm,
425        )
426        .unwrap_err();
427        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
428    }
429
430    // --- Ports of TS Balancer.test.ts test cases ---------------------
431
432    /// TS: "Does not overspend coins" — with two available coins and a small
433    /// deficit, exactly one input should be consumed and change returned.
434    #[test]
435    fn ts_does_not_overspend_coins() {
436        let cm = TransactionCostModel::new(19_314, 19_708);
437        let coins = vec![coin(NATIVE, 10_000_000), coin(NATIVE, 10_000_000)];
438        let recipe = balance_test(coins, Imbalances::from_entry(native(), -1_000_000), cm).unwrap();
439        assert_eq!(recipe.inputs.len(), 1);
440        assert_eq!(recipe.outputs.len(), 1);
441    }
442
443    /// TS: "Balance custom native token" — deficit on a custom token uses
444    /// two inputs (custom + fee) and emits one change output.
445    #[test]
446    fn ts_balance_custom_token() {
447        let custom = TokenType::new("custom");
448        let cm = TransactionCostModel::new(19_314, 19_708);
449        // Custom deficit 1, three small custom coins (1, 2, 3), one big native
450        // coin to cover fees.
451        let coins = vec![
452            coin(NATIVE, 100_000_000),
453            SimpleCoin::new(custom.clone(), 1),
454            SimpleCoin::new(custom.clone(), 2),
455            SimpleCoin::new(custom.clone(), 3),
456        ];
457        let recipe = balance_test(coins, Imbalances::from_entry(custom, -1), cm).unwrap();
458        assert_eq!(recipe.inputs.len(), 2);
459        assert_eq!(recipe.outputs.len(), 1);
460    }
461
462    /// TS: "Balance multiple token types" — duplicate-key entries in
463    /// `from_entries` must sum per token (matching TS `fromEntries` semantics).
464    #[test]
465    fn ts_balance_multiple_token_types() {
466        let custom = TokenType::new("custom");
467        let cm = TransactionCostModel::new(19_314, 19_708);
468        let coins = vec![
469            coin(NATIVE, 10_000_000),
470            coin(NATIVE, 20_000_000),
471            coin(NATIVE, 30_000_000),
472            SimpleCoin::new(custom.clone(), 1),
473            SimpleCoin::new(custom.clone(), 2),
474            SimpleCoin::new(custom.clone(), 3),
475        ];
476        // Two entries per token — from_entries must sum them: custom=-5, native=-6M.
477        let initial = Imbalances::from_entries([
478            (custom.clone(), -4),
479            (native(), -5_000_000),
480            (native(), -1_000_000),
481            (custom.clone(), -1),
482        ]);
483        let recipe = balance_test(coins, initial, cm).unwrap();
484        assert_eq!(recipe.inputs.len(), 4);
485        assert_eq!(recipe.outputs.len(), 2);
486    }
487
488    /// TS: "Fail if there aren't enough coins to cover the fees" — a single
489    /// native coin with value exactly equal to the deficit leaves nothing for
490    /// the input fee overhead.
491    #[test]
492    fn ts_fail_when_not_enough_for_fees() {
493        let cm = TransactionCostModel::new(19_314, 19_708);
494        let err = balance_test(
495            vec![coin(NATIVE, 1_000_000)],
496            Imbalances::from_entry(native(), -1_000_000),
497            cm,
498        )
499        .unwrap_err();
500        match err {
501            WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
502            other => panic!("wrong error: {other:?}"),
503        }
504    }
505
506    /// TS: "Fail if the change output value is smaller than the output fee" —
507    /// after selecting inputs, the leftover would be positive but not enough
508    /// to cover an output fee overhead.
509    #[test]
510    fn ts_fail_when_change_smaller_than_output_fee() {
511        let cm = TransactionCostModel::new(19_314, 19_708);
512        // Coin value exactly input_fee + 5 → credits 5 to imbalance.
513        // Deficit is -(5 + output_fee) → net excess 5 after input, can't mint
514        // an output smaller than output_fee.
515        let coin_val = cm.input_fee_overhead + Amount::from(5);
516        let deficit = -(Amount::from(5) + cm.output_fee_overhead);
517        let err = balance_test(
518            vec![coin(NATIVE, coin_val)],
519            Imbalances::from_entry(native(), deficit),
520            cm,
521        )
522        .unwrap_err();
523        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
524    }
525
526    /// TS: "Uses provided coin selection" — a custom selector (e.g. by-id
527    /// ordering) should be honored.
528    #[test]
529    fn ts_uses_provided_coin_selection() {
530        // Selector that picks the largest-valued matching coin first — opposite
531        // of the default smallest-first. This proves the plug-in works.
532        struct LargestFirst;
533        impl<T: CoinRecipe> CoinSelector<T> for LargestFirst {
534            fn select(
535                &self,
536                coins: &[T],
537                token: &TokenType,
538                _: Amount,
539                _: &TransactionCostModel,
540            ) -> Option<usize> {
541                coins
542                    .iter()
543                    .enumerate()
544                    .filter(|(_, c)| c.token_type() == token)
545                    .max_by_key(|(_, c)| c.value())
546                    .map(|(i, _)| i)
547            }
548        }
549
550        let cm = TransactionCostModel::ZERO;
551        let coins = vec![coin(NATIVE, 5), coin(NATIVE, 50), coin(NATIVE, 100)];
552        let recipe = balance(BalanceRequest {
553            coins,
554            initial_imbalances: Imbalances::from_entry(native(), -40),
555            target_imbalances: Imbalances::new(),
556            cost_model: cm,
557            fee_token: native(),
558            selector: &LargestFirst,
559            create_output: |r| SimpleCoin::new(r.token_type, r.value),
560            is_coin_equal: |a, b| a == b,
561        })
562        .unwrap();
563        assert_eq!(recipe.inputs.len(), 1);
564        assert_eq!(
565            recipe.inputs[0].value,
566            Amount::from(100),
567            "largest-first should pick 100"
568        );
569        assert_eq!(recipe.outputs.len(), 1);
570        assert_eq!(recipe.outputs[0].value, Amount::from(60));
571    }
572
573    /// TS: "Reaches target imbalances" — a non-empty `target_imbalances` means
574    /// the balancer should leave those specific non-fee balances on the table
575    /// instead of balancing them to zero.
576    #[test]
577    fn ts_reaches_target_imbalances() {
578        let custom = TokenType::new("custom");
579        let cm = TransactionCostModel::ZERO;
580        // We want to end with imbalance[custom] = 7 (e.g. a carried-over offer),
581        // starting from 0 and with one custom coin of exactly 7.
582        let recipe = balance(BalanceRequest {
583            coins: vec![SimpleCoin::new(custom.clone(), 7)],
584            initial_imbalances: Imbalances::new(),
585            target_imbalances: Imbalances::from_entry(custom.clone(), 7),
586            cost_model: cm,
587            fee_token: native(),
588            selector: &SmallestFirstSelector,
589            create_output: |r| SimpleCoin::new(r.token_type, r.value),
590            is_coin_equal: |a, b| a == b,
591        })
592        .unwrap();
593        // The coin is added as input (imbalance goes 0 → 7 = target), no output.
594        assert_eq!(recipe.inputs.len(), 1);
595        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
596    }
597
598    /// TS: "Errors if there are no tokens to meet target imbalances" — target
599    /// requires a non-fee token we don't hold; balancer reports that token in
600    /// the error.
601    #[test]
602    fn ts_errors_when_cannot_meet_target() {
603        let unobtainium = TokenType::new("unobtainium");
604        let cm = TransactionCostModel::ZERO;
605        let err = balance(BalanceRequest {
606            coins: vec![coin(NATIVE, 1_000_000)],
607            initial_imbalances: Imbalances::new(),
608            target_imbalances: Imbalances::from_entry(unobtainium.clone(), 1),
609            cost_model: cm,
610            fee_token: native(),
611            selector: &SmallestFirstSelector,
612            create_output: |r| SimpleCoin::new(r.token_type, r.value),
613            is_coin_equal: |a, b| a == b,
614        })
615        .unwrap_err();
616        match err {
617            WalletError::InsufficientFunds { token } => {
618                assert_eq!(token, unobtainium.as_str());
619            }
620            other => panic!("wrong error: {other:?}"),
621        }
622    }
623
624    /// Invariant: every input in the recipe comes from the original candidate
625    /// pool — the balancer never synthesizes coins.
626    #[test]
627    fn invariant_inputs_subset_of_candidate_pool() {
628        let cm = TransactionCostModel::ZERO;
629        let pool: Vec<SimpleCoin> = (1..=10).map(|v| coin(NATIVE, v * 10)).collect();
630        let recipe = balance_test(pool.clone(), Imbalances::from_entry(native(), -55), cm).unwrap();
631        for inp in &recipe.inputs {
632            assert!(
633                pool.contains(inp),
634                "input {inp:?} not in original candidate pool"
635            );
636        }
637    }
638
639    /// Invariant: after balancing, every non-fee target is met exactly.
640    /// Models the key assertion from the TS "Reaches target imbalances" fuzz test.
641    #[test]
642    fn invariant_non_fee_targets_met_exactly() {
643        let custom_a = TokenType::new("custom_a");
644        let custom_b = TokenType::new("custom_b");
645        let cm = TransactionCostModel::ZERO;
646        let coins = vec![
647            SimpleCoin::new(custom_a.clone(), 100),
648            SimpleCoin::new(custom_b.clone(), 50),
649            SimpleCoin::new(custom_b.clone(), 50),
650            coin(NATIVE, 1_000),
651        ];
652        let target = Imbalances::from_entries([(custom_a.clone(), 30), (custom_b.clone(), 25)]);
653        let recipe = balance(BalanceRequest {
654            coins,
655            initial_imbalances: Imbalances::new(),
656            target_imbalances: target.clone(),
657            cost_model: cm,
658            fee_token: native(),
659            selector: &SmallestFirstSelector,
660            create_output: |r| SimpleCoin::new(r.token_type, r.value),
661            is_coin_equal: |a, b| a == b,
662        })
663        .unwrap();
664
665        // Reconstruct net imbalance from recipe and assert it matches target
666        // for every non-fee token.
667        let mut net = Imbalances::new();
668        for c in &recipe.inputs {
669            net.set(c.token_type.clone(), net.get(&c.token_type) + c.value);
670        }
671        for c in &recipe.outputs {
672            net.set(c.token_type.clone(), net.get(&c.token_type) - c.value);
673        }
674        for (token, expected) in target.iter() {
675            assert_eq!(net.get(token), expected, "token {token:?}: target not met");
676        }
677    }
678}