moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Midnight coin-balancer — the greedy + counter-offer loop used by all
//! three sub-wallets (shielded, unshielded, dust) to resolve a partially
//! specified transaction into a concrete (inputs, outputs) recipe.
//!
//! Ported from `@midnight-ntwrk/wallet-sdk-capabilities/balancer`. Algorithm:
//!
//! 1. Seed a [`CounterOffer`] with the caller's initial imbalances (typically
//!    negative entries for each intended recipient output).
//! 2. While any non-fee token is off-target: either produce a change output
//!    (if excess exceeds target) or pick an input coin via a pluggable
//!    [`CoinSelector`].
//! 3. Repeat step 2 for the fee (native) token.
//! 4. Emit the accumulated `(inputs, outputs)` as a [`BalanceRecipe`].
//!
//! **Performance.** The default coin selector is a single-pass
//! `Iterator::min_by_key` — no intermediate `Vec` allocation, no sort.
//! Input removal after selection uses `Vec::swap_remove` when the caller
//! supplies `is_coin_equal` so we avoid `O(n)` shifts from `retain`.

mod counter_offer;
mod imbalances;

use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};

pub use counter_offer::{CounterOffer, ImbalanceView, OutputRecipe};
pub use imbalances::Imbalances;

/// Pluggable coin-selection strategy. The balancer calls this each time it
/// needs to pull an input to close a deficit.
///
/// Callers must return a coin whose `token_type()` matches `token`. Returning
/// `None` means "no suitable coin available" and will bubble up as
/// [`WalletError::InsufficientFunds`].
pub trait CoinSelector<T: CoinRecipe> {
    fn select(
        &self,
        coins: &[T],
        token: &TokenType,
        amount_needed: Amount,
        cost_model: &TransactionCostModel,
    ) -> Option<usize>;
}

/// Default coin selector — greedy smallest-first matching `token`.
///
/// Returns the index (in `coins`) of the smallest coin of the requested
/// `token` type, or `None` if none exist. `amount_needed` is ignored: the
/// outer loop will keep pulling coins until the imbalance closes, which
/// naturally degenerates into consuming progressively larger coins as
/// needed without needing a knapsack.
pub struct SmallestFirstSelector;

impl<T: CoinRecipe> CoinSelector<T> for SmallestFirstSelector {
    fn select(
        &self,
        coins: &[T],
        token: &TokenType,
        _amount_needed: Amount,
        _cost_model: &TransactionCostModel,
    ) -> Option<usize> {
        coins
            .iter()
            .enumerate()
            .filter(|(_, c)| c.token_type() == token)
            .min_by_key(|(_, c)| c.value())
            .map(|(i, _)| i)
    }
}

/// Ledger 9 time-to-dismiss-aware coin selector: minimizes the number
/// of spent inputs (and therefore signature / proof verification cost
/// in `cost_to_dismiss`).
///
/// - When at least one matching coin covers `amount_needed` on its own,
///   picks the **smallest** such coin (1 input, minimal change).
/// - Otherwise picks the **largest** matching coin so the outer balance
///   loop converges in the fewest possible inputs.
pub struct FewestCoinsSelector;

impl<T: CoinRecipe> CoinSelector<T> for FewestCoinsSelector {
    fn select(
        &self,
        coins: &[T],
        token: &TokenType,
        amount_needed: Amount,
        _cost_model: &TransactionCostModel,
    ) -> Option<usize> {
        if amount_needed > Amount::ZERO {
            if let Some((idx, _)) = coins
                .iter()
                .enumerate()
                .filter(|(_, c)| c.token_type() == token && c.value() >= amount_needed)
                .min_by_key(|(_, c)| c.value())
            {
                return Some(idx);
            }
        }
        coins
            .iter()
            .enumerate()
            .filter(|(_, c)| c.token_type() == token)
            .max_by_key(|(_, c)| c.value())
            .map(|(i, _)| i)
    }
}

/// Result of a balancing operation — the concrete inputs to spend and
/// outputs to produce. Shielded / unshielded / dust wallets each wrap this
/// into their domain-specific recipe.
#[derive(Debug, Clone)]
pub struct BalanceRecipe<TInput, TOutput> {
    pub inputs: Vec<TInput>,
    pub outputs: Vec<TOutput>,
}

