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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! Wallet Repository
//!
//! Simple container that manages [`Wallet`] instances by mint URL.

use std::collections::BTreeMap;
use std::fmt;
#[cfg(feature = "npubcash")]
use std::str::FromStr;
use std::sync::Arc;

use cdk_common::database;
use cdk_common::database::WalletDatabase;
use cdk_common::wallet::WalletKey;
use tokio::sync::RwLock;
use tracing::instrument;
use zeroize::Zeroize;

use super::builder::WalletBuilder;
use super::{AuthMintConnector, Error, MintConnector, RateLimitConfig, RateLimiterManager};
use crate::mint_url::MintUrl;
use crate::nuts::CurrencyUnit;
#[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
use crate::wallet::mint_connector::transport::TorAsync;
use crate::{OidcClient, Wallet};

/// Data extracted from a token
///
/// Contains the mint URL, proofs, and metadata from a parsed token.
#[derive(Debug, Clone)]
pub struct TokenData {
    /// The mint URL from the token
    pub mint_url: MintUrl,
    /// The proofs contained in the token
    pub proofs: cdk_common::Proofs,
    /// The memo from the token, if present
    pub memo: Option<String>,
    /// Value of token
    pub value: cdk_common::Amount,
    /// Unit of token
    pub unit: CurrencyUnit,
    /// Fee to redeem
    ///
    /// If the token is for a mint that we do not know, we cannot get the fee.
    /// To avoid just erroring and still allow decoding, this is an option.
    /// None does not mean there is no fee, it means we do not know the fee.
    pub redeem_fee: Option<cdk_common::Amount>,
}

/// Configuration for individual wallets within WalletRepository
#[derive(Clone, Default)]
pub struct WalletConfig {
    /// Custom mint connector implementation
    pub mint_connector: Option<Arc<dyn super::MintConnector + Send + Sync>>,
    /// Custom auth connector implementation
    pub auth_connector: Option<Arc<dyn super::auth::AuthMintConnector + Send + Sync>>,
    /// Target number of proofs to maintain at each denomination
    pub target_proof_count: Option<usize>,
    /// Metadata cache TTL
    ///
    /// The TTL determines how often the wallet checks the mint for new keysets and information.
    ///
    /// If `None`, the cache will never expire and the wallet will use cached data indefinitely
    /// (unless manually refreshed).
    ///
    /// The default value is 1 hour (3600 seconds).
    pub metadata_cache_ttl: Option<std::time::Duration>,
}

impl fmt::Debug for WalletConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WalletConfig")
            .field(
                "mint_connector",
                &self.mint_connector.as_ref().map(|_| "[CONFIGURED]"),
            )
            .field(
                "auth_connector",
                &self.auth_connector.as_ref().map(|_| "[CONFIGURED]"),
            )
            .field("target_proof_count", &self.target_proof_count)
            .field("metadata_cache_ttl", &self.metadata_cache_ttl)
            .finish()
    }
}

impl WalletConfig {
    /// Create a new empty WalletConfig
    pub fn new() -> Self {
        Self::default()
    }

    /// Set custom mint connector
    pub fn with_mint_connector(
        mut self,
        connector: Arc<dyn super::MintConnector + Send + Sync>,
    ) -> Self {
        self.mint_connector = Some(connector);
        self
    }

    /// Set custom auth connector
    pub fn with_auth_connector(
        mut self,
        connector: Arc<dyn super::auth::AuthMintConnector + Send + Sync>,
    ) -> Self {
        self.auth_connector = Some(connector);
        self
    }

    /// Set target proof count
    pub fn with_target_proof_count(mut self, count: usize) -> Self {
        self.target_proof_count = Some(count);
        self
    }

    /// Set metadata cache TTL
    ///
    /// The TTL determines how often the wallet checks the mint for new keysets and information.
    ///
    /// If `None`, the cache will never expire and the wallet will use cached data indefinitely
    /// (unless manually refreshed).
    ///
    /// The default value is 1 hour (3600 seconds).
    pub fn with_metadata_cache_ttl(mut self, ttl: Option<std::time::Duration>) -> Self {
        self.metadata_cache_ttl = ttl;
        self
    }
}

/// Builder for creating [`WalletRepository`] instances
///
/// # Example
/// ```no_run
/// # use std::sync::Arc;
/// # use cdk::wallet::WalletRepositoryBuilder;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let localstore = Arc::new(cdk_sqlite::wallet::memory::empty().await?);
/// let seed = [0u8; 64];
/// let wallet_repo = WalletRepositoryBuilder::new()
///     .localstore(localstore)
///     .seed(seed)
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct WalletRepositoryBuilder {
    localstore: Option<Arc<dyn WalletDatabase<database::Error> + Send + Sync>>,
    seed: Option<[u8; 64]>,
    proxy_config: Option<url::Url>,
    danger_accept_invalid_certs: bool,
    rate_limit: Option<RateLimitConfig>,
    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
    use_tor: bool,
}

impl std::fmt::Debug for WalletRepositoryBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WalletRepositoryBuilder")
            .field("localstore", &self.localstore.as_ref().map(|_| "..."))
            .field("seed", &"[REDACTED]")
            .field("proxy_config", &self.proxy_config)
            .field(
                "danger_accept_invalid_certs",
                &self.danger_accept_invalid_certs,
            )
            .field("rate_limit", &self.rate_limit)
            .finish()
    }
}

