cdk-ffi 0.17.5

FFI bindings for cdk wallet
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Wallet-related FFI types

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use cdk_common::bitcoin;
use serde::{Deserialize, Serialize};

use super::amount::{Amount, SplitTarget};
use super::proof::{Proofs, SpendingConditions};
use crate::error::FfiError;
use crate::token::Token;
use crate::{CurrencyUnit, MintUrl, PublicKey};

/// FFI-compatible SendMemo
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct SendMemo {
    /// Memo text
    pub memo: String,
    /// Include memo in token
    pub include_memo: bool,
}

impl From<SendMemo> for cdk::wallet::SendMemo {
    fn from(memo: SendMemo) -> Self {
        cdk::wallet::SendMemo {
            memo: memo.memo,
            include_memo: memo.include_memo,
        }
    }
}

impl From<cdk::wallet::SendMemo> for SendMemo {
    fn from(memo: cdk::wallet::SendMemo) -> Self {
        Self {
            memo: memo.memo,
            include_memo: memo.include_memo,
        }
    }
}

impl SendMemo {
    /// Convert SendMemo to JSON string
    pub fn to_json(&self) -> Result<String, FfiError> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Decode SendMemo from JSON string
#[uniffi::export]
pub fn decode_send_memo(json: String) -> Result<SendMemo, FfiError> {
    Ok(serde_json::from_str(&json)?)
}

/// Encode SendMemo to JSON string
#[uniffi::export]
pub fn encode_send_memo(memo: SendMemo) -> Result<String, FfiError> {
    Ok(serde_json::to_string(&memo)?)
}

/// FFI-compatible SendKind
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]
pub enum SendKind {
    /// Allow online swap before send if wallet does not have exact amount
    OnlineExact,
    /// Prefer offline send if difference is less than tolerance
    OnlineTolerance { tolerance: Amount },
    /// Wallet cannot do an online swap and selected proof must be exactly send amount
    OfflineExact,
    /// Wallet must remain offline but can over pay if below tolerance
    OfflineTolerance { tolerance: Amount },
}

impl From<SendKind> for cdk::wallet::SendKind {
    fn from(kind: SendKind) -> Self {
        match kind {
            SendKind::OnlineExact => cdk::wallet::SendKind::OnlineExact,
            SendKind::OnlineTolerance { tolerance } => {
                cdk::wallet::SendKind::OnlineTolerance(tolerance.into())
            }
            SendKind::OfflineExact => cdk::wallet::SendKind::OfflineExact,
            SendKind::OfflineTolerance { tolerance } => {
                cdk::wallet::SendKind::OfflineTolerance(tolerance.into())
            }
        }
    }
}

/// FFI-compatible P2PKSigningKey
#[derive(Debug, Clone, uniffi::Record)]
pub struct P2PKSigningKey {
    /// Public key
    pub pubkey: PublicKey,
    /// Derivation path as string
    pub derivation_path: String,
    /// Derivation index
    pub derivation_index: u32,
    /// Created time
    pub created_time: u64,
}

impl TryFrom<P2PKSigningKey> for cdk_common::wallet::P2PKSigningKey {
    type Error = crate::error::FfiError;

    fn try_from(key: P2PKSigningKey) -> Result<Self, FfiError> {
        Ok(Self {
            pubkey: key.pubkey.try_into()?,
            derivation_path: key
                .derivation_path
                .parse()
                .map_err(|e: bitcoin::bip32::Error| FfiError::Internal {
                    error_message: e.to_string(),
                })?,
            derivation_index: key.derivation_index,
            created_time: key.created_time,
        })
    }
}

impl From<cdk_common::wallet::P2PKSigningKey> for P2PKSigningKey {
    fn from(key: cdk_common::wallet::P2PKSigningKey) -> Self {
        Self {
            pubkey: key.pubkey.into(),
            derivation_path: key.derivation_path.to_string(),
            derivation_index: key.derivation_index,
            created_time: key.created_time,
        }
    }
}

