wallet.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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::payment_request::PaymentRequest;
  9. use crate::types::*;
  10. /// FFI-compatible Wallet
  11. #[derive(uniffi::Object)]
  12. pub struct Wallet {
  13. inner: Arc<CdkWallet>,
  14. }
  15. impl Wallet {
  16. /// Create a Wallet from an existing CDK wallet (internal use only)
  17. pub(crate) fn from_inner(inner: Arc<CdkWallet>) -> Self {
  18. Self { inner }
  19. }
  20. }
  21. #[uniffi::export(async_runtime = "tokio")]
  22. impl Wallet {
  23. /// Create a new Wallet from mnemonic using WalletDatabaseFfi trait
  24. #[uniffi::constructor]
  25. pub fn new(
  26. mint_url: String,
  27. unit: CurrencyUnit,
  28. mnemonic: String,
  29. db: Arc<dyn crate::database::WalletDatabase>,
  30. config: WalletConfig,
  31. ) -> Result<Self, FfiError> {
  32. // Parse mnemonic and generate seed without passphrase
  33. let m = Mnemonic::parse(&mnemonic)
  34. .map_err(|e| FfiError::internal(format!("Invalid mnemonic: {}", e)))?;
  35. let seed = m.to_seed_normalized("");
  36. tracing::info!("creating ffi wallet");
  37. // Convert the FFI database trait to a CDK database implementation
  38. let localstore = crate::database::create_cdk_database_from_ffi(db);
  39. let wallet = CdkWalletBuilder::new()
  40. .mint_url(mint_url.parse().map_err(|e: cdk::mint_url::Error| {
  41. FfiError::internal(format!("Invalid URL: {}", e))
  42. })?)
  43. .unit(unit.into())
  44. .localstore(localstore)
  45. .seed(seed)
  46. .target_proof_count(config.target_proof_count.unwrap_or(3) as usize)
  47. .build()
  48. .map_err(FfiError::from)?;
  49. Ok(Self {
  50. inner: Arc::new(wallet),
  51. })
  52. }
  53. /// Get the mint URL
  54. pub fn mint_url(&self) -> MintUrl {
  55. self.inner.mint_url.clone().into()
  56. }
  57. /// Get the currency unit
  58. pub fn unit(&self) -> CurrencyUnit {
  59. self.inner.unit.clone().into()
  60. }
  61. /// Set metadata cache TTL (time-to-live) in seconds
  62. ///
  63. /// Controls how long cached mint metadata (keysets, keys, mint info) is considered fresh
  64. /// before requiring a refresh from the mint server.
  65. ///
  66. /// # Arguments
  67. ///
  68. /// * `ttl_secs` - Optional TTL in seconds. If None, cache never expires and is always used.
  69. ///
  70. /// # Example
  71. ///
  72. /// ```ignore
  73. /// // Cache expires after 5 minutes
  74. /// wallet.set_metadata_cache_ttl(Some(300));
  75. ///
  76. /// // Cache never expires (default)
  77. /// wallet.set_metadata_cache_ttl(None);
  78. /// ```
  79. pub fn set_metadata_cache_ttl(&self, ttl_secs: Option<u64>) {
  80. let ttl = ttl_secs.map(std::time::Duration::from_secs);
  81. self.inner.set_metadata_cache_ttl(ttl);
  82. }
  83. /// Get total balance
  84. pub async fn total_balance(&self) -> Result<Amount, FfiError> {
  85. let balance = self.inner.total_balance().await?;
  86. Ok(balance.into())
  87. }
  88. /// Get total pending balance
  89. pub async fn total_pending_balance(&self) -> Result<Amount, FfiError> {
  90. let balance = self.inner.total_pending_balance().await?;
  91. Ok(balance.into())
  92. }
  93. /// Get total reserved balance
  94. pub async fn total_reserved_balance(&self) -> Result<Amount, FfiError> {
  95. let balance = self.inner.total_reserved_balance().await?;
  96. Ok(balance.into())
  97. }
  98. /// Get mint info from mint
  99. pub async fn fetch_mint_info(&self) -> Result<Option<MintInfo>, FfiError> {
  100. let info = self.inner.fetch_mint_info().await?;
  101. Ok(info.map(Into::into))
  102. }
  103. /// Load mint info
  104. ///
  105. /// This will get mint info from cache if it is fresh
  106. pub async fn load_mint_info(&self) -> Result<MintInfo, FfiError> {
  107. let info = self.inner.load_mint_info().await?;
  108. Ok(info.into())
  109. }
  110. /// Receive tokens
  111. pub async fn receive(
  112. &self,
  113. token: std::sync::Arc<Token>,
  114. options: ReceiveOptions,
  115. ) -> Result<Amount, FfiError> {
  116. let amount = self
  117. .inner
  118. .receive(&token.to_string(), options.into())
  119. .await?;
  120. Ok(amount.into())
  121. }
  122. /// Restore wallet from seed
  123. pub async fn restore(&self) -> Result<Restored, FfiError> {
  124. let restored = self.inner.restore().await?;
  125. Ok(restored.into())
  126. }
  127. /// Verify token DLEQ proofs
  128. pub async fn verify_token_dleq(&self, token: std::sync::Arc<Token>) -> Result<(), FfiError> {
  129. let cdk_token = token.inner.clone();
  130. self.inner.verify_token_dleq(&cdk_token).await?;
  131. Ok(())
  132. }
  133. /// Receive proofs directly
  134. pub async fn receive_proofs(
  135. &self,
  136. proofs: Proofs,
  137. options: ReceiveOptions,
  138. memo: Option<String>,
  139. ) -> Result<Amount, FfiError> {
  140. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  141. proofs.into_iter().map(|p| p.try_into()).collect();
  142. let cdk_proofs = cdk_proofs?;
  143. let amount = self
  144. .inner
  145. .receive_proofs(cdk_proofs, options.into(), memo)
  146. .await?;
  147. Ok(amount.into())
  148. }
  149. /// Prepare a send operation
  150. pub async fn prepare_send(
  151. &self,
  152. amount: Amount,
  153. options: SendOptions,
  154. ) -> Result<std::sync::Arc<PreparedSend>, FfiError> {
  155. let prepared = self
  156. .inner
  157. .prepare_send(amount.into(), options.into())
  158. .await?;
  159. Ok(std::sync::Arc::new(prepared.into()))
  160. }
  161. /// Get a mint quote
  162. pub async fn mint_quote(
  163. &self,
  164. amount: Amount,
  165. description: Option<String>,
  166. ) -> Result<MintQuote, FfiError> {
  167. let quote = self.inner.mint_quote(amount.into(), description).await?;
  168. Ok(quote.into())
  169. }
  170. /// Mint tokens
  171. pub async fn mint(
  172. &self,
  173. quote_id: String,
  174. amount_split_target: SplitTarget,
  175. spending_conditions: Option<SpendingConditions>,
  176. ) -> Result<Proofs, FfiError> {
  177. // Convert spending conditions if provided
  178. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  179. let proofs = self
  180. .inner
  181. .mint(&quote_id, amount_split_target.into(), conditions)
  182. .await?;
  183. Ok(proofs.into_iter().map(|p| p.into()).collect())
  184. }
  185. /// Get a melt quote
  186. pub async fn melt_quote(
  187. &self,
  188. request: String,
  189. options: Option<MeltOptions>,
  190. ) -> Result<MeltQuote, FfiError> {
  191. let cdk_options = options.map(Into::into);
  192. let quote = self.inner.melt_quote(request, cdk_options).await?;
  193. Ok(quote.into())
  194. }
  195. /// Melt tokens
  196. pub async fn melt(&self, quote_id: String) -> Result<Melted, FfiError> {
  197. let melted = self.inner.melt(&quote_id).await?;
  198. Ok(melted.into())
  199. }
  200. /// Melt specific proofs
  201. ///
  202. /// This method allows melting proofs that may not be in the wallet's database,
  203. /// similar to how `receive_proofs` handles external proofs. The proofs will be
  204. /// added to the database and used for the melt operation.
  205. ///
  206. /// # Arguments
  207. ///
  208. /// * `quote_id` - The melt quote ID (obtained from `melt_quote`)
  209. /// * `proofs` - The proofs to melt (can be external proofs not in the wallet's database)
  210. ///
  211. /// # Returns
  212. ///
  213. /// A `Melted` result containing the payment details and any change proofs
  214. pub async fn melt_proofs(&self, quote_id: String, proofs: Proofs) -> Result<Melted, FfiError> {
  215. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  216. proofs.into_iter().map(|p| p.try_into()).collect();
  217. let cdk_proofs = cdk_proofs?;
  218. let melted = self.inner.melt_proofs(&quote_id, cdk_proofs).await?;
  219. Ok(melted.into())
  220. }
  221. /// Get a quote for a bolt12 mint
  222. pub async fn mint_bolt12_quote(
  223. &self,
  224. amount: Option<Amount>,
  225. description: Option<String>,
  226. ) -> Result<MintQuote, FfiError> {
  227. let quote = self
  228. .inner
  229. .mint_bolt12_quote(amount.map(Into::into), description)
  230. .await?;
  231. Ok(quote.into())
  232. }
  233. /// Get a mint quote using a unified interface for any payment method
  234. ///
  235. /// This method supports bolt11, bolt12, and custom payment methods.
  236. /// For custom methods, you can pass extra JSON data that will be forwarded
  237. /// to the payment processor.
  238. ///
  239. /// # Arguments
  240. /// * `amount` - Optional amount to mint (required for bolt11)
  241. /// * `method` - Payment method to use (bolt11, bolt12, or custom)
  242. /// * `description` - Optional description for the quote
  243. /// * `extra` - Optional JSON string with extra payment-method-specific fields (for custom methods)
  244. pub async fn mint_quote_unified(
  245. &self,
  246. amount: Option<Amount>,
  247. method: PaymentMethod,
  248. description: Option<String>,
  249. extra: Option<String>,
  250. ) -> Result<MintQuote, FfiError> {
  251. let quote = self
  252. .inner
  253. .mint_quote_unified(amount.map(Into::into), method.into(), description, extra)
  254. .await?;
  255. Ok(quote.into())
  256. }
  257. /// Mint tokens using bolt12
  258. pub async fn mint_bolt12(
  259. &self,
  260. quote_id: String,
  261. amount: Option<Amount>,
  262. amount_split_target: SplitTarget,
  263. spending_conditions: Option<SpendingConditions>,
  264. ) -> Result<Proofs, FfiError> {
  265. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  266. let proofs = self
  267. .inner
  268. .mint_bolt12(
  269. &quote_id,
  270. amount.map(Into::into),
  271. amount_split_target.into(),
  272. conditions,
  273. )
  274. .await?;
  275. Ok(proofs.into_iter().map(|p| p.into()).collect())
  276. }
  277. pub async fn mint_unified(
  278. &self,
  279. quote_id: String,
  280. amount: Option<Amount>,
  281. amount_split_target: SplitTarget,
  282. spending_conditions: Option<SpendingConditions>,
  283. ) -> Result<Proofs, FfiError> {
  284. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  285. let proofs = self
  286. .inner
  287. .mint_unified(
  288. &quote_id,
  289. amount.map(Into::into),
  290. amount_split_target.into(),
  291. conditions,
  292. )
  293. .await?;
  294. Ok(proofs.into_iter().map(|p| p.into()).collect())
  295. }
  296. /// Get a quote for a bolt12 melt
  297. pub async fn melt_bolt12_quote(
  298. &self,
  299. request: String,
  300. options: Option<MeltOptions>,
  301. ) -> Result<MeltQuote, FfiError> {
  302. let cdk_options = options.map(Into::into);
  303. let quote = self.inner.melt_bolt12_quote(request, cdk_options).await?;
  304. Ok(quote.into())
  305. }
  306. /// Get a melt quote using a unified interface for any payment method
  307. ///
  308. /// This method supports bolt11, bolt12, and custom payment methods.
  309. /// For custom methods, you can pass extra JSON data that will be forwarded
  310. /// to the payment processor.
  311. ///
  312. /// # Arguments
  313. /// * `method` - Payment method to use (bolt11, bolt12, or custom)
  314. /// * `request` - Payment request string (invoice, offer, or custom format)
  315. /// * `options` - Optional melt options (MPP, amountless, etc.)
  316. /// * `extra` - Optional JSON string with extra payment-method-specific fields (for custom methods)
  317. pub async fn melt_quote_unified(
  318. &self,
  319. method: PaymentMethod,
  320. request: String,
  321. options: Option<MeltOptions>,
  322. extra: Option<String>,
  323. ) -> Result<MeltQuote, FfiError> {
  324. // Parse the extra JSON string into a serde_json::Value
  325. let extra_value = extra
  326. .map(|s| serde_json::from_str(&s))
  327. .transpose()
  328. .map_err(|e| FfiError::internal(format!("Invalid extra JSON: {}", e)))?;
  329. let cdk_options = options.map(Into::into);
  330. let quote = self
  331. .inner
  332. .melt_quote_unified(method.into(), request, cdk_options, extra_value)
  333. .await?;
  334. Ok(quote.into())
  335. }
  336. /// Swap proofs
  337. pub async fn swap(
  338. &self,
  339. amount: Option<Amount>,
  340. amount_split_target: SplitTarget,
  341. input_proofs: Proofs,
  342. spending_conditions: Option<SpendingConditions>,
  343. include_fees: bool,
  344. ) -> Result<Option<Proofs>, FfiError> {
  345. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  346. input_proofs.into_iter().map(|p| p.try_into()).collect();
  347. let cdk_proofs = cdk_proofs?;
  348. // Convert spending conditions if provided
  349. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  350. let result = self
  351. .inner
  352. .swap(
  353. amount.map(Into::into),
  354. amount_split_target.into(),
  355. cdk_proofs,
  356. conditions,
  357. include_fees,
  358. )
  359. .await?;
  360. Ok(result.map(|proofs| proofs.into_iter().map(|p| p.into()).collect()))
  361. }
  362. /// Get proofs by states
  363. pub async fn get_proofs_by_states(&self, states: Vec<ProofState>) -> Result<Proofs, FfiError> {
  364. let mut all_proofs = Vec::new();
  365. for state in states {
  366. let proofs = match state {
  367. ProofState::Unspent => self.inner.get_unspent_proofs().await?,
  368. ProofState::Pending => self.inner.get_pending_proofs().await?,
  369. ProofState::Reserved => self.inner.get_reserved_proofs().await?,
  370. ProofState::PendingSpent => self.inner.get_pending_spent_proofs().await?,
  371. ProofState::Spent => {
  372. // CDK doesn't have a method to get spent proofs directly
  373. // They are removed from the database when spent
  374. continue;
  375. }
  376. };
  377. for proof in proofs {
  378. all_proofs.push(proof.into());
  379. }
  380. }
  381. Ok(all_proofs)
  382. }
  383. /// Check if proofs are spent
  384. pub async fn check_proofs_spent(&self, proofs: Proofs) -> Result<Vec<bool>, FfiError> {
  385. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  386. proofs.into_iter().map(|p| p.try_into()).collect();
  387. let cdk_proofs = cdk_proofs?;
  388. let proof_states = self.inner.check_proofs_spent(cdk_proofs).await?;
  389. // Convert ProofState to bool (spent = true, unspent = false)
  390. let spent_bools = proof_states
  391. .into_iter()
  392. .map(|proof_state| {
  393. matches!(
  394. proof_state.state,
  395. cdk::nuts::State::Spent | cdk::nuts::State::PendingSpent
  396. )
  397. })
  398. .collect();
  399. Ok(spent_bools)
  400. }
  401. /// List transactions
  402. pub async fn list_transactions(
  403. &self,
  404. direction: Option<TransactionDirection>,
  405. ) -> Result<Vec<Transaction>, FfiError> {
  406. let cdk_direction = direction.map(Into::into);
  407. let transactions = self.inner.list_transactions(cdk_direction).await?;
  408. Ok(transactions.into_iter().map(Into::into).collect())
  409. }
  410. /// Get transaction by ID
  411. pub async fn get_transaction(
  412. &self,
  413. id: TransactionId,
  414. ) -> Result<Option<Transaction>, FfiError> {
  415. let cdk_id = id.try_into()?;
  416. let transaction = self.inner.get_transaction(cdk_id).await?;
  417. Ok(transaction.map(Into::into))
  418. }
  419. /// Get proofs for a transaction by transaction ID
  420. ///
  421. /// This retrieves all proofs associated with a transaction by looking up
  422. /// the transaction's Y values and fetching the corresponding proofs.
  423. pub async fn get_proofs_for_transaction(
  424. &self,
  425. id: TransactionId,
  426. ) -> Result<Vec<Proof>, FfiError> {
  427. let cdk_id = id.try_into()?;
  428. let proofs = self.inner.get_proofs_for_transaction(cdk_id).await?;
  429. Ok(proofs.into_iter().map(Into::into).collect())
  430. }
  431. /// Revert a transaction
  432. pub async fn revert_transaction(&self, id: TransactionId) -> Result<(), FfiError> {
  433. let cdk_id = id.try_into()?;
  434. self.inner.revert_transaction(cdk_id).await?;
  435. Ok(())
  436. }
  437. /// Subscribe to wallet events
  438. pub async fn subscribe(
  439. &self,
  440. params: SubscribeParams,
  441. ) -> Result<std::sync::Arc<ActiveSubscription>, FfiError> {
  442. let cdk_params: cdk::nuts::nut17::Params<Arc<String>> = params.clone().into();
  443. let sub_id = cdk_params.id.to_string();
  444. let active_sub = self.inner.subscribe(cdk_params).await?;
  445. Ok(std::sync::Arc::new(ActiveSubscription::new(
  446. active_sub, sub_id,
  447. )))
  448. }
  449. /// Refresh keysets from the mint
  450. pub async fn refresh_keysets(&self) -> Result<Vec<KeySetInfo>, FfiError> {
  451. let keysets = self.inner.refresh_keysets().await?;
  452. Ok(keysets.into_iter().map(Into::into).collect())
  453. }
  454. /// Get the active keyset for the wallet's unit
  455. pub async fn get_active_keyset(&self) -> Result<KeySetInfo, FfiError> {
  456. let keyset = self.inner.get_active_keyset().await?;
  457. Ok(keyset.into())
  458. }
  459. /// Get fees for a specific keyset ID
  460. pub async fn get_keyset_fees_by_id(&self, keyset_id: String) -> Result<u64, FfiError> {
  461. let id = cdk::nuts::Id::from_str(&keyset_id).map_err(FfiError::internal)?;
  462. Ok(self
  463. .inner
  464. .get_keyset_fees_and_amounts_by_id(id)
  465. .await?
  466. .fee())
  467. }
  468. /// Reclaim unspent proofs (mark them as unspent in the database)
  469. pub async fn reclaim_unspent(&self, proofs: Proofs) -> Result<(), FfiError> {
  470. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  471. proofs.iter().map(|p| p.clone().try_into()).collect();
  472. let cdk_proofs = cdk_proofs?;
  473. self.inner.reclaim_unspent(cdk_proofs).await?;
  474. Ok(())
  475. }
  476. /// Check all pending proofs and return the total amount reclaimed
  477. pub async fn check_all_pending_proofs(&self) -> Result<Amount, FfiError> {
  478. let amount = self.inner.check_all_pending_proofs().await?;
  479. Ok(amount.into())
  480. }
  481. /// Calculate fee for a given number of proofs with the specified keyset
  482. pub async fn calculate_fee(
  483. &self,
  484. proof_count: u32,
  485. keyset_id: String,
  486. ) -> Result<Amount, FfiError> {
  487. let id = cdk::nuts::Id::from_str(&keyset_id).map_err(FfiError::internal)?;
  488. let fee = self
  489. .inner
  490. .get_keyset_count_fee(&id, proof_count as u64)
  491. .await?;
  492. Ok(fee.into())
  493. }
  494. /// Pay a NUT-18 payment request
  495. ///
  496. /// This method prepares and sends a payment for the given payment request.
  497. /// It will use the Nostr or HTTP transport specified in the request.
  498. ///
  499. /// # Arguments
  500. ///
  501. /// * `payment_request` - The NUT-18 payment request to pay
  502. /// * `custom_amount` - Optional amount to pay (required if request has no amount)
  503. pub async fn pay_request(
  504. &self,
  505. payment_request: std::sync::Arc<PaymentRequest>,
  506. custom_amount: Option<Amount>,
  507. ) -> Result<(), FfiError> {
  508. self.inner
  509. .pay_request(
  510. payment_request.inner().clone(),
  511. custom_amount.map(Into::into),
  512. )
  513. .await?;
  514. Ok(())
  515. }
  516. }
  517. /// BIP353 methods for Wallet
  518. #[cfg(not(target_arch = "wasm32"))]
  519. #[uniffi::export(async_runtime = "tokio")]
  520. impl Wallet {
  521. /// Get a quote for a BIP353 melt
  522. ///
  523. /// This method resolves a BIP353 address (e.g., "alice@example.com") to a Lightning offer
  524. /// and then creates a melt quote for that offer.
  525. pub async fn melt_bip353_quote(
  526. &self,
  527. bip353_address: String,
  528. amount_msat: Amount,
  529. ) -> Result<MeltQuote, FfiError> {
  530. let cdk_amount: cdk::Amount = amount_msat.into();
  531. let quote = self
  532. .inner
  533. .melt_bip353_quote(&bip353_address, cdk_amount)
  534. .await?;
  535. Ok(quote.into())
  536. }
  537. /// Get a quote for a Lightning address melt
  538. ///
  539. /// This method resolves a Lightning address (e.g., "alice@example.com") to a Lightning invoice
  540. /// and then creates a melt quote for that invoice.
  541. pub async fn melt_lightning_address_quote(
  542. &self,
  543. lightning_address: String,
  544. amount_msat: Amount,
  545. ) -> Result<MeltQuote, FfiError> {
  546. let cdk_amount: cdk::Amount = amount_msat.into();
  547. let quote = self
  548. .inner
  549. .melt_lightning_address_quote(&lightning_address, cdk_amount)
  550. .await?;
  551. Ok(quote.into())
  552. }
  553. /// Get a quote for a human-readable address melt
  554. ///
  555. /// This method accepts a human-readable address that could be either a BIP353 address
  556. /// or a Lightning address. It intelligently determines which to try based on mint support:
  557. ///
  558. /// 1. If the mint supports Bolt12, it tries BIP353 first
  559. /// 2. Falls back to Lightning address only if BIP353 DNS resolution fails
  560. /// 3. If BIP353 resolves but fails at the mint, it does NOT fall back to Lightning address
  561. /// 4. If the mint doesn't support Bolt12, it tries Lightning address directly
  562. pub async fn melt_human_readable(
  563. &self,
  564. address: String,
  565. amount_msat: Amount,
  566. ) -> Result<MeltQuote, FfiError> {
  567. let cdk_amount: cdk::Amount = amount_msat.into();
  568. let quote = self
  569. .inner
  570. .melt_human_readable_quote(&address, cdk_amount)
  571. .await?;
  572. Ok(quote.into())
  573. }
  574. }
  575. /// Auth methods for Wallet
  576. #[uniffi::export(async_runtime = "tokio")]
  577. impl Wallet {
  578. /// Set Clear Auth Token (CAT) for authentication
  579. pub async fn set_cat(&self, cat: String) -> Result<(), FfiError> {
  580. self.inner.set_cat(cat).await?;
  581. Ok(())
  582. }
  583. /// Set refresh token for authentication
  584. pub async fn set_refresh_token(&self, refresh_token: String) -> Result<(), FfiError> {
  585. self.inner.set_refresh_token(refresh_token).await?;
  586. Ok(())
  587. }
  588. /// Refresh access token using the stored refresh token
  589. pub async fn refresh_access_token(&self) -> Result<(), FfiError> {
  590. self.inner.refresh_access_token().await?;
  591. Ok(())
  592. }
  593. /// Mint blind auth tokens
  594. pub async fn mint_blind_auth(&self, amount: Amount) -> Result<Proofs, FfiError> {
  595. let proofs = self.inner.mint_blind_auth(amount.into()).await?;
  596. Ok(proofs.into_iter().map(|p| p.into()).collect())
  597. }
  598. /// Get unspent auth proofs
  599. pub async fn get_unspent_auth_proofs(&self) -> Result<Vec<AuthProof>, FfiError> {
  600. let auth_proofs = self.inner.get_unspent_auth_proofs().await?;
  601. Ok(auth_proofs.into_iter().map(Into::into).collect())
  602. }
  603. }
  604. /// Configuration for creating wallets
  605. #[derive(Debug, Clone, uniffi::Record)]
  606. pub struct WalletConfig {
  607. pub target_proof_count: Option<u32>,
  608. }
  609. /// Generates a new random mnemonic phrase
  610. #[uniffi::export]
  611. pub fn generate_mnemonic() -> Result<String, FfiError> {
  612. let mnemonic = Mnemonic::generate(12)
  613. .map_err(|e| FfiError::internal(format!("Failed to generate mnemonic: {}", e)))?;
  614. Ok(mnemonic.to_string())
  615. }
  616. /// Converts a mnemonic phrase to its entropy bytes
  617. #[uniffi::export]
  618. pub fn mnemonic_to_entropy(mnemonic: String) -> Result<Vec<u8>, FfiError> {
  619. let m = Mnemonic::parse(&mnemonic)
  620. .map_err(|e| FfiError::internal(format!("Invalid mnemonic: {}", e)))?;
  621. Ok(m.to_entropy())
  622. }