impl Default for WalletRepositoryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl WalletRepositoryBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            localstore: None,
            seed: None,
            proxy_config: None,
            danger_accept_invalid_certs: false,
            rate_limit: Some(RateLimitConfig::default()),
            #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
            use_tor: false,
        }
    }

    /// Set the storage backend
    pub fn localstore(
        mut self,
        localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync>,
    ) -> Self {
        self.localstore = Some(localstore);
        self
    }

    /// Set the wallet seed
    pub fn seed(mut self, seed: [u8; 64]) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Set the proxy URL for HTTP clients
    pub fn proxy_url(mut self, proxy_url: url::Url) -> Self {
        self.proxy_config = Some(proxy_url);
        self
    }

    /// Disable TLS certificate verification for proxied HTTPS clients.
    ///
    /// This permits man-in-the-middle attacks and should only be used for
    /// local debugging or trusted test environments.
    pub fn danger_accept_invalid_certs(mut self, accept_invalid_certs: bool) -> Self {
        self.danger_accept_invalid_certs = accept_invalid_certs;
        self
    }

    /// Enable Tor transport
    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
    pub fn tor(mut self) -> Self {
        self.use_tor = true;
        self
    }

    /// Set the rate-limiting configuration shared by every wallet this
    /// repository builds.
    ///
    /// Rate limiting is on by default with [`RateLimitConfig::default`].
    pub fn with_rate_limiting_config(mut self, config: RateLimitConfig) -> Self {
        self.rate_limit = Some(config);
        self
    }

    /// Start with pacing turned off.
    ///
    /// The limiter is still built, so
    /// [`WalletRepository::set_rate_limiting_config`] can turn pacing back on
    /// later. That reversibility is why this is not named
    /// `without_rate_limiting`: the repository has no equivalent of
    /// [`WalletBuilder::without_rate_limiting`], which drops the limiter
    /// outright, because one limiter is shared across every wallet here.
    pub fn with_rate_limiting_disabled(mut self) -> Self {
        self.rate_limit = None;
        self
    }

    /// Build the WalletRepository and load existing wallets from the database.
    ///
    /// This only uses persisted mint metadata and does not make network requests.
    pub async fn build(self) -> Result<WalletRepository, Error> {
        let localstore = self
            .localstore
            .ok_or(Error::Custom("localstore is required".into()))?;
        let seed = self.seed.ok_or(Error::Custom("seed is required".into()))?;

        let rate_limiter = RateLimiterManager::new(
            self.rate_limit.unwrap_or_default(),
            Some(localstore.clone()),
        );
        rate_limiter.set_enabled(self.rate_limit.is_some());

        let wallet = WalletRepository {
            rate_limiter,
            localstore,
            seed,
            wallets: Arc::new(RwLock::new(BTreeMap::new())),
            proxy_config: self.proxy_config,
            danger_accept_invalid_certs: self.danger_accept_invalid_certs,
            #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
            shared_tor_transport: if self.use_tor {
                Some(TorAsync::new())
            } else {
                None
            },
        };

        wallet.load_wallets().await?;
        Ok(wallet)
    }
}

fn proxy_http_client(
    mint_url: MintUrl,
    proxy_url: &url::Url,
    accept_invalid_certs: bool,
) -> Result<crate::wallet::HttpClient, Error> {
    validate_proxy_url(proxy_url)?;

    crate::wallet::HttpClient::with_proxy(mint_url, proxy_url.clone(), None, accept_invalid_certs)
}

fn proxy_auth_http_client(
    mint_url: MintUrl,
    proxy_url: &url::Url,
    accept_invalid_certs: bool,
) -> Result<crate::wallet::AuthHttpClient, Error> {
    validate_proxy_url(proxy_url)?;

    crate::wallet::AuthHttpClient::with_proxy(
        mint_url,
        proxy_url.clone(),
        None,
        accept_invalid_certs,
        None,
    )
}

fn validate_proxy_url(proxy_url: &url::Url) -> Result<(), Error> {
    match proxy_url.scheme() {
        "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h" => {}
        scheme => {
            return Err(Error::HttpError(
                None,
                format!("Unsupported proxy URL scheme: {scheme}"),
            ));
        }
    }

    Ok(())
}

/// Repository for managing Wallet instances by mint URL and currency unit
///
/// Simple container that bootstraps wallets from database and provides
/// access to individual Wallet instances. Each wallet is uniquely identified
/// by the combination of mint URL and currency unit.
///
/// Every wallet shares the repository's [`RateLimiterManager`], which keys
/// budgets by the host each request is addressed to. Wallets at one mint pace
/// one combined burst regardless of currency unit, and traffic to a third-party
/// host (an LNURL service, an OIDC provider) paces against that host's own
/// budget rather than any mint's.
///
/// Because that limiter is shared, pacing is configured for the repository as a
/// whole, at build time through [`WalletRepositoryBuilder::with_rate_limiting_config`]
/// or later through [`WalletRepository::set_rate_limiting_config`], never per
/// wallet. Proxied and Tor wallets are built with a custom client, so their
/// limiter is wired to nothing and they report
/// [`Wallet::is_rate_limited`] as false whatever the repository is set to.
#[derive(Clone)]
pub struct WalletRepository {
    /// Storage backend
    localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync>,
    seed: [u8; 64],
    /// Wallets indexed by (mint URL, currency unit)
    wallets: Arc<RwLock<BTreeMap<WalletKey, Wallet>>>,
    /// Hands out one shared rate-limit budget per destination host, injected
    /// into every wallet this repository builds.
    rate_limiter: RateLimiterManager,
    /// Proxy configuration for HTTP clients (optional)
    proxy_config: Option<url::Url>,
    /// Whether proxied HTTPS clients should accept invalid TLS certificates
    danger_accept_invalid_certs: bool,
    /// Shared Tor transport to be cloned into each TorHttpClient (if enabled)
    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
    shared_tor_transport: Option<TorAsync>,
}

impl std::fmt::Debug for WalletRepository {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WalletRepository").finish_non_exhaustive()
    }
}

impl WalletRepository {
    /// Get the wallet seed
    pub fn seed(&self) -> &[u8; 64] {
        &self.seed
    }

    /// Get wallet for a mint URL and currency unit
    ///
    /// Returns an error if no wallet exists for the given mint URL and unit combination.
    #[instrument(skip(self))]
    pub async fn get_wallet(
        &self,
        mint_url: &MintUrl,
        unit: &CurrencyUnit,
    ) -> Result<Wallet, Error> {
        let key = WalletKey::new(mint_url.clone(), unit.clone());
        self.wallets
            .read()
            .await
            .get(&key)
            .cloned()
            .ok_or_else(|| Error::UnknownWallet(key))
    }

    /// Get all wallets for a specific mint URL (any currency unit)
    #[instrument(skip(self))]
    pub async fn get_wallets_for_mint(&self, mint_url: &MintUrl) -> Vec<Wallet> {
        self.wallets
            .read()
            .await
            .iter()
            .filter(|(key, _)| &key.mint_url == mint_url)
            .map(|(_, wallet)| wallet.clone())
            .collect()
    }

    /// Create an OIDC client using a wallet connector for this mint when available.
    #[instrument(skip(self))]
    pub async fn oidc_client_for_mint(
        &self,
        mint_url: &MintUrl,
        openid_discovery: String,
        client_id: Option<String>,
    ) -> OidcClient {
        match self.get_wallets_for_mint(mint_url).await.into_iter().next() {
            Some(wallet) => wallet.oidc_client(openid_discovery, client_id),
            None => OidcClient::new(openid_discovery, client_id),
        }
    }

    /// Check if a specific wallet exists (mint URL + unit combination)
    #[instrument(skip(self))]
    pub async fn has_wallet(&self, mint_url: &MintUrl, unit: &CurrencyUnit) -> bool {
        let key = WalletKey::new(mint_url.clone(), unit.clone());
        self.wallets.read().await.contains_key(&key)
    }

