lwk_bindings 0.14.0

Liquid Wallet Kit - Bindings for other languages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
use std::{
    collections::HashMap,
    ops::ControlFlow,
    sync::{Arc, Mutex},
    time::Duration,
};

use crate::{
    blockdata::address::BitcoinAddress, Address, Bolt11Invoice, ElectrumClient, EsploraClient,
    LightningPayment, LwkError, Mnemonic, Network,
};
use log::{Level, Metadata, Record};
use lwk_boltz::{
    ChainSwapDataSerializable, ChainSwapStates, InvoiceDataSerializable,
    PreparePayDataSerializable, RevSwapStates, SubSwapStates,
};
use std::fmt;

/// Log level for logging messages
#[derive(uniffi::Enum)]
pub enum LogLevel {
    /// Debug level
    Debug,
    /// Info level
    Info,
    /// Warning level
    Warn,
    /// Error level
    Error,
}

/// An exported trait for handling logging messages.
///
/// Implement this trait to receive and handle logging messages from the lightning session.
#[uniffi::export(with_foreign)]
pub trait Logging: Send + Sync {
    /// Log a message with the given level
    fn log(&self, level: LogLevel, message: String);
}

/// An object to define logging at the caller level
#[derive(uniffi::Object)]
pub struct LoggingLink {
    #[allow(dead_code)]
    pub(crate) inner: Arc<dyn Logging>,
}

#[uniffi::export]
impl LoggingLink {
    /// Create a new `LoggingLink`
    #[uniffi::constructor]
    pub fn new(logging: Arc<dyn Logging>) -> Self {
        Self { inner: logging }
    }
}

/// Bridge logger that forwards log messages to our custom Logging trait
struct LoggingBridge {
    inner: Arc<dyn Logging>,
}

impl log::Log for LoggingBridge {
    fn enabled(&self, _metadata: &Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        let level = match record.level() {
            Level::Error => LogLevel::Error,
            Level::Warn => LogLevel::Warn,
            Level::Info => LogLevel::Info,
            Level::Debug => LogLevel::Debug,
            Level::Trace => LogLevel::Debug, // Map Trace to Debug
        };

        let message = format!("{}", record.args());
        self.inner.log(level, message);
    }

    fn flush(&self) {}
}

/// A builder for the `BoltzSession`
#[derive(uniffi::Record)]
pub struct BoltzSessionBuilder {
    network: Arc<Network>,
    client: Arc<AnyClient>,
    #[uniffi(default = None)]
    timeout: Option<u64>,
    #[uniffi(default = None)]
    mnemonic: Option<Arc<Mnemonic>>,
    #[uniffi(default = None)]
    logging: Option<Arc<dyn Logging>>,
    #[uniffi(default = false)]
    polling: bool,
    #[uniffi(default = None)]
    timeout_advance: Option<u64>,
    #[uniffi(default = None)]
    next_index_to_use: Option<u32>,
    #[uniffi(default = None)]
    referral_id: Option<String>,
    #[uniffi(default = None)]
    bitcoin_electrum_client_url: Option<String>,
    #[uniffi(default = false)]
    random_preimages: bool,
}

/// A session to pay and receive lightning payments.
///
/// Lightning payments are done via LBTC swaps using Boltz.
///
/// See `BoltzSessionBuilder` for various options to configure the session.
#[derive(uniffi::Object)]
pub struct BoltzSession {
    inner: lwk_boltz::blocking::BoltzSession,
    #[allow(dead_code)]
    logging: Option<Arc<dyn Logging>>,
}

#[derive(uniffi::Object)]
pub struct PreparePayResponse {
    /// Using Option to allow consuming the inner value when complete_pay is called
    inner: Mutex<Option<lwk_boltz::blocking::PreparePayResponse>>,
}

#[derive(uniffi::Object)]
pub struct WebHook {
    url: String,
    status: Vec<String>,
}

#[derive(uniffi::Object)]
pub struct InvoiceResponse {
    /// Using Option to allow consuming the inner value when complete_pay is called
    inner: Mutex<Option<lwk_boltz::blocking::InvoiceResponse>>,
}