/// Arguments to [`balance`]. Grouped into a struct to keep call sites
/// readable — there's no meaningful default for most of these fields.
pub struct BalanceRequest<'a, TInput, TOutput, S, F>
where
    TInput: CoinRecipe + Clone,
    TOutput: CoinRecipe,
    S: CoinSelector<TInput>,
    F: FnMut(OutputRecipe) -> TOutput,
{
    /// Candidate input coins. The balancer removes selected coins from this
    /// pool (via `swap_remove`) as it goes.
    pub coins: Vec<TInput>,
    /// Starting imbalances — typically `-value` for each intended recipient.
    pub initial_imbalances: Imbalances,
    /// What each token should end up at. Usually empty (all zeros).
    pub target_imbalances: Imbalances,
    /// Per-input / per-output fee overheads in the fee token.
    pub cost_model: TransactionCostModel,
    /// Which token pays fees (native / DUST on Midnight mainnet).
    pub fee_token: TokenType,
    /// Strategy for choosing the next input.
    pub selector: &'a S,
    /// Callback that turns a raw (token, value) into a domain output.
    pub create_output: F,
    /// Two inputs are considered the same coin iff this returns true. Used
    /// to remove selected coins from the candidate pool.
    pub is_coin_equal: fn(&TInput, &TInput) -> bool,
}

/// Balance a transaction. Returns selected inputs and produced outputs, or
/// [`WalletError::InsufficientFunds`] if no coin can close a deficit.
pub fn balance<TInput, TOutput, S, F>(
    request: BalanceRequest<'_, TInput, TOutput, S, F>,
) -> Result<BalanceRecipe<TInput, TOutput>>
where
    TInput: CoinRecipe + Clone,
    TOutput: CoinRecipe,
    S: CoinSelector<TInput>,
    F: FnMut(OutputRecipe) -> TOutput,
{
    let BalanceRequest {
        mut coins,
        initial_imbalances,
        target_imbalances,
        cost_model,
        fee_token,
        selector,
        mut create_output,
        is_coin_equal,
    } = request;

    let mut counter_offer = CounterOffer::<TInput, TOutput>::new(
        initial_imbalances,
        target_imbalances,
        cost_model,
        fee_token,
    );

    // Phase 1: non-native tokens. The fields are copied out so the loop
    // body can mutate `counter_offer` freely.
    while let Some((token, value)) = counter_offer
        .find_non_native_imbalance()
        .map(|v| (v.token.clone(), v.value))
    {
        coins = settle_token(
            &token,
            value,
            coins,
            &mut counter_offer,
            selector,
            &mut create_output,
            is_coin_equal,
        )?;
    }

    // Phase 2: fee (native) token.
    while let Some((token, value)) = counter_offer
        .find_native_imbalance()
        .map(|v| (v.token.clone(), v.value))
    {
        coins = settle_token(
            &token,
            value,
            coins,
            &mut counter_offer,
            selector,
            &mut create_output,
            is_coin_equal,
        )?;
    }

    let (inputs, outputs) = counter_offer.into_recipe();
    Ok(BalanceRecipe { inputs, outputs })
}

