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
//! Unified Melt Quote types for melt use-cases.

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::nuts::nut00::KnownMethod;
use crate::nuts::nut05::{MeltQuoteCustomRequest, MeltQuoteCustomResponse};
use crate::nuts::nut23::{MeltQuoteBolt11Request, MeltQuoteBolt11Response};
use crate::nuts::nut25::{MeltQuoteBolt12Request, MeltQuoteBolt12Response};
use crate::nuts::nut_onchain::{MeltQuoteOnchainRequest, MeltQuoteOnchainResponse};
use crate::{Amount, CurrencyUnit, MeltQuoteState, PaymentMethod};

/// Melt quote request enum for different types of quotes
///
/// This enum represents the different types of melt quote requests
/// that can be made, either BOLT11, BOLT12, or Custom.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MeltQuoteRequest {
    /// Lightning Network BOLT11 invoice request
    Bolt11(MeltQuoteBolt11Request),
    /// Lightning Network BOLT12 offer request
    Bolt12(MeltQuoteBolt12Request),
    /// Onchain request
    Onchain(MeltQuoteOnchainRequest),
    /// Custom payment method request
    Custom(MeltQuoteCustomRequest),
}

impl From<MeltQuoteBolt11Request> for MeltQuoteRequest {
    fn from(request: MeltQuoteBolt11Request) -> Self {
        MeltQuoteRequest::Bolt11(request)
    }
}

impl From<MeltQuoteBolt12Request> for MeltQuoteRequest {
    fn from(request: MeltQuoteBolt12Request) -> Self {
        MeltQuoteRequest::Bolt12(request)
    }
}

impl From<MeltQuoteOnchainRequest> for MeltQuoteRequest {
    fn from(request: MeltQuoteOnchainRequest) -> Self {
        MeltQuoteRequest::Onchain(request)
    }
}

impl From<MeltQuoteCustomRequest> for MeltQuoteRequest {
    fn from(request: MeltQuoteCustomRequest) -> Self {
        MeltQuoteRequest::Custom(request)
    }
}

impl MeltQuoteRequest {
    /// Returns the payment method for this request.
    pub fn method(&self) -> PaymentMethod {
        match self {
            Self::Bolt11(_) => PaymentMethod::Known(KnownMethod::Bolt11),
            Self::Bolt12(_) => PaymentMethod::Known(KnownMethod::Bolt12),
            Self::Onchain(_) => PaymentMethod::Known(KnownMethod::Onchain),
            Self::Custom(request) => PaymentMethod::from(request.method.as_str()),
        }
    }
}

/// Unified melt quote response for all payment methods
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub enum MeltQuoteResponse<Q> {
    /// Bolt11 (Lightning invoice)
    Bolt11(MeltQuoteBolt11Response<Q>),
    /// Bolt12 (Offers)
    Bolt12(MeltQuoteBolt12Response<Q>),
    /// Onchain
    Onchain(MeltQuoteOnchainResponse<Q>),
    /// Custom payment method
    Custom((PaymentMethod, MeltQuoteCustomResponse<Q>)),
}

/// Melt quote creation response for all payment methods.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub enum MeltQuoteCreateResponse<Q> {
    /// Bolt11 (Lightning invoice)
    Bolt11(MeltQuoteBolt11Response<Q>),
    /// Bolt12 (Offers)
    Bolt12(MeltQuoteBolt12Response<Q>),
    /// Onchain
    Onchain(MeltQuoteOnchainResponse<Q>),
    /// Custom payment method
    Custom((PaymentMethod, MeltQuoteCustomResponse<Q>)),
}

impl<Q> MeltQuoteResponse<Q> {
    /// Returns the payment method for this response.
    pub fn method(&self) -> PaymentMethod {
        match self {
            Self::Bolt11(_) => PaymentMethod::Known(KnownMethod::Bolt11),
            Self::Bolt12(_) => PaymentMethod::Known(KnownMethod::Bolt12),
            Self::Onchain(_) => PaymentMethod::Known(KnownMethod::Onchain),
            Self::Custom((method, _)) => method.clone(),
        }
    }
}

