cashu 0.18.0

Cashu shared types and crypto utilities, used as the foundation for the CDK and their crates
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
//! NUT-04: Mint Tokens via Bolt11
//!
//! <https://github.com/cashubtc/nuts/blob/main/04.md>

use std::fmt;
#[cfg(feature = "mint")]
use std::str::FromStr;

use serde::de::{self, DeserializeOwned, Deserializer, MapAccess, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::nut00::{BlindSignature, BlindedMessage, CurrencyUnit, PaymentMethod};
use crate::nut00::KnownMethod;
#[cfg(feature = "mint")]
use crate::quote_id::QuoteId;
#[cfg(feature = "mint")]
use crate::quote_id::QuoteIdError;
use crate::util::serde_helpers::deserialize_empty_string_as_none;
use crate::{Amount, PublicKey};

/// NUT04 Error
#[derive(Debug, Error)]
pub enum Error {
    /// Unknown Quote State
    #[error("Unknown Quote State")]
    UnknownState,
    /// Amount overflow
    #[error("Amount overflow")]
    AmountOverflow,
}

/// Mint request [NUT-04]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub struct MintRequest<Q> {
    /// Quote id
    pub quote: Q,
    /// Outputs
    pub outputs: Vec<BlindedMessage>,
    /// Signature
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

#[cfg(feature = "mint")]
impl TryFrom<MintRequest<String>> for MintRequest<QuoteId> {
    type Error = QuoteIdError;

    fn try_from(value: MintRequest<String>) -> Result<Self, Self::Error> {
        Ok(Self {
            quote: QuoteId::from_str(&value.quote)?,
            outputs: value.outputs,
            signature: value.signature,
        })
    }
}

impl<Q> MintRequest<Q> {
    /// Total [`Amount`] of outputs
    pub fn total_amount(&self) -> Result<Amount, Error> {
        Amount::try_sum(
            self.outputs
                .iter()
                .map(|BlindedMessage { amount, .. }| *amount),
        )
        .map_err(|_| Error::AmountOverflow)
    }
}

/// Mint response [NUT-04]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MintResponse {
    /// Blinded Signatures
    pub signatures: Vec<BlindSignature>,
}

/// Mint Method Settings
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MintMethodSettings {
    /// Payment Method e.g. bolt11
    pub method: PaymentMethod,
    /// Currency Unit e.g. sat
    pub unit: CurrencyUnit,
    /// Human-readable name for the payment method.
    ///
    /// If null or omitted on the wire, wallets should derive it from `method`
    /// by replacing `_` and `-` with spaces and title-casing each word.
    pub method_name: Option<String>,
    /// Min Amount
    pub min_amount: Option<Amount>,
    /// Max Amount
    pub max_amount: Option<Amount>,
    /// Options
    pub options: Option<MintMethodOptions>,
}

impl MintMethodSettings {
    /// Human-readable payment method name.
    ///
    /// Returns the explicit `method_name` when present. If it is null or omitted,
    /// derives the name from `method` by replacing `_` and `-` with spaces and
    /// title-casing each word.
    pub fn method_name(&self) -> String {
        self.method_name
            .clone()
            .unwrap_or_else(|| self.method.derived_method_name())
    }
}

impl Serialize for MintMethodSettings {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut num_fields = 2; // method and unit are always present
        if self.min_amount.is_some() {
            num_fields += 1;
        }
        if self.max_amount.is_some() {
            num_fields += 1;
        }
        if self.method_name.is_some() {
            num_fields += 1;
        }

        let mut nested_description: Option<bool> = None;
        let mut onchain_confirmations: Option<u32> = None;

        match &self.options {
            // NUT-23 (bolt11) and NUT-25 (bolt12) advertise description support
            // in a nested options object.
            Some(MintMethodOptions::Bolt11 { description })
            | Some(MintMethodOptions::Bolt12 { description }) => {
                nested_description = Some(*description);
                num_fields += 1; // for the "options" field
            }
            Some(MintMethodOptions::Onchain { confirmations }) => {
                onchain_confirmations = Some(*confirmations);
                num_fields += 1; // for the "options" field
            }
            _ => {}
        }

