uniffi_lipalightninglib/onchain/
swap.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
use crate::amount::{AsSats, Sats, ToAmount};
use crate::errors::Result;
use crate::locker::Locker;
use crate::onchain::{get_onchain_resolving_fees, query_onchain_fee_rate};
use crate::support::Support;
use crate::util::unix_timestamp_to_system_time;
use crate::{
    Amount, CalculateLspFeeResponseV2, FailedSwapInfo, LspFee, OnchainResolvingFees,
    ResolveFailedSwapInfo, RuntimeErrorCode, SwapAddressInfo,
};
use breez_sdk_core::error::ReceiveOnchainError;
use breez_sdk_core::{
    BitcoinAddressData, Network, OpeningFeeParams, PrepareRefundRequest, ReceiveOnchainRequest,
    RefundRequest,
};
use perro::{ensure, runtime_error, MapToError};
use std::sync::Arc;

pub struct Swap {
    support: Arc<Support>,
}

impl Swap {
    pub(crate) fn new(support: Arc<Support>) -> Self {
        Self { support }
    }

    /// Generates a Bitcoin on-chain address that can be used to topup the local LN wallet from an
    /// external on-chain wallet.
    ///
    /// Funds sent to this address should conform to the min and max values provided within
    /// [`SwapAddressInfo`].
    ///
    /// If a swap is in progress, this method will return an error.
    ///
    /// Parameters:
    ///
    /// Requires network: **yes**
    pub fn create(&self) -> std::result::Result<SwapAddressInfo, ReceiveOnchainError> {
        let lsp_fee_params =
            self.get_lsp_fee_params()
                .map_err(|_e| ReceiveOnchainError::ServiceConnectivity {
                    err: "Could not retrieve lsp fee params".to_string(),
                })?;
        let swap_info = self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.receive_onchain(ReceiveOnchainRequest {
                opening_fee_params: Some(lsp_fee_params),
            }))?;
        let rate = self.support.get_exchange_rate();