/// One iteration of the outer loop: either add a change output (if we have
/// enough excess) or pull an input (if we're short).
fn settle_token<TInput, TOutput, S, F>(
    token: &TokenType,
    imbalance_amount: Amount,
    coins: Vec<TInput>,
    counter_offer: &mut CounterOffer<TInput, TOutput>,
    selector: &S,
    create_output: &mut F,
    is_coin_equal: fn(&TInput, &TInput) -> bool,
) -> Result<Vec<TInput>>
where
    TInput: CoinRecipe + Clone,
    TOutput: CoinRecipe,
    S: CoinSelector<TInput>,
    F: FnMut(OutputRecipe) -> TOutput,
{
    let target = counter_offer.target_for(token);
    let cost = counter_offer.cost_model().output_fee_overhead;
    let is_fee_token = token == counter_offer.fee_token();

    let should_add_output = if is_fee_token {
        imbalance_amount >= target + cost
    } else {
        imbalance_amount > target
    };

    if should_add_output {
        counter_offer.add_output(token, imbalance_amount - target, |tok, net_value| {
            (create_output)(OutputRecipe {
                token_type: tok,
                value: net_value,
            })
        });
        Ok(coins)
    } else {
        let Some(idx) =
            selector.select(&coins, token, imbalance_amount, counter_offer.cost_model())
        else {
            return Err(WalletError::InsufficientFunds {
                token: token.to_string(),
            });
        };

        let mut coins = coins;
        let picked = coins.swap_remove(idx);
        // Guard against duplicate entries of the same coin in the source
        // pool — remove any other copies that match.
        coins.retain(|c| !is_coin_equal(c, &picked));
        counter_offer.add_input(picked);
        Ok(coins)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::SimpleCoin;

    const NATIVE: &str = "native";
    const OTHER: &str = "other";

    fn native() -> TokenType {
        TokenType::new(NATIVE)
    }
    fn other() -> TokenType {
        TokenType::new(OTHER)
    }

    fn coin(token: &str, value: impl Into<Amount>) -> SimpleCoin {
        SimpleCoin::new(token, value)
    }

    fn default_cost_model() -> TransactionCostModel {
        TransactionCostModel::new(19_314, 19_708)
    }

    fn balance_test(
        coins: Vec<SimpleCoin>,
        initial_imbalances: Imbalances,
        cost_model: TransactionCostModel,
    ) -> Result<BalanceRecipe<SimpleCoin, SimpleCoin>> {
        balance(BalanceRequest {
            coins,
            initial_imbalances,
            target_imbalances: Imbalances::new(),
            cost_model,
            fee_token: native(),
            selector: &SmallestFirstSelector,
            create_output: |rec| SimpleCoin::new(rec.token_type, rec.value),
            is_coin_equal: |a, b| a == b,
        })
    }

    #[test]
    fn nothing_to_balance() {
        let recipe = balance_test(vec![], Imbalances::new(), TransactionCostModel::ZERO).unwrap();
        assert_eq!(recipe.inputs, [] as [SimpleCoin; 0]);
        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
    }

    #[test]
    fn uses_exactly_one_coin_when_value_matches_with_fee() {
        let cm = default_cost_model();
        let exact = coin(NATIVE, Amount::from(1_000) + cm.input_fee_overhead);
        let recipe = balance_test(
            vec![exact.clone()],
            Imbalances::from_entry(native(), -1_000),
            cm,
        )
        .unwrap();
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(recipe.inputs[0], exact);
        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
    }

    #[test]
    fn insufficient_funds_reports_correct_token() {
        let err = balance_test(
            vec![coin(NATIVE, 10)],
            Imbalances::from_entry(native(), -1_000_000),
            TransactionCostModel::ZERO,
        )
        .unwrap_err();
        match err {
            WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
            other => panic!("wrong error: {other:?}"),
        }
    }

    #[test]
    fn no_overspend_when_exact_coin_exists() {
        // Several large native coins available; deficit is small; only one
        // should be consumed and the excess returned as change.
        let cm = TransactionCostModel::ZERO;
        let coins = vec![coin(NATIVE, 100), coin(NATIVE, 100)];
        let recipe = balance_test(coins, Imbalances::from_entry(native(), -10), cm).unwrap();
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(recipe.outputs.len(), 1);
        assert_eq!(recipe.outputs[0].value, Amount::from(90));
        assert_eq!(recipe.outputs[0].token_type, native());
    }

    #[test]
    fn multi_token_balance_closes_both() {
        // Need 100 OTHER and 500 NATIVE. Pool has enough of both.
        let cm = TransactionCostModel::ZERO;
        let coins = vec![
            coin(OTHER, 150),  // covers OTHER with change
            coin(NATIVE, 500), // covers NATIVE exactly
        ];
        let initial = Imbalances::from_entries([(other(), -100), (native(), -500)]);
        let recipe = balance_test(coins, initial, cm).unwrap();

        assert_eq!(recipe.inputs.len(), 2);
        assert!(recipe.inputs.iter().any(|c| c.token_type == other()));
        assert!(recipe.inputs.iter().any(|c| c.token_type == native()));
        // OTHER had 50 excess that must come back as a change output.
        assert_eq!(recipe.outputs.len(), 1);
        assert_eq!(recipe.outputs[0].token_type, other());
        assert_eq!(recipe.outputs[0].value, Amount::from(50));
    }

    #[test]
    fn smallest_first_selector_picks_min_coin() {
        let coins = vec![coin(NATIVE, 100), coin(NATIVE, 5), coin(NATIVE, 50)];
        let idx = SmallestFirstSelector.select(
            &coins,
            &native(),
            Amount::from(10),
            &TransactionCostModel::ZERO,
        );
        assert_eq!(idx, Some(1));
    }

    #[test]
    fn smallest_first_selector_ignores_wrong_tokens() {
        let coins = vec![coin(OTHER, 1), coin(NATIVE, 100), coin(OTHER, 2)];
        let idx = SmallestFirstSelector.select(
            &coins,
            &native(),
            Amount::from(10),
            &TransactionCostModel::ZERO,
        );
        assert_eq!(idx, Some(1));
    }

    #[test]
    fn fee_token_output_emitted_when_excess_exceeds_overhead() {
        // Input fee 10, output fee 20. Deficit 100, coin 200.
        // After input: imbalance = -100 + 200 - 10 = 90. 90 >= 20 → emit output.
        // Recorded output has face value (absolute - output_fee) = 90 - 20 = 70.
        let cm = TransactionCostModel::new(10, 20);
        let coins = vec![coin(NATIVE, 200)];
        let recipe = balance_test(coins, Imbalances::from_entry(native(), -100), cm).unwrap();
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(recipe.outputs.len(), 1);
        assert_eq!(recipe.outputs[0].value, Amount::from(70));
    }

    #[test]
    fn excess_below_output_overhead_cannot_be_balanced() {
        // When a native imbalance is too small to justify a change output
        // (excess < output_fee_overhead) AND no more coins are available to
        // absorb it, the balancer must bubble InsufficientFunds — silently
        // leaking the excess as extra fee would be a correctness bug.
        let cm = TransactionCostModel::new(10, 20);
        // Coin(115): after input fee, credit = 105. Deficit 100 → excess 5.
        // 5 < 20 (output overhead) and no other coins → error.
        let err = balance_test(
            vec![coin(NATIVE, 115)],
            Imbalances::from_entry(native(), -100),
            cm,
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    // --- Ports of TS Balancer.test.ts test cases ---------------------

    /// TS: "Does not overspend coins" — with two available coins and a small
    /// deficit, exactly one input should be consumed and change returned.
    #[test]
    fn ts_does_not_overspend_coins() {
        let cm = TransactionCostModel::new(19_314, 19_708);
        let coins = vec![coin(NATIVE, 10_000_000), coin(NATIVE, 10_000_000)];
        let recipe = balance_test(coins, Imbalances::from_entry(native(), -1_000_000), cm).unwrap();
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(recipe.outputs.len(), 1);
    }

    /// TS: "Balance custom native token" — deficit on a custom token uses
    /// two inputs (custom + fee) and emits one change output.
    #[test]
    fn ts_balance_custom_token() {
        let custom = TokenType::new("custom");
        let cm = TransactionCostModel::new(19_314, 19_708);
        // Custom deficit 1, three small custom coins (1, 2, 3), one big native
        // coin to cover fees.
        let coins = vec![
            coin(NATIVE, 100_000_000),
            SimpleCoin::new(custom.clone(), 1),
            SimpleCoin::new(custom.clone(), 2),
            SimpleCoin::new(custom.clone(), 3),
        ];
        let recipe = balance_test(coins, Imbalances::from_entry(custom, -1), cm).unwrap();
        assert_eq!(recipe.inputs.len(), 2);
        assert_eq!(recipe.outputs.len(), 1);
    }

    /// TS: "Balance multiple token types" — duplicate-key entries in
    /// `from_entries` must sum per token (matching TS `fromEntries` semantics).
    #[test]
    fn ts_balance_multiple_token_types() {
        let custom = TokenType::new("custom");
        let cm = TransactionCostModel::new(19_314, 19_708);
        let coins = vec![
            coin(NATIVE, 10_000_000),
            coin(NATIVE, 20_000_000),
            coin(NATIVE, 30_000_000),
            SimpleCoin::new(custom.clone(), 1),
            SimpleCoin::new(custom.clone(), 2),
            SimpleCoin::new(custom.clone(), 3),
        ];
        // Two entries per token — from_entries must sum them: custom=-5, native=-6M.
        let initial = Imbalances::from_entries([
            (custom.clone(), -4),
            (native(), -5_000_000),
            (native(), -1_000_000),
            (custom.clone(), -1),
        ]);
        let recipe = balance_test(coins, initial, cm).unwrap();
        assert_eq!(recipe.inputs.len(), 4);
        assert_eq!(recipe.outputs.len(), 2);
    }

    /// TS: "Fail if there aren't enough coins to cover the fees" — a single
    /// native coin with value exactly equal to the deficit leaves nothing for
    /// the input fee overhead.
    #[test]
    fn ts_fail_when_not_enough_for_fees() {
        let cm = TransactionCostModel::new(19_314, 19_708);
        let err = balance_test(
            vec![coin(NATIVE, 1_000_000)],
            Imbalances::from_entry(native(), -1_000_000),
            cm,
        )
        .unwrap_err();
        match err {
            WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
            other => panic!("wrong error: {other:?}"),
        }
    }

    /// TS: "Fail if the change output value is smaller than the output fee" —
    /// after selecting inputs, the leftover would be positive but not enough
    /// to cover an output fee overhead.
    #[test]
    fn ts_fail_when_change_smaller_than_output_fee() {
        let cm = TransactionCostModel::new(19_314, 19_708);
        // Coin value exactly input_fee + 5 → credits 5 to imbalance.
        // Deficit is -(5 + output_fee) → net excess 5 after input, can't mint
        // an output smaller than output_fee.
        let coin_val = cm.input_fee_overhead + Amount::from(5);
        let deficit = -(Amount::from(5) + cm.output_fee_overhead);
        let err = balance_test(
            vec![coin(NATIVE, coin_val)],
            Imbalances::from_entry(native(), deficit),
            cm,
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    /// TS: "Uses provided coin selection" — a custom selector (e.g. by-id
    /// ordering) should be honored.
    #[test]
    fn ts_uses_provided_coin_selection() {
        // Selector that picks the largest-valued matching coin first — opposite
        // of the default smallest-first. This proves the plug-in works.
        struct LargestFirst;
        impl<T: CoinRecipe> CoinSelector<T> for LargestFirst {
            fn select(
                &self,
                coins: &[T],
                token: &TokenType,
                _: Amount,
                _: &TransactionCostModel,
            ) -> Option<usize> {
                coins
                    .iter()
                    .enumerate()
                    .filter(|(_, c)| c.token_type() == token)
                    .max_by_key(|(_, c)| c.value())
                    .map(|(i, _)| i)
            }
        }

        let cm = TransactionCostModel::ZERO;
        let coins = vec![coin(NATIVE, 5), coin(NATIVE, 50), coin(NATIVE, 100)];
        let recipe = balance(BalanceRequest {
            coins,
            initial_imbalances: Imbalances::from_entry(native(), -40),
            target_imbalances: Imbalances::new(),
            cost_model: cm,
            fee_token: native(),
            selector: &LargestFirst,
            create_output: |r| SimpleCoin::new(r.token_type, r.value),
            is_coin_equal: |a, b| a == b,
        })
        .unwrap();
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(
            recipe.inputs[0].value,
            Amount::from(100),
            "largest-first should pick 100"
        );
        assert_eq!(recipe.outputs.len(), 1);
        assert_eq!(recipe.outputs[0].value, Amount::from(60));
    }

    /// TS: "Reaches target imbalances" — a non-empty `target_imbalances` means
    /// the balancer should leave those specific non-fee balances on the table
    /// instead of balancing them to zero.
    #[test]
    fn ts_reaches_target_imbalances() {
        let custom = TokenType::new("custom");
        let cm = TransactionCostModel::ZERO;
        // We want to end with imbalance[custom] = 7 (e.g. a carried-over offer),
        // starting from 0 and with one custom coin of exactly 7.
        let recipe = balance(BalanceRequest {
            coins: vec![SimpleCoin::new(custom.clone(), 7)],
            initial_imbalances: Imbalances::new(),
            target_imbalances: Imbalances::from_entry(custom.clone(), 7),
            cost_model: cm,
            fee_token: native(),
            selector: &SmallestFirstSelector,
            create_output: |r| SimpleCoin::new(r.token_type, r.value),
            is_coin_equal: |a, b| a == b,
        })
        .unwrap();
        // The coin is added as input (imbalance goes 0 → 7 = target), no output.
        assert_eq!(recipe.inputs.len(), 1);
        assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
    }

    /// TS: "Errors if there are no tokens to meet target imbalances" — target
    /// requires a non-fee token we don't hold; balancer reports that token in
    /// the error.
    #[test]
    fn ts_errors_when_cannot_meet_target() {
        let unobtainium = TokenType::new("unobtainium");
        let cm = TransactionCostModel::ZERO;
        let err = balance(BalanceRequest {
            coins: vec![coin(NATIVE, 1_000_000)],
            initial_imbalances: Imbalances::new(),
            target_imbalances: Imbalances::from_entry(unobtainium.clone(), 1),
            cost_model: cm,
            fee_token: native(),
            selector: &SmallestFirstSelector,
            create_output: |r| SimpleCoin::new(r.token_type, r.value),
            is_coin_equal: |a, b| a == b,
        })
        .unwrap_err();
        match err {
            WalletError::InsufficientFunds { token } => {
                assert_eq!(token, unobtainium.as_str());
            }
            other => panic!("wrong error: {other:?}"),
        }
    }

    /// Invariant: every input in the recipe comes from the original candidate
    /// pool — the balancer never synthesizes coins.
    #[test]
    fn invariant_inputs_subset_of_candidate_pool() {
        let cm = TransactionCostModel::ZERO;
        let pool: Vec<SimpleCoin> = (1..=10).map(|v| coin(NATIVE, v * 10)).collect();
        let recipe = balance_test(pool.clone(), Imbalances::from_entry(native(), -55), cm).unwrap();
        for inp in &recipe.inputs {
            assert!(
                pool.contains(inp),
                "input {inp:?} not in original candidate pool"
            );
        }
    }

    /// Invariant: after balancing, every non-fee target is met exactly.
    /// Models the key assertion from the TS "Reaches target imbalances" fuzz test.
    #[test]
    fn invariant_non_fee_targets_met_exactly() {
        let custom_a = TokenType::new("custom_a");
        let custom_b = TokenType::new("custom_b");
        let cm = TransactionCostModel::ZERO;
        let coins = vec![
            SimpleCoin::new(custom_a.clone(), 100),
            SimpleCoin::new(custom_b.clone(), 50),
            SimpleCoin::new(custom_b.clone(), 50),
            coin(NATIVE, 1_000),
        ];
        let target = Imbalances::from_entries([(custom_a.clone(), 30), (custom_b.clone(), 25)]);
        let recipe = balance(BalanceRequest {
            coins,
            initial_imbalances: Imbalances::new(),
            target_imbalances: target.clone(),
            cost_model: cm,
            fee_token: native(),
            selector: &SmallestFirstSelector,
            create_output: |r| SimpleCoin::new(r.token_type, r.value),
            is_coin_equal: |a, b| a == b,
        })
        .unwrap();

        // Reconstruct net imbalance from recipe and assert it matches target
        // for every non-fee token.
        let mut net = Imbalances::new();
        for c in &recipe.inputs {
            net.set(c.token_type.clone(), net.get(&c.token_type) + c.value);
        }
        for c in &recipe.outputs {
            net.set(c.token_type.clone(), net.get(&c.token_type) - c.value);
        }
        for (token, expected) in target.iter() {
            assert_eq!(net.get(token), expected, "token {token:?}: target not met");
        }
    }
}