    /// Add wallets for a mint to the repository
    ///
    /// Fetches the mint info to discover all supported currency units and creates
    /// a wallet for each unit. Returns all created wallets.
    #[instrument(skip(self))]
    pub async fn add_wallet(&self, mint_url: MintUrl) -> Result<Vec<Wallet>, Error> {
        self.add_wallet_with_config(mint_url, None).await
    }

    /// Add wallets for a mint to the repository with a custom configuration
    ///
    /// Fetches the mint info to discover all supported currency units and creates
    /// a wallet for each unit with the given configuration. Returns all created wallets.
    #[instrument(skip(self, config))]
    pub async fn add_wallet_with_config(
        &self,
        mint_url: MintUrl,
        config: Option<WalletConfig>,
    ) -> Result<Vec<Wallet>, Error> {
        // Fetch mint info to get supported units
        let mint_info = self.fetch_mint_info(&mint_url).await?;
        let supported_units = mint_info.supported_units();

        if supported_units.is_empty() {
            return Err(Error::Custom(
                "Mint does not support any currency units".into(),
            ));
        }

        let mut wallets = Vec::new();
        for unit in supported_units {
            let wallet = self
                .get_or_create_wallet(mint_url.clone(), unit.clone(), config.clone())
                .await?;
            wallets.push(wallet);
        }

        Ok(wallets)
    }

    /// Return the wallet for a mint and unit, creating it if it does not exist yet.
    ///
    /// An existing wallet is returned untouched. Use [`Self::create_wallet`] to
    /// replace it with a new configuration.
    ///
    /// The write lock is held across the lookup and the insert so that concurrent
    /// callers for the same mint and unit all observe the same wallet instead of
    /// each building one and the last writer winning.
    #[instrument(skip(self, config))]
    pub async fn get_or_create_wallet(
        &self,
        mint_url: MintUrl,
        unit: CurrencyUnit,
        config: Option<WalletConfig>,
    ) -> Result<Wallet, Error> {
        let key = WalletKey::new(mint_url.clone(), unit.clone());
        let mut wallets = self.wallets.write().await;

        if let Some(existing) = wallets.get(&key) {
            return Ok(existing.clone());
        }

        let wallet = self
            .create_wallet_internal(mint_url, unit, config.as_ref())
            .await?;
        wallets.insert(key, wallet.clone());

        Ok(wallet)
    }

    /// Update configuration for an existing mint and unit
    ///
    /// This re-creates the wallet with the new configuration.
    #[instrument(skip(self, config))]
    pub async fn set_mint_config(
        &self,
        mint_url: MintUrl,
        unit: CurrencyUnit,
        config: WalletConfig,
    ) -> Result<Wallet, Error> {
        // Re-create wallet with new config
        self.create_wallet(mint_url, unit, Some(config)).await
    }

    /// Create and add a new wallet for a mint URL and currency unit
    /// Returns the created wallet
    #[instrument(skip(self, config))]
    pub async fn create_wallet(
        &self,
        mint_url: MintUrl,
        unit: CurrencyUnit,
        config: Option<WalletConfig>,
    ) -> Result<Wallet, Error> {
        let wallet = self
            .create_wallet_internal(mint_url.clone(), unit.clone(), config.as_ref())
            .await?;

        // Insert into wallets map using WalletKey
        let key = WalletKey::new(mint_url, unit);
        let mut wallets = self.wallets.write().await;
        wallets.insert(key, wallet.clone());

        Ok(wallet)
    }

    /// Wait until the rate-limit budgets drawn down by every wallet in this
    /// repository have been handed to storage.
    ///
    /// The repository owns the limiter its wallets share, so this is the
    /// shutdown barrier to await before dropping it. Equivalent to
    /// [`Wallet::flush_rate_limits`] on any one of its wallets, and safe to call
    /// when the repository holds no wallets at all. The same caveat applies:
    /// without it, persistence is best effort and a rebuild can outrun the
    /// detached writer.
    pub async fn flush_rate_limits(&self) {
        self.rate_limiter.flush().await;
    }

    /// Reconfigure pacing for every wallet in this repository, or turn it off
    /// with `None`.
    ///
    /// Pacing is a repository-wide property because one limiter is shared, so
    /// there is deliberately no per-wallet equivalent at creation time: it would
    /// silently reconfigure sibling wallets.
    pub fn set_rate_limiting_config(&self, config: Option<RateLimitConfig>) {
        match config {
            Some(config) => self.rate_limiter.set_config(config),
            None => self.rate_limiter.set_enabled(false),
        }
    }

    /// Whether this repository is pacing requests right now.
    ///
    /// Individual wallets can still report false while this is true: a proxied
    /// or Tor wallet is built with a custom client, which leaves its limiter
    /// wired to nothing.
    pub fn is_rate_limited(&self) -> bool {
        self.rate_limiter.is_enabled()
    }

    /// Remove a wallet from the in-memory repository
    ///
    /// This only removes the wallet from the in-memory map. It does not remove
    /// the mint from the database. Use the database directly if you need to
    /// explicitly remove persisted mint data.
    ///
    /// The origin's shared rate-limit bucket stays in the
    /// [`RateLimiterManager`] while any handle is live or its budget is still
    /// recovering, so re-adding a wallet for the same origin inherits the same
    /// live budget rather than starting full and bursting again. Once no wallet
    /// holds it and its budget has fully recovered, a later wallet creation
    /// evicts it; the persisted budget still survives a re-add.
    #[instrument(skip(self))]
    pub async fn remove_wallet(
        &self,
        mint_url: MintUrl,
        currency_unit: CurrencyUnit,
    ) -> Result<(), Error> {
        let key = WalletKey::new(mint_url, currency_unit);
        let mut wallets = self.wallets.write().await;

        if !wallets.contains_key(&key) {
            return Err(Error::UnknownWallet(key));
        }

        wallets.remove(&key);
        Ok(())
    }

    /// Get all wallets
    #[instrument(skip(self))]
    pub async fn get_wallets(&self) -> Vec<Wallet> {
        self.wallets.read().await.values().cloned().collect()
    }

    /// Check if any wallet exists for a mint (regardless of currency unit)
    #[instrument(skip(self))]
    pub async fn has_mint(&self, mint_url: &MintUrl) -> bool {
        self.wallets
            .read()
            .await
            .keys()
            .any(|key| &key.mint_url == mint_url)
    }
    /// Get balances for all wallets
    ///
    /// Returns a map of (mint URL, currency unit) to balance for each wallet in the repository.
    #[instrument(skip(self))]
    pub async fn get_balances(&self) -> Result<BTreeMap<WalletKey, cdk_common::Amount>, Error> {
        let wallets = self.wallets.read().await;
        let mut balances = BTreeMap::new();

        for (key, wallet) in wallets.iter() {
            let balance = wallet.total_balance().await?;
            balances.insert(key.clone(), balance);
        }

        Ok(balances)
    }
    /// Get total balance across all wallets, grouped by currency unit
    ///
    /// Returns a map of currency unit to total balance for that unit across all mints.
    #[instrument(skip(self))]
    pub async fn total_balance(&self) -> Result<BTreeMap<CurrencyUnit, cdk_common::Amount>, Error> {
        let balances = self.get_balances().await?;
        let mut by_unit: BTreeMap<CurrencyUnit, cdk_common::Amount> = BTreeMap::new();
        for (key, amount) in balances {
            let entry = by_unit.entry(key.unit).or_insert(cdk_common::Amount::ZERO);
            *entry += amount;
        }
        Ok(by_unit)
    }

