cdk 0.18.0-rc.0

Core Cashu Development Kit library implementing the Cashu protocol
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
//! Issue (Mint) module for the wallet.
//!
//! This module provides functionality for minting new proofs via Bolt11, Bolt12, and Custom methods.

pub(crate) mod saga;

use cdk_common::nut00::KnownMethod;
use cdk_common::nut04::MintMethodOptions;
use cdk_common::{MintQuoteRequest, MintQuoteResponse, PaymentMethod};
pub(crate) use saga::MintSaga;
use tracing::instrument;

use crate::amount::SplitTarget;
use crate::nuts::{BatchCheckMintQuoteRequest, Proofs, SecretKey, SpendingConditions};
use crate::util::unix_time;
use crate::wallet::recovery::RecoveryAction;
use crate::wallet::{DerivationCounterNamespace, MintQuote, MintQuoteState};
use crate::{Amount, Error, Wallet};

pub(crate) fn apply_mint_quote_response(
    quote: &mut MintQuote,
    response: &MintQuoteResponse<String>,
) -> bool {
    match response {
        MintQuoteResponse::Bolt11(response) => {
            let state =
                if response.amount_paid > Amount::ZERO || response.amount_issued > Amount::ZERO {
                    match cdk_common::mint_quote::quote_state_from_amounts(
                        response.amount_paid,
                        response.amount_issued,
                    ) {
                        Ok(state) => state,
                        Err(err) => {
                            tracing::debug!("Ignoring invalid mint quote accounting: {}", err);
                            return false;
                        }
                    }
                } else {
                    response.state
                };
            let (amount_paid, amount_issued) = match state {
                MintQuoteState::Paid => {
                    let amount_paid = if response.amount_paid > Amount::ZERO {
                        response.amount_paid
                    } else {
                        response.amount.unwrap_or_default()
                    };
                    (amount_paid, response.amount_issued)
                }
                MintQuoteState::Issued => {
                    let amount = response.amount.unwrap_or_default();
                    let amount_paid = if response.amount_paid > Amount::ZERO {
                        response.amount_paid
                    } else {
                        amount
                    };
                    let amount_issued = if response.amount_issued > Amount::ZERO {
                        response.amount_issued
                    } else {
                        amount
                    };
                    (amount_paid, amount_issued)
                }
                MintQuoteState::Unpaid => (response.amount_paid, response.amount_issued),
            };

            if is_stale_mint_quote_update(quote, response.updated_at, amount_paid, amount_issued) {
                return false;
            }

            quote.state = state;
            quote.amount_paid = amount_paid;
            quote.amount_issued = amount_issued;
            quote.updated_at = quote.updated_at.max(response.updated_at);
            true
        }
        MintQuoteResponse::Bolt12(response) => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
        MintQuoteResponse::Onchain(response) => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
        MintQuoteResponse::Custom { response, .. } => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
    }
}

pub(crate) fn apply_accounting_mint_quote_update(
    quote: &mut MintQuote,
    amount_paid: Amount,
    amount_issued: Amount,
    updated_at: u64,
) -> bool {
    if amount_issued > amount_paid {
        tracing::debug!(
            "Ignoring invalid mint quote accounting: amount_issued {} exceeds amount_paid {}",
            amount_issued,
            amount_paid
        );
        return false;
    }

    if is_stale_mint_quote_update(quote, updated_at, amount_paid, amount_issued) {
        return false;
    }

    quote.amount_paid = amount_paid;
    quote.amount_issued = amount_issued;
    quote.updated_at = quote.updated_at.max(updated_at);
    quote.update_state_from_amounts();
    true
}

fn is_stale_mint_quote_update(
    quote: &MintQuote,
    updated_at: u64,
    amount_paid: Amount,
    amount_issued: Amount,
) -> bool {
    updated_at < quote.updated_at
        || amount_paid < quote.amount_paid
        || amount_issued < quote.amount_issued
}

fn local_mint_quote_amount(method: &PaymentMethod, amount: Option<Amount>) -> Option<Amount> {
    match method {
        PaymentMethod::Known(KnownMethod::Onchain) => None,
        _ => amount,
    }
}

