cdk-common 0.17.0-rc.0

CDK common types and traits
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
//! CDK Mint Lightning

use std::convert::Infallible;
use std::pin::Pin;

use async_trait::async_trait;
use cashu::util::hex;
use cashu::{Bolt11Invoice, MeltOptions};
#[cfg(feature = "prometheus")]
use cdk_prometheus::METRICS;
use futures::Stream;
use lightning::offers::offer::Offer;
use lightning_invoice::ParseOrSemanticError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::mint::{MeltPaymentRequest, MeltQuote};
use crate::nuts::nut_onchain::MeltQuoteOnchainFeeOption;
use crate::nuts::{CurrencyUnit, MeltQuoteState};
use crate::{Amount, QuoteId};

/// CDK Payment Error
#[derive(Debug, Error)]
pub enum Error {
    /// Invoice already paid
    #[error("Invoice already paid")]
    InvoiceAlreadyPaid,
    /// Invoice pay pending
    #[error("Invoice pay is pending")]
    InvoicePaymentPending,
    /// Unsupported unit
    #[error("Unsupported unit")]
    UnsupportedUnit,
    /// Unsupported payment option
    #[error("Unsupported payment option")]
    UnsupportedPaymentOption,
    /// Payment state is unknown
    #[error("Payment state is unknown")]
    UnknownPaymentState,
    /// Amount mismatch
    #[error("Amount is not what is expected")]
    AmountMismatch,
    /// Invalid expiry
    #[error("Invalid expiry")]
    InvalidExpiry,
    /// Lightning Error
    #[error(transparent)]
    Lightning(Box<dyn std::error::Error + Send + Sync>),
    /// Onchain Error
    #[error(transparent)]
    Onchain(Box<dyn std::error::Error + Send + Sync>),
    /// Serde Error
    #[error(transparent)]
    Serde(#[from] serde_json::Error),
    /// AnyHow Error
    #[error(transparent)]
    Anyhow(#[from] anyhow::Error),
    /// Parse Error
    #[error(transparent)]
    Parse(#[from] ParseOrSemanticError),
    /// Amount Error
    #[error(transparent)]
    Amount(#[from] crate::amount::Error),
    /// NUT04 Error
    #[error(transparent)]
    NUT04(#[from] crate::nuts::nut04::Error),
    /// NUT05 Error
    #[error(transparent)]
    NUT05(#[from] crate::nuts::nut05::Error),
    /// NUT23 Error
    #[error(transparent)]
    NUT23(#[from] crate::nuts::nut23::Error),
    /// Hex error
    #[error("Hex error")]
    Hex(#[from] hex::Error),
    /// Invalid hash
    #[error("Invalid hash")]
    InvalidHash,
    /// Custom
    #[error("`{0}`")]
    Custom(String),
}

impl From<Infallible> for Error {
    fn from(_: Infallible) -> Self {
        unreachable!("Infallible cannot be constructed")
    }
}

/// Payment identifier types
#[derive(Clone, Hash, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum PaymentIdentifier {
    /// Label identifier
    Label(String),
    /// Offer ID identifier
    OfferId(String),
    /// Payment hash identifier
    PaymentHash([u8; 32]),
    /// Bolt12 payment hash
    Bolt12PaymentHash([u8; 32]),
    /// Payment id
    PaymentId([u8; 32]),
    /// Custom Payment ID
    CustomId(String),
    /// Quote ID
    QuoteId(QuoteId),
}

impl PaymentIdentifier {
    /// Create new [`PaymentIdentifier`]
    pub fn new(kind: &str, identifier: &str) -> Result<Self, Error> {
        match kind.to_lowercase().as_str() {
            "label" => Ok(Self::Label(identifier.to_string())),
            "offer_id" => Ok(Self::OfferId(identifier.to_string())),
            "payment_hash" => Ok(Self::PaymentHash(
                hex::decode(identifier)?
                    .try_into()
                    .map_err(|_| Error::InvalidHash)?,
            )),
            "bolt12_payment_hash" => Ok(Self::Bolt12PaymentHash(
                hex::decode(identifier)?
                    .try_into()
                    .map_err(|_| Error::InvalidHash)?,
            )),
            "custom" => Ok(Self::CustomId(identifier.to_string())),
            "payment_id" => Ok(Self::PaymentId(
                hex::decode(identifier)?
                    .try_into()
                    .map_err(|_| Error::InvalidHash)?,
            )),
            "quote_id" => {
                Ok(Self::QuoteId(identifier.parse().map_err(|_| {
                    Error::Custom("Invalid QuoteId".to_string())
                })?))
            }
            _ => Err(Error::UnsupportedPaymentOption),
        }
    }

    /// Payment id kind
    pub fn kind(&self) -> String {
        match self {
            Self::Label(_) => "label".to_string(),
            Self::OfferId(_) => "offer_id".to_string(),
            Self::PaymentHash(_) => "payment_hash".to_string(),
            Self::Bolt12PaymentHash(_) => "bolt12_payment_hash".to_string(),
            Self::PaymentId(_) => "payment_id".to_string(),
            Self::CustomId(_) => "custom".to_string(),
            Self::QuoteId(_) => "quote_id".to_string(),
        }
    }
}

impl std::fmt::Display for PaymentIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Label(l) => write!(f, "{l}"),
            Self::OfferId(o) => write!(f, "{o}"),
            Self::PaymentHash(h) => write!(f, "{}", hex::encode(h)),
            Self::Bolt12PaymentHash(h) => write!(f, "{}", hex::encode(h)),
            Self::PaymentId(h) => write!(f, "{}", hex::encode(h)),
            Self::CustomId(c) => write!(f, "{c}"),
            Self::QuoteId(q) => write!(f, "{q}"),
        }
    }
}

impl std::fmt::Debug for PaymentIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PaymentIdentifier::PaymentHash(h) => write!(f, "PaymentHash({})", hex::encode(h)),
            PaymentIdentifier::Bolt12PaymentHash(h) => {
                write!(f, "Bolt12PaymentHash({})", hex::encode(h))
            }
            PaymentIdentifier::PaymentId(h) => write!(f, "PaymentId({})", hex::encode(h)),
            PaymentIdentifier::Label(s) => write!(f, "Label({})", s),
            PaymentIdentifier::OfferId(s) => write!(f, "OfferId({})", s),
            PaymentIdentifier::CustomId(s) => write!(f, "CustomId({})", s),
            PaymentIdentifier::QuoteId(q) => write!(f, "QuoteId({})", q),
        }
    }
}

/// Options for creating a BOLT11 incoming payment request
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Bolt11IncomingPaymentOptions {
    /// Optional description for the payment request
    pub description: Option<String>,
    /// Amount for the payment request in sats
    pub amount: Amount<CurrencyUnit>,
    /// Optional expiry time as Unix timestamp in seconds
    pub unix_expiry: Option<u64>,
}

impl Default for Bolt11IncomingPaymentOptions {
    fn default() -> Self {
        Self {
            description: None,
            amount: Amount::new(0, CurrencyUnit::Sat),
            unix_expiry: None,
        }
    }
}

/// Options for creating a BOLT12 incoming payment request
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Bolt12IncomingPaymentOptions {
    /// Optional description for the payment request
    pub description: Option<String>,
    /// Optional amount for the payment request in sats
    pub amount: Option<Amount<CurrencyUnit>>,
    /// Optional expiry time as Unix timestamp in seconds
    pub unix_expiry: Option<u64>,
}

/// Options for creating a custom incoming payment request
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CustomIncomingPaymentOptions {
    /// Payment method name (e.g., "paypal", "venmo")
    pub method: String,
    /// Optional description for the payment request
    pub description: Option<String>,
    /// Amount for the payment request
    pub amount: Amount<CurrencyUnit>,
    /// Optional expiry time as Unix timestamp in seconds
    pub unix_expiry: Option<u64>,
    /// Extra payment-method-specific fields as JSON string
    ///
    /// These fields are passed through to the payment processor for
    /// method-specific validation (e.g., ehash share).
    pub extra_json: Option<String>,
}

/// Options for creating an onchain incoming payment request
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OnchainIncomingPaymentOptions {
    /// Quote ID for the incoming payment
    pub quote_id: QuoteId,
}

/// Options for incoming payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum IncomingPaymentOptions {
    /// BOLT11 payment request options
    Bolt11(Bolt11IncomingPaymentOptions),
    /// BOLT12 payment request options
    Bolt12(Box<Bolt12IncomingPaymentOptions>),
    /// Custom payment method options
    Custom(Box<CustomIncomingPaymentOptions>),
    /// Onchain payment request options
    Onchain(OnchainIncomingPaymentOptions),
}

