cdk 0.16.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
//! HTTP Mint client with pluggable transport
use std::collections::HashSet;
use std::sync::{Arc, RwLock as StdRwLock};

use async_trait::async_trait;
use cdk_common::{
    nut19, MeltQuoteBolt11Response, MeltQuoteRequest, MeltQuoteResponse, Method,
    MintQuoteBolt11Response, MintQuoteBolt12Response, MintQuoteCustomResponse, MintQuoteRequest,
    MintQuoteResponse, ProtectedEndpoint, RoutePath,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::sync::RwLock;
use tracing::instrument;
use url::Url;
use web_time::{Duration, Instant};

use super::transport::Transport;
use super::{Error, MintConnector};
use crate::mint_url::MintUrl;
use crate::nuts::nut00::{KnownMethod, PaymentMethod};
use crate::nuts::nut22::MintAuthRequest;
use crate::nuts::{
    AuthToken, BatchCheckMintQuoteRequest, BatchMintRequest, CheckStateRequest, CheckStateResponse,
    Id, KeySet, KeysResponse, KeysetResponse, MeltRequest, MintInfo, MintRequest, MintResponse,
    RestoreRequest, RestoreResponse, SwapRequest, SwapResponse,
};
use crate::wallet::auth::{AuthMintConnector, AuthWallet};

type Cache = (u64, HashSet<(nut19::Method, nut19::Path)>);

/// Http Client
#[derive(Debug, Clone)]
pub struct HttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    transport: Arc<T>,
    mint_url: MintUrl,
    cache_support: Arc<StdRwLock<Cache>>,
    auth_wallet: Arc<RwLock<Option<AuthWallet>>>,
}

