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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
//! Mixed shielded + unshielded transfer orchestration.
//!
//! Port of `WalletFacade.transferTransaction` from
//! `@midnight-ntwrk/wallet-sdk-facade/src/index.ts`. Combines
//! `shielded.transferTransaction` + `unshielded.transferTransaction` +
//! `dust.balanceTransactions` into a single builder that:
//!
//! 1. Splits the caller's [`CombinedTokenTransfer`]s into shielded vs.
//!    unshielded buckets.
//! 2. Builds each bucket's pure recipe + ledger intent/offer and wraps
//!    them in a [`Transaction<Signature, ProofPreimageMarker,
//!    PedersenRandomness, InMemoryDB>`].
//! 3. Merges the two via [`Transaction::merge`].
//! 4. If `pay_fees`, computes a dust-balancing intent that pays the
//!    merged transaction's fee, merges it in, and returns the fully
//!    balanced unproven transaction.
//!
//! The result is an [`UnprovenTransactionRecipe`] ready for a
//! [`crate::facade::submission::finalize_recipe`] call. The unshielded
//! intent is returned **unsigned** — callers sign via a future
//! `sign_recipe` helper (mirrors TS `signRecipe`) before finalizing.

use std::collections::BTreeSet;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::ShieldedTokenType;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_ledger::ledger::structure::{
    LedgerParameters, PedersenDowngradeable, ProofKind, ProofPreimageMarker, StandardTransaction,
    Transaction, UnshieldedOffer,
};
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::signatures::{Signature, SigningKey, VerifyingKey};
use moonproof_ledger::storage::arena::Sp;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::storage::Storable;
use moonproof_ledger::transient_crypto::commitment::{Pedersen, PedersenRandomness};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use rand::rngs::StdRng;
use rand::{CryptoRng, Rng, SeedableRng};

use crate::address::ShieldedAddress;
use crate::dust::{
    build_dust_balancing_intent, compute_fee_balancing_recipe, find_available_segment_id,
    CoinWithFee, DustBalancingRecipe,
};
use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
use crate::shielded::ledger_adapter::{build_shielded_offer, build_shielded_transaction};
use crate::shielded::{build_shielded_transfer_recipe, ShieldedTransfer};
use crate::types::{TokenType, TransactionCostModel};
use crate::unshielded::ledger_adapter::{build_intent, build_transaction, IntentParams};
use crate::unshielded::{build_transfer_recipe as build_unshielded_recipe, UnshieldedTransfer};

/// Type alias for the pre-prove, pre-bind transaction shape that flows
/// between facade stages. Matches
/// [`crate::unshielded::ledger_adapter::SignedTransaction`] — both
/// aliases reach the same concrete type.
pub type UnprovenTransaction =
    Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>;

/// One "send `amount` of `token_type` to `recipient`" shielded
/// instruction. Matches TS `TokenTransfer<ShieldedAddress>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShieldedTokenTransfer {
    pub token_type: ShieldedTokenType,
    pub recipient: ShieldedAddress,
    pub amount: u128,
}

/// One "send `amount` of `token_type` to `recipient`" unshielded
/// instruction. Matches TS `TokenTransfer<UnshieldedAddress>` — we carry
/// the raw 32-byte owner directly to match
/// [`crate::unshielded::UnshieldedTransfer::recipient`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedTokenTransfer {
    pub token_type: TokenType,
    pub recipient: [u8; 32],
    pub amount: u128,
}

/// Disjoint union for [`build_transfer_recipe`]'s `outputs` argument.
/// Mirrors TS `CombinedTokenTransfer`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CombinedTokenTransfer {
    Shielded(Vec<ShieldedTokenTransfer>),
    Unshielded(Vec<UnshieldedTokenTransfer>),
}

/// Secrets + keys the facade's transfer builder needs. The dust key is
/// used iff `options.pay_fees` is true.
///
/// Ownership is by reference — the struct is ephemeral and never
/// outlives its caller.
#[derive(Debug)]
pub struct TransferSigningKeys<'a> {
    pub shielded_secret_keys: &'a ZswapSecretKeys,
    pub dust_secret_key: &'a DustSecretKey,
    pub night_signing_key: &'a SigningKey,
    pub night_verifying_key: &'a VerifyingKey,
    /// 32-byte user-address bytes of the spender — used as the sender
    /// (change) address on the unshielded offer.
    pub sender_owner: [u8; 32],
}

/// Options shaping a transfer recipe. `pay_fees` defaults to `true` in
/// the TS reference; callers pass it explicitly here for clarity.
#[derive(Debug, Clone, Copy)]
pub struct TransferOptions {
    /// TTL stamped on every intent in the resulting transaction.
    pub ttl: Timestamp,
    /// "Now" timestamp used for dust-spend `ctime`. Must be derived from
    /// the chain's latest block, not `SystemTime::now()` (wallet-vs-chain
    /// ctime drift is a known footgun — see VISION.md "Lessons learned").
    pub current_time: Timestamp,
    /// If true, a dust-balancing intent is built and merged in.
    pub pay_fees: bool,
}

/// The chain view a dust-fee balance is built against. Every field comes
/// from the same synced block: dust spends are stamped with
/// `current_time`, and the fee is priced against `ledger_parameters`,
/// whose fee prices move per block — pricing against the ledger's
/// initial parameters under-pays once they rise, and the node rejects
/// the transaction as `BalanceCheckOverspend`.
#[derive(Debug, Clone, Copy)]
pub struct FeeContext<'a> {
    pub current_time: Timestamp,
    pub ttl: Timestamp,
    pub network_id: &'a str,
    pub ledger_parameters: &'a LedgerParameters,
}

/// The output of [`build_transfer_recipe`] — a fully merged unproven
/// transaction containing every shielded offer, unshielded intent, and
/// dust balancing intent the recipe needed. Ready for
/// [`crate::facade::submission::finalize_recipe`] after signing.
#[derive(Debug, Clone)]
pub struct UnprovenTransactionRecipe {
    pub transaction: UnprovenTransaction,
}

// --- Public API ------------------------------------------------------

