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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! Swap orchestration: build this wallet's half of a swap and merge
//! it into one transaction, optionally paying its fee with dust.
//!
//! Port of `WalletFacade.initSwap` from
//! `@midnight-ntwrk/wallet-sdk-facade/src/index.ts`.
//!
//! [`init_swap`] owns the whole pipeline. Each sub-wallet builds an
//! **unbalanced** leg: the shielded offer
//! ([`crate::shielded::build_shielded_init_swap_recipe`]) and the
//! unshielded intent commit inputs worth exactly the desired inputs
//! (change goes back to the wallet) and carry the desired outputs
//! unfunded. The counterparty's half, typically a DEX pool or another
//! wallet's swap, closes both imbalances. The legs are then merged and,
//! when asked, dust-balanced.
//!
//! [`build_init_swap_recipe`] is the merge + dust layer on its own, for
//! callers that build their legs themselves.
//!
//! # Why `pay_fees` defaults to FALSE for swaps
//!
//! Swaps are typically routed through a DEX pool or bridge contract that
//! pays its own fees. Forcing the caller to fund the fee out of their
//! own dust would double-charge the swap. The TS `initSwap` hard-codes
//! `payFees = false` as the default; moonproof matches.

use std::collections::BTreeMap;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::ShieldedTokenType;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use rand::{CryptoRng, Rng};

use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
use crate::facade::transfer::{
    balance_dust_fee, partition_outputs, CombinedTokenTransfer, FeeContext, ShieldedTokenTransfer,
    TransferSigningKeys, UnprovenTransaction, UnprovenTransactionRecipe, UnshieldedTokenTransfer,
    PRIMARY_SEGMENT_ID,
};
use crate::shielded::ledger_adapter::{build_shielded_offer, build_shielded_transaction};
use crate::shielded::{build_shielded_init_swap_recipe, ShieldedState, ShieldedTransfer};
use crate::types::{TokenType, TransactionCostModel};
use crate::unshielded::ledger_adapter::{
    build_intent, build_transaction, IntentParams, UnshieldedIntent,
};
use crate::unshielded::{
    build_init_swap_unshielded_recipe as build_unshielded_init_swap_recipe, UnshieldedState,
    UnshieldedTransfer,
};

/// Secrets the swap composer needs. Shielded and night signing keys are
/// the caller's responsibility on the sub-wallet legs (they should
/// already be populated inside the `shielded_leg` / `unshielded_leg`
/// arguments); the dust secret is used iff `options.pay_fees` is true.
#[derive(Debug)]
pub struct SwapSigningKeys<'a> {
    pub dust_secret_key: &'a DustSecretKey,
}

/// Options shaping a swap recipe. `pay_fees` defaults to `false` in the
/// TS reference — DEX pool fees, not wallet-paid. Callers who need
/// wallet-paid fees flip to `true`.
#[derive(Debug, Clone, Copy)]
pub struct SwapOptions {
    pub ttl: Timestamp,
    pub current_time: Timestamp,
    pub pay_fees: bool,
}

/// What this wallet puts into a swap, per sub-wallet and token type.
/// Mirrors TS `CombinedSwapInputs`.
#[derive(Debug, Default, Clone)]
pub struct SwapInputs {
    pub shielded: BTreeMap<ShieldedTokenType, u128>,
    pub unshielded: BTreeMap<TokenType, u128>,
}