fn mint_quote_response_amount(response: &MintQuoteResponse<String>) -> Option<Amount> {
    match response {
        MintQuoteResponse::Bolt11(r) => r.amount,
        MintQuoteResponse::Bolt12(r) => r.amount,
        MintQuoteResponse::Custom { response: r, .. } => r.amount,
        MintQuoteResponse::Onchain(_) => None,
    }
}

impl Wallet {
    async fn next_mint_quote_signing_key(&self) -> Result<SecretKey, Error> {
        let counter = self
            .reserve_derivation_index(DerivationCounterNamespace::Nut20Quote, 0)
            .await?;

        Ok(crate::nuts::nut20::derive_quote_locking_key(
            &self.seed, counter,
        )?)
    }

    /// Resolve the NUT-20 signing key for a mint quote
    ///
    /// Re-derives the key for explicitly marked NpubCash quotes. For all other
    /// quotes, returns the stored key without modifying wallet state.
    pub(crate) async fn mint_quote_signing_key(
        &self,
        quote: &MintQuote,
    ) -> Result<Option<SecretKey>, Error> {
        #[cfg(feature = "npubcash")]
        if let Some(key) = self.npubcash_quote_key(&quote.id).await? {
            return Ok(Some(self.npubcash_quote_secret_key(key)?));
        }

        Ok(quote.secret_key.clone())
    }

    /// Create a mint quote for the given payment method and amount
    #[instrument(skip(self, method))]
    pub async fn mint_quote(
        &self,
        method: PaymentMethod,
        amount: Option<Amount>,
        description: Option<String>,
        extra: Option<String>,
    ) -> Result<MintQuote, Error> {
        let quote = self
            .request_mint_quote(method, amount, description, extra)
            .await?;

        self.localstore.add_mint_quote(quote.clone()).await?;

        Ok(quote)
    }

