breez_sdk_liquid/
model.rs

1use anyhow::{anyhow, bail, Result};
2use bitcoin::{bip32, ScriptBuf};
3use boltz_client::{
4    boltz::{ChainPair, BOLTZ_MAINNET_URL_V2, BOLTZ_TESTNET_URL_V2},
5    network::{BitcoinChain, Chain, LiquidChain},
6    swaps::boltz::{
7        CreateChainResponse, CreateReverseResponse, CreateSubmarineResponse, Leaf, Side, SwapTree,
8    },
9    BtcSwapScript, Keypair, LBtcSwapScript,
10};
11use derivative::Derivative;
12use elements::AssetId;
13use lwk_wollet::ElementsNetwork;
14use maybe_sync::{MaybeSend, MaybeSync};
15use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
16use rusqlite::ToSql;
17use sdk_common::prelude::*;
18use sdk_common::utils::Arc;
19use sdk_common::{bitcoin::hashes::hex::ToHex, lightning_with_bolt12::offers::offer::Offer};
20use serde::{Deserialize, Serialize};
21use std::cmp::PartialEq;
22use std::path::PathBuf;
23use std::str::FromStr;
24use strum_macros::{Display, EnumString};
25use tokio_with_wasm::alias as tokio;
26
27use crate::{
28    bitcoin,
29    chain::bitcoin::esplora::EsploraBitcoinChainService,
30    chain::liquid::esplora::EsploraLiquidChainService,
31    chain::{bitcoin::BitcoinChainService, liquid::LiquidChainService},
32    elements,
33    error::{PaymentError, SdkError, SdkResult},
34    persist::model::PaymentTxBalance,
35    prelude::DEFAULT_EXTERNAL_INPUT_PARSERS,
36    receive_swap::DEFAULT_ZERO_CONF_MAX_SAT,
37    side_swap::api::{SIDESWAP_MAINNET_URL, SIDESWAP_TESTNET_URL},
38    utils,
39};
40
41// Uses f64 for the maximum precision when converting between units
42pub const LIQUID_FEE_RATE_SAT_PER_VBYTE: f64 = 0.1;
43pub const LIQUID_FEE_RATE_MSAT_PER_VBYTE: f32 = (LIQUID_FEE_RATE_SAT_PER_VBYTE * 1000.0) as f32;
44pub const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology";
45pub const BREEZ_LIQUID_ESPLORA_URL: &str = "https://lq1.breez.technology/liquid/api";
46pub const BREEZ_SWAP_PROXY_URL: &str = "https://swap.breez.technology/v2";
47pub const DEFAULT_ONCHAIN_FEE_RATE_LEEWAY_SAT: u64 = 500;
48
49const SIDESWAP_API_KEY: &str = "97fb6a1dfa37ee6656af92ef79675cc03b8ac4c52e04655f41edbd5af888dcc2";
50
51#[derive(Clone, Debug, Serialize)]
52pub enum BlockchainExplorer {
53    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
54    Electrum { url: String },
55    Esplora {
56        url: String,
57        /// Whether or not to use the "waterfalls" extension
58        use_waterfalls: bool,
59    },
60}
61
62/// Configuration for the Liquid SDK
63#[derive(Clone, Debug, Serialize)]
64pub struct Config {
65    pub liquid_explorer: BlockchainExplorer,
66    pub bitcoin_explorer: BlockchainExplorer,
67    /// Directory in which the DB and log files are stored.
68    ///
69    /// Prefix can be a relative or absolute path to this directory.
70    pub working_dir: String,
71    pub network: LiquidNetwork,
72    /// Send payment timeout. See [LiquidSdk::send_payment](crate::sdk::LiquidSdk::send_payment)
73    pub payment_timeout_sec: u64,
74    /// The url of the real-time sync service. Defaults to [BREEZ_SYNC_SERVICE_URL]
75    /// Setting this field to `None` will disable the service
76    pub sync_service_url: Option<String>,
77    /// Maximum amount in satoshi to accept zero-conf payments with
78    /// Defaults to [DEFAULT_ZERO_CONF_MAX_SAT]
79    pub zero_conf_max_amount_sat: Option<u64>,
80    /// The Breez API key used for making requests to the sync service
81    pub breez_api_key: Option<String>,
82    /// A set of external input parsers that are used by [LiquidSdk::parse](crate::sdk::LiquidSdk::parse) when the input
83    /// is not recognized. See [ExternalInputParser] for more details on how to configure
84    /// external parsing.
85    pub external_input_parsers: Option<Vec<ExternalInputParser>>,
86    /// The SDK includes some default external input parsers
87    /// ([DEFAULT_EXTERNAL_INPUT_PARSERS](crate::sdk::DEFAULT_EXTERNAL_INPUT_PARSERS)).
88    /// Set this to false in order to prevent their use.
89    pub use_default_external_input_parsers: bool,
90    /// For payments where the onchain fees can only be estimated on creation, this can be used
91    /// in order to automatically allow slightly more expensive fees. If the actual fee ends up
92    /// being above the sum of the initial estimate and this leeway, the payment will require
93    /// user fee acceptance. See [WaitingFeeAcceptance](PaymentState::WaitingFeeAcceptance).
94    ///
95    /// Defaults to [DEFAULT_ONCHAIN_FEE_RATE_LEEWAY_SAT].
96    pub onchain_fee_rate_leeway_sat: Option<u64>,
97    /// A set of asset metadata used by [LiquidSdk::parse](crate::sdk::LiquidSdk::parse) when the input is a
98    /// [LiquidAddressData] and the [asset_id](LiquidAddressData::asset_id) differs from the Liquid Bitcoin asset.
99    /// See [AssetMetadata] for more details on how define asset metadata.
100    /// By default the asset metadata for Liquid Bitcoin and Tether USD are included.
101    pub asset_metadata: Option<Vec<AssetMetadata>>,
102    /// The SideSwap API key used for making requests to the SideSwap payjoin service
103    pub sideswap_api_key: Option<String>,
104    /// Set this to false to disable the use of Magic Routing Hints (MRH) to send payments. Enabled by default.
105    pub use_magic_routing_hints: bool,
106}
107
108impl Config {
109    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
110    pub fn mainnet(breez_api_key: Option<String>) -> Self {
111        Config {
112            liquid_explorer: BlockchainExplorer::Electrum {
113                url: "elements-mainnet.breez.technology:50002".to_string(),
114            },
115            bitcoin_explorer: BlockchainExplorer::Electrum {
116                url: "bitcoin-mainnet.blockstream.info:50002".to_string(),
117            },
118            working_dir: ".".to_string(),
119            network: LiquidNetwork::Mainnet,
120            payment_timeout_sec: 15,
121            sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
122            zero_conf_max_amount_sat: None,
123            breez_api_key,
124            external_input_parsers: None,
125            use_default_external_input_parsers: true,
126            onchain_fee_rate_leeway_sat: None,
127            asset_metadata: None,
128            sideswap_api_key: Some(SIDESWAP_API_KEY.to_string()),
129            use_magic_routing_hints: true,
130        }
131    }
132
133    pub fn mainnet_esplora(breez_api_key: Option<String>) -> Self {
134        Config {
135            liquid_explorer: BlockchainExplorer::Esplora {
136                url: BREEZ_LIQUID_ESPLORA_URL.to_string(),
137                use_waterfalls: true,
138            },
139            bitcoin_explorer: BlockchainExplorer::Esplora {
140                url: "https://blockstream.info/api/".to_string(),
141                use_waterfalls: false,
142            },
143            working_dir: ".".to_string(),
144            network: LiquidNetwork::Mainnet,
145            payment_timeout_sec: 15,
146            sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
147            zero_conf_max_amount_sat: None,
148            breez_api_key,
149            external_input_parsers: None,
150            use_default_external_input_parsers: true,
151            onchain_fee_rate_leeway_sat: None,
152            asset_metadata: None,
153            sideswap_api_key: Some(SIDESWAP_API_KEY.to_string()),
154            use_magic_routing_hints: true,
155        }
156    }
157
158    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
159    pub fn testnet(breez_api_key: Option<String>) -> Self {
160        Config {
161            liquid_explorer: BlockchainExplorer::Electrum {
162                url: "elements-testnet.blockstream.info:50002".to_string(),
163            },
164            bitcoin_explorer: BlockchainExplorer::Electrum {
165                url: "bitcoin-testnet.blockstream.info:50002".to_string(),
166            },
167            working_dir: ".".to_string(),
168            network: LiquidNetwork::Testnet,
169            payment_timeout_sec: 15,
170            sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
171            zero_conf_max_amount_sat: None,
172            breez_api_key,
173            external_input_parsers: None,
174            use_default_external_input_parsers: true,
175            onchain_fee_rate_leeway_sat: None,
176            asset_metadata: None,
177            sideswap_api_key: Some(SIDESWAP_API_KEY.to_string()),
178            use_magic_routing_hints: true,
179        }
180    }
181
182    pub fn testnet_esplora(breez_api_key: Option<String>) -> Self {
183        Config {
184            liquid_explorer: BlockchainExplorer::Esplora {
185                url: "https://blockstream.info/liquidtestnet/api".to_string(),
186                use_waterfalls: false,
187            },
188            bitcoin_explorer: BlockchainExplorer::Esplora {
189                url: "https://blockstream.info/testnet/api/".to_string(),
190                use_waterfalls: false,
191            },
192            working_dir: ".".to_string(),
193            network: LiquidNetwork::Testnet,
194            payment_timeout_sec: 15,
195            sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
196            zero_conf_max_amount_sat: None,
197            breez_api_key,
198            external_input_parsers: None,
199            use_default_external_input_parsers: true,
200            onchain_fee_rate_leeway_sat: None,
201            asset_metadata: None,
202            sideswap_api_key: Some(SIDESWAP_API_KEY.to_string()),
203            use_magic_routing_hints: true,
204        }
205    }
206
207    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
208    pub fn regtest() -> Self {
209        Config {
210            liquid_explorer: BlockchainExplorer::Electrum {
211                url: "localhost:19002".to_string(),
212            },
213            bitcoin_explorer: BlockchainExplorer::Electrum {
214                url: "localhost:19001".to_string(),
215            },
216            working_dir: ".".to_string(),
217            network: LiquidNetwork::Regtest,
218            payment_timeout_sec: 15,
219            sync_service_url: Some("http://localhost:8088".to_string()),
220            zero_conf_max_amount_sat: None,
221            breez_api_key: None,
222            external_input_parsers: None,
223            use_default_external_input_parsers: true,
224            onchain_fee_rate_leeway_sat: None,
225            asset_metadata: None,
226            sideswap_api_key: None,
227            use_magic_routing_hints: true,
228        }
229    }
230
231    pub fn regtest_esplora() -> Self {
232        Config {
233            liquid_explorer: BlockchainExplorer::Esplora {
234                url: "http://localhost:3120/api".to_string(),
235                use_waterfalls: true,
236            },
237            bitcoin_explorer: BlockchainExplorer::Esplora {
238                url: "http://localhost:4002/api".to_string(),
239                use_waterfalls: false,
240            },
241            working_dir: ".".to_string(),
242            network: LiquidNetwork::Regtest,
243            payment_timeout_sec: 15,
244            sync_service_url: Some("http://localhost:8089".to_string()),
245            zero_conf_max_amount_sat: None,
246            breez_api_key: None,
247            external_input_parsers: None,
248            use_default_external_input_parsers: true,
249            onchain_fee_rate_leeway_sat: None,
250            asset_metadata: None,
251            sideswap_api_key: None,
252            use_magic_routing_hints: true,
253        }
254    }
255
256    pub fn get_wallet_dir(&self, base_dir: &str, fingerprint_hex: &str) -> anyhow::Result<String> {
257        Ok(PathBuf::from(base_dir)
258            .join(match self.network {
259                LiquidNetwork::Mainnet => "mainnet",
260                LiquidNetwork::Testnet => "testnet",
261                LiquidNetwork::Regtest => "regtest",
262            })
263            .join(fingerprint_hex)
264            .to_str()
265            .ok_or(anyhow::anyhow!(
266                "Could not get retrieve current wallet directory"
267            ))?
268            .to_string())
269    }
270
271    pub fn zero_conf_max_amount_sat(&self) -> u64 {
272        self.zero_conf_max_amount_sat
273            .unwrap_or(DEFAULT_ZERO_CONF_MAX_SAT)
274    }
275
276    pub(crate) fn lbtc_asset_id(&self) -> String {
277        utils::lbtc_asset_id(self.network).to_string()
278    }
279
280    pub(crate) fn get_all_external_input_parsers(&self) -> Vec<ExternalInputParser> {
281        let mut external_input_parsers = Vec::new();
282        if self.use_default_external_input_parsers {
283            let default_parsers = DEFAULT_EXTERNAL_INPUT_PARSERS
284                .iter()
285                .map(|(id, regex, url)| ExternalInputParser {
286                    provider_id: id.to_string(),
287                    input_regex: regex.to_string(),
288                    parser_url: url.to_string(),
289                })
290                .collect::<Vec<_>>();
291            external_input_parsers.extend(default_parsers);
292        }
293        external_input_parsers.extend(self.external_input_parsers.clone().unwrap_or_default());
294
295        external_input_parsers
296    }
297
298    pub(crate) fn default_boltz_url(&self) -> &str {
299        match self.network {
300            LiquidNetwork::Mainnet => {
301                if self.breez_api_key.is_some() {
302                    BREEZ_SWAP_PROXY_URL
303                } else {
304                    BOLTZ_MAINNET_URL_V2
305                }
306            }
307            LiquidNetwork::Testnet => BOLTZ_TESTNET_URL_V2,
308            // On regtest use the swapproxy instance by default
309            LiquidNetwork::Regtest => "http://localhost:8387/v2",
310        }
311    }
312
313    pub fn sync_enabled(&self) -> bool {
314        self.sync_service_url.is_some()
315    }
316
317    pub(crate) fn bitcoin_chain_service(&self) -> Arc<dyn BitcoinChainService> {
318        match self.bitcoin_explorer {
319            BlockchainExplorer::Esplora { .. } => {
320                Arc::new(EsploraBitcoinChainService::new(self.clone()))
321            }
322            #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
323            BlockchainExplorer::Electrum { .. } => Arc::new(
324                crate::chain::bitcoin::electrum::ElectrumBitcoinChainService::new(self.clone()),
325            ),
326        }
327    }
328
329    pub(crate) fn liquid_chain_service(&self) -> Result<Arc<dyn LiquidChainService>> {
330        match &self.liquid_explorer {
331            BlockchainExplorer::Esplora { url, .. } => {
332                if url == BREEZ_LIQUID_ESPLORA_URL && self.breez_api_key.is_none() {
333                    bail!("Cannot start the Breez Esplora chain service without providing an API key. See https://sdk-doc-liquid.breez.technology/guide/getting_started.html#api-key")
334                }
335                Ok(Arc::new(EsploraLiquidChainService::new(self.clone())))
336            }
337            #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
338            BlockchainExplorer::Electrum { .. } => Ok(Arc::new(
339                crate::chain::liquid::electrum::ElectrumLiquidChainService::new(self.clone()),
340            )),
341        }
342    }
343
344    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
345    pub(crate) fn electrum_tls_options(&self) -> (/*tls*/ bool, /*validate_domain*/ bool) {
346        match self.network {
347            LiquidNetwork::Mainnet | LiquidNetwork::Testnet => (true, true),
348            LiquidNetwork::Regtest => (false, false),
349        }
350    }
351
352    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
353    pub(crate) fn electrum_client(
354        &self,
355        url: &str,
356    ) -> Result<lwk_wollet::ElectrumClient, lwk_wollet::Error> {
357        let (tls, validate_domain) = self.electrum_tls_options();
358        let electrum_url = lwk_wollet::ElectrumUrl::new(url, tls, validate_domain)?;
359        lwk_wollet::ElectrumClient::with_options(
360            &electrum_url,
361            lwk_wollet::ElectrumOptions { timeout: Some(3) },
362        )
363    }
364
365    pub(crate) fn sideswap_url(&self) -> &'static str {
366        match self.network {
367            LiquidNetwork::Mainnet => SIDESWAP_MAINNET_URL,
368            LiquidNetwork::Testnet => SIDESWAP_TESTNET_URL,
369            LiquidNetwork::Regtest => unimplemented!(),
370        }
371    }
372}
373
374/// Network chosen for this Liquid SDK instance. Note that it represents both the Liquid and the
375/// Bitcoin network used.
376#[derive(Debug, Display, Copy, Clone, PartialEq, Serialize)]
377pub enum LiquidNetwork {
378    /// Mainnet Bitcoin and Liquid chains
379    Mainnet,
380    /// Testnet Bitcoin and Liquid chains
381    Testnet,
382    /// Regtest Bitcoin and Liquid chains
383    Regtest,
384}
385impl LiquidNetwork {
386    pub fn as_bitcoin_chain(&self) -> BitcoinChain {
387        match self {
388            LiquidNetwork::Mainnet => BitcoinChain::Bitcoin,
389            LiquidNetwork::Testnet => BitcoinChain::BitcoinTestnet,
390            LiquidNetwork::Regtest => BitcoinChain::BitcoinRegtest,
391        }
392    }
393}
394
395impl From<LiquidNetwork> for ElementsNetwork {
396    fn from(value: LiquidNetwork) -> Self {
397        match value {
398            LiquidNetwork::Mainnet => ElementsNetwork::Liquid,
399            LiquidNetwork::Testnet => ElementsNetwork::LiquidTestnet,
400            LiquidNetwork::Regtest => ElementsNetwork::ElementsRegtest {
401                policy_asset: AssetId::from_str(
402                    "5ac9f65c0efcc4775e0baec4ec03abdde22473cd3cf33c0419ca290e0751b225",
403                )
404                .unwrap(),
405            },
406        }
407    }
408}
409
410impl From<LiquidNetwork> for Chain {
411    fn from(value: LiquidNetwork) -> Self {
412        Chain::Liquid(value.into())
413    }
414}
415
416impl From<LiquidNetwork> for LiquidChain {
417    fn from(value: LiquidNetwork) -> Self {
418        match value {
419            LiquidNetwork::Mainnet => LiquidChain::Liquid,
420            LiquidNetwork::Testnet => LiquidChain::LiquidTestnet,
421            LiquidNetwork::Regtest => LiquidChain::LiquidRegtest,
422        }
423    }
424}
425
426impl TryFrom<&str> for LiquidNetwork {
427    type Error = anyhow::Error;
428
429    fn try_from(value: &str) -> Result<LiquidNetwork, anyhow::Error> {
430        match value.to_lowercase().as_str() {
431            "mainnet" => Ok(LiquidNetwork::Mainnet),
432            "testnet" => Ok(LiquidNetwork::Testnet),
433            "regtest" => Ok(LiquidNetwork::Regtest),
434            _ => Err(anyhow!("Invalid network")),
435        }
436    }
437}
438
439impl From<LiquidNetwork> for Network {
440    fn from(value: LiquidNetwork) -> Self {
441        match value {
442            LiquidNetwork::Mainnet => Self::Bitcoin,
443            LiquidNetwork::Testnet => Self::Testnet,
444            LiquidNetwork::Regtest => Self::Regtest,
445        }
446    }
447}
448
449impl From<LiquidNetwork> for sdk_common::bitcoin::Network {
450    fn from(value: LiquidNetwork) -> Self {
451        match value {
452            LiquidNetwork::Mainnet => Self::Bitcoin,
453            LiquidNetwork::Testnet => Self::Testnet,
454            LiquidNetwork::Regtest => Self::Regtest,
455        }
456    }
457}
458
459impl From<LiquidNetwork> for boltz_client::bitcoin::Network {
460    fn from(value: LiquidNetwork) -> Self {
461        match value {
462            LiquidNetwork::Mainnet => Self::Bitcoin,
463            LiquidNetwork::Testnet => Self::Testnet,
464            LiquidNetwork::Regtest => Self::Regtest,
465        }
466    }
467}
468
469/// Trait that can be used to react to various [SdkEvent]s emitted by the SDK.
470pub trait EventListener: MaybeSend + MaybeSync {
471    fn on_event(&self, e: SdkEvent);
472}
473
474/// Event emitted by the SDK. Add an [EventListener] by calling [crate::sdk::LiquidSdk::add_event_listener]
475/// to listen for emitted events.
476#[derive(Clone, Debug, PartialEq)]
477pub enum SdkEvent {
478    PaymentFailed {
479        details: Payment,
480    },
481    PaymentPending {
482        details: Payment,
483    },
484    PaymentRefundable {
485        details: Payment,
486    },
487    PaymentRefunded {
488        details: Payment,
489    },
490    PaymentRefundPending {
491        details: Payment,
492    },
493    PaymentSucceeded {
494        details: Payment,
495    },
496    PaymentWaitingConfirmation {
497        details: Payment,
498    },
499    PaymentWaitingFeeAcceptance {
500        details: Payment,
501    },
502    /// Synced with mempool and onchain data
503    Synced,
504    /// Synced with real-time data sync
505    DataSynced {
506        /// Indicates new data was pulled from other instances.
507        did_pull_new_records: bool,
508    },
509}
510
511#[derive(thiserror::Error, Debug)]
512pub enum SignerError {
513    #[error("Signer error: {err}")]
514    Generic { err: String },
515}
516
517impl From<anyhow::Error> for SignerError {
518    fn from(err: anyhow::Error) -> Self {
519        SignerError::Generic {
520            err: err.to_string(),
521        }
522    }
523}
524
525impl From<bip32::Error> for SignerError {
526    fn from(err: bip32::Error) -> Self {
527        SignerError::Generic {
528            err: err.to_string(),
529        }
530    }
531}
532
533/// A trait that can be used to sign messages and verify signatures.
534/// The sdk user can implement this trait to use their own signer.
535pub trait Signer: MaybeSend + MaybeSync {
536    /// The master xpub encoded as 78 bytes length as defined in bip32 specification.
537    /// For reference: <https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#user-content-Serialization_format>
538    fn xpub(&self) -> Result<Vec<u8>, SignerError>;
539
540    /// The derived xpub encoded as 78 bytes length as defined in bip32 specification.
541    /// The derivation path is a string represents the shorter notation of the key tree to derive. For example:
542    /// m/49'/1'/0'/0/0
543    /// m/48'/1'/0'/0/0
544    /// For reference: <https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#user-content-The_key_tree>
545    fn derive_xpub(&self, derivation_path: String) -> Result<Vec<u8>, SignerError>;
546
547    /// Sign an ECDSA message using the private key derived from the given derivation path
548    fn sign_ecdsa(&self, msg: Vec<u8>, derivation_path: String) -> Result<Vec<u8>, SignerError>;
549
550    /// Sign an ECDSA message using the private key derived from the master key
551    fn sign_ecdsa_recoverable(&self, msg: Vec<u8>) -> Result<Vec<u8>, SignerError>;
552
553    /// Return the master blinding key for SLIP77: <https://github.com/satoshilabs/slips/blob/master/slip-0077.md>
554    fn slip77_master_blinding_key(&self) -> Result<Vec<u8>, SignerError>;
555
556    /// HMAC-SHA256 using the private key derived from the given derivation path
557    /// This is used to calculate the linking key of lnurl-auth specification: <https://github.com/lnurl/luds/blob/luds/05.md>
558    fn hmac_sha256(&self, msg: Vec<u8>, derivation_path: String) -> Result<Vec<u8>, SignerError>;
559
560    /// Encrypts a message using (ECIES)[ecies::encrypt]
561    fn ecies_encrypt(&self, msg: Vec<u8>) -> Result<Vec<u8>, SignerError>;
562
563    /// Decrypts a message using (ECIES)[ecies::decrypt]
564    fn ecies_decrypt(&self, msg: Vec<u8>) -> Result<Vec<u8>, SignerError>;
565}
566
567/// An argument when calling [crate::sdk::LiquidSdk::connect].
568/// The resquest takes either a `mnemonic` and `passphrase`, or a `seed`.
569pub struct ConnectRequest {
570    /// The SDK [Config]
571    pub config: Config,
572    /// The optional Liquid wallet mnemonic
573    pub mnemonic: Option<String>,
574    /// The optional passphrase for the mnemonic
575    pub passphrase: Option<String>,
576    /// The optional Liquid wallet seed
577    pub seed: Option<Vec<u8>>,
578}
579
580pub struct ConnectWithSignerRequest {
581    pub config: Config,
582}
583
584/// A reserved address. Once an address is reserved, it can only be
585/// reallocated to another payment after the block height expiration.
586#[derive(Clone, Debug)]
587pub(crate) struct ReservedAddress {
588    /// The address that is reserved
589    pub(crate) address: String,
590    /// The block height that the address is reserved until
591    pub(crate) expiry_block_height: u32,
592}
593
594/// The send/receive methods supported by the SDK
595#[derive(Clone, Debug, Serialize)]
596pub enum PaymentMethod {
597    #[deprecated(since = "0.8.1", note = "Use `Bolt11Invoice` instead")]
598    Lightning,
599    Bolt11Invoice,
600    Bolt12Offer,
601    BitcoinAddress,
602    LiquidAddress,
603}
604
605#[derive(Debug, Serialize, Clone)]
606pub enum ReceiveAmount {
607    /// The amount in satoshi that should be paid
608    Bitcoin { payer_amount_sat: u64 },
609
610    /// The amount of an asset that should be paid
611    Asset {
612        asset_id: String,
613        payer_amount: Option<f64>,
614    },
615}
616
617/// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_payment].
618#[derive(Debug, Serialize)]
619pub struct PrepareReceiveRequest {
620    pub payment_method: PaymentMethod,
621    /// The amount to be paid in either Bitcoin or another asset
622    pub amount: Option<ReceiveAmount>,
623}
624
625/// Returned when calling [crate::sdk::LiquidSdk::prepare_receive_payment].
626#[derive(Debug, Serialize, Clone)]
627pub struct PrepareReceiveResponse {
628    pub payment_method: PaymentMethod,
629    /// Generally represents the total fees that would be paid to send or receive this payment.
630    ///
631    /// In case of Zero-Amount Receive Chain swaps, the swapper service fee (`swapper_feerate` times
632    /// the amount) is paid in addition to `fees_sat`. The swapper service feerate is already known
633    /// in the beginning, but the exact swapper service fee will only be known when the
634    /// `payer_amount_sat` is known.
635    ///
636    /// In all other types of swaps, the swapper service fee is included in `fees_sat`.
637    pub fees_sat: u64,
638    /// The amount to be paid in either Bitcoin or another asset
639    pub amount: Option<ReceiveAmount>,
640    /// The minimum amount the payer can send for this swap to succeed.
641    ///
642    /// When the method is [PaymentMethod::LiquidAddress], this is empty.
643    pub min_payer_amount_sat: Option<u64>,
644    /// The maximum amount the payer can send for this swap to succeed.
645    ///
646    /// When the method is [PaymentMethod::LiquidAddress], this is empty.
647    pub max_payer_amount_sat: Option<u64>,
648    /// The percentage of the sent amount that will count towards the service fee.
649    ///
650    /// When the method is [PaymentMethod::LiquidAddress], this is empty.
651    pub swapper_feerate: Option<f64>,
652}
653
654/// An argument when calling [crate::sdk::LiquidSdk::receive_payment].
655#[derive(Debug, Serialize)]
656pub struct ReceivePaymentRequest {
657    pub prepare_response: PrepareReceiveResponse,
658    /// The description for this payment request
659    pub description: Option<String>,
660    /// If set to true, then the hash of the description will be used
661    pub use_description_hash: Option<bool>,
662    /// An optional payer note, typically included in a LNURL-Pay request
663    pub payer_note: Option<String>,
664}
665
666/// Returned when calling [crate::sdk::LiquidSdk::receive_payment].
667#[derive(Debug, Serialize)]
668pub struct ReceivePaymentResponse {
669    /// Either a BIP21 URI (Liquid or Bitcoin), a Liquid address
670    /// or an invoice, depending on the [PrepareReceiveResponse] parameters
671    pub destination: String,
672}
673
674/// An argument when calling [crate::sdk::LiquidSdk::create_bolt12_invoice].
675#[derive(Debug, Serialize)]
676pub struct CreateBolt12InvoiceRequest {
677    /// The BOLT12 offer
678    pub offer: String,
679    /// The invoice request created from the offer
680    pub invoice_request: String,
681}
682
683/// Returned when calling [crate::sdk::LiquidSdk::create_bolt12_invoice].
684#[derive(Debug, Serialize, Clone)]
685pub struct CreateBolt12InvoiceResponse {
686    /// The BOLT12 invoice
687    pub invoice: String,
688}
689
690/// The minimum and maximum in satoshis of a Lightning or onchain payment.
691#[derive(Debug, Serialize)]
692pub struct Limits {
693    pub min_sat: u64,
694    pub max_sat: u64,
695    pub max_zero_conf_sat: u64,
696}
697
698/// Returned when calling [crate::sdk::LiquidSdk::fetch_lightning_limits].
699#[derive(Debug, Serialize)]
700pub struct LightningPaymentLimitsResponse {
701    /// Amount limits for a Send Payment to be valid
702    pub send: Limits,
703    /// Amount limits for a Receive Payment to be valid
704    pub receive: Limits,
705}
706
707/// Returned when calling [crate::sdk::LiquidSdk::fetch_onchain_limits].
708#[derive(Debug, Serialize)]
709pub struct OnchainPaymentLimitsResponse {
710    /// Amount limits for a Send Onchain Payment to be valid
711    pub send: Limits,
712    /// Amount limits for a Receive Onchain Payment to be valid
713    pub receive: Limits,
714}
715
716/// An argument when calling [crate::sdk::LiquidSdk::prepare_send_payment].
717#[derive(Debug, Serialize, Clone)]
718pub struct PrepareSendRequest {
719    /// The destination we intend to pay to.
720    /// Supports BIP21 URIs, BOLT11 invoices, BOLT12 offers and Liquid addresses
721    pub destination: String,
722    /// Should only be set when paying directly onchain or to a BIP21 URI
723    /// where no amount is specified, or when the caller wishes to drain
724    pub amount: Option<PayAmount>,
725}
726
727/// Specifies the supported destinations which can be payed by the SDK
728#[derive(Clone, Debug, Serialize)]
729pub enum SendDestination {
730    LiquidAddress {
731        address_data: liquid::LiquidAddressData,
732        /// A BIP353 address, in case one was used to resolve this Liquid address
733        bip353_address: Option<String>,
734    },
735    Bolt11 {
736        invoice: LNInvoice,
737        /// A BIP353 address, in case one was used to resolve this BOLT11
738        bip353_address: Option<String>,
739    },
740    Bolt12 {
741        offer: LNOffer,
742        receiver_amount_sat: u64,
743        /// A BIP353 address, in case one was used to resolve this BOLT12
744        bip353_address: Option<String>,
745    },
746}
747
748/// Returned when calling [crate::sdk::LiquidSdk::prepare_send_payment].
749#[derive(Debug, Serialize, Clone)]
750pub struct PrepareSendResponse {
751    pub destination: SendDestination,
752    /// The optional amount to be sent in either Bitcoin or another asset
753    pub amount: Option<PayAmount>,
754    /// The optional estimated fee in satoshi. Is set when there is Bitcoin available
755    /// to pay fees. When not set, there are asset fees available to pay fees.
756    pub fees_sat: Option<u64>,
757    /// The optional estimated fee in the asset. Is set when [PayAmount::Asset::estimate_asset_fees]
758    /// is set to `true`, the Payjoin service accepts this asset to pay fees and there
759    /// are funds available in this asset to pay fees.
760    pub estimated_asset_fees: Option<f64>,
761    /// The amount of funds required (in satoshi) to execute a SideSwap payment, excluding fees.
762    /// Only present when [PayAmount::Asset::pay_with_bitcoin] is set to `true`.
763    pub exchange_amount_sat: Option<u64>,
764}
765
766/// An argument when calling [crate::sdk::LiquidSdk::send_payment].
767#[derive(Debug, Serialize)]
768pub struct SendPaymentRequest {
769    pub prepare_response: PrepareSendResponse,
770    /// If set to true, the payment will be sent using the SideSwap payjoin service
771    pub use_asset_fees: Option<bool>,
772    /// An optional payer note, which is to be included in a BOLT12 invoice request
773    pub payer_note: Option<String>,
774}
775
776/// Returned when calling [crate::sdk::LiquidSdk::send_payment].
777#[derive(Debug, Serialize)]
778pub struct SendPaymentResponse {
779    pub payment: Payment,
780}
781
782pub(crate) struct SendPaymentViaSwapRequest {
783    pub(crate) invoice: String,
784    pub(crate) bolt12_offer: Option<String>,
785    pub(crate) payment_hash: String,
786    pub(crate) description: Option<String>,
787    pub(crate) receiver_amount_sat: u64,
788    pub(crate) fees_sat: u64,
789}
790
791pub(crate) struct PayLiquidRequest {
792    pub address_data: LiquidAddressData,
793    pub to_asset: String,
794    pub receiver_amount_sat: u64,
795    pub asset_pay_fees: bool,
796    pub fees_sat: Option<u64>,
797}
798
799pub(crate) struct PaySideSwapRequest {
800    pub address_data: LiquidAddressData,
801    pub to_asset: String,
802    pub receiver_amount_sat: u64,
803    pub fees_sat: u64,
804    pub amount: Option<PayAmount>,
805}
806
807/// Used to specify the amount to sent or to send all funds.
808#[derive(Debug, Serialize, Clone)]
809pub enum PayAmount {
810    /// The amount in satoshi that will be received
811    Bitcoin { receiver_amount_sat: u64 },
812
813    /// The amount of an asset that will be received
814    Asset {
815        /// The asset id specifying which asset will be sent
816        to_asset: String,
817        receiver_amount: f64,
818        estimate_asset_fees: Option<bool>,
819        /// The asset id whose balance we want to send funds with.
820        /// Defaults to the value provided for [PayAmount::Asset::to_asset]
821        from_asset: Option<String>,
822    },
823
824    /// Indicates that all available Bitcoin funds should be sent
825    Drain,
826}
827
828impl PayAmount {
829    pub(crate) fn is_sideswap_payment(&self) -> bool {
830        match self {
831            PayAmount::Asset {
832                to_asset,
833                from_asset,
834                ..
835            } => from_asset.as_ref().is_some_and(|asset| asset != to_asset),
836            _ => false,
837        }
838    }
839}
840
841/// An argument when calling [crate::sdk::LiquidSdk::prepare_pay_onchain].
842#[derive(Debug, Serialize, Clone)]
843pub struct PreparePayOnchainRequest {
844    /// The amount to send
845    pub amount: PayAmount,
846    /// The optional fee rate of the Bitcoin claim transaction in sat/vB. Defaults to the swapper estimated claim fee.
847    pub fee_rate_sat_per_vbyte: Option<u32>,
848}
849
850/// Returned when calling [crate::sdk::LiquidSdk::prepare_pay_onchain].
851#[derive(Debug, Serialize, Clone)]
852pub struct PreparePayOnchainResponse {
853    pub receiver_amount_sat: u64,
854    pub claim_fees_sat: u64,
855    pub total_fees_sat: u64,
856}
857
858/// An argument when calling [crate::sdk::LiquidSdk::pay_onchain].
859#[derive(Debug, Serialize)]
860pub struct PayOnchainRequest {
861    pub address: String,
862    pub prepare_response: PreparePayOnchainResponse,
863}
864
865/// An argument when calling [crate::sdk::LiquidSdk::prepare_refund].
866#[derive(Debug, Serialize)]
867pub struct PrepareRefundRequest {
868    /// The address where the swap funds are locked up
869    pub swap_address: String,
870    /// The address to refund the swap funds to
871    pub refund_address: String,
872    /// The fee rate in sat/vB for the refund transaction
873    pub fee_rate_sat_per_vbyte: u32,
874}
875
876/// Returned when calling [crate::sdk::LiquidSdk::prepare_refund].
877#[derive(Debug, Serialize)]
878pub struct PrepareRefundResponse {
879    pub tx_vsize: u32,
880    pub tx_fee_sat: u64,
881    /// The txid of the last broadcasted refund tx, if any
882    pub last_refund_tx_id: Option<String>,
883}
884
885/// An argument when calling [crate::sdk::LiquidSdk::refund].
886#[derive(Debug, Serialize)]
887pub struct RefundRequest {
888    /// The address where the swap funds are locked up
889    pub swap_address: String,
890    /// The address to refund the swap funds to
891    pub refund_address: String,
892    /// The fee rate in sat/vB for the refund transaction
893    pub fee_rate_sat_per_vbyte: u32,
894}
895
896/// Returned when calling [crate::sdk::LiquidSdk::refund].
897#[derive(Debug, Serialize)]
898pub struct RefundResponse {
899    pub refund_tx_id: String,
900}
901
902/// An asset balance to denote the balance for each asset.
903#[derive(Clone, Debug, Default, Serialize, Deserialize)]
904pub struct AssetBalance {
905    pub asset_id: String,
906    pub balance_sat: u64,
907    pub name: Option<String>,
908    pub ticker: Option<String>,
909    pub balance: Option<f64>,
910}
911
912#[derive(Debug, Serialize, Deserialize, Default)]
913pub struct BlockchainInfo {
914    pub liquid_tip: u32,
915    pub bitcoin_tip: u32,
916}
917
918#[derive(Copy, Clone)]
919pub(crate) struct ChainTips {
920    pub liquid_tip: u32,
921    pub bitcoin_tip: Option<u32>,
922}
923
924#[derive(Debug, Serialize, Deserialize)]
925pub struct WalletInfo {
926    /// Usable balance. This is the confirmed onchain balance minus `pending_send_sat`.
927    pub balance_sat: u64,
928    /// Amount that is being used for ongoing Send swaps
929    pub pending_send_sat: u64,
930    /// Incoming amount that is pending from ongoing Receive swaps
931    pub pending_receive_sat: u64,
932    /// The wallet's fingerprint. It is used to build the working directory in [Config::get_wallet_dir].
933    pub fingerprint: String,
934    /// The wallet's pubkey. Used to verify signed messages.
935    pub pubkey: String,
936    /// Asset balances of non Liquid Bitcoin assets
937    #[serde(default)]
938    pub asset_balances: Vec<AssetBalance>,
939}
940
941impl WalletInfo {
942    pub(crate) fn validate_sufficient_funds(
943        &self,
944        network: LiquidNetwork,
945        amount_sat: u64,
946        fees_sat: Option<u64>,
947        asset_id: &str,
948    ) -> Result<(), PaymentError> {
949        let fees_sat = fees_sat.unwrap_or(0);
950        if asset_id.eq(&utils::lbtc_asset_id(network).to_string()) {
951            ensure_sdk!(
952                amount_sat + fees_sat <= self.balance_sat,
953                PaymentError::InsufficientFunds
954            );
955        } else {
956            match self
957                .asset_balances
958                .iter()
959                .find(|ab| ab.asset_id.eq(asset_id))
960            {
961                Some(asset_balance) => ensure_sdk!(
962                    amount_sat <= asset_balance.balance_sat && fees_sat <= self.balance_sat,
963                    PaymentError::InsufficientFunds
964                ),
965                None => return Err(PaymentError::InsufficientFunds),
966            }
967        }
968        Ok(())
969    }
970}
971
972/// Returned when calling [crate::sdk::LiquidSdk::get_info].
973#[derive(Debug, Serialize, Deserialize)]
974pub struct GetInfoResponse {
975    /// The wallet information, such as the balance, fingerprint and public key
976    pub wallet_info: WalletInfo,
977    /// The latest synced blockchain information, such as the Liquid/Bitcoin tips
978    #[serde(default)]
979    pub blockchain_info: BlockchainInfo,
980}
981
982/// An argument when calling [crate::sdk::LiquidSdk::sign_message].
983#[derive(Clone, Debug, PartialEq)]
984pub struct SignMessageRequest {
985    pub message: String,
986}
987
988/// Returned when calling [crate::sdk::LiquidSdk::sign_message].
989#[derive(Clone, Debug, PartialEq)]
990pub struct SignMessageResponse {
991    pub signature: String,
992}
993
994/// An argument when calling [crate::sdk::LiquidSdk::check_message].
995#[derive(Clone, Debug, PartialEq)]
996pub struct CheckMessageRequest {
997    /// The message that was signed.
998    pub message: String,
999    /// The public key of the node that signed the message.
1000    pub pubkey: String,
1001    /// The zbase encoded signature to verify.
1002    pub signature: String,
1003}
1004
1005/// Returned when calling [crate::sdk::LiquidSdk::check_message].
1006#[derive(Clone, Debug, PartialEq)]
1007pub struct CheckMessageResponse {
1008    /// Boolean value indicating whether the signature covers the message and
1009    /// was signed by the given pubkey.
1010    pub is_valid: bool,
1011}
1012
1013/// An argument when calling [crate::sdk::LiquidSdk::backup].
1014#[derive(Debug, Serialize)]
1015pub struct BackupRequest {
1016    /// Path to the backup.
1017    ///
1018    /// If not set, it defaults to `backup.sql` for mainnet, `backup-testnet.sql` for testnet,
1019    /// and `backup-regtest.sql` for regtest.
1020    ///
1021    /// The file will be saved in [ConnectRequest]'s `data_dir`.
1022    pub backup_path: Option<String>,
1023}
1024
1025/// An argument when calling [crate::sdk::LiquidSdk::restore].
1026#[derive(Debug, Serialize)]
1027pub struct RestoreRequest {
1028    pub backup_path: Option<String>,
1029}
1030
1031/// An argument when calling [crate::sdk::LiquidSdk::list_payments].
1032#[derive(Default)]
1033pub struct ListPaymentsRequest {
1034    pub filters: Option<Vec<PaymentType>>,
1035    pub states: Option<Vec<PaymentState>>,
1036    /// Epoch time, in seconds
1037    pub from_timestamp: Option<i64>,
1038    /// Epoch time, in seconds
1039    pub to_timestamp: Option<i64>,
1040    pub offset: Option<u32>,
1041    pub limit: Option<u32>,
1042    pub details: Option<ListPaymentDetails>,
1043    pub sort_ascending: Option<bool>,
1044}
1045
1046/// An argument of [ListPaymentsRequest] when calling [crate::sdk::LiquidSdk::list_payments].
1047#[derive(Debug, Serialize)]
1048pub enum ListPaymentDetails {
1049    /// A Liquid payment
1050    Liquid {
1051        /// Optional asset id
1052        asset_id: Option<String>,
1053        /// Optional BIP21 URI or address
1054        destination: Option<String>,
1055    },
1056
1057    /// A Bitcoin payment
1058    Bitcoin {
1059        /// Optional address
1060        address: Option<String>,
1061    },
1062}
1063
1064/// An argument when calling [crate::sdk::LiquidSdk::get_payment].
1065#[derive(Debug, Serialize)]
1066pub enum GetPaymentRequest {
1067    /// The payment hash of a Lightning payment
1068    PaymentHash { payment_hash: String },
1069    /// A swap id or its SHA256 hash
1070    SwapId { swap_id: String },
1071}
1072
1073/// Trait that can be used to react to new blocks from Bitcoin and Liquid chains
1074#[sdk_macros::async_trait]
1075pub(crate) trait BlockListener: MaybeSend + MaybeSync {
1076    async fn on_bitcoin_block(&self, height: u32);
1077    async fn on_liquid_block(&self, height: u32);
1078}
1079
1080// A swap enum variant
1081#[derive(Clone, Debug)]
1082pub enum Swap {
1083    Chain(ChainSwap),
1084    Send(SendSwap),
1085    Receive(ReceiveSwap),
1086}
1087impl Swap {
1088    pub(crate) fn id(&self) -> String {
1089        match &self {
1090            Swap::Chain(ChainSwap { id, .. })
1091            | Swap::Send(SendSwap { id, .. })
1092            | Swap::Receive(ReceiveSwap { id, .. }) => id.clone(),
1093        }
1094    }
1095
1096    pub(crate) fn version(&self) -> u64 {
1097        match self {
1098            Swap::Chain(ChainSwap { metadata, .. })
1099            | Swap::Send(SendSwap { metadata, .. })
1100            | Swap::Receive(ReceiveSwap { metadata, .. }) => metadata.version,
1101        }
1102    }
1103
1104    pub(crate) fn set_version(&mut self, version: u64) {
1105        match self {
1106            Swap::Chain(chain_swap) => {
1107                chain_swap.metadata.version = version;
1108            }
1109            Swap::Send(send_swap) => {
1110                send_swap.metadata.version = version;
1111            }
1112            Swap::Receive(receive_swap) => {
1113                receive_swap.metadata.version = version;
1114            }
1115        }
1116    }
1117
1118    pub(crate) fn last_updated_at(&self) -> u32 {
1119        match self {
1120            Swap::Chain(ChainSwap { metadata, .. })
1121            | Swap::Send(SendSwap { metadata, .. })
1122            | Swap::Receive(ReceiveSwap { metadata, .. }) => metadata.last_updated_at,
1123        }
1124    }
1125}
1126impl From<ChainSwap> for Swap {
1127    fn from(swap: ChainSwap) -> Self {
1128        Self::Chain(swap)
1129    }
1130}
1131impl From<SendSwap> for Swap {
1132    fn from(swap: SendSwap) -> Self {
1133        Self::Send(swap)
1134    }
1135}
1136impl From<ReceiveSwap> for Swap {
1137    fn from(swap: ReceiveSwap) -> Self {
1138        Self::Receive(swap)
1139    }
1140}
1141
1142#[derive(Clone, Debug)]
1143pub(crate) enum SwapScriptV2 {
1144    Bitcoin(BtcSwapScript),
1145    Liquid(LBtcSwapScript),
1146}
1147impl SwapScriptV2 {
1148    pub(crate) fn as_bitcoin_script(&self) -> Result<BtcSwapScript> {
1149        match self {
1150            SwapScriptV2::Bitcoin(script) => Ok(script.clone()),
1151            _ => Err(anyhow!("Invalid chain")),
1152        }
1153    }
1154
1155    pub(crate) fn as_liquid_script(&self) -> Result<LBtcSwapScript> {
1156        match self {
1157            SwapScriptV2::Liquid(script) => Ok(script.clone()),
1158            _ => Err(anyhow!("Invalid chain")),
1159        }
1160    }
1161}
1162
1163#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
1164pub enum Direction {
1165    Incoming = 0,
1166    Outgoing = 1,
1167}
1168impl ToSql for Direction {
1169    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1170        Ok(rusqlite::types::ToSqlOutput::from(*self as i8))
1171    }
1172}
1173impl FromSql for Direction {
1174    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
1175        match value {
1176            ValueRef::Integer(i) => match i as u8 {
1177                0 => Ok(Direction::Incoming),
1178                1 => Ok(Direction::Outgoing),
1179                _ => Err(FromSqlError::OutOfRange(i)),
1180            },
1181            _ => Err(FromSqlError::InvalidType),
1182        }
1183    }
1184}
1185
1186#[derive(Clone, Debug, Default)]
1187pub(crate) struct SwapMetadata {
1188    /// Version used for optimistic concurrency control within local db
1189    pub(crate) version: u64,
1190    pub(crate) last_updated_at: u32,
1191    pub(crate) is_local: bool,
1192}
1193
1194/// A chain swap
1195///
1196/// See <https://docs.boltz.exchange/v/api/lifecycle#chain-swaps>
1197#[derive(Clone, Debug, Derivative)]
1198#[derivative(PartialEq)]
1199pub struct ChainSwap {
1200    pub(crate) id: String,
1201    pub(crate) direction: Direction,
1202    /// Always set for Outgoing Chain Swaps. It's the destination Bitcoin address
1203    /// Only set for Incoming Chain Swaps when a claim is broadcasted. It's a local Liquid wallet address
1204    pub(crate) claim_address: Option<String>,
1205    pub(crate) lockup_address: String,
1206    /// The Liquid refund address is only set for Outgoing Chain Swaps
1207    pub(crate) refund_address: Option<String>,
1208    pub(crate) timeout_block_height: u32,
1209    pub(crate) preimage: String,
1210    pub(crate) description: Option<String>,
1211    /// Payer amount defined at swap creation
1212    pub(crate) payer_amount_sat: u64,
1213    /// The actual payer amount as seen on the user lockup tx. Might differ from `payer_amount_sat`
1214    /// in the case of an over/underpayment
1215    pub(crate) actual_payer_amount_sat: Option<u64>,
1216    /// Receiver amount defined at swap creation
1217    pub(crate) receiver_amount_sat: u64,
1218    /// The final receiver amount, in case of an amountless swap for which fees have been accepted
1219    pub(crate) accepted_receiver_amount_sat: Option<u64>,
1220    pub(crate) claim_fees_sat: u64,
1221    /// The [ChainPair] chosen on swap creation
1222    pub(crate) pair_fees_json: String,
1223    pub(crate) accept_zero_conf: bool,
1224    /// JSON representation of [crate::persist::chain::InternalCreateChainResponse]
1225    pub(crate) create_response_json: String,
1226    /// Persisted only when the server lockup tx is successfully broadcast
1227    pub(crate) server_lockup_tx_id: Option<String>,
1228    /// Persisted only when the user lockup tx is successfully broadcast
1229    pub(crate) user_lockup_tx_id: Option<String>,
1230    /// Persisted as soon as a claim tx is broadcast
1231    pub(crate) claim_tx_id: Option<String>,
1232    /// Persisted as soon as a refund tx is broadcast
1233    pub(crate) refund_tx_id: Option<String>,
1234    pub(crate) created_at: u32,
1235    pub(crate) state: PaymentState,
1236    pub(crate) claim_private_key: String,
1237    pub(crate) refund_private_key: String,
1238    pub(crate) auto_accepted_fees: bool,
1239    /// Swap metadata that is only valid when reading one from the local database
1240    #[derivative(PartialEq = "ignore")]
1241    pub(crate) metadata: SwapMetadata,
1242}
1243impl ChainSwap {
1244    pub(crate) fn get_claim_keypair(&self) -> SdkResult<Keypair> {
1245        utils::decode_keypair(&self.claim_private_key)
1246    }
1247
1248    pub(crate) fn get_refund_keypair(&self) -> SdkResult<Keypair> {
1249        utils::decode_keypair(&self.refund_private_key)
1250    }
1251
1252    pub(crate) fn get_boltz_create_response(&self) -> Result<CreateChainResponse> {
1253        let internal_create_response: crate::persist::chain::InternalCreateChainResponse =
1254            serde_json::from_str(&self.create_response_json).map_err(|e| {
1255                anyhow!("Failed to deserialize InternalCreateSubmarineResponse: {e:?}")
1256            })?;
1257
1258        Ok(CreateChainResponse {
1259            id: self.id.clone(),
1260            claim_details: internal_create_response.claim_details,
1261            lockup_details: internal_create_response.lockup_details,
1262        })
1263    }
1264
1265    pub(crate) fn get_boltz_pair(&self) -> Result<ChainPair> {
1266        let pair: ChainPair = serde_json::from_str(&self.pair_fees_json)
1267            .map_err(|e| anyhow!("Failed to deserialize ChainPair: {e:?}"))?;
1268
1269        Ok(pair)
1270    }
1271
1272    pub(crate) fn get_claim_swap_script(&self) -> SdkResult<SwapScriptV2> {
1273        let chain_swap_details = self.get_boltz_create_response()?.claim_details;
1274        let our_pubkey = self.get_claim_keypair()?.public_key();
1275        let swap_script = match self.direction {
1276            Direction::Incoming => SwapScriptV2::Liquid(LBtcSwapScript::chain_from_swap_resp(
1277                Side::Claim,
1278                chain_swap_details,
1279                our_pubkey.into(),
1280            )?),
1281            Direction::Outgoing => SwapScriptV2::Bitcoin(BtcSwapScript::chain_from_swap_resp(
1282                Side::Claim,
1283                chain_swap_details,
1284                our_pubkey.into(),
1285            )?),
1286        };
1287        Ok(swap_script)
1288    }
1289
1290    pub(crate) fn get_lockup_swap_script(&self) -> SdkResult<SwapScriptV2> {
1291        let chain_swap_details = self.get_boltz_create_response()?.lockup_details;
1292        let our_pubkey = self.get_refund_keypair()?.public_key();
1293        let swap_script = match self.direction {
1294            Direction::Incoming => SwapScriptV2::Bitcoin(BtcSwapScript::chain_from_swap_resp(
1295                Side::Lockup,
1296                chain_swap_details,
1297                our_pubkey.into(),
1298            )?),
1299            Direction::Outgoing => SwapScriptV2::Liquid(LBtcSwapScript::chain_from_swap_resp(
1300                Side::Lockup,
1301                chain_swap_details,
1302                our_pubkey.into(),
1303            )?),
1304        };
1305        Ok(swap_script)
1306    }
1307
1308    /// Returns the lockup script pubkey for Receive Chain Swaps
1309    pub(crate) fn get_receive_lockup_swap_script_pubkey(
1310        &self,
1311        network: LiquidNetwork,
1312    ) -> SdkResult<ScriptBuf> {
1313        let swap_script = self.get_lockup_swap_script()?.as_bitcoin_script()?;
1314        let script_pubkey = swap_script
1315            .to_address(network.as_bitcoin_chain())
1316            .map_err(|e| SdkError::generic(format!("Error getting script address: {e:?}")))?
1317            .script_pubkey();
1318        Ok(script_pubkey)
1319    }
1320
1321    pub(crate) fn to_refundable(&self, amount_sat: u64) -> RefundableSwap {
1322        RefundableSwap {
1323            swap_address: self.lockup_address.clone(),
1324            timestamp: self.created_at,
1325            amount_sat,
1326            last_refund_tx_id: self.refund_tx_id.clone(),
1327        }
1328    }
1329
1330    pub(crate) fn from_boltz_struct_to_json(
1331        create_response: &CreateChainResponse,
1332        expected_swap_id: &str,
1333    ) -> Result<String, PaymentError> {
1334        let internal_create_response =
1335            crate::persist::chain::InternalCreateChainResponse::try_convert_from_boltz(
1336                create_response,
1337                expected_swap_id,
1338            )?;
1339
1340        let create_response_json =
1341            serde_json::to_string(&internal_create_response).map_err(|e| {
1342                PaymentError::Generic {
1343                    err: format!("Failed to serialize InternalCreateChainResponse: {e:?}"),
1344                }
1345            })?;
1346
1347        Ok(create_response_json)
1348    }
1349
1350    pub(crate) fn is_waiting_fee_acceptance(&self) -> bool {
1351        self.payer_amount_sat == 0 && self.accepted_receiver_amount_sat.is_none()
1352    }
1353}
1354
1355#[derive(Clone, Debug, Default)]
1356pub(crate) struct ChainSwapUpdate {
1357    pub(crate) swap_id: String,
1358    pub(crate) to_state: PaymentState,
1359    pub(crate) server_lockup_tx_id: Option<String>,
1360    pub(crate) user_lockup_tx_id: Option<String>,
1361    pub(crate) claim_address: Option<String>,
1362    pub(crate) claim_tx_id: Option<String>,
1363    pub(crate) refund_tx_id: Option<String>,
1364}
1365
1366/// A submarine swap, used for Send
1367#[derive(Clone, Debug, Derivative)]
1368#[derivative(PartialEq)]
1369pub struct SendSwap {
1370    pub(crate) id: String,
1371    /// Bolt11 or Bolt12 invoice. This is determined by whether `bolt12_offer` is set or not.
1372    pub(crate) invoice: String,
1373    /// The bolt12 offer, if this swap sends to a Bolt12 offer
1374    pub(crate) bolt12_offer: Option<String>,
1375    pub(crate) payment_hash: Option<String>,
1376    pub(crate) destination_pubkey: Option<String>,
1377    pub(crate) description: Option<String>,
1378    pub(crate) preimage: Option<String>,
1379    pub(crate) payer_amount_sat: u64,
1380    pub(crate) receiver_amount_sat: u64,
1381    /// The [SubmarinePair] chosen on swap creation
1382    pub(crate) pair_fees_json: String,
1383    /// JSON representation of [crate::persist::send::InternalCreateSubmarineResponse]
1384    pub(crate) create_response_json: String,
1385    /// Persisted only when the lockup tx is successfully broadcast
1386    pub(crate) lockup_tx_id: Option<String>,
1387    /// Persisted only when a refund tx is needed
1388    pub(crate) refund_address: Option<String>,
1389    /// Persisted after the refund tx is broadcast
1390    pub(crate) refund_tx_id: Option<String>,
1391    pub(crate) created_at: u32,
1392    pub(crate) timeout_block_height: u64,
1393    pub(crate) state: PaymentState,
1394    pub(crate) refund_private_key: String,
1395    /// Swap metadata that is only valid when reading one from the local database
1396    #[derivative(PartialEq = "ignore")]
1397    pub(crate) metadata: SwapMetadata,
1398}
1399impl SendSwap {
1400    pub(crate) fn get_refund_keypair(&self) -> Result<Keypair, SdkError> {
1401        utils::decode_keypair(&self.refund_private_key)
1402    }
1403
1404    pub(crate) fn get_boltz_create_response(&self) -> Result<CreateSubmarineResponse> {
1405        let internal_create_response: crate::persist::send::InternalCreateSubmarineResponse =
1406            serde_json::from_str(&self.create_response_json).map_err(|e| {
1407                anyhow!("Failed to deserialize InternalCreateSubmarineResponse: {e:?}")
1408            })?;
1409
1410        let res = CreateSubmarineResponse {
1411            id: self.id.clone(),
1412            accept_zero_conf: internal_create_response.accept_zero_conf,
1413            address: internal_create_response.address.clone(),
1414            bip21: internal_create_response.bip21.clone(),
1415            claim_public_key: crate::utils::json_to_pubkey(
1416                &internal_create_response.claim_public_key,
1417            )?,
1418            expected_amount: internal_create_response.expected_amount,
1419            referral_id: internal_create_response.referral_id,
1420            swap_tree: internal_create_response.swap_tree.clone().into(),
1421            timeout_block_height: internal_create_response.timeout_block_height,
1422            blinding_key: internal_create_response.blinding_key.clone(),
1423        };
1424        Ok(res)
1425    }
1426
1427    pub(crate) fn get_swap_script(&self) -> Result<LBtcSwapScript, SdkError> {
1428        LBtcSwapScript::submarine_from_swap_resp(
1429            &self.get_boltz_create_response()?,
1430            self.get_refund_keypair()?.public_key().into(),
1431        )
1432        .map_err(|e| {
1433            SdkError::generic(format!(
1434                "Failed to create swap script for Send Swap {}: {e:?}",
1435                self.id
1436            ))
1437        })
1438    }
1439
1440    pub(crate) fn from_boltz_struct_to_json(
1441        create_response: &CreateSubmarineResponse,
1442        expected_swap_id: &str,
1443    ) -> Result<String, PaymentError> {
1444        let internal_create_response =
1445            crate::persist::send::InternalCreateSubmarineResponse::try_convert_from_boltz(
1446                create_response,
1447                expected_swap_id,
1448            )?;
1449
1450        let create_response_json =
1451            serde_json::to_string(&internal_create_response).map_err(|e| {
1452                PaymentError::Generic {
1453                    err: format!("Failed to serialize InternalCreateSubmarineResponse: {e:?}"),
1454                }
1455            })?;
1456
1457        Ok(create_response_json)
1458    }
1459}
1460
1461/// A reverse swap, used for Receive
1462#[derive(Clone, Debug, Derivative)]
1463#[derivative(PartialEq)]
1464pub struct ReceiveSwap {
1465    pub(crate) id: String,
1466    pub(crate) preimage: String,
1467    /// JSON representation of [crate::persist::receive::InternalCreateReverseResponse]
1468    pub(crate) create_response_json: String,
1469    pub(crate) claim_private_key: String,
1470    pub(crate) invoice: String,
1471    /// The bolt12 offer, if used to create the swap
1472    pub(crate) bolt12_offer: Option<String>,
1473    pub(crate) payment_hash: Option<String>,
1474    pub(crate) destination_pubkey: Option<String>,
1475    pub(crate) description: Option<String>,
1476    pub(crate) payer_note: Option<String>,
1477    /// The amount of the invoice
1478    pub(crate) payer_amount_sat: u64,
1479    pub(crate) receiver_amount_sat: u64,
1480    /// The [ReversePair] chosen on swap creation
1481    pub(crate) pair_fees_json: String,
1482    pub(crate) claim_fees_sat: u64,
1483    /// Persisted only when a claim tx is needed
1484    pub(crate) claim_address: Option<String>,
1485    /// Persisted after the claim tx is broadcast
1486    pub(crate) claim_tx_id: Option<String>,
1487    /// The transaction id of the swapper's tx broadcast
1488    pub(crate) lockup_tx_id: Option<String>,
1489    /// The address reserved for a magic routing hint payment
1490    pub(crate) mrh_address: String,
1491    /// Persisted only if a transaction is sent to the `mrh_address`
1492    pub(crate) mrh_tx_id: Option<String>,
1493    /// Until the lockup tx is seen in the mempool, it contains the swap creation time.
1494    /// Afterwards, it shows the lockup tx creation time.
1495    pub(crate) created_at: u32,
1496    pub(crate) timeout_block_height: u32,
1497    pub(crate) state: PaymentState,
1498    /// Swap metadata that is only valid when reading one from the local database
1499    #[derivative(PartialEq = "ignore")]
1500    pub(crate) metadata: SwapMetadata,
1501}
1502impl ReceiveSwap {
1503    pub(crate) fn get_claim_keypair(&self) -> Result<Keypair, PaymentError> {
1504        utils::decode_keypair(&self.claim_private_key).map_err(Into::into)
1505    }
1506
1507    pub(crate) fn claim_script(&self) -> Result<elements::Script> {
1508        Ok(self
1509            .get_swap_script()?
1510            .funding_addrs
1511            .ok_or(anyhow!("No funding address found"))?
1512            .script_pubkey())
1513    }
1514
1515    pub(crate) fn get_boltz_create_response(&self) -> Result<CreateReverseResponse, PaymentError> {
1516        let internal_create_response: crate::persist::receive::InternalCreateReverseResponse =
1517            serde_json::from_str(&self.create_response_json).map_err(|e| {
1518                PaymentError::Generic {
1519                    err: format!("Failed to deserialize InternalCreateReverseResponse: {e:?}"),
1520                }
1521            })?;
1522
1523        let res = CreateReverseResponse {
1524            id: self.id.clone(),
1525            invoice: Some(self.invoice.clone()),
1526            swap_tree: internal_create_response.swap_tree.clone().into(),
1527            lockup_address: internal_create_response.lockup_address.clone(),
1528            refund_public_key: crate::utils::json_to_pubkey(
1529                &internal_create_response.refund_public_key,
1530            )?,
1531            timeout_block_height: internal_create_response.timeout_block_height,
1532            onchain_amount: internal_create_response.onchain_amount,
1533            blinding_key: internal_create_response.blinding_key.clone(),
1534        };
1535        Ok(res)
1536    }
1537
1538    pub(crate) fn get_swap_script(&self) -> Result<LBtcSwapScript, PaymentError> {
1539        let keypair = self.get_claim_keypair()?;
1540        let create_response =
1541            self.get_boltz_create_response()
1542                .map_err(|e| PaymentError::Generic {
1543                    err: format!(
1544                        "Failed to create swap script for Receive Swap {}: {e:?}",
1545                        self.id
1546                    ),
1547                })?;
1548        LBtcSwapScript::reverse_from_swap_resp(&create_response, keypair.public_key().into())
1549            .map_err(|e| PaymentError::Generic {
1550                err: format!(
1551                    "Failed to create swap script for Receive Swap {}: {e:?}",
1552                    self.id
1553                ),
1554            })
1555    }
1556
1557    pub(crate) fn from_boltz_struct_to_json(
1558        create_response: &CreateReverseResponse,
1559        expected_swap_id: &str,
1560        expected_invoice: Option<&str>,
1561    ) -> Result<String, PaymentError> {
1562        let internal_create_response =
1563            crate::persist::receive::InternalCreateReverseResponse::try_convert_from_boltz(
1564                create_response,
1565                expected_swap_id,
1566                expected_invoice,
1567            )?;
1568
1569        let create_response_json =
1570            serde_json::to_string(&internal_create_response).map_err(|e| {
1571                PaymentError::Generic {
1572                    err: format!("Failed to serialize InternalCreateReverseResponse: {e:?}"),
1573                }
1574            })?;
1575
1576        Ok(create_response_json)
1577    }
1578}
1579
1580/// Returned when calling [crate::sdk::LiquidSdk::list_refundables].
1581#[derive(Clone, Debug, PartialEq, Serialize)]
1582pub struct RefundableSwap {
1583    pub swap_address: String,
1584    pub timestamp: u32,
1585    /// Amount that is refundable, from all UTXOs
1586    pub amount_sat: u64,
1587    /// The txid of the last broadcasted refund tx, if any
1588    pub last_refund_tx_id: Option<String>,
1589}
1590
1591/// A BOLT12 offer
1592#[derive(Clone, Debug, Derivative)]
1593#[derivative(PartialEq)]
1594pub(crate) struct Bolt12Offer {
1595    /// The BOLT12 offer string
1596    pub(crate) id: String,
1597    /// The description of the offer
1598    pub(crate) description: String,
1599    /// The private key used to create the offer
1600    pub(crate) private_key: String,
1601    /// The optional webhook URL where the offer invoice request will be sent
1602    pub(crate) webhook_url: Option<String>,
1603    /// The creation time of the offer
1604    pub(crate) created_at: u32,
1605}
1606impl Bolt12Offer {
1607    pub(crate) fn get_keypair(&self) -> Result<Keypair, SdkError> {
1608        utils::decode_keypair(&self.private_key)
1609    }
1610}
1611impl TryFrom<Bolt12Offer> for Offer {
1612    type Error = SdkError;
1613
1614    fn try_from(val: Bolt12Offer) -> Result<Self, Self::Error> {
1615        Offer::from_str(&val.id)
1616            .map_err(|e| SdkError::generic(format!("Failed to parse BOLT12 offer: {e:?}")))
1617    }
1618}
1619
1620/// The payment state of an individual payment.
1621#[derive(Clone, Copy, Debug, Default, EnumString, Eq, PartialEq, Serialize, Hash)]
1622#[strum(serialize_all = "lowercase")]
1623pub enum PaymentState {
1624    #[default]
1625    Created = 0,
1626
1627    /// ## Receive Swaps
1628    ///
1629    /// Covers the cases when
1630    /// - the lockup tx is seen in the mempool or
1631    /// - our claim tx is broadcast
1632    ///
1633    /// When the claim tx is broadcast, `claim_tx_id` is set in the swap.
1634    ///
1635    /// ## Send Swaps
1636    ///
1637    /// This is the status when our lockup tx was broadcast
1638    ///
1639    /// ## Chain Swaps
1640    ///
1641    /// This is the status when the user lockup tx was broadcast
1642    ///
1643    /// ## No swap data available
1644    ///
1645    /// If no associated swap is found, this indicates the underlying tx is not confirmed yet.
1646    Pending = 1,
1647
1648    /// ## Receive Swaps
1649    ///
1650    /// Covers the case when the claim tx is confirmed.
1651    ///
1652    /// ## Send and Chain Swaps
1653    ///
1654    /// This is the status when the claim tx is broadcast and we see it in the mempool.
1655    ///
1656    /// ## No swap data available
1657    ///
1658    /// If no associated swap is found, this indicates the underlying tx is confirmed.
1659    Complete = 2,
1660
1661    /// ## Receive Swaps
1662    ///
1663    /// This is the status when the swap failed for any reason and the Receive could not complete.
1664    ///
1665    /// ## Send and Chain Swaps
1666    ///
1667    /// This is the status when a swap refund was initiated and the refund tx is confirmed.
1668    Failed = 3,
1669
1670    /// ## Send and Outgoing Chain Swaps
1671    ///
1672    /// This covers the case when the swap state is still Created and the swap fails to reach the
1673    /// Pending state in time. The TimedOut state indicates the lockup tx should never be broadcast.
1674    TimedOut = 4,
1675
1676    /// ## Incoming Chain Swaps
1677    ///
1678    /// This covers the case when the swap failed for any reason and there is a user lockup tx.
1679    /// The swap in this case has to be manually refunded with a provided Bitcoin address
1680    Refundable = 5,
1681
1682    /// ## Send and Chain Swaps
1683    ///
1684    /// This is the status when a refund was initiated and/or our refund tx was broadcast
1685    ///
1686    /// When the refund tx is broadcast, `refund_tx_id` is set in the swap.
1687    RefundPending = 6,
1688
1689    /// ## Chain Swaps
1690    ///
1691    /// This is the state when the user needs to accept new fees before the payment can proceed.
1692    ///
1693    /// Use [LiquidSdk::fetch_payment_proposed_fees](crate::sdk::LiquidSdk::fetch_payment_proposed_fees)
1694    /// to find out the current fees and
1695    /// [LiquidSdk::accept_payment_proposed_fees](crate::sdk::LiquidSdk::accept_payment_proposed_fees)
1696    /// to accept them, allowing the payment to proceed.
1697    ///
1698    /// Otherwise, this payment can be immediately refunded using
1699    /// [prepare_refund](crate::sdk::LiquidSdk::prepare_refund)/[refund](crate::sdk::LiquidSdk::refund).
1700    WaitingFeeAcceptance = 7,
1701}
1702
1703impl ToSql for PaymentState {
1704    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1705        Ok(rusqlite::types::ToSqlOutput::from(*self as i8))
1706    }
1707}
1708impl FromSql for PaymentState {
1709    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
1710        match value {
1711            ValueRef::Integer(i) => match i as u8 {
1712                0 => Ok(PaymentState::Created),
1713                1 => Ok(PaymentState::Pending),
1714                2 => Ok(PaymentState::Complete),
1715                3 => Ok(PaymentState::Failed),
1716                4 => Ok(PaymentState::TimedOut),
1717                5 => Ok(PaymentState::Refundable),
1718                6 => Ok(PaymentState::RefundPending),
1719                7 => Ok(PaymentState::WaitingFeeAcceptance),
1720                _ => Err(FromSqlError::OutOfRange(i)),
1721            },
1722            _ => Err(FromSqlError::InvalidType),
1723        }
1724    }
1725}
1726
1727impl PaymentState {
1728    pub(crate) fn is_refundable(&self) -> bool {
1729        matches!(
1730            self,
1731            PaymentState::Refundable
1732                | PaymentState::RefundPending
1733                | PaymentState::WaitingFeeAcceptance
1734        )
1735    }
1736}
1737
1738#[derive(Debug, Copy, Clone, Eq, EnumString, Display, Hash, PartialEq, Serialize)]
1739#[strum(serialize_all = "lowercase")]
1740pub enum PaymentType {
1741    Receive = 0,
1742    Send = 1,
1743}
1744impl From<Direction> for PaymentType {
1745    fn from(value: Direction) -> Self {
1746        match value {
1747            Direction::Incoming => Self::Receive,
1748            Direction::Outgoing => Self::Send,
1749        }
1750    }
1751}
1752impl ToSql for PaymentType {
1753    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1754        Ok(rusqlite::types::ToSqlOutput::from(*self as i8))
1755    }
1756}
1757impl FromSql for PaymentType {
1758    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
1759        match value {
1760            ValueRef::Integer(i) => match i as u8 {
1761                0 => Ok(PaymentType::Receive),
1762                1 => Ok(PaymentType::Send),
1763                _ => Err(FromSqlError::OutOfRange(i)),
1764            },
1765            _ => Err(FromSqlError::InvalidType),
1766        }
1767    }
1768}
1769
1770#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
1771pub enum PaymentStatus {
1772    Pending = 0,
1773    Complete = 1,
1774}
1775impl ToSql for PaymentStatus {
1776    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1777        Ok(rusqlite::types::ToSqlOutput::from(*self as i8))
1778    }
1779}
1780impl FromSql for PaymentStatus {
1781    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
1782        match value {
1783            ValueRef::Integer(i) => match i as u8 {
1784                0 => Ok(PaymentStatus::Pending),
1785                1 => Ok(PaymentStatus::Complete),
1786                _ => Err(FromSqlError::OutOfRange(i)),
1787            },
1788            _ => Err(FromSqlError::InvalidType),
1789        }
1790    }
1791}
1792
1793#[derive(Debug, Clone, Serialize)]
1794pub struct PaymentTxData {
1795    /// The tx ID of the transaction
1796    pub tx_id: String,
1797
1798    /// The point in time when the underlying tx was included in a block.
1799    pub timestamp: Option<u32>,
1800
1801    /// The onchain fees of this tx
1802    pub fees_sat: u64,
1803
1804    /// Onchain tx status
1805    pub is_confirmed: bool,
1806
1807    /// Data to use in the `blinded` param when unblinding the transaction in an explorer.
1808    /// See: <https://docs.liquid.net/docs/unblinding-transactions>
1809    pub unblinding_data: Option<String>,
1810}
1811
1812#[derive(Debug, Clone, Serialize)]
1813pub enum PaymentSwapType {
1814    Receive,
1815    Send,
1816    Chain,
1817}
1818
1819#[derive(Debug, Clone, Serialize)]
1820pub struct PaymentSwapData {
1821    pub swap_id: String,
1822
1823    pub swap_type: PaymentSwapType,
1824
1825    /// Swap creation timestamp
1826    pub created_at: u32,
1827
1828    /// The height of the block at which the swap will no longer be valid
1829    pub expiration_blockheight: u32,
1830
1831    pub preimage: Option<String>,
1832    pub invoice: Option<String>,
1833    pub bolt12_offer: Option<String>,
1834    pub payment_hash: Option<String>,
1835    pub destination_pubkey: Option<String>,
1836    pub description: String,
1837    pub payer_note: Option<String>,
1838
1839    /// Amount sent by the swap payer
1840    pub payer_amount_sat: u64,
1841
1842    /// Amount received by the swap receiver
1843    pub receiver_amount_sat: u64,
1844
1845    /// The swapper service fee
1846    pub swapper_fees_sat: u64,
1847
1848    pub refund_tx_id: Option<String>,
1849    pub refund_tx_amount_sat: Option<u64>,
1850
1851    /// Present only for chain swaps.
1852    /// It's the Bitcoin address that receives funds.
1853    pub bitcoin_address: Option<String>,
1854
1855    /// Payment status derived from the swap status
1856    pub status: PaymentState,
1857}
1858
1859/// Represents the payment LNURL info
1860#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
1861pub struct LnUrlInfo {
1862    pub ln_address: Option<String>,
1863    pub lnurl_pay_comment: Option<String>,
1864    pub lnurl_pay_domain: Option<String>,
1865    pub lnurl_pay_metadata: Option<String>,
1866    pub lnurl_pay_success_action: Option<SuccessActionProcessed>,
1867    pub lnurl_pay_unprocessed_success_action: Option<SuccessAction>,
1868    pub lnurl_withdraw_endpoint: Option<String>,
1869}
1870
1871/// Configuration for asset metadata. Each asset metadata item represents an entry in the
1872/// [Liquid Asset Registry](https://docs.liquid.net/docs/blockstream-liquid-asset-registry).
1873/// An example Liquid Asset in the registry would be [Tether USD](https://assets.blockstream.info/ce091c998b83c78bb71a632313ba3760f1763d9cfcffae02258ffa9865a37bd2.json>).
1874#[derive(Debug, Clone, Serialize)]
1875pub struct AssetMetadata {
1876    /// The asset id of the registered asset
1877    pub asset_id: String,
1878    /// The name of the asset
1879    pub name: String,
1880    /// The ticker of the asset
1881    pub ticker: String,
1882    /// The precision used to display the asset amount.
1883    /// For example, precision of 2 shifts the decimal 2 places left from the satoshi amount.
1884    pub precision: u8,
1885    /// The optional ID of the fiat currency used to represent the asset
1886    pub fiat_id: Option<String>,
1887}
1888
1889impl AssetMetadata {
1890    pub fn amount_to_sat(&self, amount: f64) -> u64 {
1891        (amount * (10_u64.pow(self.precision.into()) as f64)) as u64
1892    }
1893
1894    pub fn amount_from_sat(&self, amount_sat: u64) -> f64 {
1895        amount_sat as f64 / (10_u64.pow(self.precision.into()) as f64)
1896    }
1897}
1898
1899/// Represents the Liquid payment asset info. The asset info is derived from
1900/// the available [AssetMetadata] that is set in the [Config].
1901#[derive(Clone, Debug, PartialEq, Serialize)]
1902pub struct AssetInfo {
1903    /// The name of the asset
1904    pub name: String,
1905    /// The ticker of the asset
1906    pub ticker: String,
1907    /// The amount calculated from the satoshi amount of the transaction, having its
1908    /// decimal shifted to the left by the [precision](AssetMetadata::precision)
1909    pub amount: f64,
1910    /// The optional fees when paid using the asset, having its
1911    /// decimal shifted to the left by the [precision](AssetMetadata::precision)
1912    pub fees: Option<f64>,
1913}
1914
1915/// The specific details of a payment, depending on its type
1916#[derive(Debug, Clone, PartialEq, Serialize)]
1917#[allow(clippy::large_enum_variant)]
1918pub enum PaymentDetails {
1919    /// Swapping to or from Lightning
1920    Lightning {
1921        swap_id: String,
1922
1923        /// Represents the invoice description
1924        description: String,
1925
1926        /// The height of the block at which the swap will no longer be valid
1927        liquid_expiration_blockheight: u32,
1928
1929        /// The preimage of the paid invoice (proof of payment).
1930        preimage: Option<String>,
1931
1932        /// Represents the Bolt11/Bolt12 invoice associated with a payment
1933        /// In the case of a Send payment, this is the invoice paid by the swapper
1934        /// In the case of a Receive payment, this is the invoice paid by the user
1935        invoice: Option<String>,
1936
1937        bolt12_offer: Option<String>,
1938
1939        /// The payment hash of the invoice
1940        payment_hash: Option<String>,
1941
1942        /// The invoice destination/payee pubkey
1943        destination_pubkey: Option<String>,
1944
1945        /// The payment LNURL info
1946        lnurl_info: Option<LnUrlInfo>,
1947
1948        /// The BIP353 address used to resolve this payment
1949        bip353_address: Option<String>,
1950
1951        /// The payer note
1952        payer_note: Option<String>,
1953
1954        /// For a Receive payment, this is the claim tx id in case it has already been broadcast
1955        claim_tx_id: Option<String>,
1956
1957        /// For a Send swap which was refunded, this is the refund tx id
1958        refund_tx_id: Option<String>,
1959
1960        /// For a Send swap which was refunded, this is the refund amount
1961        refund_tx_amount_sat: Option<u64>,
1962    },
1963    /// Direct onchain payment to a Liquid address
1964    Liquid {
1965        /// Represents either a Liquid BIP21 URI or pure address
1966        destination: String,
1967
1968        /// Represents the BIP21 `message` field
1969        description: String,
1970
1971        /// The asset id
1972        asset_id: String,
1973
1974        /// The asset info derived from the [AssetMetadata]
1975        asset_info: Option<AssetInfo>,
1976
1977        /// The payment LNURL info
1978        lnurl_info: Option<LnUrlInfo>,
1979
1980        /// The BIP353 address used to resolve this payment
1981        bip353_address: Option<String>,
1982
1983        /// The payer note
1984        payer_note: Option<String>,
1985    },
1986    /// Swapping to or from the Bitcoin chain
1987    Bitcoin {
1988        swap_id: String,
1989
1990        /// The Bitcoin address that receives funds.
1991        bitcoin_address: String,
1992
1993        /// Represents the invoice description
1994        description: String,
1995
1996        /// For an amountless receive swap, this indicates if fees were automatically accepted.
1997        /// Fees are auto accepted when the swapper proposes fees that are within the initial
1998        /// estimate, plus the `onchain_fee_rate_leeway_sat_per_vbyte` set in the [Config], if any.
1999        auto_accepted_fees: bool,
2000
2001        /// The height of the Liquid block at which the swap will no longer be valid
2002        /// It should always be populated in case of an outgoing chain swap
2003        liquid_expiration_blockheight: Option<u32>,
2004
2005        /// The height of the Bitcoin block at which the swap will no longer be valid
2006        /// It should always be populated in case of an incoming chain swap
2007        bitcoin_expiration_blockheight: Option<u32>,
2008
2009        /// The lockup tx id that initiates the swap
2010        lockup_tx_id: Option<String>,
2011
2012        /// The claim tx id that claims the server lockup tx
2013        claim_tx_id: Option<String>,
2014
2015        /// For a Send swap which was refunded, this is the refund tx id
2016        refund_tx_id: Option<String>,
2017
2018        /// For a Send swap which was refunded, this is the refund amount
2019        refund_tx_amount_sat: Option<u64>,
2020    },
2021}
2022
2023impl PaymentDetails {
2024    pub(crate) fn get_swap_id(&self) -> Option<String> {
2025        match self {
2026            Self::Lightning { swap_id, .. } | Self::Bitcoin { swap_id, .. } => {
2027                Some(swap_id.clone())
2028            }
2029            Self::Liquid { .. } => None,
2030        }
2031    }
2032
2033    pub(crate) fn get_refund_tx_amount_sat(&self) -> Option<u64> {
2034        match self {
2035            Self::Lightning {
2036                refund_tx_amount_sat,
2037                ..
2038            }
2039            | Self::Bitcoin {
2040                refund_tx_amount_sat,
2041                ..
2042            } => *refund_tx_amount_sat,
2043            Self::Liquid { .. } => None,
2044        }
2045    }
2046
2047    pub(crate) fn get_description(&self) -> Option<String> {
2048        match self {
2049            Self::Lightning { description, .. }
2050            | Self::Bitcoin { description, .. }
2051            | Self::Liquid { description, .. } => Some(description.clone()),
2052        }
2053    }
2054
2055    pub(crate) fn is_lbtc_asset_id(&self, network: LiquidNetwork) -> bool {
2056        match self {
2057            Self::Liquid { asset_id, .. } => {
2058                asset_id.eq(&utils::lbtc_asset_id(network).to_string())
2059            }
2060            _ => true,
2061        }
2062    }
2063}
2064
2065/// Represents an SDK payment.
2066///
2067/// By default, this is an onchain tx. It may represent a swap, if swap metadata is available.
2068#[derive(Debug, Clone, PartialEq, Serialize)]
2069pub struct Payment {
2070    /// The destination associated with the payment, if it was created via our SDK.
2071    /// Can be either a Liquid/Bitcoin address, a Liquid BIP21 URI or an invoice
2072    pub destination: Option<String>,
2073
2074    pub tx_id: Option<String>,
2075
2076    /// Data to use in the `blinded` param when unblinding the transaction in an explorer.
2077    /// See: <https://docs.liquid.net/docs/unblinding-transactions>
2078    pub unblinding_data: Option<String>,
2079
2080    /// Composite timestamp that can be used for sorting or displaying the payment.
2081    ///
2082    /// If this payment has an associated swap, it is the swap creation time. Otherwise, the point
2083    /// in time when the underlying tx was included in a block. If there is no associated swap
2084    /// available and the underlying tx is not yet confirmed, the value is `now()`.
2085    pub timestamp: u32,
2086
2087    /// The payment amount, which corresponds to the onchain tx amount.
2088    ///
2089    /// In case of an outbound payment (Send), this is the payer amount. Otherwise it's the receiver amount.
2090    pub amount_sat: u64,
2091
2092    /// Represents the fees paid by this wallet for this payment.
2093    ///
2094    /// ### Swaps
2095    /// If there is an associated Send Swap, these fees represent the total fees paid by this wallet
2096    /// (the sender). It is the difference between the amount that was sent and the amount received.
2097    ///
2098    /// If there is an associated Receive Swap, these fees represent the total fees paid by this wallet
2099    /// (the receiver). It is also the difference between the amount that was sent and the amount received.
2100    ///
2101    /// ### Pure onchain txs
2102    /// If no swap is associated with this payment:
2103    /// - for Send payments, this is the onchain tx fee
2104    /// - for Receive payments, this is zero
2105    pub fees_sat: u64,
2106
2107    /// Service fees paid to the swapper service. This is only set for swaps (i.e. doesn't apply to
2108    /// direct Liquid payments).
2109    pub swapper_fees_sat: Option<u64>,
2110
2111    /// If it is a `Send` or `Receive` payment
2112    pub payment_type: PaymentType,
2113
2114    /// Composite status representing the overall status of the payment.
2115    ///
2116    /// If the tx has no associated swap, this reflects the onchain tx status (confirmed or not).
2117    ///
2118    /// If the tx has an associated swap, this is determined by the swap status (pending or complete).
2119    pub status: PaymentState,
2120
2121    /// The details of a payment, depending on its [destination](Payment::destination) and
2122    /// [type](Payment::payment_type)
2123    pub details: PaymentDetails,
2124}
2125impl Payment {
2126    pub(crate) fn from_pending_swap(
2127        swap: PaymentSwapData,
2128        payment_type: PaymentType,
2129        payment_details: PaymentDetails,
2130    ) -> Payment {
2131        let amount_sat = match payment_type {
2132            PaymentType::Receive => swap.receiver_amount_sat,
2133            PaymentType::Send => swap.payer_amount_sat,
2134        };
2135
2136        Payment {
2137            destination: swap.invoice.clone(),
2138            tx_id: None,
2139            unblinding_data: None,
2140            timestamp: swap.created_at,
2141            amount_sat,
2142            fees_sat: swap
2143                .payer_amount_sat
2144                .saturating_sub(swap.receiver_amount_sat),
2145            swapper_fees_sat: Some(swap.swapper_fees_sat),
2146            payment_type,
2147            status: swap.status,
2148            details: payment_details,
2149        }
2150    }
2151
2152    pub(crate) fn from_tx_data(
2153        tx: PaymentTxData,
2154        balance: PaymentTxBalance,
2155        swap: Option<PaymentSwapData>,
2156        details: PaymentDetails,
2157    ) -> Payment {
2158        let (amount_sat, fees_sat) = match swap.as_ref() {
2159            Some(s) => match balance.payment_type {
2160                // For receive swaps, to avoid some edge case issues related to potential past
2161                // overpayments, we use the actual claim value as the final received amount
2162                // for fee calculation.
2163                PaymentType::Receive => (
2164                    balance.amount,
2165                    s.payer_amount_sat.saturating_sub(balance.amount),
2166                ),
2167                PaymentType::Send => (
2168                    s.receiver_amount_sat,
2169                    s.payer_amount_sat.saturating_sub(s.receiver_amount_sat),
2170                ),
2171            },
2172            None => {
2173                let (amount_sat, fees_sat) = match balance.payment_type {
2174                    PaymentType::Receive => (balance.amount, 0),
2175                    PaymentType::Send => (balance.amount, tx.fees_sat),
2176                };
2177                // If the payment is a Liquid payment, we only show the amount if the asset
2178                // is LBTC and only show the fees if the asset info has no set fees
2179                match details {
2180                    PaymentDetails::Liquid {
2181                        asset_info: Some(ref asset_info),
2182                        ..
2183                    } if asset_info.ticker != "BTC" => (0, asset_info.fees.map_or(fees_sat, |_| 0)),
2184                    _ => (amount_sat, fees_sat),
2185                }
2186            }
2187        };
2188        Payment {
2189            tx_id: Some(tx.tx_id),
2190            unblinding_data: tx.unblinding_data,
2191            // When the swap is present and of type send and receive, we retrieve the destination from the invoice.
2192            // If it's a chain swap instead, we use the `bitcoin_address` field from the swap data.
2193            // Otherwise, we specify the Liquid address (BIP21 or pure), set in `payment_details.address`.
2194            destination: match &swap {
2195                Some(PaymentSwapData {
2196                    swap_type: PaymentSwapType::Receive,
2197                    invoice,
2198                    ..
2199                }) => invoice.clone(),
2200                Some(PaymentSwapData {
2201                    swap_type: PaymentSwapType::Send,
2202                    invoice,
2203                    bolt12_offer,
2204                    ..
2205                }) => bolt12_offer.clone().or(invoice.clone()),
2206                Some(PaymentSwapData {
2207                    swap_type: PaymentSwapType::Chain,
2208                    bitcoin_address,
2209                    ..
2210                }) => bitcoin_address.clone(),
2211                _ => match &details {
2212                    PaymentDetails::Liquid { destination, .. } => Some(destination.clone()),
2213                    _ => None,
2214                },
2215            },
2216            timestamp: tx
2217                .timestamp
2218                .or(swap.as_ref().map(|s| s.created_at))
2219                .unwrap_or(utils::now()),
2220            amount_sat,
2221            fees_sat,
2222            swapper_fees_sat: swap.as_ref().map(|s| s.swapper_fees_sat),
2223            payment_type: balance.payment_type,
2224            status: match &swap {
2225                Some(swap) => swap.status,
2226                None => match tx.is_confirmed {
2227                    true => PaymentState::Complete,
2228                    false => PaymentState::Pending,
2229                },
2230            },
2231            details,
2232        }
2233    }
2234
2235    pub(crate) fn get_refund_tx_id(&self) -> Option<String> {
2236        match self.details.clone() {
2237            PaymentDetails::Lightning { refund_tx_id, .. } => Some(refund_tx_id),
2238            PaymentDetails::Bitcoin { refund_tx_id, .. } => Some(refund_tx_id),
2239            PaymentDetails::Liquid { .. } => None,
2240        }
2241        .flatten()
2242    }
2243}
2244
2245/// Returned when calling [crate::sdk::LiquidSdk::recommended_fees].
2246#[derive(Deserialize, Serialize, Clone, Debug)]
2247#[serde(rename_all = "camelCase")]
2248pub struct RecommendedFees {
2249    pub fastest_fee: u64,
2250    pub half_hour_fee: u64,
2251    pub hour_fee: u64,
2252    pub economy_fee: u64,
2253    pub minimum_fee: u64,
2254}
2255
2256/// An argument of [PrepareBuyBitcoinRequest] when calling [crate::sdk::LiquidSdk::prepare_buy_bitcoin].
2257#[derive(Debug, Clone, Copy, EnumString, PartialEq, Serialize)]
2258pub enum BuyBitcoinProvider {
2259    #[strum(serialize = "moonpay")]
2260    Moonpay,
2261}
2262
2263/// An argument when calling [crate::sdk::LiquidSdk::prepare_buy_bitcoin].
2264#[derive(Debug, Serialize)]
2265pub struct PrepareBuyBitcoinRequest {
2266    pub provider: BuyBitcoinProvider,
2267    pub amount_sat: u64,
2268}
2269
2270/// Returned when calling [crate::sdk::LiquidSdk::prepare_buy_bitcoin].
2271#[derive(Clone, Debug, Serialize)]
2272pub struct PrepareBuyBitcoinResponse {
2273    pub provider: BuyBitcoinProvider,
2274    pub amount_sat: u64,
2275    pub fees_sat: u64,
2276}
2277
2278/// An argument when calling [crate::sdk::LiquidSdk::buy_bitcoin].
2279#[derive(Clone, Debug, Serialize)]
2280pub struct BuyBitcoinRequest {
2281    pub prepare_response: PrepareBuyBitcoinResponse,
2282    /// The optional URL to redirect to after completing the buy.
2283    ///
2284    /// For Moonpay, see <https://dev.moonpay.com/docs/on-ramp-configure-user-journey-params>
2285    pub redirect_url: Option<String>,
2286}
2287
2288/// Internal SDK log entry used in the Uniffi and Dart bindings
2289#[derive(Clone, Debug)]
2290pub struct LogEntry {
2291    pub line: String,
2292    pub level: String,
2293}
2294
2295#[derive(Clone, Debug, Serialize, Deserialize)]
2296struct InternalLeaf {
2297    pub output: String,
2298    pub version: u8,
2299}
2300impl From<InternalLeaf> for Leaf {
2301    fn from(value: InternalLeaf) -> Self {
2302        Leaf {
2303            output: value.output,
2304            version: value.version,
2305        }
2306    }
2307}
2308impl From<Leaf> for InternalLeaf {
2309    fn from(value: Leaf) -> Self {
2310        InternalLeaf {
2311            output: value.output,
2312            version: value.version,
2313        }
2314    }
2315}
2316
2317#[derive(Clone, Debug, Serialize, Deserialize)]
2318pub(super) struct InternalSwapTree {
2319    claim_leaf: InternalLeaf,
2320    refund_leaf: InternalLeaf,
2321}
2322impl From<InternalSwapTree> for SwapTree {
2323    fn from(value: InternalSwapTree) -> Self {
2324        SwapTree {
2325            claim_leaf: value.claim_leaf.into(),
2326            refund_leaf: value.refund_leaf.into(),
2327        }
2328    }
2329}
2330impl From<SwapTree> for InternalSwapTree {
2331    fn from(value: SwapTree) -> Self {
2332        InternalSwapTree {
2333            claim_leaf: value.claim_leaf.into(),
2334            refund_leaf: value.refund_leaf.into(),
2335        }
2336    }
2337}
2338
2339/// An argument when calling [crate::sdk::LiquidSdk::prepare_lnurl_pay].
2340#[derive(Debug, Serialize)]
2341pub struct PrepareLnUrlPayRequest {
2342    /// The [LnUrlPayRequestData] returned by [parse]
2343    pub data: LnUrlPayRequestData,
2344    /// The amount to send
2345    pub amount: PayAmount,
2346    /// A BIP353 address, in case one was used in order to fetch the LNURL Pay request data.
2347    /// Returned by [parse].
2348    pub bip353_address: Option<String>,
2349    /// An optional comment LUD-12 to be stored with the payment. The comment is included in the
2350    /// invoice request sent to the LNURL endpoint.
2351    pub comment: Option<String>,
2352    /// Validates that, if there is a URL success action, the URL domain matches
2353    /// the LNURL callback domain. Defaults to `true`
2354    pub validate_success_action_url: Option<bool>,
2355}
2356
2357/// Returned when calling [crate::sdk::LiquidSdk::prepare_lnurl_pay].
2358#[derive(Debug, Serialize)]
2359pub struct PrepareLnUrlPayResponse {
2360    /// The destination of the payment
2361    pub destination: SendDestination,
2362    /// The fees in satoshis to send the payment
2363    pub fees_sat: u64,
2364    /// The [LnUrlPayRequestData] returned by [parse]
2365    pub data: LnUrlPayRequestData,
2366    /// The amount to send
2367    pub amount: PayAmount,
2368    /// An optional comment LUD-12 to be stored with the payment. The comment is included in the
2369    /// invoice request sent to the LNURL endpoint.
2370    pub comment: Option<String>,
2371    /// The unprocessed LUD-09 success action. This will be processed and decrypted if
2372    /// needed after calling [crate::sdk::LiquidSdk::lnurl_pay]
2373    pub success_action: Option<SuccessAction>,
2374}
2375
2376/// An argument when calling [crate::sdk::LiquidSdk::lnurl_pay].
2377#[derive(Debug, Serialize)]
2378pub struct LnUrlPayRequest {
2379    /// The response from calling [crate::sdk::LiquidSdk::prepare_lnurl_pay]
2380    pub prepare_response: PrepareLnUrlPayResponse,
2381}
2382
2383/// Contains the result of the entire LNURL-pay interaction, as reported by the LNURL endpoint.
2384///
2385/// * `EndpointSuccess` indicates the payment is complete. The endpoint may return a `SuccessActionProcessed`,
2386///   in which case, the wallet has to present it to the user as described in
2387///   <https://github.com/lnurl/luds/blob/luds/09.md>
2388///
2389/// * `EndpointError` indicates a generic issue the LNURL endpoint encountered, including a freetext
2390///   field with the reason.
2391///
2392/// * `PayError` indicates that an error occurred while trying to pay the invoice from the LNURL endpoint.
2393///   This includes the payment hash of the failed invoice and the failure reason.
2394#[derive(Serialize)]
2395#[allow(clippy::large_enum_variant)]
2396pub enum LnUrlPayResult {
2397    EndpointSuccess { data: LnUrlPaySuccessData },
2398    EndpointError { data: LnUrlErrorData },
2399    PayError { data: LnUrlPayErrorData },
2400}
2401
2402#[derive(Serialize)]
2403pub struct LnUrlPaySuccessData {
2404    pub payment: Payment,
2405    pub success_action: Option<SuccessActionProcessed>,
2406}
2407
2408#[derive(Debug, Clone)]
2409pub enum Transaction {
2410    Liquid(boltz_client::elements::Transaction),
2411    Bitcoin(boltz_client::bitcoin::Transaction),
2412}
2413
2414impl Transaction {
2415    pub(crate) fn txid(&self) -> String {
2416        match self {
2417            Transaction::Liquid(tx) => tx.txid().to_hex(),
2418            Transaction::Bitcoin(tx) => tx.compute_txid().to_hex(),
2419        }
2420    }
2421}
2422
2423#[derive(Debug, Clone)]
2424pub enum Utxo {
2425    Liquid(
2426        Box<(
2427            boltz_client::elements::OutPoint,
2428            boltz_client::elements::TxOut,
2429        )>,
2430    ),
2431    Bitcoin(
2432        (
2433            boltz_client::bitcoin::OutPoint,
2434            boltz_client::bitcoin::TxOut,
2435        ),
2436    ),
2437}
2438
2439impl Utxo {
2440    pub(crate) fn as_bitcoin(
2441        &self,
2442    ) -> Option<&(
2443        boltz_client::bitcoin::OutPoint,
2444        boltz_client::bitcoin::TxOut,
2445    )> {
2446        match self {
2447            Utxo::Liquid(_) => None,
2448            Utxo::Bitcoin(utxo) => Some(utxo),
2449        }
2450    }
2451
2452    pub(crate) fn as_liquid(
2453        &self,
2454    ) -> Option<
2455        Box<(
2456            boltz_client::elements::OutPoint,
2457            boltz_client::elements::TxOut,
2458        )>,
2459    > {
2460        match self {
2461            Utxo::Bitcoin(_) => None,
2462            Utxo::Liquid(utxo) => Some(utxo.clone()),
2463        }
2464    }
2465}
2466
2467/// An argument when calling [crate::sdk::LiquidSdk::fetch_payment_proposed_fees].
2468#[derive(Debug, Clone)]
2469pub struct FetchPaymentProposedFeesRequest {
2470    pub swap_id: String,
2471}
2472
2473/// Returned when calling [crate::sdk::LiquidSdk::fetch_payment_proposed_fees].
2474#[derive(Debug, Clone, Serialize)]
2475pub struct FetchPaymentProposedFeesResponse {
2476    pub swap_id: String,
2477    pub fees_sat: u64,
2478    /// Amount sent by the swap payer
2479    pub payer_amount_sat: u64,
2480    /// Amount that will be received if these fees are accepted
2481    pub receiver_amount_sat: u64,
2482}
2483
2484/// An argument when calling [crate::sdk::LiquidSdk::accept_payment_proposed_fees].
2485#[derive(Debug, Clone)]
2486pub struct AcceptPaymentProposedFeesRequest {
2487    pub response: FetchPaymentProposedFeesResponse,
2488}
2489
2490#[derive(Clone, Debug)]
2491pub struct History<T> {
2492    pub txid: T,
2493    /// Confirmation height of txid
2494    ///
2495    /// -1 means unconfirmed with unconfirmed parents
2496    ///  0 means unconfirmed with confirmed parents
2497    pub height: i32,
2498}
2499pub(crate) type LBtcHistory = History<elements::Txid>;
2500pub(crate) type BtcHistory = History<bitcoin::Txid>;
2501
2502impl<T> History<T> {
2503    pub(crate) fn confirmed(&self) -> bool {
2504        self.height > 0
2505    }
2506}
2507#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2508impl From<electrum_client::GetHistoryRes> for BtcHistory {
2509    fn from(value: electrum_client::GetHistoryRes) -> Self {
2510        Self {
2511            txid: value.tx_hash,
2512            height: value.height,
2513        }
2514    }
2515}
2516impl From<lwk_wollet::History> for LBtcHistory {
2517    fn from(value: lwk_wollet::History) -> Self {
2518        Self::from(&value)
2519    }
2520}
2521impl From<&lwk_wollet::History> for LBtcHistory {
2522    fn from(value: &lwk_wollet::History) -> Self {
2523        Self {
2524            txid: value.txid,
2525            height: value.height,
2526        }
2527    }
2528}
2529pub(crate) type BtcScript = bitcoin::ScriptBuf;
2530pub(crate) type LBtcScript = elements::Script;
2531
2532#[derive(Clone, Debug)]
2533pub struct BtcScriptBalance {
2534    /// Confirmed balance in Satoshis for the address.
2535    pub confirmed: u64,
2536    /// Unconfirmed balance in Satoshis for the address.
2537    ///
2538    /// Some servers (e.g. `electrs`) return this as a negative value.
2539    pub unconfirmed: i64,
2540}
2541#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2542impl From<electrum_client::GetBalanceRes> for BtcScriptBalance {
2543    fn from(val: electrum_client::GetBalanceRes) -> Self {
2544        Self {
2545            confirmed: val.confirmed,
2546            unconfirmed: val.unconfirmed,
2547        }
2548    }
2549}
2550
2551pub(crate) struct GetSyncContextRequest {
2552    pub partial_sync: Option<bool>,
2553    pub last_liquid_tip: u32,
2554    pub last_bitcoin_tip: u32,
2555}
2556
2557pub(crate) struct SyncContext {
2558    pub maybe_liquid_tip: Option<u32>,
2559    pub maybe_bitcoin_tip: Option<u32>,
2560    pub recoverable_swaps: Vec<Swap>,
2561    pub is_new_liquid_block: bool,
2562    pub is_new_bitcoin_block: bool,
2563}
2564
2565pub(crate) struct TaskHandle {
2566    pub name: String,
2567    pub handle: tokio::task::JoinHandle<()>,
2568}
2569
2570#[macro_export]
2571macro_rules! get_updated_fields {
2572    ($($var:ident),* $(,)?) => {{
2573        let mut options = Vec::new();
2574        $(
2575            if $var.is_some() {
2576                options.push(stringify!($var).to_string());
2577            }
2578        )*
2579        match options.len() > 0 {
2580            true => Some(options),
2581            false => None,
2582        }
2583    }};
2584}