/// Segment id used for the shielded offer's internal stamping AND for
/// the unshielded intent. Shielded stamps live in
/// [`guaranteed_coins`](moonproof_ledger::ledger::structure::StandardTransaction::guaranteed_coins);
/// unshielded intents live in
/// [`intents`](moonproof_ledger::ledger::structure::StandardTransaction::intents).
/// The two namespaces are disjoint so sharing the value 1 is fine —
/// matches the pattern already in
/// [`crate::shielded::ledger_adapter`] and
/// [`crate::unshielded::ledger_adapter`] tests.
pub const PRIMARY_SEGMENT_ID: u16 = 1;

/// Build a [`UnprovenTransactionRecipe`] for a mixed shielded +
/// unshielded transfer, optionally balancing a dust fee intent.
///
/// Returns the recipe plus the updated [`FacadeState`] (sub-wallet
/// states reflect the locally-pending spends + watched outputs so that
/// subsequent sync calls don't double-count them).
///
/// ## Errors
///
/// - [`WalletError::SigningFailed`] if `outputs` is empty — at least
///   one transfer is required (matches TS
///   `At least one shielded or unshielded output is required`).
/// - Any error from the underlying sub-wallet recipe builders
///   ([`crate::shielded::build_shielded_transfer_recipe`],
///   [`crate::unshielded::build_transfer_recipe`]).
/// - [`WalletError::InsufficientFunds`] if the dust balancer can't
///   cover the merged transaction's fee.
/// - [`WalletError::Serialization`] if
///   [`Transaction::merge`](moonproof_ledger::ledger::structure::Transaction::merge)
///   refuses to merge (e.g. network id mismatch — shouldn't happen
///   since all builders use `options.network_id` derived from the
///   facade).
pub fn build_transfer_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    outputs: &[CombinedTokenTransfer],
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<(UnprovenTransactionRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let (shielded_outputs, unshielded_outputs) = partition_outputs(outputs);

    if shielded_outputs.is_empty() && unshielded_outputs.is_empty() {
        return Err(WalletError::SigningFailed(
            "transfer requires at least one shielded or unshielded output".to_owned(),
        ));
    }

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

    // --- Shielded leg --------------------------------------------------
    let shielded_tx_opt: Option<UnprovenTransaction> = if shielded_outputs.is_empty() {
        None
    } else {
        let (new_shielded_state, tx) = build_shielded_leg(
            rng,
            facade_state.shielded.clone(),
            keys.shielded_secret_keys,
            &shielded_outputs,
            &network_label,
        )?;
        facade_state = facade_state.with_shielded(new_shielded_state);
        Some(tx)
    };

    // --- Unshielded leg ------------------------------------------------
    let unshielded_tx_opt: Option<UnprovenTransaction> = if unshielded_outputs.is_empty() {
        None
    } else {
        let (new_unshielded_state, tx) = build_unshielded_leg(
            rng,
            facade_state.unshielded.clone(),
            keys,
            &unshielded_outputs,
            options.ttl,
            &network_label,
        )?;
        facade_state = facade_state.with_unshielded(new_unshielded_state);
        Some(tx)
    };

    // --- Merge the two legs ------------------------------------------
    let base_tx = merge_unproven(shielded_tx_opt, unshielded_tx_opt)?.ok_or_else(|| {
        WalletError::SigningFailed("transfer produced no transaction legs".into())
    })?;

    // --- Dust fee balancing ------------------------------------------
    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,
    ))
}

// --- Internal helpers ------------------------------------------------

/// Split a flat list of [`CombinedTokenTransfer`] entries into separate
/// shielded + unshielded output vectors. Matches the TS reference's
/// `outputs.filter(...).flatMap(...)` idiom.
pub(crate) fn partition_outputs(
    outputs: &[CombinedTokenTransfer],
) -> (Vec<ShieldedTokenTransfer>, Vec<UnshieldedTokenTransfer>) {
    let mut shielded = Vec::new();
    let mut unshielded = Vec::new();
    for entry in outputs {
        match entry {
            CombinedTokenTransfer::Shielded(outs) => shielded.extend(outs.iter().cloned()),
            CombinedTokenTransfer::Unshielded(outs) => unshielded.extend(outs.iter().cloned()),
        }
    }
    (shielded, unshielded)
}

fn build_shielded_leg<R>(
    rng: &mut R,
    shielded_state: crate::shielded::ShieldedState,
    zswap_keys: &ZswapSecretKeys,
    transfers: &[ShieldedTokenTransfer],
    network_id: &str,
) -> Result<(crate::shielded::ShieldedState, UnprovenTransaction)>
where
    R: Rng + CryptoRng,
{
    let transfers_typed: Vec<ShieldedTransfer> = transfers
        .iter()
        .map(|t| ShieldedTransfer::new(t.amount, t.token_type, t.recipient.clone()))
        .collect();

    let recipe =
        build_shielded_transfer_recipe(rng, &shielded_state, zswap_keys, &transfers_typed)?;

    let (offer, next_state) =
        build_shielded_offer(rng, shielded_state, zswap_keys, &recipe, PRIMARY_SEGMENT_ID)?
            .ok_or_else(|| {
                WalletError::ShieldedOffer(
                    "shielded transfer recipe produced empty offer despite non-empty transfers"
                        .to_owned(),
                )
            })?;
    let tx = build_shielded_transaction(offer, network_id.to_owned());
    Ok((next_state, tx))
}

fn build_unshielded_leg<R>(
    rng: &mut R,
    unshielded_state: crate::unshielded::UnshieldedState,
    keys: &TransferSigningKeys<'_>,
    transfers: &[UnshieldedTokenTransfer],
    ttl: Timestamp,
    network_id: &str,
) -> Result<(crate::unshielded::UnshieldedState, UnprovenTransaction)>
where
    R: Rng + CryptoRng,
{
    let transfers_typed: Vec<UnshieldedTransfer> = transfers
        .iter()
        .map(|t| UnshieldedTransfer::new(t.amount, t.token_type.clone(), t.recipient))
        .collect();

    // The unshielded cost model MUST be zero for real Midnight
    // transactions — non-zero overheads make the balancer destroy NIGHT,
    // which the chain rejects with InvariantViolation (199). Matches
    // the regression-gated comment in `genesis_submission_integration.rs`
    // and the TS reference's `Transacting.ts:412-415`.
    let recipe = build_unshielded_recipe(
        &unshielded_state,
        keys.sender_owner,
        &transfers_typed,
        TokenType::new("native"),
        TransactionCostModel::ZERO,
    )?;

    // Mark every spent UTXO as locally pending in the state.
    let mut next_state = unshielded_state;
    for input in &recipe.inputs {
        next_state = next_state.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 transfer recipe produced empty intent despite non-empty transfers"
                .to_owned(),
        )
    })?;

    // Leave the intent UNSIGNED — callers sign via `sign_recipe`.
    let tx = build_transaction(intent, PRIMARY_SEGMENT_ID, network_id.to_owned());
    Ok((next_state, tx))
}