        let mut state = serializer.serialize_struct("MintMethodSettings", num_fields)?;

        state.serialize_field("method", &self.method)?;
        state.serialize_field("unit", &self.unit)?;

        if let Some(method_name) = &self.method_name {
            state.serialize_field("method_name", method_name)?;
        }

        if let Some(min_amount) = &self.min_amount {
            state.serialize_field("min_amount", min_amount)?;
        }

        if let Some(max_amount) = &self.max_amount {
            state.serialize_field("max_amount", max_amount)?;
        }

        // Serialize onchain options as a nested "options" object
        if let Some(confirmations) = onchain_confirmations {
            #[derive(Serialize)]
            struct OnchainOptions {
                confirmations: u32,
            }
            state.serialize_field("options", &OnchainOptions { confirmations })?;
        }

        // Serialize bolt11/bolt12 description as a nested "options" object
        if let Some(description) = nested_description {
            #[derive(Serialize)]
            struct DescriptionOptions {
                description: bool,
            }
            state.serialize_field("options", &DescriptionOptions { description })?;
        }

        state.end()
    }
}

struct MintMethodSettingsVisitor;

impl<'de> Visitor<'de> for MintMethodSettingsVisitor {
    type Value = MintMethodSettings;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a MintMethodSettings structure")
    }

    fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
    where
        M: MapAccess<'de>,
    {
        let mut method: Option<PaymentMethod> = None;
        let mut unit: Option<CurrencyUnit> = None;
        let mut method_name: Option<String> = None;
        let mut min_amount: Option<Amount> = None;
        let mut max_amount: Option<Amount> = None;
        let mut description: Option<bool> = None;
        let mut confirmations: Option<u32> = None;

        while let Some(key) = map.next_key::<String>()? {
            match key.as_str() {
                "method" => {
                    if method.is_some() {
                        return Err(de::Error::duplicate_field("method"));
                    }
                    method = Some(map.next_value()?);
                }
                "unit" => {
                    if unit.is_some() {
                        return Err(de::Error::duplicate_field("unit"));
                    }
                    unit = Some(map.next_value()?);
                }
                "method_name" => {
                    if method_name.is_some() {
                        return Err(de::Error::duplicate_field("method_name"));
                    }
                    method_name = map.next_value()?;
                }
                "min_amount" => {
                    if min_amount.is_some() {
                        return Err(de::Error::duplicate_field("min_amount"));
                    }
                    min_amount = Some(map.next_value()?);
                }
                "max_amount" => {
                    if max_amount.is_some() {
                        return Err(de::Error::duplicate_field("max_amount"));
                    }
                    max_amount = Some(map.next_value()?);
                }
                "description" => {
                    if description.is_some() {
                        return Err(de::Error::duplicate_field("description"));
                    }
                    description = Some(map.next_value()?);
                }
                "confirmations" => {
                    return Err(de::Error::unknown_field("confirmations", &["options"]));
                }
                "options" => {
                    // If there are explicit options, they take precedence, except the description
                    // field which we will handle specially
                    let options: Option<MintMethodOptions> = map.next_value()?;

                    if let Some(MintMethodOptions::Bolt11 {
                        description: desc_from_options,
                    }) = options
                    {
                        // If we already found a top-level description, use that instead
                        if description.is_none() {
                            description = Some(desc_from_options);
                        }
                    }

                    if let Some(MintMethodOptions::Onchain {
                        confirmations: conf_from_options,
                    }) = options
                    {
                        confirmations = Some(conf_from_options);
                    }
                }
                _ => {
                    // Skip unknown fields
                    let _: serde::de::IgnoredAny = map.next_value()?;
                }
            }
        }

        let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
        let unit = unit.ok_or_else(|| de::Error::missing_field("unit"))?;

        // Create options based on the method and the description flag
        // Note: the wire format of both bolt11 and bolt12 description options is
        // {"description": bool}, which untagged deserialization maps to the
        // Bolt11 variant. It is remapped here based on the method.
        let options = if method == PaymentMethod::Known(KnownMethod::Bolt11) {
            description.map(|desc| MintMethodOptions::Bolt11 { description: desc })
        } else if method == PaymentMethod::Known(KnownMethod::Bolt12) {
            description.map(|desc| MintMethodOptions::Bolt12 { description: desc })
        } else if method == PaymentMethod::Known(KnownMethod::Onchain) {
            confirmations.map(|conf| MintMethodOptions::Onchain {
                confirmations: conf,
            })
        } else {
            None
        };

        Ok(MintMethodSettings {
            method,
            unit,
            method_name,
            min_amount,
            max_amount,
            options,
        })
    }
}