/// Build this wallet's half of a swap: inputs worth `inputs`, outputs
/// `outputs` left for the counterparty to fund, merged into one
/// transaction and dust-balanced when `options.pay_fees` is set.
///
/// A sub-wallet takes part when it has an input or an output, so a leg
/// with outputs but no inputs is still built. The unshielded intent goes
/// to `intent_segment`; the shielded offer to the guaranteed section.
/// The unshielded intent is left unsigned, as with
/// [`crate::facade::build_transfer_recipe`]: sign it with
/// [`crate::facade::sign_recipe`].
///
/// Returns the recipe and the state with the spent coins booked and the
/// wallet's own outputs watched.
///
/// # Errors
///
/// - [`WalletError::SigningFailed`] when there is neither a shielded nor
///   an unshielded part, or when `intent_segment` is 0, the guaranteed
///   segment no intent may occupy.
/// - [`WalletError::InvalidAmount`] for a zero amount.
/// - [`WalletError::InsufficientFunds`] when the wallet cannot cover the
///   inputs, or the fee when `options.pay_fees` is set.
pub fn init_swap<R>(
    rng: &mut R,
    state: FacadeState,
    inputs: &SwapInputs,
    outputs: &[CombinedTokenTransfer],
    keys: &TransferSigningKeys<'_>,
    options: &SwapOptions,
    intent_segment: u16,
) -> Result<(UnprovenTransactionRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    if intent_segment == 0 {
        return Err(WalletError::SigningFailed(
            "segment 0 is the guaranteed section; a swap intent needs a segment of 1 or more"
                .to_owned(),
        ));
    }
    let (shielded_outputs, unshielded_outputs) = partition_outputs(outputs);
    let has_shielded = !inputs.shielded.is_empty() || !shielded_outputs.is_empty();
    let has_unshielded = !inputs.unshielded.is_empty() || !unshielded_outputs.is_empty();
    if !has_shielded && !has_unshielded {
        return Err(WalletError::SigningFailed(
            "swap requires at least one shielded or unshielded input or output".to_owned(),
        ));
    }

    let network_label = state.network_id().as_str().to_owned();
    let mut facade_state = state;

    let shielded_leg = if has_shielded {
        let (next_shielded, leg) = shielded_swap_leg(
            rng,
            facade_state.shielded.clone(),
            keys.shielded_secret_keys,
            &inputs.shielded,
            &shielded_outputs,
            &network_label,
        )?;
        facade_state = facade_state.with_shielded(next_shielded);
        Some(leg)
    } else {
        None
    };

    let unshielded_leg = if has_unshielded {
        let (next_unshielded, intent) = unshielded_swap_intent(
            rng,
            facade_state.unshielded.clone(),
            keys,
            &inputs.unshielded,
            &unshielded_outputs,
            options.ttl,
        )?;
        facade_state = facade_state.with_unshielded(next_unshielded);
        Some(build_transaction(intent, intent_segment, network_label))
    } else {
        None
    };

    build_init_swap_recipe(
        rng,
        facade_state,
        shielded_leg,
        unshielded_leg,
        &SwapSigningKeys {
            dust_secret_key: keys.dust_secret_key,
        },
        options,
    )
}

/// The shielded offer of a swap, with its spends booked and the
/// wallet's own outputs watched in the returned state.
fn shielded_swap_leg<R>(
    rng: &mut R,
    shielded: ShieldedState,
    secret_keys: &ZswapSecretKeys,
    inputs: &BTreeMap<ShieldedTokenType, u128>,
    outputs: &[ShieldedTokenTransfer],
    network_id: &str,
) -> Result<(ShieldedState, UnprovenTransaction)>
where
    R: Rng + CryptoRng,
{
    let desired_inputs: Vec<(ShieldedTokenType, u128)> =
        inputs.iter().map(|(t, v)| (*t, *v)).collect();
    let desired_outputs: Vec<ShieldedTransfer> = outputs
        .iter()
        .map(|t| ShieldedTransfer::new(t.amount, t.token_type, t.recipient.clone()))
        .collect();
    let recipe = build_shielded_init_swap_recipe(
        rng,
        &shielded,
        secret_keys,
        &desired_inputs,
        &desired_outputs,
    )?;
    let (offer, next) =
        build_shielded_offer(rng, shielded, secret_keys, &recipe, PRIMARY_SEGMENT_ID)?.ok_or_else(
            || {
                WalletError::ShieldedOffer(
                    "shielded swap recipe produced an empty offer".to_owned(),
                )
            },
        )?;
    Ok((
        next,
        build_shielded_transaction(offer, network_id.to_owned()),
    ))
}

