melt-token.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use std::sync::Arc;
  2. use std::time::Duration;
  3. use bitcoin::hashes::{sha256, Hash};
  4. use bitcoin::hex::prelude::FromHex;
  5. use bitcoin::secp256k1::Secp256k1;
  6. use cdk::error::Error;
  7. use cdk::nuts::nut00::ProofsMethods;
  8. use cdk::nuts::{CurrencyUnit, SecretKey};
  9. use cdk::wallet::Wallet;
  10. use cdk::Amount;
  11. use cdk_sqlite::wallet::memory;
  12. use lightning_invoice::{Currency, InvoiceBuilder, PaymentSecret};
  13. use rand::Rng;
  14. #[tokio::main]
  15. async fn main() -> Result<(), Error> {
  16. // Initialize the memory store for the wallet
  17. let localstore = memory::empty().await?;
  18. // Generate a random seed for the wallet
  19. let seed = rand::rng().random::<[u8; 64]>();
  20. // Define the mint URL and currency unit
  21. let mint_url = "https://fake.thesimplekid.dev";
  22. let unit = CurrencyUnit::Sat;
  23. let amount = Amount::from(10);
  24. // Create a new wallet
  25. let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), seed, None)?;
  26. let quote = wallet.mint_quote(amount, None).await?;
  27. let proofs = wallet
  28. .wait_and_mint_quote(
  29. quote,
  30. Default::default(),
  31. Default::default(),
  32. Duration::from_secs(10),
  33. )
  34. .await?;
  35. let receive_amount = proofs.total_amount()?;
  36. println!("Received {} from mint {}", receive_amount, mint_url);
  37. // Now melt what we have
  38. // We need to prepare a lightning invoice
  39. let private_key = SecretKey::from_slice(
  40. &<[u8; 32]>::from_hex("e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734")
  41. .unwrap(),
  42. )
  43. .unwrap();
  44. let random_bytes = rand::rng().random::<[u8; 32]>();
  45. let payment_hash = sha256::Hash::from_slice(&random_bytes).unwrap();
  46. let payment_secret = PaymentSecret([42u8; 32]);
  47. let invoice_to_be_paid = InvoiceBuilder::new(Currency::Bitcoin)
  48. .amount_milli_satoshis(5 * 1000)
  49. .description("Pay me".into())
  50. .payment_hash(payment_hash)
  51. .payment_secret(payment_secret)
  52. .current_timestamp()
  53. .min_final_cltv_expiry_delta(144)
  54. .build_signed(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
  55. .unwrap()
  56. .to_string();
  57. println!("Invoice to be paid: {}", invoice_to_be_paid);
  58. let melt_quote = wallet.melt_quote(invoice_to_be_paid, None).await?;
  59. println!(
  60. "Melt quote: {} {} {:?}",
  61. melt_quote.amount, melt_quote.state, melt_quote,
  62. );
  63. let melted = wallet.melt(&melt_quote.id).await?;
  64. println!("Melted: {:?}", melted);
  65. Ok(())
  66. }