impl<'de> Deserialize<'de> for MintMethodSettings {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(MintMethodSettingsVisitor)
    }
}

/// Mint Method settings options
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MintMethodOptions {
    /// Bolt11 Options
    Bolt11 {
        /// Mint supports setting bolt11 description
        description: bool,
    },
    /// Bolt12 Options
    Bolt12 {
        /// Mint supports setting bolt12 description
        description: bool,
    },
    /// Onchain Options
    Onchain {
        /// Minimum number of confirmations required
        confirmations: u32,
    },
    /// Custom Options
    Custom {},
}

/// Mint Settings
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct Settings {
    /// Methods to mint
    pub methods: Vec<MintMethodSettings>,
    /// Minting disabled
    pub disabled: bool,
}

impl Settings {
    /// Create new [`Settings`]
    pub fn new(methods: Vec<MintMethodSettings>, disabled: bool) -> Self {
        Self { methods, disabled }
    }

    /// Get [`MintMethodSettings`] for unit method pair
    pub fn get_settings(
        &self,
        unit: &CurrencyUnit,
        method: &PaymentMethod,
    ) -> Option<MintMethodSettings> {
        for method_settings in self.methods.iter() {
            if method_settings.method.eq(method) && method_settings.unit.eq(unit) {
                return Some(method_settings.clone());
            }
        }

        None
    }

    /// Remove [`MintMethodSettings`] for unit method pair
    pub fn remove_settings(
        &mut self,
        unit: &CurrencyUnit,
        method: &PaymentMethod,
    ) -> Option<MintMethodSettings> {
        self.methods
            .iter()
            .position(|settings| &settings.method == method && &settings.unit == unit)
            .map(|index| self.methods.remove(index))
    }

    /// Supported nut04 methods
    pub fn supported_methods(&self) -> Vec<&PaymentMethod> {
        self.methods.iter().map(|a| &a.method).collect()
    }

    /// Supported nut04 units
    pub fn supported_units(&self) -> Vec<&CurrencyUnit> {
        self.methods.iter().map(|s| &s.unit).collect()
    }
}

/// Custom payment method mint quote request
///
/// This is a generic request type that works for any custom payment method.
/// The method name is provided in the URL path, not in the request body.
///
/// The `extra` field allows payment-method-specific fields to be included
/// without being nested. When serialized, extra fields merge into the parent JSON.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MintQuoteCustomRequest {
    /// Amount to mint
    ///
    /// Optional common field. Method-specific NUTs make it required or ignore
    /// it as needed (e.g. NUT-23 requires `amount`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub amount: Option<Amount>,
    /// Currency unit
    pub unit: CurrencyUnit,
    /// Optional description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// NUT-19 Pubkey
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pubkey: Option<PublicKey>,
    /// Extra payment-method-specific fields
    ///
    /// These fields are flattened into the JSON representation, allowing
    /// custom payment methods to include additional data (e.g., ehash share).
    /// This enables proper validation layering: the mint verifies well-defined
    /// fields while passing extra through to the payment processor.
    #[serde(flatten, default, skip_serializing_if = "serde_json::Value::is_null")]
    pub extra: serde_json::Value,
}