/// Options for BOLT11 outgoing payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Bolt11OutgoingPaymentOptions {
    /// Bolt11
    pub bolt11: Bolt11Invoice,
    /// Maximum fee amount allowed for the payment
    pub max_fee_amount: Option<Amount<CurrencyUnit>>,
    /// Optional timeout in seconds
    pub timeout_secs: Option<u64>,
    /// Melt options
    pub melt_options: Option<MeltOptions>,
    /// The mint's quote id for this melt. Set in both `get_payment_quote`
    /// and `make_payment` so backends can correlate the two calls. For
    /// BOLT11 backends the payment_hash already provides correlation, so
    /// this is informational; it is still required for protocol uniformity.
    pub quote_id: QuoteId,
}

/// Options for BOLT12 outgoing payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Bolt12OutgoingPaymentOptions {
    /// Offer
    pub offer: Offer,
    /// Maximum fee amount allowed for the payment
    pub max_fee_amount: Option<Amount<CurrencyUnit>>,
    /// Optional timeout in seconds
    pub timeout_secs: Option<u64>,
    /// Melt options
    pub melt_options: Option<MeltOptions>,
    /// The mint's quote id for this melt. See [`Bolt11OutgoingPaymentOptions::quote_id`].
    pub quote_id: QuoteId,
}