#[derive(uniffi::Object)]
#[uniffi::export(Display)]
pub struct SwapList {
    inner: Vec<lwk_boltz::SwapRestoreResponse>,
}

#[derive(uniffi::Object)]
pub struct LockupResponse {
    inner: Mutex<Option<lwk_boltz::blocking::LockupResponse>>,
}

impl fmt::Display for SwapList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let json = serde_json::to_string(&self.inner).map_err(|_| fmt::Error)?;
        write!(f, "{json}")
    }
}

#[derive(uniffi::Enum)]
pub enum PaymentState {
    Continue,
    Success,
    Failed,
}

#[derive(uniffi::Object)]
pub enum AnyClient {
    Electrum(Arc<ElectrumClient>),
    Esplora(Arc<EsploraClient>),
}

#[uniffi::export]
impl AnyClient {
    #[uniffi::constructor]
    pub fn from_electrum(client: Arc<ElectrumClient>) -> Self {
        AnyClient::Electrum(client)
    }

    #[uniffi::constructor]
    pub fn from_esplora(client: Arc<EsploraClient>) -> Self {
        AnyClient::Esplora(client)
    }
}

#[uniffi::export]
impl BoltzSession {
    /// Create the lightning session with default settings
    ///
    /// This uses default timeout and generates a random mnemonic.
    /// For custom configuration, use [`BoltzSession::from_builder()`] instead.
    #[uniffi::constructor]
    pub fn new(network: &Network, client: &AnyClient) -> Result<Self, LwkError> {
        let client_arc = match client {
            AnyClient::Electrum(c) => Arc::new(AnyClient::Electrum(c.clone())),
            AnyClient::Esplora(c) => Arc::new(AnyClient::Esplora(c.clone())),
        };
        let builder = BoltzSessionBuilder {
            network: Arc::new(*network),
            client: client_arc,
            timeout: None,
            mnemonic: None,
            logging: None,
            polling: false,
            timeout_advance: None,
            next_index_to_use: None,
            referral_id: None,
            bitcoin_electrum_client_url: None,
            random_preimages: false,
        };
        Self::from_builder(builder)
    }