impl<T> HttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    /// Create new [`HttpClient`] with a provided transport implementation.
    pub fn with_transport(
        mint_url: MintUrl,
        transport: T,
        auth_wallet: Option<AuthWallet>,
    ) -> Self {
        Self {
            transport: transport.into(),
            mint_url,
            auth_wallet: Arc::new(RwLock::new(auth_wallet)),
            cache_support: Default::default(),
        }
    }

    /// Create new [`HttpClient`]
    pub fn new(mint_url: MintUrl, auth_wallet: Option<AuthWallet>) -> Self {
        Self {
            transport: T::default().into(),
            mint_url,
            auth_wallet: Arc::new(RwLock::new(auth_wallet)),
            cache_support: Default::default(),
        }
    }

    /// Get auth token for a protected endpoint
    #[instrument(skip(self))]
    pub async fn get_auth_token(
        &self,
        method: Method,
        path: RoutePath,
    ) -> Result<Option<AuthToken>, Error> {
        let auth_wallet = self.auth_wallet.read().await;
        match auth_wallet.as_ref() {
            Some(auth_wallet) => {
                let endpoint = ProtectedEndpoint::new(method, path);
                auth_wallet.get_auth_for_request(&endpoint).await
            }
            None => Ok(None),
        }
    }

    /// Create new [`HttpClient`] with a proxy for specific TLDs.
    /// Specifying `None` for `host_matcher` will use the proxy for all
    /// requests.
    pub fn with_proxy(
        mint_url: MintUrl,
        proxy: Url,
        host_matcher: Option<&str>,
        accept_invalid_certs: bool,
    ) -> Result<Self, Error> {
        let mut transport = T::default();
        transport.with_proxy(proxy, host_matcher, accept_invalid_certs)?;

        Ok(Self {
            transport: transport.into(),
            mint_url,
            auth_wallet: Arc::new(RwLock::new(None)),
            cache_support: Default::default(),
        })
    }

    /// Generic implementation of a retriable http request
    ///
    /// The retry only happens if the mint supports replay through the Caching of NUT-19.
    #[inline(always)]
    async fn retriable_http_request<P, R>(
        &self,
        method: nut19::Method,
        path: nut19::Path,
        auth_token: Option<AuthToken>,
        payload: &P,
    ) -> Result<R, Error>
    where
        P: Serialize + ?Sized + Send + Sync,
        R: DeserializeOwned,
    {
        let started = Instant::now();

        let retriable_window = self
            .cache_support
            .read()
            .map(|cache_support| {
                cache_support
                    .1
                    .get(&(method, path.clone()))
                    .map(|_| cache_support.0)
            })
            .unwrap_or_default()
            .map(Duration::from_secs)
            .unwrap_or_default();

        let transport = self.transport.clone();
        loop {
            let url = match &path {
                nut19::Path::Swap => self.mint_url.join_paths(&["v1", "swap"])?,
                nut19::Path::Custom(custom_path) => {
                    // Custom paths should be in the format "/v1/mint/{method}" or "/v1/melt/{method}"
                    // Remove leading slash if present
                    let path_str = custom_path.trim_start_matches('/');
                    let parts: Vec<&str> = path_str.split('/').collect();
                    self.mint_url.join_paths(&parts)?
                }
            };

            let result = match method {
                nut19::Method::Get => transport.http_get(url, auth_token.clone()).await,
                nut19::Method::Post => transport.http_post(url, auth_token.clone(), payload).await,
            };

            if result.is_ok() {
                return result;
            }

            match result.as_ref() {
                Err(Error::HttpError(status_code, _)) => {
                    let status_code = status_code.to_owned().unwrap_or_default();
                    if (400..=499).contains(&status_code) {
                        // 4xx errors won't be 'solved' by retrying
                        return result;
                    }

                    // retry request, if possible
                    tracing::error!("Failed http_request {:?}", result.as_ref().err());

                    if retriable_window < started.elapsed() {
                        return result;
                    }
                }
                Err(_) => return result,
                _ => unreachable!(),
            };
        }
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T> MintConnector for HttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    #[cfg(all(feature = "bip353", not(target_arch = "wasm32")))]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn resolve_dns_txt(&self, domain: &str) -> Result<Vec<String>, Error> {
        self.transport.resolve_dns_txt(domain).await
    }

    /// Fetch Lightning address pay request data
    #[instrument(skip(self))]
    async fn fetch_lnurl_pay_request(
        &self,
        url: &str,
    ) -> Result<crate::lightning_address::LnurlPayResponse, Error> {
        let parsed_url =
            url::Url::parse(url).map_err(|e| Error::Custom(format!("Invalid URL: {}", e)))?;
        self.transport.http_get(parsed_url, None).await
    }

    /// Fetch invoice from Lightning address callback
    #[instrument(skip(self))]
    async fn fetch_lnurl_invoice(
        &self,
        url: &str,
    ) -> Result<crate::lightning_address::LnurlPayInvoiceResponse, Error> {
        let parsed_url =
            url::Url::parse(url).map_err(|e| Error::Custom(format!("Invalid URL: {}", e)))?;
        self.transport.http_get(parsed_url, None).await
    }

    /// Get Active Mint Keys [NUT-01]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_keys(&self) -> Result<Vec<KeySet>, Error> {
        let url = self.mint_url.join_paths(&["v1", "keys"])?;
        let transport = self.transport.clone();

        Ok(transport.http_get::<KeysResponse>(url, None).await?.keysets)
    }

    /// Get Keyset Keys [NUT-01]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_keyset(&self, keyset_id: Id) -> Result<KeySet, Error> {
        let url = self
            .mint_url
            .join_paths(&["v1", "keys", &keyset_id.to_string()])?;

        let transport = self.transport.clone();
        let keys_response = transport.http_get::<KeysResponse>(url, None).await?;

        Ok(keys_response
            .keysets
            .first()
            .ok_or(Error::UnknownKeySet)?
            .clone())
    }

    /// Get Keysets [NUT-02]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_keysets(&self) -> Result<KeysetResponse, Error> {
        let url = self.mint_url.join_paths(&["v1", "keysets"])?;
        let transport = self.transport.clone();
        transport.http_get(url, None).await
    }

    /// Mint Quote [NUT-04, NUT-23, NUT-25]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_mint_quote(
        &self,
        request: MintQuoteRequest,
    ) -> Result<MintQuoteResponse<String>, Error> {
        let method = request.method().to_string();
        let path = format!("v1/mint/quote/{}", method);

        let url = self
            .mint_url
            .join_paths(&path.split('/').collect::<Vec<_>>())?;

        let auth_token = self
            .get_auth_token(
                Method::Post,
                RoutePath::MintQuote(request.method().to_string()),
            )
            .await?;

        match &request {
            MintQuoteRequest::Bolt11(req) => {
                let response: cdk_common::nut23::MintQuoteBolt11Response<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MintQuoteResponse::Bolt11(response))
            }
            MintQuoteRequest::Bolt12(req) => {
                let response: cdk_common::nut25::MintQuoteBolt12Response<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MintQuoteResponse::Bolt12(response))
            }
            MintQuoteRequest::Custom(req) => {
                let response: cdk_common::nut04::MintQuoteCustomResponse<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MintQuoteResponse::Custom((request.method(), response)))
            }
        }
    }

    /// Mint Quote status with payment method
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_quote_status(
        &self,
        method: PaymentMethod,
        quote_id: &str,
    ) -> Result<MintQuoteResponse<String>, Error> {
        match &method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                let url = self
                    .mint_url
                    .join_paths(&["v1", "mint", "quote", "bolt11", quote_id])?;

                let auth_token = self
                    .get_auth_token(
                        Method::Get,
                        RoutePath::MintQuote(PaymentMethod::Known(KnownMethod::Bolt11).to_string()),
                    )
                    .await?;

                let response: MintQuoteBolt11Response<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MintQuoteResponse::Bolt11(response))
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                let url = self
                    .mint_url
                    .join_paths(&["v1", "mint", "quote", "bolt12", quote_id])?;

                let auth_token = self
                    .get_auth_token(
                        Method::Get,
                        RoutePath::MintQuote(PaymentMethod::Known(KnownMethod::Bolt12).to_string()),
                    )
                    .await?;

                let response: MintQuoteBolt12Response<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MintQuoteResponse::Bolt12(response))
            }
            // PaymentMethod::Known(KnownMethod::Onchain) => Err(Error::UnsupportedPaymentMethod),
            PaymentMethod::Custom(method_name) => {
                let url =
                    self.mint_url
                        .join_paths(&["v1", "mint", "quote", method_name, quote_id])?;

                let auth_token = self
                    .get_auth_token(Method::Get, RoutePath::MintQuote(method_name.clone()))
                    .await?;

                let response: MintQuoteCustomResponse<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MintQuoteResponse::Custom((method, response)))
            }
        }
    }

    /// Mint Tokens [NUT-04]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_mint(
        &self,
        method: &PaymentMethod,
        request: MintRequest<String>,
    ) -> Result<MintResponse, Error> {
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::Mint(method.to_string()))
            .await?;

        let path = match method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                nut19::Path::Custom("/v1/mint/bolt11".to_string())
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                nut19::Path::Custom("/v1/mint/bolt12".to_string())
            }
            PaymentMethod::Custom(m) => nut19::Path::custom_mint(m),
        };

        self.retriable_http_request(nut19::Method::Post, path, auth_token, &request)
            .await
    }

    /// Batch check mint quote status [NUT-29]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_batch_check_mint_quote_status(
        &self,
        method: &PaymentMethod,
        request: BatchCheckMintQuoteRequest<String>,
    ) -> Result<Vec<MintQuoteBolt11Response<String>>, Error> {
        let url =
            self.mint_url
                .join_paths(&["v1", "mint", "quote", &method.to_string(), "check"])?;

        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::MintQuote(method.to_string()))
            .await?;

        self.transport.http_post(url, auth_token, &request).await
    }

    /// Batch mint tokens [NUT-29]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_batch_mint(
        &self,
        method: &PaymentMethod,
        request: BatchMintRequest<String>,
    ) -> Result<MintResponse, Error> {
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::Mint(method.to_string()))
            .await?;

        let path = nut19::Path::Custom(format!("/v1/mint/{}/batch", method));

        self.retriable_http_request(nut19::Method::Post, path, auth_token, &request)
            .await
    }

    /// Melt Quote [NUT-05]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_melt_quote(
        &self,
        request: MeltQuoteRequest,
    ) -> Result<MeltQuoteResponse<String>, Error> {
        let method = request.method().to_string();
        let path = format!("v1/melt/quote/{}", method);

        let url = self
            .mint_url
            .join_paths(&path.split('/').collect::<Vec<_>>())?;
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::MeltQuote(method))
            .await?;

        match &request {
            MeltQuoteRequest::Bolt11(req) => {
                let response: cdk_common::nut23::MeltQuoteBolt11Response<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MeltQuoteResponse::Bolt11(response))
            }
            MeltQuoteRequest::Bolt12(req) => {
                let response: cdk_common::nut25::MeltQuoteBolt12Response<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MeltQuoteResponse::Bolt12(response))
            }
            MeltQuoteRequest::Custom(req) => {
                let response: cdk_common::nut05::MeltQuoteCustomResponse<String> =
                    self.transport.http_post(url, auth_token, req).await?;
                Ok(MeltQuoteResponse::Custom((request.method(), response)))
            }
        }
    }

    /// Melt Quote Status
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_melt_quote_status(
        &self,
        method: PaymentMethod,
        quote_id: &str,
    ) -> Result<MeltQuoteResponse<String>, Error> {
        match &method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                let url = self
                    .mint_url
                    .join_paths(&["v1", "melt", "quote", "bolt11", quote_id])?;

                let auth_token = self
                    .get_auth_token(
                        Method::Get,
                        RoutePath::MeltQuote(PaymentMethod::Known(KnownMethod::Bolt11).to_string()),
                    )
                    .await?;

                let response: cdk_common::nut23::MeltQuoteBolt11Response<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MeltQuoteResponse::Bolt11(response))
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                let url = self
                    .mint_url
                    .join_paths(&["v1", "melt", "quote", "bolt12", quote_id])?;

                let auth_token = self
                    .get_auth_token(
                        Method::Get,
                        RoutePath::MeltQuote(PaymentMethod::Known(KnownMethod::Bolt12).to_string()),
                    )
                    .await?;

                let response: cdk_common::nut25::MeltQuoteBolt12Response<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MeltQuoteResponse::Bolt12(response))
            }
            PaymentMethod::Custom(method_name) => {
                let url =
                    self.mint_url
                        .join_paths(&["v1", "melt", "quote", method_name, quote_id])?;

                let auth_token = self
                    .get_auth_token(Method::Get, RoutePath::MeltQuote(method_name.clone()))
                    .await?;

                let response: cdk_common::nut05::MeltQuoteCustomResponse<String> =
                    self.transport.http_get(url, auth_token).await?;

                Ok(MeltQuoteResponse::Custom((method.clone(), response)))
            }
        }
    }

    /// Melt [NUT-05]
    /// [Nut-08] Lightning fee return if outputs defined
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_melt(
        &self,
        method: &PaymentMethod,
        request: MeltRequest<String>,
    ) -> Result<MeltQuoteBolt11Response<String>, Error> {
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::Melt(method.to_string()))
            .await?;

        let path = match method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                nut19::Path::Custom("/v1/melt/bolt11".to_string())
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                nut19::Path::Custom("/v1/melt/bolt12".to_string())
            }
            PaymentMethod::Custom(m) => nut19::Path::custom_melt(m),
        };

        self.retriable_http_request(nut19::Method::Post, path, auth_token, &request)
            .await
    }

    /// Swap Token [NUT-03]
    #[instrument(skip(self, swap_request), fields(mint_url = %self.mint_url))]
    async fn post_swap(&self, swap_request: SwapRequest) -> Result<SwapResponse, Error> {
        let auth_token = self.get_auth_token(Method::Post, RoutePath::Swap).await?;

        self.retriable_http_request(
            nut19::Method::Post,
            nut19::Path::Swap,
            auth_token,
            &swap_request,
        )
        .await
    }

    /// Helper to get mint info
    async fn get_mint_info(&self) -> Result<MintInfo, Error> {
        let url = self.mint_url.join_paths(&["v1", "info"])?;
        let transport = self.transport.clone();
        let info: MintInfo = transport.http_get(url, None).await?;

        if let Ok(mut cache_support) = self.cache_support.write() {
            *cache_support = (
                info.nuts.nut19.ttl.unwrap_or(300),
                info.nuts
                    .nut19
                    .cached_endpoints
                    .clone()
                    .into_iter()
                    .map(|cached_endpoint| (cached_endpoint.method, cached_endpoint.path))
                    .collect(),
            );
        }

        Ok(info)
    }

    async fn get_auth_wallet(&self) -> Option<AuthWallet> {
        self.auth_wallet.read().await.clone()
    }

    async fn set_auth_wallet(&self, wallet: Option<AuthWallet>) {
        *self.auth_wallet.write().await = wallet;
    }

    /// Spendable check [NUT-07]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_check_state(
        &self,
        request: CheckStateRequest,
    ) -> Result<CheckStateResponse, Error> {
        let url = self.mint_url.join_paths(&["v1", "checkstate"])?;
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::Checkstate)
            .await?;

        self.transport.http_post(url, auth_token, &request).await
    }

    /// Restore request [NUT-13]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_restore(&self, request: RestoreRequest) -> Result<RestoreResponse, Error> {
        let url = self.mint_url.join_paths(&["v1", "restore"])?;
        let auth_token = self
            .get_auth_token(Method::Post, RoutePath::Restore)
            .await?;

        self.transport.http_post(url, auth_token, &request).await
    }
}