    /// Fetch mint info from a mint URL
    ///
    /// Creates a temporary HTTP client to fetch the mint info.
    /// This is useful to discover supported currency units before adding a mint.
    pub async fn fetch_mint_info(
        &self,
        mint_url: &MintUrl,
    ) -> Result<crate::nuts::MintInfo, Error> {
        // Create an HTTP client based on the repository configuration
        let client: Arc<dyn MintConnector + Send + Sync> =
            if let Some(proxy_url) = &self.proxy_config {
                Arc::new(proxy_http_client(
                    mint_url.clone(),
                    proxy_url,
                    self.danger_accept_invalid_certs,
                )?)
            } else {
                #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
                if let Some(tor) = &self.shared_tor_transport {
                    let transport = tor.clone();
                    Arc::new(crate::wallet::TorHttpClient::with_transport(
                        mint_url.clone(),
                        transport,
                        None,
                    ))
                } else {
                    Arc::new(crate::wallet::HttpClient::new(mint_url.clone(), None))
                }

                #[cfg(not(all(feature = "tor", not(target_arch = "wasm32"))))]
                {
                    Arc::new(crate::wallet::HttpClient::new(mint_url.clone(), None))
                }
            };

        client.get_mint_info().await
    }

    /// Internal: Create wallet with optional custom configuration
    ///
    /// Priority order for configuration:
    /// 1. Custom connector from config (if provided)
    /// 2. Global settings (proxy/Tor)
    /// 3. Default HttpClient
    async fn create_wallet_internal(
        &self,
        mint_url: MintUrl,
        unit: CurrencyUnit,
        config: Option<&WalletConfig>,
    ) -> Result<Wallet, Error> {
        let target_proof_count = config.and_then(|c| c.target_proof_count).unwrap_or(3);
        let metadata_cache_ttl = config.and_then(|c| c.metadata_cache_ttl);
        let configured_auth_connector = config.and_then(|c| c.auth_connector.clone());

        // Check if custom connector is provided in config
        if let Some(cfg) = config {
            if let Some(custom_connector) = &cfg.mint_connector {
                // Use custom connector with WalletBuilder
                let mut builder = WalletBuilder::new()
                    .mint_url(mint_url.clone())
                    .unit(unit.clone())
                    .localstore(self.localstore.clone())
                    .seed(self.seed)
                    .target_proof_count(target_proof_count)
                    .with_rate_limiter(self.rate_limiter.clone())
                    .shared_client(custom_connector.clone());

                if let Some(auth_connector) = configured_auth_connector.clone() {
                    builder = builder.auth_connector(auth_connector);
                }

                if let Some(ttl) = metadata_cache_ttl {
                    builder = builder.set_metadata_cache_ttl(Some(ttl));
                }

                return builder.build();
            }
        }

        // Fall back to existing logic: proxy/Tor/default
        let wallet = if let Some(proxy_url) = &self.proxy_config {
            // Create wallet with proxy-configured client
            let client = proxy_http_client(
                mint_url.clone(),
                proxy_url,
                self.danger_accept_invalid_certs,
            )?;
            let auth_connector = match configured_auth_connector.clone() {
                Some(auth_connector) => auth_connector,
                None => Arc::new(proxy_auth_http_client(
                    mint_url.clone(),
                    proxy_url,
                    self.danger_accept_invalid_certs,
                )?) as Arc<dyn AuthMintConnector + Send + Sync>,
            };
            let mut builder = WalletBuilder::new()
                .mint_url(mint_url.clone())
                .unit(unit.clone())
                .localstore(self.localstore.clone())
                .seed(self.seed)
                .target_proof_count(target_proof_count)
                .with_rate_limiter(self.rate_limiter.clone())
                .client(client)
                .auth_connector(auth_connector);

            if let Some(ttl) = metadata_cache_ttl {
                builder = builder.set_metadata_cache_ttl(Some(ttl));
            }

            builder.build()?
        } else {
            #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
            if let Some(tor) = &self.shared_tor_transport {
                // Create wallet with Tor transport client, cloning the shared transport
                let client = crate::wallet::TorHttpClient::with_transport(
                    mint_url.clone(),
                    tor.clone(),
                    None,
                );
                let auth_connector = configured_auth_connector.clone().unwrap_or_else(|| {
                    Arc::new(crate::wallet::TorAuthHttpClient::with_transport(
                        mint_url.clone(),
                        tor.clone(),
                        None,
                    )) as Arc<dyn AuthMintConnector + Send + Sync>
                });

                let mut builder = WalletBuilder::new()
                    .mint_url(mint_url.clone())
                    .unit(unit.clone())
                    .localstore(self.localstore.clone())
                    .seed(self.seed)
                    .target_proof_count(target_proof_count)
                    .with_rate_limiter(self.rate_limiter.clone())
                    .client(client)
                    .auth_connector(auth_connector);

                if let Some(ttl) = metadata_cache_ttl {
                    builder = builder.set_metadata_cache_ttl(Some(ttl));
                }

                builder.build()?
            } else {
                // Create wallet with default client
                let mut builder = WalletBuilder::new()
                    .mint_url(mint_url.clone())
                    .unit(unit.clone())
                    .localstore(self.localstore.clone())
                    .seed(self.seed)
                    .target_proof_count(target_proof_count)
                    .with_rate_limiter(self.rate_limiter.clone());

                if let Some(auth_connector) = configured_auth_connector.clone() {
                    builder = builder.auth_connector(auth_connector);
                }

                if let Some(ttl) = metadata_cache_ttl {
                    builder = builder.set_metadata_cache_ttl(Some(ttl));
                }

                builder.build()?
            }

            #[cfg(not(all(feature = "tor", not(target_arch = "wasm32"))))]
            {
                // Create wallet with default client
                let mut builder = WalletBuilder::new()
                    .mint_url(mint_url.clone())
                    .unit(unit.clone())
                    .localstore(self.localstore.clone())
                    .seed(self.seed)
                    .target_proof_count(target_proof_count)
                    .with_rate_limiter(self.rate_limiter.clone());

                if let Some(auth_connector) = configured_auth_connector.clone() {
                    builder = builder.auth_connector(auth_connector);
                }

                if let Some(ttl) = metadata_cache_ttl {
                    builder = builder.set_metadata_cache_ttl(Some(ttl));
                }

                builder.build()?
            }
        };

        Ok(wallet)
    }

