p2pk.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use std::sync::Arc;
  2. use cdk::amount::SplitTarget;
  3. use cdk::cdk_database::WalletMemoryDatabase;
  4. use cdk::error::Error;
  5. use cdk::nuts::{CurrencyUnit, MintQuoteState, NotificationPayload, SecretKey, SpendingConditions};
  6. use cdk::wallet::types::SendKind;
  7. use cdk::wallet::{Wallet, WalletSubscription};
  8. use cdk::Amount;
  9. use rand::Rng;
  10. #[tokio::main]
  11. async fn main() -> Result<(), Error> {
  12. let localstore = WalletMemoryDatabase::default();
  13. let seed = rand::thread_rng().gen::<[u8; 32]>();
  14. let mint_url = "https://testnut.cashu.space";
  15. let unit = CurrencyUnit::Sat;
  16. let amount = Amount::from(10);
  17. let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
  18. let quote = wallet.mint_quote(amount, None).await.unwrap();
  19. println!("Minting nuts ...");
  20. let mut subscription = wallet
  21. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![quote
  22. .id
  23. .clone()]))
  24. .await;
  25. while let Some(msg) = subscription.recv().await {
  26. if let NotificationPayload::MintQuoteBolt11Response(response) = msg {
  27. if response.state == MintQuoteState::Paid {
  28. break;
  29. }
  30. }
  31. }
  32. let _receive_amount = wallet
  33. .mint(&quote.id, SplitTarget::default(), None)
  34. .await
  35. .unwrap();
  36. let secret = SecretKey::generate();
  37. let spending_conditions = SpendingConditions::new_p2pk(secret.public_key(), None);
  38. let bal = wallet.total_balance().await.unwrap();
  39. println!("{}", bal);
  40. let token = wallet
  41. .send(
  42. amount,
  43. None,
  44. Some(spending_conditions),
  45. &SplitTarget::default(),
  46. &SendKind::default(),
  47. false,
  48. )
  49. .await
  50. .unwrap();
  51. println!("Created token locked to pubkey: {}", secret.public_key());
  52. println!("{}", token);
  53. let amount = wallet
  54. .receive(&token.to_string(), SplitTarget::default(), &[secret], &[])
  55. .await
  56. .unwrap();
  57. println!("Redeemed locked token worth: {}", u64::from(amount));
  58. Ok(())
  59. }