impl From<cdk::wallet::SendKind> for SendKind {
    fn from(kind: cdk::wallet::SendKind) -> Self {
        match kind {
            cdk::wallet::SendKind::OnlineExact => SendKind::OnlineExact,
            cdk::wallet::SendKind::OnlineTolerance(tolerance) => SendKind::OnlineTolerance {
                tolerance: tolerance.into(),
            },
            cdk::wallet::SendKind::OfflineExact => SendKind::OfflineExact,
            cdk::wallet::SendKind::OfflineTolerance(tolerance) => SendKind::OfflineTolerance {
                tolerance: tolerance.into(),
            },
        }
    }
}

/// FFI-compatible P2PK locked proof send mode
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, uniffi::Enum, Default,
)]
pub enum P2PKLockedProofSendMode {
    /// Swap locked proofs into fresh proofs before creating the token
    #[default]
    Swap,
    /// Sign locked proofs and include them directly in the token
    SignAndSend,
}

impl From<P2PKLockedProofSendMode> for cdk::wallet::P2PKLockedProofSendMode {
    fn from(mode: P2PKLockedProofSendMode) -> Self {
        match mode {
            P2PKLockedProofSendMode::Swap => cdk::wallet::P2PKLockedProofSendMode::Swap,
            P2PKLockedProofSendMode::SignAndSend => {
                cdk::wallet::P2PKLockedProofSendMode::SignAndSend
            }
        }
    }
}

impl From<cdk::wallet::P2PKLockedProofSendMode> for P2PKLockedProofSendMode {
    fn from(mode: cdk::wallet::P2PKLockedProofSendMode) -> Self {
        match mode {
            cdk::wallet::P2PKLockedProofSendMode::Swap => P2PKLockedProofSendMode::Swap,
            cdk::wallet::P2PKLockedProofSendMode::SignAndSend => {
                P2PKLockedProofSendMode::SignAndSend
            }
        }
    }
}

/// FFI-compatible Send options
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct SendOptions {
    /// Memo
    pub memo: Option<SendMemo>,
    /// Spending conditions
    pub conditions: Option<SpendingConditions>,
    /// Amount split target
    pub amount_split_target: SplitTarget,
    /// Send kind
    pub send_kind: SendKind,
    /// Include fee
    pub include_fee: bool,
    pub use_p2bk: bool,
    /// Maximum number of proofs to include in the token
    pub max_proofs: Option<u32>,
    /// Metadata
    pub metadata: HashMap<String, String>,
    /// Signing keys for P2PK-locked input proofs
    #[serde(default)]
    pub p2pk_signing_keys: Vec<SecretKey>,
    /// How P2PK-locked input proofs should be handled during send
    #[serde(default)]
    pub p2pk_locked_proof_send_mode: P2PKLockedProofSendMode,
}

impl Default for SendOptions {
    fn default() -> Self {
        Self {
            memo: None,
            conditions: None,
            amount_split_target: SplitTarget::None,
            send_kind: SendKind::OnlineExact,
            include_fee: false,
            max_proofs: None,
            metadata: HashMap::new(),
            use_p2bk: false,
            p2pk_signing_keys: Vec::new(),
            p2pk_locked_proof_send_mode: P2PKLockedProofSendMode::Swap,
        }
    }
}

impl TryFrom<SendOptions> for cdk::wallet::SendOptions {
    type Error = FfiError;

    fn try_from(opts: SendOptions) -> Result<Self, Self::Error> {
        let p2pk_signing_keys = opts
            .p2pk_signing_keys
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<_>, _>>()?;

        Ok(cdk::wallet::SendOptions {
            memo: opts.memo.map(Into::into),
            conditions: opts.conditions.map(TryInto::try_into).transpose()?,
            amount_split_target: opts.amount_split_target.into(),
            send_kind: opts.send_kind.into(),
            include_fee: opts.include_fee,
            max_proofs: opts.max_proofs.map(|p| p as usize),
            metadata: opts.metadata,
            use_p2bk: opts.use_p2bk,
            p2pk_signing_keys,
            p2pk_locked_proof_send_mode: opts.p2pk_locked_proof_send_mode.into(),
        })
    }
}

