From 8ab08c7fcead3bf4d213b3e61374541ba7548665 Mon Sep 17 00:00:00 2001 From: Jesus Christ <120573631+Gudnessuche@users.noreply.github.com> Date: Fri, 27 Dec 2024 13:23:17 +0000 Subject: [PATCH] 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. --- crates/cdk/examples/wallet.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/cdk/examples/wallet.rs b/crates/cdk/examples/wallet.rs index 93b6fa23e..ff973e40f 100644 --- a/crates/cdk/examples/wallet.rs +++ b/crates/cdk/examples/wallet.rs @@ -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> { + // 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("e.id).await.unwrap(); + let status = wallet.mint_quote_state("e.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("e.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(()) }