multi_mint_wallet.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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").unwrap()
  171. })
  172. });
  173. self.inner.remove_mint(&cdk_mint_url).await;
  174. }
  175. /// Check if mint is in wallet
  176. pub async fn has_mint(&self, mint_url: MintUrl) -> bool {
  177. if let Ok(cdk_mint_url) = mint_url.try_into() {
  178. self.inner.has_mint(&cdk_mint_url).await
  179. } else {
  180. false
  181. }
  182. }
  183. pub async fn get_mint_keysets(&self, mint_url: MintUrl) -> Result<Vec<KeySetInfo>, FfiError> {
  184. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  185. let keysets = self.inner.get_mint_keysets(&cdk_mint_url).await?;
  186. let keysets = keysets.into_iter().map(|k| k.into()).collect();
  187. Ok(keysets)
  188. }
  189. /// Get token data (mint URL and proofs) from a token
  190. ///
  191. /// This method extracts the mint URL and proofs from a token. It will automatically
  192. /// fetch the keysets from the mint if needed to properly decode the proofs.
  193. ///
  194. /// The mint must already be added to the wallet. If the mint is not in the wallet,
  195. /// use `add_mint` first.
  196. pub async fn get_token_data(&self, token: Arc<Token>) -> Result<TokenData, FfiError> {
  197. let token_data = self.inner.get_token_data(&token.inner).await?;
  198. Ok(token_data.into())
  199. }
  200. /// Get wallet balances for all mints
  201. pub async fn get_balances(&self) -> Result<BalanceMap, FfiError> {
  202. let balances = self.inner.get_balances().await?;
  203. let mut balance_map = HashMap::new();
  204. for (mint_url, amount) in balances {
  205. balance_map.insert(mint_url.to_string(), amount.into());
  206. }
  207. Ok(balance_map)
  208. }
  209. /// Get total balance across all mints
  210. pub async fn total_balance(&self) -> Result<Amount, FfiError> {
  211. let total = self.inner.total_balance().await?;
  212. Ok(total.into())
  213. }
  214. /// List proofs for all mints
  215. pub async fn list_proofs(&self) -> Result<ProofsByMint, FfiError> {
  216. let proofs = self.inner.list_proofs().await?;
  217. let mut proofs_by_mint = HashMap::new();
  218. for (mint_url, mint_proofs) in proofs {
  219. let ffi_proofs: Vec<Proof> = mint_proofs.into_iter().map(|p| p.into()).collect();
  220. proofs_by_mint.insert(mint_url.to_string(), ffi_proofs);
  221. }
  222. Ok(proofs_by_mint)
  223. }
  224. /// Check the state of proofs at a specific mint
  225. pub async fn check_proofs_state(
  226. &self,
  227. mint_url: MintUrl,
  228. proofs: Proofs,
  229. ) -> Result<Vec<ProofState>, FfiError> {
  230. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  231. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  232. proofs.into_iter().map(|p| p.try_into()).collect();
  233. let cdk_proofs = cdk_proofs?;
  234. let states = self
  235. .inner
  236. .check_proofs_state(&cdk_mint_url, cdk_proofs)
  237. .await?;
  238. Ok(states.into_iter().map(|s| s.into()).collect())
  239. }
  240. /// Receive token
  241. pub async fn receive(
  242. &self,
  243. token: Arc<Token>,
  244. options: MultiMintReceiveOptions,
  245. ) -> Result<Amount, FfiError> {
  246. let amount = self
  247. .inner
  248. .receive(&token.to_string(), options.into())
  249. .await?;
  250. Ok(amount.into())
  251. }
  252. /// Restore wallets for a specific mint
  253. pub async fn restore(&self, mint_url: MintUrl) -> Result<Amount, FfiError> {
  254. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  255. let amount = self.inner.restore(&cdk_mint_url).await?;
  256. Ok(amount.into())
  257. }
  258. /// Prepare a send operation from a specific mint
  259. pub async fn prepare_send(
  260. &self,
  261. mint_url: MintUrl,
  262. amount: Amount,
  263. options: MultiMintSendOptions,
  264. ) -> Result<Arc<PreparedSend>, FfiError> {
  265. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  266. let prepared = self
  267. .inner
  268. .prepare_send(cdk_mint_url, amount.into(), options.into())
  269. .await?;
  270. Ok(Arc::new(prepared.into()))
  271. }
  272. /// Get a mint quote from a specific mint
  273. pub async fn mint_quote(
  274. &self,
  275. mint_url: MintUrl,
  276. amount: Amount,
  277. description: Option<String>,
  278. ) -> Result<MintQuote, FfiError> {
  279. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  280. let quote = self
  281. .inner
  282. .mint_quote(&cdk_mint_url, amount.into(), description)
  283. .await?;
  284. Ok(quote.into())
  285. }
  286. /// Check a specific mint quote status
  287. pub async fn check_mint_quote(
  288. &self,
  289. mint_url: MintUrl,
  290. quote_id: String,
  291. ) -> Result<MintQuote, FfiError> {
  292. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  293. let quote = self
  294. .inner
  295. .check_mint_quote(&cdk_mint_url, &quote_id)
  296. .await?;
  297. Ok(quote.into())
  298. }
  299. /// Mint tokens at a specific mint
  300. pub async fn mint(
  301. &self,
  302. mint_url: MintUrl,
  303. quote_id: String,
  304. spending_conditions: Option<SpendingConditions>,
  305. ) -> Result<Proofs, FfiError> {
  306. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  307. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  308. let proofs = self
  309. .inner
  310. .mint(&cdk_mint_url, &quote_id, conditions)
  311. .await?;
  312. Ok(proofs.into_iter().map(|p| p.into()).collect())
  313. }
  314. /// Wait for a mint quote to be paid and automatically mint the proofs
  315. #[cfg(not(target_arch = "wasm32"))]
  316. pub async fn wait_for_mint_quote(
  317. &self,
  318. mint_url: MintUrl,
  319. quote_id: String,
  320. split_target: SplitTarget,
  321. spending_conditions: Option<SpendingConditions>,
  322. timeout_secs: u64,
  323. ) -> Result<Proofs, FfiError> {
  324. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  325. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  326. let proofs = self
  327. .inner
  328. .wait_for_mint_quote(
  329. &cdk_mint_url,
  330. &quote_id,
  331. split_target.into(),
  332. conditions,
  333. timeout_secs,
  334. )
  335. .await?;
  336. Ok(proofs.into_iter().map(|p| p.into()).collect())
  337. }
  338. /// Get a melt quote from a specific mint
  339. pub async fn melt_quote(
  340. &self,
  341. mint_url: MintUrl,
  342. request: String,
  343. options: Option<MeltOptions>,
  344. ) -> Result<MeltQuote, FfiError> {
  345. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  346. let cdk_options = options.map(Into::into);
  347. let quote = self
  348. .inner
  349. .melt_quote(&cdk_mint_url, request, cdk_options)
  350. .await?;
  351. Ok(quote.into())
  352. }
  353. /// Get a melt quote for a BIP353 human-readable address
  354. ///
  355. /// This method resolves a BIP353 address (e.g., "alice@example.com") to a Lightning offer
  356. /// and then creates a melt quote for that offer at the specified mint.
  357. ///
  358. /// # Arguments
  359. ///
  360. /// * `mint_url` - The mint to use for creating the melt quote
  361. /// * `bip353_address` - Human-readable address in the format "user@domain.com"
  362. /// * `amount_msat` - Amount to pay in millisatoshis
  363. #[cfg(not(target_arch = "wasm32"))]
  364. pub async fn melt_bip353_quote(
  365. &self,
  366. mint_url: MintUrl,
  367. bip353_address: String,
  368. amount_msat: u64,
  369. ) -> Result<MeltQuote, FfiError> {
  370. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  371. let cdk_amount = cdk::Amount::from(amount_msat);
  372. let quote = self
  373. .inner
  374. .melt_bip353_quote(&cdk_mint_url, &bip353_address, cdk_amount)
  375. .await?;
  376. Ok(quote.into())
  377. }
  378. /// Get a melt quote for a Lightning address
  379. ///
  380. /// This method resolves a Lightning address (e.g., "alice@example.com") to a Lightning invoice
  381. /// and then creates a melt quote for that invoice at the specified mint.
  382. ///
  383. /// # Arguments
  384. ///
  385. /// * `mint_url` - The mint to use for creating the melt quote
  386. /// * `lightning_address` - Lightning address in the format "user@domain.com"
  387. /// * `amount_msat` - Amount to pay in millisatoshis
  388. pub async fn melt_lightning_address_quote(
  389. &self,
  390. mint_url: MintUrl,
  391. lightning_address: String,
  392. amount_msat: u64,
  393. ) -> Result<MeltQuote, FfiError> {
  394. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  395. let cdk_amount = cdk::Amount::from(amount_msat);
  396. let quote = self
  397. .inner
  398. .melt_lightning_address_quote(&cdk_mint_url, &lightning_address, cdk_amount)
  399. .await?;
  400. Ok(quote.into())
  401. }
  402. /// Get a melt quote for a human-readable address
  403. ///
  404. /// This method accepts a human-readable address that could be either a BIP353 address
  405. /// or a Lightning address. It intelligently determines which to try based on mint support:
  406. ///
  407. /// 1. If the mint supports Bolt12, it tries BIP353 first
  408. /// 2. Falls back to Lightning address only if BIP353 DNS resolution fails
  409. /// 3. If BIP353 resolves but fails at the mint, it does NOT fall back to Lightning address
  410. /// 4. If the mint doesn't support Bolt12, it tries Lightning address directly
  411. ///
  412. /// # Arguments
  413. ///
  414. /// * `mint_url` - The mint to use for creating the melt quote
  415. /// * `address` - Human-readable address (BIP353 or Lightning address)
  416. /// * `amount_msat` - Amount to pay in millisatoshis
  417. #[cfg(not(target_arch = "wasm32"))]
  418. pub async fn melt_human_readable_quote(
  419. &self,
  420. mint_url: MintUrl,
  421. address: String,
  422. amount_msat: u64,
  423. ) -> Result<MeltQuote, FfiError> {
  424. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  425. let cdk_amount = cdk::Amount::from(amount_msat);
  426. let quote = self
  427. .inner
  428. .melt_human_readable_quote(&cdk_mint_url, &address, cdk_amount)
  429. .await?;
  430. Ok(quote.into())
  431. }
  432. /// Melt tokens
  433. pub async fn melt_with_mint(
  434. &self,
  435. mint_url: MintUrl,
  436. quote_id: String,
  437. ) -> Result<Melted, FfiError> {
  438. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  439. let melted = self.inner.melt_with_mint(&cdk_mint_url, &quote_id).await?;
  440. Ok(melted.into())
  441. }
  442. /// Melt specific proofs from a specific mint
  443. ///
  444. /// This method allows melting proofs that may not be in the wallet's database,
  445. /// similar to how `receive_proofs` handles external proofs. The proofs will be
  446. /// added to the database and used for the melt operation.
  447. ///
  448. /// # Arguments
  449. ///
  450. /// * `mint_url` - The mint to use for the melt operation
  451. /// * `quote_id` - The melt quote ID (obtained from `melt_quote`)
  452. /// * `proofs` - The proofs to melt (can be external proofs not in the wallet's database)
  453. ///
  454. /// # Returns
  455. ///
  456. /// A `Melted` result containing the payment details and any change proofs
  457. pub async fn melt_proofs(
  458. &self,
  459. mint_url: MintUrl,
  460. quote_id: String,
  461. proofs: Proofs,
  462. ) -> Result<Melted, FfiError> {
  463. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  464. let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
  465. proofs.into_iter().map(|p| p.try_into()).collect();
  466. let cdk_proofs = cdk_proofs?;
  467. let melted = self
  468. .inner
  469. .melt_proofs(&cdk_mint_url, &quote_id, cdk_proofs)
  470. .await?;
  471. Ok(melted.into())
  472. }
  473. /// Check melt quote status
  474. pub async fn check_melt_quote(
  475. &self,
  476. mint_url: MintUrl,
  477. quote_id: String,
  478. ) -> Result<MeltQuote, FfiError> {
  479. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  480. let melted = self
  481. .inner
  482. .check_melt_quote(&cdk_mint_url, &quote_id)
  483. .await?;
  484. Ok(melted.into())
  485. }
  486. /// Melt tokens (pay a bolt11 invoice)
  487. pub async fn melt(
  488. &self,
  489. bolt11: String,
  490. options: Option<MeltOptions>,
  491. max_fee: Option<Amount>,
  492. ) -> Result<Melted, FfiError> {
  493. let cdk_options = options.map(Into::into);
  494. let cdk_max_fee = max_fee.map(Into::into);
  495. let melted = self.inner.melt(&bolt11, cdk_options, cdk_max_fee).await?;
  496. Ok(melted.into())
  497. }
  498. /// Transfer funds between mints
  499. pub async fn transfer(
  500. &self,
  501. source_mint: MintUrl,
  502. target_mint: MintUrl,
  503. transfer_mode: TransferMode,
  504. ) -> Result<TransferResult, FfiError> {
  505. let source_cdk: cdk::mint_url::MintUrl = source_mint.try_into()?;
  506. let target_cdk: cdk::mint_url::MintUrl = target_mint.try_into()?;
  507. let result = self
  508. .inner
  509. .transfer(&source_cdk, &target_cdk, transfer_mode.into())
  510. .await?;
  511. Ok(result.into())
  512. }
  513. /// Swap proofs with automatic wallet selection
  514. pub async fn swap(
  515. &self,
  516. amount: Option<Amount>,
  517. spending_conditions: Option<SpendingConditions>,
  518. ) -> Result<Option<Proofs>, FfiError> {
  519. let conditions = spending_conditions.map(|sc| sc.try_into()).transpose()?;
  520. let result = self.inner.swap(amount.map(Into::into), conditions).await?;
  521. Ok(result.map(|proofs| proofs.into_iter().map(|p| p.into()).collect()))
  522. }
  523. /// List transactions from all mints
  524. pub async fn list_transactions(
  525. &self,
  526. direction: Option<TransactionDirection>,
  527. ) -> Result<Vec<Transaction>, FfiError> {
  528. let cdk_direction = direction.map(Into::into);
  529. let transactions = self.inner.list_transactions(cdk_direction).await?;
  530. Ok(transactions.into_iter().map(Into::into).collect())
  531. }
  532. /// Get proofs for a transaction by transaction ID
  533. ///
  534. /// This retrieves all proofs associated with a transaction. If `mint_url` is provided,
  535. /// it will only check that specific mint's wallet. Otherwise, it searches across all
  536. /// wallets to find which mint the transaction belongs to.
  537. ///
  538. /// # Arguments
  539. ///
  540. /// * `id` - The transaction ID
  541. /// * `mint_url` - Optional mint URL to check directly, avoiding iteration over all wallets
  542. pub async fn get_proofs_for_transaction(
  543. &self,
  544. id: TransactionId,
  545. mint_url: Option<MintUrl>,
  546. ) -> Result<Vec<Proof>, FfiError> {
  547. let cdk_id = id.try_into()?;
  548. let cdk_mint_url = mint_url.map(|url| url.try_into()).transpose()?;
  549. let proofs = self
  550. .inner
  551. .get_proofs_for_transaction(cdk_id, cdk_mint_url)
  552. .await?;
  553. Ok(proofs.into_iter().map(Into::into).collect())
  554. }
  555. /// Check all mint quotes and mint if paid
  556. pub async fn check_all_mint_quotes(
  557. &self,
  558. mint_url: Option<MintUrl>,
  559. ) -> Result<Amount, FfiError> {
  560. let cdk_mint_url = mint_url.map(|url| url.try_into()).transpose()?;
  561. let amount = self.inner.check_all_mint_quotes(cdk_mint_url).await?;
  562. Ok(amount.into())
  563. }
  564. /// Consolidate proofs across all mints
  565. pub async fn consolidate(&self) -> Result<Amount, FfiError> {
  566. let amount = self.inner.consolidate().await?;
  567. Ok(amount.into())
  568. }
  569. /// Get list of mint URLs
  570. pub async fn get_mint_urls(&self) -> Vec<String> {
  571. let wallets = self.inner.get_wallets().await;
  572. wallets.iter().map(|w| w.mint_url.to_string()).collect()
  573. }
  574. /// Get all wallets from MultiMintWallet
  575. pub async fn get_wallets(&self) -> Vec<Arc<crate::wallet::Wallet>> {
  576. let wallets = self.inner.get_wallets().await;
  577. wallets
  578. .into_iter()
  579. .map(|w| Arc::new(crate::wallet::Wallet::from_inner(Arc::new(w))))
  580. .collect()
  581. }
  582. /// Get a specific wallet from MultiMintWallet by mint URL
  583. pub async fn get_wallet(&self, mint_url: MintUrl) -> Option<Arc<crate::wallet::Wallet>> {
  584. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into().ok()?;
  585. let wallet = self.inner.get_wallet(&cdk_mint_url).await?;
  586. Some(Arc::new(crate::wallet::Wallet::from_inner(Arc::new(
  587. wallet,
  588. ))))
  589. }
  590. /// Verify token DLEQ proofs
  591. pub async fn verify_token_dleq(&self, token: Arc<Token>) -> Result<(), FfiError> {
  592. let cdk_token = token.inner.clone();
  593. self.inner.verify_token_dleq(&cdk_token).await?;
  594. Ok(())
  595. }
  596. /// Query mint for current mint information
  597. pub async fn fetch_mint_info(&self, mint_url: MintUrl) -> Result<Option<MintInfo>, FfiError> {
  598. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  599. let mint_info = self.inner.fetch_mint_info(&cdk_mint_url).await?;
  600. Ok(mint_info.map(Into::into))
  601. }
  602. }
  603. /// Payment request methods for MultiMintWallet
  604. #[uniffi::export(async_runtime = "tokio")]
  605. impl MultiMintWallet {
  606. /// Create a NUT-18 payment request
  607. ///
  608. /// Creates a payment request that can be shared to receive Cashu tokens.
  609. /// The request can include optional amount, description, and spending conditions.
  610. ///
  611. /// # Arguments
  612. ///
  613. /// * `params` - Parameters for creating the payment request
  614. ///
  615. /// # Transport Options
  616. ///
  617. /// - `"nostr"` - Uses Nostr relays for privacy-preserving delivery (requires nostr_relays)
  618. /// - `"http"` - Uses HTTP POST for delivery (requires http_url)
  619. /// - `"none"` - No transport; token must be delivered out-of-band
  620. ///
  621. /// # Example
  622. ///
  623. /// ```ignore
  624. /// let params = CreateRequestParams {
  625. /// amount: Some(100),
  626. /// unit: "sat".to_string(),
  627. /// description: Some("Coffee payment".to_string()),
  628. /// transport: "http".to_string(),
  629. /// http_url: Some("https://example.com/callback".to_string()),
  630. /// ..Default::default()
  631. /// };
  632. /// let result = wallet.create_request(params).await?;
  633. /// println!("Share this request: {}", result.payment_request.to_string_encoded());
  634. ///
  635. /// // If using Nostr transport, wait for payment:
  636. /// if let Some(nostr_info) = result.nostr_wait_info {
  637. /// let amount = wallet.wait_for_nostr_payment(nostr_info).await?;
  638. /// println!("Received {} sats", amount);
  639. /// }
  640. /// ```
  641. pub async fn create_request(
  642. &self,
  643. params: CreateRequestParams,
  644. ) -> Result<CreateRequestResult, FfiError> {
  645. let (payment_request, nostr_wait_info) = self.inner.create_request(params.into()).await?;
  646. Ok(CreateRequestResult {
  647. payment_request: Arc::new(PaymentRequest::from_inner(payment_request)),
  648. nostr_wait_info: nostr_wait_info.map(|info| Arc::new(NostrWaitInfo::from_inner(info))),
  649. })
  650. }
  651. /// Wait for a Nostr payment and receive it into the wallet
  652. ///
  653. /// This method connects to the Nostr relays specified in the `NostrWaitInfo`,
  654. /// subscribes for incoming payment events, and receives the first valid
  655. /// payment into the wallet.
  656. ///
  657. /// # Arguments
  658. ///
  659. /// * `info` - The Nostr wait info returned from `create_request` when using Nostr transport
  660. ///
  661. /// # Returns
  662. ///
  663. /// The amount received from the payment.
  664. ///
  665. /// # Example
  666. ///
  667. /// ```ignore
  668. /// let result = wallet.create_request(params).await?;
  669. /// if let Some(nostr_info) = result.nostr_wait_info {
  670. /// let amount = wallet.wait_for_nostr_payment(nostr_info).await?;
  671. /// println!("Received {} sats", amount);
  672. /// }
  673. /// ```
  674. pub async fn wait_for_nostr_payment(
  675. &self,
  676. info: Arc<NostrWaitInfo>,
  677. ) -> Result<Amount, FfiError> {
  678. // We need to clone the inner NostrWaitInfo since we can't consume the Arc
  679. let info_inner = cdk::wallet::payment_request::NostrWaitInfo {
  680. keys: info.inner().keys.clone(),
  681. relays: info.inner().relays.clone(),
  682. pubkey: info.inner().pubkey,
  683. };
  684. let amount = self
  685. .inner
  686. .wait_for_nostr_payment(info_inner)
  687. .await
  688. .map_err(|e| FfiError::Generic { msg: e.to_string() })?;
  689. Ok(amount.into())
  690. }
  691. }
  692. /// Auth methods for MultiMintWallet
  693. #[uniffi::export(async_runtime = "tokio")]
  694. impl MultiMintWallet {
  695. /// Set Clear Auth Token (CAT) for a specific mint
  696. pub async fn set_cat(&self, mint_url: MintUrl, cat: String) -> Result<(), FfiError> {
  697. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  698. self.inner.set_cat(&cdk_mint_url, cat).await?;
  699. Ok(())
  700. }
  701. /// Set refresh token for a specific mint
  702. pub async fn set_refresh_token(
  703. &self,
  704. mint_url: MintUrl,
  705. refresh_token: String,
  706. ) -> Result<(), FfiError> {
  707. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  708. self.inner
  709. .set_refresh_token(&cdk_mint_url, refresh_token)
  710. .await?;
  711. Ok(())
  712. }
  713. /// Refresh access token for a specific mint using the stored refresh token
  714. pub async fn refresh_access_token(&self, mint_url: MintUrl) -> Result<(), FfiError> {
  715. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  716. self.inner.refresh_access_token(&cdk_mint_url).await?;
  717. Ok(())
  718. }
  719. /// Mint blind auth tokens at a specific mint
  720. pub async fn mint_blind_auth(
  721. &self,
  722. mint_url: MintUrl,
  723. amount: Amount,
  724. ) -> Result<Proofs, FfiError> {
  725. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  726. let proofs = self
  727. .inner
  728. .mint_blind_auth(&cdk_mint_url, amount.into())
  729. .await?;
  730. Ok(proofs.into_iter().map(|p| p.into()).collect())
  731. }
  732. /// Get unspent auth proofs for a specific mint
  733. pub async fn get_unspent_auth_proofs(
  734. &self,
  735. mint_url: MintUrl,
  736. ) -> Result<Vec<AuthProof>, FfiError> {
  737. let cdk_mint_url: cdk::mint_url::MintUrl = mint_url.try_into()?;
  738. let auth_proofs = self.inner.get_unspent_auth_proofs(&cdk_mint_url).await?;
  739. Ok(auth_proofs.into_iter().map(Into::into).collect())
  740. }
  741. }
  742. /// Transfer mode for mint-to-mint transfers
  743. #[derive(Debug, Clone, uniffi::Enum)]
  744. pub enum TransferMode {
  745. /// Transfer exact amount to target (target receives specified amount)
  746. ExactReceive { amount: Amount },
  747. /// Transfer all available balance (source will be emptied)
  748. FullBalance,
  749. }
  750. impl From<TransferMode> for CdkTransferMode {
  751. fn from(mode: TransferMode) -> Self {
  752. match mode {
  753. TransferMode::ExactReceive { amount } => CdkTransferMode::ExactReceive(amount.into()),
  754. TransferMode::FullBalance => CdkTransferMode::FullBalance,
  755. }
  756. }
  757. }
  758. /// Result of a transfer operation with detailed breakdown
  759. #[derive(Debug, Clone, uniffi::Record)]
  760. pub struct TransferResult {
  761. /// Amount deducted from source mint
  762. pub amount_sent: Amount,
  763. /// Amount received at target mint
  764. pub amount_received: Amount,
  765. /// Total fees paid for the transfer
  766. pub fees_paid: Amount,
  767. /// Remaining balance in source mint after transfer
  768. pub source_balance_after: Amount,
  769. /// New balance in target mint after transfer
  770. pub target_balance_after: Amount,
  771. }
  772. impl From<CdkTransferResult> for TransferResult {
  773. fn from(result: CdkTransferResult) -> Self {
  774. Self {
  775. amount_sent: result.amount_sent.into(),
  776. amount_received: result.amount_received.into(),
  777. fees_paid: result.fees_paid.into(),
  778. source_balance_after: result.source_balance_after.into(),
  779. target_balance_after: result.target_balance_after.into(),
  780. }
  781. }
  782. }
  783. /// Data extracted from a token including mint URL, proofs, and memo
  784. #[derive(Debug, Clone, uniffi::Record)]
  785. pub struct TokenData {
  786. /// The mint URL from the token
  787. pub mint_url: MintUrl,
  788. /// The proofs contained in the token
  789. pub proofs: Proofs,
  790. /// The memo from the token, if present
  791. pub memo: Option<String>,
  792. }
  793. impl From<CdkTokenData> for TokenData {
  794. fn from(data: CdkTokenData) -> Self {
  795. Self {
  796. mint_url: data.mint_url.into(),
  797. proofs: data.proofs.into_iter().map(|p| p.into()).collect(),
  798. memo: data.memo,
  799. }
  800. }
  801. }
  802. /// Options for receiving tokens in multi-mint context
  803. #[derive(Debug, Clone, Default, uniffi::Record)]
  804. pub struct MultiMintReceiveOptions {
  805. /// Whether to allow receiving from untrusted (not yet added) mints
  806. pub allow_untrusted: bool,
  807. /// Mint URL to transfer tokens to from untrusted mints (None means keep in original mint)
  808. pub transfer_to_mint: Option<MintUrl>,
  809. /// Base receive options to apply to the wallet receive
  810. pub receive_options: ReceiveOptions,
  811. }
  812. impl From<MultiMintReceiveOptions> for CdkMultiMintReceiveOptions {
  813. fn from(options: MultiMintReceiveOptions) -> Self {
  814. let mut opts = CdkMultiMintReceiveOptions::new();
  815. opts.allow_untrusted = options.allow_untrusted;
  816. opts.transfer_to_mint = options.transfer_to_mint.and_then(|url| url.try_into().ok());
  817. opts.receive_options = options.receive_options.into();
  818. opts
  819. }
  820. }
  821. /// Options for sending tokens in multi-mint context
  822. #[derive(Debug, Clone, Default, uniffi::Record)]
  823. pub struct MultiMintSendOptions {
  824. /// Whether to allow transferring funds from other mints if needed
  825. pub allow_transfer: bool,
  826. /// Maximum amount to transfer from other mints (optional limit)
  827. pub max_transfer_amount: Option<Amount>,
  828. /// Specific mint URLs allowed for transfers (empty means all mints allowed)
  829. pub allowed_mints: Vec<MintUrl>,
  830. /// Specific mint URLs to exclude from transfers
  831. pub excluded_mints: Vec<MintUrl>,
  832. /// Base send options to apply to the wallet send
  833. pub send_options: SendOptions,
  834. }
  835. impl From<MultiMintSendOptions> for CdkMultiMintSendOptions {
  836. fn from(options: MultiMintSendOptions) -> Self {
  837. let mut opts = CdkMultiMintSendOptions::new();
  838. opts.allow_transfer = options.allow_transfer;
  839. opts.max_transfer_amount = options.max_transfer_amount.map(Into::into);
  840. opts.allowed_mints = options
  841. .allowed_mints
  842. .into_iter()
  843. .filter_map(|url| url.try_into().ok())
  844. .collect();
  845. opts.excluded_mints = options
  846. .excluded_mints
  847. .into_iter()
  848. .filter_map(|url| url.try_into().ok())
  849. .collect();
  850. opts.send_options = options.send_options.into();
  851. opts
  852. }
  853. }
  854. /// Type alias for balances by mint URL
  855. pub type BalanceMap = HashMap<String, Amount>;
  856. /// Type alias for proofs by mint URL
  857. pub type ProofsByMint = HashMap<String, Vec<Proof>>;