    /// Load all wallets from database
    ///
    /// This loads wallets for all mints stored in the database. For each mint,
    /// it uses the persisted mint info to discover supported units and creates
    /// a wallet for each supported unit. This does not make network requests.
    #[instrument(skip(self))]
    async fn load_wallets(&self) -> Result<(), Error> {
        let mints = self.localstore.get_mints().await.map_err(Error::Database)?;

        for (mint_url, mint_info) in mints {
            let units = mint_info
                .map(|info| {
                    let supported_units = info.supported_units();
                    if supported_units.is_empty() {
                        vec![CurrencyUnit::Sat]
                    } else {
                        supported_units.into_iter().cloned().collect()
                    }
                })
                // Older databases may not have mint metadata. Keep the
                // established single-sat wallet behavior for those records.
                .unwrap_or_else(|| vec![CurrencyUnit::Sat]);

            for unit in units {
                self.get_or_create_wallet(mint_url.clone(), unit, None)
                    .await?;
            }
        }

        Ok(())
    }

    /// Get the currently active NpubCash mint URL
    ///
    /// Returns the mint URL that has been set as active for NpubCash operations,
    /// or None if no active mint has been configured.
    #[cfg(feature = "npubcash")]
    pub async fn get_active_npubcash_mint(&self) -> Result<Option<MintUrl>, Error> {
        use super::npubcash::{ACTIVE_MINT_KEY, NPUBCASH_KV_NAMESPACE};
        let value = self
            .localstore
            .kv_read(NPUBCASH_KV_NAMESPACE, "", ACTIVE_MINT_KEY)
            .await?;
        match value {
            Some(bytes) => {
                let s = String::from_utf8(bytes)
                    .map_err(|_| Error::Custom("Invalid active mint URL".into()))?;
                Ok(Some(MintUrl::from_str(&s)?))
            }
            None => Ok(None),
        }
    }

    /// Set the active NpubCash mint URL
    ///
    /// This sets the mint that will be used for NpubCash operations.
    #[cfg(feature = "npubcash")]
    pub async fn set_active_npubcash_mint(&self, mint_url: MintUrl) -> Result<(), Error> {
        use super::npubcash::{ACTIVE_MINT_KEY, NPUBCASH_KV_NAMESPACE};
        self.localstore
            .kv_write(
                NPUBCASH_KV_NAMESPACE,
                "",
                ACTIVE_MINT_KEY,
                mint_url.to_string().as_bytes(),
            )
            .await?;
        Ok(())
    }

    /// Sync NpubCash quotes from the active mint
    ///
    /// Retrieves pending mint quotes from the currently active NpubCash mint.
    /// Returns an error if no active mint has been configured.
    /// Uses Sat as the default unit for NpubCash operations.
    #[cfg(feature = "npubcash")]
    pub async fn sync_npubcash_quotes(
        &self,
    ) -> Result<Vec<crate::wallet::types::MintQuote>, Error> {
        let active_mint = self.get_active_npubcash_mint().await?;
        if let Some(mint_url) = active_mint {
            // NpubCash typically uses Sat, try to find a Sat wallet first
            let wallet = self.get_wallet(&mint_url, &CurrencyUnit::Sat).await?;
            wallet.sync_npubcash_quotes().await
        } else {
            Err(Error::Custom("No active NpubCash mint set".into()))
        }
    }

    // =========================================================================
    // Helper functions for token and proof operations
    // =========================================================================

    /// Get token data (mint URL and proofs) from a token
    ///
    /// This method extracts the mint URL and proofs from a token. It will automatically
    /// fetch the keysets from the mint if needed to properly decode the proofs.
    ///
    /// The mint must already be added to the wallet. If the mint is not in the wallet,
    /// use `add_mint` first or set `allow_untrusted` in receive options.
    ///
    /// # Arguments
    ///
    /// * `token` - The token to extract data from
    ///
    /// # Returns
    ///
    /// A `TokenData` struct containing the mint URL and proofs
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use cdk::wallet::WalletRepository;
    /// # use cdk::nuts::Token;
    /// # use std::str::FromStr;
    /// # async fn example(wallet: &WalletRepository) -> Result<(), Box<dyn std::error::Error>> {
    /// let token = Token::from_str("cashuA...")?;
    /// let token_data = wallet.get_token_data(&token).await?;
    /// println!("Mint: {}", token_data.mint_url);
    /// println!("Proofs: {} total", token_data.proofs.len());
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, token))]
    pub async fn get_token_data(
        &self,
        token: &crate::nuts::nut00::Token,
    ) -> Result<TokenData, Error> {
        let mint_url = token.mint_url()?;
        let unit = token.unit().unwrap_or_default();

        // Get the keysets for this mint using the token's unit
        let wallet = self.get_wallet(&mint_url, &unit).await?;
        let proofs = wallet.token_proofs(token).await?;

        // Get the memo
        let memo = token.memo().clone();
        let redeem_fee = wallet.get_proofs_fee(&proofs).await?;

        Ok(TokenData {
            value: cdk_common::nuts::nut00::ProofsMethods::total_amount(&proofs)?,
            mint_url,
            proofs,
            memo,
            unit,
            redeem_fee: Some(redeem_fee.total),
        })
    }

    /// List proofs for all wallets
    ///
    /// Returns a map of (mint URL, currency unit) to proofs for each wallet in the repository.
    #[instrument(skip(self))]
    pub async fn list_proofs(
        &self,
    ) -> Result<std::collections::BTreeMap<WalletKey, Vec<cdk_common::Proof>>, Error> {
        let mut mint_proofs = std::collections::BTreeMap::new();

        for (key, wallet) in self.wallets.read().await.iter() {
            let wallet_proofs = wallet.get_unspent_proofs().await?;
            mint_proofs.insert(key.clone(), wallet_proofs);
        }
        Ok(mint_proofs)
    }

    /// List transactions across all wallets
    #[instrument(skip(self))]
    pub async fn list_transactions(
        &self,
        direction: Option<cdk_common::wallet::TransactionDirection>,
    ) -> Result<Vec<cdk_common::wallet::Transaction>, Error> {
        let mut transactions = Vec::new();

        for wallet in self.wallets.read().await.values() {
            let wallet_transactions = wallet.list_transactions(direction).await?;
            transactions.extend(wallet_transactions);
        }

        transactions.sort();

        Ok(transactions)
    }

    /// Check all pending mint quotes and mint any that are paid
    #[instrument(skip(self))]
    pub async fn check_all_mint_quotes(
        &self,
        mint_url: Option<MintUrl>,
    ) -> Result<cdk_common::Amount, Error> {
        let mut total_minted = cdk_common::Amount::ZERO;

        let wallets = self.wallets.read().await;
        let wallets_to_check: Vec<_> = match &mint_url {
            Some(url) => {
                // Get all wallets for this mint (any currency unit)
                let filtered: Vec<_> = wallets
                    .iter()
                    .filter(|(key, _)| &key.mint_url == url)
                    .map(|(_, wallet)| wallet.clone())
                    .collect();

                if filtered.is_empty() {
                    return Err(Error::UnknownMint {
                        mint_url: url.to_string(),
                    });
                }
                filtered
            }
            None => wallets.values().cloned().collect(),
        };
        drop(wallets);

        for wallet in wallets_to_check {
            let minted = wallet.mint_unissued_quotes().await?;
            total_minted += minted;
        }

        Ok(total_minted)
    }
}