/// Merge two [`UnprovenTransaction`]s, respecting the `None` short-
/// circuit when exactly one side is populated. Returns `None` only if
/// both are `None`.
fn merge_unproven(
    a: Option<UnprovenTransaction>,
    b: Option<UnprovenTransaction>,
) -> Result<Option<UnprovenTransaction>> {
    match (a, b) {
        (Some(x), Some(y)) => x
            .merge(&y)
            .map(Some)
            .map_err(|e| WalletError::Serialization(format!("Transaction::merge failed: {e:?}"))),
        (Some(x), None) | (None, Some(x)) => Ok(Some(x)),
        (None, None) => Ok(None),
    }
}

/// Compute the fee-balancing dust intent for `base_tx`, spend the
/// selected dust coins through the supplied [`crate::dust::DustState`],
/// build the balancing intent, and merge it into `base_tx`. Returns the
/// merged transaction plus the updated dust state.
///
/// Reusable across the facade's transfer/swap builders AND external
/// builders (e.g. the contract runtime's `create_unproven_deploy_tx` /
/// `create_unproven_call_tx`, which merge dust coverage into a
/// contract intent at the preimage stage so `prove_tx` covers every
/// preimage in one pass and `balance_tx` stays a pure seal).
pub fn balance_dust_fee<R>(
    rng: &mut R,
    dust_state: crate::dust::DustState,
    dust_sk: &DustSecretKey,
    base_tx: &UnprovenTransaction,
    ctx: &FeeContext<'_>,
) -> Result<(crate::dust::DustState, UnprovenTransaction)>
where
    R: Rng + CryptoRng,
{
    let FeeContext {
        current_time,
        ttl,
        network_id,
        ledger_parameters,
    } = *ctx;
    let initial_fee = standalone_fee_with_margin(base_tx, ledger_parameters);
    let base_tx_for_estimator = base_tx.clone();
    let dust_state_for_estimator = dust_state.clone();
    let dust_sk_for_estimator = dust_sk.clone();

    let balance_recipe =
        compute_fee_balancing_recipe(&dust_state, initial_fee, current_time, |picked| {
            Ok(estimate_merged_fee(
                &dust_state_for_estimator,
                &dust_sk_for_estimator,
                picked,
                &base_tx_for_estimator,
                ctx,
            ))
        })?;

    // No dust to spend? Then the fee is already zero and there's no
    // balancing intent to merge.
    if balance_recipe.inputs.is_empty() {
        return Ok((dust_state, base_tx.clone()));
    }

    let (spends, dust_state_after) =
        dust_state.spend_coins(dust_sk, &balance_recipe.inputs, current_time)?;

    let used_segments = used_intent_segments(base_tx);
    let bal_segment = find_available_segment_id(&used_segments).ok_or_else(|| {
        WalletError::Dust("no free segment id for dust-balancing intent".to_owned())
    })?;

    let bal_intent = build_dust_balancing_intent(&balance_recipe, spends, current_time, ttl, rng)?
        .ok_or_else(|| {
            WalletError::Dust(
                "dust balancing recipe had inputs but no intent was produced".to_owned(),
            )
        })?;

    let mut intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    intents = intents.insert(bal_segment, bal_intent);
    let bal_tx: UnprovenTransaction = Transaction::from_intents(network_id.to_owned(), intents);

    let merged = base_tx
        .merge(&bal_tx)
        .map_err(|e| WalletError::Serialization(format!("dust balancing merge failed: {e:?}")))?;

    Ok((dust_state_after, merged))
}

/// Like [`balance_dust_fee`] but returns the dust-balancing intent
/// as a **standalone** [`UnprovenTransaction`] without merging it
/// into `base_tx`. Mirrors midnight-wallet's
/// `dust.balanceTransactions(...)` shape used by
/// `balanceFinalizedTransaction` — the balancing leg lives next to
/// the original sealed tx in a `FinalizedTransactionRecipe`, and
/// the caller proves + submits both as a pair.
///
/// `base_tx` may be any `Transaction<S, P, B>` shape (unproven,
/// finalized, …) — this helper only reads the tx's fee total via
/// `fees_with_margin`, so it works against the bytes of an already
/// proven tx the dApp passes back to the wallet.
///
/// Returns `(new_dust_state, Some(balancing_tx))` when the wallet
/// has dust to cover the fee, `(unchanged_state, None)` when the
/// fee is already zero or no dust UTXOs are available.
pub fn build_dust_balancing_tx<R, P, B>(
    rng: &mut R,
    dust_state: crate::dust::DustState,
    dust_sk: &DustSecretKey,
    base_tx: &Transaction<Signature, P, B, InMemoryDB>,
    ctx: &FeeContext<'_>,
) -> Result<(crate::dust::DustState, Option<UnprovenTransaction>)>
where
    R: Rng + CryptoRng,
    P: moonproof_ledger::ledger::structure::ProofKind<InMemoryDB>,
    B: moonproof_ledger::storage::Storable<InMemoryDB>
        + moonproof_ledger::ledger::structure::PedersenDowngradeable<InMemoryDB>
        + moonproof_ledger::serialize::Serializable,
{
    let FeeContext {
        current_time,
        ttl,
        network_id,
        ledger_parameters,
    } = *ctx;
    let initial_fee = base_tx
        .fees_with_margin(ledger_parameters, FEE_BLOCKS_MARGIN)
        .unwrap_or(0);
    if initial_fee == 0 {
        return Ok((dust_state, None));
    }

    // Converging estimator. The dust leg is submitted alongside
    // `base_tx`, so the real fee is computed on the *combined* tx —
    // and the combination grows the tx, which raises the fee, which
    // may need more dust. `base_tx` and the leg can be at different
    // proof phases (proven base + unproven leg), so they can't be
    // merged directly; mirror the TS `dryRunFee` and erase proofs on
    // both to normalize the phase, merge the proof-erased copies, and
    // measure `fees_with_margin` on the result. Pure sizing — the
    // erased txs are thrown away.
    let base_erased = base_tx.erase_proofs();
    let dust_state_for_estimator = dust_state.clone();
    let dust_sk_for_estimator = dust_sk.clone();
    let balance_recipe =
        compute_fee_balancing_recipe(&dust_state, initial_fee, current_time, |picked| {
            Ok(estimate_combined_fee_erased(
                &base_erased,
                &dust_state_for_estimator,
                &dust_sk_for_estimator,
                picked,
                ctx,
            ))
        })?;

    if balance_recipe.inputs.is_empty() {
        return Ok((dust_state, None));
    }

    let (spends, dust_state_after) =
        dust_state.spend_coins(dust_sk, &balance_recipe.inputs, current_time)?;

    let used_segments = used_intent_segments_generic(base_tx);
    let bal_segment = find_available_segment_id(&used_segments).ok_or_else(|| {
        WalletError::Dust("no free segment id for dust-balancing intent".to_owned())
    })?;

    let bal_intent = build_dust_balancing_intent(&balance_recipe, spends, current_time, ttl, rng)?
        .ok_or_else(|| {
            WalletError::Dust(
                "dust balancing recipe had inputs but no intent was produced".to_owned(),
            )
        })?;

    let mut intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    intents = intents.insert(bal_segment, bal_intent);
    let bal_tx: UnprovenTransaction = Transaction::from_intents(network_id.to_owned(), intents);

    Ok((dust_state_after, Some(bal_tx)))
}

