human_readable_payment.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //! # Human Readable Payment Example
  2. //!
  3. //! This example demonstrates how to use both BIP-353 and Lightning Address (LNURL-pay)
  4. //! with the CDK wallet. Both allow users to share simple email-like addresses instead
  5. //! of complex Bitcoin addresses or Lightning invoices.
  6. //!
  7. //! ## BIP-353 (Bitcoin URI Payment Instructions)
  8. //!
  9. //! BIP-353 uses DNS TXT records to resolve human-readable addresses to BOLT12 offers.
  10. //! 1. Parse a human-readable address like `user@domain.com`
  11. //! 2. Query DNS TXT records at `user.user._bitcoin-payment.domain.com`
  12. //! 3. Extract Lightning offers (BOLT12) from the TXT records
  13. //! 4. Use the offer to create a melt quote
  14. //!
  15. //! ## Lightning Address (LNURL-pay)
  16. //!
  17. //! Lightning Address uses HTTPS to fetch BOLT11 invoices.
  18. //! 1. Parse a Lightning address like `user@domain.com`
  19. //! 2. Query HTTPS endpoint at `https://domain.com/.well-known/lnurlp/user`
  20. //! 3. Get callback URL and amount constraints
  21. //! 4. Request BOLT11 invoice with the specified amount
  22. //!
  23. //! ## Unified API
  24. //!
  25. //! The `melt_human_readable_quote()` method automatically tries BIP-353 first
  26. //! (if the mint supports BOLT12), then falls back to Lightning Address if needed.
  27. //!
  28. //! ## Usage
  29. //!
  30. //! ```bash
  31. //! cargo run --example human_readable_payment --features="wallet bip353"
  32. //! ```
  33. use std::sync::Arc;
  34. use std::time::Duration;
  35. use cdk::amount::SplitTarget;
  36. use cdk::nuts::nut00::ProofsMethods;
  37. use cdk::nuts::CurrencyUnit;
  38. use cdk::wallet::Wallet;
  39. use cdk::Amount;
  40. use cdk_sqlite::wallet::memory;
  41. use rand::random;
  42. #[tokio::main]
  43. async fn main() -> anyhow::Result<()> {
  44. println!("Human Readable Payment Example");
  45. println!("================================\n");
  46. // Example addresses
  47. let bip353_address = "tsk@thesimplekid.com";
  48. let lnurl_address =
  49. "npub1qjgcmlpkeyl8mdkvp4s0xls4ytcux6my606tgfx9xttut907h0zs76lgjw@npubx.cash";
  50. // Generate a random seed for the wallet
  51. let seed = random::<[u8; 64]>();
  52. // Mint URL and currency unit
  53. let mint_url = "https://fake.thesimplekid.dev";
  54. let unit = CurrencyUnit::Sat;
  55. let initial_amount = Amount::from(2000); // Start with 2000 sats (enough for both payments)
  56. // Initialize the memory store
  57. let localstore = Arc::new(memory::empty().await?);
  58. // Create a new wallet
  59. let wallet = Wallet::new(mint_url, unit, localstore, seed, None)?;
  60. println!("Step 1: Funding the wallet");
  61. println!("---------------------------");
  62. // First, we need to fund the wallet
  63. println!("Requesting mint quote for {} sats...", initial_amount);
  64. let mint_quote = wallet.mint_quote(initial_amount, None).await?;
  65. println!(
  66. "Pay this invoice to fund the wallet:\n{}",
  67. mint_quote.request
  68. );
  69. println!("\nQuote ID: {}", mint_quote.id);
  70. // Wait for payment and mint tokens automatically
  71. println!("\nWaiting for payment... (in real use, pay the above invoice)");
  72. let proofs = wallet
  73. .wait_and_mint_quote(
  74. mint_quote,
  75. SplitTarget::default(),
  76. None,
  77. Duration::from_secs(300), // 5 minutes timeout
  78. )
  79. .await?;
  80. let received_amount = proofs.total_amount()?;
  81. println!("✓ Successfully minted {} sats\n", received_amount);
  82. // ============================================================================
  83. // Part 1: BIP-353 Payment
  84. // ============================================================================
  85. println!("\n╔════════════════════════════════════════════════════════════════╗");
  86. println!("║ Part 1: BIP-353 Payment (BOLT12 Offer via DNS) ║");
  87. println!("╚════════════════════════════════════════════════════════════════╝\n");
  88. let bip353_amount_sats = 100; // Example: paying 100 sats
  89. println!("BIP-353 Address: {}", bip353_address);
  90. println!("Payment Amount: {} sats", bip353_amount_sats);
  91. println!("\nHow BIP-353 works:");
  92. println!("1. Parse address into user@domain");
  93. println!("2. Query DNS TXT records at: tsk.user._bitcoin-payment.thesimplekid.com");
  94. println!("3. Extract BOLT12 offer from DNS records");
  95. println!("4. Create melt quote with the offer\n");
  96. // Use the specific BIP353 method
  97. println!("Attempting BIP-353 payment...");
  98. match wallet
  99. .melt_bip353_quote(bip353_address, bip353_amount_sats * 1_000)
  100. .await
  101. {
  102. Ok(melt_quote) => {
  103. println!("✓ BIP-353 melt quote received:");
  104. println!(" Quote ID: {}", melt_quote.id);
  105. println!(" Amount: {} sats", melt_quote.amount);
  106. println!(" Fee Reserve: {} sats", melt_quote.fee_reserve);
  107. println!(" State: {}", melt_quote.state);
  108. println!(" Payment Method: {}", melt_quote.payment_method);
  109. // Execute the payment
  110. println!("\nExecuting payment...");
  111. match wallet.melt(&melt_quote.id).await {
  112. Ok(melt_result) => {
  113. println!("✓ BIP-353 payment successful!");
  114. println!(" State: {}", melt_result.state);
  115. println!(" Amount paid: {} sats", melt_result.amount);
  116. println!(" Fee paid: {} sats", melt_result.fee_paid);
  117. if let Some(preimage) = melt_result.preimage {
  118. println!(" Payment preimage: {}", preimage);
  119. }
  120. }
  121. Err(e) => {
  122. println!("✗ BIP-353 payment failed: {}", e);
  123. }
  124. }
  125. }
  126. Err(e) => {
  127. println!("✗ Failed to get BIP-353 melt quote: {}", e);
  128. println!("\nPossible reasons:");
  129. println!(" • DNS resolution failed or no DNS records found");
  130. println!(" • No Lightning offer (BOLT12) in DNS TXT records");
  131. println!(" • DNSSEC validation failed");
  132. println!(" • Mint doesn't support BOLT12");
  133. println!(" • Network connectivity issues");
  134. }
  135. }
  136. // ============================================================================
  137. // Part 2: Lightning Address (LNURL-pay) Payment
  138. // ============================================================================
  139. println!("\n\n╔════════════════════════════════════════════════════════════════╗");
  140. println!("║ Part 2: Lightning Address Payment (BOLT11 via LNURL-pay) ║");
  141. println!("╚════════════════════════════════════════════════════════════════╝\n");
  142. let lnurl_amount_sats = 100; // Example: paying 100 sats
  143. println!("Lightning Address: {}", lnurl_address);
  144. println!("Payment Amount: {} sats", lnurl_amount_sats);
  145. println!("\nHow Lightning Address works:");
  146. println!("1. Parse address into user@domain");
  147. println!("2. Query HTTPS: https://npubx.cash/.well-known/lnurlp/npub1qj...");
  148. println!("3. Get callback URL and amount constraints");
  149. println!("4. Request BOLT11 invoice for the amount");
  150. println!("5. Create melt quote with the invoice\n");
  151. // Use the specific Lightning Address method
  152. println!("Attempting Lightning Address payment...");
  153. match wallet
  154. .melt_lightning_address_quote(lnurl_address, lnurl_amount_sats * 1_000)
  155. .await
  156. {
  157. Ok(melt_quote) => {
  158. println!("✓ Lightning Address melt quote received:");
  159. println!(" Quote ID: {}", melt_quote.id);
  160. println!(" Amount: {} sats", melt_quote.amount);
  161. println!(" Fee Reserve: {} sats", melt_quote.fee_reserve);
  162. println!(" State: {}", melt_quote.state);
  163. println!(" Payment Method: {}", melt_quote.payment_method);
  164. // Execute the payment
  165. println!("\nExecuting payment...");
  166. match wallet.melt(&melt_quote.id).await {
  167. Ok(melt_result) => {
  168. println!("✓ Lightning Address payment successful!");
  169. println!(" State: {}", melt_result.state);
  170. println!(" Amount paid: {} sats", melt_result.amount);
  171. println!(" Fee paid: {} sats", melt_result.fee_paid);
  172. if let Some(preimage) = melt_result.preimage {
  173. println!(" Payment preimage: {}", preimage);
  174. }
  175. }
  176. Err(e) => {
  177. println!("✗ Lightning Address payment failed: {}", e);
  178. }
  179. }
  180. }
  181. Err(e) => {
  182. println!("✗ Failed to get Lightning Address melt quote: {}", e);
  183. println!("\nPossible reasons:");
  184. println!(" • HTTPS request to .well-known/lnurlp failed");
  185. println!(" • Invalid Lightning Address format");
  186. println!(" • Amount outside min/max constraints");
  187. println!(" • Service unavailable or network issues");
  188. }
  189. }
  190. // ============================================================================
  191. // Part 3: Unified Human Readable API (Smart Fallback)
  192. // ============================================================================
  193. println!("\n\n╔════════════════════════════════════════════════════════════════╗");
  194. println!("║ Part 3: Unified API (Automatic BIP-353 → LNURL Fallback) ║");
  195. println!("╚════════════════════════════════════════════════════════════════╝\n");
  196. println!("The `melt_human_readable_quote()` method intelligently chooses:");
  197. println!("1. If mint supports BOLT12 AND address has BIP-353 DNS: Use BIP-353");
  198. println!("2. If BIP-353 DNS fails OR address has no DNS: Fall back to LNURL");
  199. println!("3. If mint doesn't support BOLT12: Use LNURL directly\n");
  200. // Test 1: Address with BIP-353 support (has DNS records)
  201. let unified_amount_sats = 50;
  202. println!("Test 1: Address with BIP-353 DNS support");
  203. println!("Address: {}", bip353_address);
  204. println!("Payment Amount: {} sats", unified_amount_sats);
  205. println!("Expected: BIP-353 (BOLT12) via DNS resolution\n");
  206. println!("Attempting unified payment...");
  207. match wallet
  208. .melt_human_readable_quote(bip353_address, unified_amount_sats * 1_000)
  209. .await
  210. {
  211. Ok(melt_quote) => {
  212. println!("✓ Unified melt quote received:");
  213. println!(" Quote ID: {}", melt_quote.id);
  214. println!(" Amount: {} sats", melt_quote.amount);
  215. println!(" Fee Reserve: {} sats", melt_quote.fee_reserve);
  216. println!(" Payment Method: {}", melt_quote.payment_method);
  217. let method_str = melt_quote.payment_method.to_string().to_lowercase();
  218. let used_method = if method_str.contains("bolt12") {
  219. "BIP-353 (BOLT12)"
  220. } else if method_str.contains("bolt11") {
  221. "Lightning Address (LNURL-pay)"
  222. } else {
  223. "Unknown method"
  224. };
  225. println!("\n → Used: {}", used_method);
  226. }
  227. Err(e) => {
  228. println!("✗ Failed to get unified melt quote: {}", e);
  229. println!(" Both BIP-353 and Lightning Address resolution failed");
  230. }
  231. }
  232. // Test 2: Address without BIP-353 support (LNURL only)
  233. println!("\n\nTest 2: Address without BIP-353 (LNURL-only)");
  234. println!("Address: {}", lnurl_address);
  235. println!("Payment Amount: {} sats", unified_amount_sats);
  236. println!("Expected: Lightning Address (LNURL-pay) fallback\n");
  237. println!("Attempting unified payment...");
  238. match wallet
  239. .melt_human_readable_quote(lnurl_address, unified_amount_sats * 1_000)
  240. .await
  241. {
  242. Ok(melt_quote) => {
  243. println!("✓ Unified melt quote received:");
  244. println!(" Quote ID: {}", melt_quote.id);
  245. println!(" Amount: {} sats", melt_quote.amount);
  246. println!(" Fee Reserve: {} sats", melt_quote.fee_reserve);
  247. println!(" Payment Method: {}", melt_quote.payment_method);
  248. let method_str = melt_quote.payment_method.to_string().to_lowercase();
  249. let used_method = if method_str.contains("bolt12") {
  250. "BIP-353 (BOLT12)"
  251. } else if method_str.contains("bolt11") {
  252. "Lightning Address (LNURL-pay)"
  253. } else {
  254. "Unknown method"
  255. };
  256. println!("\n → Used: {}", used_method);
  257. println!("\n Note: This address doesn't have BIP-353 DNS records,");
  258. println!(" so it automatically fell back to LNURL-pay.");
  259. }
  260. Err(e) => {
  261. println!("✗ Failed to get unified melt quote: {}", e);
  262. println!(" Both BIP-353 and Lightning Address resolution failed");
  263. }
  264. }
  265. Ok(())
  266. }