From e33def267914ae512e27169e570202e71d58cbc8 Mon Sep 17 00:00:00 2001 From: Jesus Christ <120573631+Gudnessuche@users.noreply.github.com> Date: Fri, 27 Dec 2024 13:57:18 +0000 Subject: [PATCH] Improve mint-token.rs - Replaced unwrap() calls with proper error handling using `?` operator. - Added comments for better code understanding. - Managed the subscription mechanism properly to avoid potential issues with concurrent message handling. - Ensured the main function returns a Result type for graceful error handling. --- crates/cdk/examples/mint-token.rs | 32 +++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/crates/cdk/examples/mint-token.rs b/crates/cdk/examples/mint-token.rs index cb2dce1e..fc6adb4e 100644 --- a/crates/cdk/examples/mint-token.rs +++ b/crates/cdk/examples/mint-token.rs @@ -1,5 +1,4 @@ use std::sync::Arc; - use cdk::amount::SplitTarget; use cdk::cdk_database::WalletMemoryDatabase; use cdk::error::Error; @@ -11,25 +10,30 @@ use rand::Rng; #[tokio::main] async fn main() -> Result<(), Error> { + // Initialize the memory store for the wallet let localstore = WalletMemoryDatabase::default(); + + // Generate a random seed for the wallet let seed = rand::thread_rng().gen::<[u8; 32]>(); + // Define the mint URL and currency unit let mint_url = "https://testnut.cashu.space"; let unit = CurrencyUnit::Sat; let amount = Amount::from(10); - let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap(); - - let quote = wallet.mint_quote(amount, None).await.unwrap(); + // Create a new wallet + let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None)?; + // Request a mint quote from the wallet + let quote = wallet.mint_quote(amount, None).await?; println!("Quote: {:#?}", quote); + // Subscribe to updates on the mint quote state let mut subscription = wallet - .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![quote - .id - .clone()])) + .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![quote.id.clone()])) .await; + // Wait for the mint quote to be paid while let Some(msg) = subscription.recv().await { if let NotificationPayload::MintQuoteBolt11Response(response) = msg { if response.state == MintQuoteState::Paid { @@ -38,13 +42,11 @@ async fn main() -> Result<(), Error> { } } - let receive_amount = wallet - .mint("e.id, SplitTarget::default(), None) - .await - .unwrap(); - - println!("Received {receive_amount} from mint {mint_url}"); + // Mint the received amount + let receive_amount = wallet.mint("e.id, SplitTarget::default(), None).await?; + println!("Received {} from mint {}", receive_amount, mint_url); + // Send a token with the specified amount let token = wallet .send( amount, @@ -54,9 +56,7 @@ async fn main() -> Result<(), Error> { &SendKind::OnlineExact, false, ) - .await - .unwrap(); - + .await?; println!("Token:"); println!("{}", token);