Skip to content

Commit

Permalink
Improve mint-token.rs
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.
- 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.
  • Loading branch information
Gudnessuche authored and thesimplekid committed Dec 28, 2024
1 parent a1ac6d3 commit e33def2
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions crates/cdk/examples/mint-token.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::sync::Arc;

use cdk::amount::SplitTarget;
use cdk::cdk_database::WalletMemoryDatabase;
use cdk::error::Error;
Expand All @@ -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 {
Expand All @@ -38,13 +42,11 @@ async fn main() -> Result<(), Error> {
}
}

let receive_amount = wallet
.mint(&quote.id, SplitTarget::default(), None)
.await
.unwrap();

println!("Received {receive_amount} from mint {mint_url}");
// Mint the received amount
let receive_amount = wallet.mint(&quote.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,
Expand All @@ -54,9 +56,7 @@ async fn main() -> Result<(), Error> {
&SendKind::OnlineExact,
false,
)
.await
.unwrap();

.await?;
println!("Token:");
println!("{}", token);

Expand Down

0 comments on commit e33def2

Please sign in to comment.