ldk_node/payment/
onchain.rs1use crate::config::Config;
11use crate::error::Error;
12use crate::logger::{log_info, LdkLogger, Logger};
13use crate::types::{ChannelManager, Wallet};
14use crate::wallet::OnchainSendAmount;
15
16use bitcoin::{Address, Txid};
17
18use std::sync::{Arc, RwLock};
19
20#[cfg(not(feature = "uniffi"))]
21type FeeRate = bitcoin::FeeRate;
22#[cfg(feature = "uniffi")]
23type FeeRate = Arc<bitcoin::FeeRate>;
24
25macro_rules! maybe_map_fee_rate_opt {
26 ($fee_rate_opt: expr) => {{
27 #[cfg(not(feature = "uniffi"))]
28 {
29 $fee_rate_opt
30 }
31 #[cfg(feature = "uniffi")]
32 {
33 $fee_rate_opt.map(|f| *f)
34 }
35 }};
36}
37
38pub struct OnchainPayment {
44 runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
45 wallet: Arc<Wallet>,
46 channel_manager: Arc<ChannelManager>,
47 config: Arc<Config>,
48 logger: Arc<Logger>,
49}
50
51impl OnchainPayment {
52 pub(crate) fn new(
53 runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, wallet: Arc<Wallet>,
54 channel_manager: Arc<ChannelManager>, config: Arc<Config>, logger: Arc<Logger>,
55 ) -> Self {
56 Self { runtime, wallet, channel_manager, config, logger }
57 }
58
59 pub fn new_address(&self) -> Result<Address, Error> {
61 let funding_address = self.wallet.get_new_address()?;
62 log_info!(self.logger, "Generated new funding address: {}", funding_address);
63 Ok(funding_address)
64 }
65
66 pub fn send_to_address(
76 &self, address: &bitcoin::Address, amount_sats: u64, fee_rate: Option<FeeRate>,
77 ) -> Result<Txid, Error> {
78 let rt_lock = self.runtime.read().unwrap();
79 if rt_lock.is_none() {
80 return Err(Error::NotRunning);
81 }
82
83 let cur_anchor_reserve_sats =
84 crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
85 let send_amount =
86 OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
87 let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
88 self.wallet.send_to_address(address, send_amount, fee_rate_opt)
89 }
90
91 pub fn send_all_to_address(
107 &self, address: &bitcoin::Address, retain_reserves: bool, fee_rate: Option<FeeRate>,
108 ) -> Result<Txid, Error> {
109 let rt_lock = self.runtime.read().unwrap();
110 if rt_lock.is_none() {
111 return Err(Error::NotRunning);
112 }
113
114 let send_amount = if retain_reserves {
115 let cur_anchor_reserve_sats =
116 crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
117 OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
118 } else {
119 OnchainSendAmount::AllDrainingReserve
120 };
121
122 let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
123 self.wallet.send_to_address(address, send_amount, fee_rate_opt)
124 }
125}