multi_mint_wallet.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. //! FFI MultiMintWallet bindings
  2. use std::collections::HashMap;
  3. use std::str::FromStr;
  4. use std::sync::Arc;
  5. use bip39::Mnemonic;
  6. use cdk::wallet::multi_mint_wallet::{
  7. MultiMintReceiveOptions as CdkMultiMintReceiveOptions,
  8. MultiMintSendOptions as CdkMultiMintSendOptions, MultiMintWallet as CdkMultiMintWallet,
  9. TokenData as CdkTokenData, TransferMode as CdkTransferMode,
  10. TransferResult as CdkTransferResult,
  11. };
  12. use crate::error::FfiError;
  13. use crate::token::Token;
  14. use crate::types::payment_request::{
  15. CreateRequestParams, CreateRequestResult, NostrWaitInfo, PaymentRequest,
  16. };
  17. use crate::types::*;
  18. /// FFI-compatible MultiMintWallet
  19. #[derive(uniffi::Object)]
  20. pub struct MultiMintWallet {
  21. inner: Arc<CdkMultiMintWallet>,
  22. }
  23. #[uniffi::export(async_runtime = "tokio")]
  24. impl MultiMintWallet {
  25. /// Create a new MultiMintWallet from mnemonic using WalletDatabaseFfi trait
  26. #[uniffi::constructor]
  27. pub fn new(
  28. unit: CurrencyUnit,
  29. mnemonic: String,
  30. db: Arc<dyn crate::database::WalletDatabase>,
  31. ) -> Result<Self, FfiError> {
  32. // Parse mnemonic and generate seed without passphrase
  33. let m = Mnemonic::parse(&mnemonic)
  34. .map_err(|e| FfiError::InvalidMnemonic { msg: e.to_string() })?;
  35. let seed = m.to_seed_normalized("");
  36. // Convert the FFI database trait to a CDK database implementation
  37. let localstore = crate::database::create_cdk_database_from_ffi(db);
  38. let wallet = match tokio::runtime::Handle::try_current() {
  39. Ok(handle) => tokio::task::block_in_place(|| {
  40. handle.block_on(async move {
  41. CdkMultiMintWallet::new(localstore, seed, unit.into()).await
  42. })
  43. }),
  44. Err(_) => {
  45. // No current runtime, create a new one
  46. tokio::runtime::Runtime::new()
  47. .map_err(|e| FfiError::Database {
  48. msg: format!("Failed to create runtime: {}", e),
  49. })?
  50. .block_on(async move {
  51. CdkMultiMintWallet::new(localstore, seed, unit.into()).await
  52. })
  53. }
  54. }?;
  55. Ok(Self {
  56. inner: Arc::new(wallet),
  57. })
  58. }
  59. /// Create a new MultiMintWallet with proxy configuration
  60. #[uniffi::constructor]
  61. pub fn new_with_proxy(
  62. unit: CurrencyUnit,
  63. mnemonic: String,
  64. db: Arc<dyn crate::database::WalletDatabase>,
  65. proxy_url: String,
  66. ) -> Result<Self, FfiError> {
  67. // Parse mnemonic and generate seed without passphrase
  68. let m = Mnemonic::parse(&mnemonic)
  69. .map_err(|e| FfiError::InvalidMnemonic { msg: e.to_string() })?;
  70. let seed = m.to_seed_normalized("");
  71. // Convert the FFI database trait to a CDK database implementation
  72. let localstore = crate::database::create_cdk_database_from_ffi(db);
  73. // Parse proxy URL
  74. let proxy_url =
  75. url::Url::parse(&proxy_url).map_err(|e| FfiError::InvalidUrl { msg: e.to_string() })?;
  76. let wallet = match tokio::runtime::Handle::try_current() {
  77. Ok(handle) => tokio::task::block_in_place(|| {
  78. handle.block_on(async move {
  79. CdkMultiMintWallet::new_with_proxy(localstore, seed, unit.into(), proxy_url)
  80. .await
  81. })
  82. }),
  83. Err(_) => {
  84. // No current runtime, create a new one
  85. tokio::runtime::Runtime::new()
  86. .map_err(|e| FfiError::Database {
  87. msg: format!("Failed to create runtime: {}", e),
  88. })?
  89. .block_on(async move {
  90. CdkMultiMintWallet::new_with_proxy(localstore, seed, unit.into(), proxy_url)
  91. .await
  92. })
  93. }
  94. }?;
  95. Ok(Self {
  96. inner: Arc::new(wallet),
  97. })
  98. }
  99. /// Get the currency unit for this wallet
  100. pub fn unit(&self) -> CurrencyUnit {
  101. self.inner.unit().clone().into()
  102. }
  103. /// Set metadata cache TTL (time-to-live) in seconds for a specific mint
  104. ///
  105. /// Controls how long cached mint metadata (keysets, keys, mint info) is considered fresh
  106. /// before requiring a refresh from the mint server for a specific mint.
  107. ///
  108. /// # Arguments
  109. ///
  110. /// * `mint_url` - The mint URL to set the TTL for
  111. /// * `ttl_secs` - Optional TTL in seconds. If None, cache never expires.
  112. pub async fn set_metadata_cache_ttl_for_mint(
  113. &self,
  114. mint_url: MintUrl,
  115. ttl_secs: Option<u64>,
  116. ) -> Result<(), FfiError> {
  117. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  118. let wallets = self.inner.get_wallets().await;
  119. if let Some(wallet) = wallets.iter().find(|w| w.mint_url == cdk_mint_url) {
  120. let ttl = ttl_secs.map(std::time::Duration::from_secs);
  121. wallet.set_metadata_cache_ttl(ttl);
  122. Ok(())
  123. } else {
  124. Err(FfiError::Generic {
  125. msg: format!("Mint not found: {}", cdk_mint_url),
  126. })
  127. }
  128. }
  129. /// Set metadata cache TTL (time-to-live) in seconds for all mints
  130. ///
  131. /// Controls how long cached mint metadata is considered fresh for all mints
  132. /// in this MultiMintWallet.
  133. ///
  134. /// # Arguments
  135. ///
  136. /// * `ttl_secs` - Optional TTL in seconds. If None, cache never expires for any mint.
  137. pub async fn set_metadata_cache_ttl_for_all_mints(&self, ttl_secs: Option<u64>) {
  138. let wallets = self.inner.get_wallets().await;
  139. let ttl = ttl_secs.map(std::time::Duration::from_secs);
  140. for wallet in wallets.iter() {
  141. wallet.set_metadata_cache_ttl(ttl);
  142. }
  143. }
  144. /// Add a mint to this MultiMintWallet
  145. pub async fn add_mint(
  146. &self,
  147. mint_url: MintUrl,
  148. target_proof_count: Option<u32>,
  149. ) -> Result<(), FfiError> {
  150. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  151. if let Some(count) = target_proof_count {
  152. let config = cdk::wallet::multi_mint_wallet::WalletConfig::new()
  153. .with_target_proof_count(count as usize);
  154. self.inner
  155. .add_mint_with_config(cdk_mint_url, config)
  156. .await?;
  157. } else {
  158. self.inner.add_mint(cdk_mint_url).await?;
  159. }
  160. Ok(())
  161. }
  162. /// Remove mint from MultiMintWallet
  163. pub async fn remove_mint(&self, mint_url: MintUrl) {
  164. let url_str = mint_url.url.clone();
  165. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into().unwrap_or_else(|_| {
  166. // If conversion fails, we can't remove the mint, but we shouldn't panic
  167. // This is a best-effort operation
  168. cdk::mint_url::MintUrl::from_str(&url_str).unwrap_or_else(|_| {
  169. // Last resort: create a dummy URL that won't match anything
  170. cdk::mint_url::MintUrl::from_str("https://invalid.mint")
  171. .expect("Valid hardcoded URL")
  172. })
  173. });
  174. self.inner.remove_mint(&cdk_mint_url).await;
  175. }
  176. /// Check if mint is in wallet
  177. pub async fn has_mint(&self, mint_url: MintUrl) -> bool {
  178. if let Ok(cdk_mint_url) = mint_url.try_into() {
  179. self.inner.has_mint(&cdk_mint_url).await
  180. } else {
  181. false
  182. }
  183. }
  184. pub async fn get_mint_keysets(&self, mint_url: MintUrl) -> Result<Vec<KeySetInfo>, FfiError> {
  185. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  186. let keysets = self.inner.get_mint_keysets(&cdk_mint_url).await?;
  187. let keysets = keysets.into_iter().map(|k| k.into()).collect();
  188. Ok(keysets)
  189. }
  190. /// Get token data (mint URL and proofs) from a token
  191. ///
  192. /// This method extracts the mint URL and proofs from a token. It will automatically
  193. /// fetch the keysets from the mint if needed to properly decode the proofs.
  194. ///
  195. /// The mint must already be added to the wallet. If the mint is not in the wallet,
  196. /// use `add_mint` first.
  197. pub async fn get_token_data(&self, token: Arc<Token>) -> Result<TokenData, FfiError> {
  198. let token_data = self.inner.get_token_data(&token.inner).await?;
  199. Ok(token_data.into())
  200. }
  201. /// Get wallet balances for all mints
  202. pub async fn get_balances(&self) -> Result<BalanceMap, FfiError> {
  203. let balances = self.inner.get_balances().await?;
  204. let mut balance_map = HashMap::new();
  205. for (mint_url, amount) in balances {
  206. balance_map.insert(mint_url.to_string(), amount.into());
  207. }
  208. Ok(balance_map)
  209. }
  210. /// Get total balance across all mints
  211. pub async fn total_balance(&self) -> Result<Amount, FfiError> {
  212. let total = self.inner.total_balance().await?;
  213. Ok(total.into())
  214. }
  215. /// List proofs for all mints
  216. pub async fn list_proofs(&self) -> Result<ProofsByMint, FfiError> {
  217. let proofs = self.inner.list_proofs().await?;
  218. let mut proofs_by_mint = HashMap::new();
  219. for (mint_url, mint_proofs) in proofs {
  220. let ffi_proofs: Vec<Proof> = mint_proofs.into_iter().map(|p| p.into()).collect();
  221. proofs_by_mint.insert(mint_url.to_string(), ffi_proofs);
  222. }
  223. Ok(proofs_by_mint)
  224. }
  225. /// Check the state of proofs at a specific mint
  226. pub async fn check_proofs_state(
  227. &self,
  228. mint_url: MintUrl,
  229. proofs: Proofs,
  230. ) -> Result<Vec<ProofState>, FfiError> {
  231. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  232. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  233. proofs.into_iter().map(|p| p.try_into()).collect();
  234. let cdk_proofs = cdk_proofs?;
  235. let states = self
  236. .inner
  237. .check_proofs_state(&cdk_mint_url, cdk_proofs)
  238. .await?;
  239. Ok(states.into_iter().map(|s| s.into()).collect())
  240. }
  241. /// Receive token
  242. pub async fn receive(
  243. &self,
  244. token: Arc<Token>,
  245. options: MultiMintReceiveOptions,
  246. ) -> Result<Amount, FfiError> {
  247. let amount = self
  248. .inner
  249. .receive(&token.to_string(), options.into())
  250. .await?;
  251. Ok(amount.into())
  252. }
  253. /// Restore wallets for a specific mint
  254. pub async fn restore(&self, mint_url: MintUrl) -> Result<Amount, FfiError> {
  255. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  256. let amount = self.inner.restore(&cdk_mint_url).await?;
  257. Ok(amount.into())
  258. }
  259. /// Prepare a send operation from a specific mint
  260. pub async fn prepare_send(
  261. &self,
  262. mint_url: MintUrl,
  263. amount: Amount,
  264. options: MultiMintSendOptions,
  265. ) -> Result<Arc<PreparedSend>, FfiError> {
  266. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  267. let prepared = self
  268. .inner
  269. .prepare_send(cdk_mint_url, amount.into(), options.into())
  270. .await?;
  271. Ok(Arc::new(prepared.into()))
  272. }
  273. /// Get a mint quote from a specific mint
  274. pub async fn mint_quote(
  275. &self,
  276. mint_url: MintUrl,
  277. amount: Amount,
  278. description: Option<String>,
  279. ) -> Result<MintQuote, FfiError> {
  280. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  281. let quote = self
  282. .inner
  283. .mint_quote(&cdk_mint_url, amount.into(), description)
  284. .await?;
  285. Ok(quote.into())
  286. }
  287. /// Check a specific mint quote status
  288. pub async fn check_mint_quote(
  289. &self,
  290. mint_url: MintUrl,
  291. quote_id: String,
  292. ) -> Result<MintQuote, FfiError> {
  293. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  294. let quote = self
  295. .inner
  296. .check_mint_quote(&cdk_mint_url, &quote_id)
  297. .await?;
  298. Ok(quote.into())
  299. }
  300. /// Mint tokens at a specific mint
  301. pub async fn mint(
  302. &self,
  303. mint_url: MintUrl,
  304. quote_id: String,
  305. spending_conditions: Option<SpendingConditions>,
  306. ) -> Result<Proofs, FfiError> {
  307. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  308. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  309. let proofs = self
  310. .inner
  311. .mint(&cdk_mint_url, &quote_id, conditions)
  312. .await?;
  313. Ok(proofs.into_iter().map(|p| p.into()).collect())
  314. }
  315. /// Wait for a mint quote to be paid and automatically mint the proofs
  316. #[cfg(not(target_arch = "wasm32"))]
  317. pub async fn wait_for_mint_quote(
  318. &self,
  319. mint_url: MintUrl,
  320. quote_id: String,
  321. split_target: SplitTarget,
  322. spending_conditions: Option<SpendingConditions>,
  323. timeout_secs: u64,
  324. ) -> Result<Proofs, FfiError> {
  325. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  326. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  327. let proofs = self
  328. .inner
  329. .wait_for_mint_quote(
  330. &cdk_mint_url,
  331. &quote_id,
  332. split_target.into(),
  333. conditions,
  334. timeout_secs,
  335. )
  336. .await?;
  337. Ok(proofs.into_iter().map(|p| p.into()).collect())
  338. }
  339. /// Get a melt quote from a specific mint
  340. pub async fn melt_quote(
  341. &self,
  342. mint_url: MintUrl,
  343. request: String,
  344. options: Option<MeltOptions>,
  345. ) -> Result<MeltQuote, FfiError> {
  346. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  347. let cdk_options = options.map(Into::into);
  348. let quote = self
  349. .inner
  350. .melt_quote(&cdk_mint_url, request, cdk_options)
  351. .await?;
  352. Ok(quote.into())
  353. }
  354. /// Get a melt quote for a BIP353 human-readable address
  355. ///
  356. /// This method resolves a BIP353 address (e.g., "alice@example.com") to a Lightning offer
  357. /// and then creates a melt quote for that offer at the specified mint.
  358. ///
  359. /// # Arguments
  360. ///
  361. /// * `mint_url` - The mint to use for creating the melt quote
  362. /// * `bip353_address` - Human-readable address in the format "user@domain.com"
  363. /// * `amount_msat` - Amount to pay in millisatoshis
  364. #[cfg(not(target_arch = "wasm32"))]
  365. pub async fn melt_bip353_quote(
  366. &self,
  367. mint_url: MintUrl,
  368. bip353_address: String,
  369. amount_msat: u64,
  370. ) -> Result<MeltQuote, FfiError> {
  371. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  372. let cdk_amount = cdk::Amount::from(amount_msat);
  373. let quote = self
  374. .inner
  375. .melt_bip353_quote(&cdk_mint_url, &bip353_address, cdk_amount)
  376. .await?;
  377. Ok(quote.into())
  378. }
  379. /// Get a melt quote for a Lightning address
  380. ///
  381. /// This method resolves a Lightning address (e.g., "alice@example.com") to a Lightning invoice
  382. /// and then creates a melt quote for that invoice at the specified mint.
  383. ///
  384. /// # Arguments
  385. ///
  386. /// * `mint_url` - The mint to use for creating the melt quote
  387. /// * `lightning_address` - Lightning address in the format "user@domain.com"
  388. /// * `amount_msat` - Amount to pay in millisatoshis
  389. pub async fn melt_lightning_address_quote(
  390. &self,
  391. mint_url: MintUrl,
  392. lightning_address: String,
  393. amount_msat: u64,
  394. ) -> Result<MeltQuote, FfiError> {
  395. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  396. let cdk_amount = cdk::Amount::from(amount_msat);
  397. let quote = self
  398. .inner
  399. .melt_lightning_address_quote(&cdk_mint_url, &lightning_address, cdk_amount)
  400. .await?;
  401. Ok(quote.into())
  402. }
  403. /// Get a melt quote for a human-readable address
  404. ///
  405. /// This method accepts a human-readable address that could be either a BIP353 address
  406. /// or a Lightning address. It intelligently determines which to try based on mint support:
  407. ///
  408. /// 1. If the mint supports Bolt12, it tries BIP353 first
  409. /// 2. Falls back to Lightning address only if BIP353 DNS resolution fails
  410. /// 3. If BIP353 resolves but fails at the mint, it does NOT fall back to Lightning address
  411. /// 4. If the mint doesn't support Bolt12, it tries Lightning address directly
  412. ///
  413. /// # Arguments
  414. ///
  415. /// * `mint_url` - The mint to use for creating the melt quote
  416. /// * `address` - Human-readable address (BIP353 or Lightning address)
  417. /// * `amount_msat` - Amount to pay in millisatoshis
  418. #[cfg(not(target_arch = "wasm32"))]
  419. pub async fn melt_human_readable_quote(
  420. &self,
  421. mint_url: MintUrl,
  422. address: String,
  423. amount_msat: u64,
  424. ) -> Result<MeltQuote, FfiError> {
  425. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  426. let cdk_amount = cdk::Amount::from(amount_msat);
  427. let quote = self
  428. .inner
  429. .melt_human_readable_quote(&cdk_mint_url, &address, cdk_amount)
  430. .await?;
  431. Ok(quote.into())
  432. }
  433. /// Melt tokens
  434. pub async fn melt_with_mint(
  435. &self,
  436. mint_url: MintUrl,
  437. quote_id: String,
  438. ) -> Result<Melted, FfiError> {
  439. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  440. let melted = self.inner.melt_with_mint(&cdk_mint_url, &quote_id).await?;
  441. Ok(melted.into())
  442. }
  443. /// Melt specific proofs from a specific mint
  444. ///
  445. /// This method allows melting proofs that may not be in the wallet's database,
  446. /// similar to how `receive_proofs` handles external proofs. The proofs will be
  447. /// added to the database and used for the melt operation.
  448. ///
  449. /// # Arguments
  450. ///
  451. /// * `mint_url` - The mint to use for the melt operation
  452. /// * `quote_id` - The melt quote ID (obtained from `melt_quote`)
  453. /// * `proofs` - The proofs to melt (can be external proofs not in the wallet's database)
  454. ///
  455. /// # Returns
  456. ///
  457. /// A `Melted` result containing the payment details and any change proofs
  458. pub async fn melt_proofs(
  459. &self,
  460. mint_url: MintUrl,
  461. quote_id: String,
  462. proofs: Proofs,
  463. ) -> Result<Melted, FfiError> {
  464. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  465. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  466. proofs.into_iter().map(|p| p.try_into()).collect();
  467. let cdk_proofs = cdk_proofs?;
  468. let melted = self
  469. .inner
  470. .melt_proofs(&cdk_mint_url, &quote_id, cdk_proofs)
  471. .await?;
  472. Ok(melted.into())
  473. }
  474. /// Check melt quote status
  475. pub async fn check_melt_quote(
  476. &self,
  477. mint_url: MintUrl,
  478. quote_id: String,
  479. ) -> Result<MeltQuote, FfiError> {
  480. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  481. let melted = self
  482. .inner
  483. .check_melt_quote(&cdk_mint_url, &quote_id)
  484. .await?;
  485. Ok(melted.into())
  486. }
  487. /// Melt tokens (pay a bolt11 invoice)
  488. pub async fn melt(
  489. &self,
  490. bolt11: String,
  491. options: Option<MeltOptions>,
  492. max_fee: Option<Amount>,
  493. ) -> Result<Melted, FfiError> {
  494. let cdk_options = options.map(Into::into);
  495. let cdk_max_fee = max_fee.map(Into::into);
  496. let melted = self.inner.melt(&bolt11, cdk_options, cdk_max_fee).await?;
  497. Ok(melted.into())
  498. }
  499. /// Transfer funds between mints
  500. pub async fn transfer(
  501. &self,
  502. source_mint: MintUrl,
  503. target_mint: MintUrl,
  504. transfer_mode: TransferMode,
  505. ) -> Result<TransferResult, FfiError> {
  506. let source_cdk: cdk::mint_url::MintUrl = source_mint.try_into()?;
  507. let target_cdk: cdk::mint_url::MintUrl = target_mint.try_into()?;
  508. let result = self
  509. .inner
  510. .transfer(&source_cdk, &target_cdk, transfer_mode.into())
  511. .await?;
  512. Ok(result.into())
  513. }
  514. /// Swap proofs with automatic wallet selection
  515. pub async fn swap(
  516. &self,
  517. amount: Option<Amount>,
  518. spending_conditions: Option<SpendingConditions>,
  519. ) -> Result<Option<Proofs>, FfiError> {
  520. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  521. let result = self.inner.swap(amount.map(Into::into), conditions).await?;
  522. Ok(result.map(|proofs| proofs.into_iter().map(|p| p.into()).collect()))
  523. }
  524. /// List transactions from all mints
  525. pub async fn list_transactions(
  526. &self,
  527. direction: Option<TransactionDirection>,
  528. ) -> Result<Vec<Transaction>, FfiError> {
  529. let cdk_direction = direction.map(Into::into);
  530. let transactions = self.inner.list_transactions(cdk_direction).await?;
  531. Ok(transactions.into_iter().map(Into::into).collect())
  532. }
  533. /// Get proofs for a transaction by transaction ID
  534. ///
  535. /// This retrieves all proofs associated with a transaction. If `mint_url` is provided,
  536. /// it will only check that specific mint's wallet. Otherwise, it searches across all
  537. /// wallets to find which mint the transaction belongs to.
  538. ///
  539. /// # Arguments
  540. ///
  541. /// * `id` - The transaction ID
  542. /// * `mint_url` - Optional mint URL to check directly, avoiding iteration over all wallets
  543. pub async fn get_proofs_for_transaction(
  544. &self,
  545. id: TransactionId,
  546. mint_url: Option<MintUrl>,
  547. ) -> Result<Vec<Proof>, FfiError> {
  548. let cdk_id = id.try_into()?;
  549. let cdk_mint_url = mint_url.map(|url| url.try_into()).transpose()?;
  550. let proofs = self
  551. .inner
  552. .get_proofs_for_transaction(cdk_id, cdk_mint_url)
  553. .await?;
  554. Ok(proofs.into_iter().map(Into::into).collect())
  555. }
  556. /// Check all mint quotes and mint if paid
  557. pub async fn check_all_mint_quotes(
  558. &self,
  559. mint_url: Option<MintUrl>,
  560. ) -> Result<Amount, FfiError> {
  561. let cdk_mint_url = mint_url.map(|url| url.try_into()).transpose()?;
  562. let amount = self.inner.check_all_mint_quotes(cdk_mint_url).await?;
  563. Ok(amount.into())
  564. }
  565. /// Consolidate proofs across all mints
  566. pub async fn consolidate(&self) -> Result<Amount, FfiError> {
  567. let amount = self.inner.consolidate().await?;
  568. Ok(amount.into())
  569. }
  570. /// Get list of mint URLs
  571. pub async fn get_mint_urls(&self) -> Vec<String> {
  572. let wallets = self.inner.get_wallets().await;
  573. wallets.iter().map(|w| w.mint_url.to_string()).collect()
  574. }
  575. /// Get all wallets from MultiMintWallet
  576. pub async fn get_wallets(&self) -> Vec<Arc<crate::wallet::Wallet>> {
  577. let wallets = self.inner.get_wallets().await;
  578. wallets
  579. .into_iter()
  580. .map(|w| Arc::new(crate::wallet::Wallet::from_inner(Arc::new(w))))
  581. .collect()
  582. }
  583. /// Get a specific wallet from MultiMintWallet by mint URL
  584. pub async fn get_wallet(&self, mint_url: MintUrl) -> Option<Arc<crate::wallet::Wallet>> {
  585. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into().ok()?;
  586. let wallet = self.inner.get_wallet(&cdk_mint_url).await?;
  587. Some(Arc::new(crate::wallet::Wallet::from_inner(Arc::new(
  588. wallet,
  589. ))))
  590. }
  591. /// Verify token DLEQ proofs
  592. pub async fn verify_token_dleq(&self, token: Arc<Token>) -> Result<(), FfiError> {
  593. let cdk_token = token.inner.clone();
  594. self.inner.verify_token_dleq(&cdk_token).await?;
  595. Ok(())
  596. }
  597. /// Query mint for current mint information
  598. pub async fn fetch_mint_info(&self, mint_url: MintUrl) -> Result<Option<MintInfo>, FfiError> {
  599. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  600. let mint_info = self.inner.fetch_mint_info(&cdk_mint_url).await?;
  601. Ok(mint_info.map(Into::into))
  602. }
  603. /// Get mint info for all wallets
  604. ///
  605. /// This method loads the mint info for each wallet in the MultiMintWallet
  606. /// and returns a map of mint URLs to their corresponding mint info.
  607. ///
  608. /// Uses cached mint info when available, only fetching from the mint if the cache
  609. /// has expired.
  610. pub async fn get_all_mint_info(&self) -> Result<MintInfoMap, FfiError> {
  611. let mint_infos = self.inner.get_all_mint_info().await?;
  612. let mut result = HashMap::new();
  613. for (mint_url, mint_info) in mint_infos {
  614. result.insert(mint_url.to_string(), mint_info.into());
  615. }
  616. Ok(result)
  617. }
  618. }
  619. /// Payment request methods for MultiMintWallet
  620. #[uniffi::export(async_runtime = "tokio")]
  621. impl MultiMintWallet {
  622. /// Create a NUT-18 payment request
  623. ///
  624. /// Creates a payment request that can be shared to receive Cashu tokens.
  625. /// The request can include optional amount, description, and spending conditions.
  626. ///
  627. /// # Arguments
  628. ///
  629. /// * `params` - Parameters for creating the payment request
  630. ///
  631. /// # Transport Options
  632. ///
  633. /// - `"nostr"` - Uses Nostr relays for privacy-preserving delivery (requires nostr_relays)
  634. /// - `"http"` - Uses HTTP POST for delivery (requires http_url)
  635. /// - `"none"` - No transport; token must be delivered out-of-band
  636. ///
  637. /// # Example
  638. ///
  639. /// ```ignore
  640. /// let params = CreateRequestParams {
  641. /// amount: Some(100),
  642. /// unit: "sat".to_string(),
  643. /// description: Some("Coffee payment".to_string()),
  644. /// transport: "http".to_string(),
  645. /// http_url: Some("https://example.com/callback".to_string()),
  646. /// ..Default::default()
  647. /// };
  648. /// let result = wallet.create_request(params).await?;
  649. /// println!("Share this request: {}", result.payment_request.to_string_encoded());
  650. ///
  651. /// // If using Nostr transport, wait for payment:
  652. /// if let Some(nostr_info) = result.nostr_wait_info {
  653. /// let amount = wallet.wait_for_nostr_payment(nostr_info).await?;
  654. /// println!("Received {} sats", amount);
  655. /// }
  656. /// ```
  657. pub async fn create_request(
  658. &self,
  659. params: CreateRequestParams,
  660. ) -> Result<CreateRequestResult, FfiError> {
  661. let (payment_request, nostr_wait_info) = self.inner.create_request(params.into()).await?;
  662. Ok(CreateRequestResult {
  663. payment_request: Arc::new(PaymentRequest::from_inner(payment_request)),
  664. nostr_wait_info: nostr_wait_info.map(|info| Arc::new(NostrWaitInfo::from_inner(info))),
  665. })
  666. }
  667. /// Wait for a Nostr payment and receive it into the wallet
  668. ///
  669. /// This method connects to the Nostr relays specified in the `NostrWaitInfo`,
  670. /// subscribes for incoming payment events, and receives the first valid
  671. /// payment into the wallet.
  672. ///
  673. /// # Arguments
  674. ///
  675. /// * `info` - The Nostr wait info returned from `create_request` when using Nostr transport
  676. ///
  677. /// # Returns
  678. ///
  679. /// The amount received from the payment.
  680. ///
  681. /// # Example
  682. ///
  683. /// ```ignore
  684. /// let result = wallet.create_request(params).await?;
  685. /// if let Some(nostr_info) = result.nostr_wait_info {
  686. /// let amount = wallet.wait_for_nostr_payment(nostr_info).await?;
  687. /// println!("Received {} sats", amount);
  688. /// }
  689. /// ```
  690. pub async fn wait_for_nostr_payment(
  691. &self,
  692. info: Arc<NostrWaitInfo>,
  693. ) -> Result<Amount, FfiError> {
  694. // We need to clone the inner NostrWaitInfo since we can't consume the Arc
  695. let info_inner = cdk::wallet::payment_request::NostrWaitInfo {
  696. keys: info.inner().keys.clone(),
  697. relays: info.inner().relays.clone(),
  698. pubkey: info.inner().pubkey,
  699. };
  700. let amount = self
  701. .inner
  702. .wait_for_nostr_payment(info_inner)
  703. .await
  704. .map_err(|e| FfiError::Generic { msg: e.to_string() })?;
  705. Ok(amount.into())
  706. }
  707. }
  708. /// Auth methods for MultiMintWallet
  709. #[uniffi::export(async_runtime = "tokio")]
  710. impl MultiMintWallet {
  711. /// Set Clear Auth Token (CAT) for a specific mint
  712. pub async fn set_cat(&self, mint_url: MintUrl, cat: String) -> Result<(), FfiError> {
  713. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  714. self.inner.set_cat(&cdk_mint_url, cat).await?;
  715. Ok(())
  716. }
  717. /// Set refresh token for a specific mint
  718. pub async fn set_refresh_token(
  719. &self,
  720. mint_url: MintUrl,
  721. refresh_token: String,
  722. ) -> Result<(), FfiError> {
  723. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  724. self.inner
  725. .set_refresh_token(&cdk_mint_url, refresh_token)
  726. .await?;
  727. Ok(())
  728. }
  729. /// Refresh access token for a specific mint using the stored refresh token
  730. pub async fn refresh_access_token(&self, mint_url: MintUrl) -> Result<(), FfiError> {
  731. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  732. self.inner.refresh_access_token(&cdk_mint_url).await?;
  733. Ok(())
  734. }
  735. /// Mint blind auth tokens at a specific mint
  736. pub async fn mint_blind_auth(
  737. &self,
  738. mint_url: MintUrl,
  739. amount: Amount,
  740. ) -> Result<Proofs, FfiError> {
  741. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  742. let proofs = self
  743. .inner
  744. .mint_blind_auth(&cdk_mint_url, amount.into())
  745. .await?;
  746. Ok(proofs.into_iter().map(|p| p.into()).collect())
  747. }
  748. /// Get unspent auth proofs for a specific mint
  749. pub async fn get_unspent_auth_proofs(
  750. &self,
  751. mint_url: MintUrl,
  752. ) -> Result<Vec<AuthProof>, FfiError> {
  753. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  754. let auth_proofs = self.inner.get_unspent_auth_proofs(&cdk_mint_url).await?;
  755. Ok(auth_proofs.into_iter().map(Into::into).collect())
  756. }
  757. }
  758. /// Transfer mode for mint-to-mint transfers
  759. #[derive(Debug, Clone, uniffi::Enum)]
  760. pub enum TransferMode {
  761. /// Transfer exact amount to target (target receives specified amount)
  762. ExactReceive { amount: Amount },
  763. /// Transfer all available balance (source will be emptied)
  764. FullBalance,
  765. }
  766. impl From<TransferMode> for CdkTransferMode {
  767. fn from(mode: TransferMode) -> Self {
  768. match mode {
  769. TransferMode::ExactReceive { amount } => CdkTransferMode::ExactReceive(amount.into()),
  770. TransferMode::FullBalance => CdkTransferMode::FullBalance,
  771. }
  772. }
  773. }
  774. /// Result of a transfer operation with detailed breakdown
  775. #[derive(Debug, Clone, uniffi::Record)]
  776. pub struct TransferResult {
  777. /// Amount deducted from source mint
  778. pub amount_sent: Amount,
  779. /// Amount received at target mint
  780. pub amount_received: Amount,
  781. /// Total fees paid for the transfer
  782. pub fees_paid: Amount,
  783. /// Remaining balance in source mint after transfer
  784. pub source_balance_after: Amount,
  785. /// New balance in target mint after transfer
  786. pub target_balance_after: Amount,
  787. }
  788. impl From<CdkTransferResult> for TransferResult {
  789. fn from(result: CdkTransferResult) -> Self {
  790. Self {
  791. amount_sent: result.amount_sent.into(),
  792. amount_received: result.amount_received.into(),
  793. fees_paid: result.fees_paid.into(),
  794. source_balance_after: result.source_balance_after.into(),
  795. target_balance_after: result.target_balance_after.into(),
  796. }
  797. }
  798. }
  799. /// Data extracted from a token including mint URL, proofs, and memo
  800. #[derive(Debug, Clone, uniffi::Record)]
  801. pub struct TokenData {
  802. /// The mint URL from the token
  803. pub mint_url: MintUrl,
  804. /// The proofs contained in the token
  805. pub proofs: Proofs,
  806. /// The memo from the token, if present
  807. pub memo: Option<String>,
  808. }
  809. impl From<CdkTokenData> for TokenData {
  810. fn from(data: CdkTokenData) -> Self {
  811. Self {
  812. mint_url: data.mint_url.into(),
  813. proofs: data.proofs.into_iter().map(|p| p.into()).collect(),
  814. memo: data.memo,
  815. }
  816. }
  817. }
  818. /// Options for receiving tokens in multi-mint context
  819. #[derive(Debug, Clone, Default, uniffi::Record)]
  820. pub struct MultiMintReceiveOptions {
  821. /// Whether to allow receiving from untrusted (not yet added) mints
  822. pub allow_untrusted: bool,
  823. /// Mint URL to transfer tokens to from untrusted mints (None means keep in original mint)
  824. pub transfer_to_mint: Option<MintUrl>,
  825. /// Base receive options to apply to the wallet receive
  826. pub receive_options: ReceiveOptions,
  827. }
  828. impl From<MultiMintReceiveOptions> for CdkMultiMintReceiveOptions {
  829. fn from(options: MultiMintReceiveOptions) -> Self {
  830. let mut opts = CdkMultiMintReceiveOptions::new();
  831. opts.allow_untrusted = options.allow_untrusted;
  832. opts.transfer_to_mint = options.transfer_to_mint.and_then(|url| url.try_into().ok());
  833. opts.receive_options = options.receive_options.into();
  834. opts
  835. }
  836. }
  837. /// Options for sending tokens in multi-mint context
  838. #[derive(Debug, Clone, Default, uniffi::Record)]
  839. pub struct MultiMintSendOptions {
  840. /// Whether to allow transferring funds from other mints if needed
  841. pub allow_transfer: bool,
  842. /// Maximum amount to transfer from other mints (optional limit)
  843. pub max_transfer_amount: Option<Amount>,
  844. /// Specific mint URLs allowed for transfers (empty means all mints allowed)
  845. pub allowed_mints: Vec<MintUrl>,
  846. /// Specific mint URLs to exclude from transfers
  847. pub excluded_mints: Vec<MintUrl>,
  848. /// Base send options to apply to the wallet send
  849. pub send_options: SendOptions,
  850. }
  851. impl From<MultiMintSendOptions> for CdkMultiMintSendOptions {
  852. fn from(options: MultiMintSendOptions) -> Self {
  853. let mut opts = CdkMultiMintSendOptions::new();
  854. opts.allow_transfer = options.allow_transfer;
  855. opts.max_transfer_amount = options.max_transfer_amount.map(Into::into);
  856. opts.allowed_mints = options
  857. .allowed_mints
  858. .into_iter()
  859. .filter_map(|url| url.try_into().ok())
  860. .collect();
  861. opts.excluded_mints = options
  862. .excluded_mints
  863. .into_iter()
  864. .filter_map(|url| url.try_into().ok())
  865. .collect();
  866. opts.send_options = options.send_options.into();
  867. opts
  868. }
  869. }
  870. /// Type alias for balances by mint URL
  871. pub type BalanceMap = HashMap<String, Amount>;
  872. /// Type alias for proofs by mint URL
  873. pub type ProofsByMint = HashMap<String, Vec<Proof>>;
  874. /// Type alias for mint info by mint URL
  875. pub type MintInfoMap = HashMap<String, MintInfo>;