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
//! Building blocks for unshielded (public) transactions.
//!
//! Port of the pure-logic half of
//! `@midnight-ntwrk/wallet-sdk-unshielded-wallet/v1/Transacting.ts`. This layer
//! produces a [`TransferRecipe`] — a typed description of which UTXOs to spend
//! and which outputs to produce, *including* change back to the sender. It's
//! fully testable without any ledger or chain state.
//!
//! The ledger adapter ([`crate::unshielded::ledger_adapter`]) consumes a [`TransferRecipe`]
//! and assembles a `moonproof_ledger::ledger::Intent<(), ProofPreimageMarker,
//! PedersenRandomness, D>` — the unsigned Intent shape that the prover and
//! signer work against. Splitting those two responsibilities keeps the core
//! balancer + selection logic unit-testable, and isolates the midnight-ledger
//! generic-type dance to one thin adapter.
//!
//! # Fee semantics
//!
//! Each recipient output incurs an `output_fee_overhead` chain fee paid in
//! the fee token. We account for those fees in the initial imbalance that we
//! feed the balancer, so the returned `inputs` cover *everything* — recipient
//! outputs, their fees, and the `input_fee_overhead` per input.
//!
//! Recipient outputs are produced with face value equal to the caller's
//! specified `amount`. Matches the TS reference: for non-fee tokens the
//! recipient gets the full amount and the fee is charged separately against
//! the fee token; for fee-token recipient outputs, the fee is baked in so the
//! recipient nets `amount - output_fee_overhead` on the wire (same as change
//! outputs).

use crate::balancer::{balance, BalanceRequest, FewestCoinsSelector, Imbalances};
use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
use crate::unshielded::state::{UnshieldedState, UtxoWithMeta};

/// One "send `amount` of `token` to `recipient`" instruction.
///
/// Matches `TokenTransfer` from the TS reference. `amount` is the output's
/// face value — i.e. what the caller wants to put on chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedTransfer {
    pub amount: u128,
    pub token_type: TokenType,
    /// 32-byte unshielded user address (recipient's public key hash).
    pub recipient: [u8; 32],
}

impl UnshieldedTransfer {
    #[inline]
    #[must_use]
    pub fn new(amount: u128, token_type: TokenType, recipient: [u8; 32]) -> Self {
        Self {
            amount,
            token_type,
            recipient,
        }
    }
}

/// A concrete output spec — (value, token, owner) — ready for the ledger
/// adapter to turn into a `moonproof_ledger::ledger::UtxoOutput`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedOutputSpec {
    pub value: u128,
    pub token_type: TokenType,
    /// 32-byte user address of the output's owner.
    pub owner: [u8; 32],
}

impl UnshieldedOutputSpec {
    #[inline]
    #[must_use]
    pub fn new(value: u128, token_type: TokenType, owner: [u8; 32]) -> Self {
        Self {
            value,
            token_type,
            owner,
        }
    }
}

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

/// Output of [`build_transfer_recipe`] — the concrete plan for an unshielded
/// transfer. Three disjoint sections:
///
/// - `inputs`: UTXOs we'll spend (matched against wallet state).
/// - `recipient_outputs`: outputs we produce for the caller-specified
///   destinations, in the same order as the incoming `transfers` argument.
/// - `change_outputs`: outputs the balancer emitted to absorb excess; their
///   owner is always the sender.
///
/// The ledger-Intent adapter concatenates `recipient_outputs` and
/// `change_outputs` when assembling the `UnshieldedOffer`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRecipe {
    pub inputs: Vec<UtxoWithMeta>,
    pub recipient_outputs: Vec<UnshieldedOutputSpec>,
    pub change_outputs: Vec<UnshieldedOutputSpec>,
}