impl<Q: ToString> MeltQuoteResponse<Q> {
    /// Convert the MeltQuoteResponse with a quote type Q to a String
    pub fn to_string_id(self) -> MeltQuoteResponse<String> {
        match self {
            Self::Bolt11(r) => MeltQuoteResponse::Bolt11(r.to_string_id()),
            Self::Bolt12(r) => MeltQuoteResponse::Bolt12(r.to_string_id()),
            Self::Onchain(r) => MeltQuoteResponse::Onchain(r.to_string_id()),
            Self::Custom((method, r)) => MeltQuoteResponse::Custom((method, r.to_string_id())),
        }
    }

    /// Returns the quote ID.
    pub fn quote(&self) -> &Q {
        match self {
            Self::Bolt11(r) => &r.quote,
            Self::Bolt12(r) => &r.quote,
            Self::Onchain(r) => &r.quote,
            Self::Custom((_, r)) => &r.quote,
        }
    }

    /// Returns the quoted amount.
    pub fn amount(&self) -> Amount {
        match self {
            Self::Bolt11(r) => r.amount,
            Self::Bolt12(r) => r.amount,
            Self::Onchain(r) => r.amount,
            Self::Custom((_, r)) => r.amount,
        }
    }

    /// Returns the fee reserve.
    pub fn fee_reserve(&self) -> Amount {
        match self {
            Self::Bolt11(r) => r.fee_reserve,
            Self::Bolt12(r) => r.fee_reserve,
            Self::Onchain(r) => r
                .selected_fee_index
                .and_then(|selected| {
                    r.fee_options
                        .iter()
                        .find(|option| option.fee_index == selected)
                })
                .or_else(|| r.fee_options.first())
                .map(|option| option.fee_reserve)
                .unwrap_or(Amount::ZERO),
            Self::Custom((_, r)) => r.fee_reserve.unwrap_or_default(),
        }
    }

    /// Returns the quote state.
    pub fn state(&self) -> MeltQuoteState {
        match self {
            Self::Bolt11(r) => r.state,
            Self::Bolt12(r) => r.state,
            Self::Onchain(r) => r.state,
            Self::Custom((_, r)) => r.state,
        }
    }

    /// Returns the quote expiry timestamp.
    pub fn expiry(&self) -> u64 {
        match self {
            Self::Bolt11(r) => r.expiry,
            Self::Bolt12(r) => r.expiry,
            Self::Onchain(r) => r.expiry,
            Self::Custom((_, r)) => r.expiry,
        }
    }

    /// Returns the payment proof.
    ///
    /// For Bolt11/Bolt12/Custom methods this is the Lightning payment
    /// preimage. For Onchain, the "proof" is the broadcast outpoint
    /// (`txid:vout`) — it plays the same role of a canonical,
    /// method-specific artifact proving the mint executed the payment.
    /// Callers inspecting `payment_proof` to decide whether an irreversible
    /// settlement has occurred can treat Onchain uniformly with the other
    /// methods.
    pub fn payment_proof(&self) -> Option<&str> {
        match self {
            Self::Bolt11(r) => r.payment_preimage.as_deref(),
            Self::Bolt12(r) => r.payment_preimage.as_deref(),
            Self::Onchain(r) => r.outpoint.as_deref(),
            Self::Custom((_, r)) => r.payment_preimage.as_deref(),
        }
    }

    /// Returns the change signatures when present.
    pub fn change(&self) -> Option<&Vec<crate::BlindSignature>> {
        match self {
            Self::Bolt11(r) => r.change.as_ref(),
            Self::Bolt12(r) => r.change.as_ref(),
            Self::Onchain(r) => r.change.as_ref(),
            Self::Custom((_, r)) => r.change.as_ref(),
        }
    }