        Ok(SwapAddressInfo {
            address: swap_info.bitcoin_address,
            min_deposit: (swap_info.min_allowed_deposit as u64)
                .as_sats()
                .to_amount_up(&rate),
            max_deposit: (swap_info.max_allowed_deposit as u64)
                .as_sats()
                .to_amount_down(&rate),
            swap_fee: 0_u64.as_sats().to_amount_up(&rate),
        })
    }

    /// Returns the fees for resolving a failed swap if there are enough funds to pay for fees.
    ///
    /// Must only be called when the failed swap is unresolved.
    ///
    /// Returns the fee information for the available resolving options.
    ///
    /// Requires network: *yes*
    pub fn determine_resolving_fees(
        &self,
        failed_swap_info: FailedSwapInfo,
    ) -> Result<Option<OnchainResolvingFees>> {
        let failed_swap_closure = failed_swap_info.clone();
        let prepare_onchain_tx = move |address: String| -> Result<(Sats, Sats, u32)> {
            let sweep_info = self.prepare_sweep(
                failed_swap_closure,
                BitcoinAddressData {
                    address,
                    network: Network::Bitcoin,
                    amount_sat: None,
                    label: None,
                    message: None,
                },
            )?;

            Ok((
                sweep_info.recovered_amount.sats.as_sats(),
                sweep_info.onchain_fee.sats.as_sats(),
                sweep_info.onchain_fee_rate,
            ))
        };
        get_onchain_resolving_fees(
            &self.support,
            self,
            failed_swap_info.amount.sats.as_sats().msats(),
            prepare_onchain_tx,
        )
    }

    /// Prepares the sweep transaction for failed swap in order to know how much will be recovered
    /// and how much will be paid in on-chain fees.
    ///
    /// Parameters:
    /// * `failed_swap_info` - the failed swap that will be prepared
    /// * `destination` - the destination address to which funds will be sent.
    ///     Can be obtained using [`Util::decode_data`](crate::Util::decode_data)
    ///
    /// Requires network: **yes**
    pub fn prepare_sweep(
        &self,
        failed_swap_info: FailedSwapInfo,
        destination: BitcoinAddressData,
    ) -> Result<SweepFailedSwapInfo> {
        let to_address = destination.address;
        let onchain_fee_rate = query_onchain_fee_rate(&self.support)?;
        let response = self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.prepare_refund(PrepareRefundRequest {
                swap_address: failed_swap_info.address.clone(),
                to_address: to_address.clone(),
                sat_per_vbyte: onchain_fee_rate,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to prepare a failed swap refund transaction",
            )?;

        let rate = self.support.get_exchange_rate();
        let onchain_fee = response.refund_tx_fee_sat.as_sats().to_amount_up(&rate);
        let recovered_amount = (failed_swap_info.amount.sats - onchain_fee.sats)
            .as_sats()
            .to_amount_down(&rate);

        Ok(SweepFailedSwapInfo {
            swap_address: failed_swap_info.address,
            recovered_amount,
            onchain_fee,
            to_address,
            onchain_fee_rate,
        })
    }

    /// Creates and broadcasts a sweeping transaction to recover funds from a failed swap. Existing
    /// failed swaps can be listed using [`ActionsRequired::list`](crate::ActionsRequired::list) and preparing
    /// the resolution of a failed swap can be done using [`Swap::prepare_sweep`].
    ///
    /// Parameters:
    /// * `sweep_failed_swap_info` - Information needed to sweep the failed swap. Can be obtained
    ///   using [`Swap::prepare_sweep`].
    ///
    /// Returns the txid of the resolving transaction.
    ///
    /// Paid on-chain fees can be known in advance using [`Swap::prepare_sweep`].
    ///
    /// Requires network: **yes**
    pub fn sweep(&self, sweep_failed_swap_info: SweepFailedSwapInfo) -> Result<String> {
        Ok(self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.refund(RefundRequest {
                swap_address: sweep_failed_swap_info.swap_address,
                to_address: sweep_failed_swap_info.to_address,
                sat_per_vbyte: sweep_failed_swap_info.onchain_fee_rate,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to create and broadcast failed swap refund transaction",
            )?
            .refund_tx_id)
    }

    /// Automatically swaps failed swap funds back to lightning.
    ///
    /// If a swap is in progress, this method will return an error.
    ///
    /// If the current balance doesn't fulfill the limits, this method will return an error.
    /// Before using this method use [`Swap::determine_resolving_fees`] to validate a swap is available.
    ///
    /// Parameters:
    /// * `sat_per_vbyte` - the fee rate to use for the on-chain transaction.
    ///   Can be obtained with [`Swap::determine_resolving_fees`].
    ///
    /// Returns the txid of the sweeping tx.
    ///
    /// Requires network: **yes**
    pub fn swap(&self, failed_swap_info: FailedSwapInfo, sats_per_vbyte: u32) -> Result<String> {
        let swap_address_info = self.create().map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Couldn't generate swap address",
        )?;

        let prepare_response = self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.prepare_refund(PrepareRefundRequest {
                swap_address: failed_swap_info.address.clone(),
                to_address: swap_address_info.address.clone(),
                sat_per_vbyte: sats_per_vbyte,
            }))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Coudln't prepare refund")?;

        let send_amount_sats = failed_swap_info.amount.sats - prepare_response.refund_tx_fee_sat;

        ensure!(
            swap_address_info.min_deposit.sats <= send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed swap amount isn't enough for creating new swap"
            )
        );

        ensure!(
            swap_address_info.max_deposit.sats >= send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed swap amount is too big for creating new swap"
            )
        );

        let lsp_fees = self
            .support
            .calculate_lsp_fee_for_amount(send_amount_sats, self.get_lsp_fee_params()?)?
            .lsp_fee
            .sats;

        ensure!(
            lsp_fees < send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "A new channel is needed and the failed swap amount is not enough to pay for fees"
            )
        );

        let refund_response = self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.refund(RefundRequest {
                swap_address: failed_swap_info.address,
                to_address: swap_address_info.address,
                sat_per_vbyte: sats_per_vbyte,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't broadcast swap refund transaction",
            )?;

        Ok(refund_response.refund_tx_id)
    }

    pub(crate) fn list_failed_unresolved(&self) -> Result<Vec<FailedSwapInfo>> {
        Ok(self
            .support
            .rt
            .handle()
            .block_on(self.support.sdk.list_refundables())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to list refundable failed swaps",
            )?
            .into_iter()
            .filter(|s| s.refund_tx_ids.is_empty())
            .map(|s| FailedSwapInfo {
                address: s.bitcoin_address,
                amount: s
                    .confirmed_sats
                    .as_sats()
                    .to_amount_down(&self.support.get_exchange_rate()),
                created_at: unix_timestamp_to_system_time(s.created_at as u64),
            })
            .collect())
    }

    /// Calculate the actual LSP fee for the given amount of a swap.
    /// If the already existing inbound capacity is enough, no new channel is required.
    ///
    /// Parameters:
    /// * `amount_sat` - amount in sats to compute LSP fee for
    ///
    /// Requires network: **yes**
    pub fn calculate_lsp_fee_for_amount(
        &self,
        amount_sat: u64,
    ) -> Result<CalculateLspFeeResponseV2> {
        self.support
            .calculate_lsp_fee_for_amount(amount_sat, self.get_lsp_fee_params()?)
    }

    /// When receiving swaps, a new channel MAY be required. A fee will be charged to the user.
    /// Get information about the fee charged by the LSP for opening new channels
    ///
    /// Requires network: **no**
    pub fn get_lsp_fee(&self) -> Result<LspFee> {
        let exchange_rate = self.support.get_exchange_rate();
        let lsp_fee = self.get_lsp_fee_params()?;
        Ok(LspFee {
            channel_minimum_fee: lsp_fee.min_msat.as_msats().to_amount_up(&exchange_rate),
            channel_fee_permyriad: lsp_fee.proportional as u64 / 100,
        })
    }

    pub(crate) fn get_lsp_fee_params(&self) -> Result<OpeningFeeParams> {
        self.support
            .task_manager
            .lock_unwrap()
            .get_longer_valid_lsp_fee()
    }
}

/// Information the resolution of a failed swap.
pub struct SweepFailedSwapInfo {
    /// The address of the failed swap.
    pub swap_address: String,
    /// The amount that will be sent (swap amount - on-chain fee).
    pub recovered_amount: Amount,
    /// The amount that will be paid in on-chain fees.
    pub onchain_fee: Amount,
    /// The address to which recovered funds will be sent.
    pub to_address: String,
    /// The on-chain fee rate that will be applied. This fee rate results in the `onchain_fee`.
    pub onchain_fee_rate: u32,
}

impl From<ResolveFailedSwapInfo> for SweepFailedSwapInfo {
    fn from(value: ResolveFailedSwapInfo) -> Self {
        Self {
            swap_address: value.swap_address,
            recovered_amount: value.recovered_amount,
            onchain_fee: value.onchain_fee,
            to_address: value.to_address,
            onchain_fee_rate: value.onchain_fee_rate,
        }
    }
}

impl From<SweepFailedSwapInfo> for ResolveFailedSwapInfo {
    fn from(value: SweepFailedSwapInfo) -> Self {
        Self {
            swap_address: value.swap_address,
            recovered_amount: value.recovered_amount,
            onchain_fee: value.onchain_fee,
            to_address: value.to_address,
            onchain_fee_rate: value.onchain_fee_rate,
        }
    }
}