1#[cfg(feature = "boltz")]
11#[allow(dead_code)]
12pub(crate) mod boltz;
13mod cached_fiat;
14mod orchestra;
15
16pub(crate) use cached_fiat::{CachedFiatService, DEFAULT_FIAT_CACHE_TTL};
17pub(crate) use orchestra::{
18 BreezServerOrchestraConfigResolver, DepositDestination, OrchestraQuoter, OrchestraService,
19 delivery_method_from_wire, delivery_method_to_wire, parse_rfc3339_to_unix_seconds,
20 to_route_limits,
21};
22
23use std::collections::HashMap;
24use std::str::FromStr;
25use std::sync::Arc;
26use std::time::Duration;
27
28use breez_sdk_common::fiat::FiatService;
29use serde::{Deserialize, Serialize};
30use spark_wallet::TransferId;
31
32use crate::{
33 ConversionInfo, CrossChainAddressDetails, PaymentDetails, error::SdkError,
34 utils::conversions::extract_conversion_info,
35};
36
37pub(crate) const MIN_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 10;
39pub(crate) const MAX_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 500;
40pub(crate) const DEFAULT_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 100;
43
44pub(crate) const MIN_TARGET_OVERPAY_BPS: u32 = 0;
48pub(crate) const MAX_TARGET_OVERPAY_BPS: u32 = 500;
49pub(crate) const DEFAULT_TARGET_OVERPAY_BPS: u32 = 15;
54const USD_STABLE_ASSETS: &[&str] = &["USDB", "USDC", "USDT", "USDT0"];
57
58pub(crate) const MONITOR_INTERVAL: Duration = Duration::from_secs(30);
60
61static RECEIVE_CONVERSION_WRITES: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
68
69pub(crate) async fn attach_receive_metadata_for_payment(
74 storage: &Arc<dyn crate::Storage>,
75 payment: &crate::Payment,
76) -> Result<bool, SdkError> {
77 if payment.payment_type != crate::PaymentType::Receive {
78 return Ok(false);
79 }
80 let invoice = match &payment.details {
81 Some(
82 PaymentDetails::Spark {
83 invoice_details: Some(details),
84 ..
85 }
86 | PaymentDetails::Token {
87 invoice_details: Some(details),
88 ..
89 },
90 ) => &details.invoice,
91 _ => return Ok(false),
92 };
93
94 let _serialized = RECEIVE_CONVERSION_WRITES.lock().await;
95 let already_attached = storage
96 .get_payment_by_id(payment.id.clone())
97 .await
98 .is_ok_and(|stored| extract_conversion_info(stored.details).is_some());
99 if already_attached {
100 return Ok(false);
101 }
102 let Some(conversion_info) = orchestra::link_receive_for_invoice(storage, invoice).await? else {
103 return Ok(false);
104 };
105 storage
106 .insert_payment_metadata(
107 payment.id.clone(),
108 crate::PaymentMetadata {
109 conversion_info: Some(conversion_info),
110 ..Default::default()
111 },
112 )
113 .await?;
114 Ok(true)
115}
116
117pub(crate) async fn apply_synced_swap(
121 storage: &Arc<dyn crate::Storage>,
122 event_emitter: &crate::EventEmitter,
123 swap: &crate::persist::StoredCrossChainSwap,
124 emit: bool,
125) -> Result<(), SdkError> {
126 if swap.provider == orchestra::storage_adapter::PROVIDER_TAG_ORCHESTRA {
127 orchestra::record_synced_failed_receive(storage, event_emitter, swap, emit).await?;
128 }
129 Ok(())
130}
131
132pub(crate) fn payment_with_conversion_info(
137 mut payment: crate::Payment,
138 conversion_info: Option<ConversionInfo>,
139) -> crate::Payment {
140 payment.details = match payment.details {
141 Some(PaymentDetails::Spark {
142 invoice_details,
143 htlc_details,
144 ..
145 }) => Some(PaymentDetails::Spark {
146 invoice_details,
147 htlc_details,
148 conversion_info,
149 }),
150 Some(PaymentDetails::Token {
151 metadata,
152 tx_hash,
153 tx_type,
154 invoice_details,
155 ..
156 }) => Some(PaymentDetails::Token {
157 metadata,
158 tx_hash,
159 tx_type,
160 invoice_details,
161 conversion_info,
162 }),
163 Some(PaymentDetails::Lightning {
164 description,
165 invoice,
166 destination_pubkey,
167 htlc_details,
168 lnurl_pay_info,
169 lnurl_withdraw_info,
170 lnurl_receive_metadata,
171 ..
172 }) => Some(PaymentDetails::Lightning {
173 description,
174 invoice,
175 destination_pubkey,
176 htlc_details,
177 lnurl_pay_info,
178 lnurl_withdraw_info,
179 lnurl_receive_metadata,
180 conversion_info,
181 }),
182 other => other,
183 };
184 payment
185}
186
187pub(crate) fn derive_btc_leg_transfer_id(
197 idempotency_key: Option<&str>,
198 fallback_seed: &str,
199) -> Result<TransferId, SdkError> {
200 match idempotency_key {
201 Some(key) => TransferId::from_str(key).map_err(SdkError::Generic),
202 None => Ok(TransferId::from_name(fallback_seed)),
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
207#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
208pub enum CrossChainProvider {
209 Orchestra,
210 Boltz,
212}
213
214impl std::fmt::Display for CrossChainProvider {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 match self {
217 Self::Orchestra => f.write_str("Orchestra"),
218 Self::Boltz => f.write_str("Boltz"),
219 }
220 }
221}
222
223#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
225#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
226pub enum SparkAsset {
227 Bitcoin,
229 Token { token_identifier: String },
231}
232
233#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
248#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
249pub struct CrossChainRouteLimits {
250 pub min_amount: Option<u128>,
252 pub max_amount: Option<u128>,
254 pub min_usd_cents: Option<u64>,
256 pub max_usd_cents: Option<u64>,
258}
259
260#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
265#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
266pub struct CrossChainAcceptedAsset {
267 pub asset: SparkAsset,
268 pub limits: Option<CrossChainRouteLimits>,
270}
271
272#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
274#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
275pub enum DeliveryMethod {
276 Spark,
278 Lightning,
280 Bitcoin,
282}
283
284impl std::fmt::Display for DeliveryMethod {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 match self {
287 Self::Spark => f.write_str("Spark"),
288 Self::Lightning => f.write_str("Lightning"),
289 Self::Bitcoin => f.write_str("Bitcoin"),
290 }
291 }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
298pub enum CrossChainFeeMode {
299 FeesExcluded,
306 FeesIncluded,
313}
314
315impl From<crate::FeePolicy> for CrossChainFeeMode {
316 fn from(policy: crate::FeePolicy) -> Self {
317 match policy {
318 crate::FeePolicy::FeesExcluded => Self::FeesExcluded,
319 crate::FeePolicy::FeesIncluded => Self::FeesIncluded,
320 }
321 }
322}
323
324#[derive(Clone, Debug, Deserialize, Serialize)]
327#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
328pub enum CrossChainRouteFilter {
329 Send {
332 address_details: CrossChainAddressDetails,
333 delivery_method: Option<DeliveryMethod>,
337 },
338 Receive {
341 contract_address: Option<String>,
342 delivery_method: Option<DeliveryMethod>,
346 },
347 PaymentLink {
352 address_details: CrossChainAddressDetails,
353 },
354}
355
356impl CrossChainRouteFilter {
357 pub(crate) fn normalized(&self) -> Self {
359 match self {
360 Self::PaymentLink { address_details } => Self::Send {
361 address_details: address_details.clone(),
362 delivery_method: Some(DeliveryMethod::Lightning),
363 },
364 other => other.clone(),
365 }
366 }
367}
368
369#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
372#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
373pub struct CrossChainRoutePair {
374 pub provider: CrossChainProvider,
376 pub chain: String,
378 pub chain_id: Option<String>,
382 pub asset: String,
384 pub contract_address: Option<String>,
386 pub decimals: u8,
388 pub exact_out_eligible: bool,
390 pub accepted_assets: Vec<CrossChainAcceptedAsset>,
392 pub delivery_methods: Vec<DeliveryMethod>,
395}
396
397impl CrossChainRoutePair {
398 pub fn limits_for(&self, asset: &SparkAsset) -> Option<&CrossChainRouteLimits> {
401 self.accepted_assets
402 .iter()
403 .find(|a| &a.asset == asset)
404 .and_then(|a| a.limits.as_ref())
405 }
406
407 pub fn accepts_asset(&self, asset: &SparkAsset) -> bool {
409 self.accepted_assets.iter().any(|a| &a.asset == asset)
410 }
411
412 pub(crate) fn destination_address_family(
417 &self,
418 ) -> Option<breez_sdk_common::input::CrossChainAddressFamily> {
419 self.contract_address
420 .as_deref()
421 .and_then(breez_sdk_common::input::detect_address_family)
422 }
423}
424
425#[derive(Clone)]
429pub(crate) struct CrossChainContext {
430 providers: HashMap<CrossChainProvider, Arc<dyn CrossChainService>>,
431 fiat_service: Arc<dyn FiatService>,
432 orchestra_quoter: Option<Arc<OrchestraQuoter>>,
434}
435
436impl CrossChainContext {
437 pub fn new(fiat_service: Arc<dyn FiatService>) -> Self {
438 Self {
439 providers: HashMap::new(),
440 fiat_service,
441 orchestra_quoter: None,
442 }
443 }
444
445 pub fn insert(&mut self, key: CrossChainProvider, service: Arc<dyn CrossChainService>) {
446 self.providers.insert(key, service);
447 }
448
449 pub fn set_orchestra_quoter(&mut self, quoter: Arc<OrchestraQuoter>) {
450 self.orchestra_quoter = Some(quoter);
451 }
452
453 pub fn orchestra_quoter(&self) -> Option<&Arc<OrchestraQuoter>> {
455 self.orchestra_quoter.as_ref()
456 }
457
458 pub fn ensure_enabled(&self) -> Result<(), SdkError> {
461 if self.providers.is_empty() {
462 return Err(SdkError::cross_chain_disabled());
463 }
464 Ok(())
465 }
466
467 pub fn get(
469 &self,
470 provider: CrossChainProvider,
471 ) -> Result<&Arc<dyn CrossChainService>, SdkError> {
472 self.ensure_enabled()?;
473 self.providers.get(&provider).ok_or_else(|| {
474 SdkError::InvalidInput(format!("Cross-chain provider {provider} is not available."))
475 })
476 }
477
478 pub fn values(&self) -> impl Iterator<Item = &Arc<dyn CrossChainService>> {
479 self.providers.values()
480 }
481
482 pub async fn list_routes(
485 &self,
486 filter: &CrossChainRouteFilter,
487 ) -> Result<Vec<CrossChainRoutePair>, SdkError> {
488 self.ensure_enabled()?;
489 let filter = &filter.normalized();
490 let mut all_routes = Vec::new();
491 for svc in self.values() {
492 match svc.get_routes(filter).await {
493 Ok(routes) => all_routes.extend(routes),
494 Err(e) => tracing::warn!("Cross-chain provider route fetch failed: {e}"),
495 }
496 }
497
498 all_routes.retain(|r| is_usd_stable_asset(&r.asset));
500
501 all_routes.sort_by(|a, b| {
502 a.asset
503 .cmp(&b.asset)
504 .then_with(|| a.chain.cmp(&b.chain))
505 .then_with(|| a.provider.cmp(&b.provider))
506 });
507 Ok(all_routes)
508 }
509
510 pub fn fiat_service(&self) -> &Arc<dyn FiatService> {
513 &self.fiat_service
514 }
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
521#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
522pub enum CrossChainProviderContext {
523 Orchestra {
524 quote_id: String,
526 deposit_address: String,
528 #[serde(default)]
530 deposit_amount: u128,
531 },
532 Boltz {
533 swap_id: String,
535 invoice: String,
537 #[serde(default)]
539 invoice_amount_sats: u64,
540 max_slippage_bps: u32,
542 },
543}
544
545#[derive(Debug, Clone)]
549pub(crate) struct CrossChainReceivePrepared {
550 pub payment_request: String,
552 pub info: CrossChainReceiveInfo,
553 pub quote_read_token: Option<String>,
555}
556
557#[derive(Debug, Clone, Serialize, Deserialize)]
560#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
561pub struct CrossChainReceiveInfo {
562 pub quote_id: String,
565 pub deposit_address: String,
568 pub deposit_amount: u128,
573 pub expected_received_amount: u128,
580 pub destination_asset: String,
585 pub token_identifier: Option<String>,
588 pub service_fee_amount: u128,
591 pub service_fee_asset: Option<String>,
594 pub service_fee_asset_decimals: Option<u32>,
597 pub expires_at: u64,
599}
600
601#[derive(Debug, Clone)]
604pub(crate) struct CrossChainSendPrepared {
605 pub amount_in: u128,
606 pub asset_amount_in: u128,
610 pub estimated_out: u128,
612 pub fee_amount: u128,
618 pub service_fee_amount: u128,
621 pub service_fee_asset: Option<String>,
623 pub service_fee_asset_decimals: Option<u32>,
625 pub source_transfer_fee_sats: u64,
635 pub fee_mode: CrossChainFeeMode,
638 pub expires_at: String,
639 pub pair: CrossChainRoutePair,
640 pub recipient_address: String,
641 pub token_identifier: Option<String>,
643 pub provider_context: CrossChainProviderContext,
645 pub quote_read_token: Option<String>,
647}
648
649#[allow(clippy::too_many_arguments)]
654#[macros::async_trait]
655pub(crate) trait CrossChainService: Send + Sync {
656 async fn get_routes(
662 &self,
663 filter: &CrossChainRouteFilter,
664 ) -> Result<Vec<CrossChainRoutePair>, SdkError>;
665
666 #[allow(clippy::too_many_arguments)]
674 async fn prepare_send(
675 &self,
676 recipient_address: &str,
677 route: &CrossChainRoutePair,
678 amount: u128,
679 delivery_method: Option<DeliveryMethod>,
680 source_token_identifier: Option<String>,
681 max_slippage_bps: u32,
682 fee_mode: CrossChainFeeMode,
683 ) -> Result<CrossChainSendPrepared, SdkError>;
684
685 #[allow(clippy::too_many_arguments)]
705 async fn prepare_receive(
706 &self,
707 route: &CrossChainRoutePair,
708 recipient_address: &str,
709 amount: u128,
710 max_slippage_bps: u32,
711 destination: &SparkAsset,
715 fee_mode: CrossChainFeeMode,
716 target_overpay_bps: u32,
717 delivery_method: DeliveryMethod,
718 refund_address: Option<&str>,
719 ) -> Result<CrossChainReceivePrepared, SdkError>;
720
721 async fn send(
737 &self,
738 prepared: &CrossChainSendPrepared,
739 idempotency_key: Option<String>,
740 ) -> Result<crate::Payment, SdkError>;
741}
742
743pub(crate) async fn fetch_btc_usd_rate(fiat: &dyn FiatService) -> Result<f64, SdkError> {
746 let rates = fiat
747 .fetch_fiat_rates()
748 .await
749 .map_err(|e| SdkError::Generic(format!("Cross-chain: failed to fetch fiat rates: {e}")))?;
750 let btc_usd = rates
751 .iter()
752 .find(|r| r.coin.eq_ignore_ascii_case("USD"))
753 .map(|r| r.value)
754 .ok_or_else(|| {
755 SdkError::Generic("Cross-chain: BTC/USD rate not found in feed".to_string())
756 })?;
757 if !btc_usd.is_finite() || btc_usd <= 0.0 {
758 return Err(SdkError::Generic(format!(
759 "Cross-chain: invalid BTC/USD rate from feed: {btc_usd}"
760 )));
761 }
762 Ok(btc_usd)
763}
764
765#[allow(
768 clippy::cast_precision_loss,
769 clippy::cast_possible_truncation,
770 clippy::cast_sign_loss
771)]
772pub(crate) fn convert_sats_to_destination_amount(
773 sats: u128,
774 fiat_rate: f64,
775 dest_decimals: u32,
776) -> Result<u128, SdkError> {
777 let dest_scale = 10f64.powi(i32::try_from(dest_decimals).unwrap_or(i32::MAX));
778 let target = (sats as f64) * fiat_rate * dest_scale / 100_000_000f64;
779 if !target.is_finite() || target < 0.0 {
780 return Err(SdkError::Generic(format!(
781 "Cross-chain: invalid sats→dest conversion result: {target}"
782 )));
783 }
784 Ok(target as u128)
785}
786
787#[allow(
791 clippy::cast_precision_loss,
792 clippy::cast_possible_truncation,
793 clippy::cast_sign_loss
794)]
795pub(crate) fn convert_source_amount_to_sats(
796 src_base_units: u128,
797 src_decimals: u32,
798 fiat_per_btc: f64,
799) -> Result<u128, SdkError> {
800 let src_scale = 10f64.powi(i32::try_from(src_decimals).unwrap_or(i32::MAX));
801 let sats = (src_base_units as f64) * 100_000_000f64 / (src_scale * fiat_per_btc);
802 if !sats.is_finite() || sats < 0.0 {
803 return Err(SdkError::Generic(format!(
804 "Cross-chain: invalid stable→sats conversion result: {sats}"
805 )));
806 }
807 Ok(sats as u128)
808}
809
810pub(crate) fn ensure_route_delivers_over(
813 route: &CrossChainRoutePair,
814 delivery_method: DeliveryMethod,
815) -> Result<(), SdkError> {
816 if !route.delivery_methods.is_empty() && !route.delivery_methods.contains(&delivery_method) {
817 return Err(SdkError::InvalidInput(format!(
818 "The selected route doesn't support {delivery_method}"
819 )));
820 }
821 Ok(())
822}
823
824pub(crate) fn is_usd_stable_asset(asset: &str) -> bool {
825 USD_STABLE_ASSETS
826 .iter()
827 .any(|a| asset.eq_ignore_ascii_case(a))
828}
829
830pub(crate) fn build_receive_payment_request(
837 deposit_address: &str,
838 chain: &str,
839 chain_id: Option<&str>,
840 contract_address: Option<&str>,
841 amount: u128,
842) -> Result<String, SdkError> {
843 let family =
844 breez_sdk_common::input::detect_address_family(deposit_address).ok_or_else(|| {
845 SdkError::Generic(format!(
846 "Cross-chain provider returned unrecognised deposit address: {deposit_address}",
847 ))
848 })?;
849 if !family.matches_chain(chain, contract_address) {
852 return Err(SdkError::Generic(format!(
853 "Cross-chain provider returned {family:?} deposit address for {chain} route"
854 )));
855 }
856 Ok(breez_sdk_common::input::format_cross_chain_uri(
857 family,
858 deposit_address,
859 contract_address,
860 chain_id,
861 amount,
862 ))
863}
864
865pub(crate) fn compute_terminal_fee_amount(
869 new_status: &crate::ConversionStatus,
870 asset_amount_in: Option<u128>,
871 delivered_amount: Option<u128>,
872 prepare_estimate: Option<u128>,
873) -> Option<u128> {
874 match (new_status, asset_amount_in, delivered_amount) {
875 (crate::ConversionStatus::Completed, Some(a), Some(d)) => Some(a.saturating_sub(d)),
876 _ => prepare_estimate,
877 }
878}
879
880pub(crate) fn rescale_decimals(
884 amount: u128,
885 src_decimals: u32,
886 dest_decimals: u32,
887) -> Result<u128, SdkError> {
888 if dest_decimals >= src_decimals {
889 let delta = dest_decimals.saturating_sub(src_decimals);
890 let factor = 10u128
891 .checked_pow(delta)
892 .ok_or_else(|| SdkError::Generic("Cross-chain: decimal scale overflow".to_string()))?;
893 amount
894 .checked_mul(factor)
895 .ok_or_else(|| SdkError::Generic("Cross-chain: decimal rescale overflow".to_string()))
896 } else {
897 let delta = src_decimals.saturating_sub(dest_decimals);
898 let factor = 10u128
899 .checked_pow(delta)
900 .ok_or_else(|| SdkError::Generic("Cross-chain: decimal scale overflow".to_string()))?;
901 amount.checked_div(factor).ok_or_else(|| {
902 SdkError::Generic("Cross-chain: decimal rescale divisor zero".to_string())
903 })
904 }
905}
906
907#[allow(
911 clippy::cast_precision_loss,
912 clippy::cast_possible_truncation,
913 clippy::cast_sign_loss
914)]
915pub(crate) fn convert_destination_amount_to_sats(
916 destination_amount: u128,
917 fiat_rate: f64,
918 dest_decimals: u32,
919) -> Result<u128, SdkError> {
920 if !fiat_rate.is_finite() || fiat_rate <= 0.0 {
921 return Err(SdkError::Generic(format!(
922 "Cross-chain: invalid BTC/USD rate for inversion: {fiat_rate}"
923 )));
924 }
925 let dest_scale = 10f64.powi(i32::try_from(dest_decimals).unwrap_or(i32::MAX));
926 let sats = (destination_amount as f64) * 100_000_000f64 / (fiat_rate * dest_scale);
927 if !sats.is_finite() || sats < 0.0 {
928 return Err(SdkError::Generic(format!(
929 "Cross-chain: invalid dest→sats conversion result: {sats}"
930 )));
931 }
932 Ok(sats as u128)
933}
934
935pub(crate) fn resolve_target_overpay_bps(
941 requested: Option<u32>,
942 config_default: Option<u32>,
943) -> Result<u32, SdkError> {
944 if let Some(bps) = requested
945 && !(MIN_TARGET_OVERPAY_BPS..=MAX_TARGET_OVERPAY_BPS).contains(&bps)
946 {
947 return Err(SdkError::InvalidInput(format!(
948 "target_overpay_bps {bps} must be in \
949 {MIN_TARGET_OVERPAY_BPS} to {MAX_TARGET_OVERPAY_BPS}",
950 )));
951 }
952 Ok(requested
953 .or(config_default)
954 .unwrap_or(DEFAULT_TARGET_OVERPAY_BPS))
955}
956
957pub(crate) fn inflate_target_amount(amount: u128, overpay_bps: u32) -> u128 {
962 if overpay_bps == 0 {
963 return amount;
964 }
965 amount.saturating_add(amount.saturating_mul(u128::from(overpay_bps)) / 10_000)
966}
967
968#[cfg(test)]
969mod tests {
970 use super::*;
971 use macros::test_all;
972
973 #[cfg(feature = "browser-tests")]
974 wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
975
976 struct NoFiat;
977
978 #[macros::async_trait]
979 impl FiatService for NoFiat {
980 async fn fetch_fiat_currencies(
981 &self,
982 ) -> Result<
983 Vec<breez_sdk_common::fiat::FiatCurrency>,
984 breez_sdk_common::error::ServiceConnectivityError,
985 > {
986 Ok(Vec::new())
987 }
988
989 async fn fetch_fiat_rates(
990 &self,
991 ) -> Result<
992 Vec<breez_sdk_common::fiat::Rate>,
993 breez_sdk_common::error::ServiceConnectivityError,
994 > {
995 Ok(Vec::new())
996 }
997 }
998
999 struct StubProvider;
1000
1001 #[macros::async_trait]
1002 impl CrossChainService for StubProvider {
1003 async fn get_routes(
1004 &self,
1005 _filter: &CrossChainRouteFilter,
1006 ) -> Result<Vec<CrossChainRoutePair>, SdkError> {
1007 unimplemented!()
1008 }
1009
1010 async fn prepare_send(
1011 &self,
1012 _recipient_address: &str,
1013 _route: &CrossChainRoutePair,
1014 _amount: u128,
1015 _delivery_method: Option<DeliveryMethod>,
1016 _source_token_identifier: Option<String>,
1017 _max_slippage_bps: u32,
1018 _fee_mode: CrossChainFeeMode,
1019 ) -> Result<CrossChainSendPrepared, SdkError> {
1020 unimplemented!()
1021 }
1022
1023 async fn prepare_receive(
1024 &self,
1025 _route: &CrossChainRoutePair,
1026 _recipient_address: &str,
1027 _amount: u128,
1028 _max_slippage_bps: u32,
1029 _destination: &SparkAsset,
1030 _fee_mode: CrossChainFeeMode,
1031 _target_overpay_bps: u32,
1032 _delivery_method: DeliveryMethod,
1033 _refund_address: Option<&str>,
1034 ) -> Result<CrossChainReceivePrepared, SdkError> {
1035 unimplemented!()
1036 }
1037
1038 async fn send(
1039 &self,
1040 _prepared: &CrossChainSendPrepared,
1041 _idempotency_key: Option<String>,
1042 ) -> Result<crate::Payment, SdkError> {
1043 unimplemented!()
1044 }
1045 }
1046
1047 fn evm_address_details() -> crate::CrossChainAddressDetails {
1048 crate::CrossChainAddressDetails {
1049 address: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e".to_string(),
1050 address_family: crate::CrossChainAddressFamily::Evm,
1051 contract_address: None,
1052 chain_id: None,
1053 amount: None,
1054 }
1055 }
1056
1057 #[test_all]
1058 fn empty_context_reports_cross_chain_disabled() {
1059 let context = CrossChainContext::new(Arc::new(NoFiat));
1060 assert!(matches!(
1061 context.ensure_enabled(),
1062 Err(SdkError::CrossChainDisabled { .. })
1063 ));
1064 assert!(matches!(
1065 context.get(CrossChainProvider::Orchestra),
1066 Err(SdkError::CrossChainDisabled { .. })
1067 ));
1068 }
1069
1070 #[test_all]
1071 fn enabled_context_reports_missing_provider() {
1072 let mut context = CrossChainContext::new(Arc::new(NoFiat));
1073 context.insert(CrossChainProvider::Orchestra, Arc::new(StubProvider));
1074 assert!(context.ensure_enabled().is_ok());
1075 assert!(context.get(CrossChainProvider::Orchestra).is_ok());
1076 assert!(matches!(
1077 context.get(CrossChainProvider::Boltz),
1078 Err(SdkError::InvalidInput(_))
1079 ));
1080 }
1081
1082 #[test_all]
1083 fn route_filter_normalizes_payment_link_to_lightning_send() {
1084 let filter = CrossChainRouteFilter::PaymentLink {
1085 address_details: evm_address_details(),
1086 };
1087 let CrossChainRouteFilter::Send {
1088 address_details,
1089 delivery_method,
1090 } = filter.normalized()
1091 else {
1092 panic!("expected a send filter");
1093 };
1094 assert_eq!(address_details.address, evm_address_details().address);
1095 assert_eq!(delivery_method, Some(DeliveryMethod::Lightning));
1096 }
1097
1098 #[test_all]
1099 fn ensure_route_delivers_over_checks_listed_methods() {
1100 let route = |delivery_methods: Vec<DeliveryMethod>| CrossChainRoutePair {
1101 provider: CrossChainProvider::Orchestra,
1102 chain: "base".to_string(),
1103 chain_id: None,
1104 asset: "USDC".to_string(),
1105 contract_address: None,
1106 decimals: 6,
1107 exact_out_eligible: false,
1108 accepted_assets: Vec::new(),
1109 delivery_methods,
1110 };
1111 let spark = route(vec![DeliveryMethod::Spark]);
1112 let lightning = route(vec![DeliveryMethod::Lightning]);
1113 let unlisted = route(Vec::new());
1114
1115 assert!(ensure_route_delivers_over(&spark, DeliveryMethod::Spark).is_ok());
1116 assert!(matches!(
1117 ensure_route_delivers_over(&lightning, DeliveryMethod::Spark),
1118 Err(SdkError::InvalidInput(_))
1119 ));
1120 assert!(ensure_route_delivers_over(&lightning, DeliveryMethod::Lightning).is_ok());
1121 assert!(ensure_route_delivers_over(&unlisted, DeliveryMethod::Spark).is_ok());
1122 }
1123
1124 #[test_all]
1125 fn delivery_method_display_is_human_readable() {
1126 assert_eq!(DeliveryMethod::Spark.to_string(), "Spark");
1127 assert_eq!(DeliveryMethod::Lightning.to_string(), "Lightning");
1128 assert_eq!(DeliveryMethod::Bitcoin.to_string(), "Bitcoin");
1129 }
1130
1131 #[test_all]
1132 fn derive_btc_leg_transfer_id_uses_caller_key() {
1133 let key = "00000000-0000-4000-8000-000000000001";
1136 let id = derive_btc_leg_transfer_id(Some(key), "ignored-seed").unwrap();
1137 assert_eq!(id.to_string(), key);
1138 }
1139
1140 #[test_all]
1141 fn derive_btc_leg_transfer_id_deterministic_from_seed() {
1142 let a = derive_btc_leg_transfer_id(None, "cross_chain:orchestra:quote-1").unwrap();
1143 let b = derive_btc_leg_transfer_id(None, "cross_chain:orchestra:quote-1").unwrap();
1144 assert_eq!(
1145 a, b,
1146 "same seed must produce the same TransferId across calls"
1147 );
1148 }
1149
1150 #[test_all]
1151 fn derive_btc_leg_transfer_id_distinct_seeds_yield_distinct_ids() {
1152 let a = derive_btc_leg_transfer_id(None, "cross_chain:orchestra:quote-1").unwrap();
1153 let b = derive_btc_leg_transfer_id(None, "cross_chain:orchestra:quote-2").unwrap();
1154 assert_ne!(a, b);
1155 }
1156
1157 #[test_all]
1158 fn derive_btc_leg_transfer_id_orchestra_and_boltz_seeds_collide_only_on_id() {
1159 let orchestra = derive_btc_leg_transfer_id(None, "cross_chain:orchestra:abc").unwrap();
1162 let boltz = derive_btc_leg_transfer_id(None, "cross_chain:boltz:abc").unwrap();
1163 assert_ne!(orchestra, boltz);
1164 }
1165
1166 #[test_all]
1167 fn derive_btc_leg_transfer_id_rejects_invalid_caller_key() {
1168 let err = derive_btc_leg_transfer_id(Some("not-a-uuid"), "fallback").unwrap_err();
1169 assert!(matches!(err, SdkError::Generic(_)));
1170 }
1171
1172 #[test_all]
1173 fn convert_sats_to_destination_amount_round_trip_inverts_to_sats() {
1174 let dest = convert_sats_to_destination_amount(10_000, 60_000.0, 6).unwrap();
1176 assert_eq!(dest, 6_000_000);
1177 let sats = convert_destination_amount_to_sats(dest, 60_000.0, 6).unwrap();
1179 assert_eq!(sats, 10_000);
1180 }
1181
1182 #[test_all]
1183 fn convert_destination_amount_to_sats_typical_stable() {
1184 let sats = convert_destination_amount_to_sats(1_000_000, 60_000.0, 6).unwrap();
1186 assert_eq!(sats, 1_666);
1187 }
1188
1189 #[test_all]
1190 fn convert_destination_amount_to_sats_zero_passes_through() {
1191 let sats = convert_destination_amount_to_sats(0, 60_000.0, 6).unwrap();
1192 assert_eq!(sats, 0);
1193 }
1194
1195 #[test_all]
1196 fn convert_destination_amount_to_sats_rejects_non_positive_rate() {
1197 let err = convert_destination_amount_to_sats(1_000_000, 0.0, 6).unwrap_err();
1198 assert!(matches!(err, SdkError::Generic(ref m) if m.contains("invalid BTC/USD rate")));
1199 let err = convert_destination_amount_to_sats(1_000_000, f64::NAN, 6).unwrap_err();
1200 assert!(matches!(err, SdkError::Generic(_)));
1201 }
1202
1203 #[test_all]
1204 fn rescale_decimals_scales_down_when_dest_decimals_lower() {
1205 assert_eq!(rescale_decimals(100_000_000, 8, 6).unwrap(), 1_000_000);
1206 }
1207
1208 #[test_all]
1209 fn rescale_decimals_same_decimals_is_identity() {
1210 assert_eq!(rescale_decimals(123_456_789, 6, 6).unwrap(), 123_456_789);
1211 }
1212
1213 #[test_all]
1214 fn rescale_decimals_scales_up_when_dest_decimals_higher() {
1215 assert_eq!(rescale_decimals(1_000_000, 6, 8).unwrap(), 100_000_000);
1216 }
1217
1218 #[test_all]
1219 fn rescale_decimals_zero_passes_through() {
1220 assert_eq!(rescale_decimals(0, 8, 6).unwrap(), 0);
1221 assert_eq!(rescale_decimals(0, 6, 8).unwrap(), 0);
1222 }
1223
1224 #[test_all]
1225 fn is_usd_stable_asset_recognizes_known_stables() {
1226 for ticker in ["USDB", "USDC", "USDT", "USDT0", "usdb", "uSdC"] {
1227 assert!(is_usd_stable_asset(ticker), "{ticker} should be stable");
1228 }
1229 }
1230
1231 #[test_all]
1232 fn is_usd_stable_asset_rejects_btc_and_unknown() {
1233 for ticker in ["BTC", "ETH", "DAI", "", "USD"] {
1234 assert!(
1235 !is_usd_stable_asset(ticker),
1236 "{ticker} should not be a recognized USD-stable"
1237 );
1238 }
1239 }
1240
1241 #[test_all]
1244 fn compute_terminal_fee_overwrites_estimate_on_completed() {
1245 let realized = compute_terminal_fee_amount(
1246 &crate::ConversionStatus::Completed,
1247 Some(1_020_434), Some(997_498), Some(20_434), );
1251 assert_eq!(realized, Some(22_936), "= asset_amount_in − delivered");
1252 }
1253
1254 #[test_all]
1255 fn compute_terminal_fee_keeps_estimate_on_refunded() {
1256 let realized = compute_terminal_fee_amount(
1260 &crate::ConversionStatus::Refunded,
1261 Some(1_020_434),
1262 None,
1263 Some(20_434),
1264 );
1265 assert_eq!(realized, Some(20_434));
1266 }
1267
1268 #[test_all]
1269 fn compute_terminal_fee_keeps_estimate_on_failed() {
1270 let realized = compute_terminal_fee_amount(
1271 &crate::ConversionStatus::Failed,
1272 Some(1_020_434),
1273 None,
1274 Some(20_434),
1275 );
1276 assert_eq!(realized, Some(20_434));
1277 }
1278
1279 #[test_all]
1280 fn compute_terminal_fee_keeps_estimate_when_asset_amount_in_missing() {
1281 let realized = compute_terminal_fee_amount(
1284 &crate::ConversionStatus::Completed,
1285 None, Some(997_498),
1287 Some(20_434),
1288 );
1289 assert_eq!(realized, Some(20_434));
1290 }
1291
1292 #[test_all]
1293 fn compute_terminal_fee_keeps_estimate_when_delivered_amount_missing() {
1294 let realized = compute_terminal_fee_amount(
1297 &crate::ConversionStatus::Completed,
1298 Some(1_020_434),
1299 None, Some(20_434),
1301 );
1302 assert_eq!(realized, Some(20_434));
1303 }
1304
1305 #[test_all]
1306 fn compute_terminal_fee_saturating_sub_on_over_delivery() {
1307 let realized = compute_terminal_fee_amount(
1309 &crate::ConversionStatus::Completed,
1310 Some(1_000_000),
1311 Some(1_005_000),
1312 Some(0),
1313 );
1314 assert_eq!(
1315 realized,
1316 Some(0),
1317 "saturating_sub must clamp at 0, not underflow"
1318 );
1319 }
1320
1321 #[test_all]
1331 fn boltz_provider_context_invoice_amount_sats_is_independent_of_amount_in() {
1332 let ctx = CrossChainProviderContext::Boltz {
1333 swap_id: "swap_1".to_string(),
1334 invoice: "lnbc19090n1pexample".to_string(),
1335 invoice_amount_sats: 1_909,
1336 max_slippage_bps: 100,
1337 };
1338 let json = serde_json::to_string(&ctx).unwrap();
1339 let decoded: CrossChainProviderContext = serde_json::from_str(&json).unwrap();
1340 let CrossChainProviderContext::Boltz {
1341 invoice_amount_sats,
1342 ..
1343 } = &decoded
1344 else {
1345 panic!("expected Boltz variant");
1346 };
1347 assert_eq!(*invoice_amount_sats, 1_909);
1348 assert!(
1349 *invoice_amount_sats != 1_222_703,
1350 "the LN invoice sats must never be conflated with a user-facing display value (e.g. USDB base units)"
1351 );
1352 }
1353
1354 #[test_all]
1359 fn boltz_provider_context_legacy_row_without_invoice_amount_sats_defaults_to_zero() {
1360 let legacy = r#"{
1361 "Boltz": {
1362 "swap_id": "swap_legacy",
1363 "invoice": "lnbc19090n1p",
1364 "max_slippage_bps": 100
1365 }
1366 }"#;
1367 let decoded: CrossChainProviderContext = serde_json::from_str(legacy).unwrap();
1368 let CrossChainProviderContext::Boltz {
1369 invoice_amount_sats,
1370 ..
1371 } = &decoded
1372 else {
1373 panic!("expected Boltz variant");
1374 };
1375 assert_eq!(*invoice_amount_sats, 0);
1376 }
1377
1378 #[test_all]
1382 fn orchestra_provider_context_deposit_amount_is_independent_of_amount_in() {
1383 let ctx = CrossChainProviderContext::Orchestra {
1384 quote_id: "q_1".to_string(),
1385 deposit_address: "spark1...".to_string(),
1386 deposit_amount: 1_020_434,
1387 };
1388 let json = serde_json::to_string(&ctx).unwrap();
1389 let decoded: CrossChainProviderContext = serde_json::from_str(&json).unwrap();
1390 let CrossChainProviderContext::Orchestra { deposit_amount, .. } = &decoded else {
1391 panic!("expected Orchestra variant");
1392 };
1393 assert_eq!(*deposit_amount, 1_020_434);
1394 }
1395
1396 fn boltz_info(swap_id: &str) -> ConversionInfo {
1397 ConversionInfo::Boltz {
1398 swap_id: swap_id.to_string(),
1399 invoice: "lnbc1".to_string(),
1400 invoice_amount_sats: 1_000,
1401 bridge_ref: None,
1402 max_slippage_bps: 100,
1403 quote_degraded: false,
1404 chain: "polygon".to_string(),
1405 chain_id: None,
1406 asset: "USDC".to_string(),
1407 recipient_address: "0xabc".to_string(),
1408 estimated_out: 1_000_000,
1409 delivered_amount: None,
1410 status: crate::ConversionStatus::Pending,
1411 asset_amount_in: None,
1412 fee_amount: None,
1413 service_fee_amount: None,
1414 service_fee_asset: None,
1415 asset_decimals: 6,
1416 asset_contract: None,
1417 }
1418 }
1419
1420 #[test_all]
1421 fn payment_with_conversion_info_injects_into_lightning_details() {
1422 let payment = crate::Payment {
1423 id: "p1".to_string(),
1424 payment_type: crate::PaymentType::Send,
1425 status: crate::PaymentStatus::Pending,
1426 amount: 1_000,
1427 fees: 0,
1428 timestamp: 100,
1429 method: crate::PaymentMethod::Lightning,
1430 details: Some(PaymentDetails::Lightning {
1431 description: Some("desc".to_string()),
1432 invoice: "lnbc1".to_string(),
1433 destination_pubkey: "02aa".to_string(),
1434 htlc_details: crate::SparkHtlcDetails {
1435 payment_hash: "hash1".to_string(),
1436 preimage: None,
1437 expiry_time: 0,
1438 status: crate::SparkHtlcStatus::PreimageShared,
1439 },
1440 lnurl_pay_info: None,
1441 lnurl_withdraw_info: None,
1442 lnurl_receive_metadata: None,
1443 conversion_info: None,
1444 }),
1445 conversion_details: None,
1446 };
1447
1448 let out = payment_with_conversion_info(payment, Some(boltz_info("swap1")));
1449
1450 assert_eq!(out.status, crate::PaymentStatus::Pending);
1451 let Some(PaymentDetails::Lightning {
1452 invoice,
1453 description,
1454 conversion_info,
1455 ..
1456 }) = out.details
1457 else {
1458 panic!("expected Lightning details");
1459 };
1460 assert_eq!(invoice, "lnbc1");
1462 assert_eq!(description.as_deref(), Some("desc"));
1463 assert!(matches!(
1464 conversion_info,
1465 Some(ConversionInfo::Boltz { ref swap_id, .. }) if swap_id == "swap1"
1466 ));
1467 }
1468
1469 #[test_all]
1470 fn payment_with_conversion_info_passes_through_variants_without_a_slot() {
1471 let payment = crate::Payment {
1472 id: "p1".to_string(),
1473 payment_type: crate::PaymentType::Send,
1474 status: crate::PaymentStatus::Completed,
1475 amount: 1_000,
1476 fees: 0,
1477 timestamp: 100,
1478 method: crate::PaymentMethod::Withdraw,
1479 details: Some(PaymentDetails::Withdraw {
1480 tx_id: "tx1".to_string(),
1481 vout: 0,
1482 destination_address: "bcrt1p_destination".to_string(),
1483 }),
1484 conversion_details: None,
1485 };
1486
1487 let out = payment_with_conversion_info(payment, Some(boltz_info("swap1")));
1488
1489 assert!(matches!(
1490 out.details,
1491 Some(PaymentDetails::Withdraw { tx_id, .. }) if tx_id == "tx1"
1492 ));
1493 }
1494
1495 #[test_all]
1498 fn resolve_target_overpay_uses_request_when_in_range() {
1499 assert_eq!(resolve_target_overpay_bps(Some(50), Some(75)).unwrap(), 50);
1500 }
1501
1502 #[test_all]
1503 fn resolve_target_overpay_falls_back_to_config_default() {
1504 assert_eq!(resolve_target_overpay_bps(None, Some(75)).unwrap(), 75);
1505 }
1506
1507 #[test_all]
1508 fn resolve_target_overpay_falls_back_to_built_in_default() {
1509 assert_eq!(
1510 resolve_target_overpay_bps(None, None).unwrap(),
1511 DEFAULT_TARGET_OVERPAY_BPS
1512 );
1513 }
1514
1515 #[test_all]
1516 fn resolve_target_overpay_request_zero_opts_out() {
1517 assert_eq!(resolve_target_overpay_bps(Some(0), Some(50)).unwrap(), 0);
1518 }
1519
1520 #[test_all]
1521 fn resolve_target_overpay_rejects_out_of_range_request() {
1522 let too_high = MAX_TARGET_OVERPAY_BPS + 1;
1523 assert!(matches!(
1524 resolve_target_overpay_bps(Some(too_high), None),
1525 Err(SdkError::InvalidInput(_))
1526 ));
1527 }
1528
1529 #[test_all]
1532 fn inflate_target_amount_zero_bps_is_identity() {
1533 assert_eq!(inflate_target_amount(1_000_000, 0), 1_000_000);
1534 }
1535
1536 #[test_all]
1537 fn inflate_target_amount_applies_bps_pad() {
1538 assert_eq!(inflate_target_amount(1_000_000, 25), 1_002_500);
1540 }
1541
1542 #[test_all]
1543 fn inflate_target_amount_truncates_sub_unit_pad() {
1544 assert_eq!(inflate_target_amount(100, 25), 100);
1546 }
1547
1548 #[test_all]
1551 fn convert_stable_to_sats_at_par_6dp() {
1552 assert_eq!(
1554 convert_source_amount_to_sats(1_000_000, 6, 100_000.0).unwrap(),
1555 1000
1556 );
1557 }
1558
1559 #[test_all]
1560 fn convert_stable_to_sats_at_a_different_rate() {
1561 assert_eq!(
1563 convert_source_amount_to_sats(1_000_000, 6, 50_000.0).unwrap(),
1564 2000
1565 );
1566 }
1567
1568 #[test_all]
1569 fn convert_stable_to_sats_matches_across_decimals_at_same_usd_value() {
1570 let sats_6 = convert_source_amount_to_sats(1_000_000, 6, 100_000.0).unwrap();
1572 let sats_18 =
1573 convert_source_amount_to_sats(1_000_000_000_000_000_000, 18, 100_000.0).unwrap();
1574 assert_eq!(sats_6, sats_18);
1575 assert_eq!(sats_6, 1000);
1576 }
1577
1578 #[test_all]
1579 fn convert_stable_to_sats_zero_input_is_zero() {
1580 assert_eq!(convert_source_amount_to_sats(0, 6, 100_000.0).unwrap(), 0);
1581 }
1582
1583 #[test_all]
1584 fn convert_stable_to_sats_rejects_nan_rate() {
1585 assert!(matches!(
1588 convert_source_amount_to_sats(1_000_000, 6, f64::NAN),
1589 Err(SdkError::Generic(_))
1590 ));
1591 }
1592
1593 #[test_all]
1594 fn convert_stable_to_sats_rejects_negative_rate() {
1595 assert!(matches!(
1596 convert_source_amount_to_sats(1_000_000, 6, -100_000.0),
1597 Err(SdkError::Generic(_))
1598 ));
1599 }
1600
1601 #[test_all]
1606 fn build_receive_payment_request_evm_emits_eip_681_uri() {
1607 let uri = build_receive_payment_request(
1608 "0x00Df20df75800ca8f40080505a7a802331C1321c",
1609 "arbitrum",
1610 Some("42161"),
1611 Some("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"),
1612 1_000_000,
1613 )
1614 .unwrap();
1615 assert!(uri.starts_with("ethereum:"), "got {uri}");
1616 assert!(uri.contains("42161"), "chain_id must appear: {uri}");
1617 assert!(
1618 uri.contains("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"),
1619 "token contract must appear: {uri}"
1620 );
1621 assert!(uri.contains("1000000"), "amount must appear: {uri}");
1622 }
1623
1624 #[test_all]
1627 fn build_receive_payment_request_solana_returns_bare_address() {
1628 let addr = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
1629 let out = build_receive_payment_request(addr, "solana", None, None, 1_000_000).unwrap();
1630 assert_eq!(out, addr);
1631 }
1632
1633 #[test_all]
1635 fn build_receive_payment_request_tron_returns_bare_address() {
1636 let addr = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
1637 let out = build_receive_payment_request(addr, "tron", None, None, 1_000_000).unwrap();
1638 assert_eq!(out, addr);
1639 }
1640
1641 #[test_all]
1644 fn build_receive_payment_request_rejects_unrecognized_address() {
1645 let err =
1646 build_receive_payment_request("not-an-address", "arbitrum", None, None, 1_000_000)
1647 .unwrap_err();
1648 assert!(matches!(err, SdkError::Generic(_)));
1649 }
1650
1651 #[test_all]
1655 fn build_receive_payment_request_rejects_family_chain_mismatch() {
1656 let evm_addr = "0x00Df20df75800ca8f40080505a7a802331C1321c";
1657 let err =
1658 build_receive_payment_request(evm_addr, "solana", None, None, 1_000_000).unwrap_err();
1659 match err {
1660 SdkError::Generic(msg) => {
1661 assert!(
1662 msg.contains("Evm") && msg.contains("solana"),
1663 "unexpected message: {msg}"
1664 );
1665 }
1666 other => panic!("expected Generic mismatch error, got {other:?}"),
1667 }
1668
1669 let solana_addr = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
1670 assert!(
1671 build_receive_payment_request(solana_addr, "tron", None, None, 1_000_000).is_err(),
1672 "solana address must not be accepted for tron route",
1673 );
1674 }
1675
1676 #[cfg(feature = "sqlite")]
1677 mod receive_matching {
1678 use super::*;
1679 use crate::{
1680 PaymentDetails, PaymentMethod, PaymentStatus, PaymentTokenMetadata, PaymentType,
1681 SparkInvoicePaymentDetails, TokenTransactionType,
1682 };
1683
1684 fn sqlite_storage() -> Arc<dyn crate::Storage> {
1685 let mut dir = std::env::temp_dir();
1686 dir.push(format!(
1687 "breez-xchain-receive-match-{}",
1688 uuid::Uuid::new_v4()
1689 ));
1690 std::fs::create_dir_all(&dir).unwrap();
1691 Arc::new(crate::SqliteStorage::new(&dir).unwrap())
1692 }
1693
1694 async fn storage_with_open_receive(invoice: &str) -> Arc<dyn crate::Storage> {
1695 let storage = sqlite_storage();
1696 let data = orchestra::storage_adapter::OrchestraSwapData {
1697 quote_id: "q_match".to_string(),
1698 order_id: None,
1699 read_token: None,
1700 quote_read_token: None,
1701 recipient_address: "sp1rcv".to_string(),
1702 spark_invoice: Some(invoice.to_string()),
1703 paid: false,
1704 source_chain: "arbitrum".to_string(),
1705 source_asset: "USDC".to_string(),
1706 source_chain_id: Some("42161".to_string()),
1707 source_contract_address: Some("0xUSDC".to_string()),
1708 source_decimals: 6,
1709 destination_chain: "spark".to_string(),
1710 destination_asset: "BTC".to_string(),
1711 destination_decimals: 8,
1712 token_identifier: None,
1713 amount_in: "1000000".to_string(),
1714 expected_amount_out: "1146".to_string(),
1715 fee_amount: Some("10000".to_string()),
1716 fee_asset: Some("USDC".to_string()),
1717 fee_asset_decimals: Some(6),
1718 expires_at: 1_700_000_120,
1719 failure: None,
1720 };
1721 orchestra::storage_adapter::OrchestraStorageAdapter::new(Arc::clone(&storage))
1722 .upsert(&data)
1723 .await
1724 .unwrap();
1725 storage
1726 }
1727
1728 fn invoice_details(invoice: &str) -> SparkInvoicePaymentDetails {
1729 SparkInvoicePaymentDetails {
1730 description: None,
1731 invoice: invoice.to_string(),
1732 }
1733 }
1734
1735 fn payment(payment_type: PaymentType, details: PaymentDetails) -> crate::Payment {
1736 crate::Payment {
1737 id: "p1".to_string(),
1738 payment_type,
1739 status: PaymentStatus::Completed,
1740 amount: 1146,
1741 fees: 0,
1742 timestamp: 100,
1743 method: PaymentMethod::Spark,
1744 details: Some(details),
1745 conversion_details: None,
1746 }
1747 }
1748
1749 fn spark_details(invoice: Option<&str>) -> PaymentDetails {
1750 PaymentDetails::Spark {
1751 invoice_details: invoice.map(invoice_details),
1752 htlc_details: None,
1753 conversion_info: None,
1754 }
1755 }
1756
1757 fn token_details(invoice: &str) -> PaymentDetails {
1758 PaymentDetails::Token {
1759 metadata: PaymentTokenMetadata {
1760 identifier: "btkn1usdb".to_string(),
1761 issuer_public_key: "02aa".to_string(),
1762 name: "Bitcoin USD".to_string(),
1763 ticker: "USDB".to_string(),
1764 decimals: 6,
1765 max_supply: 0,
1766 is_freezable: true,
1767 },
1768 tx_hash: "abcd".to_string(),
1769 tx_type: TokenTransactionType::Transfer,
1770 invoice_details: Some(invoice_details(invoice)),
1771 conversion_info: None,
1772 }
1773 }
1774
1775 async fn stored_conversion_status(
1776 storage: &Arc<dyn crate::Storage>,
1777 payment_id: &str,
1778 ) -> Option<crate::ConversionStatus> {
1779 let stored = storage
1780 .get_payment_by_id(payment_id.to_string())
1781 .await
1782 .unwrap();
1783 match extract_conversion_info(stored.details) {
1784 Some(ConversionInfo::Orchestra { status, .. }) => Some(status),
1785 _ => None,
1786 }
1787 }
1788
1789 #[tokio::test]
1790 async fn spark_receive_fulfilling_an_open_invoice_gets_pending_conversion_info() {
1791 let storage = storage_with_open_receive("spark1inv").await;
1792 let payment = payment(PaymentType::Receive, spark_details(Some("spark1inv")));
1793 storage.apply_payment_update(payment.clone()).await.unwrap();
1794
1795 let attached = attach_receive_metadata_for_payment(&storage, &payment)
1796 .await
1797 .unwrap();
1798
1799 assert!(attached);
1800 assert_eq!(
1801 stored_conversion_status(&storage, &payment.id).await,
1802 Some(crate::ConversionStatus::Pending)
1803 );
1804 }
1805
1806 #[tokio::test]
1807 async fn token_receive_fulfilling_an_open_invoice_gets_pending_conversion_info() {
1808 let storage = storage_with_open_receive("spark1inv").await;
1809 let payment = payment(PaymentType::Receive, token_details("spark1inv"));
1810 storage.apply_payment_update(payment.clone()).await.unwrap();
1811
1812 let attached = attach_receive_metadata_for_payment(&storage, &payment)
1813 .await
1814 .unwrap();
1815
1816 assert!(attached);
1817 assert_eq!(
1818 stored_conversion_status(&storage, &payment.id).await,
1819 Some(crate::ConversionStatus::Pending)
1820 );
1821 }
1822
1823 #[tokio::test]
1824 async fn a_payment_already_carrying_a_conversion_is_left_alone() {
1825 let storage = storage_with_open_receive("spark1inv").await;
1826 let payment = payment(PaymentType::Receive, spark_details(Some("spark1inv")));
1827 storage.apply_payment_update(payment.clone()).await.unwrap();
1828 let mut completed = orchestra_receive_info_placeholder();
1829 if let ConversionInfo::Orchestra { status, .. } = &mut completed {
1830 *status = crate::ConversionStatus::Completed;
1831 }
1832 storage
1833 .insert_payment_metadata(
1834 payment.id.clone(),
1835 crate::PaymentMetadata {
1836 conversion_info: Some(completed),
1837 ..Default::default()
1838 },
1839 )
1840 .await
1841 .unwrap();
1842
1843 let attached = attach_receive_metadata_for_payment(&storage, &payment)
1844 .await
1845 .unwrap();
1846
1847 assert!(!attached);
1848 assert_eq!(
1849 stored_conversion_status(&storage, &payment.id).await,
1850 Some(crate::ConversionStatus::Completed)
1851 );
1852 }
1853
1854 #[tokio::test]
1855 async fn other_payments_get_nothing() {
1856 let storage = storage_with_open_receive("spark1inv").await;
1857
1858 for payment in [
1859 payment(PaymentType::Receive, spark_details(Some("spark1other"))),
1860 payment(PaymentType::Receive, spark_details(None)),
1861 payment(PaymentType::Send, spark_details(Some("spark1inv"))),
1862 ] {
1863 let attached = attach_receive_metadata_for_payment(&storage, &payment)
1864 .await
1865 .unwrap();
1866 assert!(!attached, "{payment:?}");
1867 }
1868 }
1869
1870 fn orchestra_receive_info_placeholder() -> ConversionInfo {
1871 ConversionInfo::Orchestra {
1872 order_id: "ord".to_string(),
1873 quote_id: "q_match".to_string(),
1874 read_token: None,
1875 chain: "arbitrum".to_string(),
1876 chain_id: Some("42161".to_string()),
1877 asset: "USDC".to_string(),
1878 recipient_address: "sp1rcv".to_string(),
1879 asset_amount_in: Some(1_000_000),
1880 estimated_out: 1146,
1881 delivered_amount: Some(1146),
1882 external_tx_hash: Some("0xdeposit".to_string()),
1883 refund_tx_hash: None,
1884 status: crate::ConversionStatus::Pending,
1885 fee_amount: Some(10_000),
1886 service_fee_amount: Some(10_000),
1887 service_fee_asset: Some("USDC".to_string()),
1888 service_fee_asset_decimals: Some(6),
1889 asset_decimals: 6,
1890 asset_contract: Some("0xUSDC".to_string()),
1891 }
1892 }
1893 }
1894}