    /// Returns the payment request string when present.
    pub fn request(&self) -> Option<&str> {
        match self {
            Self::Bolt11(r) => r.request.as_deref(),
            Self::Bolt12(r) => r.request.as_deref(),
            Self::Onchain(r) => Some(r.request.as_str()),
            Self::Custom((_, r)) => r.request.as_deref(),
        }
    }

    /// Returns the unit when present.
    pub fn unit(&self) -> Option<CurrencyUnit> {
        match self {
            Self::Bolt11(r) => r.unit.clone(),
            Self::Bolt12(r) => r.unit.clone(),
            Self::Onchain(r) => Some(r.unit.clone()),
            Self::Custom((_, r)) => r.unit.clone(),
        }
    }
}

#[cfg(feature = "mint")]
impl From<MeltQuoteResponse<crate::QuoteId>> for MeltQuoteResponse<String> {
    fn from(value: MeltQuoteResponse<crate::QuoteId>) -> Self {
        value.to_string_id()
    }
}

impl<Q: ToString> MeltQuoteCreateResponse<Q> {
    /// Convert the MeltQuoteCreateResponse with a quote type Q to a String
    pub fn to_string_id(self) -> MeltQuoteCreateResponse<String> {
        match self {
            Self::Bolt11(r) => MeltQuoteCreateResponse::Bolt11(r.to_string_id()),
            Self::Bolt12(r) => MeltQuoteCreateResponse::Bolt12(r.to_string_id()),
            Self::Onchain(r) => MeltQuoteCreateResponse::Onchain(r.to_string_id()),
            Self::Custom((method, r)) => {
                MeltQuoteCreateResponse::Custom((method, r.to_string_id()))
            }
        }
    }

    /// Returns the payment method for this response.
    pub fn method(&self) -> PaymentMethod {
        match self {
            Self::Bolt11(_) => PaymentMethod::Known(KnownMethod::Bolt11),
            Self::Bolt12(_) => PaymentMethod::Known(KnownMethod::Bolt12),
            Self::Onchain(_) => PaymentMethod::Known(KnownMethod::Onchain),
            Self::Custom((method, _)) => method.clone(),
        }
    }

    /// Returns the quote ID for single-quote methods.
    pub fn quote(&self) -> Option<&Q> {
        match self {
            Self::Bolt11(r) => Some(&r.quote),
            Self::Bolt12(r) => Some(&r.quote),
            Self::Onchain(r) => Some(&r.quote),
            Self::Custom((_, r)) => Some(&r.quote),
        }
    }
}

#[cfg(feature = "mint")]
impl From<MeltQuoteCreateResponse<crate::QuoteId>> for MeltQuoteCreateResponse<String> {
    fn from(value: MeltQuoteCreateResponse<crate::QuoteId>) -> Self {
        value.to_string_id()
    }
}