impl TransferRecipe {
    /// Total inputs + outputs for the ledger adapter — recipient outputs
    /// first (so their indices line up with the caller's `transfers` slice),
    /// change outputs second.
    #[must_use]
    pub fn all_outputs(&self) -> Vec<&UnshieldedOutputSpec> {
        let mut out = Vec::with_capacity(self.recipient_outputs.len() + self.change_outputs.len());
        for o in &self.recipient_outputs {
            out.push(o);
        }
        for o in &self.change_outputs {
            out.push(o);
        }
        out
    }

    /// Count of all produced outputs.
    #[inline]
    #[must_use]
    pub fn total_output_count(&self) -> usize {
        self.recipient_outputs.len() + self.change_outputs.len()
    }
}

/// Compute the initial imbalances the balancer should start from for a
/// given set of transfers. Pulled into its own function because the
/// accounting is subtle enough to test in isolation.
fn initial_imbalances(
    transfers: &[UnshieldedTransfer],
    fee_token: &TokenType,
    cost_model: &TransactionCostModel,
) -> Result<Imbalances> {
    let mut initial = Imbalances::new();
    for t in transfers {
        let amount = Amount::from(t.amount);

        // Face value leaves our side: decrement imbalance[token] by amount.
        let cur = initial.get(&t.token_type);
        initial.set(
            t.token_type.clone(),
            cur.checked_sub(amount).ok_or(WalletError::AmountOverflow)?,
        );

        // Every produced output pays the output_fee_overhead in fee token.
        // For fee-token outputs, the TS reference bakes this into the face
        // value via the balancer's addOutput; for *user-specified* recipient
        // outputs we emit the full `amount` face (so the recipient nets
        // `amount - output_fee_overhead` if it's a fee-token output), and the
        // fee-token imbalance naturally absorbs the shortfall because we
        // only debit it by `amount` here. For non-fee tokens we debit the
        // output overhead explicitly so the balancer pulls enough native to
        // cover it.
        if t.token_type != *fee_token {
            let cur_fee = initial.get(fee_token);
            initial.set(
                fee_token.clone(),
                cur_fee
                    .checked_sub(cost_model.output_fee_overhead)
                    .ok_or(WalletError::AmountOverflow)?,
            );
        }
    }
    Ok(initial)
}

/// Build an unshielded transfer recipe.
///
/// - `state`: the wallet's `UnshieldedState` — only `available` UTXOs are
///   considered as candidate inputs.
/// - `sender_address`: where change outputs are sent.
/// - `transfers`: the caller's (recipient, amount, token) list.
/// - `fee_token`: which token pays fees (typically the native / dust token).
/// - `cost_model`: per-input / per-output fee overheads.
///
/// Returns a [`TransferRecipe`] or `WalletError::InsufficientFunds` /
/// `WalletError::AmountOverflow`.
pub fn build_transfer_recipe(
    state: &UnshieldedState,
    sender_address: [u8; 32],
    transfers: &[UnshieldedTransfer],
    fee_token: TokenType,
    cost_model: TransactionCostModel,
) -> Result<TransferRecipe> {
    // Assemble recipient outputs first so recipe order matches `transfers`.
    let recipient_outputs: Vec<UnshieldedOutputSpec> = transfers
        .iter()
        .map(|t| UnshieldedOutputSpec::new(t.amount, t.token_type.clone(), t.recipient))
        .collect();

    let initial = initial_imbalances(transfers, &fee_token, &cost_model)?;

    // Clone the available set — the balancer removes selected coins from
    // its working pool and we don't want to mutate wallet state here.
    let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();

    let change_owner = sender_address;
    let br = balance(BalanceRequest {
        coins,
        initial_imbalances: initial,
        target_imbalances: Imbalances::new(),
        cost_model,
        fee_token,
        selector: &FewestCoinsSelector,
        create_output: move |r| {
            // Balancer hands us signed Amount; clamp to u128 defensively.
            let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
            UnshieldedOutputSpec::new(v, r.token_type, change_owner)
        },
        is_coin_equal: |a, b| a.id() == b.id(),
    })?;

    Ok(TransferRecipe {
        inputs: br.inputs,
        recipient_outputs,
        change_outputs: br.outputs,
    })
}