impl From<cdk::wallet::SendOptions> for SendOptions {
    fn from(opts: cdk::wallet::SendOptions) -> Self {
        Self {
            memo: opts.memo.map(Into::into),
            conditions: opts.conditions.map(Into::into),
            amount_split_target: opts.amount_split_target.into(),
            send_kind: opts.send_kind.into(),
            include_fee: opts.include_fee,
            max_proofs: opts.max_proofs.map(|p| p as u32),
            metadata: opts.metadata,
            use_p2bk: opts.use_p2bk,
            p2pk_signing_keys: opts.p2pk_signing_keys.into_iter().map(Into::into).collect(),
            p2pk_locked_proof_send_mode: opts.p2pk_locked_proof_send_mode.into(),
        }
    }
}

impl SendOptions {
    /// Convert SendOptions to JSON string
    pub fn to_json(&self) -> Result<String, FfiError> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Decode SendOptions from JSON string
#[uniffi::export]
pub fn decode_send_options(json: String) -> Result<SendOptions, FfiError> {
    Ok(serde_json::from_str(&json)?)
}

/// Encode SendOptions to JSON string
#[uniffi::export]
pub fn encode_send_options(options: SendOptions) -> Result<String, FfiError> {
    Ok(serde_json::to_string(&options)?)
}

/// FFI-compatible SecretKey
#[derive(Clone, Serialize, Deserialize, uniffi::Record)]
#[serde(transparent)]
pub struct SecretKey {
    /// Hex-encoded secret key (64 characters)
    pub hex: String,
}

impl fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SecretKey")
            .field("hex", &"[redacted]")
            .finish()
    }
}

impl SecretKey {
    /// Create a new SecretKey from hex string
    pub fn from_hex(hex: String) -> Result<Self, FfiError> {
        // Validate hex string length (should be 64 characters for 32 bytes)
        if hex.len() != 64 {
            return Err(FfiError::internal(
                "Secret key hex must be exactly 64 characters (32 bytes)",
            ));
        }

        // Validate hex format
        if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(FfiError::internal(
                "Secret key hex contains invalid characters",
            ));
        }

        Ok(Self { hex })
    }

    /// Generate a random secret key
    pub fn random() -> Self {
        use cdk::nuts::SecretKey as CdkSecretKey;
        let secret_key = CdkSecretKey::generate();
        Self {
            hex: secret_key.to_secret_hex(),
        }
    }
}

impl TryFrom<SecretKey> for cdk::nuts::SecretKey {
    type Error = FfiError;

    fn try_from(key: SecretKey) -> Result<Self, Self::Error> {
        cdk::nuts::SecretKey::from_hex(&key.hex)
            .map_err(|e| FfiError::internal(format!("Invalid secret key: {}", e)))
    }
}

impl From<cdk::nuts::SecretKey> for SecretKey {
    fn from(key: cdk::nuts::SecretKey) -> Self {
        Self {
            hex: key.to_secret_hex(),
        }
    }
}