#[cfg(feature = "mint")]
impl<Q> From<crate::mint::MeltQuote> for MeltQuoteResponse<Q>
where
    Q: From<crate::QuoteId>,
{
    fn from(value: crate::mint::MeltQuote) -> Self {
        match value.payment_method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                Self::Bolt11(crate::nuts::nut23::MeltQuoteBolt11Response {
                    quote: value.id.clone().into(),
                    amount: value.amount().into(),
                    fee_reserve: value.fee_reserve().into(),
                    state: value.state,
                    expiry: value.expiry,
                    payment_preimage: value.payment_proof.clone(),
                    change: None,
                    request: Some(value.request.to_string()),
                    unit: Some(value.unit.clone()),
                })
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                Self::Bolt12(crate::nuts::nut25::MeltQuoteBolt12Response {
                    quote: value.id.clone().into(),
                    amount: value.amount().into(),
                    fee_reserve: value.fee_reserve().into(),
                    state: value.state,
                    expiry: value.expiry,
                    payment_preimage: value.payment_proof.clone(),
                    change: None,
                    request: Some(value.request.to_string()),
                    unit: Some(value.unit.clone()),
                })
            }
            PaymentMethod::Known(KnownMethod::Onchain) => {
                Self::Onchain(crate::nuts::nut_onchain::MeltQuoteOnchainResponse {
                    quote: value.id.clone().into(),
                    amount: value.amount().into(),
                    unit: value.unit.clone(),
                    state: value.state,
                    expiry: value.expiry,
                    request: value.request.to_string(),
                    fee_options: value.fee_options().to_vec(),
                    selected_fee_index: value.selected_fee_index,
                    outpoint: value.payment_proof.clone(),
                    change: None,
                })
            }
            ref method => Self::Custom((
                method.clone(),
                crate::nuts::nut05::MeltQuoteCustomResponse {
                    quote: value.id.clone().into(),
                    amount: value.amount().into(),
                    fee_reserve: Some(value.fee_reserve().into()),
                    state: value.state,
                    expiry: value.expiry,
                    payment_preimage: value.payment_proof.clone(),
                    change: None,
                    request: Some(value.request.to_string()),
                    unit: Some(value.unit.clone()),
                    extra: serde_json::Value::Null,
                },
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nuts::nut05::MeltQuoteCustomResponse;
    use crate::nuts::nut23::MeltQuoteBolt11Response;
    use crate::nuts::nut_onchain::{MeltQuoteOnchainFeeOption, MeltQuoteOnchainResponse};
    use crate::{Amount, CurrencyUnit, MeltQuoteState};

    fn bolt11_response(quote: &str) -> MeltQuoteBolt11Response<String> {
        MeltQuoteBolt11Response {
            quote: quote.to_string(),
            amount: Amount::from(100),
            fee_reserve: Amount::from(1),
            state: MeltQuoteState::Unpaid,
            expiry: 1000,
            payment_preimage: Some("preimage-11".to_string()),
            change: None,
            request: Some("lnbc100".to_string()),
            unit: Some(CurrencyUnit::Sat),
        }
    }

    fn bolt12_response(quote: &str) -> MeltQuoteBolt12Response<String> {
        MeltQuoteBolt12Response {
            quote: quote.to_string(),
            amount: Amount::from(200),
            fee_reserve: Amount::from(2),
            state: MeltQuoteState::Pending,
            expiry: 2000,
            payment_preimage: Some("preimage-12".to_string()),
            change: None,
            request: Some("lno200".to_string()),
            unit: Some(CurrencyUnit::Sat),
        }
    }

    fn onchain_response(quote: &str) -> MeltQuoteOnchainResponse<String> {
        MeltQuoteOnchainResponse {
            quote: quote.to_string(),
            amount: Amount::from(400),
            unit: CurrencyUnit::Sat,
            state: MeltQuoteState::Paid,
            expiry: 4000,
            request: "bc1qonchainaddress".to_string(),
            fee_options: vec![MeltQuoteOnchainFeeOption {
                fee_index: 0,
                fee_reserve: Amount::from(4),
                estimated_blocks: 6,
            }],
            selected_fee_index: Some(0),
            outpoint: Some("abcd...ef:0".to_string()),
            change: None,
        }
    }

    fn custom_response(quote: &str) -> MeltQuoteCustomResponse<String> {
        MeltQuoteCustomResponse {
            quote: quote.to_string(),
            amount: Amount::from(300),
            fee_reserve: Some(Amount::from(3)),
            state: MeltQuoteState::Paid,
            expiry: 3000,
            payment_preimage: Some("outpoint-abc".to_string()),
            change: None,
            request: Some("bc1qaddress".to_string()),
            unit: Some(CurrencyUnit::Sat),
            extra: serde_json::Value::Null,
        }
    }

    #[test]
    fn melt_quote_response_accessors_bolt11() {
        let r = MeltQuoteResponse::Bolt11(bolt11_response("q11"));
        assert_eq!(r.method(), PaymentMethod::Known(KnownMethod::Bolt11));
        assert_eq!(r.quote(), "q11");
        assert_eq!(r.amount(), Amount::from(100));
        assert_eq!(r.fee_reserve(), Amount::from(1));
        assert_eq!(r.state(), MeltQuoteState::Unpaid);
        assert_eq!(r.expiry(), 1000);
        assert_eq!(r.payment_proof(), Some("preimage-11"));
        assert!(r.change().is_none());
        assert_eq!(r.request(), Some("lnbc100"));
        assert_eq!(r.unit(), Some(CurrencyUnit::Sat));
    }

    #[test]
    fn melt_quote_response_accessors_bolt12() {
        let r = MeltQuoteResponse::Bolt12(bolt12_response("q12"));
        assert_eq!(r.method(), PaymentMethod::Known(KnownMethod::Bolt12));
        assert_eq!(r.quote(), "q12");
        assert_eq!(r.amount(), Amount::from(200));
        assert_eq!(r.fee_reserve(), Amount::from(2));
        assert_eq!(r.state(), MeltQuoteState::Pending);
        assert_eq!(r.expiry(), 2000);
        assert_eq!(r.payment_proof(), Some("preimage-12"));
        assert_eq!(r.request(), Some("lno200"));
    }

    #[test]
    fn melt_quote_response_accessors_onchain() {
        let r = MeltQuoteResponse::Onchain(onchain_response("qoc"));
        assert_eq!(r.method(), PaymentMethod::Known(KnownMethod::Onchain));
        assert_eq!(r.quote(), "qoc");
        assert_eq!(r.amount(), Amount::from(400));
        assert_eq!(r.fee_reserve(), Amount::from(4));
        assert_eq!(r.state(), MeltQuoteState::Paid);
        assert_eq!(r.expiry(), 4000);
        // payment_proof() is the outpoint, not a Lightning preimage
        assert_eq!(r.payment_proof(), Some("abcd...ef:0"));
        assert!(r.change().is_none());
        // `request` is non-Option on onchain; accessor wraps in Some
        assert_eq!(r.request(), Some("bc1qonchainaddress"));
        // `unit` is non-Option on onchain; accessor wraps in Some
        assert_eq!(r.unit(), Some(CurrencyUnit::Sat));
    }

    #[test]
    fn melt_quote_response_accessors_custom() {
        let method = PaymentMethod::from("paypal");
        let r = MeltQuoteResponse::Custom((method.clone(), custom_response("qc")));
        assert_eq!(r.method(), method);
        assert_eq!(r.quote(), "qc");
        assert_eq!(r.amount(), Amount::from(300));
        assert_eq!(r.fee_reserve(), Amount::from(3));
        assert_eq!(r.state(), MeltQuoteState::Paid);
        assert_eq!(r.expiry(), 3000);
        assert_eq!(r.payment_proof(), Some("outpoint-abc"));
        assert_eq!(r.request(), Some("bc1qaddress"));
    }

    #[test]
    fn melt_quote_create_response_accessors() {
        let r11 = MeltQuoteCreateResponse::Bolt11(bolt11_response("c11"));
        assert_eq!(r11.method(), PaymentMethod::Known(KnownMethod::Bolt11));
        assert_eq!(r11.quote().map(String::as_str), Some("c11"));

        let r12 = MeltQuoteCreateResponse::Bolt12(bolt12_response("c12"));
        assert_eq!(r12.method(), PaymentMethod::Known(KnownMethod::Bolt12));
        assert_eq!(r12.quote().map(String::as_str), Some("c12"));

        let method = PaymentMethod::from("venmo");
        let rc = MeltQuoteCreateResponse::Custom((method.clone(), custom_response("cc")));
        assert_eq!(rc.method(), method);
        assert_eq!(rc.quote().map(String::as_str), Some("cc"));
    }

    #[test]
    fn melt_quote_request_method_dispatch() {
        use crate::nuts::nut05::MeltQuoteCustomRequest;

        let custom_req = MeltQuoteCustomRequest {
            method: "cashapp".to_string(),
            unit: CurrencyUnit::Sat,
            request: "$tag".to_string(),
            extra: serde_json::Value::Null,
        };
        let req: MeltQuoteRequest = custom_req.into();
        assert_eq!(req.method(), PaymentMethod::from("cashapp"));
    }
}