melt-token.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 (_invoice_to_pay, proofs) = wallet
  27. .mint_once_paid(amount, None, Duration::from_secs(10))
  28. .await?;
  29. // Mint the received amount
  30. let proofs = proofs.await?;
  31. let receive_amount = proofs.total_amount()?;
  32. println!("Received {} from mint {}", receive_amount, mint_url);
  33. // Now melt what we have
  34. // We need to prepare a lightning invoice
  35. let private_key = SecretKey::from_slice(
  36. &<[u8; 32]>::from_hex("e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734")
  37. .unwrap(),
  38. )
  39. .unwrap();
  40. let random_bytes = rand::rng().random::<[u8; 32]>();
  41. let payment_hash = sha256::Hash::from_slice(&random_bytes).unwrap();
  42. let payment_secret = PaymentSecret([42u8; 32]);
  43. let invoice_to_be_paid = InvoiceBuilder::new(Currency::Bitcoin)
  44. .amount_milli_satoshis(5 * 1000)
  45. .description("Pay me".into())
  46. .payment_hash(payment_hash)
  47. .payment_secret(payment_secret)
  48. .current_timestamp()
  49. .min_final_cltv_expiry_delta(144)
  50. .build_signed(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
  51. .unwrap()
  52. .to_string();
  53. println!("Invoice to be paid: {}", invoice_to_be_paid);
  54. let melt_quote = wallet.melt_quote(invoice_to_be_paid, None).await?;
  55. println!(
  56. "Melt quote: {} {} {:?}",
  57. melt_quote.amount, melt_quote.state, melt_quote,
  58. );
  59. let melted = wallet.melt(&melt_quote.id).await?;
  60. println!("Melted: {:?}", melted);
  61. Ok(())
  62. }