/// Generic version of `used_intent_segments` for any `Transaction<S,P,B>`.
fn used_intent_segments_generic<S, P, B>(
    tx: &Transaction<S, P, B, InMemoryDB>,
) -> std::collections::BTreeSet<u16>
where
    S: moonproof_ledger::ledger::structure::SignatureKind<InMemoryDB>,
    P: moonproof_ledger::ledger::structure::ProofKind<InMemoryDB>,
    B: moonproof_ledger::storage::Storable<InMemoryDB>
        + moonproof_ledger::ledger::structure::PedersenDowngradeable<InMemoryDB>
        + moonproof_ledger::serialize::Serializable,
{
    let mut out = std::collections::BTreeSet::new();
    if let Transaction::Standard(stx) = tx {
        for entry in stx.intents.iter() {
            let pair = &*entry;
            let seg: u16 = *pair.0;
            out.insert(seg);
        }
    }
    out
}

/// `fees_with_margin` against `ledger_parameters`, which must be the
/// chain's current ones: fee prices move per block, so pricing against
/// the ledger's initial parameters under-pays once they rise and the
/// node rejects the transaction as `BalanceCheckOverspend`.
pub(crate) fn standalone_fee_with_margin(
    tx: &UnprovenTransaction,
    ledger_parameters: &LedgerParameters,
) -> u128 {
    tx.fees_with_margin(ledger_parameters, FEE_BLOCKS_MARGIN)
        .unwrap_or(0)
}

/// Fee estimate for `tx` without going through the balancing path, for
/// [`crate::facade::preview`] and downstream callers.
#[must_use]
pub fn estimate_unproven_fee(
    tx: &UnprovenTransaction,
    ledger_parameters: &LedgerParameters,
) -> u128 {
    standalone_fee_with_margin(tx, ledger_parameters)
}

/// Build a synthetic balancing intent for `picked`, merge with
/// `base_tx`, and return `fees_with_margin`. Mirrors TS `dryRunFee` —
/// used as the estimator closure inside
/// [`compute_fee_balancing_recipe`].
fn estimate_merged_fee(
    state: &crate::dust::DustState,
    sk: &DustSecretKey,
    picked: &[CoinWithFee],
    base_tx: &UnprovenTransaction,
    ctx: &FeeContext<'_>,
) -> u128 {
    let FeeContext {
        current_time,
        ttl,
        network_id,
        ledger_parameters,
    } = *ctx;
    if picked.is_empty() {
        return standalone_fee_with_margin(base_tx, ledger_parameters);
    }
    let dry = state.clone();
    let Ok((spends, _after)) = dry.spend_coins(sk, picked, current_time) else {
        // If the dry-run spend fails, return a large number to kill the
        // convergence loop (the estimator saturates at 2× the standalone
        // fee — forces `compute_fee_balancing_recipe` to error cleanly).
        return standalone_fee_with_margin(base_tx, ledger_parameters).saturating_mul(2);
    };
    let mut est_rng = StdRng::seed_from_u64(FEE_ESTIMATOR_RNG_SEED);
    let Ok(Some(bal_intent)) = build_dust_balancing_intent(
        &DustBalancingRecipe {
            inputs: picked.to_vec(),
            total_fee: 0,
        },
        spends,
        current_time,
        ttl,
        &mut est_rng,
    ) else {
        return standalone_fee_with_margin(base_tx, ledger_parameters);
    };
    let used = used_intent_segments(base_tx);
    let bal_segment = find_available_segment_id(&used).unwrap_or(u16::MAX);
    let mut intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    intents = intents.insert(bal_segment, bal_intent);
    let bal_tx: UnprovenTransaction = Transaction::from_intents(network_id.to_owned(), intents);
    match base_tx.merge(&bal_tx) {
        Ok(merged) => standalone_fee_with_margin(&merged, ledger_parameters),
        Err(_) => standalone_fee_with_margin(base_tx, ledger_parameters).saturating_mul(2),
    }
}

