-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLnurlPayConfirm.swift
More file actions
234 lines (208 loc) · 9.23 KB
/
LnurlPayConfirm.swift
File metadata and controls
234 lines (208 loc) · 9.23 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
import BitkitCore
import LDKNode
import SwiftUI
struct LnurlPayConfirm: View {
@EnvironmentObject var app: AppViewModel
@EnvironmentObject var sheets: SheetViewModel
@EnvironmentObject var wallet: WalletViewModel
@EnvironmentObject var currency: CurrencyViewModel
@EnvironmentObject var settings: SettingsViewModel
@Binding var navigationPath: [SendRoute]
let requestPinCheck: () async -> Bool
@State private var showWarningAlert = false
@State private var alertContinuation: CheckedContinuation<Bool, Error>?
@State private var showingBiometricError = false
@State private var biometricErrorMessage = ""
@State private var comment = ""
@FocusState private var isCommentFocused: Bool
var uri: String {
app.lnurlPayData!.uri
}
var body: some View {
VStack {
SheetHeader(title: t("wallet__lnurl_p_title"), showBackButton: true)
VStack(alignment: .leading) {
MoneyStack(
sats: Int(wallet.sendAmountSats ?? LightningAmountConversion.satsCeil(fromMsats: app.lnurlPayData!.minSendable)),
showSymbol: true,
testIdPrefix: "ReviewAmount"
)
.padding(.bottom, 32)
VStack(spacing: 0) {
VStack(alignment: .leading) {
CaptionMText(t("wallet__send_invoice"))
.padding(.bottom, 8)
BodySSBText(uri)
.lineLimit(1)
.truncationMode(.middle)
}
.padding(.vertical)
.frame(maxWidth: .infinity, alignment: .leading)
Divider()
VStack(alignment: .leading) {
CaptionMText(t("wallet__send_fee_and_speed"))
.padding(.bottom, 8)
HStack(spacing: 0) {
Image("bolt-hollow")
.foregroundColor(.purpleAccent)
.frame(width: 16, height: 16)
.padding(.trailing, 6)
// TODO: get actual fee
BodySSBText("Instant (±$0.02)")
}
}
.padding(.vertical)
.frame(maxWidth: .infinity, alignment: .leading)
Divider()
if let commentAllowed = app.lnurlPayData?.commentAllowed, commentAllowed > 0 {
VStack(alignment: .leading) {
CaptionMText(t("wallet__lnurl_pay_confirm__comment"))
.padding(.bottom, 8)
TextField(
t("wallet__lnurl_pay_confirm__comment_placeholder"),
text: $comment,
axis: .vertical,
testIdentifier: "CommentInput",
submitLabel: .done
)
.focused($isCommentFocused)
.dismissKeyboardOnReturn(text: $comment, isFocused: $isCommentFocused)
.lineLimit(3 ... 3)
.onChange(of: comment) { _, newValue in
let maxLength = Int(commentAllowed)
if newValue.count > maxLength {
comment = String(newValue.prefix(maxLength))
}
}
}
.padding(.vertical)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
Spacer()
SwipeButton(
title: t("wallet__send_swipe"),
accentColor: .greenAccent
) {
// Check if we need to show warning for amounts over $100 USD
if settings.warnWhenSendingOver100 {
let sats: UInt64 = if let invoice = app.scannedLightningInvoice {
wallet.sendAmountSats ?? invoice.amountSatoshis
} else {
0
}
// Convert to USD to check if over $100
if let usdAmount = currency.convert(sats: sats, to: "USD") {
if usdAmount.value > 100.0 {
showWarningAlert = true
// Wait for the alert to be dismissed
let shouldProceed = try await waitForAlertDismissal()
if !shouldProceed {
// User cancelled, throw error to reset SwipeButton
throw CancellationError()
}
// User confirmed, continue with authentication if needed
}
}
}
// 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()
.alert(t("common__are_you_sure"), isPresented: $showWarningAlert) {
Button(t("common__dialog_cancel"), role: .cancel) {
alertContinuation?.resume(returning: false)
alertContinuation = nil
}
Button(t("wallet__send_yes")) {
alertContinuation?.resume(returning: true)
alertContinuation = nil
}
} message: {
Text(t("wallet__send_dialog1"))
}
.alert(
t("security__bio_error_title"),
isPresented: $showingBiometricError
) {
Button(t("common__ok")) {
// Error handled, user acknowledged
}
} message: {
Text(biometricErrorMessage)
}
}
private func waitForAlertDismissal() async throws -> Bool {
return try await withCheckedThrowingContinuation { continuation in
alertContinuation = continuation
}
}
private func performPayment() async throws {
guard let lnurlPayData = app.lnurlPayData else {
throw NSError(domain: "LNURL", code: -1, userInfo: [NSLocalizedDescriptionKey: "Missing LNURL pay data"])
}
let amountMsats: UInt64 = if let userSats = wallet.sendAmountSats {
userSats * 1000
} else {
lnurlPayData.minSendable
}
// Fetch the Lightning invoice from LNURL
let bolt11 = try await LnurlHelper.fetchLnurlInvoice(
callbackUrl: lnurlPayData.callback,
amountMsats: amountMsats,
comment: comment.isEmpty ? nil : comment
)
let parsedInvoice = try Bolt11Invoice.fromStr(invoiceStr: bolt11)
let paymentHash = String(describing: parsedInvoice.paymentHash())
do {
// Perform the Lightning payment (10s timeout → navigate to pending for hold invoices)
// LNURL server returns invoices with the amount baked in, so pass sats: nil
// to let LDK use the invoice's native millisatoshi precision.
try await wallet.sendWithTimeout(
bolt11: bolt11,
sats: nil,
onTimeout: {
app.addPendingPaymentHash(paymentHash)
navigationPath.append(.pending(paymentHash: paymentHash))
}
)
Logger.info("LNURL payment successful: \(paymentHash)")
navigationPath.append(.success(paymentId: paymentHash))
} catch is PaymentTimeoutError {
// onTimeout callback already navigated to .pending; suppress throw
return
} catch {
Logger.error("LNURL payment failed: \(error)")
// 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)
}
}
}
}