-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAppViewModel.swift
More file actions
972 lines (840 loc) · 40.6 KB
/
AppViewModel.swift
File metadata and controls
972 lines (840 loc) · 40.6 KB
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
import BitkitCore
import Combine
import LDKNode
import SwiftUI
/// Published when a payment shown on the pending screen succeeds or fails.
/// SendPendingScreen observes this and navigates accordingly.
struct SendSheetPendingResolution: Equatable {
let paymentHash: String
let success: Bool
}
enum ManualEntryValidationResult: Equatable {
case valid
case empty
case invalid
case insufficientSavings
case insufficientSpending
case expiredLightningOnly
}
@MainActor
class AppViewModel: ObservableObject {
// Send flow
@Published var scannedLightningInvoice: LightningInvoice?
@Published var scannedOnchainInvoice: OnChainInvoice?
@Published var selectedWalletToPayFrom: WalletType = .onchain
@Published var manualEntryInput: String = ""
@Published var isManualEntryInputValid: Bool = false
@Published var manualEntryValidationResult: ManualEntryValidationResult = .empty
// LNURL
@Published var lnurlPayData: LnurlPayData?
@Published var lnurlWithdrawData: LnurlWithdrawData?
// Onboarding
@AppStorage("hasDismissedWidgetsOnboardingHint") var hasDismissedWidgetsOnboardingHint: Bool = false
@AppStorage("hasSeenContactsIntro") var hasSeenContactsIntro: Bool = false
@AppStorage("hasSeenProfileIntro") var hasSeenProfileIntro: Bool = false
@AppStorage("hasSeenNotificationsIntro") var hasSeenNotificationsIntro: Bool = false
@AppStorage("hasSeenQuickpayIntro") var hasSeenQuickpayIntro: Bool = false
@AppStorage("hasSeenShopIntro") var hasSeenShopIntro: Bool = false
@AppStorage("hasSeenTransferIntro") var hasSeenTransferIntro: Bool = false
@AppStorage("hasSeenTransferToSpendingIntro") var hasSeenTransferToSpendingIntro: Bool = false
@AppStorage("hasSeenTransferToSavingsIntro") var hasSeenTransferToSavingsIntro: Bool = false
@AppStorage("hasSeenWidgetsIntro") var hasSeenWidgetsIntro: Bool = false
/// App update tracking
@AppStorage("appUpdateIgnoreTimestamp") var appUpdateIgnoreTimestamp: TimeInterval = 0
// Backup warning tracking
@AppStorage("backupVerified") var backupVerified: Bool = false
@AppStorage("backupIgnoreTimestamp") var backupIgnoreTimestamp: TimeInterval = 0
// High balance warning tracking
@AppStorage("highBalanceIgnoreCount") var highBalanceIgnoreCount: Int = 0
@AppStorage("highBalanceIgnoreTimestamp") var highBalanceIgnoreTimestamp: TimeInterval = 0
/// Drawer menu
@Published var showDrawer = false
/// Payment hashes for which we navigated to the pending screen.
/// When payment succeeds/fails, we show toast and publish resolution so SendPendingScreen can navigate.
private var pendingPaymentHashes: Set<String> = []
/// When a payment that was shown on the pending screen succeeds or fails, this is set so SendPendingScreen can navigate.
/// Consumed by SendPendingScreen via consumeSendSheetPendingResolution.
@Published var sendSheetPendingResolution: SendSheetPendingResolution?
/// App status init - shows "ready" until node is actually running
/// This prevents flashing error status during startup/background transitions
@Published var appStatusInit: Bool = false
/// Called when node reaches running state
func markAppStatusInit() {
appStatusInit = true
}
/// Called when app goes to background to reset the status facade
func resetAppStatusInit() {
appStatusInit = false
}
private let lightningService: LightningService
private let coreService: CoreService
private let sheetViewModel: SheetViewModel
private let navigationViewModel: NavigationViewModel
private var manualEntryValidationSequence: UInt64 = 0
// Combine infrastructure for debounced validation
private var manualEntryValidationCancellable: AnyCancellable?
private let manualEntryValidationSubject = PassthroughSubject<(String, Int, Int, UInt64), Never>()
init(
lightningService: LightningService = .shared,
coreService: CoreService = .shared,
sheetViewModel: SheetViewModel,
navigationViewModel: NavigationViewModel
) {
self.lightningService = lightningService
self.coreService = coreService
self.sheetViewModel = sheetViewModel
self.navigationViewModel = navigationViewModel
setupManualEntryValidationDebounce()
Task {
await checkGeoStatus()
// Check for app updates on startup
await AppUpdateService.shared.checkForAppUpdate()
}
}
private func setupManualEntryValidationDebounce() {
manualEntryValidationCancellable = manualEntryValidationSubject
.debounce(for: .milliseconds(1000), scheduler: DispatchQueue.main)
.sink { [weak self] rawValue, savingsBalanceSats, spendingBalanceSats, queuedSequence in
guard let self else { return }
// Skip if sequence changed (reset was called or new validation queued)
guard queuedSequence == manualEntryValidationSequence else { return }
Task {
await self.performValidation(rawValue, savingsBalanceSats: savingsBalanceSats, spendingBalanceSats: spendingBalanceSats)
}
}
}
/// Shows insufficient spending balance toast with amount-specific or generic description
private func showInsufficientSpendingToast(invoiceAmount: UInt64, spendingBalance: UInt64) {
let amountNeeded = invoiceAmount > spendingBalance ? invoiceAmount - spendingBalance : 0
let description = amountNeeded > 0
? t(
"other__pay_insufficient_spending_amount_description",
variables: ["amount": CurrencyFormatter.formatSats(amountNeeded)]
)
: t("other__pay_insufficient_spending_description")
toast(
type: .error,
title: t("other__pay_insufficient_spending"),
description: description,
accessibilityIdentifier: "InsufficientSpendingToast"
)
}
/// Validates onchain balance and shows toast if insufficient. Returns true if sufficient.
private func validateOnchainBalance(invoiceAmount: UInt64, onchainBalance: UInt64) -> Bool {
if invoiceAmount > 0 {
guard onchainBalance >= invoiceAmount else {
let amountNeeded = invoiceAmount - onchainBalance
toast(
type: .error,
title: t("other__pay_insufficient_savings"),
description: t(
"other__pay_insufficient_savings_amount_description",
variables: ["amount": CurrencyFormatter.formatSats(amountNeeded)]
),
accessibilityIdentifier: "InsufficientSavingsToast"
)
return false
}
} else {
// Zero-amount invoice: user must have some balance to proceed
guard onchainBalance > 0 else {
toast(
type: .error,
title: t("other__pay_insufficient_savings"),
description: t("other__pay_insufficient_savings_description"),
accessibilityIdentifier: "InsufficientSavingsToast"
)
return false
}
}
return true
}
private func showValidationErrorToast(for result: ManualEntryValidationResult) {
switch result {
case .invalid:
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__generic"),
accessibilityIdentifier: "InvalidAddressToast"
)
case .insufficientSavings:
toast(
type: .error,
title: t("other__pay_insufficient_savings"),
description: t("other__pay_insufficient_savings_description"),
accessibilityIdentifier: "InsufficientSavingsToast"
)
case .insufficientSpending:
toast(
type: .error,
title: t("other__pay_insufficient_spending"),
description: t("other__pay_insufficient_savings_description"),
accessibilityIdentifier: "InsufficientSpendingToast"
)
case .expiredLightningOnly:
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__expired"),
accessibilityIdentifier: "ExpiredLightningToast"
)
case .valid, .empty:
break
}
}
/// Convenience initializer for previews and testing
convenience init() {
self.init(sheetViewModel: SheetViewModel(), navigationViewModel: NavigationViewModel())
}
deinit {}
func checkGeoStatus() async {
// Delegate to GeoService singleton for centralized geo-blocking management
await GeoService.shared.checkGeoStatus()
}
func wipe() async throws {
hasSeenContactsIntro = false
hasSeenProfileIntro = false
hasSeenNotificationsIntro = false
hasSeenQuickpayIntro = false
hasSeenShopIntro = false
hasSeenTransferToSpendingIntro = false
hasSeenTransferToSavingsIntro = false
hasSeenWidgetsIntro = false
hasDismissedWidgetsOnboardingHint = false
appUpdateIgnoreTimestamp = 0
backupVerified = false
backupIgnoreTimestamp = 0
highBalanceIgnoreCount = 0
highBalanceIgnoreTimestamp = 0
}
}
// MARK: Toast notifications
extension AppViewModel {
func toast(
type: Toast.ToastType,
title: String,
description: String? = nil,
autoHide: Bool = true,
visibilityTime: Double = 4.0,
accessibilityIdentifier: String? = nil
) {
switch type {
case .error:
Haptics.notify(.error)
case .success:
Haptics.notify(.success)
case .info:
Haptics.play(.heavy)
case .lightning:
Haptics.play(.rigid)
case .warning:
Haptics.notify(.warning)
}
let toast = Toast(
type: type,
title: title,
description: description,
autoHide: autoHide,
visibilityTime: visibilityTime,
accessibilityIdentifier: accessibilityIdentifier
)
ToastWindowManager.shared.showToast(toast)
}
func toast(_ error: Error) {
if error is CancellationError {
return
}
toast(type: .error, title: "Error", description: error.localizedDescription)
}
func hideToast() {
ToastWindowManager.shared.hideToast()
}
}
// MARK: Pending payment tracking
extension AppViewModel {
func addPendingPaymentHash(_ hash: String) {
pendingPaymentHashes.insert(hash)
}
/// Called by SendPendingScreen when it consumes a resolution. Clears the published value.
func consumeSendSheetPendingResolution(paymentHash hash: String) {
guard sendSheetPendingResolution?.paymentHash == hash else { return }
sendSheetPendingResolution = nil
}
}
// MARK: Scanning/pasting handling
extension AppViewModel {
func handleScannedData(_ uri: String) async throws {
// Reset send state before handling new data
resetSendState()
// Workaround for duplicated BIP21 URIs (bitkit-core#63)
if Bip21Utils.isDuplicatedBip21(uri) {
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__generic"),
accessibilityIdentifier: "InvalidAddressToast"
)
return
}
let data = try await decode(invoice: uri)
switch data {
// BIP21 (Unified) invoice handling
case let .onChain(invoice):
// Check network first - treat wrong network as decoding error
let addressValidation = try? validateBitcoinAddress(address: invoice.address)
let addressNetwork: LDKNode.Network? = addressValidation.map { NetworkValidationHelper.convertNetworkType($0.network) }
if NetworkValidationHelper.isNetworkMismatch(addressNetwork: addressNetwork, currentNetwork: Env.network) {
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__generic"),
accessibilityIdentifier: "InvalidAddressToast"
)
return
}
if let lnInvoice = invoice.params?["lightning"] {
// Lightning invoice param found, prefer lightning payment if invoice is valid
if case let .lightning(lightningInvoice) = try await decode(invoice: lnInvoice) {
// Check lightning invoice network
let lnNetwork = NetworkValidationHelper.convertNetworkType(lightningInvoice.networkType)
let lnNetworkMatch = !NetworkValidationHelper.isNetworkMismatch(addressNetwork: lnNetwork, currentNetwork: Env.network)
if lnNetworkMatch, !lightningInvoice.isExpired {
let nodeIsRunning = lightningService.status?.isRunning == true
if nodeIsRunning {
// Node is running → we have fresh balances; validate immediately.
// Prefer lightning; if insufficient or no channels/capacity, fall back to onchain.
let canSendLightning = lightningService.canSend(amountSats: lightningInvoice.amountSatoshis)
if canSendLightning {
handleScannedLightningInvoice(lightningInvoice, bolt11: lnInvoice, onchainInvoice: invoice)
return
}
// Lightning insufficient for any reason (no channels, no capacity, etc).
// Fall back to onchain and validate onchain balance immediately.
let onchainBalance = lightningService.balances?.spendableOnchainBalanceSats ?? 0
guard validateOnchainBalance(invoiceAmount: invoice.amountSatoshis, onchainBalance: onchainBalance) else {
return
}
// Onchain is sufficient → proceed with onchain flow, do not open lightning flow.
handleScannedOnchainInvoice(invoice)
return
}
// Node not running: proceed with lightning; validation/fallback will happen in SendSheet after sync.
handleScannedLightningInvoice(lightningInvoice, bolt11: lnInvoice, onchainInvoice: invoice)
return
}
// If Lightning is expired or wrong network, fall back to on-chain silently (no toast)
}
}
// Fallback to on-chain if address is available
guard !invoice.address.isEmpty else { return }
// If node is running, validate balance immediately
if lightningService.status?.isRunning == true {
let onchainBalance = lightningService.balances?.spendableOnchainBalanceSats ?? 0
guard validateOnchainBalance(invoiceAmount: invoice.amountSatoshis, onchainBalance: onchainBalance) else {
return
}
}
handleScannedOnchainInvoice(invoice)
case let .lightning(invoice):
// Check network first - treat wrong network as decoding error
let invoiceNetwork = NetworkValidationHelper.convertNetworkType(invoice.networkType)
if NetworkValidationHelper.isNetworkMismatch(addressNetwork: invoiceNetwork, currentNetwork: Env.network) {
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__generic"),
accessibilityIdentifier: "InvalidAddressToast"
)
return
}
guard !invoice.isExpired else {
toast(
type: .error,
title: t("other__scan_err_decoding"),
description: t("other__scan__error__expired"),
accessibilityIdentifier: "ExpiredLightningToast"
)
return
}
// If node is running, we can check for channels and validate immediately
if lightningService.status?.isRunning == true {
// If user has no channels at all, they can never pay a pure lightning invoice.
// Show insufficient spending toast and do not navigate to the send flow.
let hasAnyChannels = (lightningService.channels?.isEmpty == false)
if !hasAnyChannels {
let spendingBalance = lightningService.balances?.totalLightningBalanceSats ?? 0
showInsufficientSpendingToast(invoiceAmount: invoice.amountSatoshis, spendingBalance: spendingBalance)
return
}
// If channels are usable, validate capacity immediately
if let channels = lightningService.channels, channels.contains(where: \.isUsable) {
guard lightningService.canSend(amountSats: invoice.amountSatoshis) else {
let spendingBalance = lightningService.balances?.totalLightningBalanceSats ?? 0
showInsufficientSpendingToast(invoiceAmount: invoice.amountSatoshis, spendingBalance: spendingBalance)
return
}
}
}
// Proceed with lightning payment (validation will happen in SendSheet if node not ready)
handleScannedLightningInvoice(invoice, bolt11: uri)
case let .lnurlPay(data: lnurlPayData):
Logger.debug("LNURL: \(lnurlPayData)")
handleLnurlPayInvoice(lnurlPayData)
case let .lnurlWithdraw(data: lnurlWithdrawData):
Logger.debug("LNURL: \(lnurlWithdrawData)")
handleLnurlWithdraw(lnurlWithdrawData)
case let .lnurlChannel(data: lnurlChannelData):
Logger.debug("LNURL: \(lnurlChannelData)")
handleLnurlChannel(lnurlChannelData)
case let .lnurlAuth(data: lnurlAuthData):
Logger.debug("LNURL: \(lnurlAuthData)")
handleLnurlAuth(lnurlAuthData, lnurl: uri)
case let .nodeId(url, _):
guard lightningService.status?.isRunning == true else {
toast(type: .error, title: "Lightning not running", description: "Please try again later.")
return
}
handleNodeUri(url)
case let .gift(code, amount):
sheetViewModel.showSheet(.gift, data: GiftConfig(code: code, amount: Int(amount)))
default:
Logger.warn("Unhandled invoice type: \(data)")
toast(type: .error, title: "Unsupported", description: "This type of invoice is not supported yet")
}
}
private func handleScannedLightningInvoice(_ invoice: LightningInvoice, bolt11: String, onchainInvoice: OnChainInvoice? = nil) {
scannedLightningInvoice = invoice
scannedOnchainInvoice = onchainInvoice // Keep onchain invoice if provided
selectedWalletToPayFrom = .lightning
if invoice.amountSatoshis > 0 {
Logger.debug("Found amount in invoice, proceeding with payment")
} else {
Logger.debug("No amount found in invoice, proceeding entering amount manually")
}
}
private func handleScannedOnchainInvoice(_ invoice: OnChainInvoice) {
selectedWalletToPayFrom = .onchain
scannedOnchainInvoice = invoice
scannedLightningInvoice = nil
}
private func handleLnurlPayInvoice(_ data: LnurlPayData) {
guard lightningService.status?.isRunning == true else {
toast(type: .error, title: "Lightning not running", description: "Please try again later.")
return
}
let minSats = max(1, LightningAmountConversion.satsCeil(fromMsats: data.minSendable))
let lightningBalance = lightningService.balances?.totalLightningBalanceSats ?? 0
if lightningBalance < minSats {
toast(
type: .warning,
title: t("other__lnurl_pay_error"),
description: t("other__lnurl_pay_error_no_capacity")
)
return
}
selectedWalletToPayFrom = .lightning
lnurlPayData = data
}
private func handleLnurlWithdraw(_ data: LnurlWithdrawData) {
guard lightningService.status?.isRunning == true else {
toast(type: .error, title: "Lightning not running", description: "Please try again later.")
return
}
let minMsats = data.minWithdrawable ?? Env.msatsPerSat
let maxMsats = data.maxWithdrawable
if minMsats > maxMsats {
toast(
type: .warning,
title: t("other__lnurl_withdr_error"),
description: t("other__lnurl_withdr_error_minmax")
)
return
}
let minSats = max(1, LightningAmountConversion.satsCeil(fromMsats: minMsats))
let lightningBalance = lightningService.balances?.totalLightningBalanceSats ?? 0
if lightningBalance < minSats {
toast(
type: .warning,
title: t("other__lnurl_withdr_error"),
description: t("other__lnurl_withdr_error_no_capacity")
)
return
}
lnurlWithdrawData = data
}
private func handleLnurlChannel(_ data: LnurlChannelData) {
// Check if lightning service is running
guard lightningService.status?.isRunning == true else {
toast(type: .error, title: "Lightning not running", description: "Please try again later.")
return
}
sheetViewModel.hideSheet()
navigationViewModel.navigate(.lnurlChannel(channelData: data))
}
private func handleLnurlAuth(_ data: LnurlAuthData, lnurl: String) {
// Check if lightning service is running
guard lightningService.status?.isRunning == true else {
toast(type: .error, title: "Lightning not running", description: "Please try again later.")
return
}
sheetViewModel.showSheet(.lnurlAuth, data: LnurlAuthConfig(lnurl: lnurl, authData: data))
}
private func handleNodeUri(_ url: String) {
sheetViewModel.hideSheet()
navigationViewModel.navigate(.fundManual(nodeUri: url))
}
func resetSendState() {
scannedLightningInvoice = nil
scannedOnchainInvoice = nil
selectedWalletToPayFrom = .onchain // Reset to default
lnurlPayData = nil
lnurlWithdrawData = nil
}
}
// MARK: Manual entry validation
extension AppViewModel {
func normalizeManualEntry(_ value: String) -> String {
value.filter { !$0.isWhitespace }
}
func resetManualEntryInput() {
manualEntryValidationSequence &+= 1
manualEntryInput = ""
isManualEntryInputValid = false
manualEntryValidationResult = .empty
}
/// Queue validation with debounce
func validateManualEntryInput(_ rawValue: String, savingsBalanceSats: Int, spendingBalanceSats: Int) {
// Increment sequence first so any pending debounced requests become stale
manualEntryValidationSequence &+= 1
let currentSequence = manualEntryValidationSequence
let normalized = normalizeManualEntry(rawValue)
// Immediately update state for empty input (no debounce needed)
guard !normalized.isEmpty else {
manualEntryValidationResult = .empty
isManualEntryInputValid = false
return
}
// Queue the validation with debounce, including the sequence to detect stale requests
manualEntryValidationSubject.send((rawValue, savingsBalanceSats, spendingBalanceSats, currentSequence))
}
/// Perform the actual validation
private func performValidation(_ rawValue: String, savingsBalanceSats: Int, spendingBalanceSats: Int) async {
let currentSequence = manualEntryValidationSequence
let normalized = normalizeManualEntry(rawValue)
guard !normalized.isEmpty else {
manualEntryValidationResult = .empty
isManualEntryInputValid = false
return
}
// Workaround for duplicated BIP21 URIs (bitkit-core#63)
if Bip21Utils.isDuplicatedBip21(normalized) {
guard currentSequence == manualEntryValidationSequence else { return }
manualEntryValidationResult = .invalid
isManualEntryInputValid = false
showValidationErrorToast(for: .invalid)
return
}
// Try to decode the invoice
guard let decodedData = try? await decode(invoice: normalized) else {
guard currentSequence == manualEntryValidationSequence else { return }
manualEntryValidationResult = .invalid
isManualEntryInputValid = false
showValidationErrorToast(for: .invalid)
return
}
guard currentSequence == manualEntryValidationSequence else { return }
// Determine validation result based on invoice type and balance
var result: ManualEntryValidationResult = .valid
switch decodedData {
case let .lightning(invoice):
// Priority 0: Check network first - treat wrong network as invalid
let invoiceNetwork = NetworkValidationHelper.convertNetworkType(invoice.networkType)
if NetworkValidationHelper.isNetworkMismatch(addressNetwork: invoiceNetwork, currentNetwork: Env.network) {
result = .invalid
break
}
// Lightning-only invoice: check spending balance and expiry
let amountSats = invoice.amountSatoshis
// Priority 1: Insufficient spending balance (only check if amount > 0)
if amountSats > 0 && spendingBalanceSats < Int(amountSats) {
result = .insufficientSpending
} else if invoice.isExpired {
// Priority 2: Expired invoice (only after balance check passes)
result = .expiredLightningOnly
}
case let .onChain(invoice):
// Priority 0: Check network first - treat wrong network as invalid
let addressValidation = try? validateBitcoinAddress(address: invoice.address)
let addressNetwork: LDKNode.Network? = addressValidation.map { NetworkValidationHelper.convertNetworkType($0.network) }
if NetworkValidationHelper.isNetworkMismatch(addressNetwork: addressNetwork, currentNetwork: Env.network) {
result = .invalid
break
}
// BIP21 with potential lightning parameter
var canPayLightning = false
if let lnInvoice = invoice.params?["lightning"],
case let .lightning(lightningInvoice) = try? await decode(invoice: lnInvoice)
{
// Check for stale request after async decode
guard currentSequence == manualEntryValidationSequence else { return }
// Check lightning invoice network too
let lnNetwork = NetworkValidationHelper.convertNetworkType(lightningInvoice.networkType)
let lnNetworkMatch = !NetworkValidationHelper.isNetworkMismatch(addressNetwork: lnNetwork, currentNetwork: Env.network)
// Has lightning fallback - check if lightning is viable
canPayLightning = lnNetworkMatch && !lightningInvoice.isExpired &&
(lightningInvoice.amountSatoshis == 0 || spendingBalanceSats >= Int(lightningInvoice.amountSatoshis))
}
if !canPayLightning {
// On-chain: check savings balance
if invoice.amountSatoshis > 0 && savingsBalanceSats < Int(invoice.amountSatoshis) {
result = .insufficientSavings
} else if invoice.amountSatoshis == 0 && savingsBalanceSats == 0 {
// Zero-amount invoice: user must have some balance to proceed
result = .insufficientSavings
}
}
case .lnurlPay, .lnurlWithdraw, .lnurlChannel, .lnurlAuth, .nodeId, .gift:
// These types are valid if decoded successfully
result = .valid
default:
result = .invalid
}
guard currentSequence == manualEntryValidationSequence else { return }
manualEntryValidationResult = result
isManualEntryInputValid = (result == .valid)
// Show toast for error results
if result != .valid && result != .empty {
showValidationErrorToast(for: result)
}
}
}
// MARK: LDK Node Events
extension AppViewModel {
func handleLdkNodeEvent(_ event: Event) {
switch event {
case let .paymentReceived(paymentId, _, amountMsat, _):
Task {
if let paymentId {
if await CoreService.shared.activity.isActivitySeen(id: paymentId) {
return
}
await CoreService.shared.activity.markActivityAsSeen(id: paymentId)
}
await MainActor.run {
let sats = LightningAmountConversion.satsCeil(fromMsats: amountMsat)
sheetViewModel.showSheet(.receivedTx, data: ReceivedTxSheetDetails(type: .lightning, sats: sats))
}
}
case .channelPending(channelId: _, userChannelId: _, formerTemporaryChannelId: _, counterpartyNodeId: _, fundingTxo: _):
// Only relevant for channels to external nodes
break
case .channelReady(let channelId, userChannelId: _, counterpartyNodeId: _, fundingTxo: _):
Task {
// Use channelCache instead of cachedChannels array, as it's updated immediately
if let channel = await lightningService.getChannelFromCache(channelId: channelId) {
let cjitOrder = await CoreService.shared.blocktank.getCjit(channel: channel)
if cjitOrder != nil {
let amount = channel.balanceOnCloseSats
let now = UInt64(Date().timeIntervalSince1970)
let ln = LightningActivity(
id: channel.fundingTxo?.txid ?? "",
txType: .received,
status: .succeeded,
value: amount,
fee: 0,
invoice: cjitOrder?.invoice.request ?? "",
message: "",
timestamp: now,
preimage: nil,
createdAt: now,
updatedAt: nil,
seenAt: nil
)
try await CoreService.shared.activity.insert(.lightning(ln))
// Show receivedTx sheet for CJIT payment
await MainActor.run {
sheetViewModel.showSheet(.receivedTx, data: ReceivedTxSheetDetails(type: .lightning, sats: amount))
}
} else if await shouldShowFirstChannelReadyToast() {
toast(
type: .lightning,
title: t("lightning__channel_opened_title"),
description: t("lightning__channel_opened_msg"),
visibilityTime: 5.0,
accessibilityIdentifier: "SpendingBalanceReadyToast"
)
}
} else {
Logger.warn("Channel not found in cache: \(channelId)")
if await shouldShowFirstChannelReadyToast() {
toast(
type: .lightning,
title: t("lightning__channel_opened_title"),
description: t("lightning__channel_opened_msg"),
visibilityTime: 5.0,
accessibilityIdentifier: "SpendingBalanceReadyToast"
)
}
}
}
case .channelClosed(channelId: _, userChannelId: _, counterpartyNodeId: _, reason: _):
break
case let .paymentSuccessful(paymentId, paymentHash, _, _):
let hash = paymentId ?? paymentHash
if pendingPaymentHashes.contains(hash) {
pendingPaymentHashes.remove(hash)
sendSheetPendingResolution = SendSheetPendingResolution(paymentHash: hash, success: true)
toast(
type: .lightning,
title: t("wallet__toast_payment_success_title"),
description: t("wallet__toast_payment_success_description"),
accessibilityIdentifier: "PaymentSuccessToast"
)
}
case let .paymentFailed(paymentId, paymentHash, _):
let hash = paymentId ?? paymentHash
if let hash, pendingPaymentHashes.contains(hash) {
pendingPaymentHashes.remove(hash)
sendSheetPendingResolution = SendSheetPendingResolution(paymentHash: hash, success: false)
toast(
type: .error,
title: t("wallet__toast_payment_failed_title"),
description: t("wallet__toast_payment_failed_description"),
accessibilityIdentifier: "PaymentFailedToast"
)
}
case .paymentClaimable:
break
case .paymentForwarded:
break
// MARK: New Onchain Transaction Events
case let .onchainTransactionReceived(txid, details):
// Show notification for incoming transactions
if details.amountSats > 0 {
let sats = UInt64(abs(Int64(details.amountSats)))
Task {
// Show sheet for new transactions or replacements with value changes
try? await Task.sleep(nanoseconds: 500_000_000) // 500ms delay
if await CoreService.shared.activity.isOnchainActivitySeen(txid: txid) {
return
}
let shouldShow = await CoreService.shared.activity.shouldShowReceivedSheet(txid: txid, value: sats)
guard shouldShow else { return }
await CoreService.shared.activity.markOnchainActivityAsSeen(txid: txid)
await MainActor.run {
sheetViewModel.showSheet(.receivedTx, data: ReceivedTxSheetDetails(type: .onchain, sats: sats))
}
}
}
case let .onchainTransactionConfirmed(txid, _, blockHeight, _, _):
Logger.info("Transaction confirmed: \(txid) at block \(blockHeight)")
case let .onchainTransactionReplaced(txid, conflicts):
Logger.info("Transaction replaced: \(txid) by \(conflicts.count) conflict(s)")
Task {
if await CoreService.shared.activity.isReceivedTransaction(txid: txid) {
await MainActor.run {
toast(
type: .info,
title: t("wallet__toast_received_transaction_replaced_title"),
description: t("wallet__toast_received_transaction_replaced_description"),
accessibilityIdentifier: "ReceivedTransactionReplacedToast"
)
}
} else {
await MainActor.run {
toast(
type: .info,
title: t("wallet__toast_transaction_replaced_title"),
description: t("wallet__toast_transaction_replaced_description"),
accessibilityIdentifier: "TransactionReplacedToast"
)
}
}
}
case let .onchainTransactionReorged(txid):
Logger.warn("Transaction reorged: \(txid)")
toast(
type: .warning,
title: t("wallet__toast_transaction_unconfirmed_title"),
description: t("wallet__toast_transaction_unconfirmed_description"),
accessibilityIdentifier: "TransactionUnconfirmedToast"
)
case let .onchainTransactionEvicted(txid):
Task {
let wasReplaced = await CoreService.shared.activity.wasTransactionReplaced(txid: txid)
await MainActor.run {
if wasReplaced {
Logger.info("Transaction \(txid) was replaced, skipping evicted toast", context: "AppViewModel")
return
}
Logger.warn("Transaction removed from mempool: \(txid)")
toast(
type: .warning,
title: t("wallet__toast_transaction_removed_title"),
description: t("wallet__toast_transaction_removed_description"),
accessibilityIdentifier: "TransactionRemovedToast"
)
}
}
// MARK: Splice Events
case .splicePending, .spliceFailed:
break
// MARK: Sync Events
case let .syncProgress(syncType, progressPercent, _, _):
Logger.debug("Sync progress: \(syncType) \(progressPercent)%")
case let .syncCompleted(syncType, syncedBlockHeight):
Logger.info("Sync completed: \(syncType) at height \(syncedBlockHeight)")
// After mnemonic restore, prune empty address types once sync has completed
if SettingsViewModel.shared.pendingRestoreAddressTypePrune {
SettingsViewModel.shared.pendingRestoreAddressTypePrune = false
Task { @MainActor in
try? await Task.sleep(nanoseconds: 30 * 1_000_000_000) // 30s delay after sync
await SettingsViewModel.shared.pruneEmptyAddressTypesAfterRestore()
}
}
if MigrationsService.shared.needsPostMigrationSync {
Task { @MainActor in
try? await CoreService.shared.activity.syncLdkNodePayments(LightningService.shared.payments ?? [])
await CoreService.shared.activity.markAllUnseenActivitiesAsSeen()
await MigrationsService.shared.reapplyMetadataAfterSync()
if MigrationsService.shared.canCleanupAfterMigration {
if MigrationsService.shared.isShowingMigrationLoading {
try? await LightningService.shared.restart()
}
SettingsViewModel.shared.updatePinEnabledState()
MigrationsService.shared.cleanupAfterMigration()
MigrationsService.shared.needsPostMigrationSync = false
MigrationsService.shared.isRestoringFromRNRemoteBackup = false
} else {
Logger.info("Post-migration sync incomplete, will retry on next sync", context: "AppViewModel")
}
if MigrationsService.shared.isShowingMigrationLoading {
MigrationsService.shared.isShowingMigrationLoading = false
}
}
}
// MARK: Balance Events
case let .balanceChanged(oldSpendableOnchain, newSpendableOnchain, _, _, oldLightning, newLightning):
Logger.debug("Balance changed: onchain \(oldSpendableOnchain)->\(newSpendableOnchain) lightning \(oldLightning)->\(newLightning)")
}
}
private func shouldShowFirstChannelReadyToast() async -> Bool {
await MainActor.run {
max(lightningService.channelCacheCount, lightningService.channels?.count ?? 0) == 1
}
}
}
// MARK: - Timed Sheets
extension AppViewModel {
func ignoreAppUpdate() {
appUpdateIgnoreTimestamp = Date().timeIntervalSince1970
}
func ignoreBackup() {
backupIgnoreTimestamp = Date().timeIntervalSince1970
}
func ignoreHighBalance() {
highBalanceIgnoreCount += 1
highBalanceIgnoreTimestamp = Date().timeIntervalSince1970
}
}