/// Options for custom outgoing payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CustomOutgoingPaymentOptions {
    /// Payment method name
    pub method: String,
    /// Payment request string (method-specific format)
    pub request: String,
    /// Maximum fee amount allowed for the payment
    pub max_fee_amount: Option<Amount<CurrencyUnit>>,
    /// Optional timeout in seconds
    pub timeout_secs: Option<u64>,
    /// Melt options
    pub melt_options: Option<MeltOptions>,
    /// Extra payment-method-specific fields as JSON string
    ///
    /// These fields are passed through to the payment processor for
    /// method-specific validation.
    pub extra_json: Option<String>,
    /// The mint's quote id for this melt. Custom backends should use this
    /// as the stable correlation key between `get_payment_quote` and
    /// `make_payment` (and any later `check_outgoing_payment` polls) — it
    /// is the only field guaranteed to be unique per melt without relying
    /// on wallet-supplied uniqueness in `request`.
    pub quote_id: QuoteId,
}

/// Options for onchain outgoing payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OnchainOutgoingPaymentOptions {
    /// Bitcoin address to send to
    pub address: String,
    /// Payment amount
    pub amount: Amount<CurrencyUnit>,
    /// Maximum fee amount allowed for the payment
    pub max_fee_amount: Option<Amount<CurrencyUnit>>,
    /// Opaque stable identifier supplied by the mint.
    ///
    /// The mint generates this value and uses it to correlate the quote with
    /// subsequent `make_payment` and `check_outgoing_payment` calls. Backends
    /// MUST NOT synthesize or modify this value. Backends MUST persist it
    /// (for example as the send intent id) and echo it verbatim in
    /// [`PaymentQuoteResponse::request_lookup_id`] and
    /// [`MakePaymentResponse::payment_lookup_id`] as
    /// `PaymentIdentifier::QuoteId(..)`. The mint layer validates the echo
    /// and will reject quotes whose backend response disagrees with the
    /// supplied `quote_id` (see
    /// [`Error::OnchainQuoteLookupIdMismatch`](crate::Error::OnchainQuoteLookupIdMismatch)).
    pub quote_id: QuoteId,
    /// Selected fee option index (mirrors the quote's chosen `fee_options[i].fee_index`)
    pub fee_index: Option<u32>,
    /// Opaque metadata as a JSON string for future extensions
    pub metadata: Option<String>,
}