/// FFI-compatible Receive options
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct ReceiveOptions {
    /// Amount split target
    pub amount_split_target: SplitTarget,
    /// P2PK signing keys
    #[serde(default)]
    pub p2pk_signing_keys: Vec<SecretKey>,
    /// Preimages for HTLC conditions
    pub preimages: Vec<String>,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

impl Default for ReceiveOptions {
    fn default() -> Self {
        Self {
            amount_split_target: SplitTarget::None,
            p2pk_signing_keys: Vec::new(),
            preimages: Vec::new(),
            metadata: HashMap::new(),
        }
    }
}

impl TryFrom<ReceiveOptions> for cdk::wallet::ReceiveOptions {
    type Error = FfiError;

    fn try_from(opts: ReceiveOptions) -> Result<Self, Self::Error> {
        let p2pk_signing_keys = opts
            .p2pk_signing_keys
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<_>, _>>()?;

        Ok(cdk::wallet::ReceiveOptions {
            amount_split_target: opts.amount_split_target.into(),
            p2pk_signing_keys,
            preimages: opts.preimages,
            metadata: opts.metadata,
        })
    }
}

impl From<cdk::wallet::ReceiveOptions> for ReceiveOptions {
    fn from(opts: cdk::wallet::ReceiveOptions) -> Self {
        Self {
            amount_split_target: opts.amount_split_target.into(),
            p2pk_signing_keys: opts.p2pk_signing_keys.into_iter().map(Into::into).collect(),
            preimages: opts.preimages,
            metadata: opts.metadata,
        }
    }
}

impl ReceiveOptions {
    /// Convert ReceiveOptions to JSON string
    pub fn to_json(&self) -> Result<String, FfiError> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Decode ReceiveOptions from JSON string
#[uniffi::export]
pub fn decode_receive_options(json: String) -> Result<ReceiveOptions, FfiError> {
    Ok(serde_json::from_str(&json)?)
}

/// Encode ReceiveOptions to JSON string
#[uniffi::export]
pub fn encode_receive_options(options: ReceiveOptions) -> Result<String, FfiError> {
    Ok(serde_json::to_string(&options)?)
}

/// FFI-compatible NUT-13 restore options
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct NUT13Options {
    /// Number of blinded messages to request per batch
    pub batch_size: u32,
    /// Number of consecutive empty batches that terminate the scan
    pub max_gap: u32,
}

impl Default for NUT13Options {
    fn default() -> Self {
        cdk::wallet::NUT13Options::default().into()
    }
}

impl TryFrom<NUT13Options> for cdk::wallet::NUT13Options {
    type Error = FfiError;

    fn try_from(opts: NUT13Options) -> Result<Self, Self::Error> {
        Ok(cdk::wallet::NUT13Options::new(
            opts.batch_size,
            opts.max_gap,
        )?)
    }
}

impl From<cdk::wallet::NUT13Options> for NUT13Options {
    fn from(opts: cdk::wallet::NUT13Options) -> Self {
        NUT13Options {
            batch_size: opts.batch_size,
            max_gap: opts.max_gap,
        }
    }
}

/// FFI-compatible PreparedSend
///
/// This wraps the data from a prepared send operation along with a reference
/// to the wallet. The actual PreparedSend<'a> from cdk has a lifetime parameter
/// that doesn't work with FFI, so we store the wallet and cached data separately.
#[derive(uniffi::Object)]
pub struct PreparedSend {
    wallet: std::sync::Arc<cdk::Wallet>,
    operation_id: uuid::Uuid,
    amount: Amount,
    options: cdk::wallet::SendOptions,
    proofs_to_swap: cdk::nuts::Proofs,
    proofs_to_send: cdk::nuts::Proofs,
    swap_fee: Amount,
    send_fee: Amount,
}

impl std::fmt::Debug for PreparedSend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PreparedSend")
            .field("operation_id", &self.operation_id)
            .field("amount", &self.amount)
            .finish()
    }
}

impl PreparedSend {
    /// Create a new FFI PreparedSend from a cdk::wallet::PreparedSend and wallet
    pub fn new(
        wallet: std::sync::Arc<cdk::Wallet>,
        prepared: &cdk::wallet::PreparedSend<'_>,
    ) -> Self {
        Self {
            wallet,
            operation_id: prepared.operation_id(),
            amount: prepared.amount().into(),
            options: prepared.options().clone(),
            proofs_to_swap: prepared.proofs_to_swap().clone(),
            proofs_to_send: prepared.proofs_to_send().clone(),
            swap_fee: prepared.swap_fee().into(),
            send_fee: prepared.send_fee().into(),
        }
    }
}

#[uniffi::export(async_runtime = "tokio")]
impl PreparedSend {
    /// Get the operation ID for this prepared send
    pub fn operation_id(&self) -> String {
        self.operation_id.to_string()
    }

    /// Get the amount to send
    pub fn amount(&self) -> Amount {
        self.amount
    }

    /// Get the proofs that will be used
    pub fn proofs(&self) -> Proofs {
        let mut all_proofs: Vec<_> = self
            .proofs_to_swap
            .iter()
            .cloned()
            .map(|p| p.into())
            .collect();
        all_proofs.extend(self.proofs_to_send.iter().cloned().map(|p| p.into()));
        all_proofs
    }

