melt.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. use std::str::FromStr;
  2. use anyhow::{bail, Result};
  3. use cdk::amount::{amount_for_offer, Amount, MSAT_IN_SAT};
  4. use cdk::mint_url::MintUrl;
  5. use cdk::nuts::{CurrencyUnit, MeltOptions};
  6. use cdk::wallet::MultiMintWallet;
  7. use cdk::Bolt11Invoice;
  8. use clap::{Args, ValueEnum};
  9. use lightning::offers::offer::Offer;
  10. use crate::utils::{get_number_input, get_user_input};
  11. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
  12. pub enum PaymentType {
  13. /// BOLT11 invoice
  14. Bolt11,
  15. /// BOLT12 offer
  16. Bolt12,
  17. /// Bip353
  18. Bip353,
  19. }
  20. #[derive(Args)]
  21. pub struct MeltSubCommand {
  22. /// Mpp
  23. #[arg(short, long, conflicts_with = "mint_url")]
  24. mpp: bool,
  25. /// Mint URL to use for melting
  26. #[arg(long, conflicts_with = "mpp")]
  27. mint_url: Option<String>,
  28. /// Payment method (bolt11, bolt12, or bip353)
  29. #[arg(long, default_value = "bolt11")]
  30. method: PaymentType,
  31. }
  32. /// Helper function to check if there are enough funds and create appropriate MeltOptions
  33. fn create_melt_options(
  34. available_funds: u64,
  35. payment_amount: Option<u64>,
  36. prompt: &str,
  37. ) -> Result<Option<MeltOptions>> {
  38. match payment_amount {
  39. Some(amount) => {
  40. // Payment has a specified amount
  41. if amount > available_funds {
  42. bail!("Not enough funds; payment requires {} msats", amount);
  43. }
  44. Ok(None) // Use default options
  45. }
  46. None => {
  47. // Payment doesn't have an amount, ask user for it
  48. let user_amount = get_number_input::<u64>(prompt)? * MSAT_IN_SAT;
  49. if user_amount > available_funds {
  50. bail!("Not enough funds");
  51. }
  52. Ok(Some(MeltOptions::new_amountless(user_amount)))
  53. }
  54. }
  55. }
  56. pub async fn pay(
  57. multi_mint_wallet: &MultiMintWallet,
  58. sub_command_args: &MeltSubCommand,
  59. ) -> Result<()> {
  60. // Check total balance across all wallets
  61. let total_balance = multi_mint_wallet.total_balance().await?;
  62. if total_balance == Amount::ZERO {
  63. bail!("No funds available");
  64. }
  65. if sub_command_args.mpp {
  66. // Manual MPP - user specifies which mints and amounts to use
  67. if !matches!(sub_command_args.method, PaymentType::Bolt11) {
  68. bail!("MPP is only supported for BOLT11 invoices");
  69. }
  70. let bolt11_str = get_user_input("Enter bolt11 invoice")?;
  71. let _bolt11 = Bolt11Invoice::from_str(&bolt11_str)?; // Validate invoice format
  72. // Show available mints and balances
  73. let balances = multi_mint_wallet.get_balances().await?;
  74. println!("\nAvailable mints and balances:");
  75. for (i, (mint_url, balance)) in balances.iter().enumerate() {
  76. println!(
  77. " {}: {} - {} {}",
  78. i,
  79. mint_url,
  80. balance,
  81. multi_mint_wallet.unit()
  82. );
  83. }
  84. // Collect mint selections and amounts
  85. let mut mint_amounts = Vec::new();
  86. loop {
  87. let mint_input = get_user_input("Enter mint number to use (or 'done' to finish)")?;
  88. if mint_input.to_lowercase() == "done" || mint_input.is_empty() {
  89. break;
  90. }
  91. let mint_index: usize = mint_input.parse()?;
  92. let mint_url = balances
  93. .iter()
  94. .nth(mint_index)
  95. .map(|(url, _)| url.clone())
  96. .ok_or_else(|| anyhow::anyhow!("Invalid mint index"))?;
  97. let amount: u64 = get_number_input(&format!(
  98. "Enter amount to use from this mint ({})",
  99. multi_mint_wallet.unit()
  100. ))?;
  101. mint_amounts.push((mint_url, Amount::from(amount)));
  102. }
  103. if mint_amounts.is_empty() {
  104. bail!("No mints selected for MPP payment");
  105. }
  106. // Get quotes for each mint
  107. println!("\nGetting melt quotes...");
  108. let quotes = multi_mint_wallet
  109. .mpp_melt_quote(bolt11_str, mint_amounts)
  110. .await?;
  111. // Display quotes
  112. println!("\nMelt quotes obtained:");
  113. for (mint_url, quote) in &quotes {
  114. println!(" {} - Quote ID: {}", mint_url, quote.id);
  115. println!(" Amount: {}, Fee: {}", quote.amount, quote.fee_reserve);
  116. }
  117. // Execute the melts
  118. let quotes_to_execute: Vec<(MintUrl, String)> = quotes
  119. .iter()
  120. .map(|(url, quote)| (url.clone(), quote.id.clone()))
  121. .collect();
  122. println!("\nExecuting MPP payment...");
  123. let results = multi_mint_wallet.mpp_melt(quotes_to_execute).await?;
  124. // Display results
  125. println!("\nPayment results:");
  126. let mut total_paid = Amount::ZERO;
  127. let mut total_fees = Amount::ZERO;
  128. for (mint_url, melted) in results {
  129. println!(
  130. " {} - Paid: {}, Fee: {}",
  131. mint_url, melted.amount, melted.fee_paid
  132. );
  133. total_paid += melted.amount;
  134. total_fees += melted.fee_paid;
  135. if let Some(preimage) = melted.preimage {
  136. println!(" Preimage: {}", preimage);
  137. }
  138. }
  139. println!("\nTotal paid: {} {}", total_paid, multi_mint_wallet.unit());
  140. println!("Total fees: {} {}", total_fees, multi_mint_wallet.unit());
  141. } else {
  142. let available_funds = <cdk::Amount as Into<u64>>::into(total_balance) * MSAT_IN_SAT;
  143. // Process payment based on payment method using new unified interface
  144. match sub_command_args.method {
  145. PaymentType::Bolt11 => {
  146. // Process BOLT11 payment
  147. let bolt11_str = get_user_input("Enter bolt11 invoice")?;
  148. let bolt11 = Bolt11Invoice::from_str(&bolt11_str)?;
  149. // Determine payment amount and options
  150. let prompt = format!(
  151. "Enter the amount you would like to pay in {} for this amountless invoice.",
  152. multi_mint_wallet.unit()
  153. );
  154. let options =
  155. create_melt_options(available_funds, bolt11.amount_milli_satoshis(), &prompt)?;
  156. // Use mint-specific functions or auto-select
  157. let melted = if let Some(mint_url) = &sub_command_args.mint_url {
  158. // User specified a mint - use the new mint-specific functions
  159. let mint_url = MintUrl::from_str(mint_url)?;
  160. // Create a melt quote for the specific mint
  161. let quote = multi_mint_wallet
  162. .melt_quote(&mint_url, bolt11_str.clone(), options)
  163. .await?;
  164. println!("Melt quote created:");
  165. println!(" Quote ID: {}", quote.id);
  166. println!(" Amount: {}", quote.amount);
  167. println!(" Fee Reserve: {}", quote.fee_reserve);
  168. // Execute the melt
  169. multi_mint_wallet
  170. .melt_with_mint(&mint_url, &quote.id)
  171. .await?
  172. } else {
  173. // Let the wallet automatically select the best mint
  174. multi_mint_wallet.melt(&bolt11_str, options, None).await?
  175. };
  176. println!("Payment successful: {:?}", melted);
  177. if let Some(preimage) = melted.preimage {
  178. println!("Payment preimage: {}", preimage);
  179. }
  180. }
  181. PaymentType::Bolt12 => {
  182. // Process BOLT12 payment (offer)
  183. let offer_str = get_user_input("Enter BOLT12 offer")?;
  184. let offer = Offer::from_str(&offer_str)
  185. .map_err(|e| anyhow::anyhow!("Invalid BOLT12 offer: {:?}", e))?;
  186. // Determine if offer has an amount
  187. let prompt = format!(
  188. "Enter the amount you would like to pay in {} for this amountless offer:",
  189. multi_mint_wallet.unit()
  190. );
  191. let amount_msat = match amount_for_offer(&offer, &CurrencyUnit::Msat) {
  192. Ok(amount) => Some(u64::from(amount)),
  193. Err(_) => None,
  194. };
  195. let options = create_melt_options(available_funds, amount_msat, &prompt)?;
  196. // Get wallet for BOLT12
  197. let wallet = if let Some(mint_url) = &sub_command_args.mint_url {
  198. // User specified a mint
  199. let mint_url = MintUrl::from_str(mint_url)?;
  200. multi_mint_wallet
  201. .get_wallet(&mint_url)
  202. .await
  203. .ok_or_else(|| anyhow::anyhow!("Mint {} not found", mint_url))?
  204. } else {
  205. // Show available mints and let user select
  206. let balances = multi_mint_wallet.get_balances().await?;
  207. println!("\nAvailable mints:");
  208. for (i, (mint_url, balance)) in balances.iter().enumerate() {
  209. println!(
  210. " {}: {} - {} {}",
  211. i,
  212. mint_url,
  213. balance,
  214. multi_mint_wallet.unit()
  215. );
  216. }
  217. let mint_number: usize = get_number_input("Enter mint number to melt from")?;
  218. let selected_mint = balances
  219. .iter()
  220. .nth(mint_number)
  221. .map(|(url, _)| url)
  222. .ok_or_else(|| anyhow::anyhow!("Invalid mint number"))?;
  223. multi_mint_wallet
  224. .get_wallet(selected_mint)
  225. .await
  226. .ok_or_else(|| anyhow::anyhow!("Mint {} not found", selected_mint))?
  227. };
  228. // Get melt quote for BOLT12
  229. let quote = wallet.melt_bolt12_quote(offer_str, options).await?;
  230. // Display quote info
  231. println!("Melt quote created:");
  232. println!(" Quote ID: {}", quote.id);
  233. println!(" Amount: {}", quote.amount);
  234. println!(" Fee Reserve: {}", quote.fee_reserve);
  235. println!(" State: {}", quote.state);
  236. println!(" Expiry: {}", quote.expiry);
  237. // Execute the melt
  238. let melted = wallet.melt(&quote.id).await?;
  239. println!(
  240. "Payment successful: Paid {} with fee {}",
  241. melted.amount, melted.fee_paid
  242. );
  243. if let Some(preimage) = melted.preimage {
  244. println!("Payment preimage: {}", preimage);
  245. }
  246. }
  247. PaymentType::Bip353 => {
  248. let bip353_addr = get_user_input("Enter Bip353 address")?;
  249. let prompt = format!(
  250. "Enter the amount you would like to pay in {} for this amountless offer:",
  251. multi_mint_wallet.unit()
  252. );
  253. // BIP353 payments are always amountless for now
  254. let options = create_melt_options(available_funds, None, &prompt)?;
  255. // Get wallet for BIP353
  256. let wallet = if let Some(mint_url) = &sub_command_args.mint_url {
  257. // User specified a mint
  258. let mint_url = MintUrl::from_str(mint_url)?;
  259. multi_mint_wallet
  260. .get_wallet(&mint_url)
  261. .await
  262. .ok_or_else(|| anyhow::anyhow!("Mint {} not found", mint_url))?
  263. } else {
  264. // Show available mints and let user select
  265. let balances = multi_mint_wallet.get_balances().await?;
  266. println!("\nAvailable mints:");
  267. for (i, (mint_url, balance)) in balances.iter().enumerate() {
  268. println!(
  269. " {}: {} - {} {}",
  270. i,
  271. mint_url,
  272. balance,
  273. multi_mint_wallet.unit()
  274. );
  275. }
  276. let mint_number: usize = get_number_input("Enter mint number to melt from")?;
  277. let selected_mint = balances
  278. .iter()
  279. .nth(mint_number)
  280. .map(|(url, _)| url)
  281. .ok_or_else(|| anyhow::anyhow!("Invalid mint number"))?;
  282. multi_mint_wallet
  283. .get_wallet(selected_mint)
  284. .await
  285. .ok_or_else(|| anyhow::anyhow!("Mint {} not found", selected_mint))?
  286. };
  287. // Get melt quote for BIP353 address (internally resolves and gets BOLT12 quote)
  288. let quote = wallet
  289. .melt_bip353_quote(
  290. &bip353_addr,
  291. options.expect("Amount is required").amount_msat(),
  292. )
  293. .await?;
  294. // Display quote info
  295. println!("Melt quote created:");
  296. println!(" Quote ID: {}", quote.id);
  297. println!(" Amount: {}", quote.amount);
  298. println!(" Fee Reserve: {}", quote.fee_reserve);
  299. println!(" State: {}", quote.state);
  300. println!(" Expiry: {}", quote.expiry);
  301. // Execute the melt
  302. let melted = wallet.melt(&quote.id).await?;
  303. println!(
  304. "Payment successful: Paid {} with fee {}",
  305. melted.amount, melted.fee_paid
  306. );
  307. if let Some(preimage) = melted.preimage {
  308. println!("Payment preimage: {}", preimage);
  309. }
  310. }
  311. }
  312. }
  313. Ok(())
  314. }