-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSendConfirmationView.swift
More file actions
782 lines (702 loc) · 31.3 KB
/
SendConfirmationView.swift
File metadata and controls
782 lines (702 loc) · 31.3 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
import BitkitCore
import SwiftUI
struct SendConfirmationView: View {
@EnvironmentObject var app: AppViewModel
@EnvironmentObject var currency: CurrencyViewModel
@EnvironmentObject var feeEstimatesManager: FeeEstimatesManager
@EnvironmentObject var settings: SettingsViewModel
@EnvironmentObject var sheets: SheetViewModel
@EnvironmentObject var wallet: WalletViewModel
@EnvironmentObject var tagManager: TagManager
@Binding var navigationPath: [SendRoute]
let requestPinCheck: () async -> Bool
@State private var showDetails = false
@State private var showingBiometricError = false
@State private var biometricErrorMessage = ""
@State private var transactionFee: Int = 0
@State private var shouldUseSendAll: Bool = false
@State private var currentWarning: WarningType?
@State private var pendingWarnings: [WarningType] = []
@State private var warningContinuation: CheckedContinuation<Bool, Error>?
@State private var swipeProgress: CGFloat = 0
var accentColor: Color {
app.selectedWalletToPayFrom == .lightning ? .purpleAccent : .brandAccent
}
var canSwitchWallet: Bool {
guard app.scannedOnchainInvoice != nil, app.scannedLightningInvoice != nil else { return false }
let amount = wallet.sendAmountSats ?? app.scannedOnchainInvoice?.amountSatoshis ?? 0
return wallet.canSwitchWalletForUnifiedInvoice(amountSats: amount)
}
/// `.instant` is only valid when paying from Lightning; align `selectedSpeed` with the current sat/vB on savings.
private func reconcileInstantSpeedWhenSwitchingToOnChain() async {
guard wallet.selectedSpeed == .instant else { return }
await MainActor.run {
wallet.selectedSpeed = settings.defaultTransactionSpeed
}
}
/// BIP21 flow can land on confirm with `sendAmountSats` unset; set it from the scanned invoices.
@MainActor
private func ensureSendAmountFromScannedInvoicesIfNeeded() {
guard wallet.sendAmountSats == nil || wallet.sendAmountSats == 0 else { return }
if let invoice = app.scannedOnchainInvoice, invoice.amountSatoshis > 0 {
wallet.sendAmountSats = invoice.amountSatoshis
} else if let lightning = app.scannedLightningInvoice, lightning.amountSatoshis > 0 {
wallet.sendAmountSats = lightning.amountSatoshis
}
}
/// Warning system
private enum WarningType: String, CaseIterable {
case amount
case balance
case fee
case feePercentage
case minimumFee
var title: String {
switch self {
case .minimumFee: return t("wallet__send_dialog5_title")
default: return t("common__are_you_sure")
}
}
var message: String {
switch self {
case .amount: return t("wallet__send_dialog1")
case .balance: return t("wallet__send_dialog2")
case .fee: return t("wallet__send_dialog4")
case .feePercentage: return t("wallet__send_dialog3")
case .minimumFee: return t("wallet__send_dialog5_description")
}
}
}
private var canEditAmount: Bool {
guard app.selectedWalletToPayFrom == .lightning else { return true }
guard let invoice = app.scannedLightningInvoice else { return true }
return invoice.amountSatoshis == 0
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
SheetHeader(title: t("wallet__send_review"), showBackButton: !navigationPath.isEmpty)
VStack(alignment: .leading, spacing: 0) {
if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice {
MoneyStack(
sats: Int(wallet.sendAmountSats ?? invoice.amountSatoshis),
showSymbol: true,
testIdPrefix: "ReviewAmount",
onTap: navigateToAmount
)
} else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice {
MoneyStack(
sats: Int(wallet.sendAmountSats ?? invoice.amountSatoshis),
showSymbol: true,
testIdPrefix: "ReviewAmount",
onTap: navigateToAmount
)
}
}
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 44)
if showDetails {
if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice {
onchainView(invoice)
} else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice {
lightningView(invoice)
}
} else {
Image("coin-stack-4")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: UIScreen.main.bounds.width * 0.8)
.frame(maxWidth: .infinity)
.padding(.bottom, 16)
.rotationEffect(.degrees(swipeProgress * 14))
}
if !UIScreen.main.isSmall || !showDetails {
CustomButton(
title: showDetails ? t("common__hide_details") : t("common__show_details"),
size: .small,
icon: Image(showDetails ? "eye-slash" : app.selectedWalletToPayFrom == .lightning ? "bolt-hollow" : "speed-normal")
.resizable()
.frame(width: 16, height: 16)
.foregroundColor(accentColor)
) {
showDetails.toggle()
}
.frame(maxWidth: .infinity, alignment: .center)
.padding(.top, 16)
.accessibilityIdentifier("SendConfirmToggleDetails")
}
Spacer(minLength: 16)
SwipeButton(title: t("wallet__send_swipe"), accentColor: accentColor, swipeProgress: $swipeProgress) {
// Validate payment and show warnings if needed
let warnings = await validatePayment()
if !warnings.isEmpty {
let shouldProceed = try await showWarnings(warnings)
if !shouldProceed {
throw CancellationError()
}
}
// Check if authentication is required for payments
if settings.requirePinForPayments && settings.pinEnabled {
if settings.useBiometrics && BiometricAuth.isAvailable {
let result = await BiometricAuth.authenticate()
switch result {
case .success:
break
case .cancelled:
throw CancellationError()
case let .failed(message):
biometricErrorMessage = message
showingBiometricError = true
throw CancellationError()
}
} else {
let shouldProceed = await requestPinCheck()
guard shouldProceed else {
throw CancellationError()
}
}
}
try await performPayment()
}
}
.navigationBarHidden(true)
.padding(.horizontal, 16)
.sheetBackground()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.task {
ensureSendAmountFromScannedInvoicesIfNeeded()
await calculateTransactionFee()
await calculateRoutingFee()
}
.onChange(of: wallet.selectedFeeRateSatsPerVByte) {
Task {
await calculateTransactionFee()
}
}
.onChange(of: app.selectedWalletToPayFrom) {
Task {
if app.selectedWalletToPayFrom == .lightning {
await MainActor.run { transactionFee = 0 }
} else {
await onSwitchToOnchainWallet()
}
}
}
.alert(
t("security__bio_error_title"),
isPresented: $showingBiometricError
) {
Button(t("common__ok")) {
// Error handled, user acknowledged
}
} message: {
Text(biometricErrorMessage)
}
.alert(
currentWarning?.title ?? "",
isPresented: .constant(currentWarning != nil)
) {
Button(t("common__dialog_cancel"), role: .cancel) {
warningContinuation?.resume(returning: false)
warningContinuation = nil
currentWarning = nil
}
Button(t("wallet__send_yes")) {
warningContinuation?.resume(returning: true)
warningContinuation = nil
currentWarning = nil
}
} message: {
if let warning = currentWarning {
Text(warning.message)
}
}
}
func onchainView(_ invoice: OnChainInvoice) -> some View {
VStack(alignment: .leading, spacing: 16) {
HStack(alignment: .top, spacing: 16) {
SendSectionView(t("wallet__send_from")) {
NumberPadActionButton(
text: t("wallet__savings__title"),
imageName: canSwitchWallet ? "arrow-up-down" : nil,
color: app.selectedWalletToPayFrom == .lightning ? .purpleAccent : .brandAccent,
variant: canSwitchWallet ? .primary : .secondary,
disabled: !canSwitchWallet
) {
if canSwitchWallet {
app.selectedWalletToPayFrom.toggle()
}
}
.accessibilityIdentifier("SendConfirmAssetButton")
}
Button {
navigateToManual(with: invoice.address)
} label: {
SendSectionView(t("wallet__send_to")) {
BodySSBText(invoice.address.ellipsis(maxLength: 18))
.lineLimit(1)
.truncationMode(.middle)
.frame(height: 28)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.buttonStyle(.plain)
.accessibilityIdentifier("ReviewUri")
}
.frame(maxWidth: .infinity, alignment: .leading)
HStack(alignment: .top, spacing: 16) {
Button(action: {
navigationPath.append(.feeRate)
}) {
SendSectionView(t("wallet__send_fee_and_speed")) {
HStack(spacing: 0) {
Image(wallet.selectedSpeed.iconName)
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(wallet.selectedSpeed.iconColor)
.frame(width: 16, height: 16)
.padding(.trailing, 4)
if transactionFee > 0 {
let feeText = "\(wallet.selectedSpeed.title) ("
HStack(spacing: 0) {
BodySSBText(feeText)
MoneyText(sats: transactionFee, size: .bodySSB, symbol: true, symbolColor: .textPrimary)
BodySSBText(")")
}
Image("pencil")
.foregroundColor(.textPrimary)
.frame(width: 12, height: 12)
.padding(.leading, 6)
}
}
}
}
SendSectionView(t("wallet__send_confirming_in")) {
HStack(spacing: 0) {
Image("clock")
.foregroundColor(.brandAccent)
.frame(width: 16, height: 16)
.padding(.trailing, 4)
BodySSBText(
TransactionSpeed.getFeeTierLocalized(
feeRate: UInt64(wallet.selectedFeeRateSatsPerVByte ?? 0),
feeEstimates: feeEstimatesManager.estimates,
variant: .range
)
)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
SendSectionView(t("wallet__tags")) {
TagsListView(
tags: tagManager.selectedTagsArray,
icon: .close,
onAddTag: {
navigationPath.append(.tag)
},
onTagDelete: { tag in
tagManager.removeTagFromSelection(tag)
},
addButtonTestId: "TagsAddSend"
)
}
}
}
func lightningView(_ invoice: LightningInvoice) -> some View {
VStack(alignment: .leading, spacing: 16) {
HStack {
SendSectionView(t("wallet__send_from")) {
NumberPadActionButton(
text: t("wallet__spending__title"),
imageName: canSwitchWallet ? "arrow-up-down" : nil,
color: app.selectedWalletToPayFrom == .lightning ? .purpleAccent : .brandAccent,
variant: canSwitchWallet ? .primary : .secondary,
disabled: !canSwitchWallet
) {
if canSwitchWallet {
app.selectedWalletToPayFrom.toggle()
}
}
.accessibilityIdentifier("SendConfirmAssetButton")
}
Spacer(minLength: 16)
Button {
navigateToManual(with: invoice.bolt11)
} label: {
SendSectionView(t("wallet__send_to")) {
BodySSBText(invoice.bolt11.ellipsis(maxLength: 18))
.lineLimit(1)
.truncationMode(.middle)
.frame(height: 28)
}
}
.buttonStyle(.plain)
.accessibilityIdentifier("ReviewUri")
}
HStack(alignment: .top, spacing: 16) {
Button(action: {
if canSwitchWallet {
navigationPath.append(.feeRate)
}
}) {
SendSectionView(t("wallet__send_fee_and_speed")) {
HStack(spacing: 0) {
Image("bolt-hollow")
.foregroundColor(.purpleAccent)
.frame(width: 16, height: 16)
.padding(.trailing, 4)
if wallet.routingFeeEstimateSats > 0 {
let feeText = "\(t("fee__instant__title")) (±"
HStack(spacing: 0) {
BodySSBText(feeText)
MoneyText(
sats: Int(wallet.routingFeeEstimateSats),
size: .bodySSB,
symbol: true,
symbolColor: .textPrimary
)
BodySSBText(")")
}
} else {
BodySSBText(t("fee__instant__title"))
}
if canSwitchWallet {
Image("pencil")
.foregroundColor(.textPrimary)
.frame(width: 12, height: 12)
.padding(.leading, 6)
}
}
}
}
SendSectionView(t("wallet__send_invoice_expiration")) {
HStack(spacing: 4) {
Image("timer-alt")
.foregroundColor(.purpleAccent)
.frame(width: 16, height: 16)
BodySSBText(DateFormatterHelpers.formatInvoiceExpiryRelative(
timestampSeconds: invoice.timestampSeconds,
expirySeconds: invoice.expirySeconds
))
}
}
}
if let description = app.scannedLightningInvoice?.description, !description.isEmpty {
SendSectionView(t("wallet__note")) {
ScrollView(.horizontal, showsIndicators: false) {
BodySSBText(description)
.lineLimit(1)
.allowsTightening(false)
}
}
}
SendSectionView(t("wallet__tags")) {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(tagManager.selectedTagsArray, id: \.self) { tag in
Tag(tag, icon: .close, onDelete: { tagManager.removeTagFromSelection(tag) })
}
AddTagButton(onPress: { navigationPath.append(.tag) })
.accessibilityIdentifier("TagsAddSend")
}
}
}
}
}
private func performPayment() async throws {
var createdMetadataPaymentId: String? = nil
do {
if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice {
let amount = wallet.sendAmountSats ?? invoice.amountSatoshis
// Set the amount for other screens
wallet.sendAmountSats = amount
// Create pre-activity metadata for tags and activity address
let paymentHash = invoice.paymentHash.hex
createdMetadataPaymentId = paymentHash
await createPreActivityMetadata(paymentId: paymentHash, paymentHash: paymentHash)
// Perform the Lightning payment (10s timeout → navigate to pending for hold invoices)
// For invoices with a built-in amount, pass sats: nil so LDK uses the invoice's
// native millisatoshi precision instead of our truncated satoshi value.
let paymentSats: UInt64? = invoice.amountSatoshis == 0 ? amount : nil
do {
try await wallet.sendWithTimeout(
bolt11: invoice.bolt11,
sats: paymentSats,
onTimeout: {
app.addPendingPaymentHash(paymentHash)
navigationPath.append(.pending(paymentHash: paymentHash))
}
)
Logger.info("Lightning payment successful: \(paymentHash)")
navigationPath.append(.success(paymentId: paymentHash))
} catch is PaymentTimeoutError {
// onTimeout callback already navigated to .pending; suppress throw
return
} catch {
throw error
}
} else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice {
let amount = wallet.sendAmountSats ?? invoice.amountSatoshis
// Use sendAll if explicitly MAX or if change would be dust
let useMaxAmount = wallet.isMaxAmountSend || shouldUseSendAll
let txid = try await wallet.send(address: invoice.address, sats: amount, isMaxAmount: useMaxAmount)
// Create pre-activity metadata for tags and activity address
await createPreActivityMetadata(paymentId: txid, address: invoice.address, txId: txid, feeRate: wallet.selectedFeeRateSatsPerVByte)
// Create sent onchain activity immediately so it appears before LDK event (which can be delayed)
await CoreService.shared.activity.createSentOnchainActivityFromSendResult(
txid: txid,
address: invoice.address,
amount: amount,
fee: UInt64(transactionFee),
feeRate: wallet.selectedFeeRateSatsPerVByte ?? 1
)
// Set the amount for the success screen
wallet.sendAmountSats = amount
Logger.info("Onchain send result txid: \(txid)")
navigationPath.append(.success(paymentId: txid))
} else {
throw NSError(
domain: "Payment", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid payment method or missing invoice data"]
)
}
} catch {
Logger.error("Payment failed: \(error)")
if let paymentId = createdMetadataPaymentId {
try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentId)
}
// TODO: remove toast and use failure screen instead
app.toast(error)
// TODO: this is a hack to make sure the navigation binding is ready
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
navigationPath.append(.failure)
}
}
}
private func validatePayment() async -> [WarningType] {
var warnings: [WarningType] = []
let amount: UInt64 = if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice {
wallet.sendAmountSats ?? invoice.amountSatoshis
} else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice {
wallet.sendAmountSats ?? invoice.amountSatoshis
} else {
0
}
// Check if amount > 50% of balance
if app.selectedWalletToPayFrom == .lightning {
let lightningBalance = wallet.totalLightningSats
if amount > lightningBalance / 2 {
warnings.append(.balance)
}
} else {
let onchainBalance = wallet.totalOnchainSats
if amount > onchainBalance / 2 {
warnings.append(.balance)
}
}
// Check if amount > $100 and warning is enabled
if settings.warnWhenSendingOver100 {
if let usdAmount = currency.convert(sats: amount, to: "USD") {
if usdAmount.value > 100.0 {
warnings.append(.amount)
}
}
}
// Check if fee > $10 (only for onchain)
if app.selectedWalletToPayFrom == .onchain {
if let feeUsd = currency.convert(sats: UInt64(transactionFee), to: "USD") {
if feeUsd.value > 10.0 {
warnings.append(.fee)
}
}
// Check if fee > 50% of send amount
if transactionFee > 0 && UInt64(transactionFee) > amount / 2 {
warnings.append(.feePercentage)
}
// TODO: add minimum fee warning
// Check minimum fee warning
// if let feeRate = wallet.selectedFeeRateSatsPerVByte,
// let minimumFee = wallet.minimumFeeRateSatsPerVByte,
// feeRate <= minimumFee {
// warnings.append(.minimumFee)
// }
}
return warnings
}
private func showWarnings(_ warnings: [WarningType]) async throws -> Bool {
pendingWarnings = warnings
while !pendingWarnings.isEmpty {
let warning = pendingWarnings.removeFirst()
let shouldProceed = try await withCheckedThrowingContinuation { continuation in
warningContinuation = continuation
currentWarning = warning
}
if !shouldProceed {
return false
}
}
return true
}
private func createPreActivityMetadata(
paymentId: String,
paymentHash: String? = nil,
address: String? = nil,
txId: String? = nil,
feeRate: UInt32? = nil
) async {
let currentTime = UInt64(Date().timeIntervalSince1970)
let preActivityMetadata = BitkitCore.PreActivityMetadata(
paymentId: paymentId,
tags: tagManager.selectedTagsArray,
paymentHash: paymentHash,
txId: txId,
address: address,
isReceive: false,
feeRate: feeRate.map { UInt64($0) } ?? 0,
isTransfer: false,
channelId: nil,
createdAt: currentTime
)
try? await CoreService.shared.activity.addPreActivityMetadata(preActivityMetadata)
}
private func navigateToManual(with value: String) {
guard !value.isEmpty else { return }
app.manualEntryInput = value
app.validateManualEntryInput(
value,
savingsBalanceSats: wallet.spendableOnchainBalanceSats,
spendingBalanceSats: wallet.maxSendLightningSats
)
if let manualIndex = navigationPath.firstIndex(of: .manual) {
navigationPath = Array(navigationPath.prefix(manualIndex + 1))
} else {
navigationPath = [.manual]
}
}
private func navigateToAmount() {
guard canEditAmount else { return }
if let amountIndex = navigationPath.lastIndex(of: .amount) {
navigationPath = Array(navigationPath.prefix(amountIndex + 1))
} else {
if let confirmIndex = navigationPath.lastIndex(of: .confirm) {
navigationPath = Array(navigationPath.prefix(confirmIndex))
}
navigationPath.append(.amount)
}
}
/// After the user chooses savings, prepares on-chain send (amount, fee rate, UTXOs) and refreshes the shown fee.
private func onSwitchToOnchainWallet() async {
guard app.selectedWalletToPayFrom == .onchain else { return }
await reconcileInstantSpeedWhenSwitchingToOnChain()
if wallet.selectedFeeRateSatsPerVByte == nil {
do {
try await wallet.setFeeRate(speed: settings.defaultTransactionSpeed)
} catch {
Logger.error("Failed to set fee rate when switching to on-chain: \(error)")
await MainActor.run {
app.selectedWalletToPayFrom = .lightning
app.toast(type: .error, title: t("other__try_again"))
}
return
}
}
if settings.coinSelectionMethod == .manual {
if wallet.selectedUtxos == nil || wallet.selectedUtxos?.isEmpty == true {
do {
try await wallet.loadAvailableUtxos()
await MainActor.run {
navigationPath.append(.utxoSelection)
}
} catch {
Logger.error("Failed to load UTXOs when switching to on-chain: \(error)")
await MainActor.run {
app.selectedWalletToPayFrom = .lightning
app.toast(type: .error, title: t("other__try_again"))
}
}
return
}
} else {
do {
try await wallet.setUtxoSelection(coinSelectionAlgorythm: settings.coinSelectionAlgorithm)
} catch {
Logger.error("Failed to set UTXO selection when switching to on-chain: \(error)")
await MainActor.run {
app.selectedWalletToPayFrom = .lightning
app.toast(
type: .error,
title: t("other__try_again"),
description: error.localizedDescription
)
}
return
}
}
await calculateTransactionFee()
}
private func calculateTransactionFee() async {
guard app.selectedWalletToPayFrom == .onchain else {
return
}
guard let address = app.scannedOnchainInvoice?.address,
let amountSats = wallet.sendAmountSats,
let feeRate = wallet.selectedFeeRateSatsPerVByte
else {
return
}
do {
// Fee for normal send (recipient + change outputs) - used to check if change would be dust
let normalFee = try await wallet.calculateTotalFee(
address: address,
amountSats: amountSats,
satsPerVByte: feeRate,
utxosToSpend: wallet.selectedUtxos
)
let totalInput = wallet.selectedUtxos?.reduce(0) { $0 + $1.valueSats }
?? UInt64(wallet.spendableOnchainBalanceSats)
let useSendAll = DustChangeHelper.shouldUseSendAllToAvoidDust(
totalInput: totalInput,
amountSats: amountSats,
normalFee: normalFee
)
if useSendAll {
// Change would be dust - use sendAll and add dust to fee
let sendAllFee = try await wallet.estimateSendAllFee(
address: address,
satsPerVByte: feeRate
)
await MainActor.run {
transactionFee = Int(sendAllFee)
shouldUseSendAll = true
}
} else {
// Normal send with change output
await MainActor.run {
transactionFee = Int(normalFee)
shouldUseSendAll = false
}
}
} catch {
Logger.error("Failed to calculate actual fee: \(error)")
await MainActor.run {
transactionFee = 0
shouldUseSendAll = false
app.toast(type: .error, title: t("other__try_again"))
}
}
}
@MainActor
private func calculateRoutingFee() async {
guard let bolt11 = app.scannedLightningInvoice?.bolt11 else {
wallet.routingFeeEstimateSats = 0
return
}
if canSwitchWallet || app.selectedWalletToPayFrom == .lightning {
// For invoices with a built-in amount, pass nil so LDK uses native msat precision
let amountSats: UInt64? = app.scannedLightningInvoice?.amountSatoshis == 0 ? wallet.sendAmountSats : nil
await wallet.refreshRoutingFeeEstimate(bolt11: bolt11, amountSats: amountSats)
} else {
wallet.routingFeeEstimateSats = 0
}
}
}