/// Build an unshielded swap-init recipe.
///
/// Mirrors midnight-wallet's `unshielded.initSwap`: the wallet commits
/// inputs worth exactly `desired_inputs` (change returns to
/// `sender_address`) and lists `desired_outputs` without funding them.
/// Both sides are left for the counterparty to close, so the resulting
/// intent is intentionally unbalanced: a surplus of `desired_inputs`
/// and a deficit of `desired_outputs`.
///
/// Returns a [`TransferRecipe`] whose `inputs` and `change_outputs`
/// cover `desired_inputs` alone, and whose `recipient_outputs` are the
/// dApp's `desired_outputs`.
pub fn build_init_swap_recipe(
    state: &UnshieldedState,
    sender_address: [u8; 32],
    desired_inputs: &[(TokenType, u128)],
    desired_outputs: &[UnshieldedTransfer],
    fee_token: TokenType,
    cost_model: TransactionCostModel,
) -> Result<TransferRecipe> {
    use crate::balancer::OutputRecipe;

    if desired_inputs.is_empty() && desired_outputs.is_empty() {
        return Err(WalletError::SigningFailed(
            "initSwap requires at least one input or output".to_owned(),
        ));
    }
    for (_, amount) in desired_inputs {
        if *amount == 0 {
            return Err(WalletError::SigningFailed(
                "initSwap input amount must be positive".to_owned(),
            ));
        }
    }
    for t in desired_outputs {
        if t.amount == 0 {
            return Err(WalletError::SigningFailed(
                "initSwap output amount must be positive".to_owned(),
            ));
        }
    }

    let recipient_outputs: Vec<UnshieldedOutputSpec> = desired_outputs
        .iter()
        .map(|t| UnshieldedOutputSpec::new(t.amount, t.token_type.clone(), t.recipient))
        .collect();

    // Target imbalance: positive `desired_inputs` — wallet must
    // commit those amounts as inputs (the counterparty produces the
    // matching outputs on its leg). The desired outputs stay out of
    // the balance: the counterparty funds them.
    let target = Imbalances::from_entries(
        desired_inputs
            .iter()
            .map(|(t, v)| (t.clone(), Amount::from(*v))),
    );

    let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();
    let change_owner = sender_address;

    let br = balance(BalanceRequest {
        coins,
        initial_imbalances: Imbalances::new(),
        target_imbalances: target,
        cost_model,
        fee_token,
        selector: &FewestCoinsSelector,
        create_output: move |r: OutputRecipe| {
            let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
            UnshieldedOutputSpec::new(v, r.token_type, change_owner)
        },
        is_coin_equal: |a, b| a.id() == b.id(),
    })?;

    Ok(TransferRecipe {
        inputs: br.inputs,
        recipient_outputs,
        change_outputs: br.outputs,
    })
}

