Skip to content

Commit

Permalink
Improve wallet example with memory store
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
Gudnessuche authored and thesimplekid committed Dec 28, 2024
1 parent 7fea2ff commit 8ab08c7
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions crates/cdk/examples/wallet.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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,
Expand All @@ -56,8 +68,9 @@ async fn main() {
&SendKind::default(),
false,
)
.await
.unwrap();
.await?;

println!("{}", token);

Ok(())
}

0 comments on commit 8ab08c7

Please # to comment.