breez_sdk_liquid/swapper/boltz/
proxy.rs

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
use std::sync::OnceLock;

use anyhow::Result;
use sdk_common::prelude::BreezServer;
use sdk_common::utils::Arc;
use url::Url;

use crate::{persist::Persister, swapper::ProxyUrlFetcher};

pub(crate) struct BoltzProxyFetcher {
    url: OnceLock<Option<String>>,
    persister: Arc<Persister>,
}

pub(crate) fn split_proxy_url(url: &str) -> (Option<String>, Option<String>) {
    Url::parse(url)
        .map(|url| {
            let api_base_url = url.domain().map(|domain| format!("https://{domain}/v2"));
            let referral_id = url.query().and_then(|q| {
                q.split('=')
                    .map(Into::into)
                    .collect::<Vec<String>>()
                    .get(1)
                    .cloned()
            });
            (api_base_url, referral_id)
        })
        .unwrap_or_default()
}

impl BoltzProxyFetcher {
    pub(crate) fn new(persister: Arc<Persister>) -> Self {
        Self {
            url: OnceLock::new(),
            persister,
        }
    }
}

#[sdk_macros::async_trait]
impl ProxyUrlFetcher for BoltzProxyFetcher {
    async fn fetch(&self) -> Result<&Option<String>> {
        if let Some(swapper_proxy_url) = self.url.get() {
            return Ok(swapper_proxy_url);
        }

        let maybe_swapper_proxy_url =
            match BreezServer::new("https://bs1.breez.technology:443".into(), None) {
                Ok(breez_server) => {
                    let maybe_swapper_proxy_url = breez_server
                        .fetch_boltz_swapper_urls()
                        .await
                        .map(|swapper_urls| swapper_urls.first().cloned())?;

                    if let Some(swapper_proxy_url) = maybe_swapper_proxy_url.clone() {
                        self.persister.set_swapper_proxy_url(swapper_proxy_url)?;
                    }
                    maybe_swapper_proxy_url
                }
                Err(_) => self.persister.get_swapper_proxy_url().unwrap_or(None),
            };

        let swapper_proxy_url = self.url.get_or_init(|| maybe_swapper_proxy_url);
        Ok(swapper_proxy_url)
    }
}