/// Options for outgoing payments
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum OutgoingPaymentOptions {
    /// BOLT11 payment options
    Bolt11(Box<Bolt11OutgoingPaymentOptions>),
    /// BOLT12 payment options
    Bolt12(Box<Bolt12OutgoingPaymentOptions>),
    /// Custom payment method options
    Custom(Box<CustomOutgoingPaymentOptions>),
    /// Onchain payment options
    Onchain(Box<OnchainOutgoingPaymentOptions>),
}

impl OutgoingPaymentOptions {
    /// Creates payment options from a melt quote
    pub fn from_melt_quote_with_fee(
        melt_quote: MeltQuote,
    ) -> Result<OutgoingPaymentOptions, Error> {
        let fee_reserve = melt_quote.fee_reserve();
        let quote_id = melt_quote.id.clone();
        match &melt_quote.request {
            MeltPaymentRequest::Bolt11 { bolt11 } => Ok(OutgoingPaymentOptions::Bolt11(Box::new(
                Bolt11OutgoingPaymentOptions {
                    max_fee_amount: Some(fee_reserve),
                    timeout_secs: None,
                    bolt11: bolt11.clone(),
                    melt_options: melt_quote.options,
                    quote_id,
                },
            ))),
            MeltPaymentRequest::Bolt12 { offer } => {
                let melt_options = match melt_quote.options {
                    Some(MeltOptions::Mpp { mpp: _ }) => return Err(Error::UnsupportedUnit),
                    Some(options) => Some(options),
                    _ => None,
                };

                Ok(OutgoingPaymentOptions::Bolt12(Box::new(
                    Bolt12OutgoingPaymentOptions {
                        max_fee_amount: Some(fee_reserve),
                        timeout_secs: None,
                        offer: *offer.clone(),
                        melt_options,
                        quote_id,
                    },
                )))
            }
            MeltPaymentRequest::Custom { method, request } => Ok(OutgoingPaymentOptions::Custom(
                Box::new(CustomOutgoingPaymentOptions {
                    method: method.to_string(),
                    request: request.to_string(),
                    max_fee_amount: Some(fee_reserve),
                    timeout_secs: None,
                    melt_options: melt_quote.options,
                    extra_json: None,
                    quote_id,
                }),
            )),
            MeltPaymentRequest::Onchain { address } => Ok(OutgoingPaymentOptions::Onchain(
                Box::new(OnchainOutgoingPaymentOptions {
                    address: address.clone(),
                    amount: melt_quote.amount(),
                    max_fee_amount: Some(fee_reserve),
                    quote_id: melt_quote.id,
                    fee_index: melt_quote.selected_fee_index,
                    metadata: None,
                }),
            )),
        }
    }
}

/// Mint payment trait
#[async_trait]
pub trait MintPayment {
    /// Mint Lightning Error
    type Err: Into<Error> + From<Error>;

    /// Start the payment processor
    /// Called when the mint starts up to initialize the payment processor
    async fn start(&self) -> Result<(), Self::Err> {
        // Default implementation - do nothing
        Ok(())
    }

    /// Stop the payment processor
    /// Called when the mint shuts down to gracefully stop the payment processor
    async fn stop(&self) -> Result<(), Self::Err> {
        // Default implementation - do nothing
        Ok(())
    }

    /// Base Settings
    async fn get_settings(&self) -> Result<SettingsResponse, Self::Err>;

    /// Create a new invoice
    async fn create_incoming_payment_request(
        &self,
        options: IncomingPaymentOptions,
    ) -> Result<CreateIncomingPaymentResponse, Self::Err>;