    /// Get the total fee for this send operation
    pub fn fee(&self) -> Amount {
        Amount::new(self.swap_fee.value + self.send_fee.value)
    }

    /// Confirm the prepared send and create a token
    pub async fn confirm(
        self: std::sync::Arc<Self>,
        memo: Option<String>,
    ) -> Result<Token, FfiError> {
        let send_memo = memo.map(|m| cdk::wallet::SendMemo::for_token(&m));
        let token = self
            .wallet
            .confirm_send(
                self.operation_id,
                self.amount.into(),
                self.options.clone(),
                self.proofs_to_swap.clone(),
                self.proofs_to_send.clone(),
                self.swap_fee.into(),
                self.send_fee.into(),
                send_memo,
            )
            .await?;

        Ok(token.into())
    }

    /// Cancel the prepared send operation
    pub async fn cancel(self: std::sync::Arc<Self>) -> Result<(), FfiError> {
        self.wallet
            .cancel_send(
                self.operation_id,
                self.proofs_to_swap.clone(),
                self.proofs_to_send.clone(),
            )
            .await?;
        Ok(())
    }
}

/// FFI-compatible FinalizedMelt result
#[derive(Debug, Clone, uniffi::Record)]
pub struct FinalizedMelt {
    pub quote_id: String,
    pub state: super::quote::QuoteState,
    pub preimage: Option<String>,
    pub change: Option<Proofs>,
    pub amount: Amount,
    pub fee_paid: Amount,
}

impl From<cdk_common::common::FinalizedMelt> for FinalizedMelt {
    fn from(finalized: cdk_common::common::FinalizedMelt) -> Self {
        Self {
            quote_id: finalized.quote_id().to_string(),
            state: finalized.state().into(),
            preimage: finalized.payment_proof().map(|s: &str| s.to_string()),
            change: finalized
                .change()
                .map(|proofs| proofs.iter().cloned().map(|p| p.into()).collect()),
            amount: finalized.amount().into(),
            fee_paid: finalized.fee_paid().into(),
        }
    }
}

/// A pending async melt accepted by the mint.
///
/// FFI callers receive this handle when the mint accepts a melt for background
/// processing. Call [`PendingMelt::wait`] from a background task/coroutine to
/// poll existing wallet recovery until the melt settles.
///
/// Mobile apps should also call [`crate::Wallet::recover_incomplete_sagas`] or
/// [`crate::Wallet::finalize_pending_melts`] on startup/resume, because
/// operating systems may suspend or cancel long-running background waits.
#[derive(uniffi::Object)]
pub struct PendingMelt {
    wallet: Arc<cdk::Wallet>,
    quote_id: String,
    operation_id: uuid::Uuid,
    payment_method: cdk_common::PaymentMethod,
}

impl std::fmt::Debug for PendingMelt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PendingMelt")
            .field("operation_id", &self.operation_id)
            .field("quote_id", &self.quote_id)
            .finish()
    }
}

#[uniffi::export(async_runtime = "tokio")]
impl PendingMelt {
    /// Quote ID for this pending melt.
    pub fn quote_id(&self) -> String {
        self.quote_id.clone()
    }

    /// Operation ID for this pending melt saga.
    pub fn operation_id(&self) -> String {
        self.operation_id.to_string()
    }

    /// Wait for this pending melt to complete.
    ///
    /// This method polls the wallet's existing melt recovery path until the
    /// pending saga finalizes or fails.
    ///
    /// This can wait for an extended period. Swift/Kotlin callers should run it
    /// in a cancellable background task or coroutine, not directly in UI
    /// control flow. If the app is suspended or killed before this returns,
    /// call `Wallet::recover_incomplete_sagas()` or
    /// `Wallet::finalize_pending_melts()` after restart/resume.
    pub async fn wait(&self) -> Result<FinalizedMelt, FfiError> {
        let finalized = self
            .wallet
            .wait_pending_melt(
                self.operation_id,
                &self.quote_id,
                self.payment_method.clone(),
            )
            .await?;

        Ok(finalized.into())
    }
}

