Skip to main content

breez_sdk_spark/models/
adaptors.rs

1use bitcoin::{
2    Address, Transaction, address::NetworkUnchecked, consensus::encode::deserialize_hex,
3};
4use breez_sdk_common::input::{
5    self, InputType, PaymentRequestSource, SparkInvoiceDetails, parse_spark_address,
6};
7use spark_wallet::{
8    CoopExitAcceptance, CoopExitFeeQuote, CoopExitRequest, CoopExitSpeedFeeQuote, ExitSpeed,
9    LightningSendPayment, LightningSendStatus, Network as SparkNetwork, PreimageRequest,
10    PreimageRequestStatus, SilentPaymentAddress, SspUserRequest, TokenTransactionStatus,
11    TransferDirection, TransferStatus, TransferType, WalletTransfer,
12};
13use std::time::Duration;
14
15use platform_utils::time::UNIX_EPOCH;
16use tracing::{debug, warn};
17
18use crate::{
19    AutoOptimizationEvent, Fee, HtlcPayment, Network, OnchainConfirmationSpeed,
20    OptimizationOutcome, Payment, PaymentDetails, PaymentMethod, PaymentStatus, PaymentType,
21    SdkError, SendOnchainFeeQuote, SendOnchainSpeedFeeQuote, SparkHtlcDetails, SparkHtlcStatus,
22    SparkInvoicePaymentDetails, TokenBalance, TokenMetadata,
23};
24
25/// Feb 1, 2026 00:00:00 UTC — transfers before this may lack HTLC data on the operator.
26#[allow(clippy::duration_suboptimal_units)]
27const HTLC_DATA_REQUIRED_SINCE: Duration = Duration::from_secs(1_769_904_000);
28
29/// Derive HTLC details from SSP request fields when the operator lacks the
30/// `PreimageRequest`. Only allowed for old transfers (before [`HTLC_DATA_REQUIRED_SINCE`]);
31/// new transfers without HTLC data are considered an error.
32fn derive_htlc_details_from_ssp(
33    transfer: &WalletTransfer,
34    payment_hash: &str,
35    preimage: Option<&str>,
36) -> Result<SparkHtlcDetails, SdkError> {
37    let cutoff = UNIX_EPOCH
38        .checked_add(HTLC_DATA_REQUIRED_SINCE)
39        .ok_or_else(|| SdkError::Generic("HTLC cutoff time overflow".to_string()))?;
40    let is_old = transfer.created_at.is_none_or(|t| t < cutoff);
41    if !is_old {
42        return Err(SdkError::Generic(format!(
43            "Missing HTLC details for Lightning payment transfer {}",
44            transfer.id
45        )));
46    }
47
48    warn!(
49        "Missing HTLC preimage request for Lightning transfer {}, deriving from SSP data",
50        transfer.id
51    );
52
53    let status = match transfer.status {
54        TransferStatus::Completed => SparkHtlcStatus::PreimageShared,
55        TransferStatus::Expired | TransferStatus::Returned => SparkHtlcStatus::Returned,
56        _ => SparkHtlcStatus::WaitingForPreimage,
57    };
58    Ok(SparkHtlcDetails {
59        payment_hash: payment_hash.to_string(),
60        preimage: preimage.map(ToString::to_string),
61        expiry_time: transfer
62            .expiry_time
63            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
64            .map_or(0, |d| d.as_secs()),
65        status,
66    })
67}
68
69/// If the HTLC details are missing a preimage, fill it in from the given fallback and update
70/// the status to [`SparkHtlcStatus::PreimageShared`] accordingly.
71fn reconcile_htlc_preimage(details: &mut SparkHtlcDetails, preimage: Option<&str>) {
72    if details.preimage.is_none() {
73        details.preimage = preimage.map(ToString::to_string);
74    }
75    if details.preimage.is_some() {
76        details.status = SparkHtlcStatus::PreimageShared;
77    }
78}
79
80/// Builds HTLC details from the operator's preimage request, taking a missing preimage from
81/// `fallback_preimage`. A known preimage means [`SparkHtlcStatus::PreimageShared`], so an
82/// unrecognized status is only an error when no preimage is known.
83fn htlc_details_from_preimage_request(
84    request: &PreimageRequest,
85    fallback_preimage: Option<&str>,
86) -> Result<SparkHtlcDetails, SdkError> {
87    let preimage = request
88        .preimage
89        .as_ref()
90        .map(spark_wallet::Preimage::encode_hex)
91        .or_else(|| fallback_preimage.map(ToString::to_string));
92    let status = if preimage.is_some() {
93        SparkHtlcStatus::PreimageShared
94    } else {
95        request.status.try_into()?
96    };
97    Ok(SparkHtlcDetails {
98        payment_hash: request.payment_hash.to_string(),
99        preimage,
100        expiry_time: request
101            .expiry_time
102            .duration_since(UNIX_EPOCH)
103            .map_err(|e| SdkError::Generic(format!("Invalid expiry time: {e}")))?
104            .as_secs(),
105        status,
106    })
107}
108
109fn withdrawal_vout(request: &CoopExitRequest) -> Option<u32> {
110    let address = request.withdrawal_address.as_str();
111    let transaction: Transaction = deserialize_hex(&request.raw_coop_exit_transaction).ok()?;
112    let Ok(bitcoin_address) = address.parse::<Address<NetworkUnchecked>>() else {
113        // The SDK cannot derive a silent payment output's script from the address,
114        // because the script also depends on the transaction's inputs. Under
115        // Spark's rules the payout to a silent payment address is output 0.
116        return address.parse::<SilentPaymentAddress>().is_ok().then_some(0);
117    };
118    let script_pubkey = bitcoin_address.assume_checked().script_pubkey();
119    let index = transaction
120        .output
121        .iter()
122        .position(|output| output.script_pubkey == script_pubkey)?;
123    u32::try_from(index).ok()
124}
125
126impl PaymentMethod {
127    fn from_transfer(transfer: &WalletTransfer) -> Self {
128        match transfer.transfer_type {
129            TransferType::PreimageSwap => {
130                if transfer.is_ssp_transfer {
131                    PaymentMethod::Lightning
132                } else {
133                    PaymentMethod::Spark
134                }
135            }
136            TransferType::CooperativeExit => PaymentMethod::Withdraw,
137            TransferType::UtxoSwap => PaymentMethod::Deposit,
138            TransferType::Transfer => PaymentMethod::Spark,
139            _ => PaymentMethod::Unknown,
140        }
141    }
142}
143
144impl PaymentDetails {
145    #[allow(clippy::too_many_lines)]
146    fn from_transfer(transfer: &WalletTransfer) -> Result<Option<Self>, SdkError> {
147        if !transfer.is_ssp_transfer {
148            // Check for Spark invoice payments
149            if let Some(spark_invoice) = &transfer.spark_invoice {
150                let Some(InputType::SparkInvoice(invoice_details)) =
151                    parse_spark_address(spark_invoice, &PaymentRequestSource::default())
152                else {
153                    return Err(SdkError::Generic("Invalid spark invoice".to_string()));
154                };
155
156                return Ok(Some(PaymentDetails::Spark {
157                    invoice_details: Some(invoice_details.into()),
158                    htlc_details: None,
159                    conversion_info: None,
160                }));
161            }
162
163            // Check for Spark HTLC payments (when no user request is present)
164            if let Some(htlc_preimage_request) = &transfer.htlc_preimage_request {
165                return Ok(Some(PaymentDetails::Spark {
166                    invoice_details: None,
167                    htlc_details: Some(htlc_details_from_preimage_request(
168                        htlc_preimage_request,
169                        None,
170                    )?),
171                    conversion_info: None,
172                }));
173            }
174
175            return Ok(Some(PaymentDetails::Spark {
176                invoice_details: None,
177                htlc_details: None,
178                conversion_info: None,
179            }));
180        }
181
182        let Some(user_request) = &transfer.user_request else {
183            return Ok(None);
184        };
185
186        let details = match user_request {
187            SspUserRequest::LightningReceiveRequest(request) => {
188                let invoice_details = input::parse_invoice(&request.invoice.encoded_invoice)
189                    .ok_or(SdkError::Generic(
190                        "Invalid invoice in SspUserRequest::LightningReceiveRequest".to_string(),
191                    ))?;
192                let htlc_details = if let Some(req) = &transfer.htlc_preimage_request {
193                    htlc_details_from_preimage_request(
194                        req,
195                        request.lightning_receive_payment_preimage.as_deref(),
196                    )?
197                } else {
198                    derive_htlc_details_from_ssp(
199                        transfer,
200                        &request.invoice.payment_hash,
201                        request.lightning_receive_payment_preimage.as_deref(),
202                    )?
203                };
204                PaymentDetails::Lightning {
205                    description: invoice_details.description,
206                    invoice: request.invoice.encoded_invoice.clone(),
207                    destination_pubkey: invoice_details.payee_pubkey,
208                    htlc_details,
209                    lnurl_pay_info: None,
210                    lnurl_withdraw_info: None,
211                    lnurl_receive_metadata: None,
212                    conversion_info: None,
213                }
214            }
215            SspUserRequest::LightningSendRequest(request) => {
216                let invoice_details =
217                    input::parse_invoice(&request.encoded_invoice).ok_or(SdkError::Generic(
218                        "Invalid invoice in SspUserRequest::LightningSendRequest".to_string(),
219                    ))?;
220                let htlc_details = if let Some(req) = &transfer.htlc_preimage_request {
221                    htlc_details_from_preimage_request(
222                        req,
223                        request.lightning_send_payment_preimage.as_deref(),
224                    )?
225                } else {
226                    derive_htlc_details_from_ssp(
227                        transfer,
228                        &invoice_details.payment_hash,
229                        request.lightning_send_payment_preimage.as_deref(),
230                    )?
231                };
232                PaymentDetails::Lightning {
233                    description: invoice_details.description,
234                    invoice: request.encoded_invoice.clone(),
235                    destination_pubkey: invoice_details.payee_pubkey,
236                    htlc_details,
237                    lnurl_pay_info: None,
238                    lnurl_withdraw_info: None,
239                    lnurl_receive_metadata: None,
240                    conversion_info: None,
241                }
242            }
243            SspUserRequest::CoopExitRequest(request) => {
244                let Some(vout) = withdrawal_vout(request) else {
245                    // An error here would stall the sync, so the payment is
246                    // stored without details instead.
247                    warn!(
248                        "The SSP's record of coop exit {} has no payout output; storing the payment without details",
249                        request.id
250                    );
251                    return Ok(None);
252                };
253                PaymentDetails::Withdraw {
254                    tx_id: request.coop_exit_txid.clone(),
255                    vout,
256                    destination_address: request.withdrawal_address.clone(),
257                }
258            }
259            SspUserRequest::LeavesSwapRequest(_) => PaymentDetails::Spark {
260                invoice_details: None,
261                htlc_details: None,
262                conversion_info: None,
263            },
264            SspUserRequest::ClaimStaticDeposit(request) => {
265                let Ok(vout) = u32::try_from(request.output_index) else {
266                    // vout=0 is a valid output index, so we can't safely default.
267                    // Returning Ok(None) mirrors the early return for a missing
268                    // user_request above: the downstream branch records the deposit
269                    // as Pending without details and the sync loop keeps advancing
270                    // the offset. Erroring here would deadlock the whole sync until
271                    // the offending transfer leaves the SSP's response.
272                    warn!(
273                        "Invalid output_index {} in SspUserRequest::ClaimStaticDeposit; skipping details",
274                        request.output_index
275                    );
276                    return Ok(None);
277                };
278                PaymentDetails::Deposit {
279                    tx_id: request.transaction_id.clone(),
280                    vout,
281                }
282            }
283        };
284
285        Ok(Some(details))
286    }
287}
288
289impl From<SparkInvoiceDetails> for SparkInvoicePaymentDetails {
290    fn from(value: SparkInvoiceDetails) -> Self {
291        Self {
292            description: value.description,
293            invoice: value.invoice,
294        }
295    }
296}
297
298impl TryFrom<WalletTransfer> for Payment {
299    type Error = SdkError;
300    fn try_from(transfer: WalletTransfer) -> Result<Self, Self::Error> {
301        if [
302            TransferType::CounterSwap,
303            TransferType::CounterSwapV3,
304            TransferType::Swap,
305            TransferType::PrimarySwapV3,
306        ]
307        .contains(&transfer.transfer_type)
308        {
309            debug!("Tried to convert swap-related transfer to payment. Transfer: {transfer:?}");
310            return Err(SdkError::Generic(
311                "Swap-related transfers are not considered payments".to_string(),
312            ));
313        }
314        let payment_type = match transfer.direction {
315            TransferDirection::Incoming => PaymentType::Receive,
316            TransferDirection::Outgoing => PaymentType::Send,
317        };
318        let mut status = match transfer.status {
319            TransferStatus::Completed => PaymentStatus::Completed,
320            TransferStatus::SenderKeyTweaked
321                if transfer.direction == TransferDirection::Outgoing =>
322            {
323                PaymentStatus::Completed
324            }
325            TransferStatus::Expired | TransferStatus::Returned => PaymentStatus::Failed,
326            _ => PaymentStatus::Pending,
327        };
328        let (fees_sat, mut amount_sat) = match transfer.clone().user_request {
329            Some(user_request) => match user_request {
330                SspUserRequest::LightningSendRequest(r) => {
331                    // TODO: if we have the preimage it is not pending. This is a workaround
332                    // until spark will implement incremental syncing based on updated time.
333                    if r.lightning_send_payment_preimage.is_some() {
334                        status = PaymentStatus::Completed;
335                    }
336                    let fee_sat = r.fee.as_sats().unwrap_or(0);
337                    (fee_sat, transfer.total_value_sat.saturating_sub(fee_sat))
338                }
339                SspUserRequest::CoopExitRequest(r) => {
340                    // A committed transfer hands the funds to the provider; only
341                    // the provider broadcasts the payout, and only once it has
342                    // accepted the exit. Until then the withdrawal is still in
343                    // flight, however far the transfer itself got.
344                    status = match r.exit_status.acceptance() {
345                        CoopExitAcceptance::Accepted => status,
346                        CoopExitAcceptance::AwaitingCompletion => PaymentStatus::Pending,
347                        CoopExitAcceptance::Failed => PaymentStatus::Failed,
348                    };
349                    let fee_sat = r
350                        .fee
351                        .as_sats()
352                        .unwrap_or(0)
353                        .saturating_add(r.l1_broadcast_fee.as_sats().unwrap_or(0));
354                    (fee_sat, transfer.total_value_sat.saturating_sub(fee_sat))
355                }
356                SspUserRequest::ClaimStaticDeposit(r) => {
357                    let fee_sat = r
358                        .deposit_amount
359                        .as_sats()
360                        .unwrap_or(0)
361                        .saturating_sub(r.credit_amount.as_sats().unwrap_or(0));
362                    (fee_sat, transfer.total_value_sat)
363                }
364                _ => (0, transfer.total_value_sat),
365            },
366            None => (0, transfer.total_value_sat),
367        };
368
369        let details = match PaymentDetails::from_transfer(&transfer) {
370            Ok(Some(details)) => Some(details),
371            Ok(None) => {
372                // in case we have a completed status without user object we want
373                // to keep syncing this payment
374                if status == PaymentStatus::Completed
375                    && [
376                        TransferType::CooperativeExit,
377                        TransferType::PreimageSwap,
378                        TransferType::UtxoSwap,
379                    ]
380                    .contains(&transfer.transfer_type)
381                {
382                    status = PaymentStatus::Pending;
383                }
384                amount_sat = transfer.total_value_sat;
385                None
386            }
387            // Failing here would stop sync at this transfer on every pass. Recording it as
388            // Pending lets sync move on while reconciliation keeps re-fetching it, so the
389            // details fill in once the operator or SSP serves data that maps again.
390            Err(e) => {
391                warn!(
392                    "Recording transfer {} as pending without payment details: {e:?}",
393                    transfer.id
394                );
395                status = PaymentStatus::Pending;
396                None
397            }
398        };
399
400        Ok(Payment {
401            id: transfer.id.to_string(),
402            payment_type,
403            status,
404            amount: amount_sat.into(),
405            fees: fees_sat.into(),
406            timestamp: match transfer.created_at.map(|t| t.duration_since(UNIX_EPOCH)) {
407                Some(Ok(duration)) => duration.as_secs(),
408                _ => 0,
409            },
410            method: PaymentMethod::from_transfer(&transfer),
411            details,
412            conversion_details: None,
413        })
414    }
415}
416
417impl TryFrom<&WalletTransfer> for HtlcPayment {
418    type Error = SdkError;
419    fn try_from(transfer: &WalletTransfer) -> Result<Self, Self::Error> {
420        let request = transfer
421            .htlc_preimage_request
422            .as_ref()
423            .ok_or_else(|| SdkError::Generic(format!("Transfer {} is not an HTLC", transfer.id)))?;
424        Ok(HtlcPayment {
425            id: transfer.id.to_string(),
426            payment_type: match transfer.direction {
427                TransferDirection::Incoming => PaymentType::Receive,
428                TransferDirection::Outgoing => PaymentType::Send,
429            },
430            amount_sats: transfer.total_value_sat,
431            timestamp: match transfer.created_at.map(|t| t.duration_since(UNIX_EPOCH)) {
432                Some(Ok(duration)) => duration.as_secs(),
433                _ => 0,
434            },
435            htlc_details: htlc_details_from_preimage_request(request, None)?,
436        })
437    }
438}
439
440impl Payment {
441    /// Creates a [`Payment`] from a [`LightningSendPayment`] and its associated HTLC details.
442    ///
443    /// The `htlc_details` may be stale (e.g. captured at payment creation time), so this
444    /// method reconciles them with the current state of the `payment`:
445    /// - The preimage is taken from `htlc_details` if present, otherwise from the payment.
446    /// - If a preimage is available from either source, the HTLC status is set to
447    ///   [`SparkHtlcStatus::PreimageShared`].
448    pub fn from_lightning(
449        payment: LightningSendPayment,
450        amount_sat: u128,
451        transfer_id: String,
452        mut htlc_details: SparkHtlcDetails,
453    ) -> Result<Self, SdkError> {
454        let mut status = match payment.status {
455            LightningSendStatus::LightningPaymentSucceeded => PaymentStatus::Completed,
456            LightningSendStatus::LightningPaymentFailed
457            | LightningSendStatus::TransferFailed
458            | LightningSendStatus::PreimageProvidingFailed
459            | LightningSendStatus::UserSwapReturnFailed
460            | LightningSendStatus::UserSwapReturned => PaymentStatus::Failed,
461            _ => PaymentStatus::Pending,
462        };
463        if payment.payment_preimage.is_some() {
464            status = PaymentStatus::Completed;
465        }
466
467        reconcile_htlc_preimage(&mut htlc_details, payment.payment_preimage.as_deref());
468
469        let invoice_details = input::parse_invoice(&payment.encoded_invoice).ok_or(
470            SdkError::Generic("Invalid invoice in LightnintSendPayment".to_string()),
471        )?;
472        let details = PaymentDetails::Lightning {
473            description: invoice_details.description,
474            invoice: payment.encoded_invoice,
475            destination_pubkey: invoice_details.payee_pubkey,
476            htlc_details,
477            lnurl_pay_info: None,
478            lnurl_withdraw_info: None,
479            lnurl_receive_metadata: None,
480            conversion_info: None,
481        };
482
483        Ok(Payment {
484            id: transfer_id,
485            payment_type: PaymentType::Send,
486            status,
487            amount: amount_sat,
488            fees: payment.fee_sat.into(),
489            timestamp: payment.created_at.cast_unsigned(),
490            method: PaymentMethod::Lightning,
491            details: Some(details),
492            conversion_details: None,
493        })
494    }
495}
496
497impl From<Network> for SparkNetwork {
498    fn from(network: Network) -> Self {
499        match network {
500            Network::Mainnet => SparkNetwork::Mainnet,
501            Network::Regtest => SparkNetwork::Regtest,
502            Network::Signet => SparkNetwork::Signet,
503        }
504    }
505}
506
507impl From<Fee> for spark_wallet::Fee {
508    fn from(fee: Fee) -> Self {
509        match fee {
510            Fee::Fixed { amount } => spark_wallet::Fee::Fixed { amount },
511            Fee::Rate { sat_per_vbyte } => spark_wallet::Fee::Rate { sat_per_vbyte },
512        }
513    }
514}
515
516impl From<spark_wallet::TokenBalance> for TokenBalance {
517    fn from(value: spark_wallet::TokenBalance) -> Self {
518        Self {
519            balance: value.balance,
520            token_metadata: value.token_metadata.into(),
521        }
522    }
523}
524
525impl From<spark_wallet::TokenMetadata> for TokenMetadata {
526    fn from(value: spark_wallet::TokenMetadata) -> Self {
527        Self {
528            identifier: value.identifier,
529            issuer_public_key: hex::encode(value.issuer_public_key.serialize()),
530            name: value.name,
531            ticker: value.ticker,
532            decimals: value.decimals,
533            max_supply: value.max_supply,
534            is_freezable: value.is_freezable,
535            extra_metadata: value.extra_metadata,
536        }
537    }
538}
539
540impl From<CoopExitFeeQuote> for SendOnchainFeeQuote {
541    fn from(value: CoopExitFeeQuote) -> Self {
542        Self {
543            id: value.id,
544            expires_at: value.expires_at,
545            speed_fast: value.speed_fast.into(),
546            speed_medium: value.speed_medium.into(),
547            speed_slow: value.speed_slow.into(),
548            is_estimate: false,
549        }
550    }
551}
552
553impl From<SendOnchainFeeQuote> for CoopExitFeeQuote {
554    fn from(value: SendOnchainFeeQuote) -> Self {
555        Self {
556            id: value.id,
557            expires_at: value.expires_at,
558            speed_fast: value.speed_fast.into(),
559            speed_medium: value.speed_medium.into(),
560            speed_slow: value.speed_slow.into(),
561        }
562    }
563}
564
565impl From<CoopExitSpeedFeeQuote> for SendOnchainSpeedFeeQuote {
566    fn from(value: CoopExitSpeedFeeQuote) -> Self {
567        Self {
568            user_fee_sat: value.user_fee_sat,
569            l1_broadcast_fee_sat: value.l1_broadcast_fee_sat,
570        }
571    }
572}
573
574impl From<SendOnchainSpeedFeeQuote> for CoopExitSpeedFeeQuote {
575    fn from(value: SendOnchainSpeedFeeQuote) -> Self {
576        Self {
577            user_fee_sat: value.user_fee_sat,
578            l1_broadcast_fee_sat: value.l1_broadcast_fee_sat,
579        }
580    }
581}
582
583impl From<OnchainConfirmationSpeed> for ExitSpeed {
584    fn from(speed: OnchainConfirmationSpeed) -> Self {
585        match speed {
586            OnchainConfirmationSpeed::Fast => ExitSpeed::Fast,
587            OnchainConfirmationSpeed::Medium => ExitSpeed::Medium,
588            OnchainConfirmationSpeed::Slow => ExitSpeed::Slow,
589        }
590    }
591}
592
593impl From<ExitSpeed> for OnchainConfirmationSpeed {
594    fn from(speed: ExitSpeed) -> Self {
595        match speed {
596            ExitSpeed::Fast => OnchainConfirmationSpeed::Fast,
597            ExitSpeed::Medium => OnchainConfirmationSpeed::Medium,
598            ExitSpeed::Slow => OnchainConfirmationSpeed::Slow,
599        }
600    }
601}
602
603impl PaymentStatus {
604    pub(crate) fn from_token_transaction_status(
605        status: TokenTransactionStatus,
606        is_transfer_transaction: bool,
607    ) -> Self {
608        match status {
609            TokenTransactionStatus::Started
610            | TokenTransactionStatus::Revealed
611            | TokenTransactionStatus::Unknown => PaymentStatus::Pending,
612            TokenTransactionStatus::Signed if is_transfer_transaction => PaymentStatus::Pending,
613            TokenTransactionStatus::Finalized | TokenTransactionStatus::Signed => {
614                PaymentStatus::Completed
615            }
616            TokenTransactionStatus::StartedCancelled | TokenTransactionStatus::SignedCancelled => {
617                PaymentStatus::Failed
618            }
619        }
620    }
621}
622
623impl TryFrom<PreimageRequest> for SparkHtlcDetails {
624    type Error = SdkError;
625    fn try_from(value: PreimageRequest) -> Result<Self, Self::Error> {
626        htlc_details_from_preimage_request(&value, None)
627    }
628}
629
630impl TryFrom<PreimageRequestStatus> for SparkHtlcStatus {
631    type Error = SdkError;
632    fn try_from(status: PreimageRequestStatus) -> Result<Self, Self::Error> {
633        match status {
634            PreimageRequestStatus::WaitingForPreimage => Ok(SparkHtlcStatus::WaitingForPreimage),
635            PreimageRequestStatus::PreimageShared => Ok(SparkHtlcStatus::PreimageShared),
636            PreimageRequestStatus::Returned => Ok(SparkHtlcStatus::Returned),
637            // No public status fits: any of them would claim a state we don't know,
638            // e.g. `WaitingForPreimage` would list the HTLC as claimable.
639            PreimageRequestStatus::Unknown => Err(SdkError::Generic(
640                "Unrecognized preimage request status".to_string(),
641            )),
642        }
643    }
644}
645
646impl From<spark_wallet::AutoOptimizationEvent> for AutoOptimizationEvent {
647    fn from(value: spark_wallet::AutoOptimizationEvent) -> Self {
648        match value {
649            spark_wallet::AutoOptimizationEvent::Started { total_rounds } => {
650                Self::Started { total_rounds }
651            }
652            spark_wallet::AutoOptimizationEvent::RoundCompleted {
653                current_round,
654                total_rounds,
655            } => Self::RoundCompleted {
656                current_round,
657                total_rounds,
658            },
659            spark_wallet::AutoOptimizationEvent::Completed => Self::Completed,
660            spark_wallet::AutoOptimizationEvent::Cancelled => Self::Cancelled,
661            spark_wallet::AutoOptimizationEvent::Failed { error } => Self::Failed { error },
662            spark_wallet::AutoOptimizationEvent::Skipped => Self::Skipped,
663        }
664    }
665}
666
667impl From<spark_wallet::OptimizationOutcome> for OptimizationOutcome {
668    fn from(value: spark_wallet::OptimizationOutcome) -> Self {
669        match value {
670            spark_wallet::OptimizationOutcome::Completed { rounds_executed } => {
671                Self::Completed { rounds_executed }
672            }
673            spark_wallet::OptimizationOutcome::InProgress => Self::InProgress,
674        }
675    }
676}
677
678impl From<crate::CpfpFundingStrategy> for spark_wallet::CpfpFundingStrategy {
679    fn from(value: crate::CpfpFundingStrategy) -> Self {
680        match value {
681            crate::CpfpFundingStrategy::PerBranch => Self::PerBranch,
682            crate::CpfpFundingStrategy::PerNode => Self::PerNode,
683        }
684    }
685}
686
687impl From<crate::WebhookEventType> for spark_wallet::SparkWalletWebhookEventType {
688    fn from(value: crate::WebhookEventType) -> Self {
689        match value {
690            crate::WebhookEventType::LightningReceiveFinished => {
691                Self::SparkLightningReceiveFinished
692            }
693            crate::WebhookEventType::LightningSendFinished => Self::SparkLightningSendFinished,
694            crate::WebhookEventType::CoopExitFinished => Self::SparkCoopExitFinished,
695            crate::WebhookEventType::StaticDepositFinished => Self::SparkStaticDepositFinished,
696            crate::WebhookEventType::Unknown(s) => Self::Unknown(s),
697        }
698    }
699}
700
701impl From<spark_wallet::SparkWalletWebhookEventType> for crate::WebhookEventType {
702    fn from(value: spark_wallet::SparkWalletWebhookEventType) -> Self {
703        match value {
704            spark_wallet::SparkWalletWebhookEventType::SparkLightningReceiveFinished => {
705                Self::LightningReceiveFinished
706            }
707            spark_wallet::SparkWalletWebhookEventType::SparkLightningSendFinished => {
708                Self::LightningSendFinished
709            }
710            spark_wallet::SparkWalletWebhookEventType::SparkCoopExitFinished => {
711                Self::CoopExitFinished
712            }
713            spark_wallet::SparkWalletWebhookEventType::SparkStaticDepositFinished => {
714                Self::StaticDepositFinished
715            }
716            spark_wallet::SparkWalletWebhookEventType::Unknown(s) => Self::Unknown(s),
717        }
718    }
719}
720
721impl From<spark_wallet::WebhookEntry> for crate::Webhook {
722    fn from(value: spark_wallet::WebhookEntry) -> Self {
723        Self {
724            id: value.webhook_id,
725            url: value.url,
726            event_types: value.event_types.into_iter().map(Into::into).collect(),
727        }
728    }
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734    use crate::SendOnchainFeeQuote;
735    use chrono::Utc;
736    use macros::test_all;
737    use platform_utils::time::SystemTime;
738    use spark_wallet::{
739        BitcoinNetwork, CoopExitFeeQuote, CoopExitSpeedFeeQuote, CurrencyAmount, CurrencyUnit,
740        LightningSendRequest, LightningSendRequestStatus, PublicKey, SparkCoopExitRequestStatus,
741        SspTransfer, Transfer, TransferId,
742    };
743
744    #[cfg(feature = "browser-tests")]
745    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
746
747    #[test_all]
748    fn test_a_provider_quote_is_never_an_estimate() {
749        // What keeps a real quote distinguishable from a locally derived one.
750        // Marking it an estimate would give it an estimate's fee headroom and
751        // stop it being refreshed near expiry.
752        let speed = || CoopExitSpeedFeeQuote {
753            user_fee_sat: 750,
754            l1_broadcast_fee_sat: 960,
755        };
756        let quote: SendOnchainFeeQuote = CoopExitFeeQuote {
757            id: "SparkCoopExitFeeQuote:test".to_string(),
758            expires_at: 1_787_907_773,
759            speed_fast: speed(),
760            speed_medium: speed(),
761            speed_slow: speed(),
762        }
763        .into();
764
765        assert!(!quote.is_estimate);
766        assert_eq!(quote.id, "SparkCoopExitFeeQuote:test");
767        assert_eq!(quote.expires_at, 1_787_907_773);
768    }
769
770    fn pk(fill_byte: u8) -> PublicKey {
771        let mut bytes = [fill_byte; 33];
772        bytes[0] = 2;
773        PublicKey::from_slice(&bytes).unwrap()
774    }
775
776    /// A completed transfer created now, sent from `sender` to `receiver`.
777    fn transfer(sender: PublicKey, receiver: PublicKey, transfer_type: TransferType) -> Transfer {
778        let now = SystemTime::now()
779            .duration_since(UNIX_EPOCH)
780            .unwrap()
781            .as_secs();
782        Transfer {
783            id: TransferId::generate(),
784            sender_identity_public_key: sender,
785            receiver_identity_public_key: receiver,
786            status: TransferStatus::Completed,
787            total_value: 1_010,
788            expiry_time: None,
789            leaves: Vec::new(),
790            created_time: Some(now),
791            updated_time: Some(now),
792            transfer_type,
793            spark_invoice: None,
794        }
795    }
796
797    #[test_all]
798    fn a_lightning_send_whose_details_fail_to_map_is_pending_with_its_amount() {
799        let (ours, ssp) = (pk(1), pk(2));
800        let request = LightningSendRequest {
801            id: "request".to_string(),
802            created_at: Utc::now(),
803            updated_at: Utc::now(),
804            network: BitcoinNetwork::Regtest,
805            encoded_invoice: "not an invoice".to_string(),
806            fee: CurrencyAmount {
807                original_value: 10,
808                original_unit: CurrencyUnit::Satoshi,
809                preferred_currency_unit: CurrencyUnit::Satoshi,
810                preferred_currency_value_rounded: 10,
811            },
812            idempotency_key: "key".to_string(),
813            status: LightningSendRequestStatus::LightningPaymentSucceeded,
814            transfer: None,
815            lightning_send_payment_preimage: None,
816        };
817        let wallet_transfer = WalletTransfer::from_transfer(
818            transfer(ours, ssp, TransferType::PreimageSwap),
819            Some(SspTransfer {
820                total_amount: request.fee.clone(),
821                spark_id: None,
822                user_request: Some(SspUserRequest::LightningSendRequest(request)),
823            }),
824            None,
825            ours,
826            ssp,
827        );
828
829        let payment = Payment::try_from(wallet_transfer).unwrap();
830
831        assert!(payment.details.is_none());
832        assert_eq!(payment.method, PaymentMethod::Lightning);
833        assert_eq!(payment.payment_type, PaymentType::Send);
834        // Pending so reconciliation re-fetches it until its details map.
835        assert_eq!(payment.status, PaymentStatus::Pending);
836        assert_eq!(payment.amount, 1_000);
837        assert_eq!(payment.fees, 10);
838    }
839
840    #[test_all]
841    fn a_spark_transfer_with_an_invalid_invoice_is_a_pending_payment() {
842        let (ours, other, ssp) = (pk(1), pk(7), pk(2));
843        let mut raw = transfer(other, ours, TransferType::Transfer);
844        raw.spark_invoice = Some("not an invoice".to_string());
845        let wallet_transfer = WalletTransfer::from_transfer(raw, None, None, ours, ssp);
846
847        let payment = Payment::try_from(wallet_transfer).unwrap();
848
849        assert!(payment.details.is_none());
850        assert_eq!(payment.method, PaymentMethod::Spark);
851        assert_eq!(payment.payment_type, PaymentType::Receive);
852        assert_eq!(payment.status, PaymentStatus::Pending);
853        assert_eq!(payment.amount, 1_010);
854    }
855
856    #[test_all]
857    fn a_spark_htlc_with_an_unknown_preimage_status_is_pending_without_details() {
858        use bitcoin::hashes::{Hash, sha256};
859
860        let (ours, other, ssp) = (pk(1), pk(7), pk(2));
861        let preimage_request = PreimageRequest {
862            payment_hash: sha256::Hash::hash(b"preimage"),
863            status: PreimageRequestStatus::Unknown,
864            created_time: SystemTime::now(),
865            expiry_time: SystemTime::now(),
866            preimage: None,
867        };
868        let wallet_transfer = WalletTransfer::from_transfer(
869            transfer(other, ours, TransferType::PreimageSwap),
870            None,
871            Some(preimage_request),
872            ours,
873            ssp,
874        );
875
876        let payment = Payment::try_from(wallet_transfer).unwrap();
877
878        // No HTLC details, so an `htlc_status` filter can't list it as claimable.
879        assert!(payment.details.is_none());
880        assert_eq!(payment.method, PaymentMethod::Spark);
881        assert_eq!(payment.status, PaymentStatus::Pending);
882    }
883
884    #[test_all]
885    fn an_unknown_preimage_status_with_a_known_preimage_is_preimage_shared() {
886        use bitcoin::hashes::{Hash, sha256};
887
888        let preimage_request = PreimageRequest {
889            payment_hash: sha256::Hash::hash(b"preimage"),
890            status: PreimageRequestStatus::Unknown,
891            created_time: SystemTime::now(),
892            expiry_time: SystemTime::now(),
893            preimage: None,
894        };
895        let preimage = "00".repeat(32);
896
897        let details =
898            htlc_details_from_preimage_request(&preimage_request, Some(&preimage)).unwrap();
899
900        assert_eq!(details.status, SparkHtlcStatus::PreimageShared);
901        assert_eq!(details.preimage, Some(preimage));
902    }
903
904    fn coop_exit(withdrawal_address: &str, raw_coop_exit_transaction: &str) -> CoopExitRequest {
905        CoopExitRequest {
906            id: "request".to_string(),
907            created_at: Utc::now(),
908            updated_at: Utc::now(),
909            network: BitcoinNetwork::Regtest,
910            fee: CurrencyAmount::default(),
911            withdrawal_address: withdrawal_address.to_string(),
912            l1_broadcast_fee: CurrencyAmount::default(),
913            exit_status: SparkCoopExitRequestStatus::Succeeded,
914            exit_expired_at: Utc::now(),
915            raw_connector_transaction: String::new(),
916            raw_coop_exit_transaction: raw_coop_exit_transaction.to_string(),
917            coop_exit_txid: "exit_txid".to_string(),
918            transfer: None,
919        }
920    }
921
922    fn regtest_address(key: PublicKey) -> Address {
923        Address::p2wpkh(
924            &bitcoin::CompressedPublicKey(key),
925            bitcoin::Network::Regtest,
926        )
927    }
928
929    fn exit_transaction_hex(addresses: &[&Address]) -> String {
930        let transaction = Transaction {
931            version: bitcoin::transaction::Version::TWO,
932            lock_time: bitcoin::absolute::LockTime::ZERO,
933            input: vec![bitcoin::TxIn::default()],
934            output: addresses
935                .iter()
936                .map(|address| bitcoin::TxOut {
937                    value: bitcoin::Amount::from_sat(1_000),
938                    script_pubkey: address.script_pubkey(),
939                })
940                .collect(),
941        };
942        bitcoin::consensus::encode::serialize_hex(&transaction)
943    }
944
945    #[test_all]
946    fn a_withdrawal_carries_its_address_and_the_index_of_its_payout_output() {
947        let (ours, ssp) = (pk(1), pk(2));
948        let address = regtest_address(pk(7));
949        let raw_transaction = exit_transaction_hex(&[&regtest_address(ssp), &address]);
950        let wallet_transfer = WalletTransfer::from_transfer(
951            transfer(ours, ssp, TransferType::CooperativeExit),
952            Some(SspTransfer {
953                total_amount: CurrencyAmount::default(),
954                spark_id: None,
955                user_request: Some(SspUserRequest::CoopExitRequest(coop_exit(
956                    &address.to_string(),
957                    &raw_transaction,
958                ))),
959            }),
960            None,
961            ours,
962            ssp,
963        );
964
965        let payment = Payment::try_from(wallet_transfer).unwrap();
966
967        let Some(PaymentDetails::Withdraw {
968            tx_id,
969            vout,
970            destination_address,
971        }) = payment.details
972        else {
973            panic!("expected withdraw details, got {:?}", payment.details);
974        };
975        assert_eq!(tx_id, "exit_txid");
976        assert_eq!(vout, 1);
977        assert_eq!(destination_address, address.to_string());
978    }
979
980    #[test_all]
981    fn a_withdrawal_without_a_payout_output_has_no_details() {
982        let (ours, ssp) = (pk(1), pk(2));
983        let address = regtest_address(pk(7));
984        let raw_transaction = exit_transaction_hex(&[&regtest_address(ssp)]);
985        let wallet_transfer = WalletTransfer::from_transfer(
986            transfer(ours, ssp, TransferType::CooperativeExit),
987            Some(SspTransfer {
988                total_amount: CurrencyAmount::default(),
989                spark_id: None,
990                user_request: Some(SspUserRequest::CoopExitRequest(coop_exit(
991                    &address.to_string(),
992                    &raw_transaction,
993                ))),
994            }),
995            None,
996            ours,
997            ssp,
998        );
999
1000        let payment = Payment::try_from(wallet_transfer).unwrap();
1001
1002        assert_eq!(payment.method, PaymentMethod::Withdraw);
1003        assert!(payment.details.is_none(), "{:?}", payment.details);
1004    }
1005
1006    #[test_all]
1007    fn no_output_index_without_an_output_to_the_withdrawal_address() {
1008        let address = regtest_address(pk(7));
1009        let raw_transaction = exit_transaction_hex(&[&regtest_address(pk(2))]);
1010
1011        let vout = withdrawal_vout(&coop_exit(&address.to_string(), &raw_transaction));
1012
1013        assert_eq!(vout, None);
1014    }
1015
1016    #[test_all]
1017    fn the_payout_to_a_silent_payment_address_is_output_zero() {
1018        let address = SilentPaymentAddress::new(pk(1), pk(7), SparkNetwork::Regtest);
1019        let raw_transaction = exit_transaction_hex(&[&regtest_address(pk(2))]);
1020
1021        let vout = withdrawal_vout(&coop_exit(&address.to_string(), &raw_transaction));
1022
1023        assert_eq!(vout, Some(0));
1024    }
1025
1026    #[test_all]
1027    fn no_output_index_when_the_exit_transaction_does_not_decode() {
1028        let address = SilentPaymentAddress::new(pk(1), pk(7), SparkNetwork::Regtest);
1029
1030        let vout = withdrawal_vout(&coop_exit(&address.to_string(), "not a transaction"));
1031
1032        assert_eq!(vout, None);
1033    }
1034}