    /// Create the lightning session from a builder
    #[uniffi::constructor]
    pub fn from_builder(builder: BoltzSessionBuilder) -> Result<Self, LwkError> {
        // Validate the logger by attempting a test call
        if let Some(ref logger_impl) = builder.logging {
            // Test the logger with a dummy message to catch issues early
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                logger_impl.log(LogLevel::Debug, "Logger validation test".to_string());
            })).map_err(|_| LwkError::Generic {
                msg: "Logger validation failed. Please ensure you pass an instance of a class that implements the Logging trait, not the class itself.".to_string(),
            })?;
        }

        // Set up the custom logger if provided
        if let Some(ref logger_impl) = builder.logging {
            let bridge = LoggingBridge {
                inner: logger_impl.clone(),
            };
            // Try to set the logger. This can only be done once globally.
            // If it fails (logger already set), we silently continue.
            let _ = log::set_boxed_logger(Box::new(bridge))
                .map(|()| log::set_max_level(log::LevelFilter::Trace));
        }
        log::info!("Creating lightning session from builder");

        let network_value = builder.network.as_ref().into();

        let client = match builder.client.as_ref() {
            AnyClient::Electrum(client) => {
                let boltz_client = lwk_boltz::clients::ElectrumClient::from_client(
                    client.clone_client().expect("TODO"),
                    network_value,
                );
                lwk_boltz::clients::AnyClient::Electrum(Arc::new(boltz_client))
            }
            AnyClient::Esplora(client) => {
                let boltz_client = lwk_boltz::clients::EsploraClient::from_client(
                    Arc::new(client.clone_async_client().expect("TODO")),
                    network_value,
                );
                lwk_boltz::clients::AnyClient::Esplora(Arc::new(boltz_client))
            }
        };

        let mut lwk_builder = lwk_boltz::BoltzSession::builder(network_value, client);
        if let Some(timeout_secs) = builder.timeout {
            lwk_builder = lwk_builder.create_swap_timeout(Duration::from_secs(timeout_secs));
        }
        if let Some(mnemonic) = builder.mnemonic {
            lwk_builder = lwk_builder.mnemonic(mnemonic.inner());
        }
        lwk_builder = lwk_builder.polling(builder.polling);
        if let Some(timeout_advance_secs) = builder.timeout_advance {
            lwk_builder = lwk_builder.timeout_advance(Duration::from_secs(timeout_advance_secs));
        }
        if let Some(next_index_to_use) = builder.next_index_to_use {
            lwk_builder = lwk_builder.next_index_to_use(next_index_to_use);
        }
        if let Some(referral_id) = builder.referral_id {
            lwk_builder = lwk_builder.referral_id(referral_id);
        }
        lwk_builder = lwk_builder.random_preimages(builder.random_preimages);

        let inner = lwk_builder
            .build_blocking()
            .map_err(|e| LwkError::Generic {
                msg: format!("Failed to create blocking lightning session: {e:?}"),
            })?;
        Ok(Self {
            inner,
            logging: builder.logging,
        })
    }

    /// Prepare to pay a bolt11 invoice
    pub fn prepare_pay(
        &self,
        lightning_payment: &LightningPayment,
        refund_address: &Address,
        webhook: Option<Arc<WebHook>>,
    ) -> Result<PreparePayResponse, LwkError> {
        let status = webhook
            .as_ref()
            .filter(|w| !w.status.is_empty())
            .map(|w| {
                w.status
                    .iter()
                    .map(|s| s.parse::<SubSwapStates>())
                    .collect::<Result<Vec<_>, _>>()
            })
            .transpose()
            .map_err(|_| LwkError::Generic {
                msg: "Invalid status".to_string(),
            })?;
        let webhook = webhook
            .as_ref()
            .map(|w| lwk_boltz::Webhook::<SubSwapStates> {
                url: w.url.to_string(),
                hash_swap_id: None,
                status,
            });
        let response =
            self.inner
                .prepare_pay(lightning_payment.as_ref(), refund_address.as_ref(), webhook)?;

        Ok(PreparePayResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Restore a payment from its serialized data see `PreparePayResponse::serialize`
    pub fn restore_prepare_pay(&self, data: &str) -> Result<PreparePayResponse, LwkError> {
        let data = PreparePayDataSerializable::deserialize(data)?;
        let response = self.inner.restore_prepare_pay(data)?;
        Ok(PreparePayResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Create a new invoice for a given amount and a claim address to receive the payment
    pub fn invoice(
        &self,
        amount: u64,
        description: Option<String>,
        claim_address: &Address,
        webhook: Option<Arc<WebHook>>,
    ) -> Result<InvoiceResponse, LwkError> {
        let status = webhook
            .as_ref()
            .filter(|w| !w.status.is_empty())
            .map(|w| {
                w.status
                    .iter()
                    .map(|s| s.parse::<RevSwapStates>())
                    .collect::<Result<Vec<_>, _>>()
            })
            .transpose()
            .map_err(|_| LwkError::Generic {
                msg: "Invalid status".to_string(),
            })?;
        let webhook = webhook
            .as_ref()
            .map(|w| lwk_boltz::Webhook::<RevSwapStates> {
                url: w.url.to_string(),
                hash_swap_id: None,
                status,
            });
        let response = self
            .inner
            .invoice(amount, description, claim_address.as_ref(), webhook)
            .map_err(|e| LwkError::Generic {
                msg: format!("Invoice failed: {e:?}"),
            })?;

        Ok(InvoiceResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Restore an invoice flow from its serialized data see `InvoiceResponse::serialize`
    pub fn restore_invoice(&self, data: &str) -> Result<InvoiceResponse, LwkError> {
        let data: InvoiceDataSerializable = serde_json::from_str(data)?;
        let response = self.inner.restore_invoice(data)?;
        Ok(InvoiceResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Create an onchain swap to convert BTC to LBTC
    pub fn btc_to_lbtc(
        &self,
        amount: u64,
        refund_address: &BitcoinAddress,
        claim_address: &Address,
        webhook: Option<Arc<WebHook>>,
    ) -> Result<LockupResponse, LwkError> {
        let webhook = webhook
            .as_ref()
            .map(|w| lwk_boltz::Webhook::<ChainSwapStates> {
                url: w.url.to_string(),
                hash_swap_id: None,
                status: None,
            });
        let response = self.inner.btc_to_lbtc(
            amount,
            refund_address.as_ref(),
            claim_address.as_ref(),
            webhook,
        )?;
        Ok(LockupResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Create an onchain swap to convert LBTC to BTC
    pub fn lbtc_to_btc(
        &self,
        amount: u64,
        refund_address: &Address,
        claim_address: &BitcoinAddress,
        webhook: Option<Arc<WebHook>>,
    ) -> Result<LockupResponse, LwkError> {
        let webhook = webhook
            .as_ref()
            .map(|w| lwk_boltz::Webhook::<ChainSwapStates> {
                url: w.url.to_string(),
                hash_swap_id: None,
                status: None,
            });

        let response = self.inner.lbtc_to_btc(
            amount,
            refund_address.as_ref(),
            claim_address.as_ref(),
            webhook,
        )?;
        Ok(LockupResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Restore an onchain swap from its serialized data see `LockupResponse::serialize`
    pub fn restore_lockup(&self, data: &str) -> Result<LockupResponse, LwkError> {
        let data = ChainSwapDataSerializable::deserialize(data)?;
        let response = self.inner.restore_lockup(data)?;
        Ok(LockupResponse {
            inner: Mutex::new(Some(response)),
        })
    }

    /// Generate a rescue file with lightning session mnemonic.
    ///
    /// The rescue file is a JSON file that contains the swaps mnemonic.
    /// It can be used on the Boltz web app to bring non terminated swaps to completition.
    pub fn rescue_file(&self) -> Result<String, LwkError> {
        let rescue_file = self.inner.rescue_file();
        let rescue_file_json = serde_json::to_string(&rescue_file)?;
        Ok(rescue_file_json)
    }

    /// Returns a the list of all the swaps ever done with the session mnemonic.
    ///
    /// The object returned can be converted to a json String with toString()
    pub fn swap_restore(&self) -> Result<SwapList, LwkError> {
        let response = self.inner.swap_restore()?;
        Ok(SwapList { inner: response })
    }

    /// Filter the swap list to only include restorable reverse swaps
    pub fn restorable_reverse_swaps(
        &self,
        swap_list: &SwapList,
        claim_address: &Address,
    ) -> Result<Vec<String>, LwkError> {
        let response = self
            .inner
            .restorable_reverse_swaps(&swap_list.inner, claim_address.as_ref())?;
        let data = response
            .into_iter()
            .map(|e| self.inner.restore_invoice(e.into()))
            .map(|e| e.and_then(|e| e.serialize()))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(data)
    }

    /// Filter the swap list to only include restorable submarine swaps
    pub fn restorable_submarine_swaps(
        &self,
        swap_list: &SwapList,
        refund_address: &Address,
    ) -> Result<Vec<String>, LwkError> {
        let response = self
            .inner
            .restorable_submarine_swaps(&swap_list.inner, refund_address.as_ref())?;
        let data = response
            .into_iter()
            .map(|e| self.inner.restore_prepare_pay(e.into()))
            .map(|e| e.and_then(|e| e.serialize()))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(data)
    }

    /// Filter the swap list to only include restorable BTC to LBTC swaps
    pub fn restorable_btc_to_lbtc_swaps(
        &self,
        swap_list: &SwapList,
        claim_address: &Address,
        refund_address: &BitcoinAddress,
    ) -> Result<Vec<String>, LwkError> {
        let response = self.inner.restorable_btc_to_lbtc_swaps(
            &swap_list.inner,
            claim_address.as_ref(),
            refund_address.as_ref(),
        )?;
        let data = response
            .into_iter()
            .map(|e| self.inner.restore_lockup(e.into()))
            .map(|e| e.and_then(|e| e.serialize()))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(data)
    }

    /// Filter the swap list to only include restorable LBTC to BTC swaps
    pub fn restorable_lbtc_to_btc_swaps(
        &self,
        swap_list: &SwapList,
        claim_address: &BitcoinAddress,
        refund_address: &Address,
    ) -> Result<Vec<String>, LwkError> {
        let response = self.inner.restorable_lbtc_to_btc_swaps(
            &swap_list.inner,
            claim_address.as_ref(),
            refund_address.as_ref(),
        )?;
        let data = response
            .into_iter()
            .map(|e| self.inner.restore_lockup(e.into()))
            .map(|e| e.and_then(|e| e.serialize()))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(data)
    }

    /// Fetch informations, such as min and max amounts, about the reverse and submarine pairs from the boltz api.
    pub fn fetch_swaps_info(&self) -> Result<String, LwkError> {
        let (reverse, submarine, chain) = self.inner.fetch_swaps_info()?;
        let reverse_json = serde_json::to_value(&reverse)?;
        let submarine_json = serde_json::to_value(&submarine)?;
        let chain_json = serde_json::to_value(&chain)?;
        let mut result = HashMap::new();
        result.insert("reverse".to_string(), reverse_json);
        result.insert("submarine".to_string(), submarine_json);
        result.insert("chain".to_string(), chain_json);
        let result_json = serde_json::to_string(&result)?;
        Ok(result_json)
    }

    /// Get the next index to use for deriving keypairs
    pub fn next_index_to_use(&self) -> u32 {
        self.inner.next_index_to_use()
    }

    /// Set the next index to use for deriving keypairs
    ///
    /// This may be necessary to handle multiple sessions with the same mnemonic.
    pub fn set_next_index_to_use(&self, next_index_to_use: u32) {
        self.inner.set_next_index_to_use(next_index_to_use);
    }
}

#[uniffi::export]
impl PreparePayResponse {
    pub fn complete_pay(&self) -> Result<bool, LwkError> {
        let mut lock = self.inner.lock()?;
        let response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(response.complete_pay()?)
    }

    pub fn swap_id(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .swap_id())
    }

    /// Serialize the prepare pay response data to a json string
    ///
    /// This can be used to restore the prepare pay response after a crash
    pub fn serialize(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .serialize()?)
    }

    pub fn uri(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .uri())
    }

    pub fn uri_address(&self) -> Result<Arc<Address>, LwkError> {
        let uri_address = self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .uri_address()?;
        Ok(Arc::new(uri_address.into()))
    }
    pub fn uri_amount(&self) -> Result<u64, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .uri_amount())
    }

    /// The fee of the swap provider and the network fee
    ///
    /// It is equal to the amount requested onchain minus the amount of the bolt11 invoice
    pub fn fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .fee())
    }

    /// The fee of the swap provider
    ///
    /// It is equal to the invoice amount multiplied by the boltz fee rate.
    /// For example for paying an invoice of 1000 satoshi with a 0.1% rate would be 1 satoshi.
    pub fn boltz_fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .boltz_fee())
    }

    pub fn advance(&self) -> Result<PaymentState, LwkError> {
        let mut lock = self.inner.lock()?;
        let mut response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(match response.advance() {
            Ok(ControlFlow::Continue(_update)) => {
                *lock = Some(response);
                PaymentState::Continue
            }
            Ok(ControlFlow::Break(update)) => {
                *lock = Some(response);
                if update {
                    PaymentState::Success
                } else {
                    PaymentState::Failed
                }
            }
            Err(lwk_boltz::Error::NoBoltzUpdate) => {
                *lock = Some(response);
                return Err(LwkError::NoBoltzUpdate);
            }
            Err(e) => return Err(e.into()),
        })
    }
}

#[uniffi::export]
impl InvoiceResponse {
    pub fn bolt11_invoice(&self) -> Result<Bolt11Invoice, LwkError> {
        let bolt11_invoice = self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .bolt11_invoice();
        Ok(Bolt11Invoice::from(bolt11_invoice))
    }

    pub fn swap_id(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .swap_id())
    }

    /// The fee of the swap provider and the network fee
    ///
    /// It is equal to the amount of the invoice minus the amount of the onchain transaction.
    pub fn fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .fee())
    }

    /// The fee of the swap provider
    ///
    /// It is equal to the invoice amount multiplied by the boltz fee rate.
    /// For example for receiving an invoice of 10000 satoshi with a 0.25% rate would be 25 satoshi.
    pub fn boltz_fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .boltz_fee())
    }

    /// The txid of the claim transaction of the swap
    pub fn claim_txid(&self) -> Result<Option<String>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .claim_txid()
            .map(|txid| txid.to_string()))
    }

    /// Serialize the prepare pay response data to a json string
    ///
    /// This can be used to restore the prepare pay response after a crash
    pub fn serialize(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .serialize()?)
    }

    pub fn complete_pay(&self) -> Result<bool, LwkError> {
        let mut lock = self.inner.lock()?;
        let response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(response.complete_pay()?)
    }

    pub fn advance(&self) -> Result<PaymentState, LwkError> {
        let mut lock = self.inner.lock()?;
        let mut response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(match response.advance() {
            Ok(ControlFlow::Continue(_update)) => {
                *lock = Some(response);
                PaymentState::Continue
            }
            Ok(ControlFlow::Break(update)) => {
                *lock = Some(response);
                if update {
                    PaymentState::Success
                } else {
                    PaymentState::Failed
                }
            }
            Err(lwk_boltz::Error::NoBoltzUpdate) => {
                *lock = Some(response);
                return Err(LwkError::NoBoltzUpdate);
            }
            Err(e) => return Err(e.into()),
        })
    }
}

