Skip to main content

breez_sdk_spark/persist/
mod.rs

1pub(crate) mod backend;
2#[cfg(any(feature = "mysql", feature = "db-storage-api"))]
3pub mod mysql;
4pub(crate) mod path;
5#[cfg(any(feature = "postgres", feature = "db-storage-api"))]
6pub mod postgres;
7#[cfg(feature = "sqlite")]
8pub(crate) mod sqlite;
9
10// The `sqlite`, `postgres` and `mysql` storage backends use native-only Rust
11// drivers and cannot be built for the wasm32 target. WASM builds use a
12// JS-backed storage backend instead, so none of these features apply there.
13#[cfg(all(
14    any(feature = "sqlite", feature = "postgres", feature = "mysql"),
15    target_family = "wasm",
16    target_os = "unknown"
17))]
18compile_error!(
19    "the `sqlite`, `postgres` and `mysql` storage features are native-only and \
20     cannot be enabled for the wasm32 target"
21);
22
23use std::{collections::HashMap, sync::Arc};
24
25use macros::async_trait;
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29use crate::{
30    AssetFilter, Contact, ConversionInfo, ConversionStatus, DepositClaimError, DepositInfo,
31    InstantClaimStatus, LightningAddressInfo, ListContactsRequest, ListPaymentsRequest,
32    LnurlPayInfo, LnurlWithdrawInfo, MaxFee, PaymentDetailsFilter, PaymentStatus, PaymentType,
33    RefundState, SparkHtlcStatus, TokenBalance, TokenMetadata, TokenTransactionType,
34    models::Payment,
35    sync_storage::{IncomingChange, OutgoingChange, Record, UnversionedRecordChange},
36};
37
38const ACCOUNT_INFO_KEY: &str = "account_info";
39const LAST_SYNC_TIME_KEY: &str = "last_sync_time";
40const LAST_SYNCED_AT_KEY: &str = "last_synced_at";
41pub(crate) const LIGHTNING_ADDRESS_KEY: &str = "lightning_address";
42const LNURL_METADATA_UPDATED_AFTER_KEY: &str = "lnurl_metadata_updated_after";
43const SYNC_OFFSET_KEY: &str = "sync_offset";
44const TX_CACHE_KEY: &str = "tx_cache";
45// Note: the key "static_deposit_address" may still exist in storage from older versions.
46// Versioned: entries under the unversioned "token_metadata_" prefix lack `extra_metadata`.
47const TOKEN_METADATA_KEY_PREFIX: &str = "token_metadata_v2_";
48const PAYMENT_METADATA_KEY_PREFIX: &str = "payment_metadata";
49const PUBLISHED_PACKAGE_KEY_PREFIX: &str = "published_package_";
50const SPARK_PRIVATE_MODE_INITIALIZED_KEY: &str = "spark_private_mode_initialized";
51const FLASHNET_REWARDS_DELEGATION_KEY: &str = "flashnet_rewards_delegation";
52pub(crate) const STABLE_BALANCE_ACTIVE_LABEL_KEY: &str = "stable_balance_active_label";
53const PENDING_CONVERSIONS_KEY: &str = "pending_conversions";
54const PENDING_LIGHTNING_SENDS_KEY: &str = "pending_lightning_sends";
55const CONVERSION_BACKOFF_KEY: &str = "conversion_backoff";
56const RECOVERABLE_FUNDS_KEY: &str = "recoverable_funds";
57
58/// Wrapper stored in the cache that carries context about whether the value
59/// was written as part of a recovery or a client-initiated change.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub(crate) struct CachedLightningAddress {
62    pub address: Option<LightningAddressInfo>,
63    pub recovered: bool,
64}
65
66/// Parses a cached lightning address value.
67pub(crate) fn parse_cached_lightning_address(
68    value: &str,
69) -> Result<CachedLightningAddress, StorageError> {
70    serde_json::from_str(value).map_err(|e| StorageError::Serialization(e.to_string()))
71}
72
73#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
74pub enum UpdateDepositPayload {
75    ClaimError {
76        error: DepositClaimError,
77    },
78    Refund {
79        refund_txid: String,
80        refund_tx: String,
81        state: RefundState,
82    },
83    InstantClaim {
84        status: InstantClaimStatus,
85    },
86    /// Moves an existing refund between states without touching the refund
87    /// itself or the last claim error. Applies only while `refund_txid` is still
88    /// the stored refund, so a state decided against one refund cannot land on a
89    /// newer one.
90    RefundBroadcastState {
91        refund_txid: String,
92        state: RefundState,
93    },
94    /// Sets the fee ceiling standing for this deposit, which later automatic
95    /// claims run under. `None` clears it, returning the deposit to the
96    /// configured ceiling.
97    MaxClaimFee {
98        max_fee: Option<MaxFee>,
99    },
100}
101
102/// A static deposit address being watched on-chain for unconfirmed deposits.
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
105pub struct WatchedDepositAddress {
106    pub address: String,
107    /// When the address was handed out, in seconds since the epoch. The watch
108    /// window is measured from here.
109    pub issued_at: u64,
110    /// Whether a deposit to it has been seen unconfirmed.
111    pub seen: bool,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
115#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
116pub enum UpdateWatchedAddressPayload {
117    /// Starts watching the address, or restarts the window on one already
118    /// watched, clearing `seen`.
119    Watch { issued_at: u64 },
120    /// Records that a deposit to it has been seen unconfirmed.
121    Seen,
122    /// Stops watching it, removing the row. Applies only while `issued_at` is
123    /// still the stored value, so an address handed out again since it was read
124    /// is not retired by a decision taken before that.
125    Unwatch { issued_at: u64 },
126}
127
128/// A transaction the chain service reported in a block.
129#[derive(Debug, Clone, PartialEq, Eq)]
130#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
131pub struct ChainTransaction {
132    pub txid: String,
133    pub block_height: u32,
134}
135
136/// The on-chain output holding a leaf's funds after a watchtower exit.
137#[derive(Debug, Clone, PartialEq, Eq)]
138#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
139pub struct StoredWatchtowerExitOutput {
140    pub txid: String,
141    pub vout: u32,
142    pub amount_sats: u64,
143    pub script_pubkey: String,
144    /// The block the output's transaction is in.
145    pub block_height: u32,
146}
147
148/// A transaction the Spark operators co-signed, with a
149/// [`StoredWatchtowerExitOutput`] as its input.
150#[derive(Debug, Clone, PartialEq, Eq)]
151#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
152pub struct WatchtowerExitRecovery {
153    pub txid: String,
154    pub transaction_hex: String,
155    /// The amount of the transaction's output. Its fee is its input's amount less this.
156    pub output_amount_sats: u64,
157}
158
159/// What is stored about a leaf with funds to recover on-chain.
160#[derive(Debug, Clone, PartialEq, Eq)]
161#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
162pub struct LeafRecovery {
163    pub leaf_id: String,
164    /// When the SDK last completed a check of the leaf's on-chain state with
165    /// the chain service, in seconds since the epoch. Unset while it has
166    /// completed none.
167    pub chain_checked_at: Option<u64>,
168    pub watchtower_exit_output: Option<StoredWatchtowerExitOutput>,
169    /// The co-signed recoveries of `watchtower_exit_output`, ordered by txid.
170    pub watchtower_exit_recoveries: Vec<WatchtowerExitRecovery>,
171    /// The spend of `watchtower_exit_output`, once it is in a block.
172    pub watchtower_exit_spend: Option<ChainTransaction>,
173    /// The sweep of the leaf's refund, once it is in a block.
174    pub unilateral_exit_sweep: Option<ChainTransaction>,
175}
176
177/// A change to a stored [`LeafRecovery`]. The storage keeps what it holds for a
178/// part left unset.
179#[derive(Debug, Clone, Default, PartialEq, Eq)]
180#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
181pub struct UpdateLeafRecovery {
182    pub leaf_id: String,
183    /// The storage keeps the later of this time and the one it holds.
184    pub chain_checked_at: Option<u64>,
185    /// The storage replaces the output it holds with this one. When this one
186    /// is at another txid or vout, the storage also removes the recoveries and
187    /// the spend it holds, which belong to the replaced output.
188    pub watchtower_exit_output: Option<StoredWatchtowerExitOutput>,
189    /// The storage adds this recovery unless it holds one with the same txid.
190    pub watchtower_exit_recovery: Option<WatchtowerExitRecovery>,
191    /// The storage replaces the spend it holds with this one.
192    pub watchtower_exit_spend: Option<ChainTransaction>,
193    /// The storage replaces the sweep it holds with this one.
194    pub unilateral_exit_sweep: Option<ChainTransaction>,
195}
196
197#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
198pub struct SetLnurlMetadataItem {
199    pub payment_hash: String,
200    pub sender_comment: Option<String>,
201    pub nostr_zap_request: Option<String>,
202    pub nostr_zap_receipt: Option<String>,
203    pub lightning_address: Option<String>,
204}
205
206impl From<lnurl_models::ListMetadataMetadata> for SetLnurlMetadataItem {
207    fn from(value: lnurl_models::ListMetadataMetadata) -> Self {
208        SetLnurlMetadataItem {
209            payment_hash: value.payment_hash,
210            sender_comment: value.sender_comment,
211            nostr_zap_request: value.nostr_zap_request,
212            nostr_zap_receipt: value.nostr_zap_receipt,
213            lightning_address: value.lightning_address,
214        }
215    }
216}
217
218/// Errors that can occur during storage operations
219#[derive(Debug, Error, Clone)]
220#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
221pub enum StorageError {
222    /// Connection-related errors (pool exhaustion, timeouts, connection refused).
223    /// These are often transient and may be retried.
224    #[error("Connection error: {0}")]
225    Connection(String),
226
227    #[error("Underlying implementation error: {0}")]
228    Implementation(String),
229
230    /// Database initialization error
231    #[error("Failed to initialize database: {0}")]
232    InitializationError(String),
233
234    #[error("Failed to serialize/deserialize data: {0}")]
235    Serialization(String),
236
237    #[error("Not found")]
238    NotFound,
239}
240
241impl From<serde_json::Error> for StorageError {
242    fn from(e: serde_json::Error) -> Self {
243        StorageError::Serialization(e.to_string())
244    }
245}
246
247impl From<std::num::TryFromIntError> for StorageError {
248    fn from(e: std::num::TryFromIntError) -> Self {
249        StorageError::Implementation(format!("integer overflow: {e}"))
250    }
251}
252
253/// Selects payments by conversion type + status for background tasks.
254#[derive(Debug, Clone)]
255#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
256pub enum ConversionFilter {
257    /// AMM conversions that need a refund (clawback).
258    AmmRefundNeeded,
259    /// Orchestra orders that have not yet reached a terminal state.
260    OrchestraPending,
261    /// Boltz reverse swaps that have not yet reached a terminal state. Lives on
262    /// the Lightning leg (the hold-invoice pay), so it is selected via the
263    /// [`StoragePaymentDetailsFilter::Lightning`] filter.
264    BoltzPending,
265}
266
267/// Storage-internal variant of [`PaymentDetailsFilter`].
268#[derive(Debug, Clone)]
269#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
270pub enum StoragePaymentDetailsFilter {
271    Spark {
272        htlc_status: Option<Vec<SparkHtlcStatus>>,
273        conversion_filter: Option<ConversionFilter>,
274    },
275    Token {
276        conversion_filter: Option<ConversionFilter>,
277        tx_hash: Option<String>,
278        tx_type: Option<TokenTransactionType>,
279    },
280    Lightning {
281        htlc_status: Option<Vec<SparkHtlcStatus>>,
282        conversion_filter: Option<ConversionFilter>,
283    },
284}
285
286impl From<PaymentDetailsFilter> for StoragePaymentDetailsFilter {
287    fn from(filter: PaymentDetailsFilter) -> Self {
288        match filter {
289            PaymentDetailsFilter::Spark {
290                htlc_status,
291                conversion_refund_needed,
292            } => StoragePaymentDetailsFilter::Spark {
293                htlc_status,
294                conversion_filter: conversion_refund_needed
295                    .and_then(|v| v.then_some(ConversionFilter::AmmRefundNeeded)),
296            },
297            PaymentDetailsFilter::Token {
298                conversion_refund_needed,
299                tx_hash,
300                tx_type,
301            } => StoragePaymentDetailsFilter::Token {
302                conversion_filter: conversion_refund_needed
303                    .and_then(|v| v.then_some(ConversionFilter::AmmRefundNeeded)),
304                tx_hash,
305                tx_type,
306            },
307            PaymentDetailsFilter::Lightning { htlc_status } => {
308                StoragePaymentDetailsFilter::Lightning {
309                    htlc_status,
310                    conversion_filter: None,
311                }
312            }
313        }
314    }
315}
316
317impl From<StoragePaymentDetailsFilter> for PaymentDetailsFilter {
318    fn from(filter: StoragePaymentDetailsFilter) -> Self {
319        match filter {
320            StoragePaymentDetailsFilter::Spark {
321                htlc_status,
322                conversion_filter,
323            } => PaymentDetailsFilter::Spark {
324                htlc_status,
325                conversion_refund_needed: conversion_filter
326                    .map(|f| matches!(f, ConversionFilter::AmmRefundNeeded)),
327            },
328            StoragePaymentDetailsFilter::Token {
329                conversion_filter,
330                tx_hash,
331                tx_type,
332            } => PaymentDetailsFilter::Token {
333                conversion_refund_needed: conversion_filter
334                    .map(|f| matches!(f, ConversionFilter::AmmRefundNeeded)),
335                tx_hash,
336                tx_type,
337            },
338            StoragePaymentDetailsFilter::Lightning { htlc_status, .. } => {
339                PaymentDetailsFilter::Lightning { htlc_status }
340            }
341        }
342    }
343}
344
345/// Storage-internal variant of [`ListPaymentsRequest`] that uses
346/// [`StoragePaymentDetailsFilter`] instead of the public [`PaymentDetailsFilter`].
347#[derive(Debug, Clone, Default)]
348#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
349pub struct StorageListPaymentsRequest {
350    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
351    pub type_filter: Option<Vec<PaymentType>>,
352    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
353    pub status_filter: Option<Vec<PaymentStatus>>,
354    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
355    pub asset_filter: Option<AssetFilter>,
356    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
357    pub payment_details_filter: Option<Vec<StoragePaymentDetailsFilter>>,
358    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
359    pub from_timestamp: Option<u64>,
360    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
361    pub to_timestamp: Option<u64>,
362    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
363    pub offset: Option<u32>,
364    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
365    pub limit: Option<u32>,
366    #[cfg_attr(feature = "uniffi", uniffi(default=None))]
367    pub sort_ascending: Option<bool>,
368}
369
370impl From<ListPaymentsRequest> for StorageListPaymentsRequest {
371    fn from(request: ListPaymentsRequest) -> Self {
372        StorageListPaymentsRequest {
373            type_filter: request.type_filter,
374            status_filter: request.status_filter,
375            asset_filter: request.asset_filter,
376            payment_details_filter: request
377                .payment_details_filter
378                .map(|filters| filters.into_iter().map(Into::into).collect()),
379            from_timestamp: request.from_timestamp,
380            to_timestamp: request.to_timestamp,
381            offset: request.offset,
382            limit: request.limit,
383            sort_ascending: request.sort_ascending,
384        }
385    }
386}
387
388impl From<StorageListPaymentsRequest> for ListPaymentsRequest {
389    fn from(request: StorageListPaymentsRequest) -> Self {
390        ListPaymentsRequest {
391            type_filter: request.type_filter,
392            status_filter: request.status_filter,
393            asset_filter: request.asset_filter,
394            payment_details_filter: request
395                .payment_details_filter
396                .map(|filters| filters.into_iter().map(Into::into).collect()),
397            from_timestamp: request.from_timestamp,
398            to_timestamp: request.to_timestamp,
399            offset: request.offset,
400            limit: request.limit,
401            sort_ascending: request.sort_ascending,
402        }
403    }
404}
405
406/// Metadata associated with a payment that cannot be extracted from the Spark operator.
407#[derive(Clone, Default, Deserialize, Serialize)]
408#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
409pub struct PaymentMetadata {
410    #[serde(skip_serializing_if = "Option::is_none")]
411    pub parent_payment_id: Option<String>,
412    #[serde(skip_serializing_if = "Option::is_none")]
413    pub lnurl_pay_info: Option<LnurlPayInfo>,
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub lnurl_withdraw_info: Option<LnurlWithdrawInfo>,
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub lnurl_description: Option<String>,
418    /// Conversion info for this payment. Defaults `"type"` to `"amm"` when the
419    /// tag is missing (pre-migration sync records).
420    #[serde(
421        skip_serializing_if = "Option::is_none",
422        deserialize_with = "deserialize_conversion_info_with_default_type",
423        default
424    )]
425    pub conversion_info: Option<ConversionInfo>,
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub conversion_status: Option<ConversionStatus>,
428}
429
430#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
431pub(crate) fn parse_payment_status(value: &str) -> Result<PaymentStatus, StorageError> {
432    value
433        .parse()
434        .map_err(|e| StorageError::Implementation(format!("invalid payment status: {e}")))
435}
436
437/// Deserializes `ConversionInfo` leniently — ensures the `"type"` tag exists
438/// (defaulting to `"amm"` for pre-migration sync records), then deserializes.
439/// The `entry().or_insert_with()` is a no-op hash lookup when the tag already
440/// exists, so the happy path has minimal overhead beyond the `Value` intermediary.
441fn deserialize_conversion_info_with_default_type<'de, D>(
442    deserializer: D,
443) -> Result<Option<ConversionInfo>, D::Error>
444where
445    D: serde::Deserializer<'de>,
446{
447    use serde::de::Deserialize;
448
449    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
450    match value {
451        None => Ok(None),
452        Some(mut v) => {
453            if let Some(obj) = v.as_object_mut() {
454                obj.entry("type")
455                    .or_insert_with(|| serde_json::Value::String("amm".to_string()));
456            }
457            match serde_json::from_value::<ConversionInfo>(v) {
458                Ok(info) => Ok(Some(info)),
459                Err(_) => Ok(None),
460            }
461        }
462    }
463}
464
465/// A cross-chain swap row as persisted and synced. Shared across providers
466/// (Boltz, Orchestra, future) so each provider's adapter writes opaque
467/// JSON into `data` and (optionally) opaque ciphertext into `secrets`.
468///
469/// For providers with money-critical secrets, the adapter lifts them out of
470/// the swap JSON, ECIES-encrypts them, and carries only the ciphertext in
471/// `secrets`. The storage layer treats both fields as opaque, so it needs
472/// no signer.
473#[derive(Debug, Clone, Serialize, Deserialize)]
474#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
475#[serde(rename_all = "camelCase")]
476pub struct StoredCrossChainSwap {
477    /// Provider tag (e.g. `"boltz"`, `"orchestra"`).
478    pub provider: String,
479    /// Provider-scoped swap id (boltz swap id, orchestra quote-or-order id).
480    pub id: String,
481    /// Lifted from the underlying swap's terminal flag into an indexed column
482    /// so `list_active_cross_chain_swaps` filters without parsing `data`.
483    pub is_terminal: bool,
484    /// Lifted from the underlying swap's `updated_at` into a column so the
485    /// row's freshness is inspectable without parsing `data`.
486    pub updated_at: u64,
487    /// Serialized JSON owned by the cross-chain provider's storage adapter.
488    pub data: String,
489    /// Base64 of the ECIES ciphertext of the provider's lifted secrets.
490    /// Empty for providers with no money-critical secrets to protect at rest.
491    pub secrets: String,
492}
493
494/// Trait for persistent storage
495#[cfg_attr(feature = "uniffi", uniffi::export(with_foreign))]
496#[async_trait]
497pub trait Storage: Send + Sync {
498    async fn delete_cached_item(&self, key: String) -> Result<(), StorageError>;
499    async fn get_cached_item(&self, key: String) -> Result<Option<String>, StorageError>;
500    async fn set_cached_item(&self, key: String, value: String) -> Result<(), StorageError>;
501    /// Lists payments with optional filters and pagination
502    ///
503    /// # Arguments
504    ///
505    /// * `list_payments_request` - The request to list payments
506    ///
507    /// # Returns
508    ///
509    /// A vector of payments or a `StorageError`
510    async fn list_payments(
511        &self,
512        request: StorageListPaymentsRequest,
513    ) -> Result<Vec<Payment>, StorageError>;
514
515    /// Inserts or updates a payment unless it would replace a terminal status.
516    ///
517    /// Same-status updates are still persisted so details can be enriched.
518    ///
519    /// Returns `true` if the caller should emit a payment event (new payment was
520    /// inserted, or status transitioned). Returns `false` for redundant
521    /// same-status updates and for rejected updates against a terminal stored
522    /// status
523    async fn apply_payment_update(&self, payment: Payment) -> Result<bool, StorageError>;
524
525    /// Inserts payment metadata into storage
526    ///
527    /// # Arguments
528    ///
529    /// * `payment_id` - The ID of the payment
530    /// * `metadata` - The metadata to insert
531    ///
532    /// # Returns
533    ///
534    /// Success or a `StorageError`
535    async fn insert_payment_metadata(
536        &self,
537        payment_id: String,
538        metadata: PaymentMetadata,
539    ) -> Result<(), StorageError>;
540
541    /// Gets a payment by its ID
542    /// # Arguments
543    ///
544    /// * `id` - The ID of the payment to retrieve
545    ///
546    /// # Returns
547    ///
548    /// The payment if found or None if not found
549    async fn get_payment_by_id(&self, id: String) -> Result<Payment, StorageError>;
550
551    /// Gets a payment by its invoice
552    /// # Arguments
553    ///
554    /// * `invoice` - The invoice of the payment to retrieve
555    /// # Returns
556    ///
557    /// The payment if found or None if not found
558    async fn get_payment_by_invoice(
559        &self,
560        invoice: String,
561    ) -> Result<Option<Payment>, StorageError>;
562
563    /// Gets payments that have any of the specified parent payment IDs.
564    /// Used to load related payments for a set of parent payments.
565    ///
566    /// # Arguments
567    ///
568    /// * `parent_payment_ids` - The IDs of the parent payments
569    ///
570    /// # Returns
571    ///
572    /// A map of `parent_payment_id` -> Vec<Payment> or a `StorageError`
573    async fn get_payments_by_parent_ids(
574        &self,
575        parent_payment_ids: Vec<String>,
576    ) -> Result<HashMap<String, Vec<Payment>>, StorageError>;
577
578    /// Add a deposit to storage (upsert: updates `is_mature` and `amount_sats` on conflict)
579    /// # Arguments
580    ///
581    /// * `txid` - The transaction ID of the deposit
582    /// * `vout` - The output index of the deposit
583    /// * `amount_sats` - The amount of the deposit in sats
584    /// * `is_mature` - Whether the deposit UTXO has enough confirmations to be claimable
585    ///
586    /// # Returns
587    ///
588    /// Success or a `StorageError`
589    async fn add_deposit(
590        &self,
591        txid: String,
592        vout: u32,
593        amount_sats: u64,
594        is_mature: bool,
595    ) -> Result<(), StorageError>;
596
597    /// Removes an unclaimed deposit from storage
598    /// # Arguments
599    ///
600    /// * `txid` - The transaction ID of the deposit
601    /// * `vout` - The output index of the deposit
602    ///
603    /// # Returns
604    ///
605    /// Success or a `StorageError`
606    async fn delete_deposit(&self, txid: String, vout: u32) -> Result<(), StorageError>;
607
608    /// Lists all unclaimed deposits from storage
609    /// # Returns
610    ///
611    /// A vector of `DepositInfo` or a `StorageError`
612    async fn list_deposits(&self) -> Result<Vec<DepositInfo>, StorageError>;
613
614    /// Updates or inserts unclaimed deposit details
615    /// # Arguments
616    ///
617    /// * `txid` - The transaction ID of the deposit
618    /// * `vout` - The output index of the deposit
619    /// * `payload` - The payload for the update
620    ///
621    /// # Returns
622    ///
623    /// Success or a `StorageError`
624    async fn update_deposit(
625        &self,
626        txid: String,
627        vout: u32,
628        payload: UpdateDepositPayload,
629    ) -> Result<(), StorageError>;
630
631    /// Lists the deposit addresses currently being watched for unconfirmed
632    /// deposits, most recently issued first.
633    async fn list_watched_deposit_addresses(
634        &self,
635    ) -> Result<Vec<WatchedDepositAddress>, StorageError>;
636
637    /// Applies one change to a watched deposit address. `Watch` inserts or
638    /// restarts it, `Seen` marks it, and `Unwatch` removes it.
639    async fn update_watched_deposit_address(
640        &self,
641        address: String,
642        payload: UpdateWatchedAddressPayload,
643    ) -> Result<(), StorageError>;
644
645    /// Lists every stored leaf recovery, ordered by leaf id.
646    async fn list_leaf_recoveries(&self) -> Result<Vec<LeafRecovery>, StorageError>;
647
648    /// Stores a leaf recovery when the leaf has none, then applies the parts of
649    /// `update` that are set, all in one atomic write. A txid has one block
650    /// height: the one given last.
651    async fn update_leaf_recovery(&self, update: UpdateLeafRecovery) -> Result<(), StorageError>;
652
653    async fn set_lnurl_metadata(
654        &self,
655        metadata: Vec<SetLnurlMetadataItem>,
656    ) -> Result<(), StorageError>;
657
658    /// Lists contacts from storage with optional pagination
659    async fn list_contacts(
660        &self,
661        request: ListContactsRequest,
662    ) -> Result<Vec<Contact>, StorageError>;
663
664    /// Gets a single contact by its ID
665    async fn get_contact(&self, id: String) -> Result<Contact, StorageError>;
666
667    /// Inserts or updates a contact in storage (upsert by id).
668    /// Preserves `created_at` on update.
669    async fn insert_contact(&self, contact: Contact) -> Result<(), StorageError>;
670
671    /// Deletes a contact by its ID
672    async fn delete_contact(&self, id: String) -> Result<(), StorageError>;
673
674    /// Inserts or overwrites a cross-chain swap row (upsert by `(provider, id)`).
675    async fn set_cross_chain_swap(&self, swap: StoredCrossChainSwap) -> Result<(), StorageError>;
676
677    /// Gets a single cross-chain swap row by its `(provider, id)`, or `None` if absent.
678    async fn get_cross_chain_swap(
679        &self,
680        provider: String,
681        id: String,
682    ) -> Result<Option<StoredCrossChainSwap>, StorageError>;
683
684    /// Lists all non-terminal cross-chain swap rows for a single provider
685    /// (`provider = ? AND is_terminal = false`).
686    async fn list_active_cross_chain_swaps(
687        &self,
688        provider: String,
689    ) -> Result<Vec<StoredCrossChainSwap>, StorageError>;
690
691    // Sync storage methods
692    async fn add_outgoing_change(
693        &self,
694        record: UnversionedRecordChange,
695    ) -> Result<u64, StorageError>;
696    async fn complete_outgoing_sync(
697        &self,
698        record: Record,
699        local_revision: u64,
700    ) -> Result<(), StorageError>;
701    async fn get_pending_outgoing_changes(
702        &self,
703        limit: u32,
704    ) -> Result<Vec<OutgoingChange>, StorageError>;
705
706    /// Get the last committed sync revision.
707    ///
708    /// The `sync_revision` table tracks the highest revision that has been committed
709    /// (i.e. acknowledged by the server or received from it). It does NOT include
710    /// pending outgoing queue ids. This value is used by the sync protocol to
711    /// request changes from the server.
712    async fn get_last_revision(&self) -> Result<u64, StorageError>;
713
714    /// Insert incoming records from remote sync
715    async fn insert_incoming_records(&self, records: Vec<Record>) -> Result<(), StorageError>;
716
717    /// Delete an incoming record after it has been processed
718    async fn delete_incoming_record(&self, record: Record) -> Result<(), StorageError>;
719
720    /// Get incoming records that need to be processed, up to the specified limit
721    async fn get_incoming_records(&self, limit: u32) -> Result<Vec<IncomingChange>, StorageError>;
722
723    /// Get the latest outgoing record if any exists
724    async fn get_latest_outgoing_change(&self) -> Result<Option<OutgoingChange>, StorageError>;
725
726    /// Update the sync state record from an incoming record
727    async fn update_record_from_incoming(&self, record: Record) -> Result<(), StorageError>;
728}
729
730pub(crate) struct ObjectCacheRepository {
731    storage: Arc<dyn Storage>,
732}
733
734impl ObjectCacheRepository {
735    pub(crate) fn new(storage: Arc<dyn Storage>) -> Self {
736        ObjectCacheRepository { storage }
737    }
738
739    pub(crate) async fn save_account_info(
740        &self,
741        value: &CachedAccountInfo,
742    ) -> Result<(), StorageError> {
743        self.storage
744            .set_cached_item(ACCOUNT_INFO_KEY.to_string(), serde_json::to_string(value)?)
745            .await?;
746        Ok(())
747    }
748
749    pub(crate) async fn fetch_account_info(
750        &self,
751    ) -> Result<Option<CachedAccountInfo>, StorageError> {
752        let value = self
753            .storage
754            .get_cached_item(ACCOUNT_INFO_KEY.to_string())
755            .await?;
756        match value {
757            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
758            None => Ok(None),
759        }
760    }
761
762    pub(crate) async fn save_sync_info(&self, value: &CachedSyncInfo) -> Result<(), StorageError> {
763        self.storage
764            .set_cached_item(SYNC_OFFSET_KEY.to_string(), serde_json::to_string(value)?)
765            .await?;
766        Ok(())
767    }
768
769    pub(crate) async fn fetch_sync_info(&self) -> Result<Option<CachedSyncInfo>, StorageError> {
770        let value = self
771            .storage
772            .get_cached_item(SYNC_OFFSET_KEY.to_string())
773            .await?;
774        match value {
775            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
776            None => Ok(None),
777        }
778    }
779
780    /// Records a successfully published signed package under its package id
781    /// (swap transfer id or token partial-transaction digest), mapping to the
782    /// resulting payment id ("swap" for swap packages), so a replayed publish
783    /// can answer without re-submitting.
784    pub(crate) async fn save_published_package(
785        &self,
786        package_id: &str,
787        payment_id: &str,
788    ) -> Result<(), StorageError> {
789        self.storage
790            .set_cached_item(
791                format!("{PUBLISHED_PACKAGE_KEY_PREFIX}{package_id}"),
792                payment_id.to_string(),
793            )
794            .await?;
795        Ok(())
796    }
797
798    pub(crate) async fn fetch_published_package(
799        &self,
800        package_id: &str,
801    ) -> Result<Option<String>, StorageError> {
802        self.storage
803            .get_cached_item(format!("{PUBLISHED_PACKAGE_KEY_PREFIX}{package_id}"))
804            .await
805    }
806
807    pub(crate) async fn save_recoverable_funds(&self, sats: u64) -> Result<(), StorageError> {
808        self.storage
809            .set_cached_item(RECOVERABLE_FUNDS_KEY.to_string(), sats.to_string())
810            .await
811    }
812
813    pub(crate) async fn fetch_recoverable_funds(&self) -> Result<Option<u64>, StorageError> {
814        let value = self
815            .storage
816            .get_cached_item(RECOVERABLE_FUNDS_KEY.to_string())
817            .await?;
818        match value {
819            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
820            None => Ok(None),
821        }
822    }
823
824    pub(crate) async fn save_tx(&self, txid: &str, value: &CachedTx) -> Result<(), StorageError> {
825        self.storage
826            .set_cached_item(
827                format!("{TX_CACHE_KEY}-{txid}"),
828                serde_json::to_string(value)?,
829            )
830            .await?;
831        Ok(())
832    }
833
834    pub(crate) async fn delete_tx(&self, txid: &str) -> Result<(), StorageError> {
835        self.storage
836            .delete_cached_item(format!("{TX_CACHE_KEY}-{txid}"))
837            .await
838    }
839
840    pub(crate) async fn fetch_tx(&self, txid: &str) -> Result<Option<CachedTx>, StorageError> {
841        let value = self
842            .storage
843            .get_cached_item(format!("{TX_CACHE_KEY}-{txid}"))
844            .await?;
845        match value {
846            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
847            None => Ok(None),
848        }
849    }
850
851    pub(crate) async fn save_lightning_address(
852        &self,
853        value: &LightningAddressInfo,
854        recovered: bool,
855    ) -> Result<(), StorageError> {
856        let cached = CachedLightningAddress {
857            address: Some(value.clone()),
858            recovered,
859        };
860        self.storage
861            .set_cached_item(
862                LIGHTNING_ADDRESS_KEY.to_string(),
863                serde_json::to_string(&cached)?,
864            )
865            .await?;
866        Ok(())
867    }
868
869    /// Marks the lightning address as "no address registered" by storing `None`.
870    pub(crate) async fn delete_lightning_address(
871        &self,
872        recovered: bool,
873    ) -> Result<(), StorageError> {
874        let cached = CachedLightningAddress {
875            address: None,
876            recovered,
877        };
878        self.storage
879            .set_cached_item(
880                LIGHTNING_ADDRESS_KEY.to_string(),
881                serde_json::to_string(&cached)?,
882            )
883            .await?;
884        Ok(())
885    }
886
887    /// Returns:
888    /// - `Ok(None)` — key absent, never recovered
889    /// - `Ok(Some(None))` — recovered, no address registered
890    /// - `Ok(Some(Some(info)))` — recovered, has address
891    pub(crate) async fn fetch_lightning_address(
892        &self,
893    ) -> Result<Option<Option<LightningAddressInfo>>, StorageError> {
894        let value = self
895            .storage
896            .get_cached_item(LIGHTNING_ADDRESS_KEY.to_string())
897            .await?;
898        match value {
899            Some(value) => {
900                let cached = parse_cached_lightning_address(&value)?;
901                Ok(Some(cached.address))
902            }
903            None => Ok(None),
904        }
905    }
906
907    pub(crate) async fn save_token_metadata(
908        &self,
909        value: &TokenMetadata,
910    ) -> Result<(), StorageError> {
911        self.storage
912            .set_cached_item(
913                format!("{TOKEN_METADATA_KEY_PREFIX}{}", value.identifier),
914                serde_json::to_string(value)?,
915            )
916            .await?;
917        Ok(())
918    }
919
920    pub(crate) async fn fetch_token_metadata(
921        &self,
922        identifier: &str,
923    ) -> Result<Option<TokenMetadata>, StorageError> {
924        let value = self
925            .storage
926            .get_cached_item(format!("{TOKEN_METADATA_KEY_PREFIX}{identifier}"))
927            .await?;
928        match value {
929            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
930            None => Ok(None),
931        }
932    }
933
934    pub(crate) async fn save_payment_metadata(
935        &self,
936        identifier: &str,
937        value: &PaymentMetadata,
938    ) -> Result<(), StorageError> {
939        self.storage
940            .set_cached_item(
941                format!("{PAYMENT_METADATA_KEY_PREFIX}-{identifier}"),
942                serde_json::to_string(value)?,
943            )
944            .await?;
945        Ok(())
946    }
947
948    pub(crate) async fn fetch_payment_metadata(
949        &self,
950        identifier: &str,
951    ) -> Result<Option<PaymentMetadata>, StorageError> {
952        let value = self
953            .storage
954            .get_cached_item(format!("{PAYMENT_METADATA_KEY_PREFIX}-{identifier}"))
955            .await?;
956        match value {
957            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
958            None => Ok(None),
959        }
960    }
961
962    pub(crate) async fn delete_payment_metadata(
963        &self,
964        identifier: &str,
965    ) -> Result<(), StorageError> {
966        self.storage
967            .delete_cached_item(format!("{PAYMENT_METADATA_KEY_PREFIX}-{identifier}"))
968            .await?;
969        Ok(())
970    }
971
972    pub(crate) async fn save_spark_private_mode_initialized(&self) -> Result<(), StorageError> {
973        self.storage
974            .set_cached_item(
975                SPARK_PRIVATE_MODE_INITIALIZED_KEY.to_string(),
976                "true".to_string(),
977            )
978            .await?;
979        Ok(())
980    }
981
982    pub(crate) async fn fetch_spark_private_mode_initialized(&self) -> Result<bool, StorageError> {
983        let value = self
984            .storage
985            .get_cached_item(SPARK_PRIVATE_MODE_INITIALIZED_KEY.to_string())
986            .await?;
987        match value {
988            Some(value) => Ok(value == "true"),
989            None => Ok(false),
990        }
991    }
992
993    pub(crate) async fn save_rewards_delegation(
994        &self,
995        value: &CachedRewardsDelegation,
996    ) -> Result<(), StorageError> {
997        self.storage
998            .set_cached_item(
999                FLASHNET_REWARDS_DELEGATION_KEY.to_string(),
1000                serde_json::to_string(value)?,
1001            )
1002            .await?;
1003        Ok(())
1004    }
1005
1006    pub(crate) async fn fetch_rewards_delegation(
1007        &self,
1008    ) -> Result<Option<CachedRewardsDelegation>, StorageError> {
1009        let value = self
1010            .storage
1011            .get_cached_item(FLASHNET_REWARDS_DELEGATION_KEY.to_string())
1012            .await?;
1013        match value {
1014            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
1015            None => Ok(None),
1016        }
1017    }
1018
1019    pub(crate) async fn save_stable_balance_active_label(
1020        &self,
1021        label: &str,
1022    ) -> Result<(), StorageError> {
1023        self.storage
1024            .set_cached_item(
1025                STABLE_BALANCE_ACTIVE_LABEL_KEY.to_string(),
1026                label.to_string(),
1027            )
1028            .await
1029    }
1030
1031    pub(crate) async fn fetch_stable_balance_active_label(
1032        &self,
1033    ) -> Result<Option<String>, StorageError> {
1034        self.storage
1035            .get_cached_item(STABLE_BALANCE_ACTIVE_LABEL_KEY.to_string())
1036            .await
1037    }
1038
1039    /// Records that the user turned stable balance off. Stored as an empty
1040    /// label rather than deleted, so a configured default does not turn it
1041    /// back on at the next start.
1042    pub(crate) async fn save_stable_balance_deactivated(&self) -> Result<(), StorageError> {
1043        self.save_stable_balance_active_label("").await
1044    }
1045
1046    /// Records a Lightning send whose preimage swap is about to be committed
1047    /// with the operators. Written before that commit so a send interrupted
1048    /// before the SSP is asked to pay can still be resumed: the invoice is the
1049    /// one thing neither the operators nor the SSP can tell us afterwards.
1050    pub(crate) async fn save_pending_lightning_sends(
1051        &self,
1052        pending: &[super::sdk::PendingLightningSend],
1053    ) -> Result<(), StorageError> {
1054        self.storage
1055            .set_cached_item(
1056                PENDING_LIGHTNING_SENDS_KEY.to_string(),
1057                serde_json::to_string(pending)?,
1058            )
1059            .await?;
1060        Ok(())
1061    }
1062
1063    pub(crate) async fn fetch_pending_lightning_sends(
1064        &self,
1065    ) -> Result<Vec<super::sdk::PendingLightningSend>, StorageError> {
1066        let value = self
1067            .storage
1068            .get_cached_item(PENDING_LIGHTNING_SENDS_KEY.to_string())
1069            .await?;
1070        match value {
1071            Some(value) => Ok(serde_json::from_str(&value)?),
1072            None => Ok(Vec::new()),
1073        }
1074    }
1075
1076    pub(crate) async fn save_pending_conversions(
1077        &self,
1078        pending: &super::stable_balance::PendingQueue,
1079    ) -> Result<(), StorageError> {
1080        self.storage
1081            .set_cached_item(
1082                PENDING_CONVERSIONS_KEY.to_string(),
1083                serde_json::to_string(pending)?,
1084            )
1085            .await?;
1086        Ok(())
1087    }
1088
1089    pub(crate) async fn fetch_pending_conversions(
1090        &self,
1091    ) -> Result<Option<super::stable_balance::PendingQueue>, StorageError> {
1092        let value = self
1093            .storage
1094            .get_cached_item(PENDING_CONVERSIONS_KEY.to_string())
1095            .await?;
1096        match value {
1097            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
1098            None => Ok(None),
1099        }
1100    }
1101
1102    pub(crate) async fn delete_pending_conversions(&self) -> Result<(), StorageError> {
1103        self.storage
1104            .delete_cached_item(PENDING_CONVERSIONS_KEY.to_string())
1105            .await
1106    }
1107
1108    pub(crate) async fn save_conversion_backoff(
1109        &self,
1110        backoff: &super::stable_balance::ConversionBackoff,
1111    ) -> Result<(), StorageError> {
1112        self.storage
1113            .set_cached_item(
1114                CONVERSION_BACKOFF_KEY.to_string(),
1115                serde_json::to_string(backoff)?,
1116            )
1117            .await?;
1118        Ok(())
1119    }
1120
1121    pub(crate) async fn fetch_conversion_backoff(
1122        &self,
1123    ) -> Result<Option<super::stable_balance::ConversionBackoff>, StorageError> {
1124        let value = self
1125            .storage
1126            .get_cached_item(CONVERSION_BACKOFF_KEY.to_string())
1127            .await?;
1128        match value {
1129            Some(value) => Ok(Some(serde_json::from_str(&value)?)),
1130            None => Ok(None),
1131        }
1132    }
1133
1134    pub(crate) async fn delete_conversion_backoff(&self) -> Result<(), StorageError> {
1135        self.storage
1136            .delete_cached_item(CONVERSION_BACKOFF_KEY.to_string())
1137            .await
1138    }
1139
1140    pub(crate) async fn save_lnurl_metadata_updated_after(
1141        &self,
1142        offset: i64,
1143    ) -> Result<(), StorageError> {
1144        self.storage
1145            .set_cached_item(
1146                LNURL_METADATA_UPDATED_AFTER_KEY.to_string(),
1147                offset.to_string(),
1148            )
1149            .await?;
1150        Ok(())
1151    }
1152
1153    pub(crate) async fn fetch_lnurl_metadata_updated_after(&self) -> Result<i64, StorageError> {
1154        let value = self
1155            .storage
1156            .get_cached_item(LNURL_METADATA_UPDATED_AFTER_KEY.to_string())
1157            .await?;
1158        match value {
1159            Some(value) => Ok(value.parse().map_err(|_| {
1160                StorageError::Serialization("invalid lnurl_metadata_updated_after".to_string())
1161            })?),
1162            None => Ok(0),
1163        }
1164    }
1165
1166    pub(crate) async fn get_last_sync_time(&self) -> Result<Option<u64>, StorageError> {
1167        let value = self
1168            .storage
1169            .get_cached_item(LAST_SYNC_TIME_KEY.to_string())
1170            .await?;
1171        match value {
1172            Some(v) => Ok(Some(v.parse().map_err(|_| {
1173                StorageError::Serialization("invalid last_sync_time".to_string())
1174            })?)),
1175            None => Ok(None),
1176        }
1177    }
1178
1179    pub(crate) async fn set_last_sync_time(&self, time: u64) -> Result<(), StorageError> {
1180        self.storage
1181            .set_cached_item(LAST_SYNC_TIME_KEY.to_string(), time.to_string())
1182            .await
1183    }
1184
1185    pub(crate) async fn get_last_synced_at(&self) -> Result<Option<u64>, StorageError> {
1186        let value = self
1187            .storage
1188            .get_cached_item(LAST_SYNCED_AT_KEY.to_string())
1189            .await?;
1190        match value {
1191            Some(v) => Ok(Some(v.parse().map_err(|_| {
1192                StorageError::Serialization("invalid last_synced_at".to_string())
1193            })?)),
1194            None => Ok(None),
1195        }
1196    }
1197
1198    pub(crate) async fn set_last_synced_at(&self, time: u64) -> Result<(), StorageError> {
1199        self.storage
1200            .set_cached_item(LAST_SYNCED_AT_KEY.to_string(), time.to_string())
1201            .await
1202    }
1203}
1204
1205/// Outcome of the Flashnet rewards delegation.
1206#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1207pub(crate) enum CachedRewardsDelegation {
1208    /// Delegation is checked and settled.
1209    Done,
1210    /// No attempt before this unix time.
1211    RetryAfter(u64),
1212}
1213
1214#[derive(Serialize, Deserialize, Default)]
1215pub(crate) struct CachedAccountInfo {
1216    pub(crate) balance_sats: u64,
1217    #[serde(default)]
1218    pub(crate) token_balances: HashMap<String, TokenBalance>,
1219}
1220
1221#[derive(Serialize, Deserialize, Default)]
1222pub(crate) struct CachedSyncInfo {
1223    pub(crate) offset: u64,
1224    pub(crate) last_synced_final_token_payment_id: Option<String>,
1225}
1226
1227#[derive(Serialize, Deserialize, Default)]
1228pub(crate) struct CachedTx {
1229    pub(crate) raw_tx: String,
1230}
1231
1232#[cfg(feature = "test-utils")]
1233pub mod tests;