    /// Get payment quote
    /// Used to get fee and amount required for a payment request
    async fn get_payment_quote(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<PaymentQuoteResponse, Self::Err>;

    /// Pay request
    async fn make_payment(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<MakePaymentResponse, Self::Err>;

    /// Listen for invoices to be paid to the mint
    /// Returns a stream of request_lookup_id once invoices are paid
    async fn wait_payment_event(
        &self,
    ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err>;

    /// Is the payment event stream active
    fn is_payment_event_stream_active(&self) -> bool;

    /// Cancel the payment event stream
    fn cancel_payment_event_stream(&self);

    /// Check the status of an incoming payment
    async fn check_incoming_payment_status(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<Vec<WaitPaymentResponse>, Self::Err>;

    /// Check the status of an outgoing payment
    async fn check_outgoing_payment(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<MakePaymentResponse, Self::Err>;
}

/// An event emitted which should be handled by the mint
#[derive(Debug, Clone, Hash)]
pub enum Event {
    /// A payment has been received.
    PaymentReceived(WaitPaymentResponse),
    /// An outgoing payment has been confirmed.
    PaymentSuccessful {
        /// Quote ID linking to the melt quote
        quote_id: QuoteId,
        /// Payment response details
        details: MakePaymentResponse,
    },
    /// An outgoing payment has permanently failed.
    PaymentFailed {
        /// Quote ID linking to the melt quote
        quote_id: QuoteId,
        /// Human-readable reason for the failure
        reason: String,
    },
}

/// Wait any invoice response
#[derive(Debug, Clone, Hash)]
pub struct WaitPaymentResponse {
    /// Request look up id
    /// Id that relates the quote and payment request
    pub payment_identifier: PaymentIdentifier,
    /// Payment amount (typed with unit for compile-time safety)
    pub payment_amount: Amount<CurrencyUnit>,
    /// Unique id of payment
    // Payment hash
    pub payment_id: String,
}

impl WaitPaymentResponse {
    /// Get the currency unit
    pub fn unit(&self) -> &CurrencyUnit {
        self.payment_amount.unit()
    }
}

/// Create incoming payment response
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateIncomingPaymentResponse {
    /// Id that is used to look up the payment from the ln backend
    pub request_lookup_id: PaymentIdentifier,
    /// Payment request
    pub request: String,
    /// Unix Expiry of Invoice
    pub expiry: Option<u64>,
    /// 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)]
    pub extra_json: Option<serde_json::Value>,
}

/// Payment response
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct MakePaymentResponse {
    /// Payment hash
    ///
    /// For onchain payments, this MUST be
    /// `PaymentIdentifier::QuoteId(quote_id)` where `quote_id` is the value
    /// supplied by the mint in
    /// [`OnchainOutgoingPaymentOptions::quote_id`]. See that field for the
    /// full echo contract.
    pub payment_lookup_id: PaymentIdentifier,
    /// Payment proof
    pub payment_proof: Option<String>,
    /// Status
    pub status: MeltQuoteState,
    /// Total amount spent, including fees. Only authoritative when `status`
    /// is [`MeltQuoteState::Paid`]; otherwise backends return `0`.
    pub total_spent: Amount<CurrencyUnit>,
}

impl MakePaymentResponse {
    /// Get the currency unit
    pub fn unit(&self) -> &CurrencyUnit {
        self.total_spent.unit()
    }
}

/// Payment quote response
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct PaymentQuoteResponse {
    /// Request look up id
    ///
    /// For onchain quotes, this MUST be
    /// `Some(PaymentIdentifier::QuoteId(quote_id))` where `quote_id` is the
    /// value supplied by the mint in
    /// [`OnchainOutgoingPaymentOptions::quote_id`]. The mint validates this
    /// echo and rejects mismatches — see
    /// [`OnchainOutgoingPaymentOptions::quote_id`] for the full contract.
    pub request_lookup_id: Option<PaymentIdentifier>,
    /// Amount (typed with unit for compile-time safety)
    pub amount: Amount<CurrencyUnit>,
    /// Fee required for melt (typed with unit for compile-time safety)
    pub fee: Amount<CurrencyUnit>,
    /// Status
    pub state: MeltQuoteState,
    /// Extra payment-method-specific fields
    pub extra_json: Option<serde_json::Value>,
    /// Estimated confirmation target in blocks for onchain quotes.
    ///
    /// Onchain backends must return explicit `fee_options`; this field remains
    /// a convenience mirror of the quoted or selected confirmation target.
    pub estimated_blocks: Option<u32>,
    /// Explicit onchain fee options the backend is willing to honor.
    ///
    /// For onchain melt quotes the mint enforces that `fee_options` is
    /// non-empty.
    ///
    /// Backends assign stable `fee_index` values and must be able to honor the
    /// selected value later in [`OnchainOutgoingPaymentOptions::fee_index`].
    /// The mint validates, persists, and exposes these values unchanged.
    /// Onchain backends must return `Some(vec)` here. Empty vectors produce
    /// [`Error::OnchainFeeOptionsEmpty`](crate::Error::OnchainFeeOptionsEmpty),
    /// and the quote is not persisted.
    pub fee_options: Option<Vec<MeltQuoteOnchainFeeOption>>,
}

impl PaymentQuoteResponse {
    /// Get the currency unit
    pub fn unit(&self) -> &CurrencyUnit {
        self.amount.unit()
    }
}

/// BOLT11 settings
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Bolt11Settings {
    /// Multi-part payment (MPP) supported
    pub mpp: bool,
    /// Amountless invoice support
    pub amountless: bool,
    /// Invoice description supported
    pub invoice_description: bool,
}

/// BOLT12 settings
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Bolt12Settings {
    /// Amountless offer support
    pub amountless: bool,
}

/// Onchain settings
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct OnchainSettings {
    /// Number of confirmations required
    pub confirmations: u32,
    /// Minimum incoming onchain payment amount accepted by the backend
    pub min_receive_amount_sat: u64,
    /// Minimum outgoing onchain payment amount accepted by the backend
    pub min_send_amount_sat: u64,
}

/// Payment processor settings response
/// Mirrors the proto SettingsResponse structure
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettingsResponse {
    /// Base unit of backend
    pub unit: String,
    /// BOLT11 settings (None if not supported)
    pub bolt11: Option<Bolt11Settings>,
    /// BOLT12 settings (None if not supported)
    pub bolt12: Option<Bolt12Settings>,
    /// Onchain settings (None if not supported)
    pub onchain: Option<OnchainSettings>,
    /// Custom payment methods settings (method name -> settings data)
    #[serde(default)]
    pub custom: std::collections::HashMap<String, String>,
}

impl From<SettingsResponse> for Value {
    fn from(value: SettingsResponse) -> Self {
        serde_json::to_value(value).unwrap_or(Value::Null)
    }
}

impl TryFrom<Value> for SettingsResponse {
    type Error = crate::error::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        serde_json::from_value(value).map_err(|err| err.into())
    }
}

/// Metrics wrapper for MintPayment implementations
///
/// This wrapper implements the Decorator pattern to collect metrics on all
/// MintPayment trait methods. It wraps any existing MintPayment implementation
/// and automatically records timing and operation metrics.
#[derive(Debug, Clone)]
#[cfg(feature = "prometheus")]
pub struct MetricsMintPayment<T> {
    inner: T,
}
#[cfg(feature = "prometheus")]
impl<T> MetricsMintPayment<T>
where
    T: MintPayment,
{
    /// Create a new metrics wrapper around a MintPayment implementation
    pub fn new(inner: T) -> Self {
        Self { inner }
    }

    /// Get reference to the underlying implementation
    pub fn inner(&self) -> &T {
        &self.inner
    }

    /// Consume the wrapper and return the inner implementation
    pub fn into_inner(self) -> T {
        self.inner
    }
}

#[async_trait]
#[cfg(feature = "prometheus")]
impl<T> MintPayment for MetricsMintPayment<T>
where
    T: MintPayment + Send + Sync,
{
    type Err = T::Err;

    async fn start(&self) -> Result<(), Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("start");

        let result = self.inner.start().await;

        let duration = start.elapsed().as_secs_f64();
        METRICS.record_mint_operation_histogram("start", result.is_ok(), duration);
        METRICS.dec_in_flight_requests("start");

        result
    }

    async fn stop(&self) -> Result<(), Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("stop");

        let result = self.inner.stop().await;

        let duration = start.elapsed().as_secs_f64();
        METRICS.record_mint_operation_histogram("stop", result.is_ok(), duration);
        METRICS.dec_in_flight_requests("stop");

        result
    }
    async fn get_settings(&self) -> Result<SettingsResponse, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("get_settings");

        let result = self.inner.get_settings().await;

        let duration = start.elapsed().as_secs_f64();
        METRICS.record_mint_operation_histogram("get_settings", result.is_ok(), duration);
        METRICS.dec_in_flight_requests("get_settings");

        result
    }

    async fn create_incoming_payment_request(
        &self,
        options: IncomingPaymentOptions,
    ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("create_incoming_payment_request");

        let result = self.inner.create_incoming_payment_request(options).await;

        let duration = start.elapsed().as_secs_f64();
        METRICS.record_mint_operation_histogram(
            "create_incoming_payment_request",
            result.is_ok(),
            duration,
        );
        METRICS.dec_in_flight_requests("create_incoming_payment_request");

        result
    }

    async fn get_payment_quote(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<PaymentQuoteResponse, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("get_payment_quote");

        let result = self.inner.get_payment_quote(unit, options).await;

        let duration = start.elapsed().as_secs_f64();
        let success = result.is_ok();

        if let Ok(ref quote) = result {
            let amount: f64 = quote.amount.value() as f64;
            let fee: f64 = quote.fee.value() as f64;
            METRICS.record_lightning_payment(amount, fee);
        }

        METRICS.record_mint_operation_histogram("get_payment_quote", success, duration);
        METRICS.dec_in_flight_requests("get_payment_quote");

        result
    }
    async fn wait_payment_event(
        &self,
    ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("wait_payment_event");

        let result = self.inner.wait_payment_event().await;

        let duration = start.elapsed().as_secs_f64();
        let success = result.is_ok();

        METRICS.record_mint_operation_histogram("wait_payment_event", success, duration);
        METRICS.dec_in_flight_requests("wait_payment_event");

        result
    }

    async fn make_payment(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<MakePaymentResponse, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("make_payment");

        let result = self.inner.make_payment(unit, options).await;

        let duration = start.elapsed().as_secs_f64();
        let success = result.is_ok();

        METRICS.record_mint_operation_histogram("make_payment", success, duration);
        METRICS.dec_in_flight_requests("make_payment");

        result
    }

    fn is_payment_event_stream_active(&self) -> bool {
        self.inner.is_payment_event_stream_active()
    }

    fn cancel_payment_event_stream(&self) {
        self.inner.cancel_payment_event_stream()
    }

    async fn check_incoming_payment_status(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("check_incoming_payment_status");

        let result = self
            .inner
            .check_incoming_payment_status(payment_identifier)
            .await;

        let duration = start.elapsed().as_secs_f64();
        METRICS.record_mint_operation_histogram(
            "check_incoming_payment_status",
            result.is_ok(),
            duration,
        );
        METRICS.dec_in_flight_requests("check_incoming_payment_status");

        result
    }

    async fn check_outgoing_payment(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<MakePaymentResponse, Self::Err> {
        let start = std::time::Instant::now();
        METRICS.inc_in_flight_requests("check_outgoing_payment");

        let result = self.inner.check_outgoing_payment(payment_identifier).await;

        let duration = start.elapsed().as_secs_f64();
        let success = result.is_ok();

        METRICS.record_mint_operation_histogram("check_outgoing_payment", success, duration);
        METRICS.dec_in_flight_requests("check_outgoing_payment");

        result
    }
}

/// Type alias for Mint Payment trait
pub type DynMintPayment = std::sync::Arc<dyn MintPayment<Err = Error> + Send + Sync>;

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;
    use crate::QuoteId;

    #[test]
    fn test_payment_identifier_quote_id_roundtrip() {
        let quote_id = QuoteId::new_uuid();
        let identifier = PaymentIdentifier::QuoteId(quote_id.clone());

        let kind = identifier.kind();
        assert_eq!(kind, "quote_id");

        let display = identifier.to_string();
        assert_eq!(display, quote_id.to_string());

        let debug = format!("{:?}", identifier);
        assert_eq!(debug, format!("QuoteId({})", quote_id));

        let parsed = PaymentIdentifier::new(&kind, &display).unwrap();
        assert_eq!(parsed, identifier);
    }

    #[test]
    fn test_payment_identifier_quote_id_base64_roundtrip() {
        let quote_id_str = "SGVsbG8gV29ybGQh"; // Valid Base64
        let identifier = PaymentIdentifier::QuoteId(QuoteId::from_str(quote_id_str).unwrap());

        let kind = identifier.kind();
        assert_eq!(kind, "quote_id");

        let display = identifier.to_string();
        assert_eq!(display, quote_id_str);

        let parsed = PaymentIdentifier::new(&kind, &display).unwrap();
        assert_eq!(parsed, identifier);
    }

    #[test]
    fn test_payment_identifier_unsupported_kind() {
        let result = PaymentIdentifier::new("unsupported_kind", "123");
        assert!(matches!(result, Err(Error::UnsupportedPaymentOption)));
    }

    #[test]
    fn test_payment_identifier_invalid_quote_id() {
        // An invalid base64 and invalid UUID string (e.g. spaces and special characters)
        let result = PaymentIdentifier::new("quote_id", "invalid!@#quote");
        assert!(matches!(result, Err(Error::Custom(_))));
    }

    #[test]
    fn test_payment_identifier_invalid_hash() {
        // Invalid hex
        let result_hex = PaymentIdentifier::new("payment_hash", "not_hex!");
        assert!(matches!(result_hex, Err(Error::Hex(_))));

        // Valid hex, but wrong length (e.g. 1 byte instead of 32)
        let result_len = PaymentIdentifier::new("payment_hash", "00");
        assert!(matches!(result_len, Err(Error::InvalidHash)));

        // Invalid length for bolt12_payment_hash
        let result_bolt12 = PaymentIdentifier::new("bolt12_payment_hash", "00");
        assert!(matches!(result_bolt12, Err(Error::InvalidHash)));
    }
}

#[test]
fn test_payment_identifier_hash_variants_roundtrip() {
    let dummy_hash = [1u8; 32];
    let hex_encoded = hex::encode(dummy_hash);

    // Test Bolt12PaymentHash
    let bolt12_identifier = PaymentIdentifier::Bolt12PaymentHash(dummy_hash);

    let kind = bolt12_identifier.kind();
    assert_eq!(kind, "bolt12_payment_hash");

    let display = bolt12_identifier.to_string();
    assert_eq!(display, hex_encoded);

    let debug = format!("{:?}", bolt12_identifier);
    assert_eq!(debug, format!("Bolt12PaymentHash({})", hex_encoded));

    let parsed = PaymentIdentifier::new(&kind, &display).unwrap();
    assert_eq!(parsed, bolt12_identifier);

    // Test PaymentId
    let dummy_hash_2 = [2u8; 32];
    let hex_encoded_2 = hex::encode(dummy_hash_2);
    let payment_id_identifier = PaymentIdentifier::PaymentId(dummy_hash_2);

    let kind = payment_id_identifier.kind();
    assert_eq!(kind, "payment_id");

    let display = payment_id_identifier.to_string();
    assert_eq!(display, hex_encoded_2);

    let debug = format!("{:?}", payment_id_identifier);
    assert_eq!(debug, format!("PaymentId({})", hex_encoded_2));

    let parsed = PaymentIdentifier::new(&kind, &display).unwrap();
    assert_eq!(parsed, payment_id_identifier);
}