breez_sdk_liquid/
buy.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
use anyhow::{anyhow, Result};
use maybe_sync::{MaybeSend, MaybeSync};
use sdk_common::prelude::{utils::Arc, BreezServer, BuyBitcoinProviderApi, MoonpayProvider};

use crate::{
    model::{BuyBitcoinProvider, ChainSwap, Config},
    prelude::LiquidNetwork,
};

#[sdk_macros::async_trait]
pub(crate) trait BuyBitcoinApi: MaybeSend + MaybeSync {
    /// Initiate buying Bitcoin and return a URL to the selected third party provider
    async fn buy_bitcoin(
        &self,
        provider: BuyBitcoinProvider,
        chain_swap: &ChainSwap,
        redirect_url: Option<String>,
    ) -> Result<String>;
}

pub(crate) struct BuyBitcoinService {
    config: Config,
    moonpay_provider: Arc<dyn BuyBitcoinProviderApi>,
}

impl BuyBitcoinService {
    pub fn new(config: Config, breez_server: Arc<BreezServer>) -> Self {
        let moonpay_provider = Arc::new(MoonpayProvider::new(breez_server));
        Self {
            config,
            moonpay_provider,
        }
    }
}

#[sdk_macros::async_trait]
impl BuyBitcoinApi for BuyBitcoinService {
    async fn buy_bitcoin(
        &self,
        provider: BuyBitcoinProvider,
        chain_swap: &ChainSwap,
        redirect_url: Option<String>,
    ) -> Result<String> {
        if self.config.network != LiquidNetwork::Mainnet {
            return Err(anyhow!("Can only buy bitcoin on Mainnet"));
        }

        let create_response = chain_swap.get_boltz_create_response()?;

        match provider {
            BuyBitcoinProvider::Moonpay => {
                self.moonpay_provider
                    .buy_bitcoin(
                        create_response.lockup_details.lockup_address,
                        Some(create_response.lockup_details.amount),
                        None,
                        redirect_url,
                    )
                    .await
            }
        }
    }
}