wallet.rs 22 KB

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