Skip to main content

breez_sdk_spark/sdk/bridging/
mod.rs

1//! Bridging: orders in which a payer on another chain or on Lightning pays a
2//! recipient, with no funds moving through the SDK.
3
4mod models;
5mod orchestra;
6
7pub use models::*;
8
9use std::collections::HashSet;
10use std::sync::Arc;
11
12use breez_sdk_common::{
13    breez_server::{BreezServer, PRODUCTION_BREEZSERVER_URL},
14    buy::cashapp::{CashAppProvider, cash_app_lightning_address},
15    fiat::FiatService,
16    input::{CrossChainAddressFamily, detect_address_family, validate_lightning_address_format},
17    lnurl::pay::validate_user_input,
18};
19
20use crate::{
21    BitcoinAddressDetails, BitcoinNetwork, BridgeFromCashAppRequest, BridgeFromCashAppResponse,
22    BridgeToCashAppRequest, BridgeToCashAppResponse, CrossChainAcceptedAsset,
23    CrossChainAddressDetails, CrossChainConfig, CrossChainProvider, CrossChainReceiveInfo,
24    CrossChainRoutePair, DeliveryMethod, FeePolicy, InputType, LightningAddressDetails,
25    SparkAddressDetails, SparkAsset,
26    cross_chain::{
27        BreezServerOrchestraConfigResolver, CachedFiatService, CrossChainContext,
28        CrossChainFeeMode, CrossChainProviderContext, CrossChainReceivePrepared,
29        CrossChainSendPrepared, CrossChainService, DEFAULT_FIAT_CACHE_TTL, DepositDestination,
30        OrchestraQuoter, convert_destination_amount_to_sats, delivery_method_from_wire,
31        delivery_method_to_wire, fetch_btc_usd_rate, is_usd_stable_asset,
32        parse_rfc3339_to_unix_seconds, rescale_decimals,
33    },
34    error::SdkError,
35    utils::time::now_secs,
36};
37
38use self::orchestra::{bridge_status_response, is_unpaid_onramp_order, to_bridge_route_pair};
39use super::SdkInputParser;
40use super::helpers::{partner_id, validate_breez_api_key};
41use super::payments::receive::{
42    quote_cross_chain_receive, resolve_cross_chain_receive_params, validate_receive_destination,
43};
44use super::payments::validation::{
45    known_token_contracts, resolve_direct_overpay_amount, resolve_slippage_bps,
46    validate_address_family_against_route, validate_amount,
47    validate_recipient_not_contract_address, validate_refund_address,
48};
49
50/// Creates bridges: orders that pay a recipient from another chain or over
51/// Lightning, with no funds moving through the SDK. Get one with
52/// [`new_bridging_client`], or from a connected SDK with
53/// `get_bridging_client`. Only available on mainnet.
54#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
55pub struct BridgingClient {
56    cross_chain_config: Option<CrossChainConfig>,
57    cross_chain_context: CrossChainContext,
58    quoter: Arc<OrchestraQuoter>,
59    input_parser: Arc<SdkInputParser>,
60}
61
62/// Builds a [`BridgingClient`] from an API key, with no seed or storage.
63#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
64pub async fn new_bridging_client(config: BridgingConfig) -> Result<Arc<BridgingClient>, SdkError> {
65    validate_breez_api_key(&config.api_key)?;
66    if let Some(proxy) = &config.proxy {
67        proxy.validate()?;
68    }
69    if let Some(cross_chain_config) = &config.cross_chain_config {
70        cross_chain_config.validate()?;
71    }
72
73    let user_agent = crate::default_user_agent();
74    let transport_proxy = config.proxy.as_ref().map(platform_utils::ProxyConfig::from);
75    let http_client =
76        platform_utils::create_http_client_with_proxy(Some(&user_agent), transport_proxy.as_ref())
77            .map_err(|e| {
78                SdkError::InvalidInput(format!("Failed to build proxied HTTP client: {e}"))
79            })?;
80    let breez_server = Arc::new(
81        BreezServer::new(
82            PRODUCTION_BREEZSERVER_URL,
83            Some(config.api_key.clone()),
84            &user_agent,
85            transport_proxy.as_ref(),
86        )
87        .map_err(|e| SdkError::Generic(e.to_string()))?,
88    );
89    // Lightning-address hosts are chosen by remote parties, so their lookups
90    // ride a client that revalidates every redirect hop, as in the SDK.
91    let lnurl_http_client: Arc<dyn platform_utils::HttpClient> =
92        platform_utils::create_http_client_with_redirect_filter(
93            Some(&user_agent),
94            transport_proxy.as_ref(),
95            breez_sdk_common::lnurl::security::lnurl_redirect_filter(),
96        )
97        .map_err(|e| SdkError::Generic(format!("Failed to build LNURL HTTP client: {e}")))?;
98    let input_parser = Arc::new(SdkInputParser::new(
99        breez_sdk_common::dns::Resolver::with_proxy(transport_proxy.as_ref())
100            .map_err(|e| SdkError::Generic(format!("Failed to build DNS resolver: {e}")))?,
101        lnurl_http_client,
102        None,
103    ));
104    let fiat_service: Arc<dyn FiatService> = Arc::new(CachedFiatService::new(
105        Arc::clone(&breez_server) as Arc<dyn FiatService>,
106        DEFAULT_FIAT_CACHE_TTL,
107    ));
108    let quoter = Arc::new(OrchestraQuoter::new(
109        Arc::new(BreezServerOrchestraConfigResolver::new(breez_server)),
110        partner_id(&config.api_key),
111        Arc::clone(&fiat_service),
112        http_client,
113    ));
114    Ok(Arc::new(BridgingClient::new(
115        config.cross_chain_config,
116        quoter,
117        fiat_service,
118        input_parser,
119    )))
120}
121
122/// Settings for [`new_bridging_client`] with every optional field unset.
123#[cfg_attr(feature = "uniffi", uniffi::export)]
124pub fn default_bridging_config(api_key: String) -> BridgingConfig {
125    BridgingConfig {
126        api_key,
127        proxy: None,
128        cross_chain_config: None,
129    }
130}
131
132impl BridgingClient {
133    pub(crate) fn new(
134        cross_chain_config: Option<CrossChainConfig>,
135        quoter: Arc<OrchestraQuoter>,
136        fiat_service: Arc<dyn FiatService>,
137        input_parser: Arc<SdkInputParser>,
138    ) -> Self {
139        let mut cross_chain_context = CrossChainContext::new(fiat_service);
140        cross_chain_context.insert(
141            CrossChainProvider::Orchestra,
142            Arc::clone(&quoter) as Arc<dyn CrossChainService>,
143        );
144        Self {
145            cross_chain_config,
146            cross_chain_context,
147            quoter,
148            input_parser,
149        }
150    }
151}
152
153#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
154impl BridgingClient {
155    /// Lists the routes that can pay `recipient`.
156    pub async fn get_routes(
157        &self,
158        request: GetBridgeRoutesRequest,
159    ) -> Result<GetBridgeRoutesResponse, SdkError> {
160        let recipient = self.parse_recipient(&request.recipient).await?;
161        let mut routes = match &recipient {
162            BridgeRecipient::Spark(_) => {
163                self.listed_routes(delivery_method_to_wire(DeliveryMethod::Spark), false)
164                    .await?
165            }
166            BridgeRecipient::Lightning(_) => {
167                self.listed_routes(delivery_method_to_wire(DeliveryMethod::Lightning), false)
168                    .await?
169            }
170            BridgeRecipient::CrossChain(_) | BridgeRecipient::Bitcoin(_) => {
171                self.routes_to_other_chain(&recipient).await?
172            }
173        };
174        routes.retain(|route| route_pays(&recipient, route));
175        let mut seen = HashSet::new();
176        routes.retain(|route| seen.insert((route.source.clone(), route.destination.clone())));
177        routes.sort_by(|a, b| route_order(a).cmp(&route_order(b)));
178        Ok(GetBridgeRoutesResponse { routes })
179    }
180
181    /// Creates a bridge and returns what the payer pays. Once paid, the
182    /// provider delivers to the recipient, or refunds `refund_address` if it
183    /// can't. Track it with [`Self::get_bridge_status`].
184    pub async fn create_bridge(
185        &self,
186        request: CreateBridgeRequest,
187    ) -> Result<CreateBridgeResponse, SdkError> {
188        self.create_bridge_with(request, LightningInvoice::Quote)
189            .await
190    }
191
192    /// Reads a bridge's status from the provider.
193    pub async fn get_bridge_status(
194        &self,
195        request: GetBridgeStatusRequest,
196    ) -> Result<GetBridgeStatusResponse, SdkError> {
197        if request.bridge_id.trim().is_empty() {
198            return Err(SdkError::InvalidInput("Bridge id is empty".to_string()));
199        }
200        let status_token = request
201            .status_token
202            .as_deref()
203            .map(str::trim)
204            .filter(|token| !token.is_empty());
205        let bridge_id = request.bridge_id.trim();
206        // Only a bridge from Cash App is an order, created before payment.
207        let order = if is_order_id(bridge_id) {
208            self.quoter
209                .find_order_by_id(bridge_id, status_token)
210                .await?
211                .filter(|order| !is_unpaid_onramp_order(order))
212        } else {
213            self.quoter.find_order(bridge_id, status_token).await?
214        };
215        Ok(bridge_status_response(order.as_ref()))
216    }
217
218    /// Pays a recipient on another chain from Cash App. Takes a route for the
219    /// address that the payer funds over Lightning, and returns the bridge
220    /// with the Cash App link as its `payment_request`. The provider allows
221    /// these payments 10% slippage when they execute. With fees excluded,
222    /// `max_slippage_bps` bounds how far the quoted delivery may fall short of
223    /// `amount` when the bridge is created.
224    pub async fn bridge_from_cash_app(
225        &self,
226        request: CreateBridgeRequest,
227    ) -> Result<CreateBridgeResponse, SdkError> {
228        if delivery_method(&request.route.source) != Some(DeliveryMethod::Lightning) {
229            return Err(SdkError::InvalidInput(
230                "Cash App pays a recipient on another chain over Lightning".to_string(),
231            ));
232        }
233        let mut response = self
234            .create_bridge_with(request, LightningInvoice::CashApp)
235            .await?;
236        response.payment_request = CashAppProvider::build_url(&response.info.deposit_address);
237        Ok(response)
238    }
239
240    /// Pays a Cash App user from another chain. The recipient is their
241    /// username, as `$alice`, or their `alice@cash.app` Lightning address, as
242    /// given to [`Self::get_routes`].
243    pub async fn bridge_to_cash_app(
244        &self,
245        request: CreateBridgeRequest,
246    ) -> Result<CreateBridgeResponse, SdkError> {
247        let Some(address) = cash_app_lightning_address(request.recipient.trim()) else {
248            return Err(SdkError::InvalidInput(format!(
249                "{} is not a Cash App username",
250                request.recipient
251            )));
252        };
253        self.create_bridge(CreateBridgeRequest {
254            recipient: address,
255            ..request
256        })
257        .await
258    }
259}
260
261impl BridgingClient {
262    /// Bridges from Cash App over a `CrossChainRoutePair` route. A failure
263    /// before the swap is refunded to `refund_address`, a Lightning address.
264    pub(crate) async fn legacy_bridge_from_cash_app(
265        &self,
266        request: BridgeFromCashAppRequest,
267        refund_address: Option<&str>,
268    ) -> Result<BridgeFromCashAppResponse, SdkError> {
269        validate_amount(Some(request.amount))?;
270
271        let BridgeFromCashAppRequest {
272            address,
273            route,
274            amount,
275            fee_policy,
276            max_slippage_bps,
277        } = request;
278
279        // A Boltz reverse swap needs the SDK online to claim before the
280        // payer's HTLC settles, so it can't back a link someone else pays
281        // later. Orchestra orders are submitless and deliver without the SDK.
282        if !matches!(route.provider, CrossChainProvider::Orchestra) {
283            return Err(SdkError::InvalidInput(
284                "Bridging from Cash App is only supported on Orchestra routes".to_string(),
285            ));
286        }
287
288        // Cash App funds the deposit over Lightning. Fail fast before quoting if
289        // the route can't be funded that way. Rejecting an empty
290        // `delivery_methods` stops a hand-built route from reaching
291        // `prepare` and committing provider state it can't fund.
292        if !route_supports_delivery_method(&route, DeliveryMethod::Lightning) {
293            return Err(SdkError::InvalidInput(
294                "The selected route can't be funded over Lightning".to_string(),
295            ));
296        }
297
298        // Validate the recipient before creating the order, using the same guards
299        // as the send path.
300        let InputType::CrossChainAddress(recipient) = self.parse(&address).await? else {
301            return Err(SdkError::InvalidInput(
302                "Recipient must be a cross-chain (EVM/Solana/Tron) address".to_string(),
303            ));
304        };
305        self.validate_cross_chain_recipient(&recipient, &route)
306            .await?;
307
308        let funded = self
309            .quote_lightning_funded(
310                &recipient.address,
311                &route,
312                amount,
313                fee_policy,
314                max_slippage_bps,
315                LightningInvoice::CashApp,
316                refund_address,
317            )
318            .await?;
319
320        let url = CashAppProvider::build_url(&funded.deposit_target);
321
322        bridge_from_cash_app_response(funded.prepared, url, funded.amount_sats)
323    }
324
325    /// Bridges to a Cash App user over a `CrossChainRoutePair` route.
326    pub(crate) async fn legacy_bridge_to_cash_app(
327        &self,
328        request: BridgeToCashAppRequest,
329    ) -> Result<BridgeToCashAppResponse, SdkError> {
330        validate_amount(Some(request.amount))?;
331
332        let BridgeToCashAppRequest {
333            recipient,
334            route,
335            amount,
336            fee_policy,
337            refund_address,
338            max_slippage_bps,
339        } = request;
340
341        // The provider pays out after the deposit lands, with no wallet
342        // online, which only Orchestra supports.
343        if !matches!(route.provider, CrossChainProvider::Orchestra) {
344            return Err(SdkError::InvalidInput(
345                "Bridging to Cash App is only supported on Orchestra routes".to_string(),
346            ));
347        }
348        if !route_supports_delivery_method(&route, DeliveryMethod::Lightning) {
349            return Err(SdkError::InvalidInput(
350                "The selected route can't deliver over Lightning".to_string(),
351            ));
352        }
353
354        let Some(address) = cash_app_lightning_address(recipient.trim()) else {
355            return Err(SdkError::InvalidInput(format!(
356                "{recipient} is not a Cash App username"
357            )));
358        };
359        // Resolved before quoting so an unknown account fails before the payer
360        // funds anything.
361        let Ok(InputType::LightningAddress(recipient)) = self.parse(&address).await else {
362            return Err(SdkError::InvalidInput(format!(
363                "{recipient} is not a reachable Cash App account"
364            )));
365        };
366
367        let refund = self
368            .validate_refund_address(Some(&refund_address), &route)
369            .await?;
370
371        let prepared = self
372            .quote_external_funded(
373                &route,
374                amount,
375                SparkAsset::Bitcoin,
376                DeliveryMethod::Lightning,
377                &recipient.address,
378                refund.as_deref(),
379                fee_policy,
380                max_slippage_bps,
381            )
382            .await?;
383        check_lightning_address_accepts(&recipient, prepared.info.expected_received_amount)?;
384
385        Ok(BridgeToCashAppResponse {
386            payment_request: prepared.payment_request,
387            info: prepared.info,
388        })
389    }
390
391    async fn parse(&self, input: &str) -> Result<InputType, SdkError> {
392        Ok(self.input_parser.parse(input).await?.into())
393    }
394
395    /// Parses who a bridge pays. Anything a bridge can't pay fails with
396    /// `InvalidInput`.
397    async fn parse_recipient(&self, input: &str) -> Result<BridgeRecipient, SdkError> {
398        match self.parse(input).await? {
399            InputType::SparkAddress(details) => {
400                validate_spark_recipient(&details)?;
401                Ok(BridgeRecipient::Spark(details))
402            }
403            InputType::LightningAddress(details) => Ok(BridgeRecipient::Lightning(details)),
404            InputType::CrossChainAddress(details) => Ok(BridgeRecipient::CrossChain(details)),
405            InputType::BitcoinAddress(details) => {
406                validate_bitcoin_recipient(&details)?;
407                Ok(BridgeRecipient::Bitcoin(details))
408            }
409            InputType::Bip21(bip21) => {
410                let details = bip21
411                    .payment_methods
412                    .into_iter()
413                    .find_map(|method| match method {
414                        InputType::BitcoinAddress(details) => Some(details),
415                        _ => None,
416                    })
417                    .ok_or_else(|| {
418                        SdkError::InvalidInput(
419                            "A bridge can only pay the Bitcoin address of a BIP21 URI".to_string(),
420                        )
421                    })?;
422                validate_bitcoin_recipient(&details)?;
423                Ok(BridgeRecipient::Bitcoin(details))
424            }
425            _ => Err(SdkError::InvalidInput(
426                "A bridge can only pay a Spark address, a Lightning address, a Bitcoin \
427                 address, or an EVM/Solana/Tron/XRP/Zcash address"
428                    .to_string(),
429            )),
430        }
431    }
432
433    async fn create_bridge_with(
434        &self,
435        request: CreateBridgeRequest,
436        invoice: LightningInvoice,
437    ) -> Result<CreateBridgeResponse, SdkError> {
438        validate_amount(Some(request.amount))?;
439        if !matches!(request.route.provider, CrossChainProvider::Orchestra) {
440            return Err(SdkError::InvalidInput(
441                "Bridging is only supported on Orchestra routes".to_string(),
442            ));
443        }
444        let recipient = self.parse_recipient(&request.recipient).await?;
445        self.create_bridge_for(&recipient, request, invoice).await
446    }
447
448    /// Creates a bridge to a parsed `recipient`.
449    async fn create_bridge_for(
450        &self,
451        recipient: &BridgeRecipient,
452        request: CreateBridgeRequest,
453        invoice: LightningInvoice,
454    ) -> Result<CreateBridgeResponse, SdkError> {
455        let CreateBridgeRequest {
456            route,
457            amount,
458            refund_address,
459            fee_policy,
460            max_slippage_bps,
461            ..
462        } = request;
463        if !route_pays(recipient, &route) {
464            return Err(SdkError::InvalidInput(
465                "The route doesn't pay this recipient".to_string(),
466            ));
467        }
468        self.validate_recipient(recipient, &route, refund_address.as_deref())
469            .await?;
470        // The payment request is built from the route's sides, so they must be
471        // the provider's, not a hand-built or stale copy.
472        let listed = self.listed_routes(&route.destination.chain, false).await?;
473        if !is_listed(&listed, &route) {
474            return Err(SdkError::InvalidInput(
475                "The provider doesn't serve this route".to_string(),
476            ));
477        }
478
479        match recipient {
480            BridgeRecipient::CrossChain(CrossChainAddressDetails { address, .. })
481            | BridgeRecipient::Bitcoin(BitcoinAddressDetails { address, .. }) => {
482                self.create_bridge_to_other_chain(
483                    address,
484                    &route,
485                    amount,
486                    refund_address.as_deref(),
487                    fee_policy,
488                    max_slippage_bps,
489                    invoice,
490                )
491                .await
492            }
493            BridgeRecipient::Spark(details) => {
494                let destination = spark_asset(&route.destination);
495                let source = external_pair(
496                    &route,
497                    &route.source,
498                    Some((destination.clone(), DeliveryMethod::Spark)),
499                );
500                let refund = self
501                    .validate_refund_address(refund_address.as_deref(), &source)
502                    .await?;
503                let prepared = self
504                    .quote_external_funded(
505                        &source,
506                        source_units(&route, amount)?,
507                        destination,
508                        DeliveryMethod::Spark,
509                        &details.address,
510                        refund.as_deref(),
511                        fee_policy,
512                        max_slippage_bps,
513                    )
514                    .await?;
515                Ok(create_bridge_response(prepared))
516            }
517            BridgeRecipient::Lightning(details) => {
518                let source = external_pair(
519                    &route,
520                    &route.source,
521                    Some((SparkAsset::Bitcoin, DeliveryMethod::Lightning)),
522                );
523                let refund = self
524                    .validate_refund_address(refund_address.as_deref(), &source)
525                    .await?;
526                let prepared = self
527                    .quote_external_funded(
528                        &source,
529                        amount,
530                        SparkAsset::Bitcoin,
531                        DeliveryMethod::Lightning,
532                        &details.address,
533                        refund.as_deref(),
534                        fee_policy,
535                        max_slippage_bps,
536                    )
537                    .await?;
538                check_lightning_address_accepts(details, prepared.info.expected_received_amount)?;
539                Ok(create_bridge_response(prepared))
540            }
541        }
542    }
543
544    /// Checks that `recipient` can be paid over `route`, before anything is
545    /// quoted.
546    async fn validate_recipient(
547        &self,
548        recipient: &BridgeRecipient,
549        route: &BridgeRoutePair,
550        refund_address: Option<&str>,
551    ) -> Result<(), SdkError> {
552        match recipient {
553            BridgeRecipient::Spark(details) => validate_spark_recipient(details),
554            BridgeRecipient::Bitcoin(details) => validate_bitcoin_recipient(details),
555            BridgeRecipient::CrossChain(details) => {
556                self.validate_cross_chain_recipient(
557                    details,
558                    &external_pair(route, &route.destination, None),
559                )
560                .await
561            }
562            // Orchestra only pays out over Lightning with a refund address.
563            BridgeRecipient::Lightning(_) if refund_address.is_none() => {
564                Err(SdkError::InvalidInput(
565                    "A refund address is required to pay a Lightning address".to_string(),
566                ))
567            }
568            BridgeRecipient::Lightning(_) => Ok(()),
569        }
570    }
571
572    fn default_slippage_bps(&self) -> Option<u32> {
573        self.cross_chain_config
574            .as_ref()
575            .and_then(|c| c.default_slippage_bps)
576    }
577
578    fn default_target_overpay_bps(&self) -> Option<u32> {
579        self.cross_chain_config
580            .as_ref()
581            .and_then(|c| c.default_target_overpay_bps)
582    }
583
584    /// Checks a recipient on another chain against `route`, and that it isn't
585    /// a token contract, which can never pass funds on.
586    async fn validate_cross_chain_recipient(
587        &self,
588        recipient: &CrossChainAddressDetails,
589        route: &CrossChainRoutePair,
590    ) -> Result<(), SdkError> {
591        let recipient_family: CrossChainAddressFamily = recipient.address_family.into();
592        validate_address_family_against_route(recipient_family, route)?;
593        let known_contracts = known_token_contracts(
594            &self.cross_chain_context,
595            &recipient.address,
596            recipient_family,
597            route,
598        )
599        .await;
600        validate_recipient_not_contract_address(
601            &recipient.address,
602            recipient_family,
603            &known_contracts,
604        )
605    }
606
607    /// Parses the payer's refund address, when given, and checks it against
608    /// the source `route`.
609    async fn validate_refund_address(
610        &self,
611        refund_address: Option<&str>,
612        route: &CrossChainRoutePair,
613    ) -> Result<Option<String>, SdkError> {
614        validate_refund_address(
615            &self.cross_chain_context,
616            &self.input_parser,
617            refund_address,
618            route,
619        )
620        .await
621    }
622
623    /// Quotes an order the payer funds over Lightning, delivering `amount` of
624    /// `route`'s asset to `recipient_address`, with an `invoice` of that kind.
625    /// A failure before the swap is refunded to `refund_address`, which must
626    /// be one [`Self::lightning_refund_address`] accepts.
627    #[allow(clippy::too_many_arguments)]
628    async fn quote_lightning_funded(
629        &self,
630        recipient_address: &str,
631        route: &CrossChainRoutePair,
632        amount: u128,
633        fee_policy: Option<FeePolicy>,
634        max_slippage_bps: Option<u32>,
635        invoice: LightningInvoice,
636        refund_address: Option<&str>,
637    ) -> Result<LightningFunded, SdkError> {
638        let slippage_bps = resolve_slippage_bps(max_slippage_bps, self.default_slippage_bps())?;
639        let refund = self.lightning_refund_address(refund_address).await?;
640        let refund_address = refund.as_ref().map(|r| r.address.as_str());
641
642        // A stablecoin `amount` is in the destination's base units (the
643        // route's `decimals`), the USD value at parity, and goes to sats at the
644        // live rate. Any other `amount` is already in sats.
645        let source_sats = if amount_side(&route.asset) == BridgeAmountSide::Destination {
646            let btc_usd =
647                fetch_btc_usd_rate(self.cross_chain_context.fiat_service().as_ref()).await?;
648            convert_destination_amount_to_sats(amount, btc_usd, route.decimals.into())?
649        } else {
650            amount
651        };
652        if source_sats == 0 {
653            return Err(SdkError::InvalidInput(
654                "Amount is too small to fund over Lightning".to_string(),
655            ));
656        }
657
658        // Match the send path: on `FeesExcluded` pad the source so the recipient
659        // lands at or above target despite provider slippage. The pad comes from
660        // config (no per-request override on a Lightning-funded bridge). A route
661        // that only moves BTC has no price to slip, and its fees are sized
662        // exactly, so it takes none.
663        let fee_policy = fee_policy.unwrap_or_default();
664        let overpay_bps = crate::cross_chain::resolve_target_overpay_bps(
665            None,
666            self.default_target_overpay_bps(),
667        )?;
668        let overpay_bps = if route.asset.eq_ignore_ascii_case("BTC") {
669            0
670        } else {
671            overpay_bps
672        };
673        let source_sats = resolve_direct_overpay_amount(source_sats, fee_policy, overpay_bps);
674
675        let (prepared, order_id) = match invoice {
676            LightningInvoice::Quote => {
677                let prepared = self
678                    .quoter
679                    .quote_send(
680                        recipient_address,
681                        route,
682                        source_sats,
683                        DeliveryMethod::Lightning,
684                        None,
685                        slippage_bps,
686                        fee_policy.into(),
687                        refund_address,
688                    )
689                    .await?;
690                (prepared, None)
691            }
692            LightningInvoice::CashApp => {
693                let order = self
694                    .quoter
695                    .prepare_onramp_send(
696                        recipient_address,
697                        route,
698                        source_sats,
699                        slippage_bps,
700                        fee_policy.into(),
701                        refund_address,
702                    )
703                    .await?;
704                (order.prepared, Some(order.order_id))
705            }
706        };
707
708        let checked = match check_refund_outlives(refund.as_ref(), &prepared.expires_at) {
709            Ok(()) => self.check_lightning_funded(&prepared).await,
710            Err(e) => Err(e),
711        };
712        let (deposit_target, amount_sats) = checked.inspect_err(|e| {
713            // The order exists and expires unpaid, but support may ask for it.
714            if let Some(order_id) = &order_id {
715                tracing::warn!("Bridging: discarding order {order_id}: {e}");
716            }
717        })?;
718
719        Ok(LightningFunded {
720            prepared,
721            deposit_target,
722            amount_sats,
723            order_id,
724        })
725    }
726
727    /// The BOLT11 the payer funds and its amount in sats, checked against the
728    /// quote before the payer is sent to it.
729    async fn check_lightning_funded(
730        &self,
731        prepared: &CrossChainSendPrepared,
732    ) -> Result<(String, u64), SdkError> {
733        let amount_sats = u64::try_from(prepared.amount_in).map_err(|_| {
734            SdkError::Generic(format!(
735                "Deposit amount {} sats exceeds u64::MAX",
736                prepared.amount_in
737            ))
738        })?;
739        // The payer funds the provider's invoice directly, and the provider
740        // delivers once it is paid: there is no Spark transfer to make.
741        let deposit_target = deposit_target(&prepared.provider_context);
742        let parsed_target = self.parse(&deposit_target).await;
743        check_deposit_target(&parsed_target, amount_sats)?;
744        Ok((deposit_target, amount_sats))
745    }
746
747    /// The refund destination a Lightning-funded order takes for
748    /// `refund_address`: a Lightning address, a `$cashtag` as its Cash App
749    /// Lightning address, or an unexpired amountless mainnet BOLT11. Anything
750    /// else fails with `InvalidInput`.
751    async fn lightning_refund_address(
752        &self,
753        refund_address: Option<&str>,
754    ) -> Result<Option<LightningRefund>, SdkError> {
755        let Some(input) = refund_address.map(str::trim).filter(|a| !a.is_empty()) else {
756            return Ok(None);
757        };
758        let parsed = if input.starts_with('$') || validate_lightning_address_format(input) {
759            None
760        } else {
761            self.parse(input).await.ok()
762        };
763        accepted_lightning_refund(input, parsed.as_ref(), now_secs())
764            .map(Some)
765            .ok_or_else(|| {
766                SdkError::InvalidInput(
767                    "A Lightning refund address must be a Lightning address, a $cashtag or an \
768                     unexpired amountless mainnet BOLT11 invoice"
769                        .to_string(),
770                )
771            })
772    }
773
774    /// Quotes an order the payer funds with a deposit on `route`'s chain,
775    /// delivering `destination` to `recipient` over `delivery_method`.
776    #[allow(clippy::too_many_arguments)]
777    async fn quote_external_funded(
778        &self,
779        route: &CrossChainRoutePair,
780        amount: u128,
781        destination: SparkAsset,
782        delivery_method: DeliveryMethod,
783        recipient: &str,
784        refund_address: Option<&str>,
785        fee_policy: Option<FeePolicy>,
786        max_slippage_bps: Option<u32>,
787    ) -> Result<CrossChainReceivePrepared, SdkError> {
788        let params = resolve_cross_chain_receive_params(
789            &self.cross_chain_context,
790            self.cross_chain_config.as_ref(),
791            route,
792            amount,
793            delivery_method,
794            fee_policy.map(Into::into),
795            max_slippage_bps,
796            None,
797        )?;
798        let destination = validate_receive_destination(route, destination)?;
799        quote_cross_chain_receive(
800            &self.cross_chain_context,
801            route,
802            amount,
803            &destination,
804            &params,
805            recipient,
806            refund_address,
807        )
808        .await
809    }
810
811    /// Creates a bridge to `recipient_address` on another chain, funded over
812    /// Lightning or by a stablecoin deposit, as `route` says.
813    #[allow(clippy::too_many_arguments)]
814    async fn create_bridge_to_other_chain(
815        &self,
816        recipient_address: &str,
817        route: &BridgeRoutePair,
818        amount: u128,
819        refund_address: Option<&str>,
820        fee_policy: Option<FeePolicy>,
821        max_slippage_bps: Option<u32>,
822        invoice: LightningInvoice,
823    ) -> Result<CreateBridgeResponse, SdkError> {
824        if delivery_method(&route.source) == Some(DeliveryMethod::Lightning) {
825            let destination = external_pair(
826                route,
827                &route.destination,
828                Some((SparkAsset::Bitcoin, DeliveryMethod::Lightning)),
829            );
830            let funded = self
831                .quote_lightning_funded(
832                    recipient_address,
833                    &destination,
834                    amount,
835                    fee_policy,
836                    max_slippage_bps,
837                    invoice,
838                    refund_address,
839                )
840                .await?;
841            return lightning_funded_bridge_response(funded);
842        }
843
844        let source = external_pair(route, &route.source, None);
845        let refund = self
846            .validate_refund_address(refund_address, &source)
847            .await?;
848        let prepared = self
849            .quote_chain_to_chain(
850                route,
851                &source,
852                amount,
853                recipient_address,
854                refund.as_deref(),
855                fee_policy,
856                max_slippage_bps,
857            )
858            .await?;
859        Ok(create_bridge_response(prepared))
860    }
861
862    /// Quotes an order the payer funds with a stablecoin deposit on
863    /// `source`'s chain, delivering `route`'s destination stablecoin to
864    /// `recipient`. `amount` is in destination units.
865    #[allow(clippy::too_many_arguments)]
866    async fn quote_chain_to_chain(
867        &self,
868        route: &BridgeRoutePair,
869        source: &CrossChainRoutePair,
870        amount: u128,
871        recipient: &str,
872        refund_address: Option<&str>,
873        fee_policy: Option<FeePolicy>,
874        max_slippage_bps: Option<u32>,
875    ) -> Result<CrossChainReceivePrepared, SdkError> {
876        let slippage_bps = resolve_slippage_bps(max_slippage_bps, self.default_slippage_bps())?;
877        let overpay_bps = crate::cross_chain::resolve_target_overpay_bps(
878            None,
879            self.default_target_overpay_bps(),
880        )?;
881        let fee_mode: CrossChainFeeMode = fee_policy.unwrap_or_default().into();
882        // Fees included, `amount` is the deposit, at parity in the source asset.
883        let provider_amount = match fee_mode {
884            CrossChainFeeMode::FeesExcluded => amount,
885            CrossChainFeeMode::FeesIncluded => source_units(route, amount)?,
886        };
887        if provider_amount == 0 {
888            return Err(SdkError::InvalidInput(
889                "Amount is too small for this route".to_string(),
890            ));
891        }
892        let destination = DepositDestination {
893            chain: route.destination.chain.clone(),
894            asset: route.destination.asset.clone(),
895            decimals: route.destination.decimals.into(),
896            token_identifier: None,
897        };
898        let quote = self
899            .quoter
900            .quote_deposit(
901                source,
902                &destination,
903                route.limits.as_ref(),
904                recipient,
905                provider_amount,
906                slippage_bps,
907                fee_mode,
908                overpay_bps,
909                refund_address,
910            )
911            .await?;
912        Ok(quote.prepared)
913    }
914
915    /// The routes the provider serves out of `chain` when `is_send`, into it
916    /// otherwise.
917    async fn listed_routes(
918        &self,
919        chain: &str,
920        is_send: bool,
921    ) -> Result<Vec<BridgeRoutePair>, SdkError> {
922        let routes = self.quoter.route_listing(chain, is_send).await?;
923        Ok(routes.iter().map(to_bridge_route_pair).collect())
924    }
925
926    /// Routes to a recipient on another chain: funded over Lightning, or by a
927    /// deposit into one of the chains Lightning-funded routes reach.
928    async fn routes_to_other_chain(
929        &self,
930        recipient: &BridgeRecipient,
931    ) -> Result<Vec<BridgeRoutePair>, SdkError> {
932        let mut routes = self
933            .listed_routes(delivery_method_to_wire(DeliveryMethod::Lightning), true)
934            .await?;
935        routes.retain(|route| route_pays(recipient, route));
936        let mut chains: Vec<String> = routes.iter().map(|r| r.destination.chain.clone()).collect();
937        chains.sort();
938        chains.dedup();
939        let listings =
940            futures::future::join_all(chains.iter().map(|chain| self.listed_routes(chain, false)))
941                .await;
942        for (chain, listing) in chains.iter().zip(listings) {
943            match listing {
944                Ok(listed) => routes.extend(listed),
945                Err(e) => tracing::warn!("Bridging: listing the routes into {chain} failed: {e}"),
946            }
947        }
948        Ok(routes)
949    }
950}
951
952/// Who a bridge pays.
953#[derive(Debug, Clone)]
954enum BridgeRecipient {
955    /// Paid in Bitcoin or a Spark token.
956    Spark(SparkAddressDetails),
957    /// Paid in Bitcoin over Lightning.
958    Lightning(LightningAddressDetails),
959    /// Paid in a USD stablecoin, or the chain's native coin.
960    CrossChain(CrossChainAddressDetails),
961    /// Paid in Bitcoin on-chain.
962    Bitcoin(BitcoinAddressDetails),
963}
964
965/// The order routes are listed in: by what the payer pays, then stablecoin
966/// destinations ahead of native coins, then by what the recipient receives.
967fn route_order(route: &BridgeRoutePair) -> (&str, &str, bool, &str, &str) {
968    (
969        &route.source.asset,
970        &route.source.chain,
971        is_native_coin(&route.destination),
972        &route.destination.asset,
973        &route.destination.chain,
974    )
975}
976
977/// Whether `route` pays `recipient`. A Spark or Lightning recipient is paid
978/// from a stablecoin deposit on another chain. A recipient on another chain
979/// is paid a stablecoin from one too, or over Lightning, and only Lightning
980/// pays a native coin or Bitcoin on-chain.
981fn route_pays(recipient: &BridgeRecipient, route: &BridgeRoutePair) -> bool {
982    let (source, destination) = (&route.source, &route.destination);
983    match recipient {
984        BridgeRecipient::Spark(_) => {
985            is_deposit(source)
986                && delivery_method(destination) == Some(DeliveryMethod::Spark)
987                && (is_bitcoin(destination)
988                    || (destination.contract_address.is_some()
989                        && is_usd_stable_asset(&destination.asset)))
990        }
991        BridgeRecipient::Lightning(_) => {
992            is_deposit(source) && delivery_method(destination) == Some(DeliveryMethod::Lightning)
993        }
994        BridgeRecipient::CrossChain(details) => {
995            let funded = delivery_method(source) == Some(DeliveryMethod::Lightning)
996                || (is_deposit(source) && !is_native_coin(destination));
997            funded && pays_address(destination, details)
998        }
999        BridgeRecipient::Bitcoin(_) => {
1000            delivery_method(source) == Some(DeliveryMethod::Lightning)
1001                && delivery_method(destination) == Some(DeliveryMethod::Bitcoin)
1002                && is_bitcoin(destination)
1003        }
1004    }
1005}
1006
1007/// The side whose base units a bridge's `amount` is in, for a route paying
1008/// `destination_asset`: the recipient's when it is a USD stablecoin, the
1009/// payer's otherwise.
1010pub(super) fn amount_side(destination_asset: &str) -> BridgeAmountSide {
1011    if is_usd_stable_asset(destination_asset) {
1012        BridgeAmountSide::Destination
1013    } else {
1014        BridgeAmountSide::Source
1015    }
1016}
1017
1018/// Whether `listed` has a route with `route`'s sides.
1019fn is_listed(listed: &[BridgeRoutePair], route: &BridgeRoutePair) -> bool {
1020    listed
1021        .iter()
1022        .any(|r| r.source == route.source && r.destination == route.destination)
1023}
1024
1025/// The delivery method `side` is on, or `None` for another chain. Lightning
1026/// only carries Bitcoin, while Spark also carries tokens.
1027fn delivery_method(side: &BridgeRoutePairSide) -> Option<DeliveryMethod> {
1028    delivery_method_from_wire(&side.chain)
1029}
1030
1031fn is_bitcoin(side: &BridgeRoutePairSide) -> bool {
1032    side.asset.eq_ignore_ascii_case("BTC")
1033}
1034
1035/// A stablecoin on another chain whose token contract names its address
1036/// family, so a refund address can be checked against it.
1037fn is_deposit(side: &BridgeRoutePairSide) -> bool {
1038    delivery_method(side).is_none()
1039        && is_usd_stable_asset(&side.asset)
1040        && side
1041            .contract_address
1042            .as_deref()
1043            .and_then(detect_address_family)
1044            .is_some()
1045}
1046
1047/// A chain's own coin, on a chain other than Spark, Lightning and Bitcoin.
1048fn is_native_coin(side: &BridgeRoutePairSide) -> bool {
1049    delivery_method(side).is_none()
1050        && side.contract_address.is_none()
1051        && !is_usd_stable_asset(&side.asset)
1052}
1053
1054/// The address family of the chain a native coin `side` is on: the family
1055/// that names the chain, else EVM for a decimal EIP-155 chain id.
1056fn native_coin_family(side: &BridgeRoutePairSide) -> Option<CrossChainAddressFamily> {
1057    [
1058        CrossChainAddressFamily::Evm,
1059        CrossChainAddressFamily::Solana,
1060        CrossChainAddressFamily::Tron,
1061        CrossChainAddressFamily::Xrp,
1062        CrossChainAddressFamily::Zcash,
1063    ]
1064    .into_iter()
1065    .find(|family| family.matches_chain(&side.chain, None))
1066    .or_else(|| {
1067        side.chain_id
1068            .as_deref()?
1069            .parse::<u64>()
1070            .ok()
1071            .map(|_| CrossChainAddressFamily::Evm)
1072    })
1073}
1074
1075/// Whether `side` delivers a stablecoin or native coin `recipient` can hold:
1076/// on a chain of its address family, and the token and chain it names, if
1077/// any.
1078fn pays_address(side: &BridgeRoutePairSide, recipient: &CrossChainAddressDetails) -> bool {
1079    let family: CrossChainAddressFamily = recipient.address_family.into();
1080    let on_family = if is_usd_stable_asset(&side.asset) {
1081        family.matches_chain(&side.chain, side.contract_address.as_deref())
1082    } else {
1083        is_native_coin(side) && native_coin_family(side) == Some(family)
1084    };
1085    delivery_method(side).is_none()
1086        && on_family
1087        && recipient.contract_address.as_deref().is_none_or(|wanted| {
1088            side.contract_address
1089                .as_deref()
1090                .is_some_and(|contract| family.addresses_equal(contract, wanted))
1091        })
1092        && recipient.chain_id.is_none_or(|wanted| {
1093            side.chain_id
1094                .as_deref()
1095                .and_then(|id| id.parse::<u64>().ok())
1096                == Some(wanted)
1097        })
1098}
1099
1100/// The Spark asset a route pays a Spark recipient.
1101fn spark_asset(side: &BridgeRoutePairSide) -> SparkAsset {
1102    match &side.contract_address {
1103        Some(token_identifier) if !is_bitcoin(side) => SparkAsset::Token {
1104            token_identifier: token_identifier.clone(),
1105        },
1106        _ => SparkAsset::Bitcoin,
1107    }
1108}
1109
1110/// `amount` in source units. A stablecoin destination is rescaled at parity,
1111/// and any other amount is already in source units.
1112fn source_units(route: &BridgeRoutePair, amount: u128) -> Result<u128, SdkError> {
1113    if amount_side(&route.destination.asset) == BridgeAmountSide::Source {
1114        return Ok(amount);
1115    }
1116    rescale_decimals(
1117        amount,
1118        route.destination.decimals.into(),
1119        route.source.decimals.into(),
1120    )
1121}
1122
1123/// `side` as the external side of a [`CrossChainRoutePair`], for the quoting
1124/// and checks written against one. `local` is the Spark asset the route moves
1125/// and the rail it moves on.
1126fn external_pair(
1127    route: &BridgeRoutePair,
1128    side: &BridgeRoutePairSide,
1129    local: Option<(SparkAsset, DeliveryMethod)>,
1130) -> CrossChainRoutePair {
1131    let (accepted_assets, delivery_methods) = match local {
1132        Some((asset, delivery_method)) => (
1133            vec![CrossChainAcceptedAsset {
1134                asset,
1135                limits: route.limits.clone(),
1136            }],
1137            vec![delivery_method],
1138        ),
1139        None => (Vec::new(), Vec::new()),
1140    };
1141    CrossChainRoutePair {
1142        provider: route.provider,
1143        chain: side.chain.clone(),
1144        chain_id: side.chain_id.clone(),
1145        asset: side.asset.clone(),
1146        contract_address: side.contract_address.clone(),
1147        decimals: side.decimals,
1148        exact_out_eligible: false,
1149        accepted_assets,
1150        delivery_methods,
1151    }
1152}
1153
1154/// Rejects a Bitcoin address on a network other than mainnet.
1155fn validate_bitcoin_recipient(details: &BitcoinAddressDetails) -> Result<(), SdkError> {
1156    if details.network != BitcoinNetwork::Bitcoin {
1157        return Err(SdkError::InvalidInput(
1158            "The Bitcoin address is not a mainnet address".to_string(),
1159        ));
1160    }
1161    Ok(())
1162}
1163
1164/// Rejects a Spark address on a network other than mainnet.
1165fn validate_spark_recipient(details: &crate::SparkAddressDetails) -> Result<(), SdkError> {
1166    if details.network != BitcoinNetwork::Bitcoin {
1167        return Err(SdkError::InvalidInput(
1168            "The Spark address is not a mainnet address".to_string(),
1169        ));
1170    }
1171    Ok(())
1172}
1173
1174/// Checks the Lightning address accepts `expected_sats`, the amount the
1175/// provider will pay it.
1176fn check_lightning_address_accepts(
1177    recipient: &LightningAddressDetails,
1178    expected_sats: u128,
1179) -> Result<(), SdkError> {
1180    let amount_msat = u64::try_from(expected_sats)
1181        .ok()
1182        .and_then(|sats| sats.checked_mul(1000))
1183        .ok_or_else(|| SdkError::InvalidInput("Amount is too large".to_string()))?;
1184    validate_user_input(
1185        amount_msat,
1186        &None,
1187        recipient.pay_request.min_sendable,
1188        recipient.pay_request.max_sendable,
1189        0,
1190    )
1191    .map_err(|e| SdkError::InvalidInput(e.to_string()))
1192}
1193
1194fn create_bridge_response(prepared: CrossChainReceivePrepared) -> CreateBridgeResponse {
1195    CreateBridgeResponse {
1196        bridge_id: prepared.info.quote_id.clone(),
1197        status_token: prepared.quote_read_token,
1198        payment_request: prepared.payment_request,
1199        info: prepared.info,
1200    }
1201}
1202
1203/// The response for a bridge the payer funds over Lightning: the deposit is
1204/// the provider's BOLT11 for `amount_sats`, and the recipient receives the
1205/// route's destination asset. The bridge is the order when there is one,
1206/// otherwise the quote.
1207fn lightning_funded_bridge_response(
1208    funded: LightningFunded,
1209) -> Result<CreateBridgeResponse, SdkError> {
1210    let LightningFunded {
1211        prepared,
1212        deposit_target,
1213        amount_sats,
1214        order_id,
1215    } = funded;
1216    let CrossChainProviderContext::Orchestra { quote_id, .. } = prepared.provider_context else {
1217        return Err(SdkError::Generic(
1218            "Bridging is only supported on Orchestra routes".to_string(),
1219        ));
1220    };
1221    Ok(CreateBridgeResponse {
1222        bridge_id: order_id.unwrap_or_else(|| quote_id.clone()),
1223        status_token: prepared.quote_read_token,
1224        payment_request: deposit_target.clone(),
1225        info: CrossChainReceiveInfo {
1226            quote_id,
1227            deposit_address: deposit_target,
1228            deposit_amount: u128::from(amount_sats),
1229            expected_received_amount: prepared.estimated_out,
1230            destination_asset: prepared.pair.asset,
1231            token_identifier: None,
1232            service_fee_amount: prepared.service_fee_amount,
1233            service_fee_asset: prepared.service_fee_asset,
1234            service_fee_asset_decimals: prepared.service_fee_asset_decimals,
1235            expires_at: parse_rfc3339_to_unix_seconds(&prepared.expires_at)?,
1236        },
1237    })
1238}
1239
1240/// Where a bridge the payer funds over Lightning gets its invoice.
1241#[derive(Debug, Clone, Copy)]
1242enum LightningInvoice {
1243    /// A quote's invoice.
1244    Quote,
1245    /// An onramp order's invoice.
1246    CashApp,
1247}
1248
1249/// A bridge the payer funds over Lightning, before it is reported.
1250struct LightningFunded {
1251    prepared: CrossChainSendPrepared,
1252    /// The BOLT11 invoice the payer pays.
1253    deposit_target: String,
1254    amount_sats: u64,
1255    /// The order, when the invoice is an onramp order's.
1256    order_id: Option<String>,
1257}
1258
1259/// Where a Lightning-funded bridge refunds a failure before the swap.
1260#[derive(Debug, PartialEq)]
1261struct LightningRefund {
1262    address: String,
1263    /// When the refund can no longer be paid, for an invoice.
1264    expires_at: Option<u64>,
1265}
1266
1267/// What [`BridgingClient::lightning_refund_address`] accepts for `input`,
1268/// which parsed as `parsed` when it is neither a cashtag nor a Lightning
1269/// address.
1270fn accepted_lightning_refund(
1271    input: &str,
1272    parsed: Option<&InputType>,
1273    now: u64,
1274) -> Option<LightningRefund> {
1275    let address = |address: String| LightningRefund {
1276        address,
1277        expires_at: None,
1278    };
1279    if input.starts_with('$') {
1280        return cash_app_lightning_address(input).map(address);
1281    }
1282    if validate_lightning_address_format(input) {
1283        return Some(address(input.to_string()));
1284    }
1285    match parsed {
1286        // Orchestra refuses an invoice with an amount: the refund sets it.
1287        Some(InputType::Bolt11Invoice(details))
1288            if details.network == BitcoinNetwork::Bitcoin
1289                && details.amount_msat.is_none()
1290                && details.timestamp.saturating_add(details.expiry) > now =>
1291        {
1292            Some(LightningRefund {
1293                address: details.invoice.bolt11.clone(),
1294                expires_at: Some(details.timestamp.saturating_add(details.expiry)),
1295            })
1296        }
1297        _ => None,
1298    }
1299}
1300
1301/// Errors if `refund` is an invoice that expires before the bridge, which
1302/// can be paid until `bridge_expires_at`: a failure after a late payment
1303/// could not be refunded.
1304fn check_refund_outlives(
1305    refund: Option<&LightningRefund>,
1306    bridge_expires_at: &str,
1307) -> Result<(), SdkError> {
1308    let Some(refund_expires_at) = refund.and_then(|r| r.expires_at) else {
1309        return Ok(());
1310    };
1311    if refund_expires_at < parse_rfc3339_to_unix_seconds(bridge_expires_at)? {
1312        return Err(SdkError::InvalidInput(
1313            "The refund invoice expires before the bridge does".to_string(),
1314        ));
1315    }
1316    Ok(())
1317}
1318
1319/// Whether a bridge id names an order rather than a quote. Orchestra's API
1320/// documents order ids as `ord_...` (`GET /v1/explorer/operations/{id}`), and
1321/// its quote ids start with `q_`.
1322fn is_order_id(bridge_id: &str) -> bool {
1323    bridge_id.starts_with("ord_")
1324}
1325
1326/// Whether `route` advertises `required` as a fundable delivery method. An
1327/// empty `delivery_methods` (e.g. a hand-built route) matches nothing and is
1328/// rejected.
1329fn route_supports_delivery_method(route: &CrossChainRoutePair, required: DeliveryMethod) -> bool {
1330    route.delivery_methods.contains(&required)
1331}
1332
1333/// Verifies the provider's deposit `target` is a BOLT11 invoice requesting
1334/// exactly `expected_sats`, the Lightning payment request the payer funds. A
1335/// wrong type, wrong amount, or unparseable target indicates a provider bug.
1336pub(super) fn check_deposit_target(
1337    parsed_target: &Result<InputType, SdkError>,
1338    expected_sats: u64,
1339) -> Result<(), SdkError> {
1340    let Ok(InputType::Bolt11Invoice(details)) = parsed_target else {
1341        return Err(SdkError::Generic(
1342            "The provider returned a deposit target that is not a valid Lightning \
1343             payment request"
1344                .to_string(),
1345        ));
1346    };
1347    // The invoice must request the quoted deposit: a mismatch would have the
1348    // payer fund the wrong amount.
1349    if details.amount_msat.map(u128::from) != Some(u128::from(expected_sats) * 1000) {
1350        return Err(SdkError::Generic(format!(
1351            "The provider's deposit invoice does not request the quoted \
1352             {expected_sats} sats"
1353        )));
1354    }
1355    Ok(())
1356}
1357
1358/// The BOLT11 an external payer funds, read from the provider context
1359/// (Orchestra `deposit_address` or Boltz `invoice`).
1360fn deposit_target(context: &CrossChainProviderContext) -> String {
1361    match context {
1362        CrossChainProviderContext::Orchestra {
1363            deposit_address, ..
1364        } => deposit_address.clone(),
1365        CrossChainProviderContext::Boltz { invoice, .. } => invoice.clone(),
1366    }
1367}
1368
1369/// Maps a [`CrossChainSendPrepared`] + funding `url` to a
1370/// [`BridgeFromCashAppResponse`].
1371///
1372/// `estimated_out` is in the destination `asset`'s base units. The fee mirrors
1373/// the cross-chain send response: `service_fee_amount` in `service_fee_asset`
1374/// base units, where `None` means sats (Boltz denominates its fee in sats;
1375/// Orchestra in the stablecoin).
1376fn bridge_from_cash_app_response(
1377    prepared: CrossChainSendPrepared,
1378    url: String,
1379    amount_sats: u64,
1380) -> Result<BridgeFromCashAppResponse, SdkError> {
1381    Ok(BridgeFromCashAppResponse {
1382        url,
1383        amount_sats,
1384        estimated_out: prepared.estimated_out,
1385        asset: prepared.pair.asset,
1386        service_fee_amount: prepared.service_fee_amount,
1387        service_fee_asset: prepared.service_fee_asset,
1388        service_fee_asset_decimals: prepared.service_fee_asset_decimals,
1389        expires_at: parse_rfc3339_to_unix_seconds(&prepared.expires_at)?,
1390    })
1391}
1392
1393#[cfg(test)]
1394mod tests {
1395    use std::sync::Arc;
1396
1397    use breez_sdk_common::buy::cashapp::CashAppProvider;
1398    use macros::{async_test_all, test_all};
1399
1400    use super::{
1401        BridgeAmountSide, BridgeRecipient, BridgeRoutePair, BridgeRoutePairSide, BridgeStatus,
1402        BridgingClient, CreateBridgeRequest, GetBridgeStatusRequest, LightningFunded,
1403        LightningInvoice, LightningRefund, accepted_lightning_refund, amount_side,
1404        bridge_from_cash_app_response, check_lightning_address_accepts, check_refund_outlives,
1405        deposit_target, external_pair, is_listed, is_order_id, lightning_funded_bridge_response,
1406        native_coin_family, route_order, route_pays, route_supports_delivery_method, source_units,
1407        validate_spark_recipient,
1408    };
1409    use crate::cross_chain::{CrossChainProviderContext, CrossChainSendPrepared};
1410    use crate::{
1411        BitcoinAddressDetails, BitcoinNetwork, Bolt11Invoice, Bolt11InvoiceDetails,
1412        CrossChainAddressDetails, CrossChainAddressFamily, CrossChainFeeMode, CrossChainProvider,
1413        CrossChainRouteLimits, CrossChainRoutePair, DeliveryMethod, InputType,
1414        LightningAddressDetails, LnurlPayRequestDetails, PaymentRequestSource, SdkError,
1415        SparkAddressDetails, SparkAsset,
1416    };
1417
1418    #[cfg(feature = "browser-tests")]
1419    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
1420
1421    fn orchestra_context() -> CrossChainProviderContext {
1422        CrossChainProviderContext::Orchestra {
1423            quote_id: "q1".to_string(),
1424            deposit_address: "lnbc100u1pxyz".to_string(),
1425            deposit_amount: 5000,
1426        }
1427    }
1428
1429    fn route_with_delivery_methods(methods: Vec<DeliveryMethod>) -> CrossChainRoutePair {
1430        CrossChainRoutePair {
1431            provider: CrossChainProvider::Orchestra,
1432            chain: "base".to_string(),
1433            chain_id: Some("8453".to_string()),
1434            asset: "USDC".to_string(),
1435            contract_address: None,
1436            decimals: 6,
1437            exact_out_eligible: false,
1438            accepted_assets: vec![],
1439            delivery_methods: methods,
1440        }
1441    }
1442
1443    #[test_all]
1444    fn route_supports_delivery_method_checks_membership() {
1445        let lightning_only = route_with_delivery_methods(vec![DeliveryMethod::Lightning]);
1446        // Cash App (Lightning) is supported; MoonPay (Bitcoin) is not.
1447        assert!(route_supports_delivery_method(
1448            &lightning_only,
1449            DeliveryMethod::Lightning
1450        ));
1451        assert!(!route_supports_delivery_method(
1452            &lightning_only,
1453            DeliveryMethod::Bitcoin
1454        ));
1455
1456        let both =
1457            route_with_delivery_methods(vec![DeliveryMethod::Lightning, DeliveryMethod::Bitcoin]);
1458        assert!(route_supports_delivery_method(
1459            &both,
1460            DeliveryMethod::Bitcoin
1461        ));
1462
1463        // An empty list matches nothing: a route must advertise its rails, so a
1464        // hand-built route can't slip a bad rail through to `prepare`.
1465        let empty = route_with_delivery_methods(vec![]);
1466        assert!(!route_supports_delivery_method(
1467            &empty,
1468            DeliveryMethod::Bitcoin
1469        ));
1470    }
1471
1472    fn prepared(provider_context: CrossChainProviderContext) -> CrossChainSendPrepared {
1473        CrossChainSendPrepared {
1474            amount_in: 5000,
1475            asset_amount_in: 6_500_000,
1476            estimated_out: 6_450_000,
1477            fee_amount: 50_000,
1478            service_fee_amount: 47_684,
1479            service_fee_asset: Some("USDC".to_string()),
1480            service_fee_asset_decimals: Some(6),
1481            source_transfer_fee_sats: 0,
1482            fee_mode: CrossChainFeeMode::FeesExcluded,
1483            expires_at: "2026-07-25T08:09:26.770Z".to_string(),
1484            pair: CrossChainRoutePair {
1485                provider: CrossChainProvider::Orchestra,
1486                chain: "base".to_string(),
1487                chain_id: Some("8453".to_string()),
1488                asset: "USDC".to_string(),
1489                contract_address: None,
1490                decimals: 6,
1491                exact_out_eligible: false,
1492                accepted_assets: vec![],
1493                delivery_methods: vec![],
1494            },
1495            recipient_address: "0xabc".to_string(),
1496            token_identifier: None,
1497            provider_context,
1498            quote_read_token: None,
1499        }
1500    }
1501
1502    #[test_all]
1503    fn deposit_target_reads_orchestra_address_and_boltz_invoice() {
1504        assert_eq!(deposit_target(&orchestra_context()), "lnbc100u1pxyz");
1505        assert_eq!(
1506            deposit_target(&CrossChainProviderContext::Boltz {
1507                swap_id: "s1".to_string(),
1508                invoice: "lnbc200u1pboltz".to_string(),
1509                invoice_amount_sats: 5000,
1510                max_slippage_bps: 100,
1511            }),
1512            "lnbc200u1pboltz"
1513        );
1514    }
1515
1516    #[test_all]
1517    fn cashapp_url_built_from_deposit_target() {
1518        let url = CashAppProvider::build_url(&deposit_target(&orchestra_context()));
1519        assert_eq!(url, "https://cash.app/launch/lightning/lnbc100u1pxyz");
1520    }
1521
1522    #[test_all]
1523    fn orchestra_response_maps_stablecoin_fee() {
1524        let resp = bridge_from_cash_app_response(
1525            prepared(orchestra_context()),
1526            "https://x".to_string(),
1527            5000,
1528        )
1529        .unwrap();
1530        assert_eq!(resp.url, "https://x");
1531        assert_eq!(resp.expires_at, 1_784_966_966);
1532        assert_eq!(resp.amount_sats, 5000);
1533        assert_eq!(resp.estimated_out, 6_450_000);
1534        assert_eq!(resp.asset, "USDC");
1535        // Orchestra denominates its service fee in the stablecoin.
1536        assert_eq!(resp.service_fee_amount, 47_684);
1537        assert_eq!(resp.service_fee_asset.as_deref(), Some("USDC"));
1538        assert_eq!(resp.service_fee_asset_decimals, Some(6));
1539    }
1540
1541    #[test_all]
1542    fn boltz_response_reports_native_sats_fee() {
1543        let mut prepared = prepared(CrossChainProviderContext::Boltz {
1544            swap_id: "s1".to_string(),
1545            invoice: "lnbc200u1pboltz".to_string(),
1546            invoice_amount_sats: 5000,
1547            max_slippage_bps: 100,
1548        });
1549        // Boltz denominates its service fee in sats (service_fee_asset = None).
1550        prepared.service_fee_amount = 17;
1551        prepared.service_fee_asset = None;
1552        prepared.service_fee_asset_decimals = None;
1553        let resp = bridge_from_cash_app_response(prepared, "https://x".to_string(), 5000).unwrap();
1554        assert_eq!(resp.asset, "USDC");
1555        assert_eq!(resp.service_fee_amount, 17);
1556        assert_eq!(resp.service_fee_asset, None);
1557        assert_eq!(resp.service_fee_asset_decimals, None);
1558    }
1559
1560    fn spark_address(network: BitcoinNetwork) -> SparkAddressDetails {
1561        SparkAddressDetails {
1562            address: "spark1merchant".to_string(),
1563            identity_public_key: "02".to_string(),
1564            network,
1565            source: PaymentRequestSource::default(),
1566        }
1567    }
1568
1569    fn lightning_address(min_sendable: u64, max_sendable: u64) -> LightningAddressDetails {
1570        LightningAddressDetails {
1571            address: "alice@cash.app".to_string(),
1572            pay_request: LnurlPayRequestDetails {
1573                callback: "https://cash.app/callback".to_string(),
1574                min_sendable,
1575                max_sendable,
1576                metadata_str: "[]".to_string(),
1577                comment_allowed: 0,
1578                domain: "cash.app".to_string(),
1579                url: "https://cash.app/.well-known/lnurlp/alice".to_string(),
1580                address: Some("alice@cash.app".to_string()),
1581                allows_nostr: None,
1582                nostr_pubkey: None,
1583            },
1584        }
1585    }
1586
1587    #[test_all]
1588    fn spark_recipient_must_be_on_mainnet() {
1589        assert!(validate_spark_recipient(&spark_address(BitcoinNetwork::Bitcoin)).is_ok());
1590        assert!(matches!(
1591            validate_spark_recipient(&spark_address(BitcoinNetwork::Regtest)),
1592            Err(SdkError::InvalidInput(_))
1593        ));
1594    }
1595
1596    #[test_all]
1597    fn lightning_address_bounds_are_checked_in_msat() {
1598        let recipient = lightning_address(1_000_000, 100_000_000);
1599        assert!(check_lightning_address_accepts(&recipient, 1_000).is_ok());
1600        assert!(check_lightning_address_accepts(&recipient, 100_000).is_ok());
1601        assert!(check_lightning_address_accepts(&recipient, 999).is_err());
1602        assert!(check_lightning_address_accepts(&recipient, 100_001).is_err());
1603    }
1604
1605    /// A client whose provider calls would fail, for checks that must reject
1606    /// a request before anything is quoted.
1607    fn offline_client() -> BridgingClient {
1608        struct Unreachable;
1609
1610        #[macros::async_trait]
1611        impl platform_utils::HttpClient for Unreachable {
1612            async fn get(
1613                &self,
1614                url: String,
1615                _: Option<std::collections::HashMap<String, String>>,
1616            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1617                panic!("unexpected GET {url}")
1618            }
1619            async fn post(
1620                &self,
1621                url: String,
1622                _: Option<std::collections::HashMap<String, String>>,
1623                _: Option<String>,
1624            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1625                panic!("unexpected POST {url}")
1626            }
1627            async fn delete(
1628                &self,
1629                url: String,
1630                _: Option<std::collections::HashMap<String, String>>,
1631                _: Option<String>,
1632            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1633                panic!("unexpected DELETE {url}")
1634            }
1635        }
1636
1637        struct NoConfig;
1638
1639        #[macros::async_trait]
1640        impl flashnet::OrchestraConfigResolver for NoConfig {
1641            async fn resolve(&self) -> Result<flashnet::OrchestraConfig, flashnet::FlashnetError> {
1642                panic!("unexpected Orchestra config lookup")
1643            }
1644        }
1645
1646        client_with(Arc::new(Unreachable), Arc::new(NoConfig))
1647    }
1648
1649    fn client_with(
1650        http: Arc<dyn platform_utils::HttpClient>,
1651        config: Arc<dyn flashnet::OrchestraConfigResolver>,
1652    ) -> BridgingClient {
1653        struct NoFiat;
1654
1655        #[macros::async_trait]
1656        impl breez_sdk_common::fiat::FiatService for NoFiat {
1657            async fn fetch_fiat_currencies(
1658                &self,
1659            ) -> Result<
1660                Vec<breez_sdk_common::fiat::FiatCurrency>,
1661                breez_sdk_common::error::ServiceConnectivityError,
1662            > {
1663                panic!("unexpected fiat lookup")
1664            }
1665            async fn fetch_fiat_rates(
1666                &self,
1667            ) -> Result<
1668                Vec<breez_sdk_common::fiat::Rate>,
1669                breez_sdk_common::error::ServiceConnectivityError,
1670            > {
1671                panic!("unexpected fiat lookup")
1672            }
1673        }
1674
1675        let fiat: Arc<dyn breez_sdk_common::fiat::FiatService> = Arc::new(NoFiat);
1676        let quoter = Arc::new(crate::cross_chain::OrchestraQuoter::new(
1677            config,
1678            None,
1679            Arc::clone(&fiat),
1680            Arc::clone(&http),
1681        ));
1682        let input_parser = Arc::new(crate::sdk::SdkInputParser::new(
1683            breez_sdk_common::dns::Resolver::with_proxy(None).unwrap(),
1684            http,
1685            None,
1686        ));
1687        BridgingClient::new(None, quoter, fiat, input_parser)
1688    }
1689
1690    #[test_all]
1691    fn a_lightning_refund_takes_a_lightning_address_cashtag_or_amountless_invoice() {
1692        let invoice = |amount_msat: Option<u64>, timestamp: u64| {
1693            InputType::Bolt11Invoice(Bolt11InvoiceDetails {
1694                amount_msat,
1695                description: None,
1696                description_hash: None,
1697                expiry: 3600,
1698                invoice: Bolt11Invoice {
1699                    bolt11: "lnbc1refund".to_string(),
1700                    source: PaymentRequestSource::default(),
1701                },
1702                min_final_cltv_expiry_delta: 144,
1703                network: BitcoinNetwork::Bitcoin,
1704                payee_pubkey: String::new(),
1705                payment_hash: String::new(),
1706                payment_secret: String::new(),
1707                routing_hints: vec![],
1708                timestamp,
1709            })
1710        };
1711        let now = 1_000_000;
1712        let accepted = |input: &str, parsed: Option<InputType>| {
1713            accepted_lightning_refund(input, parsed.as_ref(), now).map(|r| r.address)
1714        };
1715
1716        assert_eq!(
1717            accepted("alice@example.com", None).as_deref(),
1718            Some("alice@example.com")
1719        );
1720        assert_eq!(accepted("$alice", None).as_deref(), Some("alice@cash.app"));
1721        assert_eq!(accepted("$not-a-tag", None), None);
1722        assert_eq!(
1723            accepted("lightning:lnbc1refund", Some(invoice(None, now))).as_deref(),
1724            Some("lnbc1refund")
1725        );
1726        // The refund sets the amount, and an expired invoice can't take it.
1727        assert_eq!(accepted("lnbc1", Some(invoice(Some(1_000), now))), None);
1728        assert_eq!(accepted("lnbc1", Some(invoice(None, now - 3600))), None);
1729        // Bridges run on mainnet, where a refund can't pay a test network.
1730        let mut testnet = invoice(None, now);
1731        if let InputType::Bolt11Invoice(details) = &mut testnet {
1732            details.network = BitcoinNetwork::Testnet3;
1733        }
1734        assert_eq!(accepted("lntb1", Some(testnet)), None);
1735        assert_eq!(accepted("0xabc", None), None);
1736        assert_eq!(
1737            accepted_lightning_refund("lnbc1", Some(&invoice(None, now)), now)
1738                .and_then(|r| r.expires_at),
1739            Some(now + 3600)
1740        );
1741    }
1742
1743    #[test_all]
1744    fn a_refund_invoice_must_outlive_the_bridge() {
1745        let bridge_expires_at = "2026-11-10T12:00:00Z";
1746        let bridge_secs = super::parse_rfc3339_to_unix_seconds(bridge_expires_at).unwrap();
1747        let invoice = |expires_at| LightningRefund {
1748            address: "lnbc1refund".to_string(),
1749            expires_at: Some(expires_at),
1750        };
1751        let address = LightningRefund {
1752            address: "alice@cash.app".to_string(),
1753            expires_at: None,
1754        };
1755        assert!(check_refund_outlives(None, bridge_expires_at).is_ok());
1756        assert!(check_refund_outlives(Some(&address), bridge_expires_at).is_ok());
1757        assert!(check_refund_outlives(Some(&invoice(bridge_secs)), bridge_expires_at).is_ok());
1758        assert_invalid_input(
1759            check_refund_outlives(
1760                Some(&invoice(bridge_secs.checked_sub(1).unwrap())),
1761                bridge_expires_at,
1762            ),
1763            "expires before the bridge",
1764        );
1765    }
1766
1767    /// A client whose Orchestra knows one Lightning-funded order, `ord_1`, with
1768    /// `status`. Its explorer names the source chain and `/status` doesn't.
1769    fn explorer_client(status: &'static str) -> BridgingClient {
1770        struct Explorer(&'static str);
1771
1772        #[macros::async_trait]
1773        impl platform_utils::HttpClient for Explorer {
1774            async fn get(
1775                &self,
1776                url: String,
1777                _: Option<std::collections::HashMap<String, String>>,
1778            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1779                let mut operation = serde_json::json!({
1780                    "id": "ord_1",
1781                    "status": self.0,
1782                    "destinationChain": "base",
1783                    "createdAt": "2026-11-10T10:00:00Z",
1784                    "updatedAt": "2026-11-10T10:00:00Z",
1785                });
1786                let body = if url.contains("/v1/orchestration/status?id=ord_1") {
1787                    serde_json::json!({ "order": operation, "stages": [] })
1788                } else {
1789                    assert!(url.ends_with("/v1/explorer/operations?q=ord_1"), "{url}");
1790                    operation["sourceChain"] = "lightning".into();
1791                    serde_json::json!({
1792                        "operations": [{ "operation": operation, "partner": null, "refs": [] }],
1793                        "nextOffset": null,
1794                    })
1795                };
1796                Ok(platform_utils::HttpResponse {
1797                    status: 200,
1798                    body: body.to_string(),
1799                    headers: std::collections::HashMap::new(),
1800                })
1801            }
1802            async fn post(
1803                &self,
1804                url: String,
1805                _: Option<std::collections::HashMap<String, String>>,
1806                _: Option<String>,
1807            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1808                panic!("unexpected POST {url}")
1809            }
1810            async fn delete(
1811                &self,
1812                url: String,
1813                _: Option<std::collections::HashMap<String, String>>,
1814                _: Option<String>,
1815            ) -> Result<platform_utils::HttpResponse, platform_utils::HttpError> {
1816                panic!("unexpected DELETE {url}")
1817            }
1818        }
1819
1820        struct FixedConfig;
1821
1822        #[macros::async_trait]
1823        impl flashnet::OrchestraConfigResolver for FixedConfig {
1824            async fn resolve(&self) -> Result<flashnet::OrchestraConfig, flashnet::FlashnetError> {
1825                Ok(flashnet::OrchestraConfig {
1826                    base_url: "https://orchestra.test".to_string(),
1827                    api_key: "key".to_string(),
1828                })
1829            }
1830        }
1831
1832        client_with(Arc::new(Explorer(status)), Arc::new(FixedConfig))
1833    }
1834
1835    #[async_test_all]
1836    async fn an_unpaid_cash_app_bridge_is_created_until_its_order_expires() {
1837        for (order_status, expected) in [
1838            ("processing", BridgeStatus::Created),
1839            ("expired", BridgeStatus::Expired),
1840            ("swapping", BridgeStatus::Pending),
1841        ] {
1842            for status_token in [None, Some("rt_order".to_string())] {
1843                let response = explorer_client(order_status)
1844                    .get_bridge_status(GetBridgeStatusRequest {
1845                        bridge_id: "ord_1".to_string(),
1846                        status_token: status_token.clone(),
1847                    })
1848                    .await
1849                    .unwrap();
1850                assert_eq!(response.status, expected, "{order_status} {status_token:?}");
1851            }
1852        }
1853    }
1854
1855    fn create_request(recipient: &str, route: BridgeRoutePair) -> CreateBridgeRequest {
1856        CreateBridgeRequest {
1857            recipient: recipient.to_string(),
1858            route,
1859            amount: 10_000_000,
1860            refund_address: None,
1861            fee_policy: None,
1862            max_slippage_bps: None,
1863        }
1864    }
1865
1866    fn assert_invalid_input<T: std::fmt::Debug>(result: Result<T, SdkError>, contains: &str) {
1867        match result {
1868            Err(SdkError::InvalidInput(message)) => {
1869                assert!(message.contains(contains), "{message}");
1870            }
1871            other => panic!("expected InvalidInput containing {contains:?}, got {other:?}"),
1872        }
1873    }
1874
1875    fn base_address() -> CrossChainAddressDetails {
1876        CrossChainAddressDetails {
1877            address: "0x0000000000000000000000000000000000000001".to_string(),
1878            address_family: CrossChainAddressFamily::Evm,
1879            contract_address: None,
1880            chain_id: None,
1881            amount: None,
1882        }
1883    }
1884
1885    const BASE_USDC: &str = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
1886
1887    fn side(chain: &str, asset: &str, contract: Option<&str>, decimals: u8) -> BridgeRoutePairSide {
1888        BridgeRoutePairSide {
1889            chain: chain.to_string(),
1890            chain_id: None,
1891            asset: asset.to_string(),
1892            contract_address: contract.map(str::to_string),
1893            decimals,
1894        }
1895    }
1896
1897    fn base_usdc() -> BridgeRoutePairSide {
1898        BridgeRoutePairSide {
1899            chain_id: Some("8453".to_string()),
1900            ..side("base", "USDC", Some(BASE_USDC), 6)
1901        }
1902    }
1903
1904    fn base_usdt() -> BridgeRoutePairSide {
1905        BridgeRoutePairSide {
1906            chain_id: Some("8453".to_string()),
1907            ..side(
1908                "base",
1909                "USDT",
1910                Some("0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2"),
1911                6,
1912            )
1913        }
1914    }
1915
1916    fn tron_usdt() -> BridgeRoutePairSide {
1917        side(
1918            "tron",
1919            "USDT",
1920            Some("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"),
1921            6,
1922        )
1923    }
1924
1925    fn solana_usdc() -> BridgeRoutePairSide {
1926        side(
1927            "solana",
1928            "USDC",
1929            Some("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
1930            6,
1931        )
1932    }
1933
1934    fn base_weth() -> BridgeRoutePairSide {
1935        side(
1936            "base",
1937            "WETH",
1938            Some("0x4200000000000000000000000000000000000006"),
1939            18,
1940        )
1941    }
1942
1943    fn spark_btc() -> BridgeRoutePairSide {
1944        side("spark", "BTC", None, 8)
1945    }
1946
1947    fn spark_usdb() -> BridgeRoutePairSide {
1948        side("spark", "USDB", Some("btkn1usdb"), 6)
1949    }
1950
1951    fn lightning_btc() -> BridgeRoutePairSide {
1952        side("lightning", "BTC", None, 8)
1953    }
1954
1955    fn native(
1956        chain: &str,
1957        chain_id: Option<&str>,
1958        asset: &str,
1959        decimals: u8,
1960    ) -> BridgeRoutePairSide {
1961        BridgeRoutePairSide {
1962            chain_id: chain_id.map(str::to_string),
1963            ..side(chain, asset, None, decimals)
1964        }
1965    }
1966
1967    fn base_eth() -> BridgeRoutePairSide {
1968        native("base", Some("8453"), "ETH", 18)
1969    }
1970
1971    fn ethereum_eth() -> BridgeRoutePairSide {
1972        native("ethereum", Some("1"), "ETH", 18)
1973    }
1974
1975    fn bsc_bnb() -> BridgeRoutePairSide {
1976        native("bsc", Some("56"), "BNB", 18)
1977    }
1978
1979    fn tron_trx() -> BridgeRoutePairSide {
1980        native("tron", Some("728126428"), "TRX", 6)
1981    }
1982
1983    fn solana_sol() -> BridgeRoutePairSide {
1984        native(
1985            "solana",
1986            Some("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"),
1987            "SOL",
1988            9,
1989        )
1990    }
1991
1992    fn xrp_xrp() -> BridgeRoutePairSide {
1993        native("xrp", Some("xrp:mainnet"), "XRP", 6)
1994    }
1995
1996    fn zcash_zec() -> BridgeRoutePairSide {
1997        native("zcash", Some("zcash:mainnet"), "ZEC", 8)
1998    }
1999
2000    fn bitcoin_btc() -> BridgeRoutePairSide {
2001        native("bitcoin", None, "BTC", 8)
2002    }
2003
2004    fn pair(source: BridgeRoutePairSide, destination: BridgeRoutePairSide) -> BridgeRoutePair {
2005        BridgeRoutePair {
2006            provider: CrossChainProvider::Orchestra,
2007            amount_side: amount_side(&destination.asset),
2008            source,
2009            destination,
2010            limits: None,
2011        }
2012    }
2013
2014    fn spark_recipient() -> BridgeRecipient {
2015        BridgeRecipient::Spark(spark_address(BitcoinNetwork::Bitcoin))
2016    }
2017
2018    fn lightning_recipient() -> BridgeRecipient {
2019        BridgeRecipient::Lightning(lightning_address(1_000, 1_000_000))
2020    }
2021
2022    fn base_recipient() -> BridgeRecipient {
2023        BridgeRecipient::CrossChain(base_address())
2024    }
2025
2026    fn other_chain_recipient(address: &str, family: CrossChainAddressFamily) -> BridgeRecipient {
2027        BridgeRecipient::CrossChain(CrossChainAddressDetails {
2028            address: address.to_string(),
2029            address_family: family,
2030            ..base_address()
2031        })
2032    }
2033
2034    fn bitcoin_recipient() -> BridgeRecipient {
2035        BridgeRecipient::Bitcoin(BitcoinAddressDetails {
2036            address: "bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj".to_string(),
2037            network: BitcoinNetwork::Bitcoin,
2038            source: PaymentRequestSource::default(),
2039        })
2040    }
2041
2042    #[test_all]
2043    fn route_pays_each_kind_of_recipient() {
2044        let (spark, lightning, base) = (spark_recipient(), lightning_recipient(), base_recipient());
2045
2046        assert!(route_pays(&spark, &pair(base_usdc(), spark_btc())));
2047        assert!(route_pays(&spark, &pair(tron_usdt(), spark_usdb())));
2048        assert!(!route_pays(&spark, &pair(base_usdc(), lightning_btc())));
2049        assert!(!route_pays(&spark, &pair(lightning_btc(), spark_btc())));
2050
2051        assert!(route_pays(&lightning, &pair(base_usdc(), lightning_btc())));
2052        assert!(!route_pays(&lightning, &pair(base_usdc(), spark_btc())));
2053
2054        assert!(route_pays(&base, &pair(lightning_btc(), base_usdc())));
2055        assert!(route_pays(&base, &pair(tron_usdt(), base_usdc())));
2056        assert!(route_pays(&base, &pair(base_usdt(), base_usdc())));
2057        // A payer on Spark sends from their wallet instead.
2058        assert!(!route_pays(&base, &pair(spark_btc(), base_usdc())));
2059        assert!(!route_pays(&base, &pair(tron_usdt(), solana_usdc())));
2060    }
2061
2062    #[test_all]
2063    fn route_pays_no_other_tokens_or_sources() {
2064        let (spark, base) = (spark_recipient(), base_recipient());
2065        assert!(!route_pays(&spark, &pair(base_weth(), spark_btc())));
2066        assert!(!route_pays(&base, &pair(tron_usdt(), base_weth())));
2067        assert!(!route_pays(
2068            &spark,
2069            &pair(side("bitcoin", "BTC", None, 8), spark_btc())
2070        ));
2071        // A deposit whose chain can't be told from its token takes no refund
2072        // address that could be checked.
2073        assert!(!route_pays(
2074            &spark,
2075            &pair(side("ton", "USDT", None, 6), spark_btc())
2076        ));
2077    }
2078
2079    #[test_all]
2080    fn route_pays_the_token_and_chain_the_address_names() {
2081        let usdc = BridgeRecipient::CrossChain(CrossChainAddressDetails {
2082            contract_address: Some(BASE_USDC.to_lowercase()),
2083            ..base_address()
2084        });
2085        assert!(route_pays(&usdc, &pair(tron_usdt(), base_usdc())));
2086        assert!(!route_pays(&usdc, &pair(tron_usdt(), base_usdt())));
2087
2088        let on_base = BridgeRecipient::CrossChain(CrossChainAddressDetails {
2089            chain_id: Some(8453),
2090            ..base_address()
2091        });
2092        assert!(route_pays(&on_base, &pair(tron_usdt(), base_usdc())));
2093        let on_arbitrum = BridgeRecipient::CrossChain(CrossChainAddressDetails {
2094            chain_id: Some(42161),
2095            ..base_address()
2096        });
2097        assert!(!route_pays(&on_arbitrum, &pair(tron_usdt(), base_usdc())));
2098    }
2099
2100    #[test_all]
2101    fn native_coin_family_is_named_by_the_chain_or_its_chain_id() {
2102        for (side, family) in [
2103            (base_eth(), Some(CrossChainAddressFamily::Evm)),
2104            (ethereum_eth(), Some(CrossChainAddressFamily::Evm)),
2105            (bsc_bnb(), Some(CrossChainAddressFamily::Evm)),
2106            // Tron's chain id is decimal too, but its name comes first.
2107            (tron_trx(), Some(CrossChainAddressFamily::Tron)),
2108            (solana_sol(), Some(CrossChainAddressFamily::Solana)),
2109            (xrp_xrp(), Some(CrossChainAddressFamily::Xrp)),
2110            (zcash_zec(), Some(CrossChainAddressFamily::Zcash)),
2111            (native("plasma", None, "XPL", 18), None),
2112            (native("sui", Some("sui:mainnet"), "SUI", 9), None),
2113        ] {
2114            assert_eq!(
2115                native_coin_family(&side),
2116                family.map(Into::into),
2117                "{side:?}"
2118            );
2119        }
2120    }
2121
2122    #[test_all]
2123    fn route_pays_a_native_coin_from_lightning_on_the_recipients_chain() {
2124        let base = base_recipient();
2125        assert!(route_pays(&base, &pair(lightning_btc(), base_eth())));
2126        assert!(route_pays(&base, &pair(lightning_btc(), bsc_bnb())));
2127        assert!(route_pays(&base, &pair(lightning_btc(), ethereum_eth())));
2128        assert!(!route_pays(&base, &pair(lightning_btc(), tron_trx())));
2129        assert!(!route_pays(&base, &pair(lightning_btc(), solana_sol())));
2130        // Only Lightning pays a native coin.
2131        assert!(!route_pays(&base, &pair(base_usdc(), base_eth())));
2132        assert!(!route_pays(&base, &pair(tron_usdt(), bsc_bnb())));
2133        // A token that isn't a stablecoin stays out.
2134        assert!(!route_pays(&base, &pair(lightning_btc(), base_weth())));
2135
2136        let on_ethereum = BridgeRecipient::CrossChain(CrossChainAddressDetails {
2137            chain_id: Some(1),
2138            ..base_address()
2139        });
2140        assert!(route_pays(
2141            &on_ethereum,
2142            &pair(lightning_btc(), ethereum_eth())
2143        ));
2144        assert!(!route_pays(
2145            &on_ethereum,
2146            &pair(lightning_btc(), base_eth())
2147        ));
2148        let usdc = BridgeRecipient::CrossChain(CrossChainAddressDetails {
2149            contract_address: Some(BASE_USDC.to_string()),
2150            ..base_address()
2151        });
2152        assert!(!route_pays(&usdc, &pair(lightning_btc(), base_eth())));
2153
2154        let tron = other_chain_recipient(
2155            "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
2156            CrossChainAddressFamily::Tron,
2157        );
2158        assert!(route_pays(&tron, &pair(lightning_btc(), tron_trx())));
2159        assert!(!route_pays(&tron, &pair(lightning_btc(), base_eth())));
2160        let xrp = other_chain_recipient(
2161            "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh",
2162            CrossChainAddressFamily::Xrp,
2163        );
2164        assert!(route_pays(&xrp, &pair(lightning_btc(), xrp_xrp())));
2165        assert!(!route_pays(&xrp, &pair(lightning_btc(), zcash_zec())));
2166        let zcash = other_chain_recipient(
2167            "t1KRqwQhktLV4BjbNLiuH6pb3AMoszZKcQB",
2168            CrossChainAddressFamily::Zcash,
2169        );
2170        assert!(route_pays(&zcash, &pair(lightning_btc(), zcash_zec())));
2171    }
2172
2173    #[test_all]
2174    fn route_pays_bitcoin_on_chain_only_from_lightning() {
2175        let bitcoin = bitcoin_recipient();
2176        assert!(route_pays(&bitcoin, &pair(lightning_btc(), bitcoin_btc())));
2177        assert!(!route_pays(&bitcoin, &pair(base_usdc(), bitcoin_btc())));
2178        assert!(!route_pays(&bitcoin, &pair(lightning_btc(), base_usdc())));
2179        assert!(!route_pays(&bitcoin, &pair(lightning_btc(), spark_btc())));
2180        assert!(!route_pays(
2181            &base_recipient(),
2182            &pair(lightning_btc(), bitcoin_btc())
2183        ));
2184        assert!(!route_pays(
2185            &spark_recipient(),
2186            &pair(lightning_btc(), bitcoin_btc())
2187        ));
2188    }
2189
2190    #[test_all]
2191    fn routes_list_stablecoins_ahead_of_native_coins_for_each_source() {
2192        let mut routes = [
2193            pair(lightning_btc(), base_eth()),
2194            pair(tron_usdt(), base_usdc()),
2195            pair(lightning_btc(), bsc_bnb()),
2196            pair(lightning_btc(), base_usdt()),
2197            pair(lightning_btc(), base_usdc()),
2198        ];
2199        routes.sort_by(|a, b| route_order(a).cmp(&route_order(b)));
2200        let listed: Vec<_> = routes
2201            .iter()
2202            .map(|r| (r.source.asset.as_str(), r.destination.asset.as_str()))
2203            .collect();
2204        assert_eq!(
2205            listed,
2206            [
2207                ("BTC", "USDC"),
2208                ("BTC", "USDT"),
2209                ("BTC", "BNB"),
2210                ("BTC", "ETH"),
2211                ("USDT", "USDC"),
2212            ]
2213        );
2214    }
2215
2216    #[test_all]
2217    fn amount_side_is_the_recipients_stablecoin_or_what_the_payer_pays() {
2218        for (route, side) in [
2219            (
2220                pair(lightning_btc(), base_usdc()),
2221                BridgeAmountSide::Destination,
2222            ),
2223            (
2224                pair(tron_usdt(), spark_usdb()),
2225                BridgeAmountSide::Destination,
2226            ),
2227            (pair(base_usdc(), spark_btc()), BridgeAmountSide::Source),
2228            (pair(base_usdc(), lightning_btc()), BridgeAmountSide::Source),
2229            (pair(lightning_btc(), base_eth()), BridgeAmountSide::Source),
2230            (
2231                pair(lightning_btc(), bitcoin_btc()),
2232                BridgeAmountSide::Source,
2233            ),
2234        ] {
2235            assert_eq!(amount_side(&route.destination.asset), side, "{route:?}");
2236        }
2237        assert_eq!(
2238            source_units(&pair(lightning_btc(), base_eth()), 50_000).unwrap(),
2239            50_000
2240        );
2241    }
2242
2243    #[async_test_all]
2244    async fn parse_recipient_takes_a_mainnet_bitcoin_address() {
2245        let client = offline_client();
2246        for input in [
2247            "bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj",
2248            "bitcoin:bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj?amount=0.001",
2249        ] {
2250            let recipient = client.parse_recipient(input).await;
2251            assert!(
2252                matches!(&recipient, Ok(BridgeRecipient::Bitcoin(details))
2253                    if details.address == "bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj"),
2254                "{input}: {recipient:?}"
2255            );
2256        }
2257        assert_invalid_input(
2258            client
2259                .parse_recipient("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx")
2260                .await,
2261            "not a mainnet address",
2262        );
2263    }
2264
2265    #[test_all]
2266    fn is_listed_matches_both_sides_exactly() {
2267        let listed = vec![pair(tron_usdt(), base_usdc())];
2268        assert!(is_listed(&listed, &pair(tron_usdt(), base_usdc())));
2269        let wrong_chain = BridgeRoutePairSide {
2270            chain_id: Some("1".to_string()),
2271            ..base_usdc()
2272        };
2273        assert!(!is_listed(&listed, &pair(tron_usdt(), wrong_chain)));
2274        let wrong_token = BridgeRoutePairSide {
2275            contract_address: Some("TOther".to_string()),
2276            ..tron_usdt()
2277        };
2278        assert!(!is_listed(&listed, &pair(wrong_token, base_usdc())));
2279    }
2280
2281    #[test_all]
2282    fn source_units_rescales_a_stablecoin_destination() {
2283        let bsc_usdt = side(
2284            "bsc",
2285            "USDT",
2286            Some("0x55d398326f99059fF775485246999027B3197955"),
2287            18,
2288        );
2289        assert_eq!(
2290            source_units(&pair(bsc_usdt.clone(), base_usdc()), 10_000_000).unwrap(),
2291            10_000_000_000_000_000_000
2292        );
2293        assert_eq!(
2294            source_units(&pair(bsc_usdt, lightning_btc()), 10_000_000_000_000_000_000).unwrap(),
2295            10_000_000_000_000_000_000
2296        );
2297    }
2298
2299    #[test_all]
2300    fn external_pair_moves_the_local_asset_within_the_route_limits() {
2301        let usdb = SparkAsset::Token {
2302            token_identifier: "btkn1usdb".to_string(),
2303        };
2304        let route = BridgeRoutePair {
2305            limits: Some(CrossChainRouteLimits {
2306                min_amount: None,
2307                max_amount: None,
2308                min_usd_cents: Some(200),
2309                max_usd_cents: None,
2310            }),
2311            ..pair(tron_usdt(), spark_usdb())
2312        };
2313        let external = external_pair(
2314            &route,
2315            &route.source,
2316            Some((usdb.clone(), DeliveryMethod::Spark)),
2317        );
2318        assert_eq!(external.chain, "tron");
2319        assert_eq!(
2320            external.contract_address.as_deref(),
2321            Some("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
2322        );
2323        assert_eq!(
2324            external.limits_for(&usdb).and_then(|l| l.min_usd_cents),
2325            Some(200)
2326        );
2327        assert_eq!(external.delivery_methods, vec![DeliveryMethod::Spark]);
2328
2329        let bare = external_pair(&route, &route.source, None);
2330        assert!(bare.accepted_assets.is_empty() && bare.delivery_methods.is_empty());
2331    }
2332
2333    #[async_test_all]
2334    async fn create_bridge_rejects_a_route_that_does_not_pay_the_recipient() {
2335        let client = offline_client();
2336        for (recipient, route) in [
2337            (spark_recipient(), pair(base_usdc(), lightning_btc())),
2338            (lightning_recipient(), pair(base_usdc(), spark_btc())),
2339            (base_recipient(), pair(spark_btc(), base_usdc())),
2340            (base_recipient(), pair(tron_usdt(), base_weth())),
2341            (base_recipient(), pair(base_usdc(), base_eth())),
2342            (bitcoin_recipient(), pair(base_usdc(), bitcoin_btc())),
2343        ] {
2344            assert_invalid_input(
2345                client
2346                    .create_bridge_for(
2347                        &recipient,
2348                        create_request("", route),
2349                        LightningInvoice::Quote,
2350                    )
2351                    .await,
2352                "doesn't pay this recipient",
2353            );
2354        }
2355        // An address on another chain parses without a lookup.
2356        assert_invalid_input(
2357            client
2358                .create_bridge(create_request(
2359                    "0x0000000000000000000000000000000000000001",
2360                    pair(spark_btc(), base_usdc()),
2361                ))
2362                .await,
2363            "doesn't pay this recipient",
2364        );
2365    }
2366
2367    #[async_test_all]
2368    async fn create_bridge_requires_a_refund_address_to_pay_a_lightning_address() {
2369        let result = offline_client()
2370            .create_bridge_for(
2371                &lightning_recipient(),
2372                create_request("", pair(base_usdc(), lightning_btc())),
2373                LightningInvoice::Quote,
2374            )
2375            .await;
2376        assert_invalid_input(result, "refund address is required");
2377    }
2378
2379    #[async_test_all]
2380    async fn a_refund_address_is_optional_otherwise() {
2381        let client = offline_client();
2382        let route = external_pair(&pair(tron_usdt(), base_usdc()), &tron_usdt(), None);
2383        assert_eq!(
2384            client.validate_refund_address(None, &route).await.unwrap(),
2385            None
2386        );
2387    }
2388
2389    #[async_test_all]
2390    async fn create_bridge_rejects_a_non_mainnet_spark_recipient() {
2391        let result = offline_client()
2392            .create_bridge_for(
2393                &BridgeRecipient::Spark(spark_address(BitcoinNetwork::Regtest)),
2394                create_request("", pair(base_usdc(), spark_btc())),
2395                LightningInvoice::Quote,
2396            )
2397            .await;
2398        assert_invalid_input(result, "not a mainnet address");
2399    }
2400
2401    #[async_test_all]
2402    async fn create_bridge_rejects_a_zero_amount_and_other_providers_before_any_lookup() {
2403        // The offline client fails the test on a lookup of the address.
2404        let client = offline_client();
2405        let route = pair(base_usdc(), lightning_btc());
2406
2407        let mut request = create_request("alice@example.com", route.clone());
2408        request.amount = 0;
2409        assert_invalid_input(client.create_bridge(request).await, "greater than 0");
2410
2411        let mut route = route;
2412        route.provider = CrossChainProvider::Boltz;
2413        assert_invalid_input(
2414            client
2415                .create_bridge(create_request("alice@example.com", route))
2416                .await,
2417            "only supported on Orchestra",
2418        );
2419    }
2420
2421    #[async_test_all]
2422    async fn cash_app_bridges_take_only_cash_app_routes_and_recipients() {
2423        let client = offline_client();
2424        assert_invalid_input(
2425            client
2426                .bridge_from_cash_app(create_request(
2427                    "0x0000000000000000000000000000000000000001",
2428                    pair(tron_usdt(), base_usdc()),
2429                ))
2430                .await,
2431            "over Lightning",
2432        );
2433
2434        for recipient in [
2435            "alice@example.com",
2436            "sp1pgss8s9wq7kafdwppyynpr0xzx7v9x8nyx0",
2437        ] {
2438            assert_invalid_input(
2439                client
2440                    .bridge_to_cash_app(create_request(
2441                        recipient,
2442                        pair(base_usdc(), lightning_btc()),
2443                    ))
2444                    .await,
2445                "not a Cash App username",
2446            );
2447        }
2448        // A Cash App user, however written, is bridged as any other recipient.
2449        for recipient in ["alice", "$alice", "alice@cash.app"] {
2450            let mut request = create_request(recipient, pair(base_usdc(), lightning_btc()));
2451            request.amount = 0;
2452            assert_invalid_input(client.bridge_to_cash_app(request).await, "greater than 0");
2453        }
2454    }
2455
2456    #[async_test_all]
2457    async fn a_lightning_bridge_rejects_a_refund_address_it_cannot_refund() {
2458        let client = offline_client();
2459        assert_eq!(client.lightning_refund_address(None).await.unwrap(), None);
2460        assert_eq!(
2461            client.lightning_refund_address(Some("  ")).await.unwrap(),
2462            None
2463        );
2464        assert_eq!(
2465            client
2466                .lightning_refund_address(Some(" $alice "))
2467                .await
2468                .unwrap()
2469                .map(|r| r.address)
2470                .as_deref(),
2471            Some("alice@cash.app")
2472        );
2473        assert_invalid_input(
2474            client
2475                .lightning_refund_address(Some("0x0000000000000000000000000000000000000001"))
2476                .await,
2477            "Lightning refund address",
2478        );
2479    }
2480
2481    #[test_all]
2482    fn lightning_funded_response_describes_the_invoice_and_the_stablecoin() {
2483        let response = lightning_funded_bridge_response(LightningFunded {
2484            prepared: prepared(orchestra_context()),
2485            deposit_target: "lnbc100u1pxyz".to_string(),
2486            amount_sats: 5000,
2487            order_id: None,
2488        })
2489        .unwrap();
2490        assert_eq!(response.bridge_id, "q1");
2491        assert_eq!(response.payment_request, "lnbc100u1pxyz");
2492        assert_eq!(response.info.deposit_address, "lnbc100u1pxyz");
2493        assert_eq!(response.info.deposit_amount, 5000);
2494        assert_eq!(response.info.expected_received_amount, 6_450_000);
2495        assert_eq!(response.info.destination_asset, "USDC");
2496        assert_eq!(response.info.token_identifier, None);
2497        assert_eq!(response.info.service_fee_asset.as_deref(), Some("USDC"));
2498        assert_eq!(response.info.expires_at, 1_784_966_966);
2499    }
2500
2501    #[test_all]
2502    fn an_onramp_bridge_is_identified_by_its_order() {
2503        let response = lightning_funded_bridge_response(LightningFunded {
2504            prepared: prepared(orchestra_context()),
2505            deposit_target: "lnbc100u1pxyz".to_string(),
2506            amount_sats: 5000,
2507            order_id: Some("ord_1".to_string()),
2508        })
2509        .unwrap();
2510        assert_eq!(response.bridge_id, "ord_1");
2511        assert_eq!(response.info.quote_id, "q1");
2512        assert!(is_order_id(&response.bridge_id));
2513        assert!(!is_order_id("q1"));
2514    }
2515}