Improve wallet example with memory store

- Replaced unwrap() calls with proper error handling using `?` operator.
- Added comments for better code understanding.
- Introduced a timeout mechanism to prevent infinite loops when checking the quote state.
- Ensured the main function returns a Result type for graceful error handling.
- Added descriptive comments to explain the functionality of each section in the code.
This commit is contained in:
Jesus Christ
2024-12-27 13:23:17 +00:00
committed by thesimplekid
parent 7fea2ffa92
commit 8ab08c7fce

View File

@@ -1,8 +1,5 @@
//! Wallet example with memory store
use std::sync::Arc;
use std::time::Duration;
use cdk::amount::SplitTarget;
use cdk::cdk_database::WalletMemoryDatabase;
use cdk::nuts::{CurrencyUnit, MintQuoteState};
@@ -13,40 +10,55 @@ use rand::Rng;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Generate a random seed for the wallet
let seed = rand::thread_rng().gen::<[u8; 32]>();
// Mint URL and currency unit
let mint_url = "https://testnut.cashu.space";
let unit = CurrencyUnit::Sat;
let amount = Amount::from(10);
// Initialize the memory store
let localstore = WalletMemoryDatabase::default();
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
// Create a new wallet
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None)?;
let quote = wallet.mint_quote(amount, None).await.unwrap();
// Request a mint quote from the wallet
let quote = wallet.mint_quote(amount, None).await?;
println!("Pay request: {}", quote.request);
// Check the quote state in a loop with a timeout
let timeout = Duration::from_secs(60); // Set a timeout duration
let start = std::time::Instant::now();
loop {
let status = wallet.mint_quote_state(&quote.id).await.unwrap();
let status = wallet.mint_quote_state(&quote.id).await?;
if status.state == MintQuoteState::Paid {
break;
}
if start.elapsed() >= timeout {
eprintln!("Timeout while waiting for mint quote to be paid");
return Err("Timeout while waiting for mint quote to be paid".into());
}
println!("Quote state: {}", status.state);
sleep(Duration::from_secs(5)).await;
}
// Mint the received amount
let receive_amount = wallet
.mint(&quote.id, SplitTarget::default(), None)
.await
.unwrap();
.await?;
println!("Minted {}", receive_amount);
// Send the token
let token = wallet
.send(
amount,
@@ -56,8 +68,9 @@ async fn main() {
&SendKind::default(),
false,
)
.await
.unwrap();
.await?;
println!("{}", token);
Ok(())
}