Skip to main content

breez_sdk_spark/cross_chain/
mod.rs

1//! Cross-chain payment providers.
2//!
3//! The [`CrossChainService`] trait abstracts route discovery, quoting, and
4//! sending. Each provider module (e.g. `orchestra`, `boltz`) implements it.
5
6// Boltz is not registered as a provider (see `sdk_builder`): the service is not
7// operational, and it is unclear when or whether it will be again. The modules
8// stay in the tree behind the `boltz` feature so the wiring can be restored in
9// one place.
10#[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
37/// SDK-level bounds for cross-chain slippage.
38pub(crate) const MIN_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 10;
39pub(crate) const MAX_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 500;
40/// Used when neither the request nor [`crate::Config::default_slippage_bps`]
41/// supplies a value.
42pub(crate) const DEFAULT_CROSS_CHAIN_SLIPPAGE_BPS: u32 = 100;
43
44/// Bounds for the target-overpay pad applied to the user's destination amount
45/// on `FeesExcluded` conversion sends. `0` opts out. `500` caps at 5% (matches
46/// the slippage upper bound).
47pub(crate) const MIN_TARGET_OVERPAY_BPS: u32 = 0;
48pub(crate) const MAX_TARGET_OVERPAY_BPS: u32 = 500;
49/// Default pad applied when neither the request nor
50/// [`crate::CrossChainConfig::default_target_overpay_bps`] specifies one.
51/// Calibrated to the observed Orchestra delivery drift. Tune per provider
52/// as real-world data accrues.
53pub(crate) const DEFAULT_TARGET_OVERPAY_BPS: u32 = 15;
54/// Tickers treated as $1-pegged for par-value rescaling. Adding a non-USD
55/// ticker would silently misreport `fee_amount` for routes using it.
56const USD_STABLE_ASSETS: &[&str] = &["USDB", "USDC", "USDT", "USDT0"];
57
58/// Each provider's background monitor interval.
59pub(crate) const MONITOR_INTERVAL: Duration = Duration::from_secs(30);
60
61/// Serializes the conversion writes onto an inbound cross-chain receive. The
62/// invoice match writes a Pending conversion when the payment is seen. The
63/// provider monitor closes the receive row in the same critical section as
64/// its own write: the Completed conversion, or the failed payment of an order
65/// that failed or was refunded. A match racing the monitor would otherwise
66/// put Pending back for good, or reopen the closed row.
67static RECEIVE_CONVERSION_WRITES: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
68
69/// Links an inbound payment to the cross-chain receive whose Spark invoice it
70/// fulfilled, writing a Pending conversion onto it. Returns whether it did.
71/// Runs before the payment's status event so the event already carries the
72/// conversion. A payment that already carries one is left alone.
73pub(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
117/// Records what a synced cross-chain swap row implies locally: a receive that
118/// closed failed or refunded becomes a failed payment, which `emit`
119/// announces.
120pub(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
132/// Attaches a cross-chain [`ConversionInfo`] to a freshly-converted
133/// [`Payment`]. The payment's top-level `status` is left as-is: it reflects
134/// the local Spark/Token/Lightning leg's settlement, while the cross-chain
135/// pending state lives inside `conversion_info.status`.
136pub(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
187/// Resolves the BTC-leg [`TransferId`] for a cross-chain send. A
188/// caller-supplied `idempotency_key` from [`crate::SendPaymentRequest`]
189/// wins so the top-level `get_payment_by_id(idempotency_key)` lookup in
190/// `orchestrate_send` can short-circuit retries; otherwise we derive a
191/// `UUIDv5` from `fallback_seed` (the provider's quote/swap id) so that
192/// re-sending the same prepared shape still hits Spark's protocol-level
193/// dedup. Mirrors the stable-balance per-receive convention. Token-source
194/// sends ignore the return value: [`spark_wallet::transfer_tokens`] has
195/// no idempotency hook.
196pub(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    /// Not operational: no routes are currently offered under this provider.
211    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/// The asset a cross-chain route accepts on the Spark side.
224#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
225#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
226pub enum SparkAsset {
227    /// Native BTC (sats).
228    Bitcoin,
229    /// A Spark token, identified by its bech32m `token_identifier` (e.g. `btkn1...`).
230    Token { token_identifier: String },
231}
232
233/// Amount bounds a provider publishes for moving a route with one Spark-side
234/// asset.
235///
236/// A route can enforce a tighter bound than it publishes, so an amount inside
237/// these can still be rejected when the payment is prepared.
238///
239/// The two groups are independent, and either can be absent: a route may
240/// publish a base-unit floor (a dust minimum on a sats-funded route), a USD
241/// notional band, both, or neither.
242///
243/// `min_amount` / `max_amount` bound the asset that is paid in, so which asset
244/// they are denominated in follows the direction: the Spark-side asset on a
245/// send, the external asset on a receive. The USD band bounds the order's
246/// value and reads the same in both directions.
247#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
248#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
249pub struct CrossChainRouteLimits {
250    /// Smallest amount accepted, in the base units of the asset paid in.
251    pub min_amount: Option<u128>,
252    /// Largest amount accepted, in the base units of the asset paid in.
253    pub max_amount: Option<u128>,
254    /// Smallest order value accepted, in USD cents.
255    pub min_usd_cents: Option<u64>,
256    /// Largest order value accepted, in USD cents.
257    pub max_usd_cents: Option<u64>,
258}
259
260/// A Spark-side asset a route accepts, with the amount bounds that apply to it.
261///
262/// Bounds are per asset rather than per route: the same external endpoint can
263/// carry a dust floor when moved as sats and none when moved as a token.
264#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
265#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
266pub struct CrossChainAcceptedAsset {
267    pub asset: SparkAsset,
268    /// Unset when the provider publishes no bounds for this pairing.
269    pub limits: Option<CrossChainRouteLimits>,
270}
271
272/// The rail a cross-chain payment is delivered over.
273#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
274#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
275pub enum DeliveryMethod {
276    /// Delivered over the Spark network.
277    Spark,
278    /// Delivered over Lightning.
279    Lightning,
280    /// Delivered on-chain over Bitcoin.
281    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/// Which side of the transfer the request `amount` sizes: what leaves the
295/// payer, or what reaches the receiver.
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
298pub enum CrossChainFeeMode {
299    /// `amount` sizes the receiving end, and fees are paid on top.
300    ///
301    /// Sending: `amount` is the provider invoice/deposit target, and the
302    /// wallet pays `amount + source_transfer_fee_sats` in total.
303    /// Receiving: `amount` is what the wallet ends up with, and the deposit
304    /// the sender is asked for is sized above it to cover fees.
305    FeesExcluded,
306    /// `amount` sizes the paying end, and fees come out of it.
307    ///
308    /// Sending: `amount` is the wallet's total sats budget, and the provider
309    /// leg is sized so `amount_in + source_transfer_fee_sats <= amount`.
310    /// Receiving: `amount` is the deposit the sender makes, and the wallet
311    /// ends up with that minus fees.
312    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/// Filter for [`CrossChainService::get_routes`] and the public
325/// `get_cross_chain_routes()` API.
326#[derive(Clone, Debug, Deserialize, Serialize)]
327#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
328pub enum CrossChainRouteFilter {
329    /// Routes for sending to another chain, filtered by the parsed recipient
330    /// address details.
331    Send {
332        address_details: CrossChainAddressDetails,
333        /// Unset or `Spark` lists the routes paid from the Spark balance.
334        /// `Lightning` lists the routes an external payer funds over
335        /// Lightning. `Bitcoin` lists nothing.
336        delivery_method: Option<DeliveryMethod>,
337    },
338    /// Routes for receiving from another chain, optionally filtered by the
339    /// source token contract address.
340    Receive {
341        contract_address: Option<String>,
342        /// Unset or `Spark` lists the routes that deliver to the Spark balance.
343        /// `Lightning` lists the routes that pay out to a Lightning address.
344        /// `Bitcoin` lists nothing.
345        delivery_method: Option<DeliveryMethod>,
346    },
347    /// **Deprecated.** Use `Send` with the `Lightning` delivery method.
348    ///
349    /// Routes for a payment link that sends a stablecoin funded by Cash App
350    /// over Lightning rather than the Spark wallet.
351    PaymentLink {
352        address_details: CrossChainAddressDetails,
353    },
354}
355
356impl CrossChainRouteFilter {
357    /// The equivalent filter without the deprecated `PaymentLink` variant.
358    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/// A single route available for cross-chain transfers, tagged with the provider
370/// that offers it. Returned by `get_cross_chain_routes()`.
371#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
372#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
373pub struct CrossChainRoutePair {
374    /// Which provider offers this route.
375    pub provider: CrossChainProvider,
376    /// External blockchain (e.g. `"base"`, `"solana"`, `"tron"`).
377    pub chain: String,
378    /// External chain identifier (e.g. EVM `chainId` as a decimal string).
379    /// `None` for non-EVM chains that don't expose one, or when the
380    /// provider doesn't surface it.
381    pub chain_id: Option<String>,
382    /// External asset symbol (e.g. `"USDC"`, `"USDT"`).
383    pub asset: String,
384    /// Token contract / mint address on the destination chain.
385    pub contract_address: Option<String>,
386    /// Decimal places for the destination asset.
387    pub decimals: u8,
388    /// Whether the route supports exact-out mode.
389    pub exact_out_eligible: bool,
390    /// Spark-side assets this route accepts, each with its own amount bounds.
391    pub accepted_assets: Vec<CrossChainAcceptedAsset>,
392    /// Rails this route can be delivered over, orthogonal to
393    /// `accepted_assets` (the asset moved vs the rail moved on).
394    pub delivery_methods: Vec<DeliveryMethod>,
395}
396
397impl CrossChainRoutePair {
398    /// The bounds published for moving this route with `asset`, if the route
399    /// accepts it at all.
400    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    /// Whether `asset` is one of the Spark-side assets this route accepts.
408    pub fn accepts_asset(&self, asset: &SparkAsset) -> bool {
409        self.accepted_assets.iter().any(|a| &a.asset == asset)
410    }
411
412    /// Infers the destination address family from the route's
413    /// `contract_address`. Returns `None` for native-asset routes (no
414    /// contract address) or if the address format isn't recognized; callers
415    /// should treat that as "skip the address-family validation".
416    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/// Per-provider service registry plus shared cross-chain dependencies (today:
426/// the cached `FiatService`). Keeping the cache here scopes it to cross-chain
427/// flows; `sdk.fiat_service` stays uncached for general fiat consumers.
428#[derive(Clone)]
429pub(crate) struct CrossChainContext {
430    providers: HashMap<CrossChainProvider, Arc<dyn CrossChainService>>,
431    fiat_service: Arc<dyn FiatService>,
432    /// The Orchestra quoter, if one was set.
433    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    /// The Orchestra quoter, if one was set.
454    pub fn orchestra_quoter(&self) -> Option<&Arc<OrchestraQuoter>> {
455        self.orchestra_quoter.as_ref()
456    }
457
458    /// Fails with [`SdkError::CrossChainDisabled`] when no provider is
459    /// registered, which happens only when `cross_chain_config` is unset.
460    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    /// Look up a provider, returning a friendly error if missing.
468    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    /// Every provider's routes for `filter`, limited to USD-pegged assets and
483    /// sorted. A provider whose listing fails is logged and left out.
484    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        // Filter to USD-pegged destinations only.
499        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    /// Cached fiat service shared with every cross-chain provider. Read
511    /// through this on the prepare path so the TTL window is shared.
512    pub fn fiat_service(&self) -> &Arc<dyn FiatService> {
513        &self.fiat_service
514    }
515}
516
517/// Provider-internal state produced by `prepare` and consumed by `send`.
518/// Typed per provider so the send stage can resume without re-quoting and
519/// without a serde round-trip. Callers should round-trip this value as-is.
520#[derive(Debug, Clone, Serialize, Deserialize)]
521#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
522pub enum CrossChainProviderContext {
523    Orchestra {
524        /// Orchestra quote id, passed back on `/submit`.
525        quote_id: String,
526        /// Spark address Orchestra expects the deposit transfer to land on.
527        deposit_address: String,
528        /// Spark-side deposit amount in the route's source-asset base units.
529        #[serde(default)]
530        deposit_amount: u128,
531    },
532    Boltz {
533        /// Boltz swap id.
534        swap_id: String,
535        /// Hold invoice to pay.
536        invoice: String,
537        /// Hold invoice amount in sats.
538        #[serde(default)]
539        invoice_amount_sats: u64,
540        /// Slippage tolerance in basis points.
541        max_slippage_bps: u32,
542    },
543}
544
545/// Prepared cross-chain receive: the payment request to hand to the sender
546/// and the receive-quote details. For a receive into this wallet, the provider
547/// row is already persisted by the time this returns.
548#[derive(Debug, Clone)]
549pub(crate) struct CrossChainReceivePrepared {
550    /// Canonical cross-chain URI the sender can paste or scan to pay.
551    pub payment_request: String,
552    pub info: CrossChainReceiveInfo,
553    /// Provider token for reading the quote's status, when it issued one.
554    pub quote_read_token: Option<String>,
555}
556
557/// Information about the cross-chain receive quote: what the sender deposits
558/// and what the receiver is expected to get.
559#[derive(Debug, Clone, Serialize, Deserialize)]
560#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
561pub struct CrossChainReceiveInfo {
562    /// The provider's id for this receive. The incoming payment carries the
563    /// same id in its conversion info, so it can be matched to this receive.
564    pub quote_id: String,
565    /// Bare deposit address the sender pays to on the source chain, or the
566    /// BOLT11 invoice when the sender pays over Lightning.
567    pub deposit_address: String,
568    /// Amount the sender must deposit, in source-asset base units
569    /// (`route.decimals`, or sats over Lightning). On `FeesExcluded` this may
570    /// differ from the request's `amount` because the SDK inflates the deposit
571    /// to absorb provider fees. Render this value to the sender.
572    pub deposit_amount: u128,
573    /// Amount the receiver will see, net of provider fees, in
574    /// destination-asset base units. Sats when receiving BTC, token base
575    /// units when receiving a Spark token (e.g. USDB), or the stablecoin's or
576    /// native coin's base units (e.g. wei for ETH) when the receiver is on
577    /// another chain. The final delivered amount may move within the slippage
578    /// tolerance.
579    pub expected_received_amount: u128,
580    /// Symbol of the asset `expected_received_amount` is denominated in, as
581    /// the provider reports it: `"BTC"` for sats, a Spark token symbol (e.g.
582    /// `"USDB"`), or the stablecoin or native coin (e.g. `"ETH"`) when the
583    /// receiver is on another chain.
584    pub destination_asset: String,
585    /// Spark token identifier when the destination is a Spark token. Absent
586    /// otherwise.
587    pub token_identifier: Option<String>,
588    /// Provider-quoted total fee for this receive, including the partner fee
589    /// when one is set, in `service_fee_asset` units.
590    pub service_fee_amount: u128,
591    /// Ticker for `service_fee_amount`. Absent when the fee is denominated
592    /// in sats.
593    pub service_fee_asset: Option<String>,
594    /// Decimals of `service_fee_asset`, for formatting `service_fee_amount`.
595    /// Unset when the fee is in sats or the provider did not report them.
596    pub service_fee_asset_decimals: Option<u32>,
597    /// Quote expiry as a unix timestamp in seconds.
598    pub expires_at: u64,
599}
600
601/// Data stashed on the prepared send payment so the provider can resume
602/// the send stage without re-quoting.
603#[derive(Debug, Clone)]
604pub(crate) struct CrossChainSendPrepared {
605    pub amount_in: u128,
606    /// `amount_in` expressed in the cross-chain (destination) asset's base
607    /// units, via the fiat rate or decimal rescale the SDK used at prepare
608    /// time.
609    pub asset_amount_in: u128,
610    /// Amount the recipient will receive, in cross-chain asset base units.
611    pub estimated_out: u128,
612    /// Total user-visible fee in cross-chain asset base units. Covers provider
613    /// spread, bridge/gas, and DEX slippage. On the token-conversion path it
614    /// also rolls in the LN routing budget; on the direct path that budget
615    /// lives separately in `source_transfer_fee_sats`. The dispatcher
616    /// overrides this on the conversion path to reflect the token-side debit.
617    pub fee_amount: u128,
618    /// Provider service fee, including the partner fee when one is set, in
619    /// `service_fee_asset` base units.
620    pub service_fee_amount: u128,
621    /// Asset that the service fee is denominated in. Unset means BTC sats.
622    pub service_fee_asset: Option<String>,
623    /// Decimals of `service_fee_asset`. Unset for sats or when unreported.
624    pub service_fee_asset_decimals: Option<u32>,
625    /// Sats cost to the wallet of moving `amount_in` from the wallet to the
626    /// provider. For Boltz: the Lightning routing fee budget for paying the
627    /// hold invoice (a budget, not a central estimate — enforced as a hard
628    /// cap at send time). For Orchestra: the Spark transfer fee (0 today;
629    /// non-zero in the future).
630    ///
631    /// Semantically distinct from `fee_amount` (provider's service fee /
632    /// spread) and from destination-chain costs (baked into `estimated_out`).
633    /// Denominated in sats — the field assumes a sats-denominated source leg.
634    pub source_transfer_fee_sats: u64,
635    /// Fee mode the prepare was called with. Needed at send time so the
636    /// provider knows whether to apply FeesIncluded-style overpayment.
637    pub fee_mode: CrossChainFeeMode,
638    pub expires_at: String,
639    pub pair: CrossChainRoutePair,
640    pub recipient_address: String,
641    /// The `token_identifier` on the Spark source (e.g. USDB). `None` for BTC sats.
642    pub token_identifier: Option<String>,
643    /// Provider-internal state carried between `prepare` and `send`.
644    pub provider_context: CrossChainProviderContext,
645    /// Provider token for reading the quote's status, when it issued one.
646    pub quote_read_token: Option<String>,
647}
648
649/// Abstraction over cross-chain bridge/swap providers.
650///
651/// Each implementation owns its own client, caching, and background monitoring.
652/// The SDK dispatches to the provider via this trait.
653#[allow(clippy::too_many_arguments)]
654#[macros::async_trait]
655pub(crate) trait CrossChainService: Send + Sync {
656    /// Returns the available cross-chain route pairs.
657    ///
658    /// The returned [`CrossChainRoutePair`] always describes the non-Spark
659    /// side of the route. The [`CrossChainRouteFilter`] controls direction
660    /// and optional filtering.
661    async fn get_routes(
662        &self,
663        filter: &CrossChainRouteFilter,
664    ) -> Result<Vec<CrossChainRoutePair>, SdkError>;
665
666    /// Fetch a quote for a cross-chain send or Lightning onramp. `amount` is
667    /// always in the source-leg sats/token base units. The caller converts any
668    /// USD intent to sats first. `delivery_method` selects the rail the wallet
669    /// dispatches over. `None` uses the provider's default
670    /// ([`DeliveryMethod::Spark`] for Orchestra). `source_token_identifier`
671    /// is only meaningful for a Spark source (`None` = BTC sats, `Some` = a
672    /// token).
673    #[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    /// Fetch a quote for a cross-chain receive.
686    ///
687    /// `amount` is the caller's raw ask, always:
688    /// - `FeesExcluded`: net amount the receiver wants to land on the Spark
689    ///   side, in `destination`'s base units (sats for BTC, token base units
690    ///   for tokens). The provider inflates by `target_overpay_bps` when
691    ///   sizing the deposit but drift-checks against `amount` itself, so the
692    ///   overpay gives Orchestra headroom without tightening the accept
693    ///   threshold beyond what the user asked for.
694    /// - `FeesIncluded`: the deposit the sender will pay, in the route's
695    ///   source-asset base units. The receiver lands `amount - fees`.
696    ///   `target_overpay_bps` is ignored.
697    ///
698    /// `delivery_method` is the rail the funds arrive on:
699    /// [`DeliveryMethod::Spark`] pays `recipient_address` as a Spark address,
700    /// [`DeliveryMethod::Lightning`] as a Lightning address. A wallet-bound
701    /// implementation receives over Spark into its own wallet and tracks the
702    /// receive. `refund_address` is where the provider returns the deposit if
703    /// delivery fails.
704    #[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        // Pre-validated Spark-side destination: the SDK dispatch has
712        // checked this against `route.accepted_assets` and resolved any
713        // wallet-level defaults (e.g. active stable balance).
714        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    /// Execute the send: transfer funds to the deposit address, submit to
722    /// the provider, persist metadata, monitor to terminal, and return the
723    /// resulting [`Payment`].
724    ///
725    /// `idempotency_key` is the caller-provided key from `SendPaymentRequest`.
726    /// Providers should use it as the underlying Spark `TransferId` so the
727    /// outbound transfer is protocol-level idempotent on retry; if `None`,
728    /// the provider derives a deterministic key from its own quote/swap id
729    /// (same shape as the stable-balance per-receive convention). Only the
730    /// BTC-source branch benefits — token transfers have no upstream
731    /// idempotency hook, and the top-level dispatcher already rejects
732    /// idempotency keys for token-source sends.
733    ///
734    /// Each provider owns the polling-to-terminal step internally — the
735    /// SDK dispatcher does not wrap this with an additional wait.
736    async fn send(
737        &self,
738        prepared: &CrossChainSendPrepared,
739        idempotency_key: Option<String>,
740    ) -> Result<crate::Payment, SdkError>;
741}
742
743/// Fetches the BTC/USD rate from the Breez Server fiat feed. Errors if the
744/// feed is unreachable, missing the USD entry, or returns a non-finite value.
745pub(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/// `sats * fiat_rate * 10^dest_decimals / 10^8`. Sub-base-unit truncation
766/// is absorbed by the route's slippage tolerance.
767#[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/// Converts a source-asset amount (base units at `src_decimals`) to sats
788/// via `fiat_per_btc`. Assumes the source is denominated 1:1 in the same
789/// fiat as the rate. Inverse of [`convert_sats_to_destination_amount`].
790#[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
810/// Rejects a route that lists its delivery methods without `delivery_method`.
811/// A hand-built route without delivery methods is accepted.
812pub(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
830/// Builds the payment-request URI a sender pays to for a cross-chain
831/// receive. EVM destinations get an EIP-681 URI so wallets like `MetaMask`
832/// auto-fill recipient/token/chain/amount. Solana and Tron destinations
833/// fall back to the bare `deposit_address` because current wallets don't
834/// honor those schemes' parameters reliably (see
835/// [`breez_sdk_common::input::format_cross_chain_uri`]).
836pub(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    // Guard against a provider returning an address that belongs to a
850    // different chain family than the route we requested.
851    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
865/// Best-available fee: realized `asset_amount_in − delivered_amount` on
866/// `Completed`, else the prepare-time estimate. Refunded/failed keep the
867/// estimate (the realized formula would be misleading).
868pub(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
880/// Rescales an amount between two base-unit precisions. Assumes
881/// `1 source unit ≈ 1 dest unit` at face value — only valid for USD-stable
882/// pairs. Errors on overflow.
883pub(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/// Inverse of [`convert_sats_to_destination_amount`]: returns the sats whose
908/// fiat-equivalent matches the given USD-stable `destination_amount`.
909/// Errors on a non-positive `fiat_rate`.
910#[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
935/// Resolves the target-overpay bps to apply on `FeesExcluded` cross-chain
936/// preparations (send and receive). Same precedence as slippage:
937/// caller-supplied value (bounds-checked here), then the config default, then
938/// the built-in default. Config defaults are validated at SDK startup in
939/// `Config::validate`.
940pub(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
957/// Inflates a target amount by `overpay_bps` so the realized delivery lands at
958/// or above target despite provider slippage. `overpay_bps == 0` is identity.
959/// Used on both directions: send pads the destination target, receive pads
960/// the source-asset deposit.
961pub(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        // A v4 UUID is a valid TransferId — using one here checks that the
1134        // caller-supplied key wins outright.
1135        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        // The provider tag in the seed prevents an Orchestra `quote-1` and a
1160        // hypothetical Boltz `quote-1` from colliding on the same TransferId.
1161        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        // 10_000 sats at $60_000/BTC → $6.00 = 6_000_000 USDC base units.
1175        let dest = convert_sats_to_destination_amount(10_000, 60_000.0, 6).unwrap();
1176        assert_eq!(dest, 6_000_000);
1177        // Inverse must recover the source sats.
1178        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        // 1 USDC ($1.00 = 1_000_000 base units) at $60_000/BTC → 1666 sats (floor).
1185        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    // ---- compute_terminal_fee_amount ----
1242
1243    #[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), // asset_amount_in
1248            Some(997_498),   // delivered_amount
1249            Some(20_434),    // prepare-time estimate
1250        );
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        // Refunded payments don't have a realized fee semantic; the estimate
1257        // is the best we can show (and the realized formula would produce
1258        // garbage because delivered_amount is 0/None on a refund).
1259        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        // Pre-upgrade rows have no asset_amount_in; realized fee can't be
1282        // computed, so the stored estimate stays as-is.
1283        let realized = compute_terminal_fee_amount(
1284            &crate::ConversionStatus::Completed,
1285            None, // asset_amount_in missing
1286            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        // Should never happen on Completed per the contract, but defend
1295        // against the edge anyway.
1296        let realized = compute_terminal_fee_amount(
1297            &crate::ConversionStatus::Completed,
1298            Some(1_020_434),
1299            None, // delivered_amount missing
1300            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        // Rare but possible: provider over-delivers vs source.
1308        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    /// Regression: `CrossChainProviderContext::Boltz.invoice_amount_sats` must
1322    /// be the source of truth for the LN-leg amount, distinct from
1323    /// `CrossChainSendPrepared::amount_in` (which can carry a user-facing display
1324    /// value such as token base units after the dispatcher's conversion-path
1325    /// override). Conflating the two persisted USDB base units into the
1326    /// `invoice_amount_sats` field of `ConversionInfo::Boltz`, showing a
1327    /// ~$1,200,000-sat "from" amount for a ~$1 send. This test asserts the
1328    /// two fields are independently representable + survive a serde
1329    /// round-trip with their distinct values.
1330    #[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    /// Pre-bug-fix persisted contexts lack `invoice_amount_sats`. Serde must
1355    /// default the missing field to 0 rather than failing to deserialize — the
1356    /// downstream send-time error becomes obvious instead of corrupting the
1357    /// stored Payment.
1358    #[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    /// Same invariant for Orchestra: `deposit_amount` is the source of truth
1379    /// for the deposit transfer size and is distinct from
1380    /// `CrossChainSendPrepared::amount_in`.
1381    #[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        // Sibling fields survive the rebuild.
1461        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    // ---- resolve_target_overpay_bps ----
1496
1497    #[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    // ---- inflate_target_amount ----
1530
1531    #[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        // 25 bps on 1_000_000 → 2_500 pad.
1539        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        // 25 bps on 100 → 0.25 pad, truncates to 0.
1545        assert_eq!(inflate_target_amount(100, 25), 100);
1546    }
1547
1548    // ---- convert_source_amount_to_sats ----
1549
1550    #[test_all]
1551    fn convert_stable_to_sats_at_par_6dp() {
1552        // BTC/USD = 100_000, 1 USD = 1000 sats. 1_000_000 (6dp) = $1 = 1000 sats.
1553        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        // BTC/USD = 50_000, $1 = 2000 sats.
1562        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        // $1 at 6dp and at 18dp must produce the same sats.
1571        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        // Infinity is intentionally allowed (produces 0 sats, a finite result);
1586        // NaN is the pathological input we guard against.
1587        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    // ---- build_receive_payment_request ----
1602
1603    /// EVM destinations produce an EIP-681 URI (with `chain_id` and token
1604    /// contract when present) so wallets like `MetaMask` auto-fill.
1605    #[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    /// Solana falls back to the bare deposit address: current wallets don't
1625    /// honor solana: URI parameters reliably.
1626    #[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    /// Tron falls back to the bare deposit address for the same reason.
1634    #[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    /// An unrecognized address surfaces a Generic error rather than silently
1642    /// returning something usable.
1643    #[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    /// An EVM-looking deposit address for a Solana route must be rejected:
1652    /// a provider that miswires chains cannot silently redirect funds by
1653    /// returning an EVM address where a Solana address was expected.
1654    #[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}