/// Result of async-preferred melt confirmation.
///
/// `Paid` means the melt finalized during confirmation. `Pending` means the
/// mint accepted the melt for asynchronous processing; call
/// [`PendingMelt::wait`] to complete the normal app flow.
#[derive(Debug, Clone, uniffi::Enum)]
pub enum MeltConfirmOutcome {
    /// Melt finalized during confirmation.
    Paid { finalized: FinalizedMelt },
    /// Mint accepted async melt processing and the payment is still pending.
    Pending { pending: Arc<PendingMelt> },
}

/// FFI-compatible PreparedMelt
///
/// This wraps the data from a prepared melt operation along with a reference
/// to the wallet. The actual PreparedMelt<'a> from cdk has a lifetime parameter
/// that doesn't work with FFI, so we store the wallet and cached data separately.
#[derive(uniffi::Object)]
pub struct PreparedMelt {
    wallet: Arc<cdk::Wallet>,
    operation_id: uuid::Uuid,
    quote: cdk_common::wallet::MeltQuote,
    proofs: cdk::nuts::Proofs,
    proofs_to_swap: cdk::nuts::Proofs,
    swap_fee: Amount,
    input_fee: Amount,
    input_fee_without_swap: Amount,
    metadata: HashMap<String, String>,
}

impl std::fmt::Debug for PreparedMelt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PreparedMelt")
            .field("operation_id", &self.operation_id)
            .field("quote_id", &self.quote.id)
            .field("amount", &self.quote.amount)
            .finish()
    }
}

impl PreparedMelt {
    /// Create a new FFI PreparedMelt from a cdk::wallet::PreparedMelt and wallet
    pub fn new(wallet: Arc<cdk::Wallet>, prepared: &cdk::wallet::PreparedMelt<'_>) -> Self {
        Self {
            wallet,
            operation_id: prepared.operation_id(),
            quote: prepared.quote().clone(),
            proofs: prepared.proofs().clone(),
            proofs_to_swap: prepared.proofs_to_swap().clone(),
            swap_fee: prepared.swap_fee().into(),
            input_fee: prepared.input_fee().into(),
            input_fee_without_swap: prepared.input_fee_without_swap().into(),
            metadata: prepared.metadata().clone(),
        }
    }

    async fn confirm_prefer_async_with_options(
        &self,
        options: MeltConfirmOptions,
    ) -> Result<MeltConfirmOutcome, FfiError> {
        let outcome = self
            .wallet
            .confirm_prepared_melt_prefer_async_with_options(
                self.operation_id,
                self.quote.clone(),
                self.proofs.clone(),
                self.proofs_to_swap.clone(),
                self.input_fee.into(),
                self.input_fee_without_swap.into(),
                self.metadata.clone(),
                options.into(),
            )
            .await?;

        match outcome {
            cdk::wallet::MeltOutcome::Paid(finalized) => Ok(MeltConfirmOutcome::Paid {
                finalized: finalized.into(),
            }),
            cdk::wallet::MeltOutcome::Pending(_) => Ok(MeltConfirmOutcome::Pending {
                pending: Arc::new(PendingMelt {
                    wallet: Arc::clone(&self.wallet),
                    quote_id: self.quote.id.clone(),
                    operation_id: self.operation_id,
                    payment_method: self.quote.payment_method.clone(),
                }),
            }),
        }
    }
}

#[uniffi::export(async_runtime = "tokio")]
impl PreparedMelt {
    /// Get the operation ID for this prepared melt
    pub fn operation_id(&self) -> String {
        self.operation_id.to_string()
    }

    /// Get the quote ID
    pub fn quote_id(&self) -> String {
        self.quote.id.clone()
    }

    /// Get the amount to be melted
    pub fn amount(&self) -> Amount {
        self.quote.amount.into()
    }

    /// Get the fee reserve from the quote
    pub fn fee_reserve(&self) -> Amount {
        self.quote.fee_reserve.into()
    }