impl Drop for WalletRepository {
    fn drop(&mut self) {
        self.seed.zeroize();
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    use cdk_common::database::WalletDatabase;
    use cdk_common::nut00::KnownMethod;
    use cdk_common::nuts::{MintInfo, MintMethodSettings};
    use tokio::net::TcpListener;

    use super::*;
    use crate::nuts::{NUT04Settings, Nuts, PaymentMethod};

    async fn create_test_repository() -> WalletRepository {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let seed = [0u8; 64];
        WalletRepositoryBuilder::new()
            .localstore(localstore)
            .seed(seed)
            .build()
            .await
            .expect("Failed to create WalletRepository")
    }

    async fn create_test_repository_with_proxy(proxy_url: url::Url) -> WalletRepository {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let seed = [0u8; 64];
        WalletRepositoryBuilder::new()
            .localstore(localstore)
            .seed(seed)
            .proxy_url(proxy_url)
            .build()
            .await
            .expect("Failed to create WalletRepository")
    }

    async fn local_mint_url_with_connection_counter(
    ) -> (MintUrl, Arc<AtomicUsize>, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("Failed to bind test mint listener");
        let address = listener
            .local_addr()
            .expect("Failed to get test mint listener address");
        let direct_connections = Arc::new(AtomicUsize::new(0));
        let connection_count = Arc::clone(&direct_connections);
        let handle = tokio::spawn(async move {
            while let Ok((_stream, _address)) = listener.accept().await {
                connection_count.fetch_add(1, Ordering::SeqCst);
            }
        });

        (
            format!("http://{address}")
                .parse()
                .expect("Failed to parse test mint URL"),
            direct_connections,
            handle,
        )
    }

    fn unsupported_proxy_url() -> url::Url {
        "gopher://127.0.0.1:1080"
            .parse()
            .expect("Failed to parse proxy URL")
    }

    fn mint_info_with_units(units: Vec<CurrencyUnit>) -> MintInfo {
        MintInfo::new().nuts(
            Nuts::new().nut04(NUT04Settings::new(
                units
                    .into_iter()
                    .map(|unit| MintMethodSettings {
                        method: PaymentMethod::Known(KnownMethod::Bolt11),
                        unit,
                        method_name: None,
                        min_amount: None,
                        max_amount: None,
                        options: None,
                    })
                    .collect(),
                false,
            )),
        )
    }

    #[test]
    fn builder_verifies_proxy_tls_certificates_by_default() {
        let builder = WalletRepositoryBuilder::new();

        assert!(!builder.danger_accept_invalid_certs);
    }

    #[test]
    fn builder_can_explicitly_accept_invalid_proxy_tls_certificates() {
        let builder = WalletRepositoryBuilder::new().danger_accept_invalid_certs(true);

        assert!(builder.danger_accept_invalid_certs);
    }

    #[tokio::test]
    async fn test_wallet_repository_creation() {
        let repo = create_test_repository().await;
        assert!(repo.wallets.try_read().is_ok());
    }

    #[tokio::test]
    async fn test_load_wallets_uses_persisted_metadata_without_network() {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let (mint_url, direct_connections, listener_handle) =
            local_mint_url_with_connection_counter().await;
        localstore
            .add_mint(
                mint_url.clone(),
                Some(mint_info_with_units(vec![
                    CurrencyUnit::Sat,
                    CurrencyUnit::Usd,
                ])),
            )
            .await
            .expect("Failed to add mint metadata");

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            WalletRepositoryBuilder::new()
                .localstore(localstore)
                .seed([0u8; 64])
                .build(),
        )
        .await;
        listener_handle.abort();

        let repo = result
            .expect("Repository startup should not wait for a mint request")
            .expect("Repository startup should succeed");

        assert_eq!(direct_connections.load(Ordering::SeqCst), 0);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Usd).await);
    }

    #[tokio::test]
    async fn test_load_wallets_falls_back_to_sat_without_persisted_metadata() {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let (mint_url, direct_connections, listener_handle) =
            local_mint_url_with_connection_counter().await;
        localstore
            .add_mint(mint_url.clone(), None)
            .await
            .expect("Failed to add legacy mint");

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            WalletRepositoryBuilder::new()
                .localstore(localstore)
                .seed([0u8; 64])
                .build(),
        )
        .await;
        listener_handle.abort();

        let repo = result
            .expect("Repository startup should not wait for a mint request")
            .expect("Repository startup should succeed");

        assert_eq!(direct_connections.load(Ordering::SeqCst), 0);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
    }

    #[tokio::test]
    async fn test_has_mint_empty() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();
        assert!(!repo.has_mint(&mint_url).await);
    }

    #[tokio::test]
    async fn test_create_and_get_wallet() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        // Create a wallet
        let wallet = repo
            .create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet");

        assert_eq!(wallet.mint_url, mint_url);
        assert_eq!(wallet.unit, CurrencyUnit::Sat);

        // Verify we can get it back
        assert!(repo.has_mint(&mint_url).await);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
        let retrieved = repo.get_wallet(&mint_url, &CurrencyUnit::Sat).await;
        assert!(retrieved.is_ok());
    }

    #[tokio::test]
    async fn test_get_or_create_wallet_keeps_the_existing_wallet() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        repo.create_wallet(
            mint_url.clone(),
            CurrencyUnit::Sat,
            Some(WalletConfig::new().with_target_proof_count(5)),
        )
        .await
        .expect("Failed to create wallet");

        let wallet = repo
            .get_or_create_wallet(
                mint_url.clone(),
                CurrencyUnit::Sat,
                Some(WalletConfig::new().with_target_proof_count(99)),
            )
            .await
            .expect("Failed to get wallet");

        assert_eq!(wallet.target_proof_count, 5);
    }

    #[tokio::test]
    async fn test_get_or_create_wallet_creates_a_missing_wallet() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        let wallet = repo
            .get_or_create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet");

        assert_eq!(wallet.mint_url, mint_url);
        assert_eq!(wallet.unit, CurrencyUnit::Sat);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
    }

    #[tokio::test]
    async fn test_fetch_mint_info_returns_error_when_proxy_setup_fails() {
        let repo = create_test_repository_with_proxy(unsupported_proxy_url()).await;
        let (mint_url, direct_connections, listener_handle) =
            local_mint_url_with_connection_counter().await;

        let result = repo.fetch_mint_info(&mint_url).await;

        listener_handle.abort();
        assert!(result.is_err());
        assert_eq!(direct_connections.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn test_create_wallet_returns_error_when_proxy_setup_fails() {
        let repo = create_test_repository_with_proxy(unsupported_proxy_url()).await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        let result = repo
            .create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await;

        assert!(result.is_err());
        assert!(!repo.has_mint(&mint_url).await);
        assert!(!repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
    }

    #[tokio::test]
    async fn test_remove_wallet() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        // Create and then remove
        repo.create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet");

        assert!(repo.has_mint(&mint_url).await);
        assert!(repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
        let _ = repo
            .remove_wallet(mint_url.clone(), CurrencyUnit::Sat)
            .await;
        assert!(!repo.has_mint(&mint_url).await);
        assert!(!repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);
    }

    #[tokio::test]
    async fn test_get_wallets() {
        let repo = create_test_repository().await;

        let mint1: MintUrl = "https://mint1.example.com".parse().unwrap();
        let mint2: MintUrl = "https://mint2.example.com".parse().unwrap();

        repo.create_wallet(mint1, CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet 1");
        repo.create_wallet(mint2, CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet 2");

        let wallets = repo.get_wallets().await;
        assert_eq!(wallets.len(), 2);
    }

    #[tokio::test]
    async fn test_remove_wallet_does_not_touch_db() {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let seed = [0u8; 64];
        let repo = WalletRepositoryBuilder::new()
            .localstore(localstore.clone())
            .seed(seed)
            .build()
            .await
            .expect("Failed to create WalletRepository");

        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        // Add mint to DB manually to simulate existing state
        localstore.add_mint(mint_url.clone(), None).await.unwrap();

        // Create wallet in repo
        repo.create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("Failed to create wallet");

        // Remove wallet from in-memory repo
        repo.remove_wallet(mint_url.clone(), CurrencyUnit::Sat)
            .await
            .expect("Failed to remove wallet");

        // Verify wallet is gone from in-memory repo
        assert!(!repo.has_wallet(&mint_url, &CurrencyUnit::Sat).await);

        // Verify mint is still in DB (remove_wallet does not touch DB)
        assert!(localstore
            .get_mint(mint_url.clone())
            .await
            .unwrap()
            .is_some());
    }

    // The default rate-limit config admits exactly `capacity` (20) immediate
    // `try_acquire`s before pacing kicks in, and its burst tolerance (~57s) far
    // exceeds test wall-clock, so no slot is earned back mid-test.
    const DEFAULT_BURST: usize = 20;

    /// Resolve the bucket a wallet's requests to `url` would draw from.
    fn bucket_for(wallet: &Wallet, url: &str) -> crate::wallet::TokenBucket {
        wallet
            .rate_limiter
            .clone()
            .expect("default path retains its limiter")
            .bucket_for(&url::Url::parse(url).expect("valid url"))
    }

    #[tokio::test]
    async fn wallets_for_same_mint_share_one_rate_limit_budget() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        let sat = repo
            .create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("failed to create sat wallet");
        let usd = repo
            .create_wallet(mint_url.clone(), CurrencyUnit::Usd, None)
            .await
            .expect("failed to create usd wallet");

        let sat_bucket = bucket_for(&sat, "https://mint.example.com/v1/mint");
        let usd_bucket = bucket_for(&usd, "https://mint.example.com/v1/melt");

        // Interleave across the two handles: sharing one budget means the two
        // together drain a single burst, not one each.
        let mut admitted = 0;
        for _ in 0..DEFAULT_BURST {
            if sat_bucket.try_acquire().await {
                admitted += 1;
            }
            if usd_bucket.try_acquire().await {
                admitted += 1;
            }
        }
        assert_eq!(
            admitted, DEFAULT_BURST,
            "combined burst is one capacity, not two"
        );
        assert!(
            !sat_bucket.try_acquire().await,
            "shared budget already spent"
        );
        assert!(
            !usd_bucket.try_acquire().await,
            "shared budget already spent"
        );
    }

    #[tokio::test]
    async fn wallets_for_different_mints_have_independent_budgets() {
        let repo = create_test_repository().await;
        let mint_a: MintUrl = "https://mint-a.example.com".parse().unwrap();
        let mint_b: MintUrl = "https://mint-b.example.com".parse().unwrap();

        let wallet_a = repo
            .create_wallet(mint_a, CurrencyUnit::Sat, None)
            .await
            .expect("failed to create wallet a");
        let wallet_b = repo
            .create_wallet(mint_b, CurrencyUnit::Sat, None)
            .await
            .expect("failed to create wallet b");
        let bucket_a = bucket_for(&wallet_a, "https://mint-a.example.com/v1/info");
        let bucket_b = bucket_for(&wallet_b, "https://mint-b.example.com/v1/info");

        for _ in 0..DEFAULT_BURST {
            assert!(bucket_a.try_acquire().await);
        }
        assert!(
            !bucket_a.try_acquire().await,
            "mint A's own burst is drained"
        );
        assert!(
            bucket_b.try_acquire().await,
            "mint B has an untouched budget"
        );
    }

    #[tokio::test]
    async fn third_party_hosts_pace_against_their_own_budget() {
        // A wallet's transport also carries LNURL and OIDC traffic. That must
        // neither spend the mint's budget nor be paced by it, and two wallets at
        // different mints hitting one service must share that service's budget.
        let repo = create_test_repository().await;
        let wallet_a = repo
            .create_wallet(
                "https://mint-a.example.com".parse().unwrap(),
                CurrencyUnit::Sat,
                None,
            )
            .await
            .expect("failed to create wallet a");
        let wallet_b = repo
            .create_wallet(
                "https://mint-b.example.com".parse().unwrap(),
                CurrencyUnit::Sat,
                None,
            )
            .await
            .expect("failed to create wallet b");

        let mint_bucket = bucket_for(&wallet_a, "https://mint-a.example.com/v1/info");
        let lnurl = "https://pay.example.org/.well-known/lnurlp/alice";
        let lnurl_bucket = bucket_for(&wallet_a, lnurl);

        // Spending the mint's whole burst leaves the LNURL host untouched.
        for _ in 0..DEFAULT_BURST {
            assert!(mint_bucket.try_acquire().await);
        }
        assert!(!mint_bucket.try_acquire().await);
        assert!(
            lnurl_bucket.try_acquire().await,
            "the LNURL host keeps its own budget"
        );

        // Wallet B, a different mint entirely, draws from the same LNURL budget.
        for _ in 0..(DEFAULT_BURST - 1) {
            assert!(bucket_for(&wallet_b, lnurl).try_acquire().await);
        }
        assert!(
            !bucket_for(&wallet_b, lnurl).try_acquire().await,
            "the LNURL host's budget is shared across mints"
        );
    }

    /// Awaiting the barrier is what makes the handover deterministic: without
    /// it the rebuild races the detached writer. Capacity 2 and emission ~200ms
    /// keep the pace signal clear of scheduler noise.
    #[tokio::test]
    async fn flushing_a_wallet_hands_its_budget_to_the_rebuilt_one() {
        let cfg = RateLimitConfig::try_new(2, 300).expect("non-zero");
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();
        let mint_endpoint = "https://mint.example.com/v1/mint";

        let repo = WalletRepositoryBuilder::new()
            .localstore(localstore.clone())
            .seed([0u8; 64])
            .build()
            .await
            .expect("Failed to create WalletRepository");
        let wallet = repo
            .create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("failed to create wallet");
        wallet.set_rate_limiting_config(cfg);

        let bucket = bucket_for(&wallet, mint_endpoint);
        bucket.acquire(async {}).await;
        bucket.acquire(async {}).await;
        wallet.flush_rate_limits().await;
        drop((bucket, wallet, repo));

        let rebuilt_repo = WalletRepositoryBuilder::new()
            .localstore(localstore)
            .seed([0u8; 64])
            .build()
            .await
            .expect("Failed to rebuild WalletRepository");
        let rebuilt = rebuilt_repo
            .get_or_create_wallet(mint_url, CurrencyUnit::Sat, None)
            .await
            .expect("failed to rebuild wallet");
        rebuilt.set_rate_limiting_config(cfg);

        let rebuilt_bucket = bucket_for(&rebuilt, mint_endpoint);
        let start = Instant::now();
        rebuilt_bucket.acquire(async {}).await;
        rebuilt_bucket.acquire(async {}).await;
        assert!(
            start.elapsed() >= Duration::from_millis(150),
            "rebuilt wallet should inherit the flushed budget, took {:?}",
            start.elapsed()
        );

        let untouched = bucket_for(&rebuilt, "https://other.example.com/v1/info");
        let start = Instant::now();
        untouched.acquire(async {}).await;
        untouched.acquire(async {}).await;
        assert!(
            start.elapsed() < Duration::from_millis(100),
            "an origin the flushed wallet never touched still bursts"
        );
    }

    /// A wallet built with a custom client keeps no limiter, and a fresh
    /// repository has no origins, so the barrier has nothing to wait for and
    /// must still return.
    #[tokio::test]
    async fn flush_rate_limits_is_a_no_op_without_a_limiter() {
        use crate::wallet::test_utils::MockMintConnector;

        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let unlimited = crate::wallet::WalletBuilder::default()
            .mint_url("https://mint.example.com".parse().unwrap())
            .unit(CurrencyUnit::Sat)
            .localstore(localstore)
            .seed([0u8; 64])
            .shared_client(Arc::new(MockMintConnector::new()))
            .build()
            .expect("failed to build wallet");

        assert!(unlimited.rate_limiter.is_none());
        unlimited.flush_rate_limits().await;
        create_test_repository().await.flush_rate_limits().await;
    }

    async fn repository_with_rate_limit(rate_limit: Option<RateLimitConfig>) -> WalletRepository {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("Failed to create in-memory database"),
        );
        let builder = WalletRepositoryBuilder::new()
            .localstore(localstore)
            .seed([0u8; 64]);
        let builder = match rate_limit {
            Some(config) => builder.with_rate_limiting_config(config),
            None => builder.with_rate_limiting_disabled(),
        };
        builder
            .build()
            .await
            .expect("Failed to create WalletRepository")
    }

    #[tokio::test]
    async fn repository_starts_with_the_configured_rate_limit() {
        assert!(create_test_repository().await.is_rate_limited());
        assert!(repository_with_rate_limit(RateLimitConfig::try_new(5, 30))
            .await
            .is_rate_limited());
        assert!(!repository_with_rate_limit(None).await.is_rate_limited());
    }

    #[tokio::test]
    async fn repository_rate_limit_reaches_wallets_it_already_handed_out() {
        let repo = repository_with_rate_limit(None).await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();
        let wallet = repo
            .get_or_create_wallet(mint_url, CurrencyUnit::Sat, None)
            .await
            .expect("wallet should be created");
        assert!(!wallet.is_rate_limited());

        repo.set_rate_limiting_config(Some(RateLimitConfig::default()));
        assert!(repo.is_rate_limited());
        assert!(
            wallet.is_rate_limited(),
            "the wallet shares the repository's limiter"
        );

        repo.set_rate_limiting_config(None);
        assert!(!wallet.is_rate_limited());
    }

    #[tokio::test]
    async fn a_disabled_repository_admits_more_than_one_burst() {
        let repo = repository_with_rate_limit(None).await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();
        let wallet = repo
            .get_or_create_wallet(mint_url, CurrencyUnit::Sat, None)
            .await
            .expect("wallet should be created");

        let bucket = bucket_for(&wallet, "https://mint.example.com/v1/info");
        for _ in 0..(DEFAULT_BURST + 5) {
            assert!(bucket.try_acquire().await, "pacing is off");
        }
    }

    #[tokio::test]
    async fn get_or_create_wallet_second_unit_shares_the_budget() {
        let repo = create_test_repository().await;
        let mint_url: MintUrl = "https://mint.example.com".parse().unwrap();

        let sat = repo
            .get_or_create_wallet(mint_url.clone(), CurrencyUnit::Sat, None)
            .await
            .expect("failed to create sat wallet");
        let usd = repo
            .get_or_create_wallet(mint_url.clone(), CurrencyUnit::Usd, None)
            .await
            .expect("failed to create usd wallet");

        let sat_bucket = bucket_for(&sat, "https://mint.example.com/v1/mint");
        let usd_bucket = bucket_for(&usd, "https://mint.example.com/v1/melt");

        // Drain the whole burst through the Sat handle; the Usd handle sees an
        // already-spent budget because they share one bucket.
        for _ in 0..DEFAULT_BURST {
            assert!(sat_bucket.try_acquire().await);
        }
        assert!(
            !usd_bucket.try_acquire().await,
            "shared budget already spent"
        );
    }
}