    /// Request a mint quote without persisting it to the wallet database.
    pub(crate) async fn request_mint_quote(
        &self,
        method: PaymentMethod,
        amount: Option<Amount>,
        description: Option<String>,
        extra: Option<String>,
    ) -> Result<MintQuote, Error> {
        let mint_info = self.load_mint_info().await?;
        let mint_url = self.mint_url.clone();
        let unit = self.unit.clone();

        // Check settings and description support
        if description.is_some() {
            let settings = mint_info
                .nuts
                .nut04
                .get_settings(&unit, &method)
                .ok_or(Error::UnsupportedUnit)?;

            match settings.options {
                Some(MintMethodOptions::Bolt11 { description }) if description => (),
                _ => return Err(Error::InvoiceDescriptionUnsupported),
            }
        }

        self.keysets(Default::default()).await?;

        let secret_key = self.next_mint_quote_signing_key().await?;

        let request = match &method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                let amount = amount.ok_or(Error::AmountUndefined)?;
                MintQuoteRequest::Bolt11(cdk_common::nut23::MintQuoteBolt11Request {
                    amount,
                    unit: unit.clone(),
                    description,
                    pubkey: Some(secret_key.public_key()),
                })
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                MintQuoteRequest::Bolt12(cdk_common::nut25::MintQuoteBolt12Request {
                    amount,
                    unit: unit.clone(),
                    description,
                    pubkey: secret_key.public_key(),
                })
            }
            PaymentMethod::Custom(_) => {
                let amount = amount.ok_or(Error::AmountUndefined)?;
                MintQuoteRequest::Custom {
                    method: method.clone(),
                    request: cdk_common::nuts::MintQuoteCustomRequest {
                        amount: Some(amount),
                        unit: unit.clone(),
                        description,
                        pubkey: Some(secret_key.public_key()),
                        extra: serde_json::from_str(extra.as_deref().unwrap_or("{}"))?,
                    },
                }
            }
            PaymentMethod::Known(KnownMethod::Onchain) => {
                MintQuoteRequest::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainRequest {
                    unit: unit.clone(),
                    pubkey: secret_key.public_key(),
                })
            }
        };

        let response: MintQuoteResponse<String> = self.client.post_mint_quote(request).await?;
        let quote_id = response.quote().to_string();
        let request_str = response.request().to_string();
        let expiry = response.expiry();

        let mut quote = MintQuote::new(
            quote_id,
            mint_url,
            method.clone(),
            local_mint_quote_amount(&method, amount),
            unit,
            request_str,
            expiry.unwrap_or(0),
            Some(secret_key),
        );
        apply_mint_quote_response(&mut quote, &response);

        Ok(quote)
    }

    /// Checks the state of a mint quote with the mint
    async fn check_state(&self, mint_quote: &mut MintQuote) -> Result<(), Error> {
        let mint_quote_response: MintQuoteResponse<String> = self
            .client
            .get_mint_quote_status(mint_quote.payment_method.clone(), &mint_quote.id)
            .await?;
        apply_mint_quote_response(mint_quote, &mint_quote_response);

        Ok(())
    }

    /// This method:
    /// 1. Fetches the current quote state from the mint
    /// 2. If there's an in-progress saga for this quote, attempts to complete it
    /// 3. If the saga was compensated (rolled back), attempts a fresh mint
    /// 4. Returns the updated quote
    #[instrument(skip_all)]
    async fn inner_check_mint_quote_status(
        &self,
        mut mint_quote: MintQuote,
    ) -> Result<MintQuote, Error> {
        let quote_id = mint_quote.id.clone();
        // First, check/update the state from the mint
        self.check_state(&mut mint_quote).await?;

        // Check if there's an in-progress saga for this quote
        if let Some(ref operation_id_str) = mint_quote.used_by_operation {
            if let Ok(operation_id) = uuid::Uuid::parse_str(operation_id_str) {
                match self.localstore.get_saga(&operation_id).await {
                    Ok(Some(saga)) => {
                        // Saga exists - try to complete it (like recovery does)
                        tracing::info!(
                            "Mint quote {} has in-progress saga {}, attempting to complete",
                            quote_id,
                            operation_id
                        );

                        let recovery_action = self.resume_issue_saga(&saga).await?;

                        // If compensated, the saga was rolled back - attempt to mint again
                        if recovery_action == RecoveryAction::Compensated {
                            tracing::info!(
                                "Saga {} was compensated, attempting fresh mint for quote {}",
                                operation_id,
                                quote_id
                            );
                        } else {
                            // If the saga completed we need to get the updated state of the mint quote fn the db
                            mint_quote = self
                                .localstore
                                .get_mint_quote(&quote_id)
                                .await?
                                .ok_or(Error::UnknownQuote)?;
                        }
                        // If Recovered or Skipped, just continue with the updated quote
                    }
                    Ok(None) => {
                        // Orphaned reservation - release it
                        tracing::warn!(
                            "Mint quote {} has orphaned reservation for operation {}, releasing",
                            quote_id,
                            operation_id
                        );
                        if let Err(e) = self.localstore.release_mint_quote(&operation_id).await {
                            tracing::warn!("Failed to release orphaned mint quote: {}", e);
                        }
                    }
                    Err(e) => {
                        tracing::warn!("Failed to check saga for mint quote {}: {}", quote_id, e);
                        return Err(Error::Database(e));
                    }
                }
            }
        }

        self.localstore.add_mint_quote(mint_quote.clone()).await?;
        Ok(mint_quote)
    }

    /// Check the status of a single mint quote from the mint.
    ///
    /// Calls `GET /v1/mint/quote/{method}/{quote_id}` per NUT-04.
    /// Updates local store with current state from mint.
    /// If there was a crashed mid-mint (pending saga), attempts to complete it.
    /// Does NOT mint tokens directly - use mint() for that.
    ///
    /// **Note:** The mint quote must be known to the wallet (stored locally) for this
    /// function to work. If the quote is not stored locally, use `fetch_mint_quote`
    /// instead.
    #[instrument(skip(self, quote_id))]
    pub async fn check_mint_quote_status(&self, quote_id: &str) -> Result<MintQuote, Error> {
        let mint_quote = self
            .localstore
            .get_mint_quote(quote_id)
            .await?
            .ok_or(Error::UnknownQuote)?;

        let mint_quote = self.inner_check_mint_quote_status(mint_quote).await?;

        Ok(mint_quote)
    }

    /// Check a mint quote status (alias for `check_mint_quote_status`)
    #[instrument(skip(self, quote_id))]
    pub async fn check_mint_quote(&self, quote_id: &str) -> Result<MintQuote, Error> {
        self.check_mint_quote_status(quote_id).await
    }

    /// Check all unissued mint quote states from the mint.
    ///
    /// Calls `GET /v1/mint/quote/{method}/{quote_id}` per NUT-04 for each quote.
    /// Updates local store with current state from mint for each quote.
    /// If there was a crashed mid-mint (pending saga), attempts to complete it.
    /// Does NOT mint tokens directly - use mint() or mint_unissued_quotes() for that.
    #[instrument(skip(self))]
    pub async fn check_all_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mint_quotes = self.localstore.get_unissued_mint_quotes().await?;
        let mut updated_quotes = Vec::new();

        for mint_quote in mint_quotes {
            if mint_quote.mint_url != self.mint_url || mint_quote.unit != self.unit {
                continue;
            }

            match self.inner_check_mint_quote_status(mint_quote).await {
                Ok(q) => updated_quotes.push(q),
                Err(err) => {
                    tracing::warn!("Could not check quote state: {}", err);
                    continue;
                }
            }
        }
        Ok(updated_quotes)
    }

    /// Refresh states and mint all unissued quotes that have mintable amounts.
    /// Returns the total amount minted across all quotes.
    ///
    /// # Privacy
    ///
    /// This method retrieves all unissued mint quotes from the local store and
    /// checks their state with the mint. This has a negative privacy effect of
    /// linking all these quotes to a single wallet session.
    #[instrument(skip(self))]
    pub async fn mint_unissued_quotes(&self) -> Result<Amount, Error> {
        let mint_quotes = self.localstore.get_unissued_mint_quotes().await?;
        let mut total_amount = Amount::ZERO;

        for mint_quote in mint_quotes {
            if mint_quote.mint_url != self.mint_url || mint_quote.unit != self.unit {
                continue;
            }

            let current_amount_issued = mint_quote.amount_issued;

            let mint_quote = match self.inner_check_mint_quote_status(mint_quote).await {
                Ok(q) => q,
                Err(err) => {
                    tracing::warn!("Could not check quote state: {}", err);
                    continue;
                }
            };

            if mint_quote.amount_mintable() > Amount::ZERO {
                if let Err(err) = self
                    .mint(&mint_quote.id, SplitTarget::default(), None)
                    .await
                {
                    tracing::warn!("Could not mint quote {}: {}", mint_quote.id, err);
                    continue;
                }
            }

            // Get updated quote to calculate minted amount
            let updated_quote = match self.localstore.get_mint_quote(&mint_quote.id).await {
                Ok(Some(q)) => q,
                _ => continue,
            };

            total_amount = total_amount
                .checked_add(
                    updated_quote
                        .amount_issued
                        .checked_sub(current_amount_issued)
                        .unwrap_or_default(),
                )
                .ok_or(Error::AmountOverflow)?;
        }
        Ok(total_amount)
    }

    /// Get active mint quotes
    /// Returns mint quotes that are not expired and not yet issued.
    #[instrument(skip(self))]
    pub async fn get_active_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mut mint_quotes = self.localstore.get_mint_quotes().await?;
        let unix_time = unix_time();
        mint_quotes.retain(|quote| {
            quote.mint_url == self.mint_url
                && quote.unit == self.unit
                && quote.state != MintQuoteState::Issued
                && quote.expiry > unix_time
        });
        Ok(mint_quotes)
    }

    /// Get unissued mint quotes
    /// Returns bolt11 quotes where nothing has been issued yet (amount_issued = 0) and all bolt12 quotes.
    /// Includes unpaid bolt11 quotes to allow checking with the mint if they've been paid (wallet state may be outdated).
    /// Filters out quotes from other mints and units. Does not filter by expiry time to allow
    /// checking with the mint if expired quotes can still be minted.
    #[instrument(skip(self))]
    pub async fn get_unissued_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mut pending_quotes = self.localstore.get_unissued_mint_quotes().await?;
        pending_quotes.retain(|quote| quote.mint_url == self.mint_url && quote.unit == self.unit);
        Ok(pending_quotes)
    }

    /// Mint
    #[instrument(skip(self))]
    pub async fn mint(
        &self,
        quote_id: &str,
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
    ) -> Result<Proofs, Error> {
        self.retry_on_inactive_keyset(|| async {
            let saga = MintSaga::new(self);
            let saga = saga
                .prepare(
                    quote_id,
                    amount_split_target.clone(),
                    spending_conditions.clone(),
                )
                .await?;
            let saga = saga.execute().await?;
            Ok(saga.into_proofs())
        })
        .await
    }

    /// Mint tokens for a quote (alias for `mint`)
    #[instrument(skip(self))]
    pub async fn mint_unified(
        &self,
        quote_id: &str,
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
    ) -> Result<Proofs, Error> {
        self.mint(quote_id, amount_split_target, spending_conditions)
            .await
    }

    /// Fetch a mint quote from the mint and store it locally
    ///
    /// This method contacts the mint to get the current state of a quote,
    /// creates or updates the quote in local storage, and returns the stored quote.
    ///
    /// Works with all payment methods (Bolt11, Bolt12, and custom payment methods).
    ///
    /// # Arguments
    /// * `quote_id` - The ID of the quote to fetch
    /// * `payment_method` - The payment method for the quote. Required if the quote
    ///   is not already stored locally. If the quote exists locally, the stored
    ///   payment method will be used and this parameter is ignored.
    ///
    /// # Errors
    /// Returns `Error::PaymentMethodRequired` if the quote is not found locally
    /// and no payment method is provided.
    #[instrument(skip(self, quote_id))]
    pub async fn fetch_mint_quote(
        &self,
        quote_id: &str,
        payment_method: Option<PaymentMethod>,
    ) -> Result<MintQuote, Error> {
        // Check if we already have this quote stored locally
        let existing_quote = self.localstore.get_mint_quote(quote_id).await?;

        // Determine the payment method to use
        let method = match (&existing_quote, &payment_method) {
            (Some(q), _) => q.payment_method.clone(),
            (None, Some(m)) => m.clone(),
            (None, None) => return Err(Error::PaymentMethodRequired),
        };

        // Fetch the quote status from the mint using unified method
        let response: MintQuoteResponse<String> = self
            .client
            .get_mint_quote_status(method.clone(), quote_id)
            .await?;

        let quote = match existing_quote {
            Some(mut existing) => {
                apply_mint_quote_response(&mut existing, &response);
                existing
            }
            None => {
                // Create a new quote from the response
                let amount = mint_quote_response_amount(&response);
                let unit = match &response {
                    MintQuoteResponse::Bolt11(r) => r.unit.clone(),
                    MintQuoteResponse::Bolt12(r) => Some(r.unit.clone()),
                    MintQuoteResponse::Custom { response: r, .. } => r.unit.clone(),
                    MintQuoteResponse::Onchain(r) => Some(r.unit.clone()),
                };
                let mut quote = MintQuote::new(
                    quote_id.to_string(),
                    self.mint_url.clone(),
                    method,
                    amount,
                    unit.unwrap_or(self.unit.clone()),
                    response.request().to_string(),
                    response.expiry().unwrap_or(0),
                    None,
                );
                apply_mint_quote_response(&mut quote, &response);
                quote
            }
        };

        // Store the quote
        self.localstore.add_mint_quote(quote.clone()).await?;

        Ok(quote)
    }

    /// Batch check status of multiple mint quotes from the mint.
    ///
    /// Calls `POST /v1/mint/quote/{method}/check` per NUT-29.
    /// All quotes must share the same payment method.
    /// Updates local store with current state from mint for each quote.
    #[instrument(skip(self, quote_ids))]
    pub async fn batch_check_mint_quote_status(
        &self,
        quote_ids: &[&str],
    ) -> Result<Vec<MintQuote>, Error> {
        if quote_ids.is_empty() {
            return Err(Error::UnknownQuote);
        }

        // Load all quotes and determine payment method
        let mut quotes: Vec<MintQuote> = Vec::new();
        for quote_id in quote_ids {
            let quote = self
                .localstore
                .get_mint_quote(quote_id)
                .await?
                .ok_or(Error::UnknownQuote)?;
            quotes.push(quote);
        }

        // All quotes must share the same payment method
        let payment_method = quotes[0].payment_method.clone();
        for quote in &quotes {
            if quote.payment_method != payment_method {
                return Err(Error::InvalidPaymentMethod);
            }
        }

        // Call batch check endpoint
        let request = BatchCheckMintQuoteRequest {
            quotes: quote_ids.iter().map(|s| s.to_string()).collect(),
        };

        let responses = self
            .client
            .post_batch_check_mint_quote_status(&payment_method, request)
            .await?;

        // Update local quotes with response data
        for (quote, response) in quotes.iter_mut().zip(responses.iter()) {
            apply_mint_quote_response(quote, response);
            self.localstore.add_mint_quote(quote.clone()).await?;
        }

        Ok(quotes)
    }

    /// Mint tokens for multiple quotes in a single batch operation.
    ///
    /// Calls `POST /v1/mint/{method}/batch` per NUT-29.
    /// All quotes must share the same payment method and unit.
    /// Uses the saga pattern for crash recovery.
    ///
    /// # Arguments
    /// * `quote_ids` - Array of unique quote IDs to mint
    /// * `amount_split_target` - How to split the minted amount into proofs
    /// * `spending_conditions` - Optional conditions to attach to the proofs
    /// * `external_keys` - Optional signing keys for quotes not in local store
    #[instrument(skip(self, quote_ids, spending_conditions, external_keys))]
    pub async fn batch_mint(
        &self,
        quote_ids: &[&str],
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
        external_keys: Option<std::collections::HashMap<String, SecretKey>>,
    ) -> Result<Proofs, Error> {
        // Create saga and prepare batch
        let saga = MintSaga::new(self);

        let prepared = saga
            .prepare_batch(
                quote_ids,
                amount_split_target,
                spending_conditions,
                external_keys.as_ref(),
            )
            .await?;

        // Execute the mint
        let finalized = prepared.execute().await?;

        Ok(finalized.into_proofs())
    }
}

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

    use bip39::Mnemonic;
    use cdk_common::mint_url::MintUrl;
    use cdk_common::nuts::CurrencyUnit;

    use super::*;

    #[tokio::test]
    async fn mint_quote_signing_keys_follow_nut20_counter_across_wallet_instances() {
        let mnemonic = Mnemonic::from_str(
            "half depart obvious quality work element tank gorilla view sugar picture humble",
        )
        .expect("valid mnemonic");
        let seed = mnemonic.to_seed_normalized("");
        let db = crate::wallet::test_utils::create_test_db().await;
        let wallet = Wallet::new(
            "https://mint.example.com",
            CurrencyUnit::Sat,
            db.clone(),
            seed,
            None,
        )
        .expect("wallet should build");

        let first = wallet
            .next_mint_quote_signing_key()
            .await
            .expect("first key should derive");
        let second = wallet
            .next_mint_quote_signing_key()
            .await
            .expect("second key should derive");

        let restarted_wallet = Wallet::new(
            "https://mint.example.com",
            CurrencyUnit::Sat,
            db,
            seed,
            None,
        )
        .expect("wallet should rebuild");
        let third = restarted_wallet
            .next_mint_quote_signing_key()
            .await
            .expect("third key should derive");

        assert_eq!(
            first.public_key().to_hex(),
            "03062837166e56114b59a4d1fd3a5a812bf7aadc1dde758428cf943d80acd41539"
        );
        assert_eq!(
            second.public_key().to_hex(),
            "02b47d9d41725f5ce6f08c874835cef25376cb1e95f6cb073fef52ca8fd986cf15"
        );
        assert_eq!(
            third.public_key().to_hex(),
            "029acbd3a46fd75bc05ba0226d0b4d909b2fb6e96c80544a094a1a3567737e44d3"
        );
    }

    #[test]
    fn local_onchain_mint_quote_amount_is_not_stored() {
        let amount = Some(Amount::from(1_000));

        assert_eq!(
            local_mint_quote_amount(&PaymentMethod::Known(KnownMethod::Onchain), amount),
            None
        );
    }

    #[test]
    fn fetched_onchain_mint_quote_does_not_use_amount_paid_as_amount() {
        let response =
            MintQuoteResponse::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainResponse {
                quote: "quote-id".to_string(),
                request: "bc1qexample".to_string(),
                unit: CurrencyUnit::Sat,
                method: PaymentMethod::Known(KnownMethod::Onchain),
                expiry: Some(1_700_000_000),
                pubkey: SecretKey::generate().public_key(),
                amount_paid: Amount::from(1_000),
                amount_issued: Amount::from(250),
                updated_at: 0,
            });

        assert_eq!(mint_quote_response_amount(&response), None);
    }

    #[test]
    fn stale_mint_quote_response_does_not_decrease_accounting() {
        let mut quote = MintQuote::new(
            "quote-id".to_string(),
            MintUrl::from_str("https://mint.example.com").expect("valid mint url"),
            PaymentMethod::Custom("custom".to_string()),
            Some(Amount::from(200)),
            CurrencyUnit::Sat,
            "custom-request".to_string(),
            1_700_000_000,
            None,
        );
        quote.amount_paid = Amount::from(100);
        quote.amount_issued = Amount::from(20);
        quote.updated_at = 10;
        quote.update_state_from_amounts();

        let stale_response = custom_mint_quote_response(Amount::from(200), Amount::from(20), 9);
        assert!(!apply_mint_quote_response(&mut quote, &stale_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);

        let decreasing_response =
            custom_mint_quote_response(Amount::from(90), Amount::from(20), 11);
        assert!(!apply_mint_quote_response(&mut quote, &decreasing_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);

        let fresh_response = custom_mint_quote_response(Amount::from(150), Amount::from(30), 12);
        assert!(apply_mint_quote_response(&mut quote, &fresh_response));

        assert_eq!(quote.amount_paid, Amount::from(150));
        assert_eq!(quote.amount_issued, Amount::from(30));
        assert_eq!(quote.updated_at, 12);
    }

    #[test]
    fn invalid_mint_quote_response_does_not_apply_accounting() {
        let mut quote = MintQuote::new(
            "quote-id".to_string(),
            MintUrl::from_str("https://mint.example.com").expect("valid mint url"),
            PaymentMethod::Custom("custom".to_string()),
            Some(Amount::from(200)),
            CurrencyUnit::Sat,
            "custom-request".to_string(),
            1_700_000_000,
            None,
        );
        quote.amount_paid = Amount::from(100);
        quote.amount_issued = Amount::from(20);
        quote.updated_at = 10;
        quote.update_state_from_amounts();

        let invalid_response = custom_mint_quote_response(Amount::from(120), Amount::from(150), 11);
        assert!(!apply_mint_quote_response(&mut quote, &invalid_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);
        assert_eq!(quote.state, MintQuoteState::Paid);
    }

    fn custom_mint_quote_response(
        amount_paid: Amount,
        amount_issued: Amount,
        updated_at: u64,
    ) -> MintQuoteResponse<String> {
        MintQuoteResponse::Custom {
            method: PaymentMethod::Custom("custom".to_string()),
            response: cdk_common::nut04::MintQuoteCustomResponse {
                quote: "quote-id".to_string(),
                request: "custom-request".to_string(),
                method: PaymentMethod::Custom("custom".to_string()),
                amount: Some(Amount::from(200)),
                amount_paid,
                amount_issued,
                updated_at,
                unit: Some(CurrencyUnit::Sat),
                expiry: Some(1_700_000_000),
                pubkey: None,
                extra: serde_json::Value::Null,
            },
        }
    }
}