/// Custom payment method mint quote response
///
/// This is a generic response type for custom payment methods.
///
/// The `extra` field allows payment-method-specific fields to be included
/// without being nested. When serialized, extra fields merge into the parent JSON:
/// ```json
/// {
///   "quote": "abc123",
///   "method": "paypal",
///   "amount": 1000,
///   "amount_paid": 0,
///   "amount_issued": 0,
///   "paypal_link": "https://paypal.me/merchant",
///   "paypal_email": "merchant@example.com"
/// }
/// ```
///
/// This separation enables proper validation layering: the mint verifies
/// well-defined fields (amount, unit, etc.) while passing extra through
/// to the gRPC payment processor for method-specific validation.
///
/// It also provides a clean upgrade path: when a payment method becomes speced,
/// its fields can be promoted from `extra` to well-defined struct fields without
/// breaking existing clients (e.g., bolt12's `amount_paid` and `amount_issued`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + for<'a> Deserialize<'a>")]
pub struct MintQuoteCustomResponse<Q> {
    /// Quote ID
    pub quote: Q,
    /// Payment request string (method-specific format)
    pub request: String,
    /// Payment method
    pub method: PaymentMethod,
    /// Amount
    pub amount: Option<Amount>,
    /// Amount that has been paid
    pub amount_paid: Amount,
    /// Amount that has been issued
    pub amount_issued: Amount,
    /// Unix timestamp indicating when the quote was last updated
    #[serde(default)]
    pub updated_at: u64,
    /// Currency unit
    pub unit: Option<CurrencyUnit>,
    /// Unix timestamp until the quote is valid
    pub expiry: Option<u64>,
    /// NUT-19 Pubkey
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_empty_string_as_none"
    )]
    pub pubkey: Option<PublicKey>,
    /// Extra payment-method-specific fields
    ///
    /// These fields are flattened into the JSON representation, allowing
    /// custom payment methods to include additional data without nesting.
    #[serde(flatten, default, skip_serializing_if = "serde_json::Value::is_null")]
    pub extra: serde_json::Value,
}

#[cfg(feature = "mint")]
impl<Q: ToString> MintQuoteCustomResponse<Q> {
    /// Convert the MintQuoteCustomResponse with a quote type Q to a String
    pub fn to_string_id(&self) -> MintQuoteCustomResponse<String> {
        MintQuoteCustomResponse {
            quote: self.quote.to_string(),
            request: self.request.clone(),
            method: self.method.clone(),
            amount: self.amount,
            amount_paid: self.amount_paid,
            amount_issued: self.amount_issued,
            updated_at: self.updated_at,
            unit: self.unit.clone(),
            expiry: self.expiry,
            pubkey: self.pubkey,
            extra: self.extra.clone(),
        }
    }
}

#[cfg(feature = "mint")]
impl From<MintQuoteCustomResponse<QuoteId>> for MintQuoteCustomResponse<String> {
    fn from(value: MintQuoteCustomResponse<QuoteId>) -> Self {
        Self {
            quote: value.quote.to_string(),
            request: value.request,
            method: value.method,
            amount: value.amount,
            amount_paid: value.amount_paid,
            amount_issued: value.amount_issued,
            updated_at: value.updated_at,
            unit: value.unit,
            expiry: value.expiry,
            pubkey: value.pubkey,
            extra: value.extra,
        }
    }
}
#[cfg(test)]
mod tests {
    use std::fmt;

    use serde::ser::{Impossible, SerializeStruct, Serializer};
    use serde_json::{from_str, json, to_string};

    use super::*;
    use crate::nut00::KnownMethod;

    #[derive(Debug)]
    struct FieldCountError(String);

