Skip to main content

breez_sdk_spark/models/
mod.rs

1pub(crate) mod adaptors;
2pub mod payment_observer;
3pub use payment_observer::*;
4pub mod token_allowance;
5pub use token_allowance::*;
6
7// Re-export public conversion types from the conversion module
8pub use crate::token_conversion::{
9    AmountAdjustmentReason, ConversionEstimate, ConversionInfo, ConversionOptions,
10    ConversionPurpose, ConversionStatus, ConversionType, FetchConversionLimitsRequest,
11    FetchConversionLimitsResponse, SwapDegradation,
12};
13
14use core::fmt;
15use lnurl_models::RecoverLnurlPayResponse;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use spark_wallet::bech32m_decode_token_id;
19use std::{
20    collections::{HashMap, HashSet},
21    fmt::Display,
22    str::FromStr,
23};
24
25use crate::{
26    BitcoinAddressDetails, BitcoinNetwork, Bolt11InvoiceDetails, ExternalInputParser, FiatCurrency,
27    LnurlPayRequestDetails, LnurlWithdrawRequestDetails, Rate, SdkError, SparkInvoiceDetails,
28    SuccessAction, SuccessActionProcessed,
29    chain::FeeMarket,
30    cross_chain::{CrossChainFeeMode, CrossChainProviderContext, CrossChainRoutePair},
31    error::{CooperativeRecoveryError, DepositClaimError},
32};
33
34/// A list of external input parsers that are used by default.
35/// To opt-out, set `use_default_external_input_parsers` in [Config] to false.
36pub const DEFAULT_EXTERNAL_INPUT_PARSERS: &[(&str, &str, &str)] = &[
37    (
38        "picknpay",
39        "(.*)(za.co.electrum.picknpay)(.*)",
40        "https://cryptoqr.net/.well-known/lnurlp/<input>",
41    ),
42    (
43        "bootleggers",
44        r"(.*)(wigroup\.co|yoyogroup\.co)(.*)",
45        "https://cryptoqr.net/.well-known/lnurlw/<input>",
46    ),
47];
48
49/// Represents the seed for wallet generation, either as a mnemonic phrase with an optional
50/// passphrase or as raw entropy bytes.
51#[derive(Clone)]
52#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
53pub enum Seed {
54    /// A BIP-39 mnemonic phrase with an optional passphrase.
55    Mnemonic {
56        /// The mnemonic phrase. 12 or 24 words.
57        mnemonic: String,
58        /// An optional passphrase for the mnemonic.
59        passphrase: Option<String>,
60    },
61    /// Raw entropy bytes.
62    Entropy(Vec<u8>),
63}
64
65impl fmt::Debug for Seed {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Seed::Mnemonic { passphrase, .. } => f
69                .debug_struct("Mnemonic")
70                .field("mnemonic", &"<redacted>")
71                .field("passphrase", &passphrase.as_ref().map(|_| "<redacted>"))
72                .finish(),
73            Seed::Entropy(_) => f.debug_tuple("Entropy").field(&"<redacted>").finish(),
74        }
75    }
76}
77
78impl Seed {
79    pub fn to_bytes(&self) -> Result<Vec<u8>, SdkError> {
80        match self {
81            Seed::Mnemonic {
82                mnemonic,
83                passphrase,
84            } => {
85                let mnemonic = bip39::Mnemonic::parse(mnemonic)
86                    .map_err(|e| SdkError::Generic(e.to_string()))?;
87
88                Ok(mnemonic
89                    .to_seed(passphrase.as_deref().unwrap_or(""))
90                    .to_vec())
91            }
92            Seed::Entropy(entropy) => Ok(entropy.clone()),
93        }
94    }
95}
96
97#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
98pub struct ConnectRequest {
99    pub config: Config,
100    pub seed: Seed,
101    pub storage_dir: String,
102}
103
104/// Request object for connecting to the Spark network using an external signer.
105///
106/// This allows using a custom signer implementation instead of providing a seed directly.
107#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
108#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
109pub struct ConnectWithSignerRequest {
110    pub config: Config,
111    /// External signer for non-Spark SDK signing (LNURL-auth, sync, message
112    /// signing, ECIES).
113    pub breez_signer: std::sync::Arc<dyn crate::signer::ExternalBreezSigner>,
114    /// External high-level Spark signer for the Spark wallet flows.
115    pub spark_signer: std::sync::Arc<dyn crate::signer::ExternalSparkSigner>,
116    pub storage_dir: String,
117}
118
119/// Request object for connecting to the Spark network using a signing-only
120/// external signer.
121///
122/// Use this instead of [`ConnectWithSignerRequest`] for a signer that can't
123/// perform the SDK's local ECIES/HMAC operations (for example a
124/// policy-restricted enclave). The SDK keeps session tokens in plaintext and
125/// disables the features that rely on ECIES/HMAC.
126#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
127#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
128pub struct ConnectWithSigningOnlySignerRequest {
129    pub config: Config,
130    /// Signing-only external signer for non-Spark SDK signing.
131    pub breez_signer: std::sync::Arc<dyn crate::signer::ExternalSigningSigner>,
132    /// External high-level Spark signer for the Spark wallet flows.
133    pub spark_signer: std::sync::Arc<dyn crate::signer::ExternalSparkSigner>,
134    pub storage_dir: String,
135}
136
137/// The type of payment
138#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
139#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
140pub enum PaymentType {
141    /// Payment sent from this wallet
142    Send,
143    /// Payment received to this wallet
144    Receive,
145}
146
147impl fmt::Display for PaymentType {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            PaymentType::Send => write!(f, "send"),
151            PaymentType::Receive => write!(f, "receive"),
152        }
153    }
154}
155
156impl FromStr for PaymentType {
157    type Err = String;
158
159    fn from_str(s: &str) -> Result<Self, Self::Err> {
160        Ok(match s.to_lowercase().as_str() {
161            "receive" => PaymentType::Receive,
162            "send" => PaymentType::Send,
163            _ => return Err(format!("invalid payment type '{s}'")),
164        })
165    }
166}
167
168/// The status of a payment
169#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
170#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
171pub enum PaymentStatus {
172    /// Payment is completed successfully
173    Completed,
174    /// Payment is in progress
175    Pending,
176    /// Payment has failed
177    Failed,
178}
179
180impl PaymentStatus {
181    /// Returns true if the payment status is final (either Completed or Failed)
182    pub fn is_final(&self) -> bool {
183        matches!(self, PaymentStatus::Completed | PaymentStatus::Failed)
184    }
185}
186
187impl fmt::Display for PaymentStatus {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        match self {
190            PaymentStatus::Completed => write!(f, "completed"),
191            PaymentStatus::Pending => write!(f, "pending"),
192            PaymentStatus::Failed => write!(f, "failed"),
193        }
194    }
195}
196
197impl FromStr for PaymentStatus {
198    type Err = String;
199
200    fn from_str(s: &str) -> Result<Self, Self::Err> {
201        Ok(match s.to_lowercase().as_str() {
202            "completed" => PaymentStatus::Completed,
203            "pending" => PaymentStatus::Pending,
204            "failed" => PaymentStatus::Failed,
205            _ => return Err(format!("Invalid payment status '{s}'")),
206        })
207    }
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
211#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
212pub enum PaymentMethod {
213    Lightning,
214    Spark,
215    Token,
216    Deposit,
217    Withdraw,
218    Unknown,
219}
220
221impl Display for PaymentMethod {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        match self {
224            PaymentMethod::Lightning => write!(f, "lightning"),
225            PaymentMethod::Spark => write!(f, "spark"),
226            PaymentMethod::Token => write!(f, "token"),
227            PaymentMethod::Deposit => write!(f, "deposit"),
228            PaymentMethod::Withdraw => write!(f, "withdraw"),
229            PaymentMethod::Unknown => write!(f, "unknown"),
230        }
231    }
232}
233
234impl FromStr for PaymentMethod {
235    type Err = ();
236
237    fn from_str(s: &str) -> Result<Self, Self::Err> {
238        match s {
239            "lightning" => Ok(PaymentMethod::Lightning),
240            "spark" => Ok(PaymentMethod::Spark),
241            "token" => Ok(PaymentMethod::Token),
242            "deposit" => Ok(PaymentMethod::Deposit),
243            "withdraw" => Ok(PaymentMethod::Withdraw),
244            "unknown" => Ok(PaymentMethod::Unknown),
245            _ => Err(()),
246        }
247    }
248}
249
250/// Represents a payment (sent or received)
251#[derive(Debug, Clone, Serialize, Deserialize)]
252#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
253pub struct Payment {
254    /// Unique identifier for the payment. A second payment of the same invoice has a
255    /// different id.
256    pub id: String,
257    /// Type of payment (send or receive)
258    pub payment_type: PaymentType,
259    /// Status of the payment
260    pub status: PaymentStatus,
261    /// Amount in satoshis or token base units
262    pub amount: u128,
263    /// Fee paid in satoshis or token base units
264    pub fees: u128,
265    /// Timestamp of when the payment was created
266    pub timestamp: u64,
267    /// Method of payment. Sometimes the payment details is empty so this field
268    /// is used to determine the payment method.
269    pub method: PaymentMethod,
270    /// Details of the payment
271    pub details: Option<PaymentDetails>,
272    /// If set, this payment involved a conversion before the payment
273    pub conversion_details: Option<ConversionDetails>,
274}
275
276impl Payment {
277    /// Returns `true` if this payment is a child of a conversion operation.
278    ///
279    /// An AMM conversion (stable balance, convert-on-send) settles as its own
280    /// payments: sats out to the pool, tokens back in. Those legs are internal
281    /// plumbing, so they carry [`ConversionInfo::Amm`]. A cross-chain
282    /// conversion has no such legs: it annotates the payment the user made or
283    /// received, which is never a child.
284    pub fn is_conversion_child(&self) -> bool {
285        matches!(
286            &self.details,
287            Some(
288                PaymentDetails::Spark {
289                    conversion_info: Some(ConversionInfo::Amm { .. }),
290                    ..
291                } | PaymentDetails::Token {
292                    conversion_info: Some(ConversionInfo::Amm { .. }),
293                    ..
294                }
295            )
296        )
297    }
298}
299
300/// Outlines the steps involved in one or more conversions on a payment.
301///
302/// Built progressively: `status` is available immediately from payment metadata,
303/// while `conversions` are enriched later from child payments and conversion info.
304#[derive(Debug, Clone, Serialize, Deserialize)]
305#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
306pub struct ConversionDetails {
307    /// Overall status of the conversion. On a send, it follows the cross-chain
308    /// step until that step finishes.
309    pub status: ConversionStatus,
310    /// Ordered list of conversion steps. For sends: [AMM, cross-chain].
311    /// For receives: [cross-chain, AMM]. Rebuilt on retrieval, not persisted.
312    #[serde(default)]
313    pub conversions: Vec<Conversion>,
314}
315
316/// The provider that performed a conversion.
317#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
318#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
319pub enum ConversionProvider {
320    /// AMM (Flashnet pool) conversion between token and BTC on Spark
321    Amm,
322    /// Orchestra cross-chain conversion
323    Orchestra,
324    /// Boltz reverse-swap cross-chain conversion
325    Boltz,
326}
327
328/// The chain or network that a [`ConversionSide`] lives on.
329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
330#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
331pub enum ConversionChain {
332    /// Spark layer-2 network.
333    Spark,
334    /// Bitcoin Lightning Network.
335    Lightning,
336    /// An external chain reached via a cross-chain provider.
337    External {
338        /// Human-readable chain name (e.g. `"base"`, `"solana"`, `"arbitrum"`).
339        name: String,
340        /// Stable chain identifier (e.g. EVM `chainId` as a decimal string,
341        /// or a chain-native identifier). `None` when the provider does not
342        /// expose one for this route.
343        chain_id: Option<String>,
344    },
345}
346
347/// The asset on a [`ConversionSide`] — groups the ticker, stable identifier,
348/// and decimals that always travel together.
349#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
350#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
351pub struct ConversionAsset {
352    /// Ticker (e.g. `"BTC"`, `"USDB"`, `"USDC"`, `"USDT"`). Tickers alone
353    /// are ambiguous across chains — pair with [`Self::identifier`] for a
354    /// hard match.
355    pub ticker: String,
356    /// Stable identifier: a Spark token identifier for Spark tokens, or a
357    /// contract/mint address for cross-chain assets. `None` for BTC/sats.
358    pub identifier: Option<String>,
359    /// Number of decimals for the asset.
360    /// `0` for BTC/sats sides (amount is already in the smallest unit,
361    /// so no scaling is needed); non-zero for token assets (e.g. `6` for
362    /// USDC/USDT/USDB).
363    pub decimals: u32,
364}
365
366/// One side (source or destination) of a conversion.
367#[derive(Debug, Clone, Serialize, Deserialize)]
368#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
369pub struct ConversionSide {
370    /// The chain or network for this side.
371    pub chain: ConversionChain,
372    /// The asset being converted on this side.
373    pub asset: ConversionAsset,
374    /// Amount in base units (satoshis or token base units)
375    pub amount: u128,
376    /// Fee in the same base units
377    pub fee: u128,
378}
379
380/// A single conversion in a payment's conversion chain.
381#[derive(Debug, Clone, Serialize, Deserialize)]
382#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
383pub struct Conversion {
384    /// The provider that performed this conversion
385    pub provider: ConversionProvider,
386    /// Status of this specific conversion step
387    pub status: ConversionStatus,
388    /// Source side of the conversion
389    pub from: ConversionSide,
390    /// Destination side of the conversion
391    pub to: ConversionSide,
392    /// Reason the conversion amount was adjusted, if applicable (AMM only)
393    #[serde(default)]
394    pub amount_adjustment: Option<AmountAdjustmentReason>,
395}
396
397#[cfg(feature = "uniffi")]
398uniffi::custom_type!(u128, String, {
399    remote,
400    try_lift: |val| val.parse::<u128>().map_err(uniffi::deps::anyhow::Error::msg),
401    lower: |obj| obj.to_string(),
402});
403
404// TODO: fix large enum variant lint - may be done by boxing lnurl_pay_info but that requires
405//  some changes to the wasm bindgen macro
406#[allow(clippy::large_enum_variant)]
407#[derive(Debug, Clone, Serialize, Deserialize)]
408#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
409pub enum PaymentDetails {
410    Spark {
411        /// The invoice details if the payment fulfilled a spark invoice
412        invoice_details: Option<SparkInvoicePaymentDetails>,
413        /// The HTLC transfer details if the payment fulfilled an HTLC transfer
414        htlc_details: Option<SparkHtlcDetails>,
415        /// The information for a conversion
416        conversion_info: Option<ConversionInfo>,
417    },
418    Token {
419        metadata: PaymentTokenMetadata,
420        tx_hash: String,
421        tx_type: TokenTransactionType,
422        /// The invoice details if the payment fulfilled a spark invoice
423        invoice_details: Option<SparkInvoicePaymentDetails>,
424        /// The information for a conversion
425        conversion_info: Option<ConversionInfo>,
426    },
427    Lightning {
428        /// Represents the invoice description
429        description: Option<String>,
430        /// Represents the Bolt11/Bolt12 invoice associated with a payment
431        /// In the case of a Send payment, this is the invoice paid by the user
432        /// In the case of a Receive payment, this is the invoice paid to the user
433        invoice: String,
434
435        /// The invoice destination/payee pubkey
436        destination_pubkey: String,
437
438        /// The HTLC transfer details
439        htlc_details: SparkHtlcDetails,
440
441        /// Lnurl payment information if this was an lnurl payment.
442        lnurl_pay_info: Option<LnurlPayInfo>,
443
444        /// Lnurl withdrawal information if this was an lnurl payment.
445        lnurl_withdraw_info: Option<LnurlWithdrawInfo>,
446
447        /// Lnurl receive information if this was a received lnurl payment.
448        lnurl_receive_metadata: Option<LnurlReceiveMetadata>,
449
450        /// The information for a conversion — populated when this Lightning
451        /// payment is the source leg of a cross-chain conversion (e.g. a
452        /// Boltz reverse swap paying a hold invoice).
453        conversion_info: Option<ConversionInfo>,
454    },
455    Withdraw {
456        tx_id: String,
457        /// The index of the withdrawal transaction's output that pays the
458        /// destination address.
459        vout: u32,
460        destination_address: String,
461    },
462    Deposit {
463        tx_id: String,
464        vout: u32,
465    },
466}
467
468#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
469#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
470pub enum TokenTransactionType {
471    Transfer,
472    Mint,
473    Burn,
474}
475
476impl fmt::Display for TokenTransactionType {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        match self {
479            TokenTransactionType::Transfer => write!(f, "transfer"),
480            TokenTransactionType::Mint => write!(f, "mint"),
481            TokenTransactionType::Burn => write!(f, "burn"),
482        }
483    }
484}
485
486impl FromStr for TokenTransactionType {
487    type Err = String;
488
489    fn from_str(s: &str) -> Result<Self, Self::Err> {
490        match s.to_lowercase().as_str() {
491            "transfer" => Ok(TokenTransactionType::Transfer),
492            "mint" => Ok(TokenTransactionType::Mint),
493            "burn" => Ok(TokenTransactionType::Burn),
494            _ => Err(format!("Invalid token transaction type '{s}'")),
495        }
496    }
497}
498
499#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
500#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
501pub struct SparkInvoicePaymentDetails {
502    /// Represents the spark invoice description
503    pub description: Option<String>,
504    /// The raw spark invoice string
505    pub invoice: String,
506}
507
508#[derive(Clone, Serialize, Deserialize, PartialEq)]
509#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
510pub struct SparkHtlcDetails {
511    /// The payment hash of the HTLC
512    pub payment_hash: String,
513    /// The preimage of the HTLC. Empty until receiver has released it.
514    pub preimage: Option<String>,
515    /// The expiry time of the HTLC as a unix timestamp in seconds
516    pub expiry_time: u64,
517    /// The HTLC status
518    pub status: SparkHtlcStatus,
519}
520
521impl fmt::Debug for SparkHtlcDetails {
522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523        f.debug_struct("SparkHtlcDetails")
524            .field("payment_hash", &self.payment_hash)
525            .field("preimage", &self.preimage.as_ref().map(|_| "<redacted>"))
526            .field("expiry_time", &self.expiry_time)
527            .field("status", &self.status)
528            .finish()
529    }
530}
531
532#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
533#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
534pub enum SparkHtlcStatus {
535    /// The HTLC is waiting for the preimage to be shared by the receiver
536    WaitingForPreimage,
537    /// The HTLC preimage has been shared and the transfer can be or has been claimed by the receiver
538    PreimageShared,
539    /// The HTLC has been returned to the sender due to expiry
540    Returned,
541}
542
543impl fmt::Display for SparkHtlcStatus {
544    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545        match self {
546            SparkHtlcStatus::WaitingForPreimage => write!(f, "WaitingForPreimage"),
547            SparkHtlcStatus::PreimageShared => write!(f, "PreimageShared"),
548            SparkHtlcStatus::Returned => write!(f, "Returned"),
549        }
550    }
551}
552
553impl FromStr for SparkHtlcStatus {
554    type Err = String;
555
556    fn from_str(s: &str) -> Result<Self, Self::Err> {
557        match s {
558            "WaitingForPreimage" => Ok(SparkHtlcStatus::WaitingForPreimage),
559            "PreimageShared" => Ok(SparkHtlcStatus::PreimageShared),
560            "Returned" => Ok(SparkHtlcStatus::Returned),
561            _ => Err("Invalid Spark HTLC status".to_string()),
562        }
563    }
564}
565
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
568pub enum Network {
569    Mainnet,
570    Regtest,
571    Signet,
572}
573
574impl std::fmt::Display for Network {
575    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
576        match self {
577            Network::Mainnet => write!(f, "Mainnet"),
578            Network::Regtest => write!(f, "Regtest"),
579            Network::Signet => write!(f, "Signet"),
580        }
581    }
582}
583
584impl From<Network> for BitcoinNetwork {
585    fn from(network: Network) -> Self {
586        match network {
587            Network::Mainnet => BitcoinNetwork::Bitcoin,
588            Network::Regtest => BitcoinNetwork::Regtest,
589            Network::Signet => BitcoinNetwork::Signet,
590        }
591    }
592}
593
594impl From<Network> for breez_sdk_common::network::BitcoinNetwork {
595    fn from(network: Network) -> Self {
596        match network {
597            Network::Mainnet => breez_sdk_common::network::BitcoinNetwork::Bitcoin,
598            Network::Regtest => breez_sdk_common::network::BitcoinNetwork::Regtest,
599            Network::Signet => breez_sdk_common::network::BitcoinNetwork::Signet,
600        }
601    }
602}
603
604impl From<Network> for bitcoin::Network {
605    fn from(network: Network) -> Self {
606        match network {
607            Network::Mainnet => bitcoin::Network::Bitcoin,
608            Network::Regtest => bitcoin::Network::Regtest,
609            Network::Signet => bitcoin::Network::Signet,
610        }
611    }
612}
613
614impl FromStr for Network {
615    type Err = String;
616
617    fn from_str(s: &str) -> Result<Self, Self::Err> {
618        match s {
619            "mainnet" => Ok(Network::Mainnet),
620            "regtest" => Ok(Network::Regtest),
621            "signet" => Ok(Network::Signet),
622            _ => Err("Invalid network".to_string()),
623        }
624    }
625}
626
627/// A SOCKS5 proxy carrying the connections the SDK opens.
628///
629/// Hostnames are resolved by the proxy rather than locally, so a DNS query
630/// never discloses which host is being reached. A connection that cannot be
631/// established through the proxy fails: the SDK never falls back to a direct
632/// one.
633///
634/// Not supported on WASM, where the browser owns connection setup and exposes
635/// no proxy control. In Node, route the SDK by installing a proxy dispatcher
636/// on the global `fetch` instead.
637#[derive(Debug, Clone, PartialEq, Eq)]
638#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
639pub struct ProxyConfig {
640    /// Proxy host. An IP address, or a name resolvable locally: reaching the
641    /// proxy is the one lookup that cannot itself go through the proxy.
642    pub host: String,
643    pub port: u16,
644    /// Username for SOCKS5 username/password authentication. Authentication is
645    /// only offered when both this and `password` are set.
646    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
647    pub username: Option<String>,
648    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
649    pub password: Option<String>,
650}
651
652impl From<&ProxyConfig> for platform_utils::ProxyConfig {
653    fn from(config: &ProxyConfig) -> Self {
654        Self {
655            host: config.host.clone(),
656            port: config.port,
657            username: config.username.clone(),
658            password: config.password.clone(),
659        }
660    }
661}
662
663impl ProxyConfig {
664    /// A validated HTTP client honouring `proxy`, for the components built
665    /// outside the SDK's shared context. Everything inside it takes the
666    /// context's pooled client instead and never sees a proxy.
667    pub(crate) fn http_client(
668        proxy: Option<&Self>,
669        user_agent: Option<&str>,
670    ) -> Result<std::sync::Arc<dyn platform_utils::HttpClient>, SdkError> {
671        if let Some(proxy) = proxy {
672            proxy.validate()?;
673        }
674        platform_utils::create_http_client_with_proxy(
675            user_agent,
676            proxy.map(platform_utils::ProxyConfig::from).as_ref(),
677        )
678        .map_err(|e| SdkError::InvalidInput(format!("Failed to build proxied HTTP client: {e}")))
679    }
680
681    /// Rejects a proxy the SDK cannot honour end to end. Accepting one it can
682    /// only partly apply would leave some traffic going direct, which is worse
683    /// than refusing outright.
684    pub(crate) fn validate(&self) -> Result<(), SdkError> {
685        if cfg!(all(target_family = "wasm", target_os = "unknown")) {
686            return Err(SdkError::InvalidInput(
687                "A SOCKS5 proxy is not supported on WASM: the browser owns connection setup and \
688                 exposes no proxy control. In Node, install a proxy dispatcher on the global \
689                 fetch instead."
690                    .to_string(),
691            ));
692        }
693        if self.host.is_empty() {
694            return Err(SdkError::InvalidInput(
695                "Proxy host must not be empty".to_string(),
696            ));
697        }
698        if self.port == 0 {
699            return Err(SdkError::InvalidInput(
700                "Proxy port must not be 0".to_string(),
701            ));
702        }
703        if self.username.is_some() != self.password.is_some() {
704            return Err(SdkError::InvalidInput(
705                "Proxy username and password must be set together".to_string(),
706            ));
707        }
708        // The host ends up in a URL authority, so it has to survive being put
709        // there unchanged. Parsing is not enough on its own: a host carrying
710        // `@` parses, but as userinfo, which silently turns part of it into a
711        // username and moves the address. Checked here rather than at client
712        // build time so the error names the config that caused it.
713        let address = platform_utils::ProxyConfig::from(self).address();
714        let intact = url::Url::parse(&format!("socks5h://{address}")).is_ok_and(|url| {
715            url.username().is_empty()
716                && url.password().is_none()
717                && url.port() == Some(self.port)
718                && url.path().is_empty()
719                && url.query().is_none()
720                && url.fragment().is_none()
721        });
722        if !intact {
723            return Err(SdkError::InvalidInput(format!(
724                "Proxy host '{}' cannot be used in a proxy URL",
725                self.host
726            )));
727        }
728        Ok(())
729    }
730}
731
732#[derive(Debug, Clone)]
733#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
734#[allow(clippy::struct_excessive_bools)]
735pub struct Config {
736    pub api_key: Option<String>,
737    pub network: Network,
738    pub sync_interval_secs: u32,
739
740    /// The maximum fee that can be paid to claim an on-chain deposit. It also caps
741    /// the provider's spread for crediting a deposit before it matures, so raising
742    /// it is what allows deposits to be claimed early. Unset disables claiming
743    /// rather than allowing any fee.
744    pub max_deposit_claim_fee: Option<MaxFee>,
745
746    /// The domain used for receiving through lnurl-pay and lightning address.
747    pub lnurl_domain: Option<String>,
748
749    /// When this is set to `true` we will prefer to use spark payments over
750    /// lightning when sending and receiving. This has the benefit of lower fees
751    /// but is at the cost of privacy.
752    pub prefer_spark_over_lightning: bool,
753
754    /// Whether the data needed to exit a payment unilaterally, without the Spark
755    /// operators, is collected automatically as funds arrive. Collection runs in
756    /// the background, after an operation rather than during it. A leaf the
757    /// operators cannot complete stays un-exitable until a later attempt
758    /// succeeds.
759    ///
760    /// Turn it off when collecting behind every operation costs more than it is
761    /// worth, on a busy wallet holding many leaves. `sync_wallet` collects
762    /// regardless of this flag, and waits for the pass before returning, so an
763    /// explicit sync on a cadence of your choosing is how the data is kept
764    /// current with the automatic collection off.
765    ///
766    /// Only that automatic collection is governed, so this has no effect at all
767    /// where none runs: with `background_tasks_enabled` off there is no
768    /// background collector, and every sync is an explicit one.
769    ///
770    /// Default value is true.
771    pub exit_chain_auto_fetch_enabled: bool,
772
773    /// Whether the SDK pre-signs the transactions that protect funds on chain at
774    /// a range of fees, so the protection holds when on-chain fees are high.
775    ///
776    /// Unset turns it on. It is not supported with a remote signer, such as
777    /// Turnkey: unset keeps it off there, and true fails to connect.
778    pub watchtower_fee_ladder_enabled: Option<bool>,
779
780    /// A set of external input parsers that are used by [`BreezSdk::parse`](crate::sdk::BreezSdk::parse) when the input
781    /// is not recognized. See [`ExternalInputParser`] for more details on how to configure
782    /// external parsing.
783    pub external_input_parsers: Option<Vec<ExternalInputParser>>,
784    /// The SDK includes some default external input parsers
785    /// ([`DEFAULT_EXTERNAL_INPUT_PARSERS`]).
786    /// Set this to false in order to prevent their use.
787    pub use_default_external_input_parsers: bool,
788
789    /// Url to use for the real-time sync server. Defaults to the Breez real-time sync server.
790    pub real_time_sync_server_url: Option<String>,
791
792    /// Whether the Spark private mode is enabled by default.
793    ///
794    /// If set to true, the Spark private mode will be enabled on the first
795    /// initialization of the SDK. If set to false, no changes will be made
796    /// to the Spark private mode.
797    ///
798    /// This default is only auto-applied when `background_tasks_enabled` is
799    /// `true`. When `background_tasks_enabled` is `false`, the SDK does not
800    /// touch the Spark private mode on startup; call `update_user_settings`
801    /// with `spark_private_mode_enabled` set as needed on a one-time setup
802    /// pass.
803    pub private_enabled_default: bool,
804
805    /// Configuration for leaf optimization.
806    ///
807    /// Leaf optimization controls the denominations of leaves that are held in the wallet.
808    /// Fewer, bigger leaves allow for more funds to be exited unilaterally.
809    /// More leaves allow payments to be made without needing a swap, reducing payment latency.
810    pub leaf_optimization_config: LeafOptimizationConfig,
811
812    /// Configuration for token-output optimization.
813    ///
814    /// Token-output optimization controls automatic consolidation of a token's
815    /// available outputs. Keeping the output set small reduces transaction size,
816    /// while keeping enough distinct outputs preserves concurrency for parallel
817    /// sends.
818    pub token_optimization_config: TokenOptimizationConfig,
819
820    /// Configuration for automatic conversion of Bitcoin to stable tokens.
821    ///
822    /// When set, received sats will be automatically converted to the specified token
823    /// once the balance exceeds the threshold.
824    pub stable_balance_config: Option<StableBalanceConfig>,
825
826    /// Maximum number of concurrent transfer claims.
827    ///
828    /// Default is 4. Increase for server environments with high incoming payment volume.
829    pub max_concurrent_claims: u32,
830
831    /// Optional custom Spark environment configuration.
832    ///
833    /// When set, overrides the default Spark operator pool, service provider,
834    /// threshold, and token settings. Use this to connect to alternative Spark
835    /// deployments (e.g. dev/staging environments).
836    pub spark_config: Option<SparkConfig>,
837
838    /// Master switch for per-instance background services.
839    ///
840    /// When `true` (default), the SDK runs its standard background work:
841    /// periodic sync, lightning-address recovery, private-mode initialization,
842    /// the leaf and token-output optimizers, the Spark server-event
843    /// subscription, and the real-time sync client (when
844    /// `real_time_sync_server_url` is set).
845    ///
846    /// When `false`, **no background service is started**, regardless of any
847    /// other setting on this config. This is intended for multi-tenant server
848    /// deployments where the host application orchestrates sync and claims
849    /// explicitly and receives events via webhooks. Use
850    /// `default_server_config` to get this preset.
851    ///
852    /// Explicit operations (`sync_wallet`, `claim_deposit`,
853    /// `list_unclaimed_deposits`, `refund_deposit`,
854    /// `refund_pending_conversions`, leaf/token optimization, etc.) work
855    /// regardless of this flag.
856    ///
857    /// When `false`, the SDK rejects builds where fields whose backing
858    /// service is gated off are still in their active shape:
859    /// `stable_balance_config` must be `None`, `real_time_sync_server_url`
860    /// must be `None`, and `optimization_config.auto_enabled` must be `false`.
861    /// `default_server_config` already sets these compatible values.
862    pub background_tasks_enabled: bool,
863
864    /// Routes the connections the SDK opens through a SOCKS5 proxy.
865    ///
866    /// Covers HTTP and gRPC alike, and resolves hostnames at the proxy so no
867    /// DNS query leaks the destination. `None` (default) connects directly.
868    ///
869    /// When an [`SdkContext`](crate::SdkContext) is supplied to the builder,
870    /// its proxy must match this one: the context owns the shared clients, so
871    /// a disagreement would mean part of the traffic bypassed the proxy.
872    pub proxy: Option<ProxyConfig>,
873
874    /// Enables cross-chain payments: sending and receiving USDC/USDT on other
875    /// chains. Set it to a default `CrossChainConfig`, or one with your own
876    /// defaults, to turn the feature on. Unset (the default) leaves it off, and
877    /// the cross-chain calls fail with a `CrossChainDisabled` error.
878    ///
879    /// Off by default because the providers run background work such as web
880    /// sockets. Only supported on mainnet.
881    pub cross_chain_config: Option<CrossChainConfig>,
882}
883
884/// Configuration for cross-chain payments. Setting it on the config turns the
885/// feature on.
886#[derive(Debug, Clone, Default)]
887#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
888pub struct CrossChainConfig {
889    /// Default maximum slippage in basis points used when
890    /// [`PaymentRequest::CrossChain::max_slippage_bps`] is not set on the
891    /// prepare request. Must be in 10 to 500. Falls back to 100 bps (1%)
892    /// when this field is unset.
893    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
894    pub default_slippage_bps: Option<u32>,
895    /// Default target-overpay pad in basis points applied to the user's
896    /// destination amount on `FeesExcluded` conversion sends. Bumps the
897    /// target upward before quoting so the recipient lands at or above the
898    /// requested amount despite provider slippage. Must be in 0 to 500.
899    /// Falls back to 15 bps when unset.
900    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
901    pub default_target_overpay_bps: Option<u32>,
902}
903
904impl CrossChainConfig {
905    pub(crate) fn validate(&self) -> Result<(), SdkError> {
906        if let Some(bps) = self.default_slippage_bps
907            && !(crate::cross_chain::MIN_CROSS_CHAIN_SLIPPAGE_BPS
908                ..=crate::cross_chain::MAX_CROSS_CHAIN_SLIPPAGE_BPS)
909                .contains(&bps)
910        {
911            return Err(SdkError::InvalidInput(format!(
912                "Default cross-chain slippage must be between {} and {} basis points, but got {bps}.",
913                crate::cross_chain::MIN_CROSS_CHAIN_SLIPPAGE_BPS,
914                crate::cross_chain::MAX_CROSS_CHAIN_SLIPPAGE_BPS,
915            )));
916        }
917        if let Some(bps) = self.default_target_overpay_bps
918            && !(crate::cross_chain::MIN_TARGET_OVERPAY_BPS
919                ..=crate::cross_chain::MAX_TARGET_OVERPAY_BPS)
920                .contains(&bps)
921        {
922            return Err(SdkError::InvalidInput(format!(
923                "Default cross-chain target-overpay must be between {} and {} basis points, but got {bps}.",
924                crate::cross_chain::MIN_TARGET_OVERPAY_BPS,
925                crate::cross_chain::MAX_TARGET_OVERPAY_BPS,
926            )));
927        }
928        Ok(())
929    }
930}
931
932/// Configuration for leaf optimization.
933#[derive(Debug, Clone)]
934#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
935pub struct LeafOptimizationConfig {
936    /// Whether automatic leaf optimization is enabled.
937    ///
938    /// If set to true, the SDK will automatically optimize the leaf set when it changes.
939    /// Otherwise, the manual optimization API must be used to optimize the leaf set.
940    ///
941    /// Default value is true.
942    pub auto_enabled: bool,
943    /// The desired multiplicity for the leaf set.
944    ///
945    /// Setting this to 0 will optimize for maximizing unilateral exit.
946    /// Higher values will optimize for minimizing transfer swaps, with higher values
947    /// being more aggressive and allowing better TPS rates.
948    ///
949    /// For end-user wallets, values of 1-5 are recommended. Values above 5 are
950    /// intended for high-throughput server environments and are not recommended
951    /// for end-user wallets due to significantly higher unilateral exit costs.
952    ///
953    /// Default value is 1.
954    pub multiplicity: u8,
955}
956
957/// Configuration for token-output optimization.
958#[derive(Debug, Clone)]
959#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
960pub struct TokenOptimizationConfig {
961    /// Whether automatic token-output consolidation is enabled.
962    ///
963    /// If set to true, the SDK will periodically consolidate a token's outputs
964    /// once their count exceeds [`Self::min_outputs_threshold`]. Otherwise, no
965    /// automatic consolidation is performed.
966    ///
967    /// Default value is true.
968    pub auto_enabled: bool,
969    /// Number of token outputs to produce when token-output auto-consolidation
970    /// fires.
971    ///
972    /// Instead of collapsing a token's outputs into a single output (which
973    /// serializes subsequent payments), the SDK splits the consolidated balance
974    /// across this many outputs of roughly equal value. Higher values preserve
975    /// concurrency for parallel sends at the cost of a slightly larger output
976    /// set.
977    ///
978    /// Must be >= 1 and strictly less than [`Self::min_outputs_threshold`].
979    ///
980    /// Default value is 5.
981    pub target_output_count: u32,
982    /// Output count that triggers per-token auto-consolidation.
983    ///
984    /// Auto-consolidation triggers for a token when its available output count
985    /// strictly exceeds this threshold.
986    ///
987    /// Must be greater than 1.
988    ///
989    /// Default value is 50.
990    pub min_outputs_threshold: u32,
991}
992
993/// A stable token that can be used for automatic balance conversion.
994#[derive(Debug, Clone)]
995#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
996pub struct StableBalanceToken {
997    /// Integrator-defined display label for the token, e.g. "USD".
998    ///
999    /// This is a short, human-readable name set by the integrator for display purposes.
1000    /// It is **not** a canonical Spark token ticker — it has no protocol-level meaning.
1001    /// Labels must be unique within the [`StableBalanceConfig::tokens`] list.
1002    pub label: String,
1003
1004    /// The full token identifier string used for conversions.
1005    pub token_identifier: String,
1006}
1007
1008/// Configuration for automatic conversion of Bitcoin to stable tokens.
1009///
1010/// When configured, the SDK automatically monitors the Bitcoin balance after each
1011/// wallet sync. Once the balance reaches the configured threshold, the SDK converts
1012/// the whole Bitcoin balance to the active stable token.
1013///
1014/// When the balance is held in a stable token, Bitcoin payments can still be sent.
1015/// The SDK automatically detects when there's not enough Bitcoin balance to cover a
1016/// payment and auto-populates the token-to-Bitcoin conversion options to facilitate
1017/// the payment.
1018///
1019/// The active token can be changed at runtime via [`UpdateUserSettingsRequest`].
1020#[derive(Debug, Clone)]
1021#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1022pub struct StableBalanceConfig {
1023    /// Available tokens that can be used for stable balance.
1024    pub tokens: Vec<StableBalanceToken>,
1025
1026    /// The label of the token to activate by default.
1027    ///
1028    /// If `None`, stable balance starts deactivated. The user can activate it
1029    /// at runtime via [`UpdateUserSettingsRequest`]. If a user setting is cached
1030    /// locally, it takes precedence over this default.
1031    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
1032    pub default_active_label: Option<String>,
1033
1034    /// The minimum sats balance that triggers auto-conversion.
1035    ///
1036    /// If not provided, uses the minimum from conversion limits.
1037    /// If provided but less than the conversion limit minimum, the limit minimum is used.
1038    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
1039    pub threshold_sats: Option<u64>,
1040
1041    /// Maximum slippage in basis points (1/100 of a percent).
1042    ///
1043    /// Defaults to 10 bps (0.1%) if not set.
1044    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
1045    pub max_slippage_bps: Option<u32>,
1046}
1047
1048/// Specifies how to update the active stable balance token.
1049#[derive(Debug, Clone)]
1050#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1051pub enum StableBalanceActiveLabel {
1052    /// Activate stable balance with the given label.
1053    Set { label: String },
1054    /// Deactivate stable balance.
1055    Unset,
1056}
1057
1058/// Configuration for a custom Spark environment.
1059///
1060/// When set on [`Config`], overrides the default Spark operator pool,
1061/// service provider, threshold, and token settings. This allows connecting
1062/// to alternative Spark deployments (e.g. dev/staging environments).
1063#[derive(Debug, Clone, Deserialize)]
1064#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1065pub struct SparkConfig {
1066    /// Hex-encoded identifier of the coordinator operator.
1067    pub coordinator_identifier: String,
1068    /// The FROST signing threshold (e.g. 2 of 3).
1069    pub threshold: u32,
1070    /// The set of signing operators.
1071    pub signing_operators: Vec<SparkSigningOperator>,
1072    /// Service provider (SSP) configuration.
1073    pub ssp_config: SparkSspConfig,
1074    /// Expected bond amount in sats for token withdrawals.
1075    pub expected_withdraw_bond_sats: u64,
1076    /// Expected relative block locktime for token withdrawals.
1077    pub expected_withdraw_relative_block_locktime: u64,
1078    /// Cap on the inputs a single token transaction may spend. A send needing
1079    /// more first consolidates the wallet's token outputs. Unset uses the SDK
1080    /// default (500).
1081    pub max_token_transaction_inputs: Option<u32>,
1082}
1083
1084impl From<&SparkConfig> for spark_wallet::SparkDeployment {
1085    fn from(config: &SparkConfig) -> Self {
1086        Self {
1087            coordinator_identifier: config.coordinator_identifier.clone(),
1088            threshold: config.threshold,
1089            signing_operators: config
1090                .signing_operators
1091                .iter()
1092                .map(|operator| spark_wallet::SparkDeploymentOperator {
1093                    id: operator.id,
1094                    identifier: operator.identifier.clone(),
1095                    address: operator.address.clone(),
1096                    identity_public_key: operator.identity_public_key.clone(),
1097                    ca_cert_pem: operator.ca_cert_pem.clone(),
1098                })
1099                .collect(),
1100            ssp_config: spark_wallet::SparkDeploymentSsp {
1101                base_url: config.ssp_config.base_url.clone(),
1102                identity_public_key: config.ssp_config.identity_public_key.clone(),
1103                schema_endpoint: config.ssp_config.schema_endpoint.clone(),
1104            },
1105            expected_withdraw_bond_sats: config.expected_withdraw_bond_sats,
1106            expected_withdraw_relative_block_locktime: config
1107                .expected_withdraw_relative_block_locktime,
1108            max_token_transaction_inputs: config.max_token_transaction_inputs,
1109        }
1110    }
1111}
1112
1113/// A Spark signing operator.
1114#[derive(Debug, Clone, Deserialize)]
1115#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1116pub struct SparkSigningOperator {
1117    /// Sequential operator ID (0-indexed).
1118    pub id: u32,
1119    /// Hex-encoded 32-byte FROST identifier.
1120    pub identifier: String,
1121    /// gRPC address of the operator (e.g. `https://0.spark.lightspark.com`).
1122    pub address: String,
1123    /// Hex-encoded compressed public key of the operator.
1124    pub identity_public_key: String,
1125    /// Optional PEM-encoded CA certificate for TLS verification.
1126    /// When set, the SDK uses this CA to verify the operator's TLS certificate
1127    /// instead of the system/default roots. Useful for local development with
1128    /// self-signed certificates.
1129    pub ca_cert_pem: Option<String>,
1130}
1131
1132/// Configuration for the Spark Service Provider (SSP).
1133#[derive(Debug, Clone, Deserialize)]
1134#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1135pub struct SparkSspConfig {
1136    /// Base URL of the SSP GraphQL API.
1137    pub base_url: String,
1138    /// Hex-encoded compressed public key of the SSP.
1139    pub identity_public_key: String,
1140    /// Optional GraphQL schema endpoint path (e.g. "graphql/spark/rc").
1141    /// Defaults to the hardcoded schema endpoint if not set.
1142    pub schema_endpoint: Option<String>,
1143}
1144
1145impl Config {
1146    /// Validates the configuration.
1147    ///
1148    /// Returns an error if any configuration values are invalid.
1149    pub fn validate(&self) -> Result<(), SdkError> {
1150        if self.network == Network::Signet && self.spark_config.is_none() {
1151            return Err(SdkError::InvalidInput(
1152                "Signet requires an explicit spark_config with signing operators and an SSP"
1153                    .to_string(),
1154            ));
1155        }
1156        if self.max_concurrent_claims == 0 {
1157            return Err(SdkError::InvalidInput(
1158                "max_concurrent_claims must be greater than 0".to_string(),
1159            ));
1160        }
1161
1162        if let Some(sb) = &self.stable_balance_config {
1163            if sb.tokens.is_empty() {
1164                return Err(SdkError::InvalidInput(
1165                    "tokens must not be empty".to_string(),
1166                ));
1167            }
1168
1169            let mut seen_labels = HashSet::new();
1170            let mut seen_identifiers = HashSet::new();
1171            for token in &sb.tokens {
1172                if token.label.is_empty() {
1173                    return Err(SdkError::InvalidInput(
1174                        "token label must not be empty".to_string(),
1175                    ));
1176                }
1177                if token.token_identifier.is_empty() {
1178                    return Err(SdkError::InvalidInput(
1179                        "token_identifier must not be empty".to_string(),
1180                    ));
1181                }
1182                if bech32m_decode_token_id(&token.token_identifier, Some(self.network.into()))
1183                    .is_err()
1184                {
1185                    return Err(SdkError::InvalidInput(format!(
1186                        "token_identifier must be a bech32m token identifier for this network: {}",
1187                        token.token_identifier
1188                    )));
1189                }
1190                if !seen_labels.insert(&token.label) {
1191                    return Err(SdkError::InvalidInput(format!(
1192                        "tokens contains duplicate label: {}",
1193                        token.label
1194                    )));
1195                }
1196                if !seen_identifiers.insert(&token.token_identifier) {
1197                    return Err(SdkError::InvalidInput(format!(
1198                        "tokens contains duplicate token_identifier: {}",
1199                        token.token_identifier
1200                    )));
1201                }
1202            }
1203
1204            if let Some(bps) = sb.max_slippage_bps
1205                && bps > 10000
1206            {
1207                return Err(SdkError::InvalidInput(
1208                    "max_slippage_bps must be <= 10000".to_string(),
1209                ));
1210            }
1211
1212            if let Some(default_label) = &sb.default_active_label
1213                && !seen_labels.contains(default_label)
1214            {
1215                return Err(SdkError::InvalidInput(format!(
1216                    "default_active_label '{default_label}' not found in tokens list"
1217                )));
1218            }
1219        }
1220
1221        self.validate_token_optimization()?;
1222        self.proxy.as_ref().map_or(Ok(()), ProxyConfig::validate)?;
1223
1224        if let Some(cc) = &self.cross_chain_config {
1225            if self.network != Network::Mainnet {
1226                return Err(SdkError::InvalidInput(format!(
1227                    "Cross-chain sends are only available on Mainnet, not on {}.",
1228                    self.network,
1229                )));
1230            }
1231            cc.validate()?;
1232        }
1233
1234        Ok(())
1235    }
1236
1237    fn validate_token_optimization(&self) -> Result<(), SdkError> {
1238        let token_opt = &self.token_optimization_config;
1239        if token_opt.min_outputs_threshold <= 1 {
1240            return Err(SdkError::InvalidInput(
1241                "token optimization minimum outputs threshold must be greater than 1".to_string(),
1242            ));
1243        }
1244        if token_opt.target_output_count < 1 {
1245            return Err(SdkError::InvalidInput(
1246                "token optimization target output count must be at least 1".to_string(),
1247            ));
1248        }
1249        if token_opt.target_output_count >= token_opt.min_outputs_threshold {
1250            return Err(SdkError::InvalidInput(
1251                "token optimization target output count must be less than the minimum outputs threshold".to_string(),
1252            ));
1253        }
1254        Ok(())
1255    }
1256
1257    pub(crate) fn get_all_external_input_parsers(&self) -> Vec<ExternalInputParser> {
1258        let mut external_input_parsers = Vec::new();
1259        if self.use_default_external_input_parsers {
1260            let default_parsers = DEFAULT_EXTERNAL_INPUT_PARSERS
1261                .iter()
1262                .map(|(id, regex, url)| ExternalInputParser {
1263                    provider_id: (*id).to_string(),
1264                    input_regex: (*regex).to_string(),
1265                    parser_url: (*url).to_string(),
1266                })
1267                .collect::<Vec<_>>();
1268            external_input_parsers.extend(default_parsers);
1269        }
1270        external_input_parsers.extend(self.external_input_parsers.clone().unwrap_or_default());
1271
1272        external_input_parsers
1273    }
1274}
1275
1276/// The most a deposit claim may cost: an on-chain part plus an optional share
1277/// of the deposit amount.
1278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1279#[serde(from = "StoredMaxFee", into = "StoredMaxFee")]
1280#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1281pub struct MaxFee {
1282    pub onchain: MaxOnchainFee,
1283    /// A share of the deposit amount added on top of the on-chain part, in parts
1284    /// per million (100 ppm is 0.01%), to allow for a provider fee that grows
1285    /// with the deposit. It applies to every claim, early ones included. Unset
1286    /// adds nothing.
1287    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
1288    pub proportional_ppm: Option<u32>,
1289}
1290
1291/// The on-chain part of a [`MaxFee`].
1292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1293#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1294pub enum MaxOnchainFee {
1295    /// A fixed amount in sats.
1296    Fixed { amount: u64 },
1297    /// A fee rate in sats per vbyte.
1298    Rate { sat_per_vbyte: u64 },
1299    /// The fastest recommended fee rate at the time of the claim plus a leeway in
1300    /// sats per vbyte.
1301    NetworkRecommended { leeway_sat_per_vbyte: u64 },
1302}
1303
1304/// How a [`MaxFee`] is persisted: one variant per on-chain kind, each carrying the
1305/// proportional part. Ceilings stored before the split are in this shape, so
1306/// keeping it lets them load as they are.
1307#[derive(Serialize, Deserialize)]
1308enum StoredMaxFee {
1309    Fixed {
1310        amount: u64,
1311        #[serde(default, skip_serializing_if = "Option::is_none")]
1312        proportional_ppm: Option<u32>,
1313    },
1314    Rate {
1315        sat_per_vbyte: u64,
1316        #[serde(default, skip_serializing_if = "Option::is_none")]
1317        proportional_ppm: Option<u32>,
1318    },
1319    NetworkRecommended {
1320        leeway_sat_per_vbyte: u64,
1321        #[serde(default, skip_serializing_if = "Option::is_none")]
1322        proportional_ppm: Option<u32>,
1323    },
1324}
1325
1326impl From<StoredMaxFee> for MaxFee {
1327    fn from(stored: StoredMaxFee) -> Self {
1328        let (onchain, proportional_ppm) = match stored {
1329            StoredMaxFee::Fixed {
1330                amount,
1331                proportional_ppm,
1332            } => (MaxOnchainFee::Fixed { amount }, proportional_ppm),
1333            StoredMaxFee::Rate {
1334                sat_per_vbyte,
1335                proportional_ppm,
1336            } => (MaxOnchainFee::Rate { sat_per_vbyte }, proportional_ppm),
1337            StoredMaxFee::NetworkRecommended {
1338                leeway_sat_per_vbyte,
1339                proportional_ppm,
1340            } => (
1341                MaxOnchainFee::NetworkRecommended {
1342                    leeway_sat_per_vbyte,
1343                },
1344                proportional_ppm,
1345            ),
1346        };
1347        MaxFee {
1348            onchain,
1349            proportional_ppm,
1350        }
1351    }
1352}
1353
1354impl From<MaxFee> for StoredMaxFee {
1355    fn from(max_fee: MaxFee) -> Self {
1356        let proportional_ppm = max_fee.proportional_ppm;
1357        match max_fee.onchain {
1358            MaxOnchainFee::Fixed { amount } => StoredMaxFee::Fixed {
1359                amount,
1360                proportional_ppm,
1361            },
1362            MaxOnchainFee::Rate { sat_per_vbyte } => StoredMaxFee::Rate {
1363                sat_per_vbyte,
1364                proportional_ppm,
1365            },
1366            MaxOnchainFee::NetworkRecommended {
1367                leeway_sat_per_vbyte,
1368            } => StoredMaxFee::NetworkRecommended {
1369                leeway_sat_per_vbyte,
1370                proportional_ppm,
1371            },
1372        }
1373    }
1374}
1375
1376impl MaxFee {
1377    /// The share of the deposit amount allowed on top of the on-chain part, in
1378    /// parts per million.
1379    pub(crate) fn proportional_ppm(&self) -> u32 {
1380        self.proportional_ppm.unwrap_or(0)
1381    }
1382
1383    /// The on-chain part of the ceiling, priced at the current fee market.
1384    pub(crate) async fn to_fee(&self, fee_market: &FeeMarket<'_>) -> Result<Fee, SdkError> {
1385        match &self.onchain {
1386            MaxOnchainFee::Fixed { amount } => Ok(Fee::Fixed { amount: *amount }),
1387            MaxOnchainFee::Rate { sat_per_vbyte } => Ok(Fee::Rate {
1388                sat_per_vbyte: *sat_per_vbyte,
1389            }),
1390            MaxOnchainFee::NetworkRecommended {
1391                leeway_sat_per_vbyte,
1392            } => {
1393                let recommended_fees = fee_market.recommended_fees().await?;
1394                let max_fee_rate = recommended_fees
1395                    .fastest_fee
1396                    .saturating_add(*leeway_sat_per_vbyte);
1397                Ok(Fee::Rate {
1398                    sat_per_vbyte: max_fee_rate,
1399                })
1400            }
1401        }
1402    }
1403}
1404
1405#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1406#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1407pub enum Fee {
1408    // Fixed fee amount in sats
1409    Fixed { amount: u64 },
1410    // Relative fee rate in satoshis per vbyte
1411    Rate { sat_per_vbyte: u64 },
1412}
1413
1414impl Fee {
1415    pub fn to_sats(&self, vbytes: u64) -> u64 {
1416        match self {
1417            Fee::Fixed { amount } => *amount,
1418            Fee::Rate { sat_per_vbyte } => sat_per_vbyte.saturating_mul(vbytes),
1419        }
1420    }
1421}
1422
1423/// State of an instant claim attempt on a deposit.
1424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1425#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1426pub enum InstantClaimStatus {
1427    /// The early claim was declined and the deposit falls through to the claim at
1428    /// maturity. `max_fee_sats` is the ceiling that declined it, unset when the
1429    /// decline was for a reason no ceiling will fix. `confirmations` is the depth
1430    /// it was declined at.
1431    Declined {
1432        max_fee_sats: Option<u64>,
1433        #[serde(default)]
1434        confirmations: u32,
1435    },
1436    /// An instant claim was submitted and is settling. Carries the SSP claim id.
1437    Submitted { claim_id: String },
1438    /// A claim has taken the deposit: either its credit arrived here, or the
1439    /// provider reports the deposit as already claimed. It stays listed until
1440    /// the provider spends the output, so treat it as settled rather than as
1441    /// awaiting action.
1442    Claimed,
1443}
1444
1445/// State of the deposit refund broadcast.
1446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1447#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1448pub enum RefundState {
1449    /// The refund is signed and stored but has not been seen on the network.
1450    /// `last_error` carries the reason the most recent broadcast was refused,
1451    /// unset while none has been refused. A refund whose fee is under the
1452    /// network's current minimum stays here until it is re-created at a higher
1453    /// fee.
1454    BroadcastPending { last_error: Option<String> },
1455    /// The refund has been accepted by the network and is waiting to confirm.
1456    Broadcast,
1457}
1458
1459#[derive(Debug, Clone, Serialize, Deserialize)]
1460#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1461pub struct DepositInfo {
1462    /// Transaction id of the on-chain output the deposit came from.
1463    pub txid: String,
1464    /// Index of that output within its transaction.
1465    pub vout: u32,
1466    /// Deposit value in satoshis.
1467    pub amount_sats: u64,
1468    /// Whether the deposit has enough confirmations to be claimed.
1469    pub is_mature: bool,
1470    /// Raw refund transaction, once one has been created.
1471    pub refund_tx: Option<String>,
1472    /// Transaction id of the refund, once one has been created.
1473    pub refund_tx_id: Option<String>,
1474    /// How far the refund has got towards the network. Unset when no refund has
1475    /// been created, and on refunds created before this field existed.
1476    pub refund_state: Option<RefundState>,
1477    /// Why the last claim attempt failed. Unset while none has failed.
1478    pub claim_error: Option<DepositClaimError>,
1479    /// Unset when no instant claim has been attempted.
1480    pub instant_claim_status: Option<InstantClaimStatus>,
1481    /// The fee ceiling standing for this deposit alone. It caps what may be paid
1482    /// to claim the deposit ahead of maturity. The claim at maturity runs under
1483    /// whichever is larger, this or the configured max deposit claim fee, so a
1484    /// ceiling set below that one does not hold the deposit back from it. Unset
1485    /// means the configured ceiling applies to both.
1486    pub max_claim_fee: Option<MaxFee>,
1487}
1488
1489#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1490pub struct ClaimDepositRequest {
1491    pub txid: String,
1492    pub vout: u32,
1493    /// Caps what the claim may cost, and is recorded on the deposit so later
1494    /// automatic attempts are held to it too.
1495    ///
1496    /// Raising it above the quoted spread is what lets a deposit be claimed ahead
1497    /// of maturity without further input. Lowering it below the spread keeps the
1498    /// deposit from being claimed early, and does not hold back its claim at
1499    /// maturity: that one runs under whichever is larger, this or the configured
1500    /// max deposit claim fee.
1501    ///
1502    /// Unset claims under the configured max deposit claim fee and clears any
1503    /// ceiling previously recorded on the deposit.
1504    ///
1505    /// The ceiling is recorded before the claim is attempted, so it stands even
1506    /// when the attempt is then declined for exceeding it.
1507    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
1508    pub max_fee: Option<MaxFee>,
1509}
1510
1511/// Why a claim was deferred rather than made.
1512#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1513#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1514pub enum ClaimDeferredReason {
1515    /// Claiming ahead of maturity costs more than the fee ceiling allows. Unlike a
1516    /// depth that has not arrived, this does not clear on its own: the deposit is
1517    /// claimed at maturity unless the ceiling is raised.
1518    ///
1519    /// `required_fee_sats` is what the early claim would have cost, so a caller can
1520    /// offer it at that price rather than quoting again.
1521    MaxFeeExceeded {
1522        /// What the provider asked to credit the deposit early.
1523        required_fee_sats: u64,
1524        /// The ceiling it was held to.
1525        max_fee_sats: u64,
1526    },
1527    /// The provider offers no early claim at the deposit's current depth, either
1528    /// because it is too shallow for any plan or because none was offered for it.
1529    /// Depth is the usual cause, and it resolves itself: the next confirmation may
1530    /// well bring an early claim within reach.
1531    NoEarlyClaimAvailable,
1532    /// The provider refused the early claim or could not be reached, so nothing was
1533    /// submitted. Unlike a depth that has not arrived, waiting for a confirmation
1534    /// does not address this, and the deposit is claimed at maturity unless a later
1535    /// call succeeds. `message` is what the provider or the transport reported.
1536    ProviderDeclined { message: String },
1537}
1538
1539/// What became of a claim.
1540#[allow(clippy::large_enum_variant)]
1541#[derive(Debug, Clone, Serialize)]
1542#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1543pub enum ClaimDepositOutcome {
1544    /// Claimed at maturity and settled, carrying the payment it produced.
1545    Settled { payment: Payment },
1546    /// Claimed ahead of maturity and submitted. The transfer settles
1547    /// asynchronously, so no payment is returned yet: watch for it via events or
1548    /// `list_payments`.
1549    Submitted,
1550    /// Nothing was claimed yet, and no further call is needed: any fee ceiling this
1551    /// one asked for stands on the deposit, and the SDK keeps claiming it on its
1552    /// own. An early claim is attempted again as the deposit gains confirmations,
1553    /// so one declined for being too shallow is often claimed early a block or two
1554    /// later. Failing that, the deposit is claimed at maturity.
1555    ///
1556    /// An ordinary outcome rather than a failure. `reason` says which of the two to
1557    /// expect: a depth that has not arrived yet, or a cost the ceiling will not
1558    /// cover.
1559    Deferred { reason: ClaimDeferredReason },
1560}
1561
1562#[derive(Debug, Clone, Serialize)]
1563#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1564pub struct ClaimDepositResponse {
1565    /// What the call did. Which outcome occurs follows from the deposit's maturity
1566    /// and the fee ceiling, not from anything the caller asks for, so handle all
1567    /// three on every claim.
1568    pub outcome: ClaimDepositOutcome,
1569}
1570
1571#[derive(Debug, Clone, Serialize)]
1572#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1573pub struct FetchClaimDepositQuoteRequest {
1574    pub txid: String,
1575    pub vout: u32,
1576}
1577
1578/// What one way of claiming a deposit costs.
1579#[derive(Debug, Clone, Serialize)]
1580#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1581pub struct ClaimDepositQuote {
1582    /// The depth this becomes claimable at, as a total confirmation count on the
1583    /// deposit tx and not a number still to wait. A deposit already at or past
1584    /// this depth can be claimed.
1585    pub confirmations_required: u32,
1586    /// What reaches the balance.
1587    pub credit_amount_sats: u64,
1588    /// The deposit value less the credit.
1589    pub fee_sats: u64,
1590    /// The most this claim may cost for this deposit, in sats, under the max claim
1591    /// fee that applies to it. The SDK claims automatically when `fee_sats` is
1592    /// within it. Unset when automatic claiming is off.
1593    pub max_fee_sats: Option<u64>,
1594    /// The provider would not quote this yet, so the fee is derived from current
1595    /// on-chain fees and the real one may differ.
1596    pub is_estimate: bool,
1597}
1598
1599#[derive(Debug, Clone, Serialize)]
1600#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1601pub struct FetchClaimDepositQuoteResponse {
1602    pub amount_sats: u64,
1603    /// Confirmations the deposit has now, 0 while unconfirmed.
1604    pub confirmations: u32,
1605    /// Claiming ahead of maturity, for a spread. Absent when the provider offers
1606    /// no such option for this deposit, and when claiming early would not actually
1607    /// be earlier: a deposit that has already matured, or a plan crediting no
1608    /// sooner than maturity would, is only ever the more expensive way to wait.
1609    ///
1610    /// Also absent when the provider could not be reached for a quote, which is not
1611    /// distinguished here from having nothing to offer: both mean there is no early
1612    /// claim to show right now, and the one worth retrying is the transient one.
1613    ///
1614    /// Priced regardless of the max claim fee, so it can be offered: its
1615    /// `fee_sats` within its `max_fee_sats` means the SDK claims it on its own.
1616    /// Claiming it by hand needs a max fee of at least its `fee_sats`.
1617    pub instant: Option<ClaimDepositQuote>,
1618    /// Claiming once the deposit matures.
1619    pub mature: ClaimDepositQuote,
1620}
1621
1622#[derive(Debug, Clone, Serialize)]
1623#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1624pub struct RefundDepositRequest {
1625    pub txid: String,
1626    pub vout: u32,
1627    pub destination_address: String,
1628    pub fee: Fee,
1629}
1630
1631#[derive(Debug, Clone, Serialize)]
1632#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1633pub struct RefundDepositResponse {
1634    pub tx_id: String,
1635    pub tx_hex: String,
1636}
1637
1638#[derive(Debug, Clone, Serialize)]
1639#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1640pub struct ListUnclaimedDepositsRequest {}
1641
1642#[derive(Debug, Clone, Serialize)]
1643#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1644pub struct ListUnclaimedDepositsResponse {
1645    pub deposits: Vec<DepositInfo>,
1646}
1647
1648/// The available providers for buying Bitcoin
1649/// Request to buy Bitcoin using an external provider.
1650///
1651/// Each variant carries only the parameters relevant to that provider.
1652#[derive(Debug, Clone)]
1653#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1654pub enum BuyBitcoinRequest {
1655    /// `MoonPay`: Fiat purchase via credit card, Apple Pay, etc.
1656    Moonpay {
1657        /// How `MoonPay` delivers the purchase. Defaults to Bitcoin with no
1658        /// amount.
1659        delivery: Option<MoonpayDelivery>,
1660        /// Custom redirect URL after purchase completion.
1661        redirect_url: Option<String>,
1662    },
1663    /// `CashApp`: Pay via the Lightning Network.
1664    /// Returns a `cash.app` deep link to a bolt11 invoice. A conversion
1665    /// provider delivers the payment to the wallet over Spark, and the payer
1666    /// pays its fee on top of the amount. Only available on mainnet.
1667    ///
1668    /// The amount is required. With an amountless invoice, Cash App only
1669    /// lets the payer fund from their existing Cash App BTC balance. With
1670    /// a fixed-amount invoice, Cash App opens up funding via fiat balance
1671    /// and debit card.
1672    CashApp {
1673        /// Amount in satoshis the wallet receives. Must be non-zero.
1674        amount_sats: u64,
1675    },
1676}
1677
1678impl Default for BuyBitcoinRequest {
1679    fn default() -> Self {
1680        Self::Moonpay {
1681            delivery: None,
1682            redirect_url: None,
1683        }
1684    }
1685}
1686
1687/// How a `MoonPay` purchase is delivered.
1688#[derive(Debug, Clone)]
1689#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1690pub enum MoonpayDelivery {
1691    /// Bitcoin to an on-chain deposit address.
1692    Bitcoin {
1693        /// Amount in satoshis to prefill the checkout with.
1694        amount_sat: Option<u64>,
1695    },
1696    /// USDC on Solana, converted on arrival into the active stable balance
1697    /// token if set, otherwise Bitcoin. Requires `cross_chain_config`.
1698    CrossChain {
1699        /// USD amount to prefill the checkout with, in 6-decimal base units
1700        /// (`1_000_000` is $1).
1701        amount: u128,
1702        /// Whether the conversion fee is added on top of `amount`
1703        /// (`FeesExcluded`, the default) or deducted from it (`FeesIncluded`).
1704        fee_mode: Option<crate::cross_chain::CrossChainFeeMode>,
1705    },
1706}
1707
1708impl Default for MoonpayDelivery {
1709    fn default() -> Self {
1710        Self::Bitcoin { amount_sat: None }
1711    }
1712}
1713
1714/// Response containing a URL to complete the Bitcoin purchase
1715#[derive(Debug, Clone, Serialize)]
1716#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1717pub struct BuyBitcoinResponse {
1718    /// The URL to open in a browser to complete the purchase
1719    pub url: String,
1720    /// The conversion quote, populated for cross-chain delivery and for
1721    /// `CashApp`, whose purchase is delivered through a conversion provider.
1722    pub cross_chain_info: Option<crate::cross_chain::CrossChainReceiveInfo>,
1723}
1724
1725/// Response from refunding pending conversions.
1726#[derive(Debug, Clone, Serialize, Default)]
1727#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1728pub struct RefundPendingConversionsResponse {
1729    /// Conversions successfully refunded this pass.
1730    pub refunded: u32,
1731    /// Conversions not clawed back this pass: held back by a safety window, or
1732    /// found to have executed after all. Only the former are retried.
1733    pub skipped: u32,
1734    /// Conversions whose clawback did not complete this pass (rejected or
1735    /// errored; funds not returned). The next pass will retry them.
1736    pub failed: u32,
1737}
1738
1739/// **Deprecated.** Use `CreateBridgeRequest` with the bridging client's
1740/// `bridge_from_cash_app`.
1741///
1742/// Request for a payment link that sends USDC/USDT to an external-chain
1743/// recipient, funded by Cash App over Lightning.
1744///
1745/// The user pays the returned URL, and the cross-chain provider delivers the
1746/// stablecoin to `address`. No funds move through the Spark wallet. Only
1747/// available on mainnet.
1748#[derive(Debug, Clone)]
1749#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1750pub struct PreparePaymentLinkRequest {
1751    /// Recipient address on the destination chain (e.g. an EVM `0x...` address).
1752    pub address: String,
1753    /// The destination route from calling `get_cross_chain_routes()` with the
1754    /// `CrossChainRouteFilter::PaymentLink` filter. Selects the destination chain
1755    /// + asset (e.g. USDC on Base).
1756    pub route: CrossChainRoutePair,
1757    /// Amount in the destination asset's base units, per the route's
1758    /// `decimals`. These routes deliver USD-pegged stablecoins, so at parity
1759    /// this is the USD value: `1_000_000` is 1 USDC (6 decimals), about $1.
1760    ///
1761    /// With the default fee policy the recipient receives this net amount.
1762    /// With `FeesIncluded` it is the amount the payer deposits.
1763    pub amount: u128,
1764    /// Whether fees are added on top of `amount` (`FeesExcluded`, the default)
1765    /// or deducted from it (`FeesIncluded`).
1766    pub fee_policy: Option<FeePolicy>,
1767    /// Maximum slippage tolerance in basis points. Falls back to the SDK
1768    /// default when unset.
1769    pub max_slippage_bps: Option<u32>,
1770}
1771
1772/// **Deprecated.** Use `CreateBridgeResponse`, from the bridging client's
1773/// `bridge_from_cash_app`.
1774///
1775/// Response to a [`PreparePaymentLinkRequest`]. Mirrors `BuyBitcoinResponse`
1776/// (a payable `url`) plus the quote so the caller can display the expected
1777/// delivery and fees.
1778#[derive(Debug, Clone, Serialize)]
1779#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1780pub struct PreparePaymentLinkResponse {
1781    /// The URL to open in a browser; paying it delivers the stablecoin.
1782    pub url: String,
1783    /// Sats the payer deposits through the fiat rail.
1784    pub amount_sats: u64,
1785    /// Estimated amount delivered to the recipient, in `asset` base units.
1786    pub estimated_out: u128,
1787    /// The destination stablecoin symbol (e.g. `USDC`). `estimated_out` is
1788    /// denominated in it.
1789    pub asset: String,
1790    /// Provider service fee, including the partner fee when one is set, in
1791    /// `service_fee_asset` base units.
1792    pub service_fee_amount: u128,
1793    /// Denomination of `service_fee_amount`. `None` means sats: Boltz
1794    /// denominates its fee in sats, Orchestra in the stablecoin.
1795    pub service_fee_asset: Option<String>,
1796    /// Decimals of `service_fee_asset`, for formatting `service_fee_amount`.
1797    /// Unset when the fee is in sats or the provider did not report them.
1798    pub service_fee_asset_decimals: Option<u32>,
1799    /// RFC3339 timestamp after which the quote is no longer valid.
1800    pub expires_at: String,
1801}
1802
1803/// **Deprecated.** Use `CreateBridgeRequest` with the bridging client's
1804/// `bridge_from_cash_app`.
1805///
1806/// Request to bridge from Cash App to USDC/USDT on an external chain.
1807///
1808/// The payer pays the returned URL in Cash App over Lightning, and the
1809/// cross-chain provider delivers the stablecoin to `address`. No funds move
1810/// through the Spark wallet. Only available on mainnet.
1811#[derive(Debug, Clone)]
1812#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1813pub struct BridgeFromCashAppRequest {
1814    /// Recipient address on the destination chain (e.g. an EVM `0x...` address).
1815    pub address: String,
1816    /// The destination route from calling `get_cross_chain_routes()` with the
1817    /// `CrossChainRouteFilter::Send` filter and its `delivery_method` set to
1818    /// `Lightning`. Selects the destination chain + asset (e.g. USDC on Base).
1819    pub route: CrossChainRoutePair,
1820    /// Amount in the destination asset's base units, per the route's
1821    /// `decimals`. These routes deliver USD-pegged stablecoins, so at parity
1822    /// this is the USD value: `1_000_000` is 1 USDC (6 decimals), about $1.
1823    ///
1824    /// With the default fee policy the recipient receives this net amount.
1825    /// With `FeesIncluded` it is the amount the payer deposits.
1826    pub amount: u128,
1827    /// Whether fees are added on top of `amount` (`FeesExcluded`, the default)
1828    /// or deducted from it (`FeesIncluded`).
1829    pub fee_policy: Option<FeePolicy>,
1830    /// Maximum slippage tolerance in basis points. Falls back to the SDK
1831    /// default when unset.
1832    pub max_slippage_bps: Option<u32>,
1833}
1834
1835/// **Deprecated.** Use `CreateBridgeResponse`, from the bridging client's
1836/// `bridge_from_cash_app`.
1837///
1838/// Response to a [`BridgeFromCashAppRequest`]: the URL to pay plus the quote,
1839/// so the caller can display the expected delivery and fees.
1840#[derive(Debug, Clone, Serialize)]
1841#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1842pub struct BridgeFromCashAppResponse {
1843    /// The `cash.app` URL to open. Paying it delivers the stablecoin.
1844    pub url: String,
1845    /// Sats the payer deposits through Cash App.
1846    pub amount_sats: u64,
1847    /// Estimated amount delivered to the recipient, in `asset` base units.
1848    pub estimated_out: u128,
1849    /// The destination stablecoin symbol (e.g. `USDC`). `estimated_out` is
1850    /// denominated in it.
1851    pub asset: String,
1852    /// Provider service fee, including the partner fee when one is set, in
1853    /// `service_fee_asset` base units.
1854    pub service_fee_amount: u128,
1855    /// Denomination of `service_fee_amount`. Unset means sats.
1856    pub service_fee_asset: Option<String>,
1857    /// Decimals of `service_fee_asset`, for formatting `service_fee_amount`.
1858    /// Unset when the fee is in sats or the provider did not report them.
1859    pub service_fee_asset_decimals: Option<u32>,
1860    /// Quote expiry as a Unix timestamp in seconds.
1861    pub expires_at: u64,
1862}
1863
1864impl From<PreparePaymentLinkRequest> for BridgeFromCashAppRequest {
1865    fn from(request: PreparePaymentLinkRequest) -> Self {
1866        BridgeFromCashAppRequest {
1867            address: request.address,
1868            route: request.route,
1869            amount: request.amount,
1870            fee_policy: request.fee_policy,
1871            max_slippage_bps: request.max_slippage_bps,
1872        }
1873    }
1874}
1875
1876impl From<BridgeFromCashAppResponse> for PreparePaymentLinkResponse {
1877    fn from(response: BridgeFromCashAppResponse) -> Self {
1878        PreparePaymentLinkResponse {
1879            url: response.url,
1880            amount_sats: response.amount_sats,
1881            estimated_out: response.estimated_out,
1882            asset: response.asset,
1883            service_fee_amount: response.service_fee_amount,
1884            service_fee_asset: response.service_fee_asset,
1885            service_fee_asset_decimals: response.service_fee_asset_decimals,
1886            expires_at: i64::try_from(response.expires_at)
1887                .ok()
1888                .and_then(|secs| chrono::DateTime::from_timestamp(secs, 0))
1889                .map_or_else(
1890                    || response.expires_at.to_string(),
1891                    |dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1892                ),
1893        }
1894    }
1895}
1896
1897/// **Deprecated.** Use `CreateBridgeRequest` with the bridging client's
1898/// `bridge_to_cash_app`.
1899///
1900/// Request to bridge USDC/USDT from an external chain to a Cash App user.
1901///
1902/// The payer deposits the stablecoin to the returned address, and the
1903/// cross-chain provider pays the recipient in Bitcoin over Lightning. No funds
1904/// move through the Spark wallet. Only available on mainnet.
1905#[derive(Debug, Clone)]
1906#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1907pub struct BridgeToCashAppRequest {
1908    /// The Cash App user, as a username (`alice` or `$alice`) or a Cash App
1909    /// Lightning address (`alice@cash.app`).
1910    pub recipient: String,
1911    /// The source route from calling `get_cross_chain_routes()` with the
1912    /// `CrossChainRouteFilter::Receive` filter and its `delivery_method` set to
1913    /// `Lightning`. Selects the source chain + asset (e.g. USDC on Base).
1914    pub route: CrossChainRoutePair,
1915    /// Amount in the source asset's base units, per the route's `decimals`.
1916    /// These routes carry USD-pegged stablecoins, so at parity this is the USD
1917    /// value: `1_000_000` is 1 USDC (6 decimals), about $1.
1918    ///
1919    /// With the default fee policy the recipient receives about this value in
1920    /// Bitcoin. With `FeesIncluded` it is the amount the payer deposits.
1921    pub amount: u128,
1922    /// Whether fees are added on top of `amount` (`FeesExcluded`, the default)
1923    /// or deducted from it (`FeesIncluded`).
1924    pub fee_policy: Option<FeePolicy>,
1925    /// The payer's address on the source chain. The deposit is refunded here
1926    /// if the recipient can't be paid.
1927    pub refund_address: String,
1928    /// Maximum slippage tolerance in basis points. Falls back to the SDK
1929    /// default when unset.
1930    pub max_slippage_bps: Option<u32>,
1931}
1932
1933/// **Deprecated.** Use `CreateBridgeResponse`, from the bridging client's
1934/// `bridge_to_cash_app`.
1935///
1936/// Response to a [`BridgeToCashAppRequest`].
1937#[derive(Debug, Clone, Serialize)]
1938#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1939pub struct BridgeToCashAppResponse {
1940    /// What the payer pays: an EIP-681 URI on EVM chains, otherwise the bare
1941    /// deposit address.
1942    pub payment_request: String,
1943    /// The deposit and the expected delivery. `expected_received_amount` is
1944    /// in sats.
1945    pub info: crate::cross_chain::CrossChainReceiveInfo,
1946}
1947
1948impl std::fmt::Display for MaxFee {
1949    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1950        match &self.onchain {
1951            MaxOnchainFee::Fixed { amount } => write!(f, "Fixed: {amount}")?,
1952            MaxOnchainFee::Rate { sat_per_vbyte } => write!(f, "Rate: {sat_per_vbyte}")?,
1953            MaxOnchainFee::NetworkRecommended {
1954                leeway_sat_per_vbyte,
1955            } => write!(f, "NetworkRecommended: {leeway_sat_per_vbyte}")?,
1956        }
1957        match self.proportional_ppm() {
1958            0 => Ok(()),
1959            ppm => write!(f, " + {ppm} ppm"),
1960        }
1961    }
1962}
1963
1964#[derive(Debug, Clone)]
1965#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1966pub struct Credentials {
1967    pub username: String,
1968    pub password: String,
1969}
1970
1971/// Request to get the balance of the wallet
1972#[derive(Debug, Clone)]
1973#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1974pub struct GetInfoRequest {
1975    /// When `Some(true)`, and `background_tasks_enabled` is `true`, the call
1976    /// waits for the initial Full sync to complete before returning. The sync
1977    /// can fail to reach the network: `last_sync_error` in the response says
1978    /// whether it did.
1979    ///
1980    /// When `background_tasks_enabled` is `false`, setting this to `Some(true)`
1981    /// is rejected with an invalid-input error. There is no background sync to
1982    /// wait on; call `sync_wallet` explicitly first if you need fresh state.
1983    pub ensure_synced: Option<bool>,
1984}
1985
1986/// Response containing the balance of the wallet
1987#[derive(Debug, Clone, Serialize)]
1988#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1989pub struct GetInfoResponse {
1990    /// The identity public key of the wallet as a hex string
1991    pub identity_pubkey: String,
1992    /// The balance in satoshis
1993    pub balance_sats: u64,
1994    /// The balances of the tokens in the wallet keyed by the token identifier
1995    pub token_balances: HashMap<String, TokenBalance>,
1996    /// Funds that left `balance_sats` and wait to be recovered on-chain with
1997    /// `recover_funds`. The SDK on this device takes them out of this total
1998    /// once it has seen their recovery in a block, at the next sync at the
1999    /// latest. It looks for that in `prepare_recover_funds`, `recover_funds`
2000    /// and `check_recover_funds`, and during syncs at most once per leaf. The
2001    /// total includes funds too small to be worth recovering at the fee rate
2002    /// you choose.
2003    pub recoverable_funds_sats: u64,
2004    /// Why the latest sync could not refresh the balances, which may then be
2005    /// out of date. Unset once a sync succeeds. It is not persisted, so it is
2006    /// also unset after each `connect` until the first sync ends.
2007    pub last_sync_error: Option<SyncError>,
2008    /// When a sync last refreshed the balances, in seconds since the Unix
2009    /// epoch. Unset until a sync succeeds with this storage.
2010    pub last_synced_at: Option<u64>,
2011}
2012
2013/// Why a sync could not refresh the balances. Each message is for logs, not
2014/// for display.
2015#[derive(Debug, Clone, PartialEq, Serialize)]
2016#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2017pub enum SyncError {
2018    /// The network could not be reached, or is temporarily too busy to answer.
2019    Network { message: String },
2020    /// Any other failure.
2021    Generic { message: String },
2022}
2023
2024#[derive(Debug, Clone, Serialize, Deserialize)]
2025#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2026pub struct TokenBalance {
2027    pub balance: u128,
2028    pub token_metadata: TokenMetadata,
2029}
2030
2031#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2032#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2033pub struct TokenMetadata {
2034    pub identifier: String,
2035    /// Hex representation of the issuer public key
2036    pub issuer_public_key: String,
2037    pub name: String,
2038    pub ticker: String,
2039    /// Number of decimals the token uses
2040    pub decimals: u32,
2041    pub max_supply: u128,
2042    pub is_freezable: bool,
2043    /// Arbitrary data the issuer attached when creating the token, such as an icon or a JSON
2044    /// description. Unset when the issuer attached none.
2045    pub extra_metadata: Option<Vec<u8>>,
2046}
2047
2048/// Metadata of the token a payment moved. The token's extra metadata is available from
2049/// `get_tokens_metadata`.
2050#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2051#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2052pub struct PaymentTokenMetadata {
2053    pub identifier: String,
2054    /// Hex representation of the issuer public key
2055    pub issuer_public_key: String,
2056    pub name: String,
2057    pub ticker: String,
2058    /// Number of decimals the token uses
2059    pub decimals: u32,
2060    pub max_supply: u128,
2061    pub is_freezable: bool,
2062}
2063
2064impl From<TokenMetadata> for PaymentTokenMetadata {
2065    fn from(value: TokenMetadata) -> Self {
2066        Self {
2067            identifier: value.identifier,
2068            issuer_public_key: value.issuer_public_key,
2069            name: value.name,
2070            ticker: value.ticker,
2071            decimals: value.decimals,
2072            max_supply: value.max_supply,
2073            is_freezable: value.is_freezable,
2074        }
2075    }
2076}
2077
2078/// Request to sync the wallet with the Spark network
2079#[derive(Debug, Clone)]
2080#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2081pub struct SyncWalletRequest {}
2082
2083/// Response from synchronizing the wallet
2084#[derive(Debug, Clone, Serialize)]
2085#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2086pub struct SyncWalletResponse {
2087    /// Why the sync could not refresh the balances, which may then be out of
2088    /// date. Unset when it succeeded.
2089    pub last_sync_error: Option<SyncError>,
2090    /// When a sync last refreshed the balances, in seconds since the Unix
2091    /// epoch. Unset until a sync succeeds with this storage.
2092    pub last_synced_at: Option<u64>,
2093}
2094
2095#[derive(Clone, Serialize)]
2096#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2097pub enum ReceivePaymentMethod {
2098    SparkAddress,
2099    SparkInvoice {
2100        /// Amount to receive. Denominated in sats if token identifier is empty, otherwise in the token base units
2101        amount: Option<u128>,
2102        /// The presence of this field indicates that the payment is for a token
2103        /// If empty, it is a Bitcoin payment
2104        token_identifier: Option<String>,
2105        /// The expiry time of the invoice as a unix timestamp in seconds
2106        expiry_time: Option<u64>,
2107        /// A description to embed in the invoice.
2108        description: Option<String>,
2109        /// If set, the invoice may only be fulfilled by a payer with this public key
2110        sender_public_key: Option<String>,
2111    },
2112    BitcoinAddress {
2113        /// If true, rotate to a new deposit address. Previous ones remain valid.
2114        /// If false or absent, return the existing address (creating one if none
2115        /// exists yet).
2116        new_address: Option<bool>,
2117    },
2118    Bolt11Invoice {
2119        description: String,
2120        amount_sats: Option<u64>,
2121        /// The expiry of the invoice as a duration in seconds
2122        expiry_secs: Option<u32>,
2123        /// If set, creates a HODL invoice with this payment hash (hex-encoded).
2124        /// The payer's HTLC will be held until the preimage is provided via
2125        /// `claim_htlc_payment` or the HTLC expires.
2126        payment_hash: Option<String>,
2127        /// Spark identity public key that will receive the payment.
2128        /// If absent, the connected wallet's identity public key is used.
2129        receiver_identity_public_key: Option<String>,
2130        /// If set, creates an invoice for the hash of this preimage (hex-encoded)
2131        /// instead of one the SDK generates. The SSP settles the payment without
2132        /// the receiver, and the payer learns the preimage. Use a random value
2133        /// below the secp256k1 group order, and a new one for each invoice. The
2134        /// invoice never includes a Spark address. Set at most one of this and
2135        /// `payment_hash`.
2136        preimage: Option<String>,
2137    },
2138    CrossChain {
2139        /// The selected cross-chain route in the receive direction.
2140        route: crate::cross_chain::CrossChainRoutePair,
2141        /// The amount, in the source asset's base units (`route.decimals`).
2142        /// USD-stable sources are at parity, so `1 USD = 10^route.decimals`
2143        /// (e.g. `1_000_000` for 6-decimal USDC/USDT, `10^18` for 18-decimal
2144        /// BSC USDC).
2145        ///
2146        /// - `FeesExcluded` (default): what the receiver ends up with, sized
2147        ///   as if `amount` source units were converted to the Spark-side
2148        ///   destination at parity (USDB) or the live BTC/USD rate (Bitcoin).
2149        /// - `FeesIncluded`: what the sender deposits. The receiver ends up
2150        ///   with that amount minus provider fees.
2151        amount: u128,
2152        /// Spark-side asset the receiver wants delivered. When absent, the
2153        /// SDK auto-selects: the wallet's active stable-balance token if
2154        /// the route supports it, otherwise Bitcoin (sats). When set, the
2155        /// value must appear in the route's `accepted_assets`.
2156        destination: Option<crate::cross_chain::SparkAsset>,
2157        /// How `amount` should be interpreted. When absent, defaults to
2158        /// `FeesExcluded`.
2159        fee_mode: Option<crate::cross_chain::CrossChainFeeMode>,
2160        /// Maximum slippage in basis points. When absent, the SDK default
2161        /// (100 bps) is used.
2162        max_slippage_bps: Option<u32>,
2163        /// Per-request override for the overpay buffer applied to the
2164        /// sender's deposit when `fee_mode == FeesExcluded`. Range 0 to 500.
2165        /// When absent, falls back to `CrossChainConfig::default_target_overpay_bps`
2166        /// then the built-in default (15 bps). Ignored when `fee_mode`
2167        /// is `FeesIncluded`.
2168        target_overpay_bps: Option<u32>,
2169        /// The payer's address on the route's chain, where the provider returns
2170        /// a deposit it can't deliver. Required when the payer sends from an
2171        /// exchange, and advised for BSC and Tron: unset, the provider refunds
2172        /// the sending address only when that is safe, and otherwise holds the
2173        /// deposit for manual recovery. Must not be a token contract.
2174        refund_address: Option<String>,
2175    },
2176}
2177
2178impl fmt::Debug for ReceivePaymentMethod {
2179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2180        match self {
2181            ReceivePaymentMethod::SparkAddress => f.write_str("SparkAddress"),
2182            ReceivePaymentMethod::SparkInvoice {
2183                amount,
2184                token_identifier,
2185                expiry_time,
2186                description,
2187                sender_public_key,
2188            } => f
2189                .debug_struct("SparkInvoice")
2190                .field("amount", amount)
2191                .field("token_identifier", token_identifier)
2192                .field("expiry_time", expiry_time)
2193                .field("description", description)
2194                .field("sender_public_key", sender_public_key)
2195                .finish(),
2196            ReceivePaymentMethod::BitcoinAddress { new_address } => f
2197                .debug_struct("BitcoinAddress")
2198                .field("new_address", new_address)
2199                .finish(),
2200            ReceivePaymentMethod::Bolt11Invoice {
2201                description,
2202                amount_sats,
2203                expiry_secs,
2204                payment_hash,
2205                receiver_identity_public_key,
2206                preimage,
2207            } => f
2208                .debug_struct("Bolt11Invoice")
2209                .field("description", description)
2210                .field("amount_sats", amount_sats)
2211                .field("expiry_secs", expiry_secs)
2212                .field("payment_hash", payment_hash)
2213                .field("receiver_identity_public_key", receiver_identity_public_key)
2214                .field("preimage", &preimage.as_ref().map(|_| "<redacted>"))
2215                .finish(),
2216            ReceivePaymentMethod::CrossChain {
2217                route,
2218                amount,
2219                destination,
2220                fee_mode,
2221                max_slippage_bps,
2222                target_overpay_bps,
2223                refund_address,
2224            } => f
2225                .debug_struct("CrossChain")
2226                .field("route", route)
2227                .field("amount", amount)
2228                .field("destination", destination)
2229                .field("fee_mode", fee_mode)
2230                .field("max_slippage_bps", max_slippage_bps)
2231                .field("target_overpay_bps", target_overpay_bps)
2232                .field("refund_address", refund_address)
2233                .finish(),
2234        }
2235    }
2236}
2237
2238#[derive(Debug, Clone, Serialize)]
2239#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2240pub enum SendPaymentMethod {
2241    BitcoinAddress {
2242        address: BitcoinAddressDetails,
2243        fee_quote: SendOnchainFeeQuote,
2244    },
2245    Bolt11Invoice {
2246        invoice_details: Bolt11InvoiceDetails,
2247        spark_transfer_fee_sats: Option<u64>,
2248        lightning_fee_sats: u64,
2249    }, // should be replaced with the parsed invoice
2250    SparkAddress {
2251        address: String,
2252        /// Fee to pay for the transaction
2253        /// Denominated in sats if token identifier is empty, otherwise in the token base units
2254        fee: u128,
2255        /// The presence of this field indicates that the payment is for a token
2256        /// If empty, it is a Bitcoin payment
2257        token_identifier: Option<String>,
2258    },
2259    SparkInvoice {
2260        spark_invoice_details: SparkInvoiceDetails,
2261        /// Fee to pay for the transaction
2262        /// Denominated in sats if token identifier is empty, otherwise in the token base units
2263        fee: u128,
2264        /// The presence of this field indicates that the payment is for a token
2265        /// If empty, it is a Bitcoin payment
2266        token_identifier: Option<String>,
2267    },
2268    /// A cross-chain send via a bridge/swap provider.
2269    CrossChainAddress {
2270        /// The route selected for this cross-chain send (includes provider, chain, asset).
2271        route: CrossChainRoutePair,
2272        /// Raw destination address (e.g. `0xabc...`).
2273        recipient_address: String,
2274        /// Amount routed to the provider, in the route's source-asset units
2275        /// (Boltz invoice sats; Orchestra deposit sats/token). On the
2276        /// token-conversion path (both `FeesIncluded` and `FeesExcluded`)
2277        /// the dispatcher overrides this with the wallet-side token debit
2278        /// when the source token and destination asset form a USD-stable pair.
2279        amount_in: u128,
2280        /// `amount_in` expressed in the cross-chain (destination) asset's
2281        /// base units, via the same rate the SDK used at prepare time.
2282        asset_amount_in: u128,
2283        /// Estimated recipient amount in cross-chain asset base units.
2284        estimated_out: u128,
2285        /// Prepare-time total user-visible fee in cross-chain asset base units.
2286        /// Covers provider spread + bridge/gas + DEX slippage. On the
2287        /// token-conversion path it also rolls in the LN routing budget; on
2288        /// the direct path that budget lives separately in
2289        /// `source_transfer_fee_sats`.
2290        fee_amount: u128,
2291        /// Provider service fee, including the partner fee when one is set, in
2292        /// `service_fee_asset` base units.
2293        service_fee_amount: u128,
2294        /// Asset which service fee is denominated in. Unset means BTC sats.
2295        service_fee_asset: Option<String>,
2296        /// Decimals of `service_fee_asset`, for formatting `service_fee_amount`.
2297        /// Unset when the fee is in sats or the provider did not report them.
2298        service_fee_asset_decimals: Option<u32>,
2299        /// Sats budget for moving the amount in from the wallet to the provider.
2300        source_transfer_fee_sats: u64,
2301        /// Fee mode the prepare ran under; the send stage matches.
2302        fee_mode: CrossChainFeeMode,
2303        /// ISO8601 timestamp after which the quote is no longer valid.
2304        expires_at: String,
2305        /// Provider-internal state, produced when preparing and consumed
2306        /// when sending.
2307        provider_context: CrossChainProviderContext,
2308    },
2309}
2310
2311#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2312#[derive(Debug, Clone, Serialize, Deserialize)]
2313pub struct SendOnchainFeeQuote {
2314    /// Identifies the quote to the provider when the payment is sent. Empty on
2315    /// an estimate, which no provider has issued.
2316    pub id: String,
2317    /// When the quote stops being honoured, as a Unix timestamp in seconds.
2318    /// Zero on an estimate.
2319    pub expires_at: u64,
2320    pub speed_fast: SendOnchainSpeedFeeQuote,
2321    pub speed_medium: SendOnchainSpeedFeeQuote,
2322    pub speed_slow: SendOnchainSpeedFeeQuote,
2323    /// Set when the wallet holds no bitcoin and a token conversion will fund the
2324    /// send, because the provider will not quote without funds to price against.
2325    /// The estimate is an upper bound: the payment quotes for real once the
2326    /// conversion lands, and fails rather than spending more than this.
2327    pub is_estimate: bool,
2328}
2329
2330#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2331#[derive(Debug, Clone, Serialize, Deserialize)]
2332pub struct SendOnchainSpeedFeeQuote {
2333    pub user_fee_sat: u64,
2334    pub l1_broadcast_fee_sat: u64,
2335}
2336
2337impl SendOnchainSpeedFeeQuote {
2338    pub fn total_fee_sat(&self) -> u64 {
2339        self.user_fee_sat.saturating_add(self.l1_broadcast_fee_sat)
2340    }
2341}
2342
2343#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2344pub struct ReceivePaymentRequest {
2345    pub payment_method: ReceivePaymentMethod,
2346}
2347
2348#[derive(Debug, Clone, Serialize)]
2349#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2350pub struct ReceivePaymentResponse {
2351    pub payment_request: String,
2352    /// Fee to pay to receive the payment
2353    /// Denominated in sats or token base units
2354    pub fee: u128,
2355    /// Optional information populated only for cross-chain receives.
2356    pub cross_chain_info: Option<crate::cross_chain::CrossChainReceiveInfo>,
2357}
2358
2359#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2360pub struct PrepareLnurlPayRequest {
2361    /// The amount to send. Denominated in satoshis, or in token base units
2362    /// when `token_identifier` is set.
2363    pub amount: u128,
2364    pub pay_request: LnurlPayRequestDetails,
2365    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2366    pub comment: Option<String>,
2367    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2368    pub validate_success_action_url: Option<bool>,
2369    /// The token identifier when sending a token amount with conversion.
2370    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2371    pub token_identifier: Option<String>,
2372    /// If provided, the payment will include a token conversion step before sending the payment
2373    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2374    pub conversion_options: Option<ConversionOptions>,
2375    /// How fees are handled. See [`FeePolicy`]. Defaults to `FeesExcluded`.
2376    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2377    pub fee_policy: Option<FeePolicy>,
2378}
2379
2380#[derive(Debug, Clone)]
2381#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2382pub struct PrepareLnurlPayResponse {
2383    /// The amount for the payment, always denominated in sats, even when a
2384    /// `token_identifier` and conversion are present.
2385    /// When a conversion is present, the token input amount is available in
2386    /// `conversion_estimate.amount_in`.
2387    pub amount_sats: u64,
2388    pub comment: Option<String>,
2389    pub pay_request: LnurlPayRequestDetails,
2390    /// The fee in satoshis. For `FeesIncluded` operations, this represents the total fee
2391    /// (including potential overpayment).
2392    pub fee_sats: u64,
2393    pub invoice_details: Bolt11InvoiceDetails,
2394    pub success_action: Option<SuccessAction>,
2395    /// When set, the payment will include a token conversion step before sending the payment
2396    pub conversion_estimate: Option<ConversionEstimate>,
2397    /// The fee policy actually applied. May differ from the request — e.g.,
2398    /// LNURL sends with `token_identifier` set + conversion are always
2399    /// `FeesIncluded` (explicit `FeesExcluded` is rejected).
2400    pub fee_policy: FeePolicy,
2401}
2402
2403#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2404pub struct LnurlPayRequest {
2405    pub prepare_response: PrepareLnurlPayResponse,
2406    /// If set, providing the same idempotency key for multiple requests will ensure that only one
2407    /// payment is made. If an idempotency key is re-used, the same payment will be returned.
2408    /// The idempotency key must be a valid UUID. The payment's id is the idempotency key.
2409    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2410    pub idempotency_key: Option<String>,
2411}
2412
2413#[derive(Debug, Serialize)]
2414#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2415pub struct LnurlPayResponse {
2416    pub payment: Payment,
2417    pub success_action: Option<SuccessActionProcessed>,
2418}
2419
2420#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2421pub struct BuildUnsignedLnurlPayPackageRequest {
2422    pub prepare_response: PrepareLnurlPayResponse,
2423}
2424
2425#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2426pub struct PublishSignedLnurlPayPackageRequest {
2427    pub signed_package: SignedTransferPackage,
2428}
2429
2430#[allow(clippy::large_enum_variant)]
2431#[derive(Debug)]
2432#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2433pub enum PublishSignedLnurlPayResponse {
2434    SwapCompleted,
2435    PaymentSent { response: LnurlPayResponse },
2436}
2437
2438#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2439pub struct LnurlWithdrawRequest {
2440    /// The amount to withdraw in satoshis
2441    /// Must be within the min and max withdrawable limits
2442    pub amount_sats: u64,
2443    pub withdraw_request: LnurlWithdrawRequestDetails,
2444    /// If set, the function will return the payment if it is still pending after this
2445    /// number of seconds. If unset, the function will return immediately after
2446    /// initiating the LNURL withdraw.
2447    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2448    pub completion_timeout_secs: Option<u32>,
2449}
2450
2451#[derive(Debug, Serialize)]
2452#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2453pub struct LnurlWithdrawResponse {
2454    /// The Lightning invoice generated for the LNURL withdraw
2455    pub payment_request: String,
2456    pub payment: Option<Payment>,
2457}
2458
2459/// Represents the payment LNURL info
2460#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
2461#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2462pub struct LnurlPayInfo {
2463    pub ln_address: Option<String>,
2464    pub comment: Option<String>,
2465    pub domain: Option<String>,
2466    pub metadata: Option<String>,
2467    pub processed_success_action: Option<SuccessActionProcessed>,
2468    pub raw_success_action: Option<SuccessAction>,
2469}
2470
2471/// Represents the withdraw LNURL info
2472#[derive(Clone, Debug, Deserialize, Serialize)]
2473#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2474pub struct LnurlWithdrawInfo {
2475    pub withdraw_url: String,
2476}
2477
2478impl LnurlPayInfo {
2479    pub fn extract_description(&self) -> Option<String> {
2480        let Some(metadata) = &self.metadata else {
2481            return None;
2482        };
2483
2484        let Ok(metadata) = serde_json::from_str::<Vec<Vec<Value>>>(metadata) else {
2485            return None;
2486        };
2487
2488        for arr in metadata {
2489            if arr.len() != 2 {
2490                continue;
2491            }
2492            if let (Some(key), Some(value)) = (arr[0].as_str(), arr[1].as_str())
2493                && key == "text/plain"
2494            {
2495                return Some(value.to_string());
2496            }
2497        }
2498
2499        None
2500    }
2501}
2502
2503/// Specifies how fees are handled in a payment.
2504///
2505/// "Fees" are the wallet's sender-paid fees (Lightning routing, on-chain,
2506/// Spark transfer). They do not include provider spreads or destination-chain
2507/// costs on cross-chain routes; those are reported separately via
2508/// `estimated_out` on the prepare response and are not deterministic.
2509/// `FeePolicy` only controls the wallet's spend accounting.
2510#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2511#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2512pub enum FeePolicy {
2513    /// Fees are added on top of `amount`. Wallet's total spend is
2514    /// `amount + fees`. For direct sat sends, the recipient receives exactly
2515    /// `amount`. Default.
2516    #[default]
2517    FeesExcluded,
2518    /// Fees are deducted from `amount`. Wallet's total spend is `amount`.
2519    /// Use this to drain a balance — pass `amount = balance` and the wallet
2520    /// spends exactly that.
2521    FeesIncluded,
2522}
2523
2524#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2525#[derive(Debug, Clone, Serialize, Deserialize)]
2526pub enum OnchainConfirmationSpeed {
2527    Fast,
2528    Medium,
2529    Slow,
2530}
2531
2532/// The payment destination. Either a raw string (bolt11, spark address, BIP-21,
2533/// cross-chain URI, etc.) that is parsed internally, or a structured
2534/// cross-chain destination with explicit chain + asset selection.
2535#[derive(Debug, Clone, Serialize)]
2536#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2537pub enum PaymentRequest {
2538    /// Unparsed user input string (bolt11, spark address, BIP-21, cross-chain URI, etc.)
2539    Input { input: String },
2540    /// Cross-chain send with a selected route from `get_cross_chain_routes()`.
2541    /// Amount comes from `PrepareSendPaymentRequest.amount`, not here.
2542    CrossChain {
2543        address: String,
2544        route: CrossChainRoutePair,
2545        /// Maximum slippage tolerance in basis points (1/100 of a percent)
2546        /// for the cross-chain quote. Must be in 10 to 500. Falls back to
2547        /// [`Config::default_slippage_bps`] when unset, which itself
2548        /// defaults to 100 bps (1%).
2549        max_slippage_bps: Option<u32>,
2550        /// Target-overpay pad in basis points applied on `FeesExcluded`
2551        /// conversion sends. Inflates the destination target before quoting
2552        /// so the recipient lands at or above the user's requested amount
2553        /// despite provider slippage. Must be in 0 to 500. Falls back to
2554        /// [`CrossChainConfig::default_target_overpay_bps`] when unset,
2555        /// which itself defaults to 15 bps.
2556        target_overpay_bps: Option<u32>,
2557    },
2558}
2559
2560#[allow(clippy::large_enum_variant)]
2561#[derive(Debug, Clone, Serialize, Deserialize)]
2562#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2563pub enum UnsignedTransferPackage {
2564    Swap {
2565        prepare_transfer: crate::signer::ExternalPrepareTransferRequest,
2566        target_amounts: Vec<u64>,
2567        amount_sat: u64,
2568        fee_sat: u64,
2569    },
2570    Transfer {
2571        prepare_transfer: crate::signer::ExternalPrepareTransferRequest,
2572        amount_sat: u64,
2573        fee_sat: u64,
2574        target: TransferTarget,
2575    },
2576    Token {
2577        prepare_token_transaction: crate::signer::ExternalPrepareTokenTransactionRequest,
2578        token_context: Vec<u8>,
2579        token_identifier: String,
2580        amount: u128,
2581        fee: u128,
2582        /// When set, this package re-shapes the wallet's token outputs instead of
2583        /// sending a payment. Publishing it returns `SwapCompleted`: rebuild the
2584        /// original send from the same prepare response and submit again.
2585        is_swap: bool,
2586    },
2587    /// One token transaction paying several recipients. Publishing it returns
2588    /// `PaymentsSent` with one payment per recipient.
2589    TokenBatch {
2590        prepare_token_transaction: crate::signer::ExternalPrepareTokenTransactionRequest,
2591        token_context: Vec<u8>,
2592        /// What the batch debits, per token. A batch spanning tokens has no
2593        /// single amount to report.
2594        totals: Vec<BatchTotal>,
2595        /// When set, this package re-shapes the wallet's token outputs instead of
2596        /// sending a payment. Publishing it returns `SwapCompleted`: rebuild the
2597        /// original send from the same prepare response and submit again.
2598        is_swap: bool,
2599    },
2600    /// A pull from a token allowance, signed through its `prepare_token_transaction` like a Token package.
2601    TokenPull {
2602        prepare_token_transaction: crate::signer::ExternalPrepareTokenTransactionRequest,
2603        pull_context: Vec<u8>,
2604        payer_address: String,
2605        token_identifier: String,
2606        receivers: Vec<PullReceiver>,
2607        amount: u128,
2608        /// When the pull stops being publishable, in Unix seconds.
2609        expiry_time: u64,
2610    },
2611}
2612
2613#[derive(Debug, Clone, Serialize, Deserialize)]
2614#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2615pub enum TransferTarget {
2616    Spark {
2617        address: String,
2618        spark_invoice: Option<String>,
2619    },
2620    Lightning {
2621        bolt11: String,
2622        lnurl_pay: Option<LnurlPayContext>,
2623        fee_policy: FeePolicy,
2624        completion_timeout_secs: Option<u32>,
2625    },
2626    CoopExit {
2627        address: String,
2628        fee_quote: SendOnchainFeeQuote,
2629        confirmation_speed: OnchainConfirmationSpeed,
2630    },
2631}
2632
2633#[derive(Debug, Clone, Serialize, Deserialize)]
2634#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2635pub struct LnurlPayContext {
2636    pub pay_request: LnurlPayRequestDetails,
2637    pub comment: Option<String>,
2638    pub success_action: Option<SuccessAction>,
2639}
2640
2641#[derive(Debug, Clone, Serialize, Deserialize)]
2642#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2643pub struct SignedTransferPackage {
2644    pub unsigned: UnsignedTransferPackage,
2645    pub signature: TransferSignature,
2646}
2647
2648#[derive(Debug, Clone, Serialize, Deserialize)]
2649#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2650pub enum TransferSignature {
2651    Transfer {
2652        signed: crate::signer::ExternalPreparedTransfer,
2653    },
2654    Token {
2655        signed: crate::signer::ExternalPreparedTokenTransaction,
2656    },
2657}
2658
2659#[derive(Debug, Clone)]
2660#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2661pub enum BuildTransferPackageOptions {
2662    BitcoinAddress {
2663        confirmation_speed: OnchainConfirmationSpeed,
2664    },
2665    Bolt11Invoice {
2666        prefer_spark: bool,
2667
2668        /// If set, publishing the package waits up to this many seconds for the
2669        /// payment to complete before returning it while still pending. If unset,
2670        /// publishing returns immediately after initiating the payment.
2671        completion_timeout_secs: Option<u32>,
2672    },
2673}
2674
2675#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2676pub struct BuildUnsignedTransferPackageRequest {
2677    pub prepare_response: PrepareSendPaymentResponse,
2678    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2679    pub options: Option<BuildTransferPackageOptions>,
2680}
2681
2682#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2683pub struct PrepareSendPaymentRequest {
2684    pub payment_request: PaymentRequest,
2685    /// The amount to send.
2686    /// Optional for payment requests with embedded amounts (e.g., Spark/Bolt11 invoices with amounts).
2687    /// Required for Spark addresses, Bitcoin addresses, and amountless invoices.
2688    /// Denominated in satoshis for Bitcoin payments, or token base units for token payments.
2689    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2690    pub amount: Option<u128>,
2691    /// Optional token identifier for token payments.
2692    /// Absence indicates that the payment is a Bitcoin payment.
2693    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2694    pub token_identifier: Option<String>,
2695    /// If provided, the payment will include a conversion step before sending the payment
2696    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2697    pub conversion_options: Option<ConversionOptions>,
2698    /// How fees are handled. See [`FeePolicy`]. Defaults to `FeesExcluded`.
2699    ///
2700    /// Ignored on cross-chain AMM-conversion sends (whether the conversion was
2701    /// explicitly requested or auto-injected by stable balance) — fees come
2702    /// out of the converted sats. Bolt11 and Bitcoin AMM-conversion sends
2703    /// still respect this field by sizing the conversion to cover fees. The
2704    /// prepare response's `fee_policy` reflects what was actually applied.
2705    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2706    pub fee_policy: Option<FeePolicy>,
2707}
2708
2709#[derive(Debug, Clone, Serialize)]
2710#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2711pub struct PrepareSendPaymentResponse {
2712    pub payment_method: SendPaymentMethod,
2713    /// The amount to be sent, denominated in satoshis for Bitcoin payments
2714    /// (including token-to-Bitcoin conversions), or token base units for token payments.
2715    /// When a conversion is present, the input amount is in
2716    /// `conversion_estimate.amount_in`.
2717    pub amount: u128,
2718    /// Optional token identifier for token payments.
2719    /// Absence indicates that the payment is a Bitcoin payment.
2720    pub token_identifier: Option<String>,
2721    /// When set, the payment will include a conversion step before sending the payment
2722    pub conversion_estimate: Option<ConversionEstimate>,
2723    /// The fee policy actually applied. May differ from the request — e.g.,
2724    /// cross-chain AMM-conversion sends are always `FeesIncluded`.
2725    pub fee_policy: FeePolicy,
2726}
2727
2728#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2729pub enum SendPaymentOptions {
2730    BitcoinAddress {
2731        /// Confirmation speed for the on-chain transaction.
2732        confirmation_speed: OnchainConfirmationSpeed,
2733    },
2734    Bolt11Invoice {
2735        prefer_spark: bool,
2736
2737        /// If set, the function will return the payment if it is still pending after this
2738        /// number of seconds. If unset, the function will return immediately after initiating the payment.
2739        completion_timeout_secs: Option<u32>,
2740    },
2741    SparkAddress {
2742        /// Can only be provided for Bitcoin payments. If set, a Spark HTLC transfer will be created.
2743        /// The receiver will need to provide the preimage to claim it.
2744        htlc_options: Option<SparkHtlcOptions>,
2745    },
2746}
2747
2748#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2749pub struct SparkHtlcOptions {
2750    /// The payment hash of the HTLC. The receiver will need to provide the associated preimage to claim it.
2751    pub payment_hash: String,
2752    /// The duration of the HTLC in seconds.
2753    /// After this time, the HTLC will be returned.
2754    pub expiry_duration_secs: u64,
2755}
2756
2757#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2758pub struct SendPaymentRequest {
2759    pub prepare_response: PrepareSendPaymentResponse,
2760    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2761    pub options: Option<SendPaymentOptions>,
2762    /// The optional idempotency key for all Spark based transfers (excludes token payments
2763    /// and cross-chain sends).
2764    /// If set, providing the same idempotency key for multiple requests will ensure that only one
2765    /// payment is made. If an idempotency key is re-used, the same payment will be returned.
2766    /// The idempotency key must be a valid UUID. The payment's id is the idempotency key.
2767    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2768    pub idempotency_key: Option<String>,
2769}
2770
2771/// A single payee in a batch send.
2772#[derive(Debug, Clone)]
2773#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2774pub struct BatchRecipient {
2775    /// Spark address or Spark invoice identifying the payee.
2776    pub payment_request: String,
2777    /// Amount to send, in the base units of the asset being sent. Required
2778    /// unless `payment_request` is an invoice that carries its own amount.
2779    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2780    pub amount: Option<u128>,
2781    /// Token to send. Unset means sats, which a batch cannot send yet, so a
2782    /// plain address needs this set. An invoice that names a token does not.
2783    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2784    pub token_identifier: Option<String>,
2785}
2786
2787#[derive(Debug, Clone)]
2788#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2789pub struct PrepareSendBatchRequest {
2790    /// The payees, all paid by one transaction. They may span several tokens,
2791    /// and may mix Spark addresses with Spark invoices. Once a Spark invoice is
2792    /// among them, every recipient must be paid in the same token.
2793    pub recipients: Vec<BatchRecipient>,
2794}
2795
2796/// Where a batch recipient is paid, once prepare has decoded its payment request.
2797#[derive(Debug, Clone, Serialize, Deserialize)]
2798#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2799pub enum BatchDestination {
2800    SparkAddress {
2801        address: String,
2802    },
2803    SparkInvoice {
2804        invoice_details: SparkInvoiceDetails,
2805    },
2806}
2807
2808/// A recipient after prepare has resolved the asset and amount it is owed.
2809#[derive(Debug, Clone, Serialize, Deserialize)]
2810#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2811pub struct ResolvedBatchRecipient {
2812    pub destination: BatchDestination,
2813    /// Amount in the base units of the asset this recipient is paid in.
2814    pub amount: u128,
2815    /// The token this recipient is paid in. Unset means sats, which a batch
2816    /// cannot send yet.
2817    pub token_identifier: Option<String>,
2818}
2819
2820/// What a batch debits for one asset.
2821#[derive(Debug, Clone, Serialize, Deserialize)]
2822#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2823pub struct BatchTotal {
2824    /// The token debited. Unset means sats, which a batch cannot send yet.
2825    pub token_identifier: Option<String>,
2826    /// Amount in the asset's base units.
2827    pub amount: u128,
2828}
2829
2830#[derive(Debug, Clone, Serialize, Deserialize)]
2831#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2832pub struct PrepareSendBatchResponse {
2833    /// The payees in the order they were requested, which is the order their
2834    /// payments come back in.
2835    pub recipients: Vec<ResolvedBatchRecipient>,
2836    /// What the batch debits, one entry per distinct asset.
2837    pub totals: Vec<BatchTotal>,
2838}
2839
2840#[derive(Debug, Clone)]
2841#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2842pub struct SendBatchRequest {
2843    pub prepare_response: PrepareSendBatchResponse,
2844}
2845
2846#[derive(Debug, Clone)]
2847#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2848pub struct SendBatchResponse {
2849    /// One payment per recipient, in recipient order, all sharing a transaction
2850    /// hash.
2851    pub payments: Vec<Payment>,
2852}
2853
2854#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2855pub struct BuildUnsignedBatchPackageRequest {
2856    pub prepare_response: PrepareSendBatchResponse,
2857}
2858
2859#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2860pub struct PublishSignedTransferPackageRequest {
2861    pub signed_package: SignedTransferPackage,
2862}
2863
2864#[allow(clippy::large_enum_variant)]
2865#[derive(Debug, Clone)]
2866#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2867pub enum PublishSignedTransferPackageResponse {
2868    SwapCompleted,
2869    PaymentSent {
2870        payment: Payment,
2871    },
2872    /// Returned for a batch package: one payment per recipient, in recipient
2873    /// order.
2874    PaymentsSent {
2875        payments: Vec<Payment>,
2876    },
2877}
2878
2879#[derive(Debug, Clone, Serialize)]
2880#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2881pub struct SendPaymentResponse {
2882    pub payment: Payment,
2883}
2884
2885#[derive(Debug, Clone)]
2886#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2887pub enum PaymentDetailsFilter {
2888    Spark {
2889        /// Filter specific Spark HTLC statuses
2890        htlc_status: Option<Vec<SparkHtlcStatus>>,
2891        /// Filter conversion payments with refund information
2892        conversion_refund_needed: Option<bool>,
2893    },
2894    Token {
2895        /// Filter conversion payments with refund information
2896        conversion_refund_needed: Option<bool>,
2897        /// Filter by transaction hash
2898        tx_hash: Option<String>,
2899        /// Filter by transaction type
2900        tx_type: Option<TokenTransactionType>,
2901    },
2902    Lightning {
2903        /// Filter specific Spark HTLC statuses
2904        htlc_status: Option<Vec<SparkHtlcStatus>>,
2905    },
2906}
2907
2908/// Request to list payments with optional filters and pagination
2909#[derive(Debug, Clone, Default)]
2910#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2911pub struct ListPaymentsRequest {
2912    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2913    pub type_filter: Option<Vec<PaymentType>>,
2914    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2915    pub status_filter: Option<Vec<PaymentStatus>>,
2916    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2917    pub asset_filter: Option<AssetFilter>,
2918    /// Only include payments matching at least one of these payment details filters
2919    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2920    pub payment_details_filter: Option<Vec<PaymentDetailsFilter>>,
2921    /// Only include payments created after this timestamp (inclusive)
2922    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2923    pub from_timestamp: Option<u64>,
2924    /// Only include payments created before this timestamp (exclusive)
2925    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2926    pub to_timestamp: Option<u64>,
2927    /// Number of records to skip
2928    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2929    pub offset: Option<u32>,
2930    /// Maximum number of records to return
2931    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2932    pub limit: Option<u32>,
2933    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
2934    pub sort_ascending: Option<bool>,
2935}
2936
2937/// A field of [`ListPaymentsRequest`] when listing payments filtered by asset
2938#[derive(Debug, Clone)]
2939#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2940pub enum AssetFilter {
2941    Bitcoin,
2942    Token {
2943        /// Optional token identifier to filter by
2944        token_identifier: Option<String>,
2945    },
2946}
2947
2948impl FromStr for AssetFilter {
2949    type Err = String;
2950
2951    fn from_str(s: &str) -> Result<Self, Self::Err> {
2952        Ok(match s.to_lowercase().as_str() {
2953            "bitcoin" => AssetFilter::Bitcoin,
2954            "token" => AssetFilter::Token {
2955                token_identifier: None,
2956            },
2957            str if str.starts_with("token:") => AssetFilter::Token {
2958                token_identifier: Some(
2959                    str.split_once(':')
2960                        .ok_or(format!("Invalid asset filter '{s}'"))?
2961                        .1
2962                        .to_string(),
2963                ),
2964            },
2965            _ => return Err(format!("Invalid asset filter '{s}'")),
2966        })
2967    }
2968}
2969
2970/// Response from listing payments
2971#[derive(Debug, Clone, Serialize)]
2972#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2973pub struct ListPaymentsResponse {
2974    /// The list of payments
2975    pub payments: Vec<Payment>,
2976}
2977
2978#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2979pub struct GetPaymentRequest {
2980    pub payment_id: String,
2981}
2982
2983#[derive(Debug, Clone, Serialize)]
2984#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2985pub struct GetPaymentResponse {
2986    pub payment: Payment,
2987}
2988
2989#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2990pub struct FetchLightningSendStatusRequest {
2991    /// The Bolt11 invoice to look up
2992    pub invoice: String,
2993}
2994
2995#[derive(Clone, PartialEq, Serialize)]
2996#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2997pub struct FetchLightningSendStatusResponse {
2998    /// The status of this wallet's Lightning payments of the invoice: completed if one completed,
2999    /// pending if one is in flight, failed if every one was returned. Unset when there is none.
3000    /// A payment made by a direct Spark transfer to the invoice's Spark address is not found, so
3001    /// unset does not mean the invoice is unpaid.
3002    pub status: Option<PaymentStatus>,
3003    /// The hex-encoded preimage that proves the payment, set when the status is completed
3004    pub preimage: Option<String>,
3005}
3006
3007impl fmt::Debug for FetchLightningSendStatusResponse {
3008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3009        f.debug_struct("FetchLightningSendStatusResponse")
3010            .field("status", &self.status)
3011            .field("preimage", &self.preimage.as_ref().map(|_| "<redacted>"))
3012            .finish()
3013    }
3014}
3015
3016#[cfg_attr(feature = "uniffi", uniffi::export(callback_interface))]
3017pub trait Logger: Send + Sync {
3018    fn log(&self, l: LogEntry);
3019}
3020
3021#[derive(Debug, Clone, Serialize)]
3022#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3023pub struct LogEntry {
3024    pub line: String,
3025    pub level: String,
3026    /// Identity public key of the SDK instance that emitted the line, telling
3027    /// apart the logs of several instances in one process. Unset for lines not
3028    /// emitted by an instance.
3029    pub instance_id: Option<String>,
3030}
3031
3032#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3033#[derive(Debug, Clone, Serialize, Deserialize)]
3034pub struct CheckLightningAddressRequest {
3035    pub username: String,
3036}
3037
3038#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3039#[derive(Debug, Clone, Serialize, Deserialize)]
3040pub struct RegisterLightningAddressRequest {
3041    pub username: String,
3042    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
3043    pub description: Option<String>,
3044}
3045
3046/// Authorization from the current owner granting a specific new owner the
3047/// right to take over a username. Produced by
3048/// [`BreezSdk::authorize_lightning_address_transfer`] and handed to the new
3049/// owner, who passes it to [`BreezSdk::claim_lightning_address_transfer`]. It
3050/// fully describes the transfer, so the new owner needs nothing else to claim.
3051#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3052#[derive(Debug, Clone, Serialize, Deserialize)]
3053pub struct TransferAuthorization {
3054    /// The username being handed over.
3055    pub username: String,
3056    /// The current owner's public key.
3057    pub pubkey: String,
3058    /// The current owner's signature authorizing the transfer.
3059    pub signature: String,
3060    /// The lightning-address domain the authorization is for, taken from the
3061    /// address being handed over. The signed message names this domain, so an
3062    /// authorization made for one server does not verify at another.
3063    pub domain: String,
3064    /// When the authorization was produced, in seconds since the Unix epoch.
3065    /// Covered by the signature, and valid for 10 minutes: the transferee has
3066    /// to claim within that window or the current owner authorizes again.
3067    pub timestamp: u64,
3068}
3069
3070/// Request for [`BreezSdk::authorize_lightning_address_transfer`]. Called by
3071/// the *current owner* to authorize handing their registered username over to
3072/// `transferee_pubkey`.
3073#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3074#[derive(Debug, Clone, Serialize, Deserialize)]
3075pub struct AuthorizeTransferRequest {
3076    /// The new owner's identity public key.
3077    pub transferee_pubkey: String,
3078}
3079
3080/// Request for [`BreezSdk::claim_lightning_address_transfer`]. Called by the
3081/// *new owner* to complete the takeover using the authorization produced by
3082/// the current owner.
3083#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3084#[derive(Debug, Clone, Serialize, Deserialize)]
3085pub struct ClaimTransferRequest {
3086    /// Authorization produced by the current owner via
3087    /// [`BreezSdk::authorize_lightning_address_transfer`].
3088    pub authorization: TransferAuthorization,
3089    /// Description for the address. Defaults to `"Pay to {username}@{domain}"`.
3090    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
3091    pub description: Option<String>,
3092}
3093
3094#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3095#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
3096pub struct LnurlInfo {
3097    pub url: String,
3098    pub bech32: String,
3099}
3100
3101impl LnurlInfo {
3102    pub fn new(url: String) -> Self {
3103        let bech32 =
3104            breez_sdk_common::lnurl::encode_lnurl_to_bech32(&url).unwrap_or_else(|_| url.clone());
3105        Self { url, bech32 }
3106    }
3107}
3108
3109#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3110#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
3111pub struct LightningAddressInfo {
3112    pub description: String,
3113    pub lightning_address: String,
3114    pub lnurl: LnurlInfo,
3115    pub username: String,
3116}
3117
3118impl From<RecoverLnurlPayResponse> for LightningAddressInfo {
3119    fn from(resp: RecoverLnurlPayResponse) -> Self {
3120        Self {
3121            description: resp.description,
3122            lightning_address: resp.lightning_address,
3123            lnurl: LnurlInfo::new(resp.lnurl),
3124            username: resp.username,
3125        }
3126    }
3127}
3128
3129/// Response from listing fiat currencies
3130#[derive(Debug, Clone, Serialize)]
3131#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3132pub struct ListFiatCurrenciesResponse {
3133    /// The list of fiat currencies
3134    pub currencies: Vec<FiatCurrency>,
3135}
3136
3137/// Response from listing fiat rates
3138#[derive(Debug, Clone, Serialize)]
3139#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3140pub struct ListFiatRatesResponse {
3141    /// The list of fiat rates
3142    pub rates: Vec<Rate>,
3143}
3144
3145/// The operational status of a Spark service.
3146#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3147#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3148pub enum ServiceStatus {
3149    /// Service is fully operational.
3150    Operational,
3151    /// Service is experiencing degraded performance.
3152    Degraded,
3153    /// Service is partially unavailable.
3154    Partial,
3155    /// Service status is unknown.
3156    Unknown,
3157    /// Service is experiencing a major outage.
3158    Major,
3159}
3160
3161/// The status of the Spark network services relevant to the SDK.
3162#[derive(Debug, Clone, Serialize)]
3163#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3164pub struct SparkStatus {
3165    /// The worst status across all relevant services.
3166    pub status: ServiceStatus,
3167    /// The last time the status was updated, as a unix timestamp in seconds.
3168    pub last_updated: u64,
3169}
3170
3171pub(crate) enum WaitForPaymentIdentifier {
3172    PaymentId(String),
3173    LightningReceive { invoice: String, ssp_id: String },
3174}
3175
3176#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3177pub struct GetTokensMetadataRequest {
3178    pub token_identifiers: Vec<String>,
3179}
3180
3181#[derive(Debug, Clone, Serialize)]
3182#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3183pub struct GetTokensMetadataResponse {
3184    pub tokens_metadata: Vec<TokenMetadata>,
3185}
3186
3187#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3188pub struct SignMessageRequest {
3189    pub message: String,
3190    /// If true, the signature will be encoded in compact format instead of DER format
3191    pub compact: bool,
3192}
3193
3194#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3195pub struct SignMessageResponse {
3196    pub pubkey: String,
3197    /// The DER or compact hex encoded signature
3198    pub signature: String,
3199}
3200
3201#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3202pub struct CheckMessageRequest {
3203    /// The message that was signed
3204    pub message: String,
3205    /// The public key that signed the message
3206    pub pubkey: String,
3207    /// The DER or compact hex encoded signature
3208    pub signature: String,
3209}
3210
3211#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3212pub struct CheckMessageResponse {
3213    pub is_valid: bool,
3214}
3215
3216#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3217#[derive(Debug, Clone, Serialize)]
3218pub struct UserSettings {
3219    pub spark_private_mode_enabled: bool,
3220
3221    /// The label of the currently active stable balance token, or `None` if deactivated.
3222    pub stable_balance_active_label: Option<String>,
3223
3224    /// The hex encoded public key designated as this wallet's master identity
3225    /// key, or `None` if none is designated.
3226    pub spark_master_identity_public_key: Option<String>,
3227}
3228
3229/// Specifies how to update the wallet's Spark master identity public key.
3230#[derive(Debug, Clone)]
3231#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3232pub enum SparkMasterIdentityPublicKey {
3233    /// Designate the holder of this public key as the wallet's master
3234    /// identity, replacing any previously designated key. Must be hex encoded
3235    /// in the 33-byte compressed form.
3236    Set { public_key: String },
3237    /// Remove the designated master identity, leaving the owner as the only
3238    /// party able to read the wallet under private mode.
3239    Unset,
3240}
3241
3242#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3243pub struct UpdateUserSettingsRequest {
3244    pub spark_private_mode_enabled: Option<bool>,
3245
3246    /// Update the active stable balance token. `None` means no change.
3247    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
3248    pub stable_balance_active_label: Option<StableBalanceActiveLabel>,
3249
3250    /// Designate or remove the wallet's master identity, a second public key
3251    /// the Spark operators accept as a reader of this wallet's balance and
3252    /// history while `spark_private_mode_enabled` is set. The master identity
3253    /// can only read: payments still require the owner's keys. `None` means no
3254    /// change.
3255    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
3256    pub spark_master_identity_public_key: Option<SparkMasterIdentityPublicKey>,
3257}
3258
3259#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3260pub struct ClaimHtlcPaymentRequest {
3261    pub preimage: String,
3262    /// The ID of the payment to claim. When set, the claim fails unless the claimable HTLC
3263    /// with the preimage's payment hash is this payment. A payment hash can be reused once
3264    /// an earlier HTLC locked to it was returned.
3265    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
3266    pub transfer_id: Option<String>,
3267}
3268
3269#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3270pub struct ClaimHtlcPaymentResponse {
3271    pub payment: Payment,
3272}
3273
3274#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3275pub struct FetchHtlcPaymentsRequest {
3276    /// The hex-encoded payment hash to look up
3277    pub payment_hash: String,
3278}
3279
3280/// A payment locked to a payment hash, as the Spark operators report it.
3281#[derive(Debug, Clone, Serialize)]
3282#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3283pub struct HtlcPayment {
3284    /// The payment ID, the same one the payment list uses
3285    pub id: String,
3286    pub payment_type: PaymentType,
3287    /// The amount the HTLC locks. For a Lightning send this includes the fee.
3288    pub amount_sats: u64,
3289    /// When the HTLC was created, as a unix timestamp in seconds
3290    pub timestamp: u64,
3291    pub htlc_details: SparkHtlcDetails,
3292}
3293
3294#[derive(Debug, Clone, Serialize)]
3295#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3296pub struct FetchHtlcPaymentsResponse {
3297    /// The payments this wallet sent or received that are locked to the payment hash, newest
3298    /// first. Claimed and returned ones are included.
3299    pub payments: Vec<HtlcPayment>,
3300}
3301
3302#[derive(Debug, Clone, Deserialize, Serialize)]
3303#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3304pub struct LnurlReceiveMetadata {
3305    pub nostr_zap_request: Option<String>,
3306    pub nostr_zap_receipt: Option<String>,
3307    pub sender_comment: Option<String>,
3308    /// The Lightning address the payment was received on. Unset for some payments received
3309    /// before the LNURL server recorded addresses.
3310    pub lightning_address: Option<String>,
3311}
3312
3313/// Mode of a manually-triggered optimization run.
3314#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
3315#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3316pub enum OptimizationMode {
3317    /// Run until no further optimization is productive.
3318    #[default]
3319    Full,
3320    /// Execute a single round and return so the caller can drive progress.
3321    SingleRound,
3322}
3323
3324/// Request for [`BreezSdk::optimize_leaves`]. Defaults to
3325/// [`OptimizationMode::Full`].
3326#[derive(Debug, Clone, Default, Deserialize, Serialize)]
3327#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3328pub struct OptimizeLeavesRequest {
3329    /// Controls how much work the call performs before returning.
3330    pub mode: OptimizationMode,
3331}
3332
3333/// Response from a [`BreezSdk::optimize_leaves`] call.
3334#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
3335#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3336pub struct OptimizeLeavesResponse {
3337    /// The outcome of the optimization run.
3338    pub outcome: OptimizationOutcome,
3339}
3340
3341/// Outcome of a [`BreezSdk::optimize_leaves`] call.
3342///
3343/// `rounds_executed` on `Completed` refers to rounds run by *this call*.
3344/// The SDK holds no cross-call state — callers driving a `SingleRound`
3345/// loop maintain their own cumulative counter if they need one.
3346///
3347/// A `Completed { rounds_executed: 0 }` outcome means the wallet was
3348/// already optimal at call time (no swap was needed).
3349///
3350/// **`SingleRound` loop pattern**: terminate on anything that isn't
3351/// `InProgress`. `Completed` covers both the final swap of a productive
3352/// run and the "already optimal" no-op case (the latter as
3353/// `rounds_executed: 0`).
3354///
3355/// ```ignore
3356/// loop {
3357///     let request = OptimizeLeavesRequest { mode: OptimizationMode::SingleRound };
3358///     match sdk.optimize_leaves(request).await?.outcome {
3359///         OptimizationOutcome::InProgress => continue,
3360///         OptimizationOutcome::Completed { .. } => break,
3361///     }
3362/// }
3363/// ```
3364#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
3365#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3366pub enum OptimizationOutcome {
3367    /// All planned optimization work was executed in this call.
3368    /// Returned by `Full` runs on success, and by `SingleRound` runs
3369    /// whose swap was the final one needed (the planner produced a
3370    /// single-swap plan with a convergence guarantee).
3371    /// `rounds_executed == 0` means the wallet was already optimal —
3372    /// no work was performed.
3373    Completed { rounds_executed: u32 },
3374    /// `SingleRound` only: a round ran but the planner could not
3375    /// guarantee it was the last. The caller should invoke
3376    /// `optimize_leaves` again.
3377    InProgress,
3378}
3379
3380/// A contact entry containing a name and payment identifier.
3381#[derive(Debug, Clone, Serialize, Deserialize)]
3382#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3383pub struct Contact {
3384    pub id: String,
3385    pub name: String,
3386    /// A Lightning address (user@domain).
3387    pub payment_identifier: String,
3388    pub created_at: u64,
3389    pub updated_at: u64,
3390}
3391
3392/// Request to add a new contact.
3393#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3394pub struct AddContactRequest {
3395    pub name: String,
3396    /// A Lightning address (user@domain).
3397    pub payment_identifier: String,
3398}
3399
3400/// Request to update an existing contact.
3401#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3402pub struct UpdateContactRequest {
3403    pub id: String,
3404    pub name: String,
3405    /// A Lightning address (user@domain).
3406    pub payment_identifier: String,
3407}
3408
3409/// Request to list contacts with optional pagination.
3410#[derive(Debug, Clone, Default)]
3411#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3412pub struct ListContactsRequest {
3413    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
3414    pub offset: Option<u32>,
3415    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
3416    pub limit: Option<u32>,
3417}
3418
3419/// The type of event that triggers a webhook notification.
3420#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3421#[allow(clippy::enum_variant_names)]
3422#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3423pub enum WebhookEventType {
3424    /// Triggered when a Lightning receive operation completes.
3425    LightningReceiveFinished,
3426    /// Triggered when a Lightning send operation completes.
3427    LightningSendFinished,
3428    /// Triggered when a cooperative exit completes.
3429    CoopExitFinished,
3430    /// Triggered when a static deposit completes.
3431    StaticDepositFinished,
3432    /// An event type not yet recognized by this version of the SDK.
3433    Unknown(String),
3434}
3435
3436/// A registered webhook entry.
3437#[derive(Debug, Clone, Serialize)]
3438#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3439pub struct Webhook {
3440    /// Unique identifier for this webhook.
3441    pub id: String,
3442    /// The URL that receives webhook notifications.
3443    pub url: String,
3444    /// The event types this webhook is subscribed to.
3445    pub event_types: Vec<WebhookEventType>,
3446}
3447
3448/// Request to register a new webhook.
3449#[derive(Debug, Clone)]
3450#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3451pub struct RegisterWebhookRequest {
3452    /// The URL that will receive webhook notifications.
3453    pub url: String,
3454    /// A secret used for HMAC-SHA256 signature verification of webhook payloads.
3455    pub secret: String,
3456    /// The event types to subscribe to.
3457    pub event_types: Vec<WebhookEventType>,
3458}
3459
3460/// Response from registering a webhook.
3461#[derive(Debug, Clone, Serialize)]
3462#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3463pub struct RegisterWebhookResponse {
3464    /// The unique identifier of the newly registered webhook.
3465    pub webhook_id: String,
3466}
3467
3468/// Request to unregister an existing webhook.
3469#[derive(Debug, Clone)]
3470#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3471pub struct UnregisterWebhookRequest {
3472    /// The unique identifier of the webhook to unregister.
3473    pub webhook_id: String,
3474}
3475
3476// ===========================================================================
3477// Unilateral exit
3478// ===========================================================================
3479
3480/// A funding UTXO that pays the on-chain fees of a unilateral exit.
3481#[derive(Debug, Clone, Serialize, Deserialize)]
3482#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3483pub enum CpfpInput {
3484    /// A P2WPKH (native segwit v0) UTXO controlled by `pubkey` (33-byte
3485    /// compressed, hex).
3486    P2wpkh {
3487        txid: String,
3488        vout: u32,
3489        value_sats: u64,
3490        pubkey: String,
3491    },
3492    /// A P2TR (taproot, key-path) UTXO. `pubkey` (x-only or compressed, hex) is
3493    /// the **internal** (untweaked, BIP86 key-path) public key whose secret signs
3494    /// the input, not the tweaked on-chain output key. The SDK applies the BIP86
3495    /// taproot tweak itself to derive the funding scriptPubKey, so passing the
3496    /// already-tweaked output key here produces a scriptPubKey that does not match
3497    /// the UTXO and the built transaction is rejected at broadcast.
3498    P2tr {
3499        txid: String,
3500        vout: u32,
3501        value_sats: u64,
3502        pubkey: String,
3503    },
3504    /// Any witness-program script, signed via a custom `CpfpSigner`. Legacy
3505    /// (non-SegWit) scripts are rejected. `signed_input_weight` (weight units)
3506    /// is an upper bound on the input's signed weight, so the fee stays exact,
3507    /// or slightly conservative if the real signature is shorter.
3508    Custom {
3509        txid: String,
3510        vout: u32,
3511        value_sats: u64,
3512        script_pubkey_hex: String,
3513        signed_input_weight: u64,
3514    },
3515}
3516
3517/// The kind of UTXO that will fund an exit's fees.
3518#[derive(Debug, Clone, Serialize, Deserialize)]
3519#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3520pub enum CpfpFundingKind {
3521    /// Fees paid from P2WPKH (native segwit v0) UTXOs.
3522    P2wpkh,
3523    /// Fees paid from P2TR (taproot, key-path) UTXOs.
3524    P2tr,
3525    /// Fees paid from a custom witness-program script (legacy scripts are
3526    /// rejected). `script_pubkey_hex` (the funding scriptPubKey) sizes the
3527    /// fan-out output and dust; `signed_input_weight` (weight units) is an upper
3528    /// bound on the input's signed weight, so the quote stays exact or slightly
3529    /// conservative.
3530    Custom {
3531        script_pubkey_hex: String,
3532        signed_input_weight: u64,
3533    },
3534}
3535
3536/// How funding UTXOs pay a unilateral exit's CPFP children.
3537#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3538#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3539pub enum CpfpFundingStrategy {
3540    /// One UTXO per branch. Each child after the first spends the change of the
3541    /// one before it, so a child's inputs depend on the fee rate of every child
3542    /// above it.
3543    #[default]
3544    PerBranch,
3545    /// One UTXO per fee-bumped transaction. No child spends another's output,
3546    /// so each can be signed at any fee rate without knowing the others. Each
3547    /// child's change stays on the funding script rather than being swept.
3548    PerNode,
3549}
3550
3551/// Which leaves to recover. `All` and `RecoverableOnly` take a leaf only when
3552/// what is left of its funds exceeds what recovering it costs. That cost leaves
3553/// out the shared fan-out fee, which you also pay when you fund several
3554/// `funding.per_branch` entries from one UTXO: compare `recoverable_value_sats`
3555/// with `total_fee_sats`, or fund one UTXO per entry to avoid the fan-out.
3556#[derive(Debug, Clone, Serialize, Deserialize)]
3557#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3558pub enum ExitLeafSelection {
3559    /// Every leaf, including the ones still in the balance. Only for when the
3560    /// operators are unreachable or refuse to serve the wallet. Its cooperative
3561    /// leaves still need the operators.
3562    All,
3563    /// The leaves that left the balance and whose recovery has not confirmed.
3564    RecoverableOnly,
3565    /// Exactly these leaves, whether or not they are worth it. A leaf whose
3566    /// recovery finished is left out, and so is a cooperative leaf too small to
3567    /// pay its fee, or one whose funds were not found.
3568    Specific { leaf_ids: Vec<String> },
3569}
3570
3571/// Where a transaction of a recovery stands: on-chain, ready to send, or
3572/// waiting for something.
3573#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3574#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3575pub enum ExitTransactionStatus {
3576    /// Confirmed in a block, at `block_height` where the chain service reported
3577    /// one. It needs no action.
3578    ///
3579    /// A relative `csv_timelock_blocks` counts from the height of the
3580    /// transaction it spends, so this is what tells you when a child of this one
3581    /// can go out, without fetching it again.
3582    Confirmed { block_height: Option<u32> },
3583    /// Not on-chain, and nothing is holding it back. Broadcast it, with its
3584    /// `cpfp_tx_hex` where it has one.
3585    Ready,
3586    /// A transaction in `depends_on` has yet to confirm. A relative timelock
3587    /// only starts counting once it does.
3588    WaitingForDependencies,
3589    /// Every input is confirmed, but a relative timelock has yet to mature.
3590    /// `spendable_at_height` is the first block that can include this
3591    /// transaction, and is unset when the height it counts from could not be
3592    /// read from the chain.
3593    WaitingForTimelock { spendable_at_height: Option<u32> },
3594    /// The on-chain status could not be determined (the chain service errored),
3595    /// which also leaves what it is waiting for unknown. A cooperative recovery
3596    /// has this status when the SDK did not see the output it spends in a
3597    /// block, or could not check whether an earlier recovery spent that
3598    /// output. Broadcasting may fail if a conflicting transaction already
3599    /// landed.
3600    Unverified,
3601}
3602
3603/// How much one funding UTXO must hold to avoid a fan-out: for a branch of the
3604/// exit, or under `CpfpFundingStrategy::PerNode` for one transaction of it.
3605#[derive(Debug, Clone, Serialize, Deserialize)]
3606#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3607pub struct PerBranchFunding {
3608    /// The leaf whose branch this funds.
3609    pub leaf_id: String,
3610    /// Fund a UTXO of at least this many satoshis.
3611    pub funding_sats: u64,
3612}
3613
3614/// What the chain has already done to an exit's leaves, as
3615/// `prepare_recover_funds` found it. `recover_funds` builds only the steps it
3616/// does not cover.
3617#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3618#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3619pub struct ExitChainState {
3620    /// Nodes whose transaction is on-chain.
3621    pub confirmed_nodes: Vec<ConfirmedExitNode>,
3622    /// Leaves whose refund reached the chain.
3623    pub refunds: Vec<ExitRefund>,
3624    /// Leaves whose lineage was taken on-chain by a transaction the exit cannot
3625    /// continue from. Nothing further can be driven for them.
3626    pub stopped_leaf_ids: Vec<String>,
3627    /// Nodes a chain lookup could not read, so their state is unknown rather
3628    /// than absent. Transactions depending on them come back
3629    /// `ExitTransactionStatus::Unverified`.
3630    pub unverified_node_ids: Vec<String>,
3631    /// Nodes taken to be on-chain on the operators' word, the chain itself being
3632    /// unreadable. Their spend is invisible, so anything built over them risks
3633    /// double-spending an output that is already gone.
3634    pub unverifiable_confirmed_node_ids: Vec<String>,
3635}
3636
3637/// A node of the exit tree that is already on-chain.
3638#[derive(Debug, Clone, Serialize, Deserialize)]
3639#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3640pub struct ConfirmedExitNode {
3641    pub node_id: String,
3642    pub confirmed_by: ExitNodeConfirmation,
3643    /// The block it is in, where that is known. Unset for a node put in a block
3644    /// by a descendant's confirmation rather than read directly.
3645    pub block_height: Option<u32>,
3646}
3647
3648/// Which of a node's two pre-signed spends took it on-chain.
3649#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
3650#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3651pub enum ExitNodeConfirmation {
3652    /// The CPFP transaction, whose fee a child paid.
3653    Cpfp,
3654    /// The direct transaction, which pays its own fee. A leaf that went out this
3655    /// way is refunded by its direct refund transaction.
3656    Direct,
3657}
3658
3659/// A leaf's refund as the chain shows it.
3660#[derive(Debug, Clone, Serialize, Deserialize)]
3661#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3662pub struct ExitRefund {
3663    pub leaf_id: String,
3664    pub state: ExitRefundState,
3665}
3666
3667#[derive(Debug, Clone, Serialize, Deserialize)]
3668#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3669pub enum ExitRefundState {
3670    /// On-chain with its output still there, which is what the sweep pulls from.
3671    /// A sweep sitting unconfirmed in the mempool leaves the refund here, so
3672    /// that sweep is rebuilt rather than dropped.
3673    OnChain {
3674        tx_hex: String,
3675        vout: u32,
3676        value_sats: u64,
3677        block_height: Option<u32>,
3678    },
3679    /// Spent by a confirmed transaction: the sweep landed.
3680    Swept,
3681}
3682
3683/// Result of `export_unilateral_exit_state`: a self-contained copy of the
3684/// wallet's exit state, ready to be stored outside the wallet.
3685#[derive(Debug, Clone, Serialize, Deserialize)]
3686#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3687pub struct ExportUnilateralExitStateResponse {
3688    /// The serialized exit state, to be handed back to
3689    /// `import_unilateral_exit_state` unmodified.
3690    pub exit_state: String,
3691}
3692
3693/// Request for `import_unilateral_exit_state`.
3694#[derive(Debug, Clone, Serialize, Deserialize)]
3695#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3696pub struct ImportUnilateralExitStateRequest {
3697    /// An exit state as returned by `export_unilateral_exit_state`.
3698    pub exit_state: String,
3699}
3700
3701/// Result of `import_unilateral_exit_state`.
3702#[derive(Debug, Clone, Serialize, Deserialize)]
3703#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3704pub struct ImportUnilateralExitStateResponse {
3705    /// Leaves merged into the wallet's exit state, whether or not their exit
3706    /// data was taken with them.
3707    pub imported_leaves: u32,
3708    /// Leaves left out because the exit state does not record this wallet as
3709    /// their owner.
3710    pub skipped_foreign_leaves: u32,
3711    /// Leaves left out because their exit data disagrees with what the wallet
3712    /// already holds, so none of it could be trusted. The wallet is left without
3713    /// these leaves.
3714    pub skipped_conflicting_leaves: u32,
3715    /// Leaves the wallet holds whose imported exit data was left out: it is
3716    /// incomplete, the wallet's own copy can already back an exit, or the leaf
3717    /// was named more than once. The leaf itself is in the wallet either way.
3718    pub skipped_chains: u32,
3719}
3720
3721// ===========================================================================
3722// Recover funds
3723// ===========================================================================
3724
3725/// Request for `prepare_recover_funds`, which returns the recovery quote.
3726#[derive(Debug, Clone)]
3727#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3728pub struct PrepareRecoverFundsRequest {
3729    /// Target fee rate in sat/vByte, applied to every transaction the recovery
3730    /// builds. Below the network's relay minimum, zero included, nodes do not
3731    /// relay the transactions: they have to reach a miner another way.
3732    pub fee_rate_sat_per_vbyte: u64,
3733    /// The kind of UTXO that will fund a unilateral exit. Needed when a
3734    /// transaction of a unilateral exit in the quote has a CPFP child.
3735    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
3736    pub funding_kind: Option<CpfpFundingKind>,
3737    /// How the funding UTXOs pay a unilateral exit's CPFP children. Unset funds
3738    /// one UTXO per branch.
3739    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
3740    pub funding_strategy: Option<CpfpFundingStrategy>,
3741    /// The Bitcoin address the recovered funds are sent to.
3742    pub destination: String,
3743    pub selection: ExitLeafSelection,
3744}
3745
3746/// Response from `prepare_recover_funds`: which leaves would be recovered and
3747/// how, the exact fee at the requested rate, and how much to fund.
3748#[derive(Debug, Clone, Serialize, Deserialize)]
3749#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3750pub struct PrepareRecoverFundsResponse {
3751    pub leaves: Vec<RecoverFundsLeaf>,
3752    /// The leaves the selection covers that are not in `leaves`, each with the
3753    /// reason. A leaf whose recovery already finished is not listed.
3754    pub skipped: Vec<SkippedLeaf>,
3755    /// Total value of the selected leaves, in satoshis.
3756    pub recoverable_value_sats: u64,
3757    /// `cooperative_fee_sats + cpfp_fee_sats + fanout_fee_sats +
3758    /// refund_fee_sats + sweep_fee_sats`.
3759    pub total_fee_sats: u64,
3760    /// Paid from the cooperative leaves' own value. Each leaf has two fees: the
3761    /// one of the transaction the operators broadcast to move it on-chain, which
3762    /// is already paid, and the one of its recovery transaction.
3763    pub cooperative_fee_sats: u64,
3764    /// Paid by the CPFP children, from your funding UTXOs.
3765    pub cpfp_fee_sats: u64,
3766    /// Paid by the fan-out, from your funding UTXO. Funding one UTXO per
3767    /// `funding.per_branch` entry avoids it.
3768    pub fanout_fee_sats: u64,
3769    /// Paid from the unilateral leaves' own value before the sweep: each leaf's
3770    /// value less what its refund passes to the sweep. The output of a direct
3771    /// transaction, the Spark operators' version of a leaf's transaction, is its
3772    /// input less its fee, and a refund received with a watchtower fee ladder
3773    /// pays its own fee. For a refund that is not on-chain yet, the SDK counts
3774    /// the refund it expects: the operators can broadcast one with another fee.
3775    pub refund_fee_sats: u64,
3776    /// Paid by the final sweep, off the value it moves.
3777    pub sweep_fee_sats: u64,
3778    /// What to fund the unilateral exit with. Unset when nothing needs funding:
3779    /// no transaction of the recovery has a CPFP child.
3780    pub funding: Option<RecoveryFunding>,
3781    pub fee_rate_sat_per_vbyte: u64,
3782    pub destination: String,
3783    /// What the chain has already done to the unilateral leaves, read while
3784    /// preparing.
3785    pub exit_chain_state: ExitChainState,
3786}
3787
3788/// How much to fund a unilateral exit with.
3789#[derive(Debug, Clone, Serialize, Deserialize)]
3790#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3791pub struct RecoveryFunding {
3792    /// Fund a single UTXO of at least this many satoshis, which a fan-out
3793    /// splits over the `per_branch` entries.
3794    pub single_utxo_sats: u64,
3795    /// To skip the fan-out, fund one UTXO per entry of at least its amount, in
3796    /// any order. An entry is a branch, or under `CpfpFundingStrategy::PerNode`
3797    /// one transaction of a branch, so a leaf can have several.
3798    pub per_branch: Vec<PerBranchFunding>,
3799    /// The strategy the amounts were computed for, which `recover_funds` builds
3800    /// with.
3801    #[serde(default)]
3802    pub strategy: CpfpFundingStrategy,
3803}
3804
3805/// A leaf the selection covers that `prepare_recover_funds` leaves out of the
3806/// quote.
3807#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3808#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3809pub struct SkippedLeaf {
3810    pub leaf_id: String,
3811    pub value_sats: u64,
3812    pub reason: SkippedLeafReason,
3813}
3814
3815/// Why `prepare_recover_funds` leaves a leaf out of the quote.
3816#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3817#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3818pub enum SkippedLeafReason {
3819    /// At the quote's fee rate, recovering the leaf costs at least what is left
3820    /// of its funds: `value_sats`, less the fee of each direct transaction in its
3821    /// exit and the fee the operators paid out of the leaf when they broadcast
3822    /// its refund. A low enough fee rate brings the leaf back into the quote.
3823    FeeExceedsValue,
3824    /// The SDK read the chain and found no output holding the leaf's funds.
3825    FundsNotFound,
3826    /// The SDK could not look up where the leaf's funds are. It looks again the
3827    /// next time you prepare.
3828    Unverified,
3829    /// The SDK needs data from the Spark operators to find the leaf's funds,
3830    /// and could not reach them or they were too busy. It tries again the next
3831    /// time you prepare.
3832    OperatorsUnavailable,
3833    /// No recovery can be built for the leaf as it stands. `message` says why.
3834    NotRecoverable { message: String },
3835}
3836
3837/// A leaf selected for recovery.
3838#[derive(Debug, Clone, Serialize, Deserialize)]
3839#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3840pub struct RecoverFundsLeaf {
3841    pub leaf_id: String,
3842    pub value_sats: u64,
3843    pub method: RecoveryMethod,
3844}
3845
3846/// How a leaf's funds are recovered.
3847#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3848#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3849pub enum RecoveryMethod {
3850    /// One transaction the operators co-sign, paid from the leaf's value. No
3851    /// funding, no timelock.
3852    Cooperative,
3853    /// The leaf's own pre-signed transactions, fee-bumped from funding you
3854    /// supply, with timelock waits.
3855    Unilateral,
3856}
3857
3858/// Request for `recover_funds`: a `prepare_recover_funds` quote plus the
3859/// funding UTXOs that pay its fees.
3860#[derive(Debug, Clone)]
3861#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3862pub struct RecoverFundsRequest {
3863    pub prepared: PrepareRecoverFundsResponse,
3864    /// UTXOs that meet the quote's `funding`: one of at least `single_utxo_sats`,
3865    /// or one per `per_branch` entry. Not needed when the quote has no `funding`.
3866    #[cfg_attr(feature = "uniffi", uniffi(default = []))]
3867    pub funding_inputs: Vec<CpfpInput>,
3868}
3869
3870/// Result of `recover_funds`: every signed transaction of the recovery, and its
3871/// totals. The totals mean what they do on the quote, for the leaves in
3872/// `leaves`: the ones in `failed` add nothing to them.
3873#[derive(Debug, Clone, Serialize, Deserialize)]
3874#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3875pub struct RecoverFundsResponse {
3876    pub recoverable_value_sats: u64,
3877    pub total_fee_sats: u64,
3878    pub cooperative_fee_sats: u64,
3879    pub cpfp_fee_sats: u64,
3880    pub fanout_fee_sats: u64,
3881    pub refund_fee_sats: u64,
3882    pub sweep_fee_sats: u64,
3883    pub leaves: Vec<RecoverFundsLeaf>,
3884    /// Cooperative leaves whose recovery could not be produced, and why. No
3885    /// transaction depends on them.
3886    pub failed: Vec<CooperativeRecoveryFailure>,
3887    /// Every transaction, cooperative ones included, in broadcast order.
3888    pub transactions: Vec<RecoveryTransaction>,
3889    /// The funding UTXOs this recovery was built from, as you supplied them.
3890    /// Hand them back when you build it again and they are followed to whatever
3891    /// they have since become.
3892    pub funding_inputs: Vec<CpfpInput>,
3893    pub fee_rate_sat_per_vbyte: u64,
3894    pub destination: String,
3895}
3896
3897/// A cooperative recovery that could not be produced.
3898#[derive(Debug, Clone, Serialize, Deserialize)]
3899#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3900pub struct CooperativeRecoveryFailure {
3901    pub leaf_id: String,
3902    /// The output the recovery would have spent: the on-chain output where the
3903    /// SDK found the leaf's funds, or the one it assumed to hold them.
3904    pub output_txid: String,
3905    pub output_vout: u32,
3906    pub error: CooperativeRecoveryError,
3907}
3908
3909/// One transaction of a recovery, with everything needed to order and
3910/// broadcast it.
3911#[derive(Debug, Clone, Serialize, Deserialize)]
3912#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3913pub struct RecoveryTransaction {
3914    pub kind: RecoveryTxKind,
3915    /// The tree node it belongs to (the leaf, for `Cooperative`). Unset for
3916    /// `FanOut` and `Sweep`.
3917    pub node_id: Option<String>,
3918    pub txid: String,
3919    pub tx_hex: String,
3920    /// The signed CPFP child to broadcast alongside `tx_hex` as a package. Unset
3921    /// when there is no anchor to bump, and for a `Confirmed` step.
3922    pub cpfp_tx_hex: Option<String>,
3923    /// Relative CSV timelock, in blocks, that must mature on the spent input
3924    /// before this transaction can confirm. Unset when there is no timelock.
3925    pub csv_timelock_blocks: Option<u32>,
3926    /// Txids of other entries in this list that must be confirmed before this
3927    /// one can be broadcast.
3928    pub depends_on: Vec<String>,
3929    pub status: ExitTransactionStatus,
3930}
3931
3932/// The role of a transaction in a recovery.
3933#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3934#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3935pub enum RecoveryTxKind {
3936    /// Spends the on-chain output holding a leaf's funds, co-signed by the
3937    /// operators. Pays its fee from the leaf's value: no CPFP child, no
3938    /// dependencies, no timelock.
3939    Cooperative,
3940    /// Splits the caller's funding into one output per `funding.per_branch`
3941    /// entry: per branch, or under `CpfpFundingStrategy::PerNode` per
3942    /// transaction. Present only when the funding couldn't be matched
3943    /// one-to-one to the entries.
3944    FanOut,
3945    /// A tree node transaction (root, intermediate, or leaf node).
3946    Node,
3947    /// A leaf's refund transaction.
3948    Refund,
3949    /// The final transaction sweeping all refund outputs to the destination.
3950    Sweep,
3951}
3952
3953/// Request for `check_recover_funds`: the recovery you kept from a previous
3954/// `recover_funds`, as you last stored it.
3955#[derive(Debug, Clone)]
3956#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3957pub struct CheckRecoverFundsRequest {
3958    pub recovery: RecoverFundsResponse,
3959}
3960
3961/// Result of `check_recover_funds`: the same recovery, read back against the
3962/// chain.
3963#[derive(Debug, Clone)]
3964#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
3965pub struct CheckRecoverFundsResponse {
3966    /// Store it in place of the one you passed in.
3967    pub recovery: RecoverFundsResponse,
3968    pub verdict: RecoveryVerdict,
3969}
3970
3971/// What to do with a recovery that has been read back against the chain.
3972#[derive(Debug, Clone, Serialize, Deserialize)]
3973#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3974pub enum RecoveryVerdict {
3975    /// The recovery can still be finished as it stands. Broadcast the `Ready`
3976    /// transactions.
3977    Valid,
3978    /// Every transaction is confirmed. The leaves in `failed` are not part of
3979    /// the recovery.
3980    Done,
3981    /// The recovery cannot be finished as it stands. Prepare and recover again.
3982    Redo { reason: RecoveryRedoReason },
3983}
3984
3985/// Why a recovery has to be built again.
3986#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
3987#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
3988pub enum RecoveryRedoReason {
3989    /// The chain no longer matches the recovery: something that is not one of
3990    /// its own transactions took an outpoint it still needs. A different
3991    /// refund, a fee bump from elsewhere, or funding spent on something else
3992    /// all land here.
3993    OnChainStateDiverged,
3994}
3995
3996#[cfg(test)]
3997mod tests {
3998    use super::*;
3999    use crate::{ConversionStatus, PaymentMethod};
4000    use macros::test_all;
4001
4002    #[cfg(feature = "browser-tests")]
4003    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
4004
4005    #[test_all]
4006    fn seed_debug_redacts_secrets() {
4007        let mnemonic = Seed::Mnemonic {
4008            mnemonic: "abandon ability able".to_string(),
4009            passphrase: Some("hunter2".to_string()),
4010        };
4011        let rendered = format!("{mnemonic:?}");
4012        assert!(!rendered.contains("abandon"), "{rendered}");
4013        assert!(!rendered.contains("hunter2"), "{rendered}");
4014
4015        let entropy = format!("{:?}", Seed::Entropy(vec![0xab; 16]));
4016        assert!(!entropy.contains("171"), "{entropy}");
4017    }
4018
4019    #[test_all]
4020    fn debug_fmt_redacts_the_preimage_of_a_bolt11_receive() {
4021        let preimage = "ab".repeat(32);
4022        let method = ReceivePaymentMethod::Bolt11Invoice {
4023            description: "test".to_string(),
4024            amount_sats: Some(1_000),
4025            expiry_secs: None,
4026            payment_hash: None,
4027            receiver_identity_public_key: None,
4028            preimage: Some(preimage.clone()),
4029        };
4030
4031        let written = format!("{method:?}");
4032
4033        assert!(
4034            written.contains(r#"preimage: Some("<redacted>")"#),
4035            "{written}"
4036        );
4037        assert!(!written.contains(&preimage), "{written}");
4038    }
4039
4040    #[test_all]
4041    fn debug_fmt_redacts_the_preimage_of_a_lightning_send_status() {
4042        let preimage = "ab".repeat(32);
4043        let response = FetchLightningSendStatusResponse {
4044            status: Some(PaymentStatus::Completed),
4045            preimage: Some(preimage.clone()),
4046        };
4047
4048        let written = format!("{response:?}");
4049
4050        assert!(
4051            written.contains(r#"preimage: Some("<redacted>")"#),
4052            "{written}"
4053        );
4054        assert!(!written.contains(&preimage), "{written}");
4055    }
4056
4057    #[test_all]
4058    fn payment_link_types_map_to_bridge_from_cash_app() {
4059        let route = crate::CrossChainRoutePair {
4060            provider: crate::CrossChainProvider::Orchestra,
4061            chain: "base".to_string(),
4062            chain_id: None,
4063            asset: "USDC".to_string(),
4064            contract_address: None,
4065            decimals: 6,
4066            exact_out_eligible: false,
4067            accepted_assets: Vec::new(),
4068            delivery_methods: Vec::new(),
4069        };
4070        let request: BridgeFromCashAppRequest = PreparePaymentLinkRequest {
4071            address: "0xabc".to_string(),
4072            route: route.clone(),
4073            amount: 1_000_000,
4074            fee_policy: Some(FeePolicy::FeesIncluded),
4075            max_slippage_bps: Some(50),
4076        }
4077        .into();
4078        assert_eq!(request.address, "0xabc");
4079        assert_eq!(request.route, route);
4080        assert_eq!(request.amount, 1_000_000);
4081        assert_eq!(request.fee_policy, Some(FeePolicy::FeesIncluded));
4082        assert_eq!(request.max_slippage_bps, Some(50));
4083
4084        let response: PreparePaymentLinkResponse = BridgeFromCashAppResponse {
4085            url: "https://cash.app/launch/lightning/lnbc1".to_string(),
4086            amount_sats: 1_500,
4087            estimated_out: 990_000,
4088            asset: "USDC".to_string(),
4089            service_fee_amount: 10_000,
4090            service_fee_asset: Some("USDC".to_string()),
4091            service_fee_asset_decimals: Some(6),
4092            expires_at: 1_791_374_400,
4093        }
4094        .into();
4095        assert_eq!(response.url, "https://cash.app/launch/lightning/lnbc1");
4096        assert_eq!(response.amount_sats, 1_500);
4097        assert_eq!(response.estimated_out, 990_000);
4098        assert_eq!(response.asset, "USDC");
4099        assert_eq!(response.service_fee_amount, 10_000);
4100        assert_eq!(response.service_fee_asset.as_deref(), Some("USDC"));
4101        assert_eq!(response.service_fee_asset_decimals, Some(6));
4102        assert_eq!(response.expires_at, "2026-10-07T12:00:00Z");
4103    }
4104
4105    fn spark_payment(conversion_info: Option<ConversionInfo>) -> Payment {
4106        Payment {
4107            id: "pmt".to_string(),
4108            payment_type: PaymentType::Receive,
4109            status: PaymentStatus::Completed,
4110            amount: 1_000,
4111            fees: 0,
4112            timestamp: 0,
4113            method: PaymentMethod::Spark,
4114            details: Some(PaymentDetails::Spark {
4115                invoice_details: None,
4116                htlc_details: None,
4117                conversion_info,
4118            }),
4119            conversion_details: None,
4120        }
4121    }
4122
4123    fn amm_info() -> ConversionInfo {
4124        ConversionInfo::Amm {
4125            pool_id: "pool".to_string(),
4126            conversion_id: "conv".to_string(),
4127            status: ConversionStatus::Completed,
4128            fee: None,
4129            purpose: None,
4130            amount_adjustment: None,
4131            degradation: None,
4132        }
4133    }
4134
4135    fn orchestra_info() -> ConversionInfo {
4136        ConversionInfo::Orchestra {
4137            order_id: "ord".to_string(),
4138            quote_id: "q".to_string(),
4139            read_token: None,
4140            chain: "base".to_string(),
4141            chain_id: Some("8453".to_string()),
4142            asset: "USDC".to_string(),
4143            recipient_address: "sp1rcv".to_string(),
4144            asset_amount_in: Some(1_000_000),
4145            estimated_out: 990_000,
4146            delivered_amount: Some(990_000),
4147            external_tx_hash: None,
4148            refund_tx_hash: None,
4149            status: ConversionStatus::Completed,
4150            fee_amount: Some(10_000),
4151            service_fee_amount: None,
4152            service_fee_asset: None,
4153            service_fee_asset_decimals: None,
4154            asset_decimals: 6,
4155            asset_contract: None,
4156        }
4157    }
4158
4159    #[test_all]
4160    fn only_amm_legs_are_conversion_children() {
4161        // The AMM settles a conversion as its own payments, and those are the
4162        // ones the event middleware keeps to itself.
4163        assert!(spark_payment(Some(amm_info())).is_conversion_child());
4164
4165        // A cross-chain conversion annotates the payment the user made or
4166        // received. Treating it as a child would swallow its events, which on
4167        // receive is the only signal the funds arrived.
4168        assert!(!spark_payment(Some(orchestra_info())).is_conversion_child());
4169
4170        assert!(!spark_payment(None).is_conversion_child());
4171    }
4172
4173    #[test_all]
4174    fn claim_error_stored_with_a_fee_and_rate_still_loads() {
4175        let stored = r#"{"MaxDepositClaimFeeExceeded":{"tx":"tx","vout":1,
4176            "max_fee":{"Rate":{"sat_per_vbyte":2}},"required_fee_sats":500,
4177            "required_fee_rate_sat_per_vbyte":6}}"#;
4178        let error: crate::DepositClaimError = serde_json::from_str(stored).unwrap();
4179        assert_eq!(
4180            error,
4181            crate::DepositClaimError::MaxDepositClaimFeeExceeded {
4182                tx: "tx".to_string(),
4183                vout: 1,
4184                max_fee_sats: None,
4185                required_fee_sats: 500,
4186            }
4187        );
4188    }
4189
4190    #[test_all]
4191    fn max_fee_stored_without_a_proportional_part_still_loads() {
4192        for (stored, onchain) in [
4193            (
4194                r#"{"Fixed":{"amount":500}}"#,
4195                MaxOnchainFee::Fixed { amount: 500 },
4196            ),
4197            (
4198                r#"{"Rate":{"sat_per_vbyte":12}}"#,
4199                MaxOnchainFee::Rate { sat_per_vbyte: 12 },
4200            ),
4201            (
4202                r#"{"NetworkRecommended":{"leeway_sat_per_vbyte":3}}"#,
4203                MaxOnchainFee::NetworkRecommended {
4204                    leeway_sat_per_vbyte: 3,
4205                },
4206            ),
4207        ] {
4208            let max_fee: MaxFee = serde_json::from_str(stored).unwrap();
4209            assert_eq!(
4210                max_fee,
4211                MaxFee {
4212                    onchain,
4213                    proportional_ppm: None,
4214                }
4215            );
4216        }
4217    }
4218
4219    #[test_all]
4220    fn max_fee_is_stored_in_its_flat_shape() {
4221        let max_fee = MaxFee {
4222            onchain: MaxOnchainFee::Fixed { amount: 500 },
4223            proportional_ppm: Some(1_000),
4224        };
4225        let stored = serde_json::to_string(&max_fee).unwrap();
4226        assert_eq!(
4227            stored,
4228            r#"{"Fixed":{"amount":500,"proportional_ppm":1000}}"#
4229        );
4230        assert_eq!(serde_json::from_str::<MaxFee>(&stored).unwrap(), max_fee);
4231        let without_ppm = MaxFee {
4232            onchain: MaxOnchainFee::Rate { sat_per_vbyte: 2 },
4233            proportional_ppm: None,
4234        };
4235        assert_eq!(
4236            serde_json::to_string(&without_ppm).unwrap(),
4237            r#"{"Rate":{"sat_per_vbyte":2}}"#
4238        );
4239    }
4240
4241    #[test_all]
4242    fn recovery_funding_without_a_strategy_reads_as_per_branch() {
4243        // A quote is held while its funding is gathered, so one stored before the
4244        // field existed still has to read back, as the funding it always was.
4245        let stored =
4246            r#"{"single_utxo_sats":5000,"per_branch":[{"leaf_id":"a","funding_sats":5000}]}"#;
4247        let funding: RecoveryFunding = serde_json::from_str(stored).unwrap();
4248        assert_eq!(funding.strategy, CpfpFundingStrategy::PerBranch);
4249
4250        let per_node = RecoveryFunding {
4251            strategy: CpfpFundingStrategy::PerNode,
4252            ..funding
4253        };
4254        let round_trip: RecoveryFunding =
4255            serde_json::from_str(&serde_json::to_string(&per_node).unwrap()).unwrap();
4256        assert_eq!(round_trip.strategy, CpfpFundingStrategy::PerNode);
4257    }
4258}