wallet.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use std::sync::Arc;
  2. use std::time::Duration;
  3. use cdk::amount::SplitTarget;
  4. use cdk::nuts::nut00::ProofsMethods;
  5. use cdk::nuts::{CurrencyUnit, MintQuoteState};
  6. use cdk::wallet::{SendOptions, Wallet};
  7. use cdk::Amount;
  8. use cdk_sqlite::wallet::memory;
  9. use rand::Rng;
  10. use tokio::time::sleep;
  11. #[tokio::main]
  12. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  13. // Generate a random seed for the wallet
  14. let seed = rand::thread_rng().gen::<[u8; 32]>();
  15. // Mint URL and currency unit
  16. let mint_url = "https://testnut.cashu.space";
  17. let unit = CurrencyUnit::Sat;
  18. let amount = Amount::from(10);
  19. // Initialize the memory store
  20. let localstore = memory::empty().await?;
  21. // Create a new wallet
  22. let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None)?;
  23. // Request a mint quote from the wallet
  24. let quote = wallet.mint_quote(amount, None).await?;
  25. println!("Pay request: {}", quote.request);
  26. // Check the quote state in a loop with a timeout
  27. let timeout = Duration::from_secs(60); // Set a timeout duration
  28. let start = std::time::Instant::now();
  29. loop {
  30. let status = wallet.mint_quote_state(&quote.id).await?;
  31. if status.state == MintQuoteState::Paid {
  32. break;
  33. }
  34. if start.elapsed() >= timeout {
  35. eprintln!("Timeout while waiting for mint quote to be paid");
  36. return Err("Timeout while waiting for mint quote to be paid".into());
  37. }
  38. println!("Quote state: {}", status.state);
  39. sleep(Duration::from_secs(5)).await;
  40. }
  41. // Mint the received amount
  42. let proofs = wallet.mint(&quote.id, SplitTarget::default(), None).await?;
  43. let receive_amount = proofs.total_amount()?;
  44. println!("Minted {}", receive_amount);
  45. // Send the token
  46. let prepared_send = wallet.prepare_send(amount, SendOptions::default()).await?;
  47. let token = wallet.send(prepared_send, None).await?;
  48. println!("{}", token);
  49. Ok(())
  50. }