    impl fmt::Display for FieldCountError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(&self.0)
        }
    }

    impl std::error::Error for FieldCountError {}

    impl serde::ser::Error for FieldCountError {
        fn custom<T>(msg: T) -> Self
        where
            T: fmt::Display,
        {
            Self(msg.to_string())
        }
    }

    struct FieldCountSerializer;

    struct FieldCountStruct {
        declared: usize,
        actual: usize,
    }

    impl Serializer for FieldCountSerializer {
        type Ok = ();
        type Error = FieldCountError;
        type SerializeSeq = Impossible<Self::Ok, Self::Error>;
        type SerializeTuple = Impossible<Self::Ok, Self::Error>;
        type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
        type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
        type SerializeMap = Impossible<Self::Ok, Self::Error>;
        type SerializeStruct = FieldCountStruct;
        type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;

        fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported bool".to_string()))
        }

        fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported i8".to_string()))
        }

        fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported i16".to_string()))
        }

        fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported i32".to_string()))
        }

        fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported i64".to_string()))
        }

        fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported u8".to_string()))
        }

        fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported u16".to_string()))
        }

        fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported u32".to_string()))
        }

        fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported u64".to_string()))
        }

        fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported f32".to_string()))
        }

        fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported f64".to_string()))
        }

        fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported char".to_string()))
        }

        fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported str".to_string()))
        }

        fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported bytes".to_string()))
        }

        fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported none".to_string()))
        }

        fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            Err(FieldCountError("unsupported some".to_string()))
        }

        fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported unit".to_string()))
        }

        fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported unit struct".to_string()))
        }

        fn serialize_unit_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
        ) -> Result<Self::Ok, Self::Error> {
            Err(FieldCountError("unsupported unit variant".to_string()))
        }

        fn serialize_newtype_struct<T>(
            self,
            _name: &'static str,
            _value: &T,
        ) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            Err(FieldCountError("unsupported newtype struct".to_string()))
        }

        fn serialize_newtype_variant<T>(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _value: &T,
        ) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            Err(FieldCountError("unsupported newtype variant".to_string()))
        }

        fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
            Err(FieldCountError("unsupported seq".to_string()))
        }

        fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
            Err(FieldCountError("unsupported tuple".to_string()))
        }

        fn serialize_tuple_struct(
            self,
            _name: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeTupleStruct, Self::Error> {
            Err(FieldCountError("unsupported tuple struct".to_string()))
        }

        fn serialize_tuple_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeTupleVariant, Self::Error> {
            Err(FieldCountError("unsupported tuple variant".to_string()))
        }

        fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
            Err(FieldCountError("unsupported map".to_string()))
        }

        fn serialize_struct(
            self,
            _name: &'static str,
            len: usize,
        ) -> Result<Self::SerializeStruct, Self::Error> {
            Ok(FieldCountStruct {
                declared: len,
                actual: 0,
            })
        }

        fn serialize_struct_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeStructVariant, Self::Error> {
            Err(FieldCountError("unsupported struct variant".to_string()))
        }
    }

    impl SerializeStruct for FieldCountStruct {
        type Ok = ();
        type Error = FieldCountError;

        fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.actual += 1;
            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            if self.actual == self.declared {
                Ok(())
            } else {
                Err(FieldCountError(format!(
                    "declared {} fields but serialized {}",
                    self.declared, self.actual
                )))
            }
        }
    }

    fn assert_mint_method_settings_field_count(settings: &MintMethodSettings) {
        settings.serialize(FieldCountSerializer).unwrap();
    }

    #[test]
    fn test_mint_request_total_amount() {
        let request: MintRequest<String> = from_str(
            r#"{
                "quote": "quote-id",
                "outputs": [
                    {
                        "amount": 2,
                        "id": "00bfa73302d12ffd",
                        "B_": "038ec853d65ae1b79b5cdbc2774150b2cb288d6d26e12958a16fb33c32d9a86c39"
                    },
                    {
                        "amount": 4,
                        "id": "00bfa73302d12ffd",
                        "B_": "02c97ee3d1db41cf0a3ddb601724be8711a032950811bf326f8219c50c4808d3cd"
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(request.total_amount().unwrap(), Amount::from(6));
    }

    #[test]
    fn test_mint_method_settings_serialize_field_count() {
        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(1)),
            max_amount: Some(Amount::from(1000)),
            options: Some(MintMethodOptions::Bolt11 { description: true }),
        });

        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(1)),
            max_amount: None,
            options: None,
        });

        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: None,
            max_amount: Some(Amount::from(1000)),
            options: None,
        });

        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: None,
            max_amount: None,
            options: Some(MintMethodOptions::Bolt11 { description: true }),
        });

        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Onchain),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: None,
            max_amount: None,
            options: Some(MintMethodOptions::Onchain { confirmations: 3 }),
        });

        assert_mint_method_settings_field_count(&MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: Some("Lightning".to_string()),
            min_amount: None,
            max_amount: None,
            options: None,
        });
    }

    #[test]
    fn test_mint_method_settings_top_level_description() {
        // Create JSON with top-level description
        let json_str = r#"{
            "method": "bolt11",
            "unit": "sat",
            "min_amount": 0,
            "max_amount": 10000,
            "description": true
        }"#;

        // Deserialize it
        let settings: MintMethodSettings = from_str(json_str).unwrap();

        // Check that description was correctly moved to options
        assert_eq!(settings.method, PaymentMethod::Known(KnownMethod::Bolt11));
        assert_eq!(settings.unit, CurrencyUnit::Sat);
        assert_eq!(settings.method_name, None);
        assert_eq!(settings.min_amount, Some(Amount::from(0)));
        assert_eq!(settings.max_amount, Some(Amount::from(10000)));

        match settings.options {
            Some(MintMethodOptions::Bolt11 { description }) => {
                assert!(description);
            }
            _ => panic!("Expected Bolt11 options with description = true"),
        }

        // Serialize it back as nested options per NUT-23
        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["options"]["description"], json!(true));
        assert!(parsed.get("description").is_none());
    }

    #[test]
    fn test_mint_method_settings_serializes_false_description_in_options() {
        let settings = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: None,
            max_amount: None,
            options: Some(MintMethodOptions::Bolt11 { description: false }),
        };

        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["method"], json!("bolt11"));
        assert!(parsed.get("description").is_none());
        assert_eq!(parsed["options"]["description"], json!(false));
    }

    #[test]
    fn test_bolt11_settings_nested_options_round_trip() {
        let json_str = r#"{
            "method": "bolt11",
            "unit": "sat",
            "min_amount": 0,
            "max_amount": 10000,
            "options": {
                "description": true
            }
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        match settings.options {
            Some(MintMethodOptions::Bolt11 { description }) => {
                assert!(description);
            }
            _ => panic!("Expected Bolt11 options with description = true"),
        }

        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["options"]["description"], json!(true));
        assert!(parsed.get("description").is_none());
    }

    #[test]
    fn test_both_description_locations() {
        // Create JSON with description in both places (top level and in options)
        let json_str = r#"{
            "method": "bolt11",
            "unit": "sat",
            "min_amount": 0,
            "max_amount": 10000,
            "description": true,
            "options": {
                "description": false
            }
        }"#;

        // Deserialize it - top level should take precedence
        let settings: MintMethodSettings = from_str(json_str).unwrap();

        match settings.options {
            Some(MintMethodOptions::Bolt11 { description }) => {
                assert!(description, "Top-level description should take precedence");
            }
            _ => panic!("Expected Bolt11 options with description = true"),
        }
    }

    #[test]
    fn test_mint_method_settings_method_name_round_trip() {
        let json_str = r#"{
            "method": "bolt11",
            "unit": "sat",
            "method_name": "Lightning",
            "min_amount": 0,
            "max_amount": 10000
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method_name, Some("Lightning".to_string()));
        assert_eq!(settings.method_name(), "Lightning");

        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["method_name"], json!("Lightning"));
    }

    #[test]
    fn test_mint_method_settings_null_method_name_deserializes_as_none() {
        let json_str = r#"{
            "method": "bolt11",
            "unit": "sat",
            "method_name": null
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method_name, None);
        assert_eq!(settings.method_name(), "Bolt11");

        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert!(parsed.get("method_name").is_none());
    }

    #[test]
    fn test_mint_method_settings_omitted_method_name_uses_derived_name() {
        let json_str = r#"{
            "method": "apple-pay",
            "unit": "usd"
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method_name, None);
        assert_eq!(settings.method_name(), "Apple Pay");
    }

    #[test]
    fn custom_mint_quote_response_has_no_typed_state() {
        let response = MintQuoteCustomResponse {
            quote: "abc123".to_string(),
            request: "paypal://pay?id=123".to_string(),
            method: PaymentMethod::Custom("paypal".to_string()),
            amount: Some(Amount::from(1000)),
            amount_paid: Amount::ZERO,
            amount_issued: Amount::ZERO,
            updated_at: 0,
            unit: Some(CurrencyUnit::Sat),
            expiry: Some(9999999),
            pubkey: None,
            extra: serde_json::Value::Null,
        };

        let serialized = to_string(&response).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert!(parsed.get("state").is_none());
        assert_eq!(parsed["method"], json!("paypal"));
        assert_eq!(parsed["amount_paid"], json!(0));
        assert_eq!(parsed["amount_issued"], json!(0));
    }

    #[test]
    fn custom_mint_quote_response_flattens_extra_on_wire() {
        let response = MintQuoteCustomResponse {
            quote: "q1".to_string(),
            request: "custom://pay".to_string(),
            method: PaymentMethod::Custom("custom".to_string()),
            amount: Some(Amount::from(100)),
            amount_paid: Amount::ZERO,
            amount_issued: Amount::ZERO,
            updated_at: 0,
            unit: Some(CurrencyUnit::Sat),
            expiry: Some(9999),
            pubkey: None,
            extra: json!({"payment_url": "https://example.com", "ref": 42}),
        };

        let serialized = to_string(&response).expect("serializes");
        let parsed: serde_json::Value = from_str(&serialized).expect("parses");

        assert_eq!(parsed["payment_url"], json!("https://example.com"));
        assert_eq!(parsed["ref"], json!(42));
        assert!(
            parsed.get("extra").is_none(),
            "extra must be flattened, not nested under an 'extra' key"
        );
    }

    #[test]
    fn test_onchain_settings_nested_options_round_trip() {
        // NUT-26 spec format: confirmations nested inside "options"
        let json_str = r#"{
            "method": "onchain",
            "unit": "sat",
            "min_amount": 1000,
            "max_amount": 1000000,
            "options": {
                "confirmations": 3
            }
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method, PaymentMethod::Known(KnownMethod::Onchain));
        assert_eq!(settings.unit, CurrencyUnit::Sat);
        assert_eq!(settings.min_amount, Some(Amount::from(1000)));
        assert_eq!(settings.max_amount, Some(Amount::from(1000000)));

        match settings.options {
            Some(MintMethodOptions::Onchain { confirmations }) => {
                assert_eq!(confirmations, 3);
            }
            _ => panic!("Expected Onchain options with confirmations = 3"),
        }

        // Serialize it back and verify the nested "options" structure
        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["method"], json!("onchain"));
        assert_eq!(parsed["options"]["confirmations"], json!(3));
        // Verify confirmations is NOT at top level
        assert!(parsed.get("confirmations").is_none());
    }

    #[test]
    fn test_onchain_settings_top_level_confirmations_rejected() {
        let json_str = r#"{
            "method": "onchain",
            "unit": "sat",
            "confirmations": 6
        }"#;

        let err = from_str::<MintMethodSettings>(json_str).unwrap_err();
        assert!(err.to_string().contains("unknown field"));
    }

    #[test]
    fn test_onchain_settings_top_level_and_nested_rejected() {
        let json_str = r#"{
            "method": "onchain",
            "unit": "sat",
            "confirmations": 6,
            "options": {
                "confirmations": 3
            }
        }"#;

        let err = from_str::<MintMethodSettings>(json_str).unwrap_err();
        assert!(err.to_string().contains("unknown field"));
    }

    #[test]
    fn test_bolt12_settings_nested_options_round_trip() {
        // NUT-25 spec format: description nested inside "options"
        let json_str = r#"{
            "method": "bolt12",
            "unit": "sat",
            "min_amount": 0,
            "max_amount": 10000,
            "options": {
                "description": true
            }
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method, PaymentMethod::Known(KnownMethod::Bolt12));
        assert_eq!(settings.unit, CurrencyUnit::Sat);

        match settings.options {
            Some(MintMethodOptions::Bolt12 { description }) => {
                assert!(description);
            }
            _ => panic!("Expected Bolt12 options with description = true"),
        }

        // Serialize it back and verify the nested "options" structure
        let serialized = to_string(&settings).unwrap();
        let parsed: serde_json::Value = from_str(&serialized).unwrap();

        assert_eq!(parsed["method"], json!("bolt12"));
        assert_eq!(parsed["options"]["description"], json!(true));
        // Verify description is NOT at top level
        assert!(parsed.get("description").is_none());
    }

    #[test]
    fn test_bolt12_settings_top_level_description_accepted() {
        // Some mints place the description flag at the top level; it should be
        // mapped to the Bolt12 options based on the method
        let json_str = r#"{
            "method": "bolt12",
            "unit": "sat",
            "description": true
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method, PaymentMethod::Known(KnownMethod::Bolt12));
        match settings.options {
            Some(MintMethodOptions::Bolt12 { description }) => {
                assert!(description);
            }
            _ => panic!("Expected Bolt12 options with description = true"),
        }
    }

    #[test]
    fn test_bolt12_settings_no_options_when_description_absent() {
        let json_str = r#"{
            "method": "bolt12",
            "unit": "sat"
        }"#;

        let settings: MintMethodSettings = from_str(json_str).unwrap();

        assert_eq!(settings.method, PaymentMethod::Known(KnownMethod::Bolt12));
        assert_eq!(settings.options, None);
    }

    #[test]
    fn test_mint_method_settings_visitor_reports_expected_type() {
        let err = from_str::<MintMethodSettings>("[]").unwrap_err();

        assert!(err.to_string().contains("a MintMethodSettings structure"));
    }

    #[test]
    fn test_get_settings_requires_exact_method_and_unit_match() {
        let bolt11_msat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Msat,
            method_name: None,
            min_amount: Some(Amount::from(1)),
            max_amount: None,
            options: None,
        };
        let bolt12_sat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt12),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(2)),
            max_amount: None,
            options: None,
        };
        let bolt11_sat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(3)),
            max_amount: None,
            options: None,
        };
        let settings = Settings::new(
            vec![bolt11_msat.clone(), bolt12_sat.clone(), bolt11_sat.clone()],
            false,
        );

        assert_eq!(
            settings.get_settings(&CurrencyUnit::Sat, &PaymentMethod::BOLT11),
            Some(bolt11_sat)
        );
        assert_eq!(
            settings.get_settings(
                &CurrencyUnit::Msat,
                &PaymentMethod::Known(KnownMethod::Bolt12)
            ),
            None
        );
    }

    #[test]
    fn test_supported_methods_and_units_preserve_configured_values() {
        let settings = Settings::new(
            vec![
                MintMethodSettings {
                    method: PaymentMethod::Known(KnownMethod::Bolt11),
                    unit: CurrencyUnit::Msat,
                    method_name: None,
                    min_amount: Some(Amount::from(1)),
                    max_amount: None,
                    options: None,
                },
                MintMethodSettings {
                    method: PaymentMethod::Known(KnownMethod::Onchain),
                    unit: CurrencyUnit::Eur,
                    method_name: None,
                    min_amount: None,
                    max_amount: Some(Amount::from(100)),
                    options: Some(MintMethodOptions::Onchain { confirmations: 3 }),
                },
            ],
            false,
        );

        let methods = settings.supported_methods();
        assert_eq!(methods.len(), 2);
        assert_eq!(methods[0], &PaymentMethod::Known(KnownMethod::Bolt11));
        assert_eq!(methods[1], &PaymentMethod::Known(KnownMethod::Onchain));

        let units = settings.supported_units();
        assert_eq!(units.len(), 2);
        assert_eq!(units[0], &CurrencyUnit::Msat);
        assert_eq!(units[1], &CurrencyUnit::Eur);
    }

    #[test]
    fn test_remove_settings_requires_exact_method_and_unit_match() {
        let bolt11_msat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Msat,
            method_name: None,
            min_amount: Some(Amount::from(1)),
            max_amount: None,
            options: None,
        };
        let bolt12_sat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt12),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(2)),
            max_amount: None,
            options: None,
        };
        let bolt11_sat = MintMethodSettings {
            method: PaymentMethod::Known(KnownMethod::Bolt11),
            unit: CurrencyUnit::Sat,
            method_name: None,
            min_amount: Some(Amount::from(3)),
            max_amount: None,
            options: None,
        };
        let mut settings = Settings::new(
            vec![bolt11_msat.clone(), bolt12_sat.clone(), bolt11_sat.clone()],
            false,
        );

        assert_eq!(
            settings.remove_settings(&CurrencyUnit::Sat, &PaymentMethod::BOLT11),
            Some(bolt11_sat.clone())
        );
        assert_eq!(settings.methods, vec![bolt11_msat, bolt12_sat]);
        assert_eq!(
            settings.remove_settings(&CurrencyUnit::Sat, &PaymentMethod::BOLT11),
            None
        );
    }
}