/// The inputs and change outputs that bring one segment of someone
/// else's transaction to zero: a deficit pulls this wallet's UTXOs, a
/// surplus (and the change of every input) comes back to `owner`.
/// Mirrors the unshielded wallet's `#balanceSegment` in midnight-wallet,
/// with its zero cost model: unshielded fees are paid in Dust, so an
/// overhead here would burn NIGHT the chain then rejects.
///
/// Returns an empty recipe when `imbalances` is already zero.
pub fn build_balancing_recipe(
    state: &UnshieldedState,
    owner: [u8; 32],
    imbalances: Imbalances,
) -> Result<TransferRecipe> {
    let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();
    let br = balance(BalanceRequest {
        coins,
        initial_imbalances: imbalances,
        target_imbalances: Imbalances::new(),
        cost_model: TransactionCostModel::ZERO,
        fee_token: TokenType::new("native"),
        selector: &FewestCoinsSelector,
        create_output: move |r| {
            let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
            UnshieldedOutputSpec::new(v, r.token_type, owner)
        },
        is_coin_equal: |a, b| a.id() == b.id(),
    })?;
    Ok(TransferRecipe {
        inputs: br.inputs,
        recipient_outputs: Vec::new(),
        change_outputs: br.outputs,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unshielded::state::{UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta};

    const NATIVE: &str = "native";
    const CUSTOM: &str = "custom";

    const SENDER: [u8; 32] = [0xAA; 32];
    const RECIPIENT: [u8; 32] = [0xBB; 32];

    fn tok(s: &str) -> TokenType {
        TokenType::new(s)
    }

    fn utxo(intent_byte: u8, output_no: u32, value: u128, tt: &str) -> UtxoWithMeta {
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([intent_byte; 32], output_no),
                value,
                tok(tt),
                SENDER,
            ),
            UtxoMeta::new(0, false),
        )
    }

    fn seed(utxos: Vec<UtxoWithMeta>) -> UnshieldedState {
        UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(utxos, vec![]))
            .unwrap()
    }

    fn cm() -> TransactionCostModel {
        TransactionCostModel::new(1_000, 2_000)
    }

    // --- Happy-path balancing ------------------------------------------

    #[test]
    fn single_transfer_emits_recipient_output_and_pulls_inputs() {
        let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
        let transfers = vec![UnshieldedTransfer::new(500, tok(NATIVE), RECIPIENT)];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();

        assert_eq!(r.inputs.len(), 1);
        assert_eq!(r.recipient_outputs.len(), 1);
        // For fee-token transfers we don't add an extra fee overhead on the
        // output (it's baked in by the balancer-style addOutput semantics).
        assert_eq!(r.recipient_outputs[0].value, 500);
        assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
        // Huge input → change output for remainder.
        assert_eq!(r.change_outputs.len(), 1);
        assert_eq!(r.change_outputs[0].owner, SENDER);
    }

    #[test]
    fn non_fee_token_transfer_uses_two_inputs_one_for_fees() {
        let state = seed(vec![
            utxo(0x01, 0, 500, CUSTOM),
            utxo(0x02, 0, 100_000, NATIVE),
        ]);
        let transfers = vec![UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT)];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();

        // Need exactly the custom UTXO for the value + one native UTXO for fees.
        assert_eq!(r.inputs.len(), 2);
        let input_tokens: Vec<_> = r.inputs.iter().map(|u| u.utxo.token_type.clone()).collect();
        assert!(input_tokens.contains(&tok(CUSTOM)));
        assert!(input_tokens.contains(&tok(NATIVE)));

        assert_eq!(r.recipient_outputs.len(), 1);
        assert_eq!(r.recipient_outputs[0].value, 500);
        assert_eq!(r.recipient_outputs[0].token_type, tok(CUSTOM));
        assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);

        // Change: native leftover back to sender.
        assert_ne!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
        for c in &r.change_outputs {
            assert_eq!(c.owner, SENDER);
        }
    }

    #[test]
    fn multi_token_transfer_emits_one_recipient_output_per_transfer() {
        let state = seed(vec![
            utxo(0x01, 0, 500, CUSTOM),
            utxo(0x02, 0, 100_000, NATIVE),
        ]);
        let transfers = vec![
            UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT),
            UnshieldedTransfer::new(1_234, tok(NATIVE), [0xCC; 32]),
        ];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();

        assert_eq!(r.recipient_outputs.len(), 2);
        assert_eq!(r.recipient_outputs[0].value, 500);
        assert_eq!(r.recipient_outputs[0].token_type, tok(CUSTOM));
        assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
        assert_eq!(r.recipient_outputs[1].value, 1_234);
        assert_eq!(r.recipient_outputs[1].token_type, tok(NATIVE));
        assert_eq!(r.recipient_outputs[1].owner, [0xCC; 32]);
    }

    // --- Error paths ---------------------------------------------------

    #[test]
    fn insufficient_fee_token_errors_with_correct_token() {
        let state = seed(vec![utxo(0x01, 0, 500, CUSTOM)]);
        let transfers = vec![UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT)];
        let err = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap_err();
        match err {
            WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn insufficient_target_token_errors() {
        let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
        let transfers = vec![UnshieldedTransfer::new(1, tok(CUSTOM), RECIPIENT)];
        let err = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap_err();
        match err {
            WalletError::InsufficientFunds { token } => assert_eq!(token, CUSTOM),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn empty_transfer_list_produces_empty_recipe() {
        let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
        let r = build_transfer_recipe(&state, SENDER, &[], tok(NATIVE), cm()).unwrap();
        assert_eq!(r.inputs, [] as [UtxoWithMeta; 0]);
        assert_eq!(r.recipient_outputs, [] as [UnshieldedOutputSpec; 0]);
        assert_eq!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
    }

    // --- Invariants ----------------------------------------------------

    #[test]
    fn inputs_are_subset_of_wallet_available() {
        let state = seed(vec![
            utxo(0x01, 0, 1_000, NATIVE),
            utxo(0x02, 0, 2_000, NATIVE),
            utxo(0x03, 0, 50_000, NATIVE),
        ]);
        let transfers = vec![UnshieldedTransfer::new(500, tok(NATIVE), RECIPIENT)];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
        for inp in &r.inputs {
            assert!(state.has_available(&inp.id()));
        }
    }

    #[test]
    fn change_outputs_always_go_to_sender() {
        let state = seed(vec![utxo(0x01, 0, 1_000_000, NATIVE)]);
        let transfers = vec![UnshieldedTransfer::new(123, tok(NATIVE), RECIPIENT)];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
        for c in &r.change_outputs {
            assert_eq!(c.owner, SENDER, "change must always route back to sender");
        }
    }

    #[test]
    fn all_outputs_iter_returns_recipient_outputs_first_then_change() {
        let state = seed(vec![utxo(0x01, 0, 1_000_000, NATIVE)]);
        let transfers = vec![UnshieldedTransfer::new(123, tok(NATIVE), RECIPIENT)];
        let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
        let all = r.all_outputs();
        assert_eq!(all.len(), r.total_output_count());
        assert_eq!(
            all.len(),
            r.recipient_outputs.len() + r.change_outputs.len()
        );
        // First r.recipient_outputs.len() entries are the recipients.
        for (i, ro) in r.recipient_outputs.iter().enumerate() {
            assert_eq!(all[i], ro);
        }
    }

    // --- Imbalance helper unit tests ----------------------------------

    #[test]
    fn initial_imbalances_handles_fee_token_transfer() {
        let cm = TransactionCostModel::new(100, 200);
        let transfers = vec![UnshieldedTransfer::new(1_000, tok(NATIVE), RECIPIENT)];
        let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
        // Fee-token output: imbalance[fee] -= amount. No separate overhead
        // debit (balanced-in to face).
        assert_eq!(got.get(&tok(NATIVE)), Amount::from(-1_000));
    }

    #[test]
    fn initial_imbalances_handles_non_fee_token_transfer() {
        let cm = TransactionCostModel::new(100, 200);
        let transfers = vec![UnshieldedTransfer::new(1_000, tok(CUSTOM), RECIPIENT)];
        let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
        // Non-fee-token output: imbalance[token] -= amount, AND
        // imbalance[fee] -= output_fee_overhead.
        assert_eq!(got.get(&tok(CUSTOM)), Amount::from(-1_000));
        assert_eq!(got.get(&tok(NATIVE)), Amount::from(-200));
    }

    #[test]
    fn initial_imbalances_accumulates_across_transfers() {
        let cm = TransactionCostModel::new(100, 200);
        let transfers = vec![
            UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT),
            UnshieldedTransfer::new(700, tok(CUSTOM), RECIPIENT),
            UnshieldedTransfer::new(300, tok(NATIVE), RECIPIENT),
        ];
        let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
        assert_eq!(got.get(&tok(CUSTOM)), Amount::from(-1_200));
        // Two non-fee outputs each cost one output overhead, plus the
        // fee-token transfer's -300.
        assert_eq!(got.get(&tok(NATIVE)), Amount::from(-300 - 200 - 200));
    }

    #[test]
    fn initial_imbalances_lifts_full_u128_range() {
        // `Amount` is now `I256`, so a single transfer with `u128::MAX` lifts
        // cleanly into the imbalance map — the i128-era overflow path is
        // unreachable for any single u128 input by construction.
        let cm = TransactionCostModel::new(100, 200);
        let transfers = vec![UnshieldedTransfer::new(u128::MAX, tok(CUSTOM), RECIPIENT)];
        let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
        assert_eq!(got.get(&tok(CUSTOM)), -Amount::from(u128::MAX));
        assert_eq!(got.get(&tok(NATIVE)), Amount::from(-200));
    }

    // --- initSwap-style builder ---------------------------------------

    #[test]
    fn init_swap_pulls_input_for_target_imbalance() {
        // Wallet has 100 NATIVE; dApp's swap wants the wallet to commit
        // 30 NATIVE as inputs (counterparty fills the matching output
        // side via their own intent). No recipient outputs.
        let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
        let r = build_init_swap_recipe(
            &state,
            SENDER,
            &[(tok(NATIVE), 30)],
            &[],
            tok(NATIVE),
            TransactionCostModel::ZERO,
        )
        .unwrap();
        assert_eq!(r.inputs.len(), 1);
        // 100 - 30 = 70 change.
        let total_change: u128 = r.change_outputs.iter().map(|c| c.value).sum();
        assert_eq!(total_change, 70);
        assert_eq!(r.recipient_outputs, [] as [UnshieldedOutputSpec; 0]);
    }

    #[test]
    fn init_swap_with_outputs_routes_recipients_too() {
        // The dApp commits 20 NATIVE and wants 10 NATIVE paid to a
        // recipient. The wallet funds the 20 only; the 10 is listed for
        // the counterparty to fund.
        let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
        let r = build_init_swap_recipe(
            &state,
            SENDER,
            &[(tok(NATIVE), 20)],
            &[UnshieldedTransfer::new(10, tok(NATIVE), RECIPIENT)],
            tok(NATIVE),
            TransactionCostModel::ZERO,
        )
        .unwrap();
        assert_eq!(r.inputs.len(), 1);
        assert_eq!(r.recipient_outputs.len(), 1);
        assert_eq!(r.recipient_outputs[0].value, 10);
        assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
        let change: u128 = r.change_outputs.iter().map(|c| c.value).sum();
        assert_eq!(change, 80); // 100 - 20; the 10 is not the wallet's to fund
    }

    #[test]
    fn init_swap_with_only_outputs_spends_nothing() {
        let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
        let r = build_init_swap_recipe(
            &state,
            SENDER,
            &[],
            &[UnshieldedTransfer::new(10, tok(NATIVE), RECIPIENT)],
            tok(NATIVE),
            TransactionCostModel::ZERO,
        )
        .unwrap();
        assert_eq!(r.inputs, [] as [UtxoWithMeta; 0]);
        assert_eq!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
        assert_eq!(r.recipient_outputs.len(), 1);
    }

    #[test]
    fn init_swap_rejects_zero_amounts() {
        let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
        let err = build_init_swap_recipe(
            &state,
            SENDER,
            &[(tok(NATIVE), 0)],
            &[],
            tok(NATIVE),
            TransactionCostModel::ZERO,
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    #[test]
    fn init_swap_rejects_empty_request() {
        let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
        let err = build_init_swap_recipe(
            &state,
            SENDER,
            &[],
            &[],
            tok(NATIVE),
            TransactionCostModel::ZERO,
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }
}