/// The unshielded intent of a swap, unsigned, with its spends booked in
/// the returned state.
fn unshielded_swap_intent<R>(
    rng: &mut R,
    unshielded: UnshieldedState,
    keys: &TransferSigningKeys<'_>,
    inputs: &BTreeMap<TokenType, u128>,
    outputs: &[UnshieldedTokenTransfer],
    ttl: Timestamp,
) -> Result<(UnshieldedState, UnshieldedIntent)>
where
    R: Rng + CryptoRng,
{
    if outputs.iter().any(|t| t.amount == 0) {
        return Err(WalletError::InvalidAmount(
            "unshielded swap output amounts must be positive".to_owned(),
        ));
    }
    let desired_inputs: Vec<(TokenType, u128)> =
        inputs.iter().map(|(t, v)| (t.clone(), *v)).collect();
    let desired_outputs: Vec<UnshieldedTransfer> = outputs
        .iter()
        .map(|t| UnshieldedTransfer::new(t.amount, t.token_type.clone(), t.recipient))
        .collect();
    let recipe = build_unshielded_init_swap_recipe(
        &unshielded,
        keys.sender_owner,
        &desired_inputs,
        &desired_outputs,
        TokenType::new("native"),
        TransactionCostModel::ZERO,
    )?;

    let mut next = unshielded;
    for input in &recipe.inputs {
        next = next.spend_by_id(input.id())?;
    }
    let intent = build_intent(
        &recipe,
        &IntentParams {
            spender_verifying_key: keys.night_verifying_key.clone(),
            ttl,
        },
        rng,
    )?
    .ok_or_else(|| {
        WalletError::SigningFailed("unshielded swap recipe produced no intent".to_owned())
    })?;
    Ok((next, intent))
}

