Skip to main content

cdk_ffi/
sqlite.rs

1use std::sync::Arc;
2
3use cdk_sqlite::wallet::WalletSqliteDatabase as CdkWalletSqliteDatabase;
4use cdk_sqlite::SqliteConnectionManager;
5
6use crate::{
7    CurrencyUnit, FfiError, FfiWalletSQLDatabase, Id, KeySet, KeySetInfo, Keys, MeltQuote,
8    MintInfo, MintQuote, MintUrl, ProofInfo, ProofState, PublicKey, SpendingConditions,
9    Transaction, TransactionDirection, TransactionId, WalletDatabase,
10};
11
12/// FFI-compatible WalletSqliteDatabase implementation that implements the WalletDatabaseFfi trait
13#[derive(uniffi::Object)]
14pub struct WalletSqliteDatabase {
15    inner: Arc<FfiWalletSQLDatabase<SqliteConnectionManager>>,
16}
17
18#[uniffi::export]
19impl WalletSqliteDatabase {
20    /// Create a new WalletSqliteDatabase with the given work directory
21    #[uniffi::constructor]
22    pub fn new(file_path: String) -> Result<Arc<Self>, FfiError> {
23        let db = match tokio::runtime::Handle::try_current() {
24            Ok(handle) => tokio::task::block_in_place(|| {
25                handle
26                    .block_on(async move { CdkWalletSqliteDatabase::new(file_path.as_str()).await })
27            }),
28            Err(_) => {
29                // No current runtime, create a new one
30                tokio::runtime::Runtime::new()
31                    .map_err(|e| FfiError::internal(format!("Failed to create runtime: {}", e)))?
32                    .block_on(async move { CdkWalletSqliteDatabase::new(file_path.as_str()).await })
33            }
34        }
35        .map_err(FfiError::internal)?;
36        Ok(Arc::new(Self {
37            inner: FfiWalletSQLDatabase::new(db),
38        }))
39    }
40
41    /// Create an in-memory database
42    #[uniffi::constructor]
43    pub fn new_in_memory() -> Result<Arc<Self>, FfiError> {
44        let db = match tokio::runtime::Handle::try_current() {
45            Ok(handle) => tokio::task::block_in_place(|| {
46                handle.block_on(async move { cdk_sqlite::wallet::memory::empty().await })
47            }),
48            Err(_) => {
49                // No current runtime, create a new one
50                tokio::runtime::Runtime::new()
51                    .map_err(|e| FfiError::internal(format!("Failed to create runtime: {}", e)))?
52                    .block_on(async move { cdk_sqlite::wallet::memory::empty().await })
53            }
54        }
55        .map_err(FfiError::internal)?;
56        Ok(Arc::new(Self {
57            inner: FfiWalletSQLDatabase::new(db),
58        }))
59    }
60}
61
62// Use macro to implement WalletDatabase trait - delegates all methods to inner
63crate::impl_ffi_wallet_database!(WalletSqliteDatabase);