/// Estimate the fee of `base + dust-leg(picked)` when the two are
/// submitted together, working on proof-erased copies so a base at
/// any proof phase (proven, finalized) can be co-measured with the
/// unproven dust leg. Mirrors TS `dryRunFee`'s `eraseProofs()`-then-
/// merge sizing. Pure sizing — nothing here is submitted.
fn estimate_combined_fee_erased(
    base_erased: &Transaction<Signature, (), Pedersen, InMemoryDB>,
    state: &crate::dust::DustState,
    sk: &DustSecretKey,
    picked: &[CoinWithFee],
    ctx: &FeeContext<'_>,
) -> u128 {
    let FeeContext {
        current_time,
        ttl,
        network_id,
        ledger_parameters,
    } = *ctx;
    let base_fee = base_erased
        .fees_with_margin(ledger_parameters, FEE_BLOCKS_MARGIN)
        .unwrap_or(0);
    if picked.is_empty() {
        return base_fee;
    }
    let dry = state.clone();
    let Ok((spends, _after)) = dry.spend_coins(sk, picked, current_time) else {
        // Dry-run spend failed — saturate so the convergence loop
        // errors cleanly rather than spinning.
        return base_fee.saturating_mul(2);
    };
    let mut est_rng = StdRng::seed_from_u64(FEE_ESTIMATOR_RNG_SEED);
    let Ok(Some(bal_intent)) = build_dust_balancing_intent(
        &DustBalancingRecipe {
            inputs: picked.to_vec(),
            total_fee: 0,
        },
        spends,
        current_time,
        ttl,
        &mut est_rng,
    ) else {
        return base_fee;
    };
    let used = used_intent_segments_generic(base_erased);
    let bal_segment = find_available_segment_id(&used).unwrap_or(u16::MAX);
    let mut intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    intents = intents.insert(bal_segment, bal_intent);
    let leg: UnprovenTransaction = Transaction::from_intents(network_id.to_owned(), intents);
    let leg_erased = leg.erase_proofs();
    match base_erased.merge(&leg_erased) {
        Ok(merged) => merged
            .fees_with_margin(ledger_parameters, FEE_BLOCKS_MARGIN)
            .unwrap_or(base_fee),
        Err(_) => base_fee.saturating_mul(2),
    }
}

/// Collect the set of segment ids used by a transaction's intents map.
fn used_intent_segments(tx: &UnprovenTransaction) -> BTreeSet<u16> {
    match tx {
        Transaction::Standard(stx) => stx.intents.keys().collect(),
        Transaction::ClaimRewards(_) => BTreeSet::new(),
    }
}

/// Standard five-block margin for `fees_with_margin`. Matches the TS
/// reference's `feeBlocksMargin: 5` in the default configuration.
const FEE_BLOCKS_MARGIN: usize = 5;

/// Sign every unshielded offer inside `recipe.transaction` using the
/// supplied NIGHT [`SigningKey`], returning the same recipe with
/// signatures populated on each offer's inputs.
///
/// Mirrors TS `WalletFacade.signRecipe` / `signUnprovenTransaction` but
/// takes the signing key directly instead of a callback. See
/// [`sign_unshielded_inputs`] for which offers it signs.
pub fn sign_recipe<R>(
    recipe: UnprovenTransactionRecipe,
    signing_key: &SigningKey,
    rng: &mut R,
) -> Result<UnprovenTransactionRecipe>
where
    R: Rng + CryptoRng,
{
    Ok(UnprovenTransactionRecipe {
        transaction: sign_unshielded_inputs(recipe.transaction, signing_key, rng)?,
    })
}

/// Sign, with `signing_key`, every unshielded offer in `tx` that holds
/// inputs but no signatures yet, in its guaranteed and its fallible
/// section alike. Offers already signed, and intents with no unsigned
/// offer (a dust-fee intent, a registration signed by its builder),
/// pass through unchanged. Works at any proof stage: the signed data
/// erases proofs and signatures, so it is the same before proving and
/// after.
///
/// Mirrors the unshielded wallet's `signUnprovenTransaction` /
/// `signUnboundTransaction` in midnight-wallet.
///
/// # Errors
///
/// [`WalletError::SigningFailed`] when an offer to sign spends an input
/// `signing_key` does not own, or is partly signed: its signatures
/// covered the intent before inputs were added, so they no longer hold.
pub fn sign_unshielded_inputs<P, B, R>(
    tx: Transaction<Signature, P, B, InMemoryDB>,
    signing_key: &SigningKey,
    rng: &mut R,
) -> Result<Transaction<Signature, P, B, InMemoryDB>>
where
    P: ProofKind<InMemoryDB>,
    B: Storable<InMemoryDB> + PedersenDowngradeable<InMemoryDB> + Serializable,
    R: Rng + CryptoRng,
{
    let Transaction::Standard(stx) = tx else {
        return Ok(tx);
    };
    let verifying_key = signing_key.verifying_key();
    let mut intents = stx.intents.clone();
    for segment in stx.intents.keys() {
        let Some(intent) = stx.intents.get(&segment) else {
            continue;
        };
        let mut intent = (*intent).clone();
        if !needs_signing(intent.guaranteed_unshielded_offer.as_deref())
            && !needs_signing(intent.fallible_unshielded_offer.as_deref())
        {
            continue;
        }
        let data = intent
            .erase_proofs()
            .erase_signatures()
            .data_to_sign(segment);
        intent.guaranteed_unshielded_offer = sign_offer(
            intent.guaranteed_unshielded_offer.as_deref(),
            signing_key,
            &verifying_key,
            &data,
            rng,
        )?
        .or(intent.guaranteed_unshielded_offer);
        intent.fallible_unshielded_offer = sign_offer(
            intent.fallible_unshielded_offer.as_deref(),
            signing_key,
            &verifying_key,
            &data,
            rng,
        )?
        .or(intent.fallible_unshielded_offer);
        intents = intents.insert(segment, intent);
    }
    Ok(Transaction::Standard(StandardTransaction {
        network_id: stx.network_id.clone(),
        intents,
        guaranteed_coins: stx.guaranteed_coins.clone(),
        fallible_coins: stx.fallible_coins.clone(),
        binding_randomness: stx.binding_randomness,
    }))
}

fn needs_signing(offer: Option<&UnshieldedOffer<Signature, InMemoryDB>>) -> bool {
    offer.is_some_and(|o| o.signatures.len() < o.inputs.len())
}

/// The signed copy of `offer` when it needs signing, else `None`.
fn sign_offer<R>(
    offer: Option<&UnshieldedOffer<Signature, InMemoryDB>>,
    signing_key: &SigningKey,
    verifying_key: &VerifyingKey,
    data: &[u8],
    rng: &mut R,
) -> Result<Option<Sp<UnshieldedOffer<Signature, InMemoryDB>, InMemoryDB>>>
where
    R: Rng + CryptoRng,
{
    let Some(offer) = offer.filter(|o| needs_signing(Some(o))) else {
        return Ok(None);
    };
    if !offer.signatures.is_empty() {
        return Err(WalletError::SigningFailed(
            "an unshielded offer is partly signed; its signatures no longer cover the intent"
                .to_owned(),
        ));
    }
    let mut signatures = Vec::with_capacity(offer.inputs.len());
    for input in offer.inputs.iter() {
        if input.owner != *verifying_key {
            return Err(WalletError::SigningFailed(
                "an unsigned unshielded input belongs to another key".to_owned(),
            ));
        }
        signatures.push(signing_key.sign(rng, data));
    }
    let mut signed = offer.clone();
    signed.add_signatures(signatures);
    Ok(Some(Sp::new(signed)))
}

