Skip to main content

breez_sdk_spark/sdk/payments/
mod.rs

1use spark_wallet::LightningReceivePayment;
2use tracing::instrument;
3
4use crate::{
5    ClaimHtlcPaymentRequest, ClaimHtlcPaymentResponse, FetchConversionLimitsRequest,
6    FetchConversionLimitsResponse, FetchHtlcPaymentsRequest, FetchHtlcPaymentsResponse,
7    FetchLightningSendStatusRequest, FetchLightningSendStatusResponse, GetPaymentRequest,
8    GetPaymentResponse, RefundPendingConversionsResponse, WaitForPaymentIdentifier,
9    error::SdkError,
10    models::{
11        BuildUnsignedBatchPackageRequest, BuildUnsignedPullPackageRequest,
12        BuildUnsignedTransferPackageRequest, ListPaymentsRequest, ListPaymentsResponse, Payment,
13        PaymentRequest, PrepareSendBatchRequest, PrepareSendBatchResponse,
14        PrepareSendPaymentRequest, PrepareSendPaymentResponse, PublishSignedPullPackageRequest,
15        PublishSignedTransferPackageRequest, PublishSignedTransferPackageResponse,
16        PullPaymentResponse, ReceivePaymentRequest, ReceivePaymentResponse, SendBatchRequest,
17        SendBatchResponse, SendPaymentRequest, SendPaymentResponse, UnsignedTransferPackage,
18    },
19    utils::payments::get_payment_with_conversion_details,
20};
21
22use super::BreezSdk;
23
24pub(in crate::sdk) mod client_signing;
25pub(in crate::sdk) mod conversion;
26mod htlc;
27mod lightning_send_status;
28mod polling;
29pub(in crate::sdk) mod prepare;
30pub(in crate::sdk) mod receive;
31pub(in crate::sdk) mod send;
32pub(in crate::sdk) mod validation;
33
34#[macros::instance_span]
35#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
36#[allow(clippy::needless_pass_by_value)]
37impl BreezSdk {
38    pub async fn receive_payment(
39        &self,
40        request: ReceivePaymentRequest,
41    ) -> Result<ReceivePaymentResponse, SdkError> {
42        receive::receive_payment(self, request).await
43    }
44
45    pub async fn claim_htlc_payment(
46        &self,
47        request: ClaimHtlcPaymentRequest,
48    ) -> Result<ClaimHtlcPaymentResponse, SdkError> {
49        htlc::claim_htlc_payment(self, request).await
50    }
51
52    /// Fetches the payments locked to a payment hash from the Spark operators, without reading
53    /// the local payment history. Covers Spark HTLC payments and Lightning payments this wallet
54    /// sent or received.
55    pub async fn fetch_htlc_payments(
56        &self,
57        request: FetchHtlcPaymentsRequest,
58    ) -> Result<FetchHtlcPaymentsResponse, SdkError> {
59        htlc::fetch_htlc_payments(self, request).await
60    }
61
62    pub async fn prepare_send_payment(
63        &self,
64        request: PrepareSendPaymentRequest,
65    ) -> Result<PrepareSendPaymentResponse, SdkError> {
66        // Cross-chain has its own request type (no parse step required) — early-dispatch
67        // before falling through to the generic `Input` path.
68        if let PaymentRequest::CrossChain {
69            ref address,
70            ref route,
71            max_slippage_bps,
72            target_overpay_bps,
73        } = request.payment_request
74        {
75            let amount = request.amount.ok_or(SdkError::InvalidInput(
76                "Amount is required for cross-chain sends".to_string(),
77            ))?;
78            return prepare::cross_chain::prepare(
79                self,
80                address,
81                route,
82                amount,
83                request.token_identifier.clone(),
84                request.conversion_options.clone(),
85                request.fee_policy.unwrap_or_default(),
86                max_slippage_bps,
87                target_overpay_bps,
88            )
89            .await;
90        }
91        prepare::prepare(self, request).await
92    }
93
94    #[instrument(
95        level = "info",
96        target = "breez_sdk_core::send_payment",
97        skip_all,
98        fields(payment_id = tracing::field::Empty),
99    )]
100    pub async fn send_payment(
101        &self,
102        request: SendPaymentRequest,
103    ) -> Result<SendPaymentResponse, SdkError> {
104        self.maybe_ensure_spark_private_mode_initialized().await?;
105        if let Some(key) = request.idempotency_key.as_deref() {
106            tracing::Span::current().record("payment_id", key);
107        }
108        Box::pin(send::orchestrate_send(self, request, false, None)).await
109    }
110
111    /// Prepares a send to several payees, all paid by one transaction.
112    ///
113    /// Each recipient is a Spark address or a Spark invoice, and one batch may
114    /// span several tokens. The response resolves every invoice into the asset
115    /// and amount it requests, and reports what the batch debits per asset.
116    ///
117    /// A batch pays tokens: sending sats to several payees at once is not
118    /// supported yet, so a recipient that resolves to sats is rejected.
119    ///
120    /// A batch that pays a Spark invoice is limited to a single token: the
121    /// operators reject a transaction that carries an invoice and pays more
122    /// than one. Send those as one batch per token.
123    pub async fn prepare_send_batch(
124        &self,
125        request: PrepareSendBatchRequest,
126    ) -> Result<PrepareSendBatchResponse, SdkError> {
127        prepare::batch::prepare(self, request).await
128    }
129
130    /// Sends the batch prepared by [`BreezSdk::prepare_send_batch`], returning
131    /// one payment per recipient in recipient order.
132    ///
133    /// Retrying after a failure that leaves the outcome unknown may pay twice:
134    /// a token transfer has no idempotency key, since the operator can only be
135    /// asked about a transaction by a hash that is computed while broadcasting.
136    /// Look for the batch with a `Token` payment details filter on the
137    /// transaction hash before sending it again.
138    #[instrument(level = "info", target = "breez_sdk_core::send_batch", skip_all)]
139    pub async fn send_batch(
140        &self,
141        request: SendBatchRequest,
142    ) -> Result<SendBatchResponse, SdkError> {
143        self.maybe_ensure_spark_private_mode_initialized().await?;
144        Box::pin(send::batch::send(self, request)).await
145    }
146
147    /// Builds the unsigned package for the batch prepared by
148    /// [`BreezSdk::prepare_send_batch`], for signing outside the SDK.
149    ///
150    /// Publish the signed package with
151    /// [`BreezSdk::publish_signed_transfer_package`], which returns every payment.
152    pub async fn build_unsigned_batch_package(
153        &self,
154        request: BuildUnsignedBatchPackageRequest,
155    ) -> Result<UnsignedTransferPackage, SdkError> {
156        Box::pin(client_signing::build_unsigned_batch_package(
157            self,
158            &request.prepare_response,
159        ))
160        .await
161    }
162
163    pub async fn build_unsigned_transfer_package(
164        &self,
165        request: BuildUnsignedTransferPackageRequest,
166    ) -> Result<UnsignedTransferPackage, SdkError> {
167        Box::pin(client_signing::build_unsigned_transfer_package(
168            self,
169            &request.prepare_response,
170            request.options.as_ref(),
171        ))
172        .await
173    }
174
175    /// Builds the package a client signs to approve a prepared pull.
176    #[allow(clippy::unused_async)]
177    pub async fn build_unsigned_pull_package(
178        &self,
179        request: BuildUnsignedPullPackageRequest,
180    ) -> Result<UnsignedTransferPackage, SdkError> {
181        client_signing::build_unsigned_pull_package(&request, self.config.network)
182    }
183
184    #[instrument(
185        level = "info",
186        target = "breez_sdk_core::publish_signed_transfer_package",
187        skip_all
188    )]
189    pub async fn publish_signed_transfer_package(
190        &self,
191        request: PublishSignedTransferPackageRequest,
192    ) -> Result<PublishSignedTransferPackageResponse, SdkError> {
193        self.maybe_ensure_spark_private_mode_initialized().await?;
194        Box::pin(send::publish_signed_transfer_package(
195            self,
196            &request.signed_package,
197        ))
198        .await
199    }
200
201    /// Broadcasts a pull signed by a client, returning the same result when the same package is published again.
202    #[instrument(
203        level = "info",
204        target = "breez_sdk_core::publish_signed_pull_package",
205        skip_all
206    )]
207    pub async fn publish_signed_pull_package(
208        &self,
209        request: PublishSignedPullPackageRequest,
210    ) -> Result<PullPaymentResponse, SdkError> {
211        self.maybe_ensure_spark_private_mode_initialized().await?;
212        Box::pin(client_signing::publish_signed_pull_package(
213            self,
214            &request.signed_package,
215        ))
216        .await
217    }
218
219    pub async fn fetch_conversion_limits(
220        &self,
221        request: FetchConversionLimitsRequest,
222    ) -> Result<FetchConversionLimitsResponse, SdkError> {
223        self.token_converter
224            .fetch_limits(&request)
225            .await
226            .map_err(Into::into)
227    }
228
229    /// Runs one full pass of the pending-conversion refunder and returns how
230    /// many conversions were refunded, skipped (held back by a safety window),
231    /// or failed.
232    ///
233    /// The pass has two parts: refunding locally-marked failed conversions, and
234    /// reconciling against Flashnet's clawback-eligible listing to catch
235    /// conversions with no local marker (e.g. a storage write that never
236    /// landed). The SDK's periodic background schedule runs only the local
237    /// part; the reconcile runs at SDK init and on each call to this method, so
238    /// this is the explicit entry point for driving a full pass on demand.
239    pub async fn refund_pending_conversions(
240        &self,
241    ) -> Result<RefundPendingConversionsResponse, SdkError> {
242        self.token_converter
243            .refund_pending(&self.event_emitter)
244            .await
245            .map_err(Into::into)
246    }
247
248    /// Lists payments from the storage with pagination
249    ///
250    /// This method provides direct access to the payment history stored in the database.
251    /// It returns payments in reverse chronological order (newest first).
252    ///
253    /// # Arguments
254    ///
255    /// * `request` - Contains pagination parameters (offset and limit)
256    ///
257    /// # Returns
258    ///
259    /// * `Ok(ListPaymentsResponse)` - Contains the list of payments if successful
260    /// * `Err(SdkError)` - If there was an error accessing the storage
261    pub async fn list_payments(
262        &self,
263        request: ListPaymentsRequest,
264    ) -> Result<ListPaymentsResponse, SdkError> {
265        use crate::utils::conversions::extract_conversion_info;
266        use crate::utils::payments::apply_conversion_details;
267
268        let mut payments = self.storage.list_payments(request.into()).await?;
269
270        // Query child payments for payments that have conversion_details set (AMM)
271        let parent_ids: Vec<String> = payments
272            .iter()
273            .filter(|p| p.conversion_details.is_some())
274            .map(|p| p.id.clone())
275            .collect();
276
277        let related_payments_map = if parent_ids.is_empty() {
278            std::collections::HashMap::default()
279        } else {
280            self.storage.get_payments_by_parent_ids(parent_ids).await?
281        };
282
283        for payment in &mut payments {
284            let has_conversion_details = payment.conversion_details.is_some();
285            let has_crosschain_info = extract_conversion_info(payment.details.clone())
286                .is_some_and(|info| !matches!(info, crate::ConversionInfo::Amm { .. }));
287
288            if !has_conversion_details && !has_crosschain_info {
289                continue;
290            }
291
292            let child_payments = if has_conversion_details {
293                related_payments_map.get(&payment.id).map(Vec::as_slice)
294            } else {
295                None
296            };
297
298            apply_conversion_details(payment, child_payments);
299        }
300
301        Ok(ListPaymentsResponse { payments })
302    }
303
304    pub async fn get_payment(
305        &self,
306        request: GetPaymentRequest,
307    ) -> Result<GetPaymentResponse, SdkError> {
308        let payment =
309            get_payment_with_conversion_details(request.payment_id, self.storage.clone()).await?;
310
311        Ok(GetPaymentResponse { payment })
312    }
313
314    /// Fetches the status of this wallet's Lightning payment of a Bolt11 invoice from the Spark
315    /// operators, without reading the local payment history. A payment made by a direct Spark
316    /// transfer to the invoice's Spark address is not covered.
317    pub async fn fetch_lightning_send_status(
318        &self,
319        request: FetchLightningSendStatusRequest,
320    ) -> Result<FetchLightningSendStatusResponse, SdkError> {
321        lightning_send_status::fetch_lightning_send_status(self, request).await
322    }
323}
324
325// Private payment methods
326impl BreezSdk {
327    pub(crate) async fn receive_bolt11_invoice_inner(
328        &self,
329        description: String,
330        amount_sats: Option<u64>,
331        expiry_secs: Option<u32>,
332        payment_hash: Option<String>,
333        receiver_identity_public_key: Option<String>,
334        preimage: Option<String>,
335    ) -> Result<LightningReceivePayment, SdkError> {
336        receive::receive_bolt11_invoice_inner(
337            self,
338            description,
339            amount_sats,
340            expiry_secs,
341            payment_hash,
342            receiver_identity_public_key,
343            preimage,
344        )
345        .await
346    }
347
348    pub(crate) async fn wait_for_incoming_payment(
349        &self,
350        identifier: WaitForPaymentIdentifier,
351        completion_timeout_secs: u32,
352    ) -> Result<Payment, SdkError> {
353        polling::wait_for_incoming_payment(self, identifier, completion_timeout_secs).await
354    }
355
356    pub(crate) async fn finalize_payment(&self, payment: Payment) -> bool {
357        polling::finalize_payment(self, payment).await
358    }
359}