wallet.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //! FFI Wallet bindings
  2. use std::str::FromStr;
  3. use std::sync::Arc;
  4. use bip39::Mnemonic;
  5. use cdk::wallet::{Wallet as CdkWallet, WalletBuilder as CdkWalletBuilder};
  6. use crate::error::FfiError;
  7. use crate::token::Token;
  8. use crate::types::*;
  9. /// FFI-compatible Wallet
  10. #[derive(uniffi::Object)]
  11. pub struct Wallet {
  12. inner: Arc<CdkWallet>,
  13. }
  14. #[uniffi::export(async_runtime = "tokio")]
  15. impl Wallet {
  16. /// Create a new Wallet from mnemonic using WalletDatabase trait
  17. #[uniffi::constructor]
  18. pub fn new(
  19. mint_url: String,
  20. unit: CurrencyUnit,
  21. mnemonic: String,
  22. db: Arc<dyn crate::database::WalletDatabase>,
  23. config: WalletConfig,
  24. ) -> Result<Self, FfiError> {
  25. // Parse mnemonic and generate seed without passphrase
  26. let m = Mnemonic::parse(&mnemonic)
  27. .map_err(|e| FfiError::InvalidMnemonic { msg: e.to_string() })?;
  28. let seed = m.to_seed_normalized("");
  29. // Convert the FFI database trait to a CDK database implementation
  30. let localstore = crate::database::create_cdk_database_from_ffi(db);
  31. let wallet =
  32. CdkWalletBuilder::new()
  33. .mint_url(mint_url.parse().map_err(|e: cdk::mint_url::Error| {
  34. FfiError::InvalidUrl { msg: e.to_string() }
  35. })?)
  36. .unit(unit.into())
  37. .localstore(localstore)
  38. .seed(seed)
  39. .target_proof_count(config.target_proof_count.unwrap_or(3) as usize)
  40. .build()
  41. .map_err(FfiError::from)?;
  42. Ok(Self {
  43. inner: Arc::new(wallet),
  44. })
  45. }
  46. /// Get the mint URL
  47. pub fn mint_url(&self) -> MintUrl {
  48. self.inner.mint_url.clone().into()
  49. }
  50. /// Get the currency unit
  51. pub fn unit(&self) -> CurrencyUnit {
  52. self.inner.unit.clone().into()
  53. }
  54. /// Get total balance
  55. pub async fn total_balance(&self) -> Result<Amount, FfiError> {
  56. let balance = self.inner.total_balance().await?;
  57. Ok(balance.into())
  58. }
  59. /// Get total pending balance
  60. pub async fn total_pending_balance(&self) -> Result<Amount, FfiError> {
  61. let balance = self.inner.total_pending_balance().await?;
  62. Ok(balance.into())
  63. }
  64. /// Get total reserved balance
  65. pub async fn total_reserved_balance(&self) -> Result<Amount, FfiError> {
  66. let balance = self.inner.total_reserved_balance().await?;
  67. Ok(balance.into())
  68. }
  69. /// Get mint info
  70. pub async fn get_mint_info(&self) -> Result<Option<MintInfo>, FfiError> {
  71. let info = self.inner.fetch_mint_info().await?;
  72. Ok(info.map(Into::into))
  73. }
  74. /// Receive tokens
  75. pub async fn receive(
  76. &self,
  77. token: std::sync::Arc<Token>,
  78. options: ReceiveOptions,
  79. ) -> Result<Amount, FfiError> {
  80. let amount = self
  81. .inner
  82. .receive(&token.to_string(), options.into())
  83. .await?;
  84. Ok(amount.into())
  85. }
  86. /// Restore wallet from seed
  87. pub async fn restore(&self) -> Result<Amount, FfiError> {
  88. let amount = self.inner.restore().await?;
  89. Ok(amount.into())
  90. }
  91. /// Verify token DLEQ proofs
  92. pub async fn verify_token_dleq(&self, token: std::sync::Arc<Token>) -> Result<(), FfiError> {
  93. let cdk_token = token.inner.clone();
  94. self.inner.verify_token_dleq(&cdk_token).await?;
  95. Ok(())
  96. }
  97. /// Receive proofs directly
  98. pub async fn receive_proofs(
  99. &self,
  100. proofs: Proofs,
  101. options: ReceiveOptions,
  102. memo: Option<String>,
  103. ) -> Result<Amount, FfiError> {
  104. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  105. proofs.into_iter().map(|p| p.try_into()).collect();
  106. let cdk_proofs = cdk_proofs?;
  107. let amount = self
  108. .inner
  109. .receive_proofs(cdk_proofs, options.into(), memo)
  110. .await?;
  111. Ok(amount.into())
  112. }
  113. /// Prepare a send operation
  114. pub async fn prepare_send(
  115. &self,
  116. amount: Amount,
  117. options: SendOptions,
  118. ) -> Result<std::sync::Arc<PreparedSend>, FfiError> {
  119. let prepared = self
  120. .inner
  121. .prepare_send(amount.into(), options.into())
  122. .await?;
  123. Ok(std::sync::Arc::new(prepared.into()))
  124. }
  125. /// Get a mint quote
  126. pub async fn mint_quote(
  127. &self,
  128. amount: Amount,
  129. description: Option<String>,
  130. ) -> Result<MintQuote, FfiError> {
  131. let quote = self.inner.mint_quote(amount.into(), description).await?;
  132. Ok(quote.into())
  133. }
  134. /// Mint tokens
  135. pub async fn mint(
  136. &self,
  137. quote_id: String,
  138. amount_split_target: SplitTarget,
  139. spending_conditions: Option<SpendingConditions>,
  140. ) -> Result<Proofs, FfiError> {
  141. // Convert spending conditions if provided
  142. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  143. let proofs = self
  144. .inner
  145. .mint(&quote_id, amount_split_target.into(), conditions)
  146. .await?;
  147. Ok(proofs.into_iter().map(|p| p.into()).collect())
  148. }
  149. /// Get a melt quote
  150. pub async fn melt_quote(
  151. &self,
  152. request: String,
  153. options: Option<MeltOptions>,
  154. ) -> Result<MeltQuote, FfiError> {
  155. let cdk_options = options.map(Into::into);
  156. let quote = self.inner.melt_quote(request, cdk_options).await?;
  157. Ok(quote.into())
  158. }
  159. /// Melt tokens
  160. pub async fn melt(&self, quote_id: String) -> Result<Melted, FfiError> {
  161. let melted = self.inner.melt(&quote_id).await?;
  162. Ok(melted.into())
  163. }
  164. /// Get a quote for a bolt12 mint
  165. pub async fn mint_bolt12_quote(
  166. &self,
  167. amount: Option<Amount>,
  168. description: Option<String>,
  169. ) -> Result<MintQuote, FfiError> {
  170. let quote = self
  171. .inner
  172. .mint_bolt12_quote(amount.map(Into::into), description)
  173. .await?;
  174. Ok(quote.into())
  175. }
  176. /// Mint tokens using bolt12
  177. pub async fn mint_bolt12(
  178. &self,
  179. quote_id: String,
  180. amount: Option<Amount>,
  181. amount_split_target: SplitTarget,
  182. spending_conditions: Option<SpendingConditions>,
  183. ) -> Result<Proofs, FfiError> {
  184. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  185. let proofs = self
  186. .inner
  187. .mint_bolt12(
  188. &quote_id,
  189. amount.map(Into::into),
  190. amount_split_target.into(),
  191. conditions,
  192. )
  193. .await?;
  194. Ok(proofs.into_iter().map(|p| p.into()).collect())
  195. }
  196. /// Get a quote for a bolt12 melt
  197. pub async fn melt_bolt12_quote(
  198. &self,
  199. request: String,
  200. options: Option<MeltOptions>,
  201. ) -> Result<MeltQuote, FfiError> {
  202. let cdk_options = options.map(Into::into);
  203. let quote = self.inner.melt_bolt12_quote(request, cdk_options).await?;
  204. Ok(quote.into())
  205. }
  206. /// Swap proofs
  207. pub async fn swap(
  208. &self,
  209. amount: Option<Amount>,
  210. amount_split_target: SplitTarget,
  211. input_proofs: Proofs,
  212. spending_conditions: Option<SpendingConditions>,
  213. include_fees: bool,
  214. ) -> Result<Option<Proofs>, FfiError> {
  215. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  216. input_proofs.into_iter().map(|p| p.try_into()).collect();
  217. let cdk_proofs = cdk_proofs?;
  218. // Convert spending conditions if provided
  219. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  220. let result = self
  221. .inner
  222. .swap(
  223. amount.map(Into::into),
  224. amount_split_target.into(),
  225. cdk_proofs,
  226. conditions,
  227. include_fees,
  228. )
  229. .await?;
  230. Ok(result.map(|proofs| proofs.into_iter().map(|p| p.into()).collect()))
  231. }
  232. /// Get proofs by states
  233. pub async fn get_proofs_by_states(&self, states: Vec<ProofState>) -> Result<Proofs, FfiError> {
  234. let mut all_proofs = Vec::new();
  235. for state in states {
  236. let proofs = match state {
  237. ProofState::Unspent => self.inner.get_unspent_proofs().await?,
  238. ProofState::Pending => self.inner.get_pending_proofs().await?,
  239. ProofState::Reserved => self.inner.get_reserved_proofs().await?,
  240. ProofState::PendingSpent => self.inner.get_pending_spent_proofs().await?,
  241. ProofState::Spent => {
  242. // CDK doesn't have a method to get spent proofs directly
  243. // They are removed from the database when spent
  244. continue;
  245. }
  246. };
  247. for proof in proofs {
  248. all_proofs.push(proof.into());
  249. }
  250. }
  251. Ok(all_proofs)
  252. }
  253. /// Check if proofs are spent
  254. pub async fn check_proofs_spent(&self, proofs: Proofs) -> Result<Vec<bool>, FfiError> {
  255. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  256. proofs.into_iter().map(|p| p.try_into()).collect();
  257. let cdk_proofs = cdk_proofs?;
  258. let proof_states = self.inner.check_proofs_spent(cdk_proofs).await?;
  259. // Convert ProofState to bool (spent = true, unspent = false)
  260. let spent_bools = proof_states
  261. .into_iter()
  262. .map(|proof_state| {
  263. matches!(
  264. proof_state.state,
  265. cdk::nuts::State::Spent | cdk::nuts::State::PendingSpent
  266. )
  267. })
  268. .collect();
  269. Ok(spent_bools)
  270. }
  271. /// List transactions
  272. pub async fn list_transactions(
  273. &self,
  274. direction: Option<TransactionDirection>,
  275. ) -> Result<Vec<Transaction>, FfiError> {
  276. let cdk_direction = direction.map(Into::into);
  277. let transactions = self.inner.list_transactions(cdk_direction).await?;
  278. Ok(transactions.into_iter().map(Into::into).collect())
  279. }
  280. /// Get transaction by ID
  281. pub async fn get_transaction(
  282. &self,
  283. id: TransactionId,
  284. ) -> Result<Option<Transaction>, FfiError> {
  285. let cdk_id = id.try_into()?;
  286. let transaction = self.inner.get_transaction(cdk_id).await?;
  287. Ok(transaction.map(Into::into))
  288. }
  289. /// Revert a transaction
  290. pub async fn revert_transaction(&self, id: TransactionId) -> Result<(), FfiError> {
  291. let cdk_id = id.try_into()?;
  292. self.inner.revert_transaction(cdk_id).await?;
  293. Ok(())
  294. }
  295. /// Subscribe to wallet events
  296. pub async fn subscribe(
  297. &self,
  298. params: SubscribeParams,
  299. ) -> Result<std::sync::Arc<ActiveSubscription>, FfiError> {
  300. let cdk_params: cdk::nuts::nut17::Params<Arc<String>> = params.clone().into();
  301. let sub_id = cdk_params.id.to_string();
  302. let active_sub = self.inner.subscribe(cdk_params).await;
  303. Ok(std::sync::Arc::new(ActiveSubscription::new(
  304. active_sub, sub_id,
  305. )))
  306. }
  307. /// Refresh keysets from the mint
  308. pub async fn refresh_keysets(&self) -> Result<Vec<KeySetInfo>, FfiError> {
  309. let keysets = self.inner.refresh_keysets().await?;
  310. Ok(keysets.into_iter().map(Into::into).collect())
  311. }
  312. /// Get the active keyset for the wallet's unit
  313. pub async fn get_active_keyset(&self) -> Result<KeySetInfo, FfiError> {
  314. let keyset = self.inner.get_active_keyset().await?;
  315. Ok(keyset.into())
  316. }
  317. /// Get fees for a specific keyset ID
  318. pub async fn get_keyset_fees_by_id(&self, keyset_id: String) -> Result<u64, FfiError> {
  319. let id = cdk::nuts::Id::from_str(&keyset_id)
  320. .map_err(|e| FfiError::Generic { msg: e.to_string() })?;
  321. Ok(self
  322. .inner
  323. .get_keyset_fees_and_amounts_by_id(id)
  324. .await?
  325. .fee())
  326. }
  327. /// Reclaim unspent proofs (mark them as unspent in the database)
  328. pub async fn reclaim_unspent(&self, proofs: Proofs) -> Result<(), FfiError> {
  329. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  330. proofs.iter().map(|p| p.clone().try_into()).collect();
  331. let cdk_proofs = cdk_proofs?;
  332. self.inner.reclaim_unspent(cdk_proofs).await?;
  333. Ok(())
  334. }
  335. /// Check all pending proofs and return the total amount reclaimed
  336. pub async fn check_all_pending_proofs(&self) -> Result<Amount, FfiError> {
  337. let amount = self.inner.check_all_pending_proofs().await?;
  338. Ok(amount.into())
  339. }
  340. /// Calculate fee for a given number of proofs with the specified keyset
  341. pub async fn calculate_fee(
  342. &self,
  343. proof_count: u32,
  344. keyset_id: String,
  345. ) -> Result<Amount, FfiError> {
  346. let id = cdk::nuts::Id::from_str(&keyset_id)
  347. .map_err(|e| FfiError::Generic { msg: e.to_string() })?;
  348. let fee = self
  349. .inner
  350. .get_keyset_count_fee(&id, proof_count as u64)
  351. .await?;
  352. Ok(fee.into())
  353. }
  354. }
  355. /// BIP353 methods for Wallet
  356. #[cfg(not(target_arch = "wasm32"))]
  357. #[uniffi::export(async_runtime = "tokio")]
  358. impl Wallet {
  359. /// Get a quote for a BIP353 melt
  360. ///
  361. /// This method resolves a BIP353 address (e.g., "alice@example.com") to a Lightning offer
  362. /// and then creates a melt quote for that offer.
  363. pub async fn melt_bip353_quote(
  364. &self,
  365. bip353_address: String,
  366. amount_msat: Amount,
  367. ) -> Result<MeltQuote, FfiError> {
  368. let cdk_amount: cdk::Amount = amount_msat.into();
  369. let quote = self
  370. .inner
  371. .melt_bip353_quote(&bip353_address, cdk_amount)
  372. .await?;
  373. Ok(quote.into())
  374. }
  375. }
  376. /// Auth methods for Wallet
  377. #[uniffi::export(async_runtime = "tokio")]
  378. impl Wallet {
  379. /// Set Clear Auth Token (CAT) for authentication
  380. pub async fn set_cat(&self, cat: String) -> Result<(), FfiError> {
  381. self.inner.set_cat(cat).await?;
  382. Ok(())
  383. }
  384. /// Set refresh token for authentication
  385. pub async fn set_refresh_token(&self, refresh_token: String) -> Result<(), FfiError> {
  386. self.inner.set_refresh_token(refresh_token).await?;
  387. Ok(())
  388. }
  389. /// Refresh access token using the stored refresh token
  390. pub async fn refresh_access_token(&self) -> Result<(), FfiError> {
  391. self.inner.refresh_access_token().await?;
  392. Ok(())
  393. }
  394. /// Mint blind auth tokens
  395. pub async fn mint_blind_auth(&self, amount: Amount) -> Result<Proofs, FfiError> {
  396. let proofs = self.inner.mint_blind_auth(amount.into()).await?;
  397. Ok(proofs.into_iter().map(|p| p.into()).collect())
  398. }
  399. /// Get unspent auth proofs
  400. pub async fn get_unspent_auth_proofs(&self) -> Result<Vec<AuthProof>, FfiError> {
  401. let auth_proofs = self.inner.get_unspent_auth_proofs().await?;
  402. Ok(auth_proofs.into_iter().map(Into::into).collect())
  403. }
  404. }
  405. /// Configuration for creating wallets
  406. #[derive(Debug, Clone, uniffi::Record)]
  407. pub struct WalletConfig {
  408. pub target_proof_count: Option<u32>,
  409. }
  410. /// Generates a new random mnemonic phrase
  411. #[uniffi::export]
  412. pub fn generate_mnemonic() -> Result<String, FfiError> {
  413. let mnemonic =
  414. Mnemonic::generate(12).map_err(|e| FfiError::InvalidMnemonic { msg: e.to_string() })?;
  415. Ok(mnemonic.to_string())
  416. }
  417. /// Converts a mnemonic phrase to its entropy bytes
  418. #[uniffi::export]
  419. pub fn mnemonic_to_entropy(mnemonic: String) -> Result<Vec<u8>, FfiError> {
  420. let m =
  421. Mnemonic::parse(&mnemonic).map_err(|e| FfiError::InvalidMnemonic { msg: e.to_string() })?;
  422. Ok(m.to_entropy())
  423. }