#[uniffi::export]
impl LockupResponse {
    pub fn swap_id(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .swap_id())
    }

    pub fn lockup_address(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .lockup_address()
            .to_string())
    }

    pub fn expected_amount(&self) -> Result<u64, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .expected_amount())
    }

    pub fn chain_from(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .chain_from()
            .to_string())
    }

    pub fn chain_to(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .chain_to()
            .to_string())
    }

    /// The fee of the swap provider and the network fee
    ///
    /// It is equal to the amount requested minus the amount sent to the claim address.
    pub fn fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .fee())
    }

    /// The fee of the swap provider
    ///
    /// It is equal to the swap amount multiplied by the boltz fee rate.
    pub fn boltz_fee(&self) -> Result<Option<u64>, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .boltz_fee())
    }

    pub fn advance(&self) -> Result<PaymentState, LwkError> {
        let mut lock = self.inner.lock()?;
        let mut response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(match response.advance() {
            Ok(ControlFlow::Continue(_update)) => {
                *lock = Some(response);
                PaymentState::Continue
            }
            Ok(ControlFlow::Break(update)) => {
                if update {
                    PaymentState::Success
                } else {
                    PaymentState::Failed
                }
            }
            Err(lwk_boltz::Error::NoBoltzUpdate) => {
                *lock = Some(response);
                return Err(LwkError::NoBoltzUpdate);
            }
            Err(e) => return Err(e.into()),
        })
    }

    pub fn complete(&self) -> Result<bool, LwkError> {
        let mut lock = self.inner.lock()?;
        let response = lock.take().ok_or(LwkError::ObjectConsumed)?;
        Ok(response.complete()?)
    }

    pub fn serialize(&self) -> Result<String, LwkError> {
        Ok(self
            .inner
            .lock()?
            .as_ref()
            .ok_or(LwkError::ObjectConsumed)?
            .serialize()?)
    }
}

#[uniffi::export]
impl WebHook {
    #[uniffi::constructor]
    pub fn new(url: String, status: Vec<String>) -> Arc<Self> {
        Arc::new(Self { url, status })
    }
}