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
19const USD_AMOUNT_DECIMALS: u32 = 6;
21
22#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
23#[macros::instance_span]
24impl BreezSdk {
25 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 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 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 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 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 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
218fn 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}