/// Build a swap-style [`UnprovenTransactionRecipe`] by merging the
/// caller-supplied shielded / unshielded legs and (optionally) attaching
/// a dust-balancing intent.
///
/// At least one of the two legs must be `Some`; passing both `None` is
/// a caller error.
///
/// ## Legs
///
/// Each leg is an already-built
/// [`UnprovenTransaction`]:
///
/// - `shielded_leg`: a transaction whose
///   [`guaranteed_coins`](moonproof_ledger::ledger::structure::StandardTransaction::guaranteed_coins)
///   carries the caller's shielded offer (built via
///   [`crate::shielded::build_shielded_transaction`]).
/// - `unshielded_leg`: a transaction whose
///   [`intents`](moonproof_ledger::ledger::structure::StandardTransaction::intents)
///   carry the caller's unshielded swap intent (built via
///   [`crate::unshielded::ledger_adapter::build_transaction`]).
///
/// The facade does not inspect the legs — callers own the responsibility
/// for intent-segment-id non-collision and offer well-formedness. Any
/// `Transaction::merge` error is surfaced as
/// [`WalletError::Serialization`].
///
/// ## Dust fee balancing
///
/// When `options.pay_fees = true` and the facade's dust state holds
/// coins, a dust-balancing intent is produced covering the merged
/// transaction's fee and merged in. The intent goes in the first free
/// segment after the legs' combined set. When `pay_fees = false`, the
/// merged transaction is returned unchanged.
pub fn build_init_swap_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    shielded_leg: Option<UnprovenTransaction>,
    unshielded_leg: Option<UnprovenTransaction>,
    keys: &SwapSigningKeys<'_>,
    options: &SwapOptions,
) -> Result<(UnprovenTransactionRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let base_tx = match (shielded_leg, unshielded_leg) {
        (Some(sh), Some(un)) => sh
            .merge(&un)
            .map_err(|e| WalletError::Serialization(format!("swap merge failed: {e:?}")))?,
        (Some(t), None) | (None, Some(t)) => t,
        (None, None) => {
            return Err(WalletError::SigningFailed(
                "swap requires at least one shielded or unshielded leg".to_owned(),
            ));
        }
    };

    let network_label = state.network_id().as_str().to_owned();
    let mut facade_state = state;

    let final_tx = if options.pay_fees {
        let (new_dust_state, balanced_tx) = balance_dust_fee(
            rng,
            facade_state.dust.clone(),
            keys.dust_secret_key,
            &base_tx,
            &FeeContext {
                current_time: options.current_time,
                ttl: options.ttl,
                network_id: &network_label,
                ledger_parameters: facade_state.ledger_parameters(),
            },
        )?;
        facade_state = facade_state.with_dust(new_dust_state);
        balanced_tx
    } else {
        base_tx
    };

    Ok((
        UnprovenTransactionRecipe {
            transaction: final_tx,
        },
        facade_state,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use crate::address::{ShieldedCoinPublicKey, ShieldedEncryptionPublicKey};
    use crate::dust::DustState;
    use crate::facade::transfer::PRIMARY_SEGMENT_ID;
    use crate::facade::transfer::{CombinedTokenTransfer, TransferSigningKeys};
    use crate::shielded::{
        build_shielded_offer, build_shielded_transaction, build_shielded_transfer_recipe,
        ShieldedState, ShieldedTransfer,
    };
    use crate::types::{TokenType, TransactionCostModel};
    use crate::unshielded::ledger_adapter::{
        build_intent, build_transaction, signing_key_from_bytes, IntentParams,
    };
    use crate::unshielded::{
        build_transfer_recipe as build_unshielded_recipe, UnshieldedState, UnshieldedTransfer,
        UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta,
    };
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::coin_structure::coin::{
        Info as CoinInfo, Nonce, ShieldedTokenType, UserAddress,
    };
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::ledger::structure::Transaction;
    use moonproof_ledger::serialize::Serializable;
    use moonproof_ledger::storage::db::InMemoryDB;
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn zswap_keys(b: u8) -> ZswapSecretKeys {
        ZswapSecretKeys::from(ZswapSeed::from([b; 32]))
    }

    fn dust_params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 1_000,
            generation_decay_rate: 1,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn empty_facade(network: NetworkId) -> FacadeState {
        let sh = ShieldedState::init_empty(&zswap_keys(0x01), network.clone());
        let du = DustState::init_empty(
            dust_params(),
            &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
            network.clone(),
        );
        FacadeState::new(sh, UnshieldedState::empty(), du, network)
    }

    /// Build a shielded leg that contains one 500-unit self-transfer.
    /// Used to produce a non-empty `guaranteed_coins` offer in tests.
    fn build_shielded_leg_for_tests(rng: &mut StdRng) -> UnprovenTransaction {
        let keys = zswap_keys(0x05);
        let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
        let tt = ShieldedTokenType(HashOutput([0xAB; 32]));
        let coin = CoinInfo {
            nonce: Nonce(HashOutput([0x01; 32])),
            type_: tt,
            value: 1_000,
        };
        local = local.insert_coin(&keys, coin).unwrap();
        let state = ShieldedState::init(local, &keys, NetworkId::Undeployed);

        let coin_pk = ShieldedCoinPublicKey(keys.coin_public_key().0 .0);
        let mut enc_buf = Vec::new();
        keys.enc_public_key().serialize(&mut enc_buf).unwrap();
        let enc_pk = ShieldedEncryptionPublicKey(<[u8; 32]>::try_from(enc_buf.as_slice()).unwrap());
        let recipient = crate::address::ShieldedAddress::new(coin_pk, enc_pk);

        let transfers = vec![ShieldedTransfer::new(300, tt, recipient)];
        let recipe = build_shielded_transfer_recipe(rng, &state, &keys, &transfers).unwrap();
        let (offer, _) = build_shielded_offer(rng, state, &keys, &recipe, PRIMARY_SEGMENT_ID)
            .unwrap()
            .unwrap();
        build_shielded_transaction(offer, "undeployed".to_owned())
    }

    /// Build an unshielded leg that transfers 100 NIGHT from the
    /// supplied owner to a stub destination.
    fn build_unshielded_leg_for_tests(rng: &mut StdRng, owner: [u8; 32]) -> UnprovenTransaction {
        let utxos = vec![UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([0x11; 32], 0),
                1_000_000,
                TokenType::new("native"),
                owner,
            ),
            UtxoMeta::new(0, false),
        )];
        let state = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(utxos, vec![]))
            .unwrap();
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let transfers = vec![UnshieldedTransfer::new(
            100,
            TokenType::new("native"),
            [0xBB; 32],
        )];
        let recipe = build_unshielded_recipe(
            &state,
            owner,
            &transfers,
            TokenType::new("native"),
            TransactionCostModel::ZERO,
        )
        .unwrap();
        let intent = build_intent(
            &recipe,
            &IntentParams {
                spender_verifying_key: vk,
                ttl: Timestamp::from_secs(3600),
            },
            rng,
        )
        .unwrap()
        .unwrap();
        build_transaction(intent, PRIMARY_SEGMENT_ID, "undeployed".to_owned())
    }

    #[test]
    fn swap_with_both_legs_merges_into_standard_tx() {
        let mut rng = StdRng::seed_from_u64(1);
        let owner = {
            let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
            UserAddress::from(sk.verifying_key()).0 .0
        };
        let shielded = build_shielded_leg_for_tests(&mut rng);
        let unshielded = build_unshielded_leg_for_tests(&mut rng, owner);
        let f = empty_facade(NetworkId::Undeployed);

        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let keys = SwapSigningKeys {
            dust_secret_key: &dsk,
        };
        let (recipe, _new_state) = build_init_swap_recipe(
            &mut rng,
            f,
            Some(shielded),
            Some(unshielded),
            &keys,
            &SwapOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();
        match recipe.transaction {
            Transaction::Standard(stx) => {
                assert!(stx.guaranteed_coins.is_some(), "shielded offer preserved");
                assert_eq!(stx.intents.size(), 1, "unshielded intent preserved");
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn swap_shielded_only_returns_leg_unchanged_when_pay_fees_false() {
        let mut rng = StdRng::seed_from_u64(2);
        let shielded = build_shielded_leg_for_tests(&mut rng);
        let f = empty_facade(NetworkId::Undeployed);
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let keys = SwapSigningKeys {
            dust_secret_key: &dsk,
        };
        let (recipe, _) = build_init_swap_recipe(
            &mut rng,
            f,
            Some(shielded),
            None,
            &keys,
            &SwapOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();
        match recipe.transaction {
            Transaction::Standard(stx) => {
                assert!(stx.guaranteed_coins.is_some());
                assert_eq!(stx.intents.size(), 0);
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn swap_unshielded_only_returns_leg_unchanged_when_pay_fees_false() {
        let mut rng = StdRng::seed_from_u64(3);
        let owner = {
            let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
            UserAddress::from(sk.verifying_key()).0 .0
        };
        let unshielded = build_unshielded_leg_for_tests(&mut rng, owner);
        let f = empty_facade(NetworkId::Undeployed);
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let keys = SwapSigningKeys {
            dust_secret_key: &dsk,
        };
        let (recipe, _) = build_init_swap_recipe(
            &mut rng,
            f,
            None,
            Some(unshielded),
            &keys,
            &SwapOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();
        match recipe.transaction {
            Transaction::Standard(stx) => {
                assert!(stx.guaranteed_coins.is_none());
                assert_eq!(stx.intents.size(), 1);
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn swap_rejects_both_legs_none() {
        let mut rng = StdRng::seed_from_u64(4);
        let f = empty_facade(NetworkId::Undeployed);
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let keys = SwapSigningKeys {
            dust_secret_key: &dsk,
        };
        let err = build_init_swap_recipe(
            &mut rng,
            f,
            None,
            None,
            &keys,
            &SwapOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    #[test]
    fn swap_pay_fees_true_with_no_dust_errors() {
        let mut rng = StdRng::seed_from_u64(5);
        let shielded = build_shielded_leg_for_tests(&mut rng);
        let f = empty_facade(NetworkId::Undeployed);
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let keys = SwapSigningKeys {
            dust_secret_key: &dsk,
        };
        let err = build_init_swap_recipe(
            &mut rng,
            f,
            Some(shielded),
            None,
            &keys,
            &SwapOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: true,
            },
        )
        .unwrap_err();
        assert!(matches!(
            err,
            WalletError::InsufficientFunds { .. } | WalletError::Dust(_)
        ));
    }

    #[test]
    fn swap_inputs_defaults_are_empty_maps() {
        let s = SwapInputs::default();
        assert!(s.shielded.is_empty());
        assert!(s.unshielded.is_empty());
    }

    struct SwapWallet {
        zswap: ZswapSecretKeys,
        dust: DustSecretKey,
        night: moonproof_ledger::signatures::SigningKey,
        owner: [u8; 32],
    }

    impl SwapWallet {
        fn new() -> Self {
            let night = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
            let owner = UserAddress::from(night.verifying_key()).0 .0;
            Self {
                zswap: zswap_keys(0x05),
                dust: DustSecretKey::derive_secret_key(&[0x02u8; 32]),
                night,
                owner,
            }
        }

        fn keys(&self) -> (moonproof_ledger::signatures::VerifyingKey, [u8; 32]) {
            (self.night.verifying_key(), self.owner)
        }

        fn own_shielded_address(&self) -> crate::address::ShieldedAddress {
            let coin_pk = ShieldedCoinPublicKey(self.zswap.coin_public_key().0 .0);
            let mut enc_buf = Vec::new();
            self.zswap.enc_public_key().serialize(&mut enc_buf).unwrap();
            let enc_pk =
                ShieldedEncryptionPublicKey(<[u8; 32]>::try_from(enc_buf.as_slice()).unwrap());
            crate::address::ShieldedAddress::new(coin_pk, enc_pk)
        }

        /// A facade holding 1 000 of shielded token 0xAB and one
        /// 1 000 000 NIGHT UTXO.
        fn funded_facade(&self) -> FacadeState {
            let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
            local = local
                .insert_coin(
                    &self.zswap,
                    CoinInfo {
                        nonce: Nonce(HashOutput([0x01; 32])),
                        type_: shielded_token(),
                        value: 1_000,
                    },
                )
                .unwrap();
            let shielded = ShieldedState::init(local, &self.zswap, NetworkId::Undeployed);
            let unshielded = UnshieldedState::empty()
                .apply_update(&UnshieldedUpdate::success(
                    vec![UtxoWithMeta::new(
                        UnshieldedUtxo::new(
                            UtxoId::new([0x11; 32], 0),
                            1_000_000,
                            TokenType::new("native"),
                            self.owner,
                        ),
                        UtxoMeta::new(0, false),
                    )],
                    vec![],
                ))
                .unwrap();
            let dust = DustState::init_empty(dust_params(), &self.dust, NetworkId::Undeployed);
            FacadeState::new(shielded, unshielded, dust, NetworkId::Undeployed)
        }
    }

    fn shielded_token() -> ShieldedTokenType {
        ShieldedTokenType(HashOutput([0xAB; 32]))
    }

    fn no_fee_options() -> SwapOptions {
        SwapOptions {
            ttl: Timestamp::from_secs(3600),
            current_time: Timestamp::from_secs(0),
            pay_fees: false,
        }
    }

    fn run_init_swap(
        wallet: &SwapWallet,
        inputs: &SwapInputs,
        outputs: &[CombinedTokenTransfer],
        intent_segment: u16,
    ) -> Result<(UnprovenTransactionRecipe, FacadeState)> {
        let mut rng = StdRng::seed_from_u64(42);
        let (vk, owner) = wallet.keys();
        let keys = TransferSigningKeys {
            shielded_secret_keys: &wallet.zswap,
            dust_secret_key: &wallet.dust,
            night_signing_key: &wallet.night,
            night_verifying_key: &vk,
            sender_owner: owner,
        };
        init_swap(
            &mut rng,
            wallet.funded_facade(),
            inputs,
            outputs,
            &keys,
            &no_fee_options(),
            intent_segment,
        )
    }

    fn shielded_deltas(tx: &UnprovenTransaction) -> Vec<(ShieldedTokenType, i128)> {
        match tx {
            Transaction::Standard(stx) => {
                stx.guaranteed_coins
                    .as_ref()
                    .map_or_else(Vec::new, |offer| {
                        offer
                            .deltas
                            .iter()
                            .map(|d| (d.token_type, d.value))
                            .collect()
                    })
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn init_swap_offers_shielded_inputs_for_unfunded_outputs() {
        let wallet = SwapWallet::new();
        let wanted = ShieldedTokenType(HashOutput([0xCD; 32]));
        let mut inputs = SwapInputs::default();
        inputs.shielded.insert(shielded_token(), 300);
        let outputs = [CombinedTokenTransfer::Shielded(vec![
            crate::facade::transfer::ShieldedTokenTransfer {
                token_type: wanted,
                recipient: wallet.own_shielded_address(),
                amount: 750,
            },
        ])];
        let (recipe, booked) = run_init_swap(&wallet, &inputs, &outputs, 1).unwrap();

        let mut deltas = shielded_deltas(&recipe.transaction);
        deltas.sort();
        let mut expected = vec![(shielded_token(), 300), (wanted, -750)];
        expected.sort();
        assert_eq!(
            deltas, expected,
            "inputs exceed change by 300; the output is unfunded"
        );
        assert_eq!(booked.shielded.pending_spend_count(), 1);
        assert_eq!(
            booked.shielded.pending_output_count(),
            2,
            "the change and the wanted coin are both the wallet's own"
        );
        match recipe.transaction {
            Transaction::Standard(stx) => assert_eq!(stx.intents.size(), 0),
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn init_swap_offers_unshielded_inputs_at_the_requested_segment() {
        let wallet = SwapWallet::new();
        let mut inputs = SwapInputs::default();
        inputs.unshielded.insert(TokenType::new("native"), 400);
        let counterparty = [0xEE; 32];
        let outputs = [CombinedTokenTransfer::Unshielded(vec![
            crate::facade::transfer::UnshieldedTokenTransfer {
                token_type: TokenType::new("ab".repeat(32)),
                recipient: counterparty,
                amount: 90,
            },
        ])];
        let (recipe, booked) = run_init_swap(&wallet, &inputs, &outputs, 7).unwrap();

        let Transaction::Standard(stx) = recipe.transaction else {
            panic!("expected Standard");
        };
        assert!(stx.guaranteed_coins.is_none());
        assert_eq!(stx.intents.keys().collect::<Vec<_>>(), vec![7]);
        let intent = stx.intents.get(&7).unwrap();
        let offer = intent.guaranteed_unshielded_offer.as_ref().unwrap();
        let spent: u128 = offer.inputs.iter().map(|i| i.value).sum();
        let native_out: u128 = offer
            .outputs
            .iter()
            .filter(|o| o.type_ == moonproof_ledger::coin_structure::coin::NIGHT)
            .map(|o| o.value)
            .sum();
        assert_eq!(
            spent - native_out,
            400,
            "the change leaves exactly 400 NIGHT offered"
        );
        let wanted: Vec<_> = offer
            .outputs
            .iter()
            .filter(|o| o.type_ != moonproof_ledger::coin_structure::coin::NIGHT)
            .collect();
        assert_eq!(wanted.len(), 1);
        assert_eq!(wanted[0].value, 90);
        assert_eq!(wanted[0].owner.0 .0, counterparty);
        assert_eq!(
            booked.unshielded.available().count(),
            0,
            "the spent UTXO is booked"
        );
    }

    #[test]
    fn init_swap_builds_a_leg_for_outputs_without_inputs() {
        let wallet = SwapWallet::new();
        let outputs = [CombinedTokenTransfer::Unshielded(vec![
            crate::facade::transfer::UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: wallet.owner,
                amount: 5,
            },
        ])];
        let (recipe, booked) = run_init_swap(&wallet, &SwapInputs::default(), &outputs, 1).unwrap();
        let Transaction::Standard(stx) = recipe.transaction else {
            panic!("expected Standard");
        };
        let offer = stx
            .intents
            .get(&1)
            .unwrap()
            .guaranteed_unshielded_offer
            .clone()
            .unwrap();
        assert!(offer.inputs.is_empty());
        assert_eq!(offer.outputs.len(), 1);
        assert_eq!(
            booked.unshielded.available().count(),
            1,
            "nothing was spent"
        );
    }

    #[test]
    fn init_swap_mixes_both_legs() {
        let wallet = SwapWallet::new();
        let mut inputs = SwapInputs::default();
        inputs.shielded.insert(shielded_token(), 100);
        let outputs = [CombinedTokenTransfer::Unshielded(vec![
            crate::facade::transfer::UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: wallet.owner,
                amount: 50,
            },
        ])];
        let (recipe, _) = run_init_swap(&wallet, &inputs, &outputs, 3).unwrap();
        let Transaction::Standard(stx) = recipe.transaction else {
            panic!("expected Standard");
        };
        assert!(stx.guaranteed_coins.is_some());
        assert_eq!(stx.intents.keys().collect::<Vec<_>>(), vec![3]);
    }

    #[test]
    fn init_swap_rejects_the_guaranteed_segment_and_empty_swaps() {
        let wallet = SwapWallet::new();
        let mut inputs = SwapInputs::default();
        inputs.unshielded.insert(TokenType::new("native"), 1);
        assert!(matches!(
            run_init_swap(&wallet, &inputs, &[], 0),
            Err(WalletError::SigningFailed(_))
        ));
        assert!(matches!(
            run_init_swap(&wallet, &SwapInputs::default(), &[], 1),
            Err(WalletError::SigningFailed(_))
        ));
    }

    #[test]
    fn init_swap_beyond_the_balance_is_insufficient_funds() {
        let wallet = SwapWallet::new();
        let mut inputs = SwapInputs::default();
        inputs.shielded.insert(shielded_token(), 1_001);
        assert!(matches!(
            run_init_swap(&wallet, &inputs, &[], 1),
            Err(WalletError::InsufficientFunds { .. })
        ));
    }
}