agent-first-pay 0.7.0

A payment tool for AI agents — send and receive across five networks through one interface, with spending limits you control.
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
use crate::provider::{HistorySyncStats, PayError, PayProvider};
use crate::store::wallet::{self, WalletMetadata};
use crate::store::{PayStore, StorageBackend};
use crate::types::*;
use async_trait::async_trait;
use std::sync::Arc;

#[cfg(feature = "ln-lnbits")]
mod lnbits;
#[cfg(feature = "ln-nwc")]
mod nwc;
#[cfg(feature = "ln-phoenixd")]
mod phoenixd;

// ═══════════════════════════════════════════
// LnBackend — internal trait for each backend
// ═══════════════════════════════════════════

#[derive(Debug, Clone)]
pub(crate) struct LnPayResult {
    pub confirmed_amount_sats: u64,
    pub fee_msats: Option<u64>,
    pub preimage: Option<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct LnInvoiceResult {
    pub bolt11: String,
    pub payment_hash: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum LnPaymentStatus {
    Pending,
    Paid,
    Failed,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum LnInvoiceStatus {
    Pending,
    Paid { confirmed_amount_sats: u64 },
    Failed,
    Unknown,
}

#[derive(Debug, Clone)]
pub(crate) struct LnPaymentInfo {
    pub payment_hash: String,
    pub amount_msats: u64,
    pub is_outgoing: bool,
    pub status: LnPaymentStatus,
    pub created_at_epoch_s: u64,
    pub memo: Option<String>,
    pub preimage: Option<String>,
}

#[async_trait]
pub(crate) trait LnBackend: Send + Sync {
    async fn pay_invoice(
        &self,
        bolt11: &str,
        amount_msats: Option<u64>,
    ) -> Result<LnPayResult, PayError>;

    async fn create_invoice(
        &self,
        amount_sats: u64,
        memo: Option<&str>,
    ) -> Result<LnInvoiceResult, PayError>;

    async fn invoice_status(&self, payment_hash: &str) -> Result<LnInvoiceStatus, PayError>;

    async fn get_balance(&self) -> Result<BalanceInfo, PayError>;

    async fn list_payments(
        &self,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<LnPaymentInfo>, PayError>;

    async fn get_default_offer(&self) -> Result<String, PayError> {
        Err(PayError::NotImplemented(
            "bolt12 offers not supported by this backend".to_string(),
        ))
    }

    async fn pay_offer(
        &self,
        _offer: &str,
        _amount_sats: u64,
        _message: Option<&str>,
    ) -> Result<LnPayResult, PayError> {
        Err(PayError::NotImplemented(
            "bolt12 offers not supported by this backend".to_string(),
        ))
    }
}

// ═══════════════════════════════════════════
// LnProvider — PayProvider implementation
// ═══════════════════════════════════════════

fn ln_wallet_summary(m: &WalletMetadata) -> WalletSummary {
    let backend = m.backend.clone().unwrap_or_else(|| "unknown".to_string());
    WalletSummary {
        id: m.id.clone(),
        network: Network::Ln,
        label: m.label.clone(),
        address: format!("ln:{backend}"),
        backend: Some(backend),
        mint_url: None,
        rpc_endpoints: None,
        chain_id: None,
        created_at_epoch_s: m.created_at_epoch_s,
    }
}

pub struct LnProvider {
    _data_dir: String,
    store: Arc<StorageBackend>,
}

impl LnProvider {
    pub fn new(data_dir: &str, store: Arc<StorageBackend>) -> Self {
        Self {
            _data_dir: data_dir.to_string(),
            store,
        }
    }

    fn resolve_backend(&self, meta: &WalletMetadata) -> Result<Box<dyn LnBackend>, PayError> {
        let backend_name = meta.backend.as_deref().ok_or_else(|| {
            PayError::InternalError("ln wallet missing backend field".to_string())
        })?;

        #[cfg(feature = "ln-nwc")]
        if backend_name == "nwc" {
            let secret = meta.seed_secret.as_deref().unwrap_or("");
            return Ok(Box::new(nwc::NwcBackend::new(secret)?));
        }
        #[cfg(feature = "ln-phoenixd")]
        if backend_name == "phoenixd" {
            let endpoint = meta.mint_url.as_deref().unwrap_or("");
            let secret = meta.seed_secret.as_deref().unwrap_or("");
            return Ok(Box::new(phoenixd::PhoenixdBackend::new(endpoint, secret)));
        }
        #[cfg(feature = "ln-lnbits")]
        if backend_name == "lnbits" {
            let endpoint = meta.mint_url.as_deref().unwrap_or("");
            let secret = meta.seed_secret.as_deref().unwrap_or("");
            return Ok(Box::new(lnbits::LnbitsBackend::new(endpoint, secret)));
        }

        Err(PayError::NotImplemented(format!(
            "ln backend '{backend_name}' not enabled"
        )))
    }

    fn load_ln_wallet(&self, wallet_id: &str) -> Result<WalletMetadata, PayError> {
        let meta = self.store.load_wallet_metadata(wallet_id)?;
        if meta.network != Network::Ln {
            return Err(PayError::WalletNotFound(format!(
                "{wallet_id} is not a ln wallet"
            )));
        }
        Ok(meta)
    }

    /// Find a LN wallet — if wallet_id is empty, pick the first available.
    fn resolve_wallet_id(&self, wallet_id: &str) -> Result<String, PayError> {
        if !wallet_id.is_empty() {
            return Ok(wallet_id.to_string());
        }
        let wallets = self.store.list_wallet_metadata(Some(Network::Ln))?;
        wallets
            .first()
            .map(|w| w.id.clone())
            .ok_or_else(|| PayError::WalletNotFound("no ln wallet found".to_string()))
    }

    fn validate_backend_enabled(backend: LnWalletBackend) -> Result<(), PayError> {
        #[allow(unreachable_patterns)]
        let enabled = match backend {
            #[cfg(feature = "ln-nwc")]
            LnWalletBackend::Nwc => true,
            #[cfg(feature = "ln-phoenixd")]
            LnWalletBackend::Phoenixd => true,
            #[cfg(feature = "ln-lnbits")]
            LnWalletBackend::Lnbits => true,
            _ => false,
        };
        if !enabled {
            return Err(PayError::NotImplemented(format!(
                "backend '{}' not compiled; rebuild with --features {}",
                backend.as_str(),
                backend.as_str()
            )));
        }
        Ok(())
    }

    fn has_value(value: Option<&str>) -> bool {
        value.map(|v| !v.trim().is_empty()).unwrap_or(false)
    }

    fn require_field(
        backend: LnWalletBackend,
        field_name: &str,
        value: Option<String>,
    ) -> Result<String, PayError> {
        if Self::has_value(value.as_deref()) {
            return Ok(value.unwrap_or_default());
        }
        Err(PayError::InvalidAmount(format!(
            "{} backend requires --{}",
            backend.as_str(),
            field_name
        )))
    }

    fn reject_field(
        backend: LnWalletBackend,
        field_name: &str,
        value: Option<&str>,
    ) -> Result<(), PayError> {
        if Self::has_value(value) {
            return Err(PayError::InvalidAmount(format!(
                "{} backend does not accept --{}",
                backend.as_str(),
                field_name
            )));
        }
        Ok(())
    }

    async fn validate_backend_credentials(
        &self,
        backend: LnWalletBackend,
        endpoint: Option<String>,
        secret: Option<String>,
        label: Option<String>,
    ) -> Result<(), PayError> {
        let probe_meta = WalletMetadata {
            id: "__probe__".to_string(),
            network: Network::Ln,
            label,
            mint_url: endpoint,
            sol_rpc_endpoints: None,
            evm_rpc_endpoints: None,
            evm_chain_id: None,
            seed_secret: secret,
            backend: Some(backend.as_str().to_string()),
            btc_esplora_url: None,
            btc_network: None,
            btc_address_type: None,
            btc_core_url: None,
            btc_core_auth_secret: None,
            btc_electrum_url: None,
            custom_tokens: None,
            created_at_epoch_s: 0,
            error: None,
        };
        let backend_impl = self.resolve_backend(&probe_meta)?;
        backend_impl.get_balance().await.map(|_| ()).map_err(|e| {
            PayError::NetworkError(format!(
                "{} backend validation failed: {}",
                backend.as_str(),
                e
            ))
        })
    }
}

#[async_trait]
impl PayProvider for LnProvider {
    fn network(&self) -> Network {
        Network::Ln
    }

    fn writes_locally(&self) -> bool {
        true
    }

    async fn create_wallet(&self, _request: &WalletCreateRequest) -> Result<WalletInfo, PayError> {
        Err(PayError::InvalidAmount(
            "ln wallets must be created with ln_wallet_create parameters".to_string(),
        ))
    }

    async fn create_ln_wallet(
        &self,
        request: LnWalletCreateRequest,
    ) -> Result<WalletInfo, PayError> {
        Self::validate_backend_enabled(request.backend)?;

        let backend = request.backend;
        let label = request.label.as_deref().unwrap_or("default").trim();
        let wallet_label = if label.is_empty() || label == "default" {
            None
        } else {
            Some(label.to_string())
        };

        let (endpoint, secret) = match backend {
            LnWalletBackend::Nwc => {
                Self::reject_field(backend, "endpoint", request.endpoint.as_deref())?;
                Self::reject_field(
                    backend,
                    "password-secret",
                    request.password_secret.as_deref(),
                )?;
                Self::reject_field(
                    backend,
                    "admin-key-secret",
                    request.admin_key_secret.as_deref(),
                )?;
                let nwc_uri =
                    Self::require_field(backend, "nwc-uri-secret", request.nwc_uri_secret)?;
                (None, Some(nwc_uri))
            }
            LnWalletBackend::Phoenixd => {
                Self::reject_field(backend, "nwc-uri-secret", request.nwc_uri_secret.as_deref())?;
                Self::reject_field(
                    backend,
                    "admin-key-secret",
                    request.admin_key_secret.as_deref(),
                )?;
                let endpoint = Self::require_field(backend, "endpoint", request.endpoint)?;
                let password =
                    Self::require_field(backend, "password-secret", request.password_secret)?;
                (Some(endpoint), Some(password))
            }
            LnWalletBackend::Lnbits => {
                Self::reject_field(backend, "nwc-uri-secret", request.nwc_uri_secret.as_deref())?;
                Self::reject_field(
                    backend,
                    "password-secret",
                    request.password_secret.as_deref(),
                )?;
                let endpoint = Self::require_field(backend, "endpoint", request.endpoint)?;
                let admin_key =
                    Self::require_field(backend, "admin-key-secret", request.admin_key_secret)?;
                (Some(endpoint), Some(admin_key))
            }
        };

        self.validate_backend_credentials(
            backend,
            endpoint.clone(),
            secret.clone(),
            wallet_label.clone(),
        )
        .await?;

        let id = wallet::generate_wallet_identifier()?;
        let meta = WalletMetadata {
            id: id.clone(),
            network: Network::Ln,
            label: wallet_label,
            mint_url: endpoint,
            sol_rpc_endpoints: None,
            evm_rpc_endpoints: None,
            evm_chain_id: None,
            seed_secret: secret,
            backend: Some(backend.as_str().to_string()),
            btc_esplora_url: None,
            btc_network: None,
            btc_address_type: None,
            btc_core_url: None,
            btc_core_auth_secret: None,
            btc_electrum_url: None,
            custom_tokens: None,
            created_at_epoch_s: wallet::now_epoch_seconds(),
            error: None,
        };
        self.store.save_wallet_metadata(&meta)?;

        Ok(WalletInfo {
            id,
            network: Network::Ln,
            address: format!("ln:{}", backend.as_str()),
            label: meta.label,
            mnemonic: None,
        })
    }

    async fn close_wallet(&self, wallet_id: &str) -> Result<(), PayError> {
        let meta = self.load_ln_wallet(wallet_id)?;
        // Check balance — only allow closing zero-balance wallets
        let backend = self.resolve_backend(&meta)?;
        let balance = backend.get_balance().await?;
        let non_zero_components = balance.non_zero_components();
        if !non_zero_components.is_empty() {
            let component_list = non_zero_components
                .iter()
                .map(|(name, value)| format!("{name}={value}sats"))
                .collect::<Vec<_>>()
                .join(", ");
            return Err(PayError::InvalidAmount(format!(
                "wallet {wallet_id} has non-zero balance components ({component_list}); withdraw first"
            )));
        }
        self.store.delete_wallet_metadata(wallet_id)?;
        Ok(())
    }

    async fn list_wallets(&self) -> Result<Vec<WalletSummary>, PayError> {
        let wallets = self.store.list_wallet_metadata(Some(Network::Ln))?;
        Ok(wallets.iter().map(ln_wallet_summary).collect())
    }

    async fn balance(&self, wallet_id: &str) -> Result<BalanceInfo, PayError> {
        let meta = self.load_ln_wallet(wallet_id)?;
        let backend = self.resolve_backend(&meta)?;
        backend.get_balance().await
    }

    async fn balance_all(&self) -> Result<Vec<WalletBalanceItem>, PayError> {
        let wallets = self.store.list_wallet_metadata(Some(Network::Ln))?;
        let mut items = Vec::new();
        for meta in &wallets {
            let (balance, error) = match self.resolve_backend(meta) {
                Ok(backend) => match backend.get_balance().await {
                    Ok(balance) => (Some(balance), None),
                    Err(error) => (None, Some(error.to_string())),
                },
                Err(error) => (None, Some(error.to_string())),
            };
            items.push(WalletBalanceItem {
                wallet: ln_wallet_summary(meta),
                balance,
                error,
            });
        }
        Ok(items)
    }

    async fn receive_info(
        &self,
        wallet_id: &str,
        amount: Option<Amount>,
    ) -> Result<ReceiveInfo, PayError> {
        let resolved_wallet_id = if wallet_id.trim().is_empty() {
            let wallets = self.store.list_wallet_metadata(Some(Network::Ln))?;
            match wallets.len() {
                0 => return Err(PayError::WalletNotFound("no ln wallet found".to_string())),
                1 => wallets[0].id.clone(),
                _ => {
                    return Err(PayError::InvalidAmount(
                        "multiple ln wallets found; pass --wallet".to_string(),
                    ))
                }
            }
        } else {
            wallet_id.to_string()
        };

        let meta = self.load_ln_wallet(&resolved_wallet_id)?;
        let backend = self.resolve_backend(&meta)?;

        match amount.as_ref().map(|a| a.value) {
            Some(amount_sats) => {
                // BOLT11: amount-specific one-time invoice
                let result = backend.create_invoice(amount_sats, None).await?;
                Ok(ReceiveInfo {
                    address: None,
                    invoice: Some(result.bolt11),
                    quote_id: Some(result.payment_hash),
                })
            }
            None => {
                // BOLT12: persistent reusable offer (phoenixd only)
                let offer = backend.get_default_offer().await?;
                Ok(ReceiveInfo {
                    address: Some(offer),
                    invoice: None,
                    quote_id: None,
                })
            }
        }
    }

    async fn receive_claim(&self, wallet_id: &str, quote_id: &str) -> Result<u64, PayError> {
        let meta = self.load_ln_wallet(wallet_id)?;
        let backend = self.resolve_backend(&meta)?;
        match backend.invoice_status(quote_id).await? {
            LnInvoiceStatus::Paid {
                confirmed_amount_sats,
            } => {
                // Record a local receive tx once so tx_status/history remain consistent
                // even when backend history APIs are unavailable.
                if self
                    .store
                    .find_transaction_record_by_id(quote_id)?
                    .is_none()
                {
                    let now = wallet::now_epoch_seconds();
                    let record = HistoryRecord {
                        transaction_id: quote_id.to_string(),
                        wallet: wallet_id.to_string(),
                        network: Network::Ln,
                        direction: Direction::Receive,
                        amount: Amount {
                            value: confirmed_amount_sats,
                            token: "sats".to_string(),
                        },
                        status: TxStatus::Confirmed,
                        onchain_memo: Some("ln receive".to_string()),
                        local_memo: None,
                        remote_addr: None,
                        preimage: None,
                        created_at_epoch_s: now,
                        confirmed_at_epoch_s: Some(now),
                        fee: None,
                        reference_keys: None,
                    };
                    let _ = self.store.append_transaction_record(&record);
                }
                Ok(confirmed_amount_sats)
            }
            LnInvoiceStatus::Pending => {
                Err(PayError::NetworkError("invoice not yet paid".to_string()))
            }
            LnInvoiceStatus::Failed => {
                Err(PayError::NetworkError("invoice payment failed".to_string()))
            }
            LnInvoiceStatus::Unknown => {
                Err(PayError::NetworkError("invoice status unknown".to_string()))
            }
        }
    }

    async fn cashu_send(
        &self,
        _wallet: &str,
        _amount: Amount,
        _memo: Option<&str>,
        _mints: Option<&[String]>,
    ) -> Result<CashuSendResult, PayError> {
        Err(PayError::NotImplemented(
            "ln does not support bearer-token send; use `ln send --to <bolt11>`".to_string(),
        ))
    }

    async fn cashu_receive(
        &self,
        _wallet: &str,
        _token: &str,
    ) -> Result<CashuReceiveResult, PayError> {
        Err(PayError::NotImplemented(
            "ln does not support token receive; use `ln receive --amount-sats <amount>`"
                .to_string(),
        ))
    }

    async fn send_quote(
        &self,
        wallet_id: &str,
        to: &str,
        _mints: Option<&[String]>,
    ) -> Result<SendQuoteInfo, PayError> {
        let resolved = self.resolve_wallet_id(wallet_id)?;
        if is_bolt12_offer(to) {
            return Err(PayError::InvalidAmount(
                "bolt12 offers do not embed an amount; pass --amount-sats when sending to an offer"
                    .to_string(),
            ));
        }
        let amount_sats = parse_bolt11_amount_sats(to)?;
        let fee_estimate = (amount_sats / 100).max(1);
        Ok(SendQuoteInfo {
            wallet: resolved,
            amount_native: amount_sats,
            fee_estimate_native: fee_estimate,
            fee_unit: "sats".to_string(),
            spend_debits: vec![SpendDebit {
                amount_native: amount_sats.saturating_add(fee_estimate),
                token: None,
            }],
        })
    }

    async fn send(
        &self,
        wallet_id: &str,
        to: &str,
        onchain_memo: Option<&str>,
        _mints: Option<&[String]>,
    ) -> Result<SendResult, PayError> {
        let resolved = self.resolve_wallet_id(wallet_id)?;
        let meta = self.load_ln_wallet(&resolved)?;
        let backend = self.resolve_backend(&meta)?;

        let result = if is_bolt12_offer(to) {
            let (offer, amount_opt) = parse_bolt12_offer_parts(to);
            let amount_sats = amount_opt.ok_or_else(|| {
                PayError::InvalidAmount(
                    "amount-sats is required when sending to a bolt12 offer (use --amount)"
                        .to_string(),
                )
            })?;
            backend.pay_offer(&offer, amount_sats, None).await?
        } else {
            backend.pay_invoice(to, None).await?
        };

        let transaction_id = if is_bolt12_offer(to) {
            wallet::generate_transaction_identifier().unwrap_or_else(|_| "tx_unknown".to_string())
        } else {
            parse_bolt11_payment_hash(to).unwrap_or_else(|_| {
                wallet::generate_transaction_identifier()
                    .unwrap_or_else(|_| "tx_unknown".to_string())
            })
        };

        if result.confirmed_amount_sats == 0 {
            return Err(PayError::NetworkError(
                "backend did not return confirmed payment amount".to_string(),
            ));
        }

        let fee_sats = result.fee_msats.map(|f| f / 1000);
        let amount = Amount {
            value: result.confirmed_amount_sats,
            token: "sats".to_string(),
        };

        let fee_amount = fee_sats.filter(|&f| f > 0).map(|f| Amount {
            value: f,
            token: "sats".to_string(),
        });
        let record = HistoryRecord {
            transaction_id: transaction_id.clone(),
            wallet: resolved.clone(),
            network: Network::Ln,
            direction: Direction::Send,
            amount: amount.clone(),
            status: TxStatus::Confirmed,
            onchain_memo: onchain_memo
                .map(|s| s.to_string())
                .or(Some("ln send".to_string())),
            local_memo: None,
            remote_addr: Some(to.to_string()),
            preimage: result.preimage.clone(),
            created_at_epoch_s: wallet::now_epoch_seconds(),
            confirmed_at_epoch_s: Some(wallet::now_epoch_seconds()),
            fee: fee_amount.clone(),
            reference_keys: None,
        };
        let _ = self.store.append_transaction_record(&record);

        Ok(SendResult {
            wallet: resolved,
            transaction_id,
            amount,
            fee: fee_amount,
            preimage: result.preimage,
        })
    }

    async fn history_list(
        &self,
        wallet_id: &str,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<HistoryRecord>, PayError> {
        let meta = self.load_ln_wallet(wallet_id)?;
        // Try backend first, fall back to local transaction log store
        if let Ok(backend) = self.resolve_backend(&meta) {
            if let Ok(payments) = backend.list_payments(limit, offset).await {
                return Ok(payments
                    .into_iter()
                    .map(|p| HistoryRecord {
                        transaction_id: p.payment_hash.clone(),
                        wallet: wallet_id.to_string(),
                        network: Network::Ln,
                        direction: if p.is_outgoing {
                            Direction::Send
                        } else {
                            Direction::Receive
                        },
                        amount: Amount {
                            value: p.amount_msats / 1000,
                            token: "sats".to_string(),
                        },
                        status: match p.status {
                            LnPaymentStatus::Paid => TxStatus::Confirmed,
                            LnPaymentStatus::Pending => TxStatus::Pending,
                            LnPaymentStatus::Failed => TxStatus::Failed,
                            LnPaymentStatus::Unknown => TxStatus::Pending,
                        },
                        onchain_memo: p.memo,
                        local_memo: None,
                        remote_addr: None,
                        preimage: p.preimage,
                        created_at_epoch_s: p.created_at_epoch_s,
                        confirmed_at_epoch_s: if p.status == LnPaymentStatus::Paid {
                            Some(p.created_at_epoch_s)
                        } else {
                            None
                        },
                        fee: None,
                        reference_keys: None,
                    })
                    .collect());
            }
        }
        // Fallback to local transaction log store
        let all = self.store.load_wallet_transaction_records(wallet_id)?;
        let end = all.len().min(offset + limit);
        let start = all.len().min(offset);
        Ok(all[start..end].to_vec())
    }

    async fn history_status(&self, transaction_id: &str) -> Result<HistoryStatusInfo, PayError> {
        match self.store.find_transaction_record_by_id(transaction_id)? {
            Some(rec) => Ok(HistoryStatusInfo {
                transaction_id: rec.transaction_id.clone(),
                status: rec.status,
                confirmations: None,
                preimage: rec.preimage.clone(),
                item: Some(rec),
            }),
            None => {
                // Backend fallback: scan LN wallets and query both invoice-status and payments.
                let wallets = self.store.list_wallet_metadata(Some(Network::Ln))?;
                for w in &wallets {
                    let meta = self.load_ln_wallet(&w.id)?;
                    let backend = match self.resolve_backend(&meta) {
                        Ok(b) => b,
                        Err(_) => continue,
                    };
                    match backend.invoice_status(transaction_id).await {
                        Ok(LnInvoiceStatus::Paid { .. }) => {
                            return Ok(HistoryStatusInfo {
                                transaction_id: transaction_id.to_string(),
                                status: TxStatus::Confirmed,
                                confirmations: None,
                                preimage: None,
                                item: None,
                            });
                        }
                        Ok(LnInvoiceStatus::Pending) => {
                            return Ok(HistoryStatusInfo {
                                transaction_id: transaction_id.to_string(),
                                status: TxStatus::Pending,
                                confirmations: None,
                                preimage: None,
                                item: None,
                            });
                        }
                        Ok(LnInvoiceStatus::Failed) => {
                            return Ok(HistoryStatusInfo {
                                transaction_id: transaction_id.to_string(),
                                status: TxStatus::Failed,
                                confirmations: None,
                                preimage: None,
                                item: None,
                            });
                        }
                        Ok(LnInvoiceStatus::Unknown) | Err(_) => {}
                    }

                    if let Ok(payments) = backend.list_payments(200, 0).await {
                        if let Some(p) = payments
                            .into_iter()
                            .find(|p| p.payment_hash == transaction_id)
                        {
                            let status = match p.status {
                                LnPaymentStatus::Paid => TxStatus::Confirmed,
                                LnPaymentStatus::Pending | LnPaymentStatus::Unknown => {
                                    TxStatus::Pending
                                }
                                LnPaymentStatus::Failed => TxStatus::Failed,
                            };
                            let item = HistoryRecord {
                                transaction_id: p.payment_hash.clone(),
                                wallet: w.id.clone(),
                                network: Network::Ln,
                                direction: if p.is_outgoing {
                                    Direction::Send
                                } else {
                                    Direction::Receive
                                },
                                amount: Amount {
                                    value: p.amount_msats / 1000,
                                    token: "sats".to_string(),
                                },
                                status,
                                onchain_memo: p.memo.clone(),
                                local_memo: None,
                                remote_addr: None,
                                preimage: p.preimage.clone(),
                                created_at_epoch_s: p.created_at_epoch_s,
                                confirmed_at_epoch_s: if p.status == LnPaymentStatus::Paid {
                                    Some(p.created_at_epoch_s)
                                } else {
                                    None
                                },
                                fee: None,
                                reference_keys: None,
                            };
                            return Ok(HistoryStatusInfo {
                                transaction_id: transaction_id.to_string(),
                                status,
                                confirmations: None,
                                preimage: p.preimage,
                                item: Some(item),
                            });
                        }
                    }
                }
                Err(PayError::WalletNotFound(format!(
                    "transaction {transaction_id} not found"
                )))
            }
        }
    }

    async fn history_sync(
        &self,
        wallet_id: &str,
        limit: usize,
    ) -> Result<HistorySyncStats, PayError> {
        let resolved = self.resolve_wallet_id(wallet_id)?;
        let meta = self.load_ln_wallet(&resolved)?;
        let backend = self.resolve_backend(&meta)?;
        let payments = backend.list_payments(limit, 0).await?;

        let mut stats = HistorySyncStats {
            records_scanned: payments.len(),
            records_added: 0,
            records_updated: 0,
        };

        for payment in payments {
            let status = match payment.status {
                LnPaymentStatus::Paid => TxStatus::Confirmed,
                LnPaymentStatus::Pending | LnPaymentStatus::Unknown => TxStatus::Pending,
                LnPaymentStatus::Failed => TxStatus::Failed,
            };
            let confirmed_at_epoch_s = if status == TxStatus::Confirmed {
                Some(payment.created_at_epoch_s)
            } else {
                None
            };

            match self
                .store
                .find_transaction_record_by_id(&payment.payment_hash)?
            {
                Some(existing) => {
                    if existing.status != status
                        || existing.confirmed_at_epoch_s != confirmed_at_epoch_s
                    {
                        let _ = self.store.update_transaction_record_status(
                            &payment.payment_hash,
                            status,
                            confirmed_at_epoch_s,
                        );
                        stats.records_updated = stats.records_updated.saturating_add(1);
                    }
                }
                None => {
                    let record = HistoryRecord {
                        transaction_id: payment.payment_hash.clone(),
                        wallet: resolved.clone(),
                        network: Network::Ln,
                        direction: if payment.is_outgoing {
                            Direction::Send
                        } else {
                            Direction::Receive
                        },
                        amount: Amount {
                            value: payment.amount_msats / 1000,
                            token: "sats".to_string(),
                        },
                        status,
                        onchain_memo: payment.memo.clone(),
                        local_memo: None,
                        remote_addr: None,
                        preimage: payment.preimage.clone(),
                        created_at_epoch_s: payment.created_at_epoch_s,
                        confirmed_at_epoch_s,
                        fee: None,
                        reference_keys: None,
                    };
                    let _ = self.store.append_transaction_record(&record);
                    stats.records_added = stats.records_added.saturating_add(1);
                }
            }
        }

        Ok(stats)
    }
}

pub(crate) fn parse_bolt11_amount_sats(bolt11: &str) -> Result<u64, PayError> {
    let invoice: lightning_invoice::Bolt11Invoice = bolt11
        .parse()
        .map_err(|e| PayError::InvalidAmount(format!("invalid bolt11 invoice: {e}")))?;
    let amount_msats = invoice.amount_milli_satoshis().ok_or_else(|| {
        PayError::InvalidAmount("bolt11 invoice does not include amount".to_string())
    })?;
    Ok(amount_msats.saturating_add(999) / 1000)
}

pub(crate) fn parse_bolt11_payment_hash(bolt11: &str) -> Result<String, PayError> {
    let invoice: lightning_invoice::Bolt11Invoice = bolt11
        .parse()
        .map_err(|e| PayError::InvalidAmount(format!("invalid bolt11 invoice: {e}")))?;
    Ok(invoice.payment_hash().to_string())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn reject_field_detects_wrong_parameter() {
        let err =
            LnProvider::reject_field(LnWalletBackend::Phoenixd, "admin-key-secret", Some("x"))
                .expect_err("phoenixd should reject admin-key-secret");
        assert!(err
            .to_string()
            .contains("does not accept --admin-key-secret"));
    }

    #[test]
    fn parse_bolt11_payment_hash_invalid() {
        assert!(parse_bolt11_payment_hash("not-an-invoice").is_err());
    }

    #[test]
    fn bolt12_offer_detected_case_insensitive() {
        assert!(is_bolt12_offer("lno1qgsqvgjwcf6qqz9"));
        assert!(is_bolt12_offer("LNO1QGSQVGJWCF6QQZ9"));
        assert!(is_bolt12_offer("lno1abc?amount=100"));
        assert!(!is_bolt12_offer("lnbc1qgsq"));
    }

    #[test]
    fn bolt12_offer_parts_split() {
        let (offer, amt) = parse_bolt12_offer_parts("lno1abc?amount=500");
        assert_eq!(offer, "lno1abc");
        assert_eq!(amt, Some(500));

        let (offer, amt) = parse_bolt12_offer_parts("lno1abc");
        assert_eq!(offer, "lno1abc");
        assert_eq!(amt, None);
    }

    #[test]
    fn bolt12_not_bolt11() {
        // bolt12 offers should not parse as bolt11
        assert!(parse_bolt11_amount_sats("lno1abc").is_err());
        assert!(parse_bolt11_payment_hash("lno1abc").is_err());
    }
}