wallet.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. token: Option<String>,
  140. ) -> Result<Amount, FfiError> {
  141. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  142. proofs.into_iter().map(|p| p.try_into()).collect();
  143. let cdk_proofs = cdk_proofs?;
  144. let amount = self
  145. .inner
  146. .receive_proofs(cdk_proofs, options.into(), memo, token)
  147. .await?;
  148. Ok(amount.into())
  149. }
  150. /// Get all pending send operations
  151. pub async fn get_pending_sends(&self) -> Result<Vec<String>, FfiError> {
  152. let sends = self.inner.get_pending_sends().await?;
  153. Ok(sends.into_iter().map(|id| id.to_string()).collect())
  154. }
  155. /// Revoke a pending send operation
  156. pub async fn revoke_send(&self, operation_id: String) -> Result<Amount, FfiError> {
  157. let uuid = uuid::Uuid::parse_str(&operation_id)
  158. .map_err(|e| FfiError::internal(format!("Invalid operation ID: {}", e)))?;
  159. let amount = self.inner.revoke_send(uuid).await?;
  160. Ok(amount.into())
  161. }
  162. /// Check status of a pending send operation
  163. pub async fn check_send_status(&self, operation_id: String) -> Result<bool, FfiError> {
  164. let uuid = uuid::Uuid::parse_str(&operation_id)
  165. .map_err(|e| FfiError::internal(format!("Invalid operation ID: {}", e)))?;
  166. let claimed = self.inner.check_send_status(uuid).await?;
  167. Ok(claimed)
  168. }
  169. /// Prepare a send operation
  170. pub async fn prepare_send(
  171. &self,
  172. amount: Amount,
  173. options: SendOptions,
  174. ) -> Result<std::sync::Arc<PreparedSend>, FfiError> {
  175. let prepared = self
  176. .inner
  177. .prepare_send(amount.into(), options.into())
  178. .await?;
  179. Ok(std::sync::Arc::new(PreparedSend::new(
  180. self.inner.clone(),
  181. &prepared,
  182. )))
  183. }
  184. /// Get a mint quote
  185. pub async fn mint_quote(
  186. &self,
  187. payment_method: PaymentMethod,
  188. amount: Option<Amount>,
  189. description: Option<String>,
  190. extra: Option<String>,
  191. ) -> Result<MintQuote, FfiError> {
  192. let quote = self
  193. .inner
  194. .mint_quote(payment_method, amount.map(Into::into), description, extra)
  195. .await?;
  196. Ok(quote.into())
  197. }
  198. /// Refresh a specific mint quote status from the mint.
  199. /// Updates local store with current state from mint.
  200. /// Does NOT mint tokens - use mint() to mint a specific quote.
  201. pub async fn refresh_mint_quote(
  202. &self,
  203. quote_id: String,
  204. ) -> Result<MintQuoteBolt11Response, FfiError> {
  205. let quote = self.inner.refresh_mint_quote_status(&quote_id).await?;
  206. Ok(quote.into())
  207. }
  208. /// Fetch a mint quote from the mint and store it locally
  209. ///
  210. /// Works with all payment methods (Bolt11, Bolt12, and custom payment methods).
  211. ///
  212. /// # Arguments
  213. /// * `quote_id` - The ID of the quote to fetch
  214. /// * `payment_method` - The payment method for the quote. Required if the quote
  215. /// is not already stored locally. If the quote exists locally, the stored
  216. /// payment method will be used and this parameter is ignored.
  217. pub async fn fetch_mint_quote(
  218. &self,
  219. quote_id: String,
  220. payment_method: Option<PaymentMethod>,
  221. ) -> Result<MintQuote, FfiError> {
  222. let method = payment_method.map(Into::into);
  223. let quote = self.inner.fetch_mint_quote(&quote_id, method).await?;
  224. Ok(quote.into())
  225. }
  226. /// Mint tokens
  227. pub async fn mint(
  228. &self,
  229. quote_id: String,
  230. amount_split_target: SplitTarget,
  231. spending_conditions: Option<SpendingConditions>,
  232. ) -> Result<Proofs, FfiError> {
  233. // Convert spending conditions if provided
  234. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  235. let proofs = self
  236. .inner
  237. .mint(&quote_id, amount_split_target.into(), conditions)
  238. .await?;
  239. Ok(proofs.into_iter().map(|p| p.into()).collect())
  240. }
  241. /// Prepare a melt operation
  242. ///
  243. /// Returns a `PreparedMelt` that can be confirmed or cancelled.
  244. pub async fn prepare_melt(&self, quote_id: String) -> Result<PreparedMelt, FfiError> {
  245. let prepared = self
  246. .inner
  247. .prepare_melt(&quote_id, std::collections::HashMap::new())
  248. .await?;
  249. Ok(PreparedMelt::new(Arc::clone(&self.inner), &prepared))
  250. }
  251. /// Prepare a melt operation with specific proofs
  252. ///
  253. /// This method allows melting proofs that may not be in the wallet's database,
  254. /// similar to how `receive_proofs` handles external proofs. The proofs will be
  255. /// added to the database and used for the melt operation.
  256. ///
  257. /// # Arguments
  258. ///
  259. /// * `quote_id` - The melt quote ID (obtained from `melt_quote`)
  260. /// * `proofs` - The proofs to melt (can be external proofs not in the wallet's database)
  261. ///
  262. /// # Returns
  263. ///
  264. /// A `PreparedMelt` that can be confirmed or cancelled
  265. pub async fn prepare_melt_proofs(
  266. &self,
  267. quote_id: String,
  268. proofs: Proofs,
  269. ) -> Result<PreparedMelt, FfiError> {
  270. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  271. proofs.into_iter().map(|p| p.try_into()).collect();
  272. let cdk_proofs = cdk_proofs?;
  273. let prepared = self
  274. .inner
  275. .prepare_melt_proofs(&quote_id, cdk_proofs, std::collections::HashMap::new())
  276. .await?;
  277. Ok(PreparedMelt::new(Arc::clone(&self.inner), &prepared))
  278. }
  279. pub async fn mint_unified(
  280. &self,
  281. quote_id: String,
  282. amount_split_target: SplitTarget,
  283. spending_conditions: Option<SpendingConditions>,
  284. ) -> Result<Proofs, FfiError> {
  285. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  286. let proofs = self
  287. .inner
  288. .mint(&quote_id, amount_split_target.into(), conditions)
  289. .await?;
  290. Ok(proofs.into_iter().map(|p| p.into()).collect())
  291. }
  292. /// Get a melt quote using a unified interface for any payment method
  293. ///
  294. /// This method supports bolt11, bolt12, and custom payment methods.
  295. /// For custom methods, you can pass extra JSON data that will be forwarded
  296. /// to the payment processor.
  297. ///
  298. /// # Arguments
  299. /// * `method` - Payment method to use (bolt11, bolt12, or custom)
  300. /// * `request` - Payment request string (invoice, offer, or custom format)
  301. /// * `options` - Optional melt options (MPP, amountless, etc.)
  302. /// * `extra` - Optional JSON string with extra payment-method-specific fields (for custom methods)
  303. pub async fn melt_quote(
  304. &self,
  305. method: PaymentMethod,
  306. request: String,
  307. options: Option<MeltOptions>,
  308. extra: Option<String>,
  309. ) -> Result<MeltQuote, FfiError> {
  310. let cdk_options = options.map(Into::into);
  311. let quote = self
  312. .inner
  313. .melt_quote::<cdk::nuts::PaymentMethod, _>(method.into(), request, cdk_options, extra)
  314. .await?;
  315. Ok(quote.into())
  316. }
  317. /// Swap proofs
  318. pub async fn swap(
  319. &self,
  320. amount: Option<Amount>,
  321. amount_split_target: SplitTarget,
  322. input_proofs: Proofs,
  323. spending_conditions: Option<SpendingConditions>,
  324. include_fees: bool,
  325. ) -> Result<Option<Proofs>, FfiError> {
  326. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  327. input_proofs.into_iter().map(|p| p.try_into()).collect();
  328. let cdk_proofs = cdk_proofs?;
  329. // Convert spending conditions if provided
  330. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  331. let result = self
  332. .inner
  333. .swap(
  334. amount.map(Into::into),
  335. amount_split_target.into(),
  336. cdk_proofs,
  337. conditions,
  338. include_fees,
  339. )
  340. .await?;
  341. Ok(result.map(|proofs| proofs.into_iter().map(|p| p.into()).collect()))
  342. }
  343. /// Get proofs by states
  344. pub async fn get_proofs_by_states(&self, states: Vec<ProofState>) -> Result<Proofs, FfiError> {
  345. let mut all_proofs = Vec::new();
  346. for state in states {
  347. let proofs = match state {
  348. ProofState::Unspent => self.inner.get_unspent_proofs().await?,
  349. ProofState::Pending => self.inner.get_pending_proofs().await?,
  350. ProofState::Reserved => self.inner.get_reserved_proofs().await?,
  351. ProofState::PendingSpent => self.inner.get_pending_spent_proofs().await?,
  352. ProofState::Spent => {
  353. // CDK doesn't have a method to get spent proofs directly
  354. // They are removed from the database when spent
  355. continue;
  356. }
  357. };
  358. for proof in proofs {
  359. all_proofs.push(proof.into());
  360. }
  361. }
  362. Ok(all_proofs)
  363. }
  364. /// Check if proofs are spent
  365. pub async fn check_proofs_spent(&self, proofs: Proofs) -> Result<Vec<bool>, FfiError> {
  366. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  367. proofs.into_iter().map(|p| p.try_into()).collect();
  368. let cdk_proofs = cdk_proofs?;
  369. let proof_states = self.inner.check_proofs_spent(cdk_proofs).await?;
  370. // Convert ProofState to bool (spent = true, unspent = false)
  371. let spent_bools = proof_states
  372. .into_iter()
  373. .map(|proof_state| {
  374. matches!(
  375. proof_state.state,
  376. cdk::nuts::State::Spent | cdk::nuts::State::PendingSpent
  377. )
  378. })
  379. .collect();
  380. Ok(spent_bools)
  381. }
  382. /// List transactions
  383. pub async fn list_transactions(
  384. &self,
  385. direction: Option<TransactionDirection>,
  386. ) -> Result<Vec<Transaction>, FfiError> {
  387. let cdk_direction = direction.map(Into::into);
  388. let transactions = self.inner.list_transactions(cdk_direction).await?;
  389. Ok(transactions.into_iter().map(Into::into).collect())
  390. }
  391. /// Get transaction by ID
  392. pub async fn get_transaction(
  393. &self,
  394. id: TransactionId,
  395. ) -> Result<Option<Transaction>, FfiError> {
  396. let cdk_id = id.try_into()?;
  397. let transaction = self.inner.get_transaction(cdk_id).await?;
  398. Ok(transaction.map(Into::into))
  399. }
  400. /// Get proofs for a transaction by transaction ID
  401. ///
  402. /// This retrieves all proofs associated with a transaction by looking up
  403. /// the transaction's Y values and fetching the corresponding proofs.
  404. pub async fn get_proofs_for_transaction(
  405. &self,
  406. id: TransactionId,
  407. ) -> Result<Vec<Proof>, FfiError> {
  408. let cdk_id = id.try_into()?;
  409. let proofs = self.inner.get_proofs_for_transaction(cdk_id).await?;
  410. Ok(proofs.into_iter().map(Into::into).collect())
  411. }
  412. /// Revert a transaction
  413. pub async fn revert_transaction(&self, id: TransactionId) -> Result<(), FfiError> {
  414. let cdk_id = id.try_into()?;
  415. self.inner.revert_transaction(cdk_id).await?;
  416. Ok(())
  417. }
  418. /// Subscribe to wallet events
  419. pub async fn subscribe(
  420. &self,
  421. params: SubscribeParams,
  422. ) -> Result<std::sync::Arc<ActiveSubscription>, FfiError> {
  423. let cdk_params: cdk::nuts::nut17::Params<Arc<String>> = params.clone().into();
  424. let sub_id = cdk_params.id.to_string();
  425. let active_sub = self.inner.subscribe(cdk_params).await?;
  426. Ok(std::sync::Arc::new(ActiveSubscription::new(
  427. active_sub, sub_id,
  428. )))
  429. }
  430. /// Refresh keysets from the mint
  431. pub async fn refresh_keysets(&self) -> Result<Vec<KeySetInfo>, FfiError> {
  432. let keysets = self.inner.refresh_keysets().await?;
  433. Ok(keysets.into_iter().map(Into::into).collect())
  434. }
  435. /// Get the active keyset for the wallet's unit
  436. pub async fn get_active_keyset(&self) -> Result<KeySetInfo, FfiError> {
  437. let keyset = self.inner.get_active_keyset().await?;
  438. Ok(keyset.into())
  439. }
  440. /// Get fees for a specific keyset ID
  441. pub async fn get_keyset_fees_by_id(&self, keyset_id: String) -> Result<u64, FfiError> {
  442. let id = cdk::nuts::Id::from_str(&keyset_id).map_err(FfiError::internal)?;
  443. Ok(self
  444. .inner
  445. .get_keyset_fees_and_amounts_by_id(id)
  446. .await?
  447. .fee())
  448. }
  449. /// Check all pending proofs and return the total amount still pending
  450. ///
  451. /// This function checks orphaned pending proofs (not managed by active sagas)
  452. /// with the mint and marks spent proofs accordingly.
  453. pub async fn check_all_pending_proofs(&self) -> Result<Amount, FfiError> {
  454. let amount = self.inner.check_all_pending_proofs().await?;
  455. Ok(amount.into())
  456. }
  457. /// Calculate fee for a given number of proofs with the specified keyset
  458. pub async fn calculate_fee(
  459. &self,
  460. proof_count: u32,
  461. keyset_id: String,
  462. ) -> Result<Amount, FfiError> {
  463. let id = cdk::nuts::Id::from_str(&keyset_id).map_err(FfiError::internal)?;
  464. let fee = self
  465. .inner
  466. .get_keyset_count_fee(&id, proof_count as u64)
  467. .await?;
  468. Ok(fee.into())
  469. }
  470. /// Pay a NUT-18 payment request
  471. ///
  472. /// This method prepares and sends a payment for the given payment request.
  473. /// It will use the Nostr or HTTP transport specified in the request.
  474. ///
  475. /// # Arguments
  476. ///
  477. /// * `payment_request` - The NUT-18 payment request to pay
  478. /// * `custom_amount` - Optional amount to pay (required if request has no amount)
  479. pub async fn pay_request(
  480. &self,
  481. payment_request: std::sync::Arc<PaymentRequest>,
  482. custom_amount: Option<Amount>,
  483. ) -> Result<(), FfiError> {
  484. self.inner
  485. .pay_request(
  486. payment_request.inner().clone(),
  487. custom_amount.map(Into::into),
  488. )
  489. .await?;
  490. Ok(())
  491. }
  492. }
  493. /// BIP353 methods for Wallet
  494. #[cfg(not(target_arch = "wasm32"))]
  495. #[uniffi::export(async_runtime = "tokio")]
  496. impl Wallet {
  497. /// Get a quote for a BIP353 melt
  498. ///
  499. /// This method resolves a BIP353 address (e.g., "alice@example.com") to a Lightning offer
  500. /// and then creates a melt quote for that offer.
  501. pub async fn melt_bip353_quote(
  502. &self,
  503. bip353_address: String,
  504. amount_msat: Amount,
  505. ) -> Result<MeltQuote, FfiError> {
  506. let cdk_amount: cdk::Amount = amount_msat.into();
  507. let quote = self
  508. .inner
  509. .melt_bip353_quote(&bip353_address, cdk_amount)
  510. .await?;
  511. Ok(quote.into())
  512. }
  513. /// Get a quote for a Lightning address melt
  514. ///
  515. /// This method resolves a Lightning address (e.g., "alice@example.com") to a Lightning invoice
  516. /// and then creates a melt quote for that invoice.
  517. pub async fn melt_lightning_address_quote(
  518. &self,
  519. lightning_address: String,
  520. amount_msat: Amount,
  521. ) -> Result<MeltQuote, FfiError> {
  522. let cdk_amount: cdk::Amount = amount_msat.into();
  523. let quote = self
  524. .inner
  525. .melt_lightning_address_quote(&lightning_address, cdk_amount)
  526. .await?;
  527. Ok(quote.into())
  528. }
  529. /// Get a quote for a human-readable address melt
  530. ///
  531. /// This method accepts a human-readable address that could be either a BIP353 address
  532. /// or a Lightning address. It intelligently determines which to try based on mint support:
  533. ///
  534. /// 1. If the mint supports Bolt12, it tries BIP353 first
  535. /// 2. Falls back to Lightning address only if BIP353 DNS resolution fails
  536. /// 3. If BIP353 resolves but fails at the mint, it does NOT fall back to Lightning address
  537. /// 4. If the mint doesn't support Bolt12, it tries Lightning address directly
  538. pub async fn melt_human_readable(
  539. &self,
  540. address: String,
  541. amount_msat: Amount,
  542. ) -> Result<MeltQuote, FfiError> {
  543. let cdk_amount: cdk::Amount = amount_msat.into();
  544. let quote = self
  545. .inner
  546. .melt_human_readable_quote(&address, cdk_amount)
  547. .await?;
  548. Ok(quote.into())
  549. }
  550. }
  551. /// Auth methods for Wallet
  552. #[uniffi::export(async_runtime = "tokio")]
  553. impl Wallet {
  554. /// Set Clear Auth Token (CAT) for authentication
  555. pub async fn set_cat(&self, cat: String) -> Result<(), FfiError> {
  556. self.inner.set_cat(cat).await?;
  557. Ok(())
  558. }
  559. /// Set refresh token for authentication
  560. pub async fn set_refresh_token(&self, refresh_token: String) -> Result<(), FfiError> {
  561. self.inner.set_refresh_token(refresh_token).await?;
  562. Ok(())
  563. }
  564. /// Refresh access token using the stored refresh token
  565. pub async fn refresh_access_token(&self) -> Result<(), FfiError> {
  566. self.inner.refresh_access_token().await?;
  567. Ok(())
  568. }
  569. /// Mint blind auth tokens
  570. pub async fn mint_blind_auth(&self, amount: Amount) -> Result<Proofs, FfiError> {
  571. let proofs = self.inner.mint_blind_auth(amount.into()).await?;
  572. Ok(proofs.into_iter().map(|p| p.into()).collect())
  573. }
  574. /// Get unspent auth proofs
  575. pub async fn get_unspent_auth_proofs(&self) -> Result<Vec<AuthProof>, FfiError> {
  576. let auth_proofs = self.inner.get_unspent_auth_proofs().await?;
  577. Ok(auth_proofs.into_iter().map(Into::into).collect())
  578. }
  579. }
  580. /// Configuration for creating wallets
  581. #[derive(Debug, Clone, uniffi::Record)]
  582. pub struct WalletConfig {
  583. pub target_proof_count: Option<u32>,
  584. }
  585. /// Generates a new random mnemonic phrase
  586. #[uniffi::export]
  587. pub fn generate_mnemonic() -> Result<String, FfiError> {
  588. let mnemonic = Mnemonic::generate(12)
  589. .map_err(|e| FfiError::internal(format!("Failed to generate mnemonic: {}", e)))?;
  590. Ok(mnemonic.to_string())
  591. }
  592. /// Converts a mnemonic phrase to its entropy bytes
  593. #[uniffi::export]
  594. pub fn mnemonic_to_entropy(mnemonic: String) -> Result<Vec<u8>, FfiError> {
  595. let m = Mnemonic::parse(&mnemonic)
  596. .map_err(|e| FfiError::internal(format!("Invalid mnemonic: {}", e)))?;
  597. Ok(m.to_entropy())
  598. }