/// True when `tx` already carries a dust-balancing intent (any intent
/// with dust actions). Lets callers skip a redundant
/// [`balance_dust_fee`] pass on a tx whose fee is already covered —
/// e.g. a contract-runtime call tx, which merges dust coverage at the
/// preimage stage. Double-balancing such a tx produces a malformed,
/// node-rejected transaction.
#[must_use]
pub fn has_dust_balancing_intent(tx: &UnprovenTransaction) -> bool {
    match tx {
        Transaction::Standard(stx) => stx.intents.iter().any(|entry| {
            let pair = &*entry;
            let intent = &*pair.1;
            intent.dust_actions.is_some()
        }),
        Transaction::ClaimRewards(_) => false,
    }
}

/// Seed for the [`StdRng`] used inside the fee estimator. The estimator
/// runs in a tight loop with ephemeral dry-run state — a deterministic
/// seed keeps runs reproducible without impacting on-chain content
/// (which uses the caller's rng).
const FEE_ESTIMATOR_RNG_SEED: u64 = 0xFE_ED_FA_CE;

// =====================================================================
// Convenience: parse a loose `(recipient, amount, token_label)` triple
// into the `Vec<CombinedTokenTransfer>` shape `build_facade_transfer_recipe`
// expects. Used by both the CLI's `wallet transfer` verb and the REPL's
// `wallet.transfer(...)` host fn so the dispatch lives in one place.
// =====================================================================

/// Map an unshielded token label to a [`TokenType`]. The `"NIGHT"` /
/// `"night"` / `"native"` aliases collapse onto the canonical
/// `"native"` label every other workspace site keys on; arbitrary
/// labels (custom unshielded token types) pass through verbatim
/// (matches `crates/cli/src/commands/wallet.rs` and the upstream TS
/// SDK convention).
#[must_use]
pub fn parse_unshielded_token_label(label: &str) -> TokenType {
    match label {
        "NIGHT" | "night" | "native" => TokenType::new("native"),
        other => TokenType::new(other),
    }
}

/// Map a shielded token label to a [`ShieldedTokenType`]. `"NIGHT"`
/// / `"native"` resolves to [`ShieldedTokenType::default`] (the
/// reserved zero-hash); any other label is parsed as 32-byte hex —
/// the same form `ContractAddress::custom_shielded_token_type`
/// emits.
pub fn parse_shielded_token_label(label: &str) -> Result<ShieldedTokenType> {
    use moonproof_ledger::base_crypto::hash::HashOutput;
    if matches!(label, "NIGHT" | "night" | "native") {
        return Ok(ShieldedTokenType::default());
    }
    let trimmed = label.trim_start_matches("0x");
    let bytes = hex::decode(trimmed).map_err(|e| {
        WalletError::Bech32(format!(
            "shielded token-type `{label}` not 32-byte hex: {e}"
        ))
    })?;
    let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
        WalletError::Bech32(format!(
            "shielded token-type must be 32 bytes; got {}",
            bytes.len()
        ))
    })?;
    Ok(ShieldedTokenType(HashOutput(arr)))
}