    /// Get the swap fee
    pub fn swap_fee(&self) -> Amount {
        self.swap_fee
    }

    /// Get the input fee
    pub fn input_fee(&self) -> Amount {
        self.input_fee
    }

    /// Get the total fee (swap fee + input fee)
    pub fn total_fee(&self) -> Amount {
        Amount::new(self.swap_fee.value + self.input_fee.value)
    }

    /// Returns true if a swap would be performed (proofs_to_swap is not empty)
    pub fn requires_swap(&self) -> bool {
        !self.proofs_to_swap.is_empty()
    }

    /// Get the total fee if swap is performed (current default behavior)
    pub fn total_fee_with_swap(&self) -> Amount {
        Amount::new(self.swap_fee.value + self.input_fee.value)
    }

    /// Get the input fee if swap is skipped (fee on all proofs sent directly)
    pub fn input_fee_without_swap(&self) -> Amount {
        self.input_fee_without_swap
    }

    /// Get the fee savings from skipping the swap
    pub fn fee_savings_without_swap(&self) -> Amount {
        let total_with = self.swap_fee.value + self.input_fee.value;
        let total_without = self.input_fee_without_swap.value;
        if total_with > total_without {
            Amount::new(total_with - total_without)
        } else {
            Amount::new(0)
        }
    }

    /// Get the expected change amount if swap is skipped
    pub fn change_amount_without_swap(&self) -> Amount {
        use cdk::nuts::nut00::ProofsMethods;
        let all_proofs_total = self.proofs.total_amount().unwrap_or(cdk::Amount::ZERO)
            + self
                .proofs_to_swap
                .total_amount()
                .unwrap_or(cdk::Amount::ZERO);
        let needed =
            self.quote.amount + self.quote.fee_reserve + self.input_fee_without_swap.into();
        all_proofs_total
            .checked_sub(needed)
            .map(|a| a.into())
            .unwrap_or(Amount::new(0))
    }

    /// Get the proofs that will be used
    pub fn proofs(&self) -> Proofs {
        self.proofs.iter().cloned().map(|p| p.into()).collect()
    }

    /// Confirm the prepared melt and execute the payment
    pub async fn confirm(&self) -> Result<FinalizedMelt, FfiError> {
        self.confirm_with_options(MeltConfirmOptions::default())
            .await
    }

    /// Confirm the prepared melt with custom options
    pub async fn confirm_with_options(
        &self,
        options: MeltConfirmOptions,
    ) -> Result<FinalizedMelt, FfiError> {
        let finalized = self
            .wallet
            .confirm_prepared_melt_with_options(
                self.operation_id,
                self.quote.clone(),
                self.proofs.clone(),
                self.proofs_to_swap.clone(),
                self.input_fee.into(),
                self.input_fee_without_swap.into(),
                self.metadata.clone(),
                options.into(),
            )
            .await?;

        Ok(finalized.into())
    }

    /// Confirm the prepared melt using NUT-05 async support when the mint accepts it.
    ///
    /// If the melt completes immediately, this returns
    /// `MeltConfirmOutcome::Paid`. If the mint accepts the payment for
    /// background processing, this returns `MeltConfirmOutcome::Pending` with a
    /// `PendingMelt` handle.
    ///
    /// FFI callers should call `PendingMelt::wait()` from a background
    /// task/coroutine to poll for completion. Mobile apps should also call
    /// `recover_incomplete_sagas()` or `finalize_pending_melts()` on
    /// startup/resume, because operating systems may suspend or cancel
    /// long-running background waits.
    pub async fn confirm_prefer_async(&self) -> Result<MeltConfirmOutcome, FfiError> {
        self.confirm_prefer_async_with_options(MeltConfirmOptions::default())
            .await
    }

    /// Cancel the prepared melt and release reserved proofs
    pub async fn cancel(&self) -> Result<(), FfiError> {
        self.wallet
            .cancel_prepared_melt(
                self.operation_id,
                self.proofs.clone(),
                self.proofs_to_swap.clone(),
            )
            .await?;
        Ok(())
    }
}

