Skip to main content

breez_sdk_spark/sdk/
buy.rs

1use breez_sdk_common::buy::{cashapp::CashAppProvider, moonpay::USDC_SOLANA_PRECISION};
2use tracing::warn;
3
4use crate::{
5    BuyBitcoinRequest, BuyBitcoinResponse, MoonpayDelivery, Network, ReceivePaymentMethod,
6    ReceivePaymentRequest,
7    cross_chain::{
8        CrossChainFeeMode, CrossChainProvider, CrossChainReceiveInfo, CrossChainRouteFilter,
9        CrossChainRoutePair, rescale_decimals,
10    },
11    error::SdkError,
12};
13
14use super::{BreezSdk, bridging::check_deposit_target, helpers::get_deposit_address};
15
16const SOLANA_CHAIN: &str = "solana";
17const USDC_ASSET: &str = "USDC";
18
19/// Decimal places of `MoonpayDelivery::CrossChain::amount`.
20const USD_AMOUNT_DECIMALS: u32 = 6;
21
22#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
23#[macros::instance_span]
24impl BreezSdk {
25    /// Initiates a Bitcoin purchase flow via an external provider.
26    ///
27    /// Returns a URL the user should open to complete the purchase.
28    /// The request variant determines the provider and its parameters:
29    ///
30    /// - [`BuyBitcoinRequest::Moonpay`]: Fiat-to-Bitcoin, delivered to an
31    ///   on-chain deposit address or as USDC on Solana (see [`MoonpayDelivery`]).
32    /// - [`BuyBitcoinRequest::CashApp`]: Lightning invoice + `cash.app` deep link (mainnet only).
33    pub async fn buy_bitcoin(
34        &self,
35        request: BuyBitcoinRequest,
36    ) -> Result<BuyBitcoinResponse, SdkError> {
37        let url = match request {
38            BuyBitcoinRequest::Moonpay {
39                delivery,
40                redirect_url,
41            } => match delivery.unwrap_or_default() {
42                MoonpayDelivery::Bitcoin { amount_sat } => {
43                    let address =
44                        get_deposit_address(&self.spark_wallet, &self.storage, true).await?;
45                    self.buy_bitcoin_provider
46                        .buy_bitcoin(address, amount_sat, redirect_url)
47                        .await
48                        .map_err(|e| {
49                            SdkError::Generic(format!("Failed to create buy bitcoin URL: {e}"))
50                        })?
51                }
52                MoonpayDelivery::CrossChain { amount, fee_mode } => {
53                    let (info, decimals) = self
54                        .quote_moonpay_usdc_solana(
55                            amount,
56                            fee_mode.unwrap_or(CrossChainFeeMode::FeesExcluded),
57                        )
58                        .await?;
59                    let url = self
60                        .buy_bitcoin_provider
61                        .buy_usdc_solana(
62                            info.deposit_address.clone(),
63                            info.deposit_amount,
64                            u32::from(decimals),
65                            redirect_url,
66                        )
67                        .await
68                        .map_err(|e| {
69                            SdkError::Generic(format!("Failed to create buy bitcoin URL: {e}"))
70                        })?;
71                    return Ok(BuyBitcoinResponse {
72                        url,
73                        cross_chain_info: Some(info),
74                    });
75                }
76            },
77            BuyBitcoinRequest::CashApp { amount_sats } => {
78                if !matches!(self.config.network, Network::Mainnet) {
79                    return Err(SdkError::Generic(
80                        "CashApp is only available on mainnet".to_string(),
81                    ));
82                }
83                if amount_sats == 0 {
84                    return Err(SdkError::Generic(
85                        "CashApp requires a non-zero amount".to_string(),
86                    ));
87                }
88                let (url, info) = self.cash_app_purchase(amount_sats).await?;
89                return Ok(BuyBitcoinResponse {
90                    url,
91                    cross_chain_info: Some(info),
92                });
93            }
94        };
95
96        Ok(BuyBitcoinResponse {
97            url,
98            cross_chain_info: None,
99        })
100    }
101}
102
103impl BreezSdk {
104    /// The wallet's Lightning address, where a failed Cash App order is
105    /// refunded. Best effort: unset when none is registered or the lookup
106    /// fails, and the order then has no refund destination.
107    pub(super) async fn wallet_refund_address(&self) -> Option<String> {
108        self.get_lightning_address()
109            .await
110            .inspect_err(|e| warn!("CashApp: no refund address, lookup failed: {e}"))
111            .ok()
112            .flatten()
113            .map(|info| info.lightning_address)
114    }
115
116    /// The `cash.app` link for a Cash App purchase that delivers `amount_sats`,
117    /// and the order behind it. Cash App pays the invoice of a Flashnet
118    /// Orchestra onramp order, which delivers the sats to this wallet, or
119    /// refunds them to its Lightning address, when one is registered, if the
120    /// order fails. The link is built around the invoice checked here rather
121    /// than taken from the order.
122    async fn cash_app_purchase(
123        &self,
124        amount_sats: u64,
125    ) -> Result<(String, CrossChainReceiveInfo), SdkError> {
126        let orchestra = self.orchestra.as_ref().ok_or_else(|| {
127            SdkError::Generic(
128                "CashApp is not available when background tasks are disabled".to_string(),
129            )
130        })?;
131        let refund_address = self.wallet_refund_address().await;
132        let order = orchestra
133            .create_lightning_receive_delivering(amount_sats, refund_address.as_deref())
134            .await?;
135        let invoice = order.info.deposit_address.clone();
136        let expected_sats = u64::try_from(order.info.deposit_amount).map_err(|_| {
137            SdkError::Generic(format!(
138                "Deposit amount {} sats exceeds u64::MAX",
139                order.info.deposit_amount
140            ))
141        })?;
142        check_deposit_target(&self.parse(&invoice).await, expected_sats)?;
143        let info = orchestra.track_lightning_receive(order).await?;
144        Ok((CashAppProvider::build_url(&invoice), info))
145    }
146
147    /// Quotes a USDC-on-Solana receive for a `MoonPay` purchase to fund.
148    /// `amount` is in USD at 6 decimals. Returns the quote, with its deposit
149    /// rounded up to whole cents, and the route's decimals.
150    async fn quote_moonpay_usdc_solana(
151        &self,
152        amount: u128,
153        fee_mode: CrossChainFeeMode,
154    ) -> Result<(CrossChainReceiveInfo, u8), SdkError> {
155        let service = self
156            .cross_chain_context
157            .get(CrossChainProvider::Orchestra)?;
158        if amount == 0 {
159            return Err(SdkError::InvalidInput(
160                "MoonPay cross-chain delivery requires a non-zero amount".to_string(),
161            ));
162        }
163        let route = service
164            .get_routes(&CrossChainRouteFilter::Receive {
165                contract_address: None,
166                delivery_method: None,
167            })
168            .await?
169            .into_iter()
170            .find(is_usdc_solana)
171            .ok_or_else(|| {
172                SdkError::cross_chain_route_unavailable(
173                    "USDC on Solana is not offered".to_string(),
174                    false,
175                )
176            })?;
177        let decimals = route.decimals;
178
179        // With fees included the amount is the deposit itself, so it has to
180        // be whole cents already.
181        let amount = match fee_mode {
182            CrossChainFeeMode::FeesIncluded => {
183                round_up_to_precision(amount, USD_AMOUNT_DECIMALS, USDC_SOLANA_PRECISION)
184            }
185            CrossChainFeeMode::FeesExcluded => amount,
186        };
187        let amount = rescale_decimals(amount, USD_AMOUNT_DECIMALS, u32::from(decimals))?;
188        let response = self
189            .receive_payment(ReceivePaymentRequest {
190                payment_method: ReceivePaymentMethod::CrossChain {
191                    route,
192                    amount,
193                    destination: None,
194                    fee_mode: Some(fee_mode),
195                    max_slippage_bps: None,
196                    target_overpay_bps: None,
197                    refund_address: None,
198                },
199            })
200            .await?;
201        let mut info = response.cross_chain_info.ok_or_else(|| {
202            SdkError::Generic("Cross-chain receive returned no quote".to_string())
203        })?;
204        // MoonPay buys whole cents. The quote can call for a fraction of one.
205        info.deposit_amount = round_up_to_precision(
206            info.deposit_amount,
207            u32::from(decimals),
208            USDC_SOLANA_PRECISION,
209        );
210        Ok((info, decimals))
211    }
212}
213
214fn is_usdc_solana(route: &CrossChainRoutePair) -> bool {
215    route.chain.eq_ignore_ascii_case(SOLANA_CHAIN) && route.asset.eq_ignore_ascii_case(USDC_ASSET)
216}
217
218/// Rounds `amount` (base units at `decimals`) up to the nearest whole unit
219/// at `precision` fractional digits.
220fn round_up_to_precision(amount: u128, decimals: u32, precision: u32) -> u128 {
221    let Some(shift) = decimals.checked_sub(precision) else {
222        return amount;
223    };
224    let unit = 10u128.saturating_pow(shift);
225    amount.div_ceil(unit).saturating_mul(unit)
226}
227
228#[cfg(test)]
229mod tests {
230    use super::round_up_to_precision;
231
232    #[test]
233    fn test_round_up_to_precision() {
234        assert_eq!(round_up_to_precision(12_340_000, 6, 2), 12_340_000);
235        assert_eq!(round_up_to_precision(12_340_001, 6, 2), 12_350_000);
236        assert_eq!(round_up_to_precision(12_349_999, 6, 2), 12_350_000);
237        assert_eq!(round_up_to_precision(0, 6, 2), 0);
238        assert_eq!(round_up_to_precision(1_234, 2, 2), 1_234);
239        assert_eq!(round_up_to_precision(5, 1, 2), 5);
240    }
241}