/// Auto-dispatch a transfer-output triple based on the recipient's
/// bech32m kind. Shielded address + label → `Shielded(...)` batch;
/// unshielded address + label → `Unshielded(...)` batch.
///
/// Errors:
/// - `DUST` rejected (fee-only on this ledger).
/// - Recipient bech32m parses as neither shielded nor unshielded.
/// - Shielded path: token label not `"native"` or 32-byte hex.
pub fn build_combined_outputs(
    recipient: &str,
    amount: u128,
    token_label: &str,
) -> Result<Vec<CombinedTokenTransfer>> {
    use crate::address::UnshieldedAddress;

    if matches!(token_label, "DUST" | "dust") {
        return Err(WalletError::Bech32(
            "dust transfers are paid as fees, not user-initiated transfers".to_owned(),
        ));
    }

    if let Ok(shielded) = ShieldedAddress::parse(recipient) {
        let token_type = parse_shielded_token_label(token_label)?;
        return Ok(vec![CombinedTokenTransfer::Shielded(vec![
            ShieldedTokenTransfer {
                token_type,
                recipient: shielded,
                amount,
            },
        ])]);
    }

    if let Ok(unshielded) = UnshieldedAddress::parse(recipient) {
        let token_type = parse_unshielded_token_label(token_label);
        return Ok(vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type,
                recipient: unshielded.0,
                amount,
            },
        ])]);
    }

    Err(WalletError::Bech32(format!(
        "recipient `{recipient}` is neither a valid shielded nor unshielded bech32m address"
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use crate::address::{ShieldedCoinPublicKey, ShieldedEncryptionPublicKey};
    use crate::dust::DustState;
    use crate::shielded::ShieldedState;
    use crate::unshielded::{
        ledger_adapter::signing_key_from_bytes, UnshieldedState, UnshieldedUpdate, UnshieldedUtxo,
        UtxoId, UtxoMeta, UtxoWithMeta,
    };
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::serialize::Serializable;
    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 shielded_address_of(keys: &ZswapSecretKeys) -> ShieldedAddress {
        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());
        ShieldedAddress::new(coin_pk, enc_pk)
    }

    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)
    }

    fn utxo(intent: u8, value: u128, owner: [u8; 32]) -> UtxoWithMeta {
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([intent; 32], 0),
                value,
                TokenType::new("native"),
                owner,
            ),
            UtxoMeta::new(0, false),
        )
    }

    fn seeded_unshielded(owner: [u8; 32], utxos: Vec<UtxoWithMeta>) -> UnshieldedState {
        let _ = owner;
        UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(utxos, vec![]))
            .unwrap()
    }

    // --- partition_outputs ---------------------------------------------

    #[test]
    fn partition_outputs_separates_shielded_and_unshielded() {
        let keys = zswap_keys(0x10);
        let addr = shielded_address_of(&keys);
        let inputs = vec![
            CombinedTokenTransfer::Unshielded(vec![UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xAA; 32],
                amount: 123,
            }]),
            CombinedTokenTransfer::Shielded(vec![ShieldedTokenTransfer {
                token_type: ShieldedTokenType::default(),
                recipient: addr.clone(),
                amount: 10,
            }]),
        ];
        let (sh, un) = partition_outputs(&inputs);
        assert_eq!(sh.len(), 1);
        assert_eq!(un.len(), 1);
        assert_eq!(un[0].amount, 123);
        assert_eq!(sh[0].recipient, addr);
    }

    #[test]
    fn empty_transfer_list_errors() {
        let mut rng = StdRng::seed_from_u64(1);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);
        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: [0; 32],
        };
        let f = empty_facade(NetworkId::Undeployed);
        let err = build_transfer_recipe(
            &mut rng,
            f,
            &[],
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    // --- Unshielded-only transfer (no fees) ----------------------------

    #[test]
    fn unshielded_only_transfer_produces_merged_standard_tx() {
        let mut rng = StdRng::seed_from_u64(42);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);

        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 1_000_000, owner_bytes)],
        ));

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 100,
            },
        ])];
        let (recipe, new_state) = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false, // empty dust state → cannot pay fees
            },
        )
        .unwrap();

        match &recipe.transaction {
            Transaction::Standard(stx) => {
                assert_eq!(stx.intents.size(), 1, "one unshielded intent at segment 1");
                assert!(stx.guaranteed_coins.is_none(), "no shielded offer");
                assert_eq!(stx.fallible_coins.size(), 0);
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
        // The spent UTXO moved to pending.
        assert_eq!(new_state.unshielded.pending_len(), 1);
        assert_eq!(new_state.unshielded.available_len(), 0);
    }

    /// Fees follow the parameters they are priced against. Pricing
    /// against the ledger's initial parameters instead of the chain's
    /// under-paid once fee prices rose, and the node rejected the
    /// transaction as `BalanceCheckOverspend`.
    #[test]
    fn fee_estimate_scales_with_the_supplied_fee_prices() {
        use moonproof_ledger::base_crypto::cost_model::FixedPoint;
        use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;

        let mut rng = StdRng::seed_from_u64(42);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);
        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 1_000_000, owner_bytes)],
        ));
        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 100,
            },
        ])];
        let (recipe, _) = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();

        let mut pricier = INITIAL_PARAMETERS;
        pricier.fee_prices.overall_price =
            INITIAL_PARAMETERS.fee_prices.overall_price * FixedPoint::from_u64_div(3, 1);
        let base = estimate_unproven_fee(&recipe.transaction, &INITIAL_PARAMETERS);
        let raised = estimate_unproven_fee(&recipe.transaction, &pricier);
        assert!(base > 0, "an unshielded transfer carries a fee");
        assert!(
            raised > base,
            "tripled prices must raise the fee: {raised} <= {base}"
        );
    }

    // --- Shielded-only transfer (no fees) -----------------------------

    #[test]
    fn shielded_only_transfer_produces_tx_with_guaranteed_offer() {
        use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce, ShieldedTokenType};
        use moonproof_ledger::transient_crypto::hash::HashOutput;

        let mut rng = StdRng::seed_from_u64(7);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x05);

        // Seed a shielded state with one coin.
        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: 500,
        };
        local = local.insert_coin(&zsk, coin).unwrap();
        let sh = ShieldedState::init(local, &zsk, NetworkId::Undeployed);
        let du = DustState::init_empty(
            dust_params(),
            &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
            NetworkId::Undeployed,
        );
        let f = FacadeState::new(sh, UnshieldedState::empty(), du, NetworkId::Undeployed);

        let recipient_keys = zswap_keys(0x99);
        let addr = shielded_address_of(&recipient_keys);

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: [0; 32],
        };
        let outputs = vec![CombinedTokenTransfer::Shielded(vec![
            ShieldedTokenTransfer {
                token_type: tt,
                recipient: addr,
                amount: 200,
            },
        ])];
        let (recipe, new_state) = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                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 present");
                assert_eq!(stx.intents.size(), 0, "no unshielded / dust intents");
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
        assert_eq!(new_state.shielded.pending_spend_count(), 1);
    }

    // --- Mixed shielded + unshielded transfer --------------------------

    /// A shielded + unshielded transfer from a facade holding one
    /// shielded coin and one NIGHT `UTxO`.
    fn build_mixed_transfer() -> (UnprovenTransactionRecipe, FacadeState) {
        use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce, ShieldedTokenType};
        use moonproof_ledger::transient_crypto::hash::HashOutput;

        let mut rng = StdRng::seed_from_u64(7);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x05);

        let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
        let tt = ShieldedTokenType(HashOutput([0xCD; 32]));
        let coin = CoinInfo {
            nonce: Nonce(HashOutput([0x02; 32])),
            type_: tt,
            value: 1_000,
        };
        local = local.insert_coin(&zsk, coin).unwrap();
        let sh = ShieldedState::init(local, &zsk, NetworkId::Undeployed);

        let du = DustState::init_empty(
            dust_params(),
            &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
            NetworkId::Undeployed,
        );

        let unshielded = seeded_unshielded(owner_bytes, vec![utxo(0x11, 500_000, owner_bytes)]);
        let f = FacadeState::new(sh, unshielded, du, NetworkId::Undeployed);

        let recipient_keys = zswap_keys(0x99);
        let shielded_recipient = shielded_address_of(&recipient_keys);

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![
            CombinedTokenTransfer::Shielded(vec![ShieldedTokenTransfer {
                token_type: tt,
                recipient: shielded_recipient,
                amount: 100,
            }]),
            CombinedTokenTransfer::Unshielded(vec![UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xAA; 32],
                amount: 200,
            }]),
        ];
        build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap()
    }

    #[test]
    fn mixed_transfer_merges_shielded_offer_and_unshielded_intent() {
        let (recipe, _new_state) = build_mixed_transfer();

        match &recipe.transaction {
            Transaction::Standard(stx) => {
                assert!(
                    stx.guaranteed_coins.is_some(),
                    "shielded offer landed in guaranteed_coins"
                );
                assert_eq!(
                    stx.intents.size(),
                    1,
                    "unshielded intent merged at segment 1"
                );
                assert!(
                    stx.intents.contains_key(&PRIMARY_SEGMENT_ID),
                    "intent at expected segment"
                );
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn a_rejected_transfer_releases_everything_it_booked() {
        let (recipe, booked) = build_mixed_transfer();
        assert_eq!(booked.unshielded.pending_len(), 1);
        assert_eq!(booked.shielded.pending_spend_count(), 1);

        let released = booked.revert_transaction(&recipe.transaction);
        assert_eq!(released.unshielded.pending_len(), 0);
        assert_eq!(released.unshielded.available_len(), 1);
        assert_eq!(released.shielded.pending_spend_count(), 0);

        let again = released.clone().revert_transaction(&recipe.transaction);
        assert_eq!(
            again.unshielded.available_len(),
            1,
            "releasing twice changes nothing"
        );
    }

    #[test]
    fn insufficient_unshielded_funds_surfaces_as_insufficient_funds() {
        let mut rng = StdRng::seed_from_u64(3);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);

        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 10, owner_bytes)],
        ));

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 1_000,
            },
        ])];
        let err = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    // --- pay_fees with empty dust state errors ------------------------

    #[test]
    fn pay_fees_true_with_no_dust_errors_insufficient() {
        let mut rng = StdRng::seed_from_u64(9);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);

        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 1_000_000, owner_bytes)],
        ));

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 100,
            },
        ])];
        let err = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: true, // empty dust → insufficient funds error
            },
        )
        .unwrap_err();
        // The exact variant depends on whether standalone_fee is 0 (then
        // picked_coins=[], merged fee still >0 for any Standard tx, and
        // convergence fails via InsufficientFunds). Accept both.
        assert!(
            matches!(
                err,
                WalletError::InsufficientFunds { .. } | WalletError::Dust(_)
            ),
            "unexpected variant: {err:?}"
        );
    }

    #[test]
    fn used_intent_segments_reads_standard_intents() {
        // Quick sanity for the helper — empty map → empty set.
        let empty: UnprovenTransaction =
            Transaction::from_intents("undeployed", StorageHashMap::new());
        assert!(used_intent_segments(&empty).is_empty());
    }

    // --- sign_recipe ---------------------------------------------------

    #[test]
    fn sign_recipe_populates_unshielded_offer_signatures() {
        let mut rng = StdRng::seed_from_u64(0xA11CE);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);

        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 1_000_000, owner_bytes)],
        ));

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 100,
            },
        ])];
        let (unsigned_recipe, _new_state) = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();

        // Before sign_recipe: signatures array is empty.
        match &unsigned_recipe.transaction {
            Transaction::Standard(stx) => {
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let offer = intent.guaranteed_unshielded_offer.as_ref().unwrap();
                assert_eq!(offer.signatures.len(), 0);
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }

        let signed = sign_recipe(unsigned_recipe, &sk, &mut rng).unwrap();

        // After sign_recipe: one signature per input.
        match &signed.transaction {
            Transaction::Standard(stx) => {
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let offer = intent.guaranteed_unshielded_offer.as_ref().unwrap();
                assert_eq!(offer.signatures.len(), offer.inputs.len());
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn sign_recipe_is_idempotent_for_already_signed_intents() {
        let mut rng = StdRng::seed_from_u64(0xB0B);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner_bytes = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let zsk = zswap_keys(0x01);

        let f = empty_facade(NetworkId::Undeployed).with_unshielded(seeded_unshielded(
            owner_bytes,
            vec![utxo(0x01, 1_000_000, owner_bytes)],
        ));

        let keys = TransferSigningKeys {
            shielded_secret_keys: &zsk,
            dust_secret_key: &dsk,
            night_signing_key: &sk,
            night_verifying_key: &vk,
            sender_owner: owner_bytes,
        };
        let outputs = vec![CombinedTokenTransfer::Unshielded(vec![
            UnshieldedTokenTransfer {
                token_type: TokenType::new("native"),
                recipient: [0xBB; 32],
                amount: 100,
            },
        ])];
        let (recipe, _) = build_transfer_recipe(
            &mut rng,
            f,
            &outputs,
            &keys,
            &TransferOptions {
                ttl: Timestamp::from_secs(3600),
                current_time: Timestamp::from_secs(0),
                pay_fees: false,
            },
        )
        .unwrap();

        let signed = sign_recipe(recipe, &sk, &mut rng).unwrap();
        // Second call must not error (the first call populated
        // signatures; the second call sees them and skips).
        let signed_twice = sign_recipe(signed, &sk, &mut rng).unwrap();
        match &signed_twice.transaction {
            Transaction::Standard(stx) => {
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let offer = intent.guaranteed_unshielded_offer.as_ref().unwrap();
                assert_eq!(offer.signatures.len(), offer.inputs.len());
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn parse_unshielded_token_label_normalises_native_aliases() {
        assert_eq!(parse_unshielded_token_label("NIGHT").as_str(), "native");
        assert_eq!(parse_unshielded_token_label("native").as_str(), "native");
        assert_eq!(
            parse_unshielded_token_label("custom-tok").as_str(),
            "custom-tok"
        );
    }

    #[test]
    fn parse_shielded_token_label_native_maps_to_default() {
        assert_eq!(
            parse_shielded_token_label("native").unwrap(),
            ShieldedTokenType::default()
        );
    }

    #[test]
    fn parse_shielded_token_label_accepts_32_byte_hex_with_or_without_prefix() {
        let bare = "a".repeat(64);
        let prefixed = format!("0x{bare}");
        let parsed_a = parse_shielded_token_label(&bare).unwrap();
        let parsed_b = parse_shielded_token_label(&prefixed).unwrap();
        assert_eq!(parsed_a, parsed_b);
        assert_eq!(parsed_a.0 .0[..], [0xaa; 32][..]);
    }

    #[test]
    fn parse_shielded_token_label_rejects_wrong_length() {
        let err = parse_shielded_token_label(&"a".repeat(62)).unwrap_err();
        assert!(format!("{err}").contains("32 bytes"));
    }

    #[test]
    fn build_combined_outputs_rejects_dust() {
        let err = build_combined_outputs("addr", 1, "DUST").unwrap_err();
        assert!(format!("{err}").contains("dust"));
    }

    #[test]
    fn build_combined_outputs_rejects_invalid_address() {
        let err = build_combined_outputs("not-bech32", 1, "NIGHT").unwrap_err();
        assert!(format!("{err}").contains("neither a valid shielded nor unshielded"));
    }
}