/// Http Client

#[derive(Debug, Clone)]
pub struct AuthHttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    transport: Arc<T>,
    mint_url: MintUrl,
    cat: Arc<RwLock<AuthToken>>,
}

impl<T> AuthHttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    /// Create new [`AuthHttpClient`]
    pub fn new(mint_url: MintUrl, cat: Option<AuthToken>) -> Self {
        Self {
            transport: T::default().into(),
            mint_url,
            cat: Arc::new(RwLock::new(
                cat.unwrap_or(AuthToken::ClearAuth("".to_string())),
            )),
        }
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T> AuthMintConnector for AuthHttpClient<T>
where
    T: Transport + Send + Sync + 'static,
{
    async fn get_auth_token(&self) -> Result<AuthToken, Error> {
        Ok(self.cat.read().await.clone())
    }

    async fn set_auth_token(&self, token: AuthToken) -> Result<(), Error> {
        *self.cat.write().await = token;
        Ok(())
    }

    /// Get Mint Info [NUT-06]
    async fn get_mint_info(&self) -> Result<MintInfo, Error> {
        let url = self.mint_url.join_paths(&["v1", "info"])?;
        let mint_info: MintInfo = self.transport.http_get::<MintInfo>(url, None).await?;

        Ok(mint_info)
    }

    /// Get Auth Keyset Keys [NUT-22]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_blind_auth_keyset(&self, keyset_id: Id) -> Result<KeySet, Error> {
        let url =
            self.mint_url
                .join_paths(&["v1", "auth", "blind", "keys", &keyset_id.to_string()])?;

        let mut keys_response = self.transport.http_get::<KeysResponse>(url, None).await?;

        let keyset = keys_response
            .keysets
            .drain(0..1)
            .next()
            .ok_or_else(|| Error::UnknownKeySet)?;

        Ok(keyset)
    }

    /// Get Auth Keysets [NUT-22]
    #[instrument(skip(self), fields(mint_url = %self.mint_url))]
    async fn get_mint_blind_auth_keysets(&self) -> Result<KeysetResponse, Error> {
        let url = self
            .mint_url
            .join_paths(&["v1", "auth", "blind", "keysets"])?;

        self.transport.http_get(url, None).await
    }

    /// Mint Tokens [NUT-22]
    #[instrument(skip(self, request), fields(mint_url = %self.mint_url))]
    async fn post_mint_blind_auth(&self, request: MintAuthRequest) -> Result<MintResponse, Error> {
        let url = self.mint_url.join_paths(&["v1", "auth", "blind", "mint"])?;
        self.transport
            .http_post(url, Some(self.cat.read().await.clone()), &request)
            .await
    }
}