/// FFI-compatible MeltOptions
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]
pub enum MeltOptions {
    /// MPP (Multi-Part Payments) options
    Mpp { amount: Amount },
    /// Amountless options
    Amountless { amount_msat: Amount },
}

impl From<MeltOptions> for cdk::nuts::MeltOptions {
    fn from(opts: MeltOptions) -> Self {
        match opts {
            MeltOptions::Mpp { amount } => {
                let cdk_amount: cdk::Amount = amount.into();
                cdk::nuts::MeltOptions::new_mpp(cdk_amount)
            }
            MeltOptions::Amountless { amount_msat } => {
                let cdk_amount: cdk::Amount = amount_msat.into();
                cdk::nuts::MeltOptions::new_amountless(cdk_amount)
            }
        }
    }
}

impl From<cdk::nuts::MeltOptions> for MeltOptions {
    fn from(opts: cdk::nuts::MeltOptions) -> Self {
        match opts {
            cdk::nuts::MeltOptions::Mpp { mpp } => MeltOptions::Mpp {
                amount: mpp.amount.into(),
            },
            cdk::nuts::MeltOptions::Amountless { amountless } => MeltOptions::Amountless {
                amount_msat: amountless.amount_msat.into(),
            },
        }
    }
}

/// Restored Data
#[derive(Debug, Clone, uniffi::Record)]
pub struct Restored {
    pub spent: Amount,
    pub unspent: Amount,
    pub pending: Amount,
}

impl From<cdk_common::wallet::Restored> for Restored {
    fn from(restored: cdk_common::wallet::Restored) -> Self {
        Self {
            spent: restored.spent.into(),
            unspent: restored.unspent.into(),
            pending: restored.pending.into(),
        }
    }
}

/// Report of wallet saga recovery operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, uniffi::Record)]
pub struct RecoveryReport {
    /// Operations successfully completed after crash.
    pub recovered: u64,
    /// Operations rolled back and resources released.
    pub compensated: u64,
    /// Operations still pending and left for a later retry.
    pub skipped: u64,
    /// Operations that could not be recovered.
    pub failed: u64,
}

impl From<cdk::wallet::RecoveryReport> for RecoveryReport {
    fn from(report: cdk::wallet::RecoveryReport) -> Self {
        Self {
            recovered: report.recovered as u64,
            compensated: report.compensated as u64,
            skipped: report.skipped as u64,
            failed: report.failed as u64,
        }
    }
}

/// FFI-compatible options for confirming a melt operation
#[derive(Debug, Clone, Default, Serialize, Deserialize, uniffi::Record)]
pub struct MeltConfirmOptions {
    /// Skip the pre-melt swap and send proofs directly to melt.
    /// When true, saves swap input fees but gets change from melt instead.
    pub skip_swap: bool,
}

impl From<MeltConfirmOptions> for cdk::wallet::MeltConfirmOptions {
    fn from(opts: MeltConfirmOptions) -> Self {
        cdk::wallet::MeltConfirmOptions {
            skip_swap: opts.skip_swap,
        }
    }
}

impl From<cdk::wallet::MeltConfirmOptions> for MeltConfirmOptions {
    fn from(opts: cdk::wallet::MeltConfirmOptions) -> Self {
        Self {
            skip_swap: opts.skip_swap,
        }
    }
}

/// FFI-compatible WalletKey
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
pub struct WalletKey {
    /// Mint Url
    pub mint_url: MintUrl,
    /// Currency Unit
    pub unit: CurrencyUnit,
}

impl TryFrom<WalletKey> for cdk::WalletKey {
    type Error = FfiError;

    fn try_from(value: WalletKey) -> Result<Self, Self::Error> {
        Ok(Self {
            mint_url: value.mint_url.try_into()?,
            unit: value.unit.into(),
        })
    }
}

impl From<cdk::WalletKey> for WalletKey {
    fn from(value: cdk::WalletKey) -> Self {
        Self {
            mint_url: value.mint_url.into(),
            unit: value.unit.into(),
        }
    }
}