From 9f6fbd6144bae0a6fa56be84d23f58aba86fd777 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 05:26:13 +0100 Subject: [PATCH 01/64] feat: pay contacts through pubky swaps A spending-only wallet pays a Paykit contact whose only endpoint is on-chain through a Pubky Swaps provider found among its contacts. Behind PUBKY_SWAPS_ROUTES on regtest debug builds. Uses bitkit-core 0.8.0-swaps.2. --- Bitkit.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/swiftpm/Package.resolved | 4 +- Bitkit/Constants/Env.swift | 13 +++ .../Localization/ar.lproj/Localizable.strings | 1 + .../Localization/ca.lproj/Localizable.strings | 1 + .../Localization/cs.lproj/Localizable.strings | 1 + .../Localization/de.lproj/Localizable.strings | 1 + .../Localization/el.lproj/Localizable.strings | 1 + .../Localization/en.lproj/Localizable.strings | 1 + .../es-419.lproj/Localizable.strings | 1 + .../Localization/es.lproj/Localizable.strings | 1 + .../Localization/fr.lproj/Localizable.strings | 1 + .../Localization/it.lproj/Localizable.strings | 1 + .../Localization/nl.lproj/Localizable.strings | 1 + .../Localization/pl.lproj/Localizable.strings | 1 + .../pt-BR.lproj/Localizable.strings | 1 + .../Localization/pt.lproj/Localizable.strings | 1 + .../Localization/ru.lproj/Localizable.strings | 1 + Bitkit/Services/PubkySwapsRouteService.swift | 98 +++++++++++++++++++ Bitkit/ViewModels/AppViewModel.swift | 14 +++ .../Views/Wallets/Send/SendAmountView.swift | 40 ++++++++ .../Wallets/Send/SendConfirmationView.swift | 93 +++++++++++++++++- Bitkit/Views/Wallets/Send/SendSheet.swift | 4 +- 23 files changed, 277 insertions(+), 6 deletions(-) create mode 100644 Bitkit/Services/PubkySwapsRouteService.swift diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 507f9cb4e7..506c381d51 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1269,7 +1269,7 @@ repositoryURL = "https://github.com/synonymdev/bitkit-core"; requirement = { kind = exactVersion; - version = "0.8.0-rc11"; + version = "0.8.0-swaps.2"; }; }; 96E493A22C942FD1000E8BC2 /* XCRemoteSwiftPackageReference "swift-secp256k1" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 8401f1e44a..8ec52eb4e0 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/bitkit-core", "state" : { - "revision" : "22e0acc31a97b65205e71f4190cfc659fdecd3ca", - "version" : "0.8.0-rc11" + "revision" : "1abc3ff8bc40848951d19ae74259f004b78ce5be", + "version" : "0.8.0-swaps.2" } }, { diff --git a/Bitkit/Constants/Env.swift b/Bitkit/Constants/Env.swift index 4cdd9ea871..cbfe04f824 100644 --- a/Bitkit/Constants/Env.swift +++ b/Bitkit/Constants/Env.swift @@ -228,6 +228,19 @@ enum Env { return electrumServerUrl(for: network) } + /// Whether a Paykit payment may route through a Pubky Swaps provider when no balance reaches the contact's + /// endpoints. Regtest debug builds with `PUBKY_SWAPS_ROUTES=true` only. + static var isPubkySwapsRouteEnabled: Bool { + isDebug && network == .regtest && boolConfigValue("PUBKY_SWAPS_ROUTES") + } + + /// Swap providers to ask besides the user's contacts, from `PUBKY_SWAPS_PROVIDERS` (comma-separated pubkys). + static var pubkySwapsProviders: [String] { + (configValue("PUBKY_SWAPS_PROVIDERS") ?? "").split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } + static var trezorBridgeEnabled: Bool { (isDebug || isE2E) && boolConfigValue("TREZOR_BRIDGE") } diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 2ba6f30416..cbf00b22ed 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1068,6 +1068,7 @@ "wallet__send_sync_long_title" = "مشاكل\nالاتصال"; "wallet__send_sync_long_description" = "يبدو أنك غير متصل. يرجى التحقق من اتصالك. سيحاول Bitkit إعادة الاتصال كل بضع ثوانٍ."; "wallet__send_to" = "إلى"; +"wallet__send_swap_route" = "المسار"; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 78a612fe0f..f30ecdb695 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1187,6 +1187,7 @@ "wallet__send_sync_long_title" = "Problemes de\nconnexió"; "wallet__send_sync_long_description" = "Sembla que estàs desconnectat. Comprova la connexió. Bitkit intentarà tornar a connectar-se cada pocs segons."; "wallet__send_to" = "A"; +"wallet__send_swap_route" = "Ruta"; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 755de70ef7..79c71454e3 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1294,6 +1294,7 @@ "wallet__send_sync_long_title" = "Problémy\ns připojením"; "wallet__send_sync_long_description" = "Zdá se, že jste odpojeni. Zkontrolujte prosím připojení. Bitkit se bude každých několik sekund pokoušet znovu připojit."; "wallet__send_to" = "Komu"; +"wallet__send_swap_route" = "Trasa"; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 41d543636a..e28b7567a4 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1292,6 +1292,7 @@ "wallet__send_sync_long_title" = "Verbindungs-\nprobleme"; "wallet__send_sync_long_description" = "Anscheinend bist du nicht verbunden. Bitte überprüfe deine Verbindung. Bitkit versucht alle paar Sekunden, sich erneut zu verbinden."; "wallet__send_to" = "An"; +"wallet__send_swap_route" = "Route"; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 3bcdf21e17..8c1fee2a8c 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1086,6 +1086,7 @@ "wallet__send_sync_long_title" = "Προβλήματα\nσύνδεσης"; "wallet__send_sync_long_description" = "Φαίνεται ότι είστε αποσυνδεδεμένοι. Ελέγξτε τη σύνδεσή σας. Το Bitkit θα προσπαθεί να επανασυνδεθεί κάθε λίγα δευτερόλεπτα."; "wallet__send_to" = "Προς"; +"wallet__send_swap_route" = "Διαδρομή"; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 9f299e68bc..cbef201848 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1307,6 +1307,7 @@ "wallet__send_sync_long_title" = "Connection\nissues"; "wallet__send_sync_long_description" = "It appears you’re disconnected. Please check your connection. Bitkit will try to reconnect every few seconds."; "wallet__send_to" = "To"; +"wallet__send_swap_route" = "Route"; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Paste Invoice"; "wallet__recipient_manual" = "Enter Manually"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 7de3e658a0..26f80e8169 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1297,6 +1297,7 @@ "wallet__send_sync_long_title" = "Problemas de\nconexión"; "wallet__send_sync_long_description" = "Parece que está desconectado. Revise su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Ruta"; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 510f689188..c0859ad22f 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1205,6 +1205,7 @@ "wallet__send_sync_long_title" = "Problemas de\nconexión"; "wallet__send_sync_long_description" = "Parece que está desconectado. Compruebe su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Ruta"; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 4074d833ea..a9e5c56035 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1305,6 +1305,7 @@ "wallet__send_sync_long_title" = "Problèmes de\nconnexion"; "wallet__send_sync_long_description" = "Il semble que vous soyez déconnecté. Veuillez vérifier votre connexion. Bitkit tentera de se reconnecter toutes les quelques secondes."; "wallet__send_to" = "Pour"; +"wallet__send_swap_route" = "Itinéraire"; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index ff531fab8b..966c8eb746 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1270,6 +1270,7 @@ "wallet__send_sync_long_title" = "Problemi di\nconnessione"; "wallet__send_sync_long_description" = "Sembra che tu sia disconnesso. Controlla la connessione. Bitkit proverà a riconnettersi ogni pochi secondi."; "wallet__send_to" = "A"; +"wallet__send_swap_route" = "Percorso"; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 087be4fee7..05327a774d 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1300,6 +1300,7 @@ "wallet__send_sync_long_title" = "Verbindings\nproblemen"; "wallet__send_sync_long_description" = "Het lijkt erop dat u niet verbonden bent. Controleer uw verbinding. Bitkit probeert om de paar seconden opnieuw verbinding te maken."; "wallet__send_to" = "Naar"; +"wallet__send_swap_route" = "Route"; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 1cd7e31c2a..4981a4c1de 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1304,6 +1304,7 @@ "wallet__send_sync_long_title" = "Problemy\nz połączeniem"; "wallet__send_sync_long_description" = "Wygląda na to, że nie masz połączenia. Sprawdź połączenie. Bitkit będzie próbował połączyć się ponownie co kilka sekund."; "wallet__send_to" = "Do"; +"wallet__send_swap_route" = "Trasa"; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index bd54df0b47..9608d304d5 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1305,6 +1305,7 @@ "wallet__send_sync_long_title" = "Problemas de\nconexão"; "wallet__send_sync_long_description" = "Parece que você está desconectado. Verifique sua conexão. A Bitkit tentará se reconectar a cada poucos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Rota"; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 5ab90bafdc..3b4c0052ce 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1059,6 +1059,7 @@ "wallet__send_sync_long_title" = "Problemas\nde ligação"; "wallet__send_sync_long_description" = "Parece que está desligado. Verifique a sua ligação. A Bitkit vai tentar voltar a ligar a cada poucos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Rota"; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index d2df40a5b4..1a4cc839fc 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1289,6 +1289,7 @@ "wallet__send_sync_long_title" = "Проблемы\nс подключением"; "wallet__send_sync_long_description" = "Похоже, вы отключены. Проверьте подключение. Bitkit будет пытаться переподключиться каждые несколько секунд."; "wallet__send_to" = "Кому"; +"wallet__send_swap_route" = "Маршрут"; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift new file mode 100644 index 0000000000..0b17a0be98 --- /dev/null +++ b/Bitkit/Services/PubkySwapsRouteService.swift @@ -0,0 +1,98 @@ +import BitkitCore +import Foundation + +/// A Paykit payment routed through a Pubky Swaps provider: the endpoint, the route once quoted, and its provider. +struct PaykitSwapRoute: Equatable { + let endpoint: PaykitEndpoint + var quote: PubkySwapRouteQuote? + var providerName: String? +} + +/// Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the +/// contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays +/// the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. +enum PubkySwapsRouteService { + private static let claimFeeRateSatVb: UInt64 = 2 + private static let pollInterval: Duration = .seconds(2) + private static let claimTimeout: TimeInterval = 10 * 60 + + static var isEnabled: Bool { + Env.isPubkySwapsRouteEnabled + } + + /// A contact whose only endpoints are on-chain, paid when savings cannot cover it but spending can. + static func route(for context: ContactPaymentContext, address: String, onchainBalanceSats: UInt64, + lightningBalanceSats: UInt64) -> PaykitSwapRoute? + { + guard isEnabled, context.incomingPaymentRequest == nil, !address.isEmpty, + !context.endpoints.isEmpty, context.endpoints.allSatisfy({ $0.methodId.onchainNetwork != nil }), + onchainBalanceSats <= UInt64(Env.dustLimit), lightningBalanceSats > 0, + let methodId = context.endpoints.first?.methodId + else { return nil } + return PaykitSwapRoute(endpoint: PaykitEndpoint(methodId: methodId.rawValue, value: address)) + } + + static func quote( + amountSats: UInt64, + endpoint: PaykitEndpoint, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + contacts: [String] + ) async throws -> PaykitRoute { + // Providers come from the user's own graph: every contact is asked for its swap offer. + let candidates = contacts + Env.pubkySwapsProviders + Logger.debug("Routing Paykit payment via \(candidates.map(PubkyPublicKeyFormat.redacted))", context: "PubkySwapsRoute") + let (mnemonic, passphrase) = try secrets() + return try await pubkySwapsRoutePaykitPayment( + request: PaykitRouteRequest( + amountSat: amountSats, + contactEndpoints: [endpoint], + lightningSpendableSat: lightningSpendableSats, + onchainSpendableSat: onchainSpendableSats, + providers: candidates, + feeRateSatVb: claimFeeRateSatVb + ), + network: Env.bitkitCoreNetwork, + mnemonic: mnemonic, + bip39Passphrase: passphrase + ) + } + + static func commit(quoteId: String) async throws -> PubkySwapRoutePayment { + let (mnemonic, passphrase) = try secrets() + return try await pubkySwapsCommitRoute( + quoteId: quoteId, + electrumUrl: Env.electrumServerUrl, + mnemonic: mnemonic, + bip39Passphrase: passphrase + ) + } + + /// Advance the swap until bitkit-core claims the lockup to the contact, returning the claim txid. + static func awaitClaim(swapId: String) async throws -> String { + let deadline = Date().addingTimeInterval(claimTimeout) + while true { + let (mnemonic, passphrase) = try secrets() + let status = try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase) + switch status.state { + case let .claimed(txid): + return txid + case let .failed(reason): + throw AppError(message: reason, debugMessage: nil) + default: + Logger.debug("Pubky Swaps route \(swapId): \(status.state)", context: "PubkySwapsRoute") + } + guard Date() < deadline else { + throw AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(status.state)") + } + try await Task.sleep(for: pollInterval) + } + } + + private static func secrets() throws -> (String, String?) { + guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: 0)) else { + throw AppError(message: "Mnemonic not found", debugMessage: nil) + } + return (mnemonic, try? Keychain.loadString(key: .bip39Passphrase(index: 0))) + } +} diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index ce446259fb..9026187630 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -167,6 +167,7 @@ class AppViewModel: ObservableObject { @Published var contactPaymentContext: ContactPaymentContext? private(set) var didRejectScannedPayment = false @Published var paykitUsesUsdt = false + @Published var paykitSwapRoute: PaykitSwapRoute? @Published var paykitReviewedAmount: PaykitAmount? @Published var paykitPaymentTerms: PaykitRequestPricing.Payment? @@ -1035,6 +1036,18 @@ extension AppViewModel { // Fallback to on-chain if address is available guard !invoice.address.isEmpty, validateIncomingOnchainPaymentRequestAmount(requestedAmount ?? invoice.amountSatoshis) else { return } + if let context = contactPaymentContext, let route = PubkySwapsRouteService.route( + for: context, + address: invoice.address, + onchainBalanceSats: max(paymentState.spendableOnchainBalanceSats, alternativeOnchainBalanceSats), + lightningBalanceSats: paymentState.totalLightningBalanceSats + ) { + handleScannedOnchainInvoice(invoice) + paykitSwapRoute = route + selectedWalletToPayFrom = .lightning + return + } + // If node is running, validate balance immediately if paymentState.isNodeRunning { let onchainBalance = max( @@ -1380,6 +1393,7 @@ extension AppViewModel { sendStateOwnerID = ownerID sendStateGeneration = UUID() paykitUsesUsdt = false + paykitSwapRoute = nil paykitReviewedAmount = nil paykitPaymentTerms = nil scannedLightningInvoice = nil diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index ba37f24e7a..b5f3e153d6 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -10,6 +10,7 @@ enum SendFundingSource: Equatable { struct SendAmountView: View { @Environment(\.dismiss) private var dismiss @EnvironmentObject var app: AppViewModel + @EnvironmentObject private var contactsManager: ContactsManager @EnvironmentObject var currency: CurrencyViewModel @EnvironmentObject var settings: SettingsViewModel @EnvironmentObject var wallet: WalletViewModel @@ -43,6 +44,9 @@ struct SendAmountView: View { { return [.usdt] } + if app.paykitSwapRoute != nil { + return [.spending] + } var sources: [SendFundingSource] = [] if app.scannedLightningInvoice != nil || app.lnurlPayData != nil { sources.append(.spending) @@ -400,6 +404,12 @@ struct SendAmountView: View { return } + if let route = app.paykitSwapRoute { + guard await quoteSwapRoute(route) else { return } + navigationPath.append(.confirm) + return + } + navigationPath.append(app.lnurlPayData != nil && app.scannedLightningInvoice == nil ? .lnurlPayConfirm : .confirm) return } @@ -448,6 +458,36 @@ struct SendAmountView: View { } } + private func quoteSwapRoute(_ route: PaykitSwapRoute) async -> Bool { + do { + let paykitRoute = try await PubkySwapsRouteService.quote( + amountSats: amountSats, + endpoint: route.endpoint, + lightningSpendableSats: UInt64(wallet.maxSendLightningSats), + onchainSpendableSats: UInt64(wallet.spendableOnchainBalanceSats), + contacts: contactsManager.contacts.map(\.publicKey) + ) + switch paykitRoute { + case let .swap(quote): + var quoted = route + quoted.quote = quote + quoted.providerName = contactsManager.contacts + .first { PubkyPublicKeyFormat.matches($0.publicKey, quote.providerPubky) }?.displayName + app.paykitSwapRoute = quoted + return true + case let .none(reason): + app.toast(type: .error, title: t("slashtags__error_pay_title"), description: reason) + case .direct: + app.paykitSwapRoute = nil + app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) + } + } catch { + Logger.error("Failed to route Paykit payment through Pubky Swaps: \(error)", context: "SendAmountView") + app.toast(type: .error, title: t("slashtags__error_pay_title"), description: error.localizedDescription) + } + return false + } + private func updateInputCap() { // Don't cap when nothing is sendable, so the pad stays usable (Continue stays disabled instead). amountViewModel.maxAmountOverride = availableAmount > 0 ? availableAmount : nil diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 9e5f470f3a..387766ecd1 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -3,6 +3,8 @@ import LDKNode import SwiftUI struct SendConfirmationView: View { + private static let providerKeyLength = 12 + @Environment(PaykitPaymentRequestManager.self) private var paykitPaymentRequestManager @EnvironmentObject var app: AppViewModel @EnvironmentObject var activityList: ActivityListViewModel @@ -331,6 +333,13 @@ struct SendConfirmationView: View { PaykitAmountText(amount: preparingRequest.amount, size: .display) .accessibilityIdentifier("ReviewAmount") } + } else if let quote = app.paykitSwapRoute?.quote { + MoneyStack( + sats: Int(wallet.sendAmountSats ?? quote.deliveredSat), + showSymbol: true, + testIdPrefix: "ReviewAmount", + onTap: navigateToAmount + ) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { MoneyStack( sats: Int(wallet.sendAmountSats ?? invoice.amountSatoshis), @@ -352,7 +361,9 @@ struct SendConfirmationView: View { .padding(.bottom, oneOffPaymentRequest == nil ? 44 : 24) if showDetails { - if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { + if let route = app.paykitSwapRoute, let quote = route.quote { + swapRouteView(route, quote: quote) + } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { onchainView(invoice) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { lightningView(invoice) @@ -701,6 +712,62 @@ struct SendConfirmationView: View { } } + func swapRouteView(_ route: PaykitSwapRoute, quote: PubkySwapRouteQuote) -> some View { + VStack(alignment: .leading, spacing: 16) { + HStack { + SendSectionView(t("wallet__send_from")) { + NumberPadActionButton( + text: t("wallet__spending__title"), + color: .purpleAccent, + variant: .secondary, + disabled: true + ) {} + .accessibilityIdentifier("SendConfirmAssetButton") + } + + Spacer(minLength: 16) + + if let contact = contactPaymentContact { + SendSectionView(contactSectionTitle) { + contactRecipient(contact) + } + } + } + + HStack(alignment: .top, spacing: 16) { + SendSectionView(t("wallet__send_fee_and_speed")) { + HStack(spacing: 0) { + Image("bolt-hollow") + .foregroundColor(.purpleAccent) + .frame(width: 16, height: 16) + .padding(.trailing, 4) + BodySSBText("\(t("fee__instant__title")) (") + MoneyText(sats: Int(quote.totalFeeSat), size: .bodySSB, symbol: true, symbolColor: .textPrimary) + BodySSBText(")") + } + } + + SendSectionView(t("wallet__send_swap_route")) { + BodySSBText("Pubky Swaps · \(route.providerName ?? quote.providerPubky.ellipsis(maxLength: Self.providerKeyLength))") + .lineLimit(2) + .accessibilityIdentifier("ReviewSwapRoute") + } + } + + 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") + } + } + } + } + } + func lightningView(_ invoice: LightningInvoice) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { @@ -952,6 +1019,8 @@ struct SendConfirmationView: View { if hwSend.isActive { navigationPath.append(.hardwareSign) + } else if let quote = app.paykitSwapRoute?.quote { + await performSwapRoutedPayment(quote) } else { try await performPayment(isAutomatic: isAutomatic) } @@ -1220,6 +1289,28 @@ struct SendConfirmationView: View { return note } + private func performSwapRoutedPayment(_ quote: PubkySwapRouteQuote) async { + isSubmittingPayment = true + defer { isSubmittingPayment = false } + do { + let payment = try await PubkySwapsRouteService.commit(quoteId: quote.quoteId) + Logger.info("Committed Pubky Swaps route \(payment.swapId) to \(payment.destinationAddress)", context: "SendConfirmation") + // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. + let paymentHash = try await LightningService.shared.send(bolt11: payment.invoice) + let claimTxid = try await PubkySwapsRouteService.awaitClaim(swapId: payment.swapId) + Logger.info("Claimed Pubky Swaps route \(payment.swapId) in \(claimTxid)", context: "SendConfirmation") + navigationPath.append(.success(paymentId: String(paymentHash))) + } catch { + Logger.error("Pubky Swaps route payment failed: \(error)", context: "SendConfirmation") + navigationPath.append(.failure(SendFailureContext( + error: error, + retryRoute: .confirm, + routingCacheResetAttempted: routingCacheResetAttempted, + paymentRequest: nil + ))) + } + } + private func performPayment(isAutomatic: Bool) async throws { let paymentActivity = PaykitPaymentActivity.shared.begin() defer { PaykitPaymentActivity.shared.end(paymentActivity) } diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 8132cbfd91..5c8f3e81d6 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -872,8 +872,8 @@ struct SendSheet: View { } } - // Validate onchain payment balance (for pure onchain invoices) - if let onchainInvoice = app.scannedOnchainInvoice { + // Validate onchain payment balance (for pure onchain invoices); a swap route pays it from spending + if app.paykitSwapRoute == nil, let onchainInvoice = app.scannedOnchainInvoice { let onchainBalance = max( LightningService.shared.balances?.spendableOnchainBalanceSats ?? 0, hwWalletManager.maximumFundingBalanceSats From c32983d09e0a5eb39e8c7b5bfa53ecc1d8959dd8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 05:26:13 +0100 Subject: [PATCH 02/64] docs: add the paykit swap route journey --- journeys/README.md | 1 + journeys/paykit-swap-route.xml | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 journeys/paykit-swap-route.xml diff --git a/journeys/README.md b/journeys/README.md index 53b04b44c8..9cf9e0f4d6 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -191,6 +191,7 @@ Known naming differences: | Pubky Ring choice row lookup spinner | `PubkyChoiceIdentityLookup` (the same tag on every row) | `PubkyChoiceRingLookup_` (bare z32 key) | | Contact import overview profile and friend count | — *(no tag; read the "Import" title and the "N friends" text)* | `ContactImportOverviewProfile`, `ContactImportOverviewSummary` | | Lightning Connections add connection | `add_connection_button` | `NavigationAction` | +| Send contact row | `SendContact_` | `SendContact-` | `SubscriptionRow-` matches Android exactly. `PaymentRequestRow` keeps that prefix but appends the billing period (`-one-time` for a one-off), because every recurring payment of one diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml new file mode 100644 index 0000000000..3499e94901 --- /dev/null +++ b/journeys/paykit-swap-route.xml @@ -0,0 +1,29 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet that holds only a spending + balance, routes through a Pubky Swaps provider found among the user's own contacts, without the user picking a + swap, and that the contact receives the exact amount on chain. + + Preconditions: a Debug build with SWIFT_ACTIVE_COMPILATION_CONDITIONS including E2E_BUILD, E2E_BACKEND=local, + E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver, launched with the + -PUBKY_SWAPS_ROUTES=true argument; bitkit-docker's default stack with the marketplace, payment-requests and + lnurl-pay profiles; the provider running against bitkit-docker's LND and funded. The simulator reaches the host's + loopback directly, so it needs no port forwarding. + The wallet has a spending balance from an LNURL channel with bitkit-docker's LND and an empty savings balance, + a Pubky profile on the local homeserver, and both the provider's and the fixture-issuer's pubkys saved as contacts. + The contact is bitkit-docker's fixture-issuer, which publishes only a btc-regtest-p2wpkh endpoint. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Verify the contact list shows both the fixture-issuer and the provider, and tap the fixture-issuer (tag "SendContact-" followed by its pubky) + Verify the amount screen (tag "SendAmount") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Pubky Swaps" followed by the provider's shortened pubky + Swipe to pay (tag "GRAB") + Once the provider logs "HTLC funded; awaiting client claim", mine one block on bitkit-docker's bitcoind + Verify the Bitcoin Sent screen (tag "SendSuccess") is visible + Verify the provider logs "client claimed; hold invoice settled", and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the fixture-issuer's address + + From 82f2bb1b4977221b4a44b104d048dd2faa66b667 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 05:45:19 +0100 Subject: [PATCH 03/64] chore: add changelog fragment --- changelog.d/next/1170.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1170.added.md diff --git a/changelog.d/next/1170.added.md b/changelog.d/next/1170.added.md new file mode 100644 index 0000000000..d7dfa80257 --- /dev/null +++ b/changelog.d/next/1170.added.md @@ -0,0 +1 @@ +Bitkit can pay a contact who only accepts on-chain bitcoin from your spending balance, through a Pubky Swaps provider among your contacts. From 2ca81e4d9915f1c7df1b7f2ae2179a25569181da Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 13:33:25 +0100 Subject: [PATCH 04/64] chore: move to bitkit-core 0.8.0-swaps.3 --- Bitkit.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/swiftpm/Package.resolved | 4 ++-- Bitkit/Services/PubkySwapsRouteService.swift | 6 ++++-- Bitkit/Views/Wallets/Send/SendAmountView.swift | 3 +++ 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 506c381d51..e4bc9fec83 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1269,7 +1269,7 @@ repositoryURL = "https://github.com/synonymdev/bitkit-core"; requirement = { kind = exactVersion; - version = "0.8.0-swaps.2"; + version = "0.8.0-swaps.3"; }; }; 96E493A22C942FD1000E8BC2 /* XCRemoteSwiftPackageReference "swift-secp256k1" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 8ec52eb4e0..8dc4790115 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/bitkit-core", "state" : { - "revision" : "1abc3ff8bc40848951d19ae74259f004b78ce5be", - "version" : "0.8.0-swaps.2" + "revision" : "f701e77dd004f3e89c2f45dc21edf7e03963194a", + "version" : "0.8.0-swaps.3" } }, { diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift index 0b17a0be98..5669d936ea 100644 --- a/Bitkit/Services/PubkySwapsRouteService.swift +++ b/Bitkit/Services/PubkySwapsRouteService.swift @@ -37,7 +37,8 @@ enum PubkySwapsRouteService { endpoint: PaykitEndpoint, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64, - contacts: [String] + contacts: [String], + serviceLegs: [ServiceRouteLeg] = [] ) async throws -> PaykitRoute { // Providers come from the user's own graph: every contact is asked for its swap offer. let candidates = contacts + Env.pubkySwapsProviders @@ -50,7 +51,8 @@ enum PubkySwapsRouteService { lightningSpendableSat: lightningSpendableSats, onchainSpendableSat: onchainSpendableSats, providers: candidates, - feeRateSatVb: claimFeeRateSatVb + feeRateSatVb: claimFeeRateSatVb, + serviceLegs: serviceLegs ), network: Env.bitkitCoreNetwork, mnemonic: mnemonic, diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index b5f3e153d6..c46c57055f 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -477,6 +477,9 @@ struct SendAmountView: View { return true case let .none(reason): app.toast(type: .error, title: t("slashtags__error_pay_title"), description: reason) + case let .service(leg): + Logger.error("Unexpected service route \(leg.service)", context: "SendAmountView") + app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) case .direct: app.paykitSwapRoute = nil app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) From 4677e4f2d885cc64193da0ac7677fe937cb15818 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 13:38:31 +0100 Subject: [PATCH 05/64] feat: pay on-chain contacts from spark --- Bitkit/Managers/SparkManager.swift | 37 +++++++++++++++++ Bitkit/Services/PubkySwapsRouteService.swift | 34 +++++++++++++-- .../Views/Wallets/Send/SendAmountView.swift | 8 +++- .../Wallets/Send/SendConfirmationView.swift | 41 +++++++++++++++---- 4 files changed, 108 insertions(+), 12 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 332c179973..1d1f008b32 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -14,6 +14,8 @@ import Observation @Observable @MainActor final class SparkManager: ChannelFreeLightningRail { static let shared = SparkManager() + nonisolated static let routeService = "spark" + private nonisolated static let routeAtomicity = "trusted" private nonisolated(unsafe) static let exitStateChanged = PassthroughSubject() /// Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. nonisolated static var exitStateChangedPublisher: AnyPublisher { @@ -324,6 +326,41 @@ final class SparkManager: ChannelFreeLightningRail { return response } + /// A Paykit route that withdraws exactly `amountSats` to the contact's on-chain `endpoint` at medium speed, with + /// Spark's fee on top, or nil while Spark cannot send it. bitkit-core weighs it against the Pubky Swaps providers. + func withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: UInt64) async throws -> ServiceRouteLeg? { + guard isReady, balanceSats >= amountSats else { return nil } + let prepared = try await prepareSend(paymentRequest: endpoint.value, amountSats: amountSats) + guard case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod else { + throw AppError(message: "Unexpected Spark payment method", debugMessage: "\(prepared.paymentMethod)") + } + let debitSats = amountSats + feeQuote.speedMedium.userFeeSat + guard !feeQuote.isEstimate, balanceSats >= debitSats else { return nil } + return ServiceRouteLeg( + service: Self.routeService, + endpoint: endpoint, + deliveredSat: amountSats, + debitSat: debitSats, + atomicity: Self.routeAtomicity, + validUntilUnix: feeQuote.expiresAt + ) + } + + /// Withdraws exactly `amountSats` to the on-chain `address` at medium speed and returns the withdrawal's txid. + func withdraw(to address: String, amountSats: UInt64) async throws -> String { + let prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) + let response = try await requireSdk().sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: .bitcoinAddress(confirmationSpeed: .medium) + )) + Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") + try await refresh() + if case let .withdraw(txId) = response.payment.details { + return txId + } + return response.payment.id + } + /// What a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. func exportExitState() async throws -> String { try await requireSdk().exportUnilateralExitState().exitState diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift index 5669d936ea..2e13d9375b 100644 --- a/Bitkit/Services/PubkySwapsRouteService.swift +++ b/Bitkit/Services/PubkySwapsRouteService.swift @@ -1,11 +1,21 @@ import BitkitCore import Foundation -/// A Paykit payment routed through a Pubky Swaps provider: the endpoint, the route once quoted, and its provider. +/// A Paykit payment routed through a Pubky Swaps provider or a service the wallet holds a balance on: the endpoint, +/// the route once quoted (a provider's quote or a service leg), and the provider's name. struct PaykitSwapRoute: Equatable { let endpoint: PaykitEndpoint var quote: PubkySwapRouteQuote? var providerName: String? + var serviceLeg: ServiceRouteLeg? + + var deliveredSat: UInt64? { + quote?.deliveredSat ?? serviceLeg?.deliveredSat + } + + var totalFeeSat: UInt64? { + quote?.totalFeeSat ?? serviceLeg.map { $0.debitSat - $0.deliveredSat } + } } /// Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the @@ -37,11 +47,11 @@ enum PubkySwapsRouteService { endpoint: PaykitEndpoint, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64, - contacts: [String], - serviceLegs: [ServiceRouteLeg] = [] + contacts: [String] ) async throws -> PaykitRoute { // Providers come from the user's own graph: every contact is asked for its swap offer. let candidates = contacts + Env.pubkySwapsProviders + let serviceLegs = await serviceLegs(endpoint: endpoint, amountSats: amountSats) Logger.debug("Routing Paykit payment via \(candidates.map(PubkyPublicKeyFormat.redacted))", context: "PubkySwapsRoute") let (mnemonic, passphrase) = try secrets() return try await pubkySwapsRoutePaykitPayment( @@ -60,6 +70,24 @@ enum PubkySwapsRouteService { ) } + /// Legs through the services the wallet holds a balance on, which compete with the providers on fee. + private static func serviceLegs(endpoint: PaykitEndpoint, amountSats: UInt64) async -> [ServiceRouteLeg] { + do { + return try await SparkManager.shared.withdrawalRouteLeg(endpoint: endpoint, amountSats: amountSats).map { [$0] } ?? [] + } catch { + Logger.warn("No Spark route to \(endpoint.methodId): \(error)", context: "PubkySwapsRoute") + return [] + } + } + + /// Runs a service leg the router picked and returns the txid that pays the contact. + static func pay(_ leg: ServiceRouteLeg) async throws -> String { + guard leg.service == SparkManager.routeService else { + throw AppError(message: "Unsupported route service", debugMessage: leg.service) + } + return try await SparkManager.shared.withdraw(to: leg.endpoint.value, amountSats: leg.deliveredSat) + } + static func commit(quoteId: String) async throws -> PubkySwapRoutePayment { let (mnemonic, passphrase) = try secrets() return try await pubkySwapsCommitRoute( diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index c46c57055f..7f2e1d159e 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -471,6 +471,7 @@ struct SendAmountView: View { case let .swap(quote): var quoted = route quoted.quote = quote + quoted.serviceLeg = nil quoted.providerName = contactsManager.contacts .first { PubkyPublicKeyFormat.matches($0.publicKey, quote.providerPubky) }?.displayName app.paykitSwapRoute = quoted @@ -478,8 +479,11 @@ struct SendAmountView: View { case let .none(reason): app.toast(type: .error, title: t("slashtags__error_pay_title"), description: reason) case let .service(leg): - Logger.error("Unexpected service route \(leg.service)", context: "SendAmountView") - app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) + var quoted = route + quoted.quote = nil + quoted.serviceLeg = leg + app.paykitSwapRoute = quoted + return true case .direct: app.paykitSwapRoute = nil app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 387766ecd1..8beaa7bc4e 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -333,9 +333,9 @@ struct SendConfirmationView: View { PaykitAmountText(amount: preparingRequest.amount, size: .display) .accessibilityIdentifier("ReviewAmount") } - } else if let quote = app.paykitSwapRoute?.quote { + } else if let deliveredSat = app.paykitSwapRoute?.deliveredSat { MoneyStack( - sats: Int(wallet.sendAmountSats ?? quote.deliveredSat), + sats: Int(wallet.sendAmountSats ?? deliveredSat), showSymbol: true, testIdPrefix: "ReviewAmount", onTap: navigateToAmount @@ -361,8 +361,8 @@ struct SendConfirmationView: View { .padding(.bottom, oneOffPaymentRequest == nil ? 44 : 24) if showDetails { - if let route = app.paykitSwapRoute, let quote = route.quote { - swapRouteView(route, quote: quote) + if let route = app.paykitSwapRoute, let totalFeeSat = route.totalFeeSat { + swapRouteView(route, totalFeeSat: totalFeeSat) } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { onchainView(invoice) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { @@ -712,7 +712,7 @@ struct SendConfirmationView: View { } } - func swapRouteView(_ route: PaykitSwapRoute, quote: PubkySwapRouteQuote) -> some View { + func swapRouteView(_ route: PaykitSwapRoute, totalFeeSat: UInt64) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { SendSectionView(t("wallet__send_from")) { @@ -742,13 +742,13 @@ struct SendConfirmationView: View { .frame(width: 16, height: 16) .padding(.trailing, 4) BodySSBText("\(t("fee__instant__title")) (") - MoneyText(sats: Int(quote.totalFeeSat), size: .bodySSB, symbol: true, symbolColor: .textPrimary) + MoneyText(sats: Int(totalFeeSat), size: .bodySSB, symbol: true, symbolColor: .textPrimary) BodySSBText(")") } } SendSectionView(t("wallet__send_swap_route")) { - BodySSBText("Pubky Swaps · \(route.providerName ?? quote.providerPubky.ellipsis(maxLength: Self.providerKeyLength))") + BodySSBText(routeName(route)) .lineLimit(2) .accessibilityIdentifier("ReviewSwapRoute") } @@ -768,6 +768,13 @@ struct SendConfirmationView: View { } } + private func routeName(_ route: PaykitSwapRoute) -> String { + if let quote = route.quote { + return "Pubky Swaps · \(route.providerName ?? quote.providerPubky.ellipsis(maxLength: Self.providerKeyLength))" + } + return "Spark" + } + func lightningView(_ invoice: LightningInvoice) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { @@ -1019,6 +1026,8 @@ struct SendConfirmationView: View { if hwSend.isActive { navigationPath.append(.hardwareSign) + } else if let leg = app.paykitSwapRoute?.serviceLeg { + await performServiceRoutedPayment(leg) } else if let quote = app.paykitSwapRoute?.quote { await performSwapRoutedPayment(quote) } else { @@ -1289,6 +1298,24 @@ struct SendConfirmationView: View { return note } + private func performServiceRoutedPayment(_ leg: ServiceRouteLeg) async { + isSubmittingPayment = true + defer { isSubmittingPayment = false } + do { + let txid = try await PubkySwapsRouteService.pay(leg) + Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") + navigationPath.append(.success(paymentId: txid)) + } catch { + Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") + navigationPath.append(.failure(SendFailureContext( + error: error, + retryRoute: .confirm, + routingCacheResetAttempted: routingCacheResetAttempted, + paymentRequest: nil + ))) + } + } + private func performSwapRoutedPayment(_ quote: PubkySwapRouteQuote) async { isSubmittingPayment = true defer { isSubmittingPayment = false } From 38e8239e6816353b7468940f58f0db5d605ee808 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 14:11:19 +0100 Subject: [PATCH 06/64] chore: add changelog fragment --- changelog.d/next/1191.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1191.added.md diff --git a/changelog.d/next/1191.added.md b/changelog.d/next/1191.added.md new file mode 100644 index 0000000000..9dd64f6e8c --- /dev/null +++ b/changelog.d/next/1191.added.md @@ -0,0 +1 @@ +Paykit contacts who only accept on-chain bitcoin can be paid from Spark when that costs less than a swap. From 438d6ae53bdf2bdd70dcfa36524d3240a8c0b676 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 16:16:34 +0100 Subject: [PATCH 07/64] docs: add the paykit spark route journey --- journeys/paykit-spark-route.xml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 journeys/paykit-spark-route.xml diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml new file mode 100644 index 0000000000..9a0cd6d979 --- /dev/null +++ b/journeys/paykit-spark-route.xml @@ -0,0 +1,28 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet whose spending balance is held + on Spark, routes through a Spark withdrawal straight to the contact's address, without the user picking a route, + and that the contact receives the exact amount on chain. + + Preconditions: a Debug build with SWIFT_ACTIVE_COMPILATION_CONDITIONS including E2E_BUILD, E2E_BACKEND=local, + E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver, launched with the + -PUBKY_SWAPS_ROUTES=true argument; bitkit-docker's default stack with the marketplace and payment-requests + profiles. The simulator reaches the host's loopback directly, so it needs no port forwarding. + The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's + regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the + fixture-issuer's pubky saved as a contact. The contact is bitkit-docker's fixture-issuer, which publishes only a + btc-regtest-p2wpkh endpoint; Spark pays it on Lightspark's regtest chain. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Tap the fixture-issuer (tag "SendContact-" followed by its pubky) + Verify the amount screen (tag "SendAmount") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Spark" + Swipe to pay (tag "GRAB") + Verify the Bitcoin Sent screen (tag "SendSuccess") shows 20 000 + Verify Lightspark's regtest mempool shows the withdrawal transaction paying exactly 20 000 sats to the fixture-issuer's address + + From f0bcc7e4ca72a5bdcb0420a60b4107cebc2a63ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:47:18 +0100 Subject: [PATCH 08/64] fix: spark route reads the withdrawal txid on sdk 0.28 --- Bitkit/Managers/SparkManager.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index f75eee31ef..3312b73e06 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -370,7 +370,7 @@ final class SparkManager: ChannelFreeLightningRail { )) Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") try await refresh() - if case let .withdraw(txId) = response.payment.details { + if case let .withdraw(txId, _, _) = response.payment.details { return txId } return response.payment.id From db348780048f35a2ad4a07e079021b17805d2598 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 00:27:36 +0100 Subject: [PATCH 09/64] feat: route every contact payment through the paykit router Moves to bitkit-core 0.8.0-spark.3 and its `paykitRoutePayment`, and removes the Pubky Swaps code: the build flags, provider quotes, commit and claim, and their journey and changelog fragment. - On the amount screen, every bitcoin contact payment asks the router how to pay from the selected source: Spending offers all of the contact's bitcoin endpoints and a Spark leg to its on-chain ones, Savings only the on-chain endpoints. Direct pays the endpoint it picks, a Spark leg opens Confirm with Route: Spark and its fee, and none stays on the amount screen with the app's copy, its reason going to the log only. - An on-chain-only contact opens with Spending as a source while Spark can carry the payment, whether or not Savings covers it. - A Spark withdrawal to a contact is journaled before it is sent, settles from Spark's payment list on its event or on the next start, and is recorded as a sent on-chain activity for the contact, confirmed once Spark completes it. A second one waits while the first is open. --- Bitkit.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/swiftpm/Package.resolved | 4 +- Bitkit/Constants/Env.swift | 13 -- Bitkit/Managers/SparkManager.swift | 140 +++++++++++++-- .../Localization/ar.lproj/Localizable.strings | 2 + .../Localization/ca.lproj/Localizable.strings | 2 + .../Localization/cs.lproj/Localizable.strings | 2 + .../Localization/de.lproj/Localizable.strings | 2 + .../Localization/el.lproj/Localizable.strings | 2 + .../Localization/en.lproj/Localizable.strings | 2 + .../es-419.lproj/Localizable.strings | 2 + .../Localization/es.lproj/Localizable.strings | 2 + .../Localization/fr.lproj/Localizable.strings | 2 + .../Localization/it.lproj/Localizable.strings | 2 + .../Localization/nl.lproj/Localizable.strings | 2 + .../Localization/pl.lproj/Localizable.strings | 2 + .../pt-BR.lproj/Localizable.strings | 2 + .../Localization/pt.lproj/Localizable.strings | 2 + .../Localization/ru.lproj/Localizable.strings | 2 + Bitkit/Services/CoreService.swift | 18 ++ Bitkit/Services/PaykitRouteService.swift | 147 +++++++++++++++ Bitkit/Services/PubkySwapsRouteService.swift | 128 ------------- Bitkit/ViewModels/AppViewModel.swift | 25 +-- .../Views/Wallets/Send/SendAmountView.swift | 134 ++++++++++---- .../Wallets/Send/SendConfirmationView.swift | 47 +---- Bitkit/Views/Wallets/Send/SendSheet.swift | 4 +- BitkitTests/PaykitRouteTests.swift | 170 ++++++++++++++++++ changelog.d/next/1170.added.md | 1 - changelog.d/next/1191.added.md | 2 +- journeys/paykit-spark-route.xml | 3 +- journeys/paykit-swap-route.xml | 29 --- 31 files changed, 618 insertions(+), 279 deletions(-) create mode 100644 Bitkit/Services/PaykitRouteService.swift delete mode 100644 Bitkit/Services/PubkySwapsRouteService.swift create mode 100644 BitkitTests/PaykitRouteTests.swift delete mode 100644 changelog.d/next/1170.added.md delete mode 100644 journeys/paykit-swap-route.xml diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 650c0646f6..16018693be 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1278,7 +1278,7 @@ repositoryURL = "https://github.com/synonymdev/bitkit-core"; requirement = { kind = exactVersion; - version = "0.8.0-swaps.3"; + version = "0.8.0-spark.3"; }; }; 96E493A22C942FD1000E8BC2 /* XCRemoteSwiftPackageReference "swift-secp256k1" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index d02afd943a..ea2c5255b6 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/bitkit-core", "state" : { - "revision" : "f701e77dd004f3e89c2f45dc21edf7e03963194a", - "version" : "0.8.0-swaps.3" + "revision" : "ac704166d07935e393f3bcf363959b83f0ed3445", + "version" : "0.8.0-spark.3" } }, { diff --git a/Bitkit/Constants/Env.swift b/Bitkit/Constants/Env.swift index 9fb57c5e12..475fc8da1d 100644 --- a/Bitkit/Constants/Env.swift +++ b/Bitkit/Constants/Env.swift @@ -237,19 +237,6 @@ enum Env { return electrumServerUrl(for: network) } - /// Whether a Paykit payment may route through a Pubky Swaps provider when no balance reaches the contact's - /// endpoints. Regtest debug builds with `PUBKY_SWAPS_ROUTES=true` only. - static var isPubkySwapsRouteEnabled: Bool { - isDebug && network == .regtest && boolConfigValue("PUBKY_SWAPS_ROUTES") - } - - /// Swap providers to ask besides the user's contacts, from `PUBKY_SWAPS_PROVIDERS` (comma-separated pubkys). - static var pubkySwapsProviders: [String] { - (configValue("PUBKY_SWAPS_PROVIDERS") ?? "").split(separator: ",") - .map { $0.trimmingCharacters(in: .whitespaces) } - .filter { !$0.isEmpty } - } - static var trezorBridgeEnabled: Bool { (isDebug || isE2E) && boolConfigValue("TREZOR_BRIDGE") } diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index cdfc5f405b..a12951822a 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -51,6 +51,8 @@ final class SparkManager: ChannelFreeLightningRail { /// The refresh in flight; callers during it wait for it, and it reads once more for them. @ObservationIgnored private var refreshTask: Task? @ObservationIgnored private var refreshAgain = false + /// A contact withdrawal is being sent, so its journal entry isn't settled from a list that can't show it yet. + @ObservationIgnored private var isWithdrawingToContact = false private init() {} @@ -98,6 +100,7 @@ final class SparkManager: ChannelFreeLightningRail { LightningService.shared.channelFreeRail = self try await refresh() try await syncActivities() + await settleContactWithdrawal(allowClear: false) } catch { connectTask = nil Logger.error("Failed to start Spark wallet: \(error)", context: "SparkManager") @@ -183,6 +186,8 @@ final class SparkManager: ChannelFreeLightningRail { sendsRecordedWithoutFee = [] sentWithdrawalTxIds = [] preparedWithdrawal = nil + Self.pendingContactWithdrawal = nil + Self.contactWithdrawalTxIds = [] onStateChanged?() try Self.removeIfPresent(Env.sparkStorage(walletIndex: walletIndex)) try Self.removeIfPresent(Env.sparkExitRestore(walletIndex: walletIndex)) @@ -435,7 +440,8 @@ final class SparkManager: ChannelFreeLightningRail { } /// A Paykit route that withdraws exactly `amountSats` to the contact's on-chain `endpoint` at medium speed, with - /// Spark's fee on top, or nil while Spark cannot send it. bitkit-core weighs it against the Pubky Swaps providers. + /// Spark's fee on top, or nil while Spark cannot send it. bitkit-core's Paykit router weighs it against the contact's + /// other endpoints. func withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: UInt64) async throws -> ServiceRouteLeg? { guard isReady, balanceSats >= amountSats else { return nil } let prepared = try await prepareSend(paymentRequest: endpoint.value, amountSats: amountSats) @@ -454,19 +460,110 @@ final class SparkManager: ChannelFreeLightningRail { ) } - /// Withdraws exactly `amountSats` to the on-chain `address` at medium speed and returns the withdrawal's txid. - func withdraw(to address: String, amountSats: UInt64) async throws -> String { + /// Withdraws exactly `amountSats` to a contact's on-chain `address` at medium speed and returns its txid. The + /// withdrawal is written to a journal before it is sent, so one interrupted mid-send settles from Spark's payment + /// list; a second one is refused while it is open. It is recorded as a sent on-chain activity for the contact. + func withdraw(to address: String, amountSats: UInt64, contact: String?) async throws -> String { + guard Self.pendingContactWithdrawal == nil else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") + } let prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) - let response = try await requireSdk().sendPayment(request: SendPaymentRequest( - prepareResponse: prepared, - options: .bitcoinAddress(confirmationSpeed: .medium) - )) + let pending = SparkContactWithdrawal( + address: address, + amountSats: amountSats, + contact: contact, + startedAt: UInt64(Date().timeIntervalSince1970) + ) + Self.pendingContactWithdrawal = pending + isWithdrawingToContact = true + defer { isWithdrawingToContact = false } + let response: SendPaymentResponse + do { + response = try await requireSdk().sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: .bitcoinAddress(confirmationSpeed: .medium) + )) + } catch { + Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") + Task { + _ = try? await requireSdk().syncWallet(request: SyncWalletRequest()) + await settleContactWithdrawal(allowClear: true) + } + throw error + } Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") - try await refresh() - if case let .withdraw(txId, _, _) = response.payment.details { - return txId + guard case let .withdraw(txId, _, _) = response.payment.details else { + await refreshState() + return response.payment.id + } + await recordContactWithdrawal(response.payment, txId: txId, pending: pending) + await refreshState() + return txId + } + + /// Settles the open contact withdrawal from Spark's payments: a withdrawal of its amount sent since it started is + /// recorded; with `allowClear`, a synced list without one closes it as never sent. + func settleContactWithdrawal(allowClear: Bool) async { + guard let pending = Self.pendingContactWithdrawal, !isWithdrawingToContact, + let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + else { return } + if let payment = Self.matchingWithdrawal(pending, in: payments), case let .withdraw(txId, _, _) = payment.details { + await recordContactWithdrawal(payment, txId: txId, pending: pending) + } else if allowClear { + Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") + Self.pendingContactWithdrawal = nil + } + } + + nonisolated static func matchingWithdrawal(_ pending: SparkContactWithdrawal, in payments: [Payment]) -> Payment? { + payments.first { payment in + guard payment.paymentType == .send, case let .withdraw(_, _, destination) = payment.details else { return false } + return destination == pending.address && sats(payment.amount) == pending.amountSats && + payment.timestamp + contactWithdrawalClockSkewSecs >= pending.startedAt } - return response.payment.id + } + + private nonisolated static let contactWithdrawalClockSkewSecs: UInt64 = 120 + + private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { + Self.pendingContactWithdrawal = nil + guard payment.status != .failed else { return } + Self.contactWithdrawalTxIds.insert(txId) + _ = await CoreService.shared.activity.createSentOnchainActivityFromSendResult( + txid: txId, + address: pending.address, + amount: pending.amountSats, + fee: Self.sats(payment.fees), + feeRate: 0, + contact: pending.contact, + feeIsExact: true + ) + if payment.status == .completed { + await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) + } + } + + private nonisolated static let pendingContactWithdrawalKey = "sparkPendingContactWithdrawal" + private nonisolated static let contactWithdrawalTxIdsKey = "sparkContactWithdrawalTxIds" + + nonisolated static var pendingContactWithdrawal: SparkContactWithdrawal? { + get { + UserDefaults.standard.data(forKey: pendingContactWithdrawalKey) + .flatMap { try? JSONDecoder().decode(SparkContactWithdrawal.self, from: $0) } + } + set { + if let newValue, let data = try? JSONEncoder().encode(newValue) { + UserDefaults.standard.set(data, forKey: pendingContactWithdrawalKey) + } else { + UserDefaults.standard.removeObject(forKey: pendingContactWithdrawalKey) + } + } + } + + /// Withdrawals paid to contacts, which stay sent payments rather than transfers to Savings. + nonisolated static var contactWithdrawalTxIds: Set { + get { Set(UserDefaults.standard.stringArray(forKey: contactWithdrawalTxIdsKey) ?? []) } + set { UserDefaults.standard.set(Array(newValue), forKey: contactWithdrawalTxIdsKey) } } /// What a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. @@ -623,9 +720,15 @@ final class SparkManager: ChannelFreeLightningRail { for payment in payments where sendsRecordedWithoutFee.contains(payment.id) && Self.sats(payment.fees) > 0 { await recordActivity(payment) } - for txId in Self.transferTxIds(unclaimed: unclaimed, payments: payments) { + let contactWithdrawals = Self.contactWithdrawalTxIds + for txId in Self.transferTxIds(unclaimed: unclaimed, payments: payments) where !contactWithdrawals.contains(txId) { await CoreService.shared.activity.markOnchainActivityAsTransfer(txId: txId) } + for payment in payments where payment.status == .completed { + if case let .withdraw(txId, _, _) = payment.details, contactWithdrawals.contains(txId) { + await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) + } + } } nonisolated static func withdrawals(_ payments: [Payment]) -> [SparkWithdrawal] { @@ -690,7 +793,10 @@ final class SparkManager: ChannelFreeLightningRail { private func onSdkEvent(_ event: SdkEvent) async { switch event { - case .synced, .newDeposits, .claimedDeposits: + case .synced: + await refreshState() + await settleContactWithdrawal(allowClear: true) + case .newDeposits, .claimedDeposits: await refreshState() case let .unclaimedDeposits(deposits): Logger.warn("Found '\(deposits.count)' unclaimed Spark deposits", context: "SparkManager") @@ -927,6 +1033,14 @@ enum SparkErrorCopy { } } +/// A Spark withdrawal to a contact's on-chain address, journaled before it is sent. +struct SparkContactWithdrawal: Codable, Equatable { + let address: String + let amountSats: UInt64 + let contact: String? + let startedAt: UInt64 +} + struct SparkWithdrawal: Identifiable, Equatable { let txid: String let amountSats: UInt64 diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index be9c7323a6..7963f87a57 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1070,6 +1070,8 @@ "wallet__send_sync_long_description" = "يبدو أنك غير متصل. يرجى التحقق من اتصالك. سيحاول Bitkit إعادة الاتصال كل بضع ثوانٍ."; "wallet__send_to" = "إلى"; "wallet__send_swap_route" = "المسار"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 891fb3ba3d..c4a74f8915 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1189,6 +1189,8 @@ "wallet__send_sync_long_description" = "Sembla que estàs desconnectat. Comprova la connexió. Bitkit intentarà tornar a connectar-se cada pocs segons."; "wallet__send_to" = "A"; "wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 5fe0df6010..22d3b357c8 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1296,6 +1296,8 @@ "wallet__send_sync_long_description" = "Zdá se, že jste odpojeni. Zkontrolujte prosím připojení. Bitkit se bude každých několik sekund pokoušet znovu připojit."; "wallet__send_to" = "Komu"; "wallet__send_swap_route" = "Trasa"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 5bed6d7d6d..924505d383 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1294,6 +1294,8 @@ "wallet__send_sync_long_description" = "Anscheinend bist du nicht verbunden. Bitte überprüfe deine Verbindung. Bitkit versucht alle paar Sekunden, sich erneut zu verbinden."; "wallet__send_to" = "An"; "wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 8fea8d9ac4..dbb52478ec 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1088,6 +1088,8 @@ "wallet__send_sync_long_description" = "Φαίνεται ότι είστε αποσυνδεδεμένοι. Ελέγξτε τη σύνδεσή σας. Το Bitkit θα προσπαθεί να επανασυνδεθεί κάθε λίγα δευτερόλεπτα."; "wallet__send_to" = "Προς"; "wallet__send_swap_route" = "Διαδρομή"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 4781ee722d..1797d581dd 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1309,6 +1309,8 @@ "wallet__send_sync_long_description" = "It appears you’re disconnected. Please check your connection. Bitkit will try to reconnect every few seconds."; "wallet__send_to" = "To"; "wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Paste Invoice"; "wallet__recipient_manual" = "Enter Manually"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 44c2b3cc59..19f2a53dfc 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1299,6 +1299,8 @@ "wallet__send_sync_long_description" = "Parece que está desconectado. Revise su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index b0d12e27d5..8de63a51d7 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1207,6 +1207,8 @@ "wallet__send_sync_long_description" = "Parece que está desconectado. Compruebe su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index d28316896e..293fad89a2 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1307,6 +1307,8 @@ "wallet__send_sync_long_description" = "Il semble que vous soyez déconnecté. Veuillez vérifier votre connexion. Bitkit tentera de se reconnecter toutes les quelques secondes."; "wallet__send_to" = "Pour"; "wallet__send_swap_route" = "Itinéraire"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 7e25bc3cff..707f161c02 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1272,6 +1272,8 @@ "wallet__send_sync_long_description" = "Sembra che tu sia disconnesso. Controlla la connessione. Bitkit proverà a riconnettersi ogni pochi secondi."; "wallet__send_to" = "A"; "wallet__send_swap_route" = "Percorso"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 7cd3454ae7..3e74cc3a6f 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1302,6 +1302,8 @@ "wallet__send_sync_long_description" = "Het lijkt erop dat u niet verbonden bent. Controleer uw verbinding. Bitkit probeert om de paar seconden opnieuw verbinding te maken."; "wallet__send_to" = "Naar"; "wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 521f10f872..1cd27fb4bb 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1306,6 +1306,8 @@ "wallet__send_sync_long_description" = "Wygląda na to, że nie masz połączenia. Sprawdź połączenie. Bitkit będzie próbował połączyć się ponownie co kilka sekund."; "wallet__send_to" = "Do"; "wallet__send_swap_route" = "Trasa"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 35c0ab87ef..6f91384934 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1307,6 +1307,8 @@ "wallet__send_sync_long_description" = "Parece que você está desconectado. Verifique sua conexão. A Bitkit tentará se reconectar a cada poucos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Rota"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index bc0adeff1c..e01173050a 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1061,6 +1061,8 @@ "wallet__send_sync_long_description" = "Parece que está desligado. Verifique a sua ligação. A Bitkit vai tentar voltar a ligar a cada poucos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Rota"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 002cecabaf..e64980d161 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1291,6 +1291,8 @@ "wallet__send_sync_long_description" = "Похоже, вы отключены. Проверьте подключение. Bitkit будет пытаться переподключиться каждые несколько секунд."; "wallet__send_to" = "Кому"; "wallet__send_swap_route" = "Маршрут"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 7677c57e74..06ef7729bf 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1486,6 +1486,24 @@ class ActivityService { } } + /// Marks a sent on-chain activity the node doesn't watch, such as a Spark withdrawal to a contact, as confirmed once + /// its sender reports it complete. + func markOnchainActivityAsConfirmed(txId: String) async { + do { + try await ServiceQueue.background(.core) { + guard let existing = try BitkitCore.getActivityByTxId(walletId: WalletScope.default, txId: txId), + !existing.confirmed + else { return } + var updated = existing + updated.confirmed = true + try updateActivity(activityId: existing.id, activity: .onchain(updated)) + self.activitiesChangedSubject.send() + } + } catch { + Logger.error("Failed to mark activity as confirmed for \(txId): \(error)", context: "ActivityService") + } + } + /// Marks the on-chain activity for `txId` as a transfer between Savings and Spending that has no channel, /// such as a Spark deposit or withdrawal. No-op until the activity exists or once it is marked. func markOnchainActivityAsTransfer(txId: String) async { diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift new file mode 100644 index 0000000000..56f5b5b3b4 --- /dev/null +++ b/Bitkit/Services/PaykitRouteService.swift @@ -0,0 +1,147 @@ +import BitkitCore +import Foundation + +/// A contact payment bitkit-core's Paykit router picks the way for: the contact's bitcoin endpoints, whether a Spark leg +/// may reach its on-chain ones, and the leg once the router picked one. +struct PaykitRouteUi: Equatable { + let endpoints: [PaykitEndpoint] + let offersSparkLeg: Bool + var serviceLeg: ServiceRouteLeg? + + var deliveredSat: UInt64? { + serviceLeg?.deliveredSat + } + + var totalFeeSat: UInt64? { + serviceLeg.map { $0.debitSat.saturatingSub($0.deliveredSat) } + } + + var onchainEndpoints: [PaykitEndpoint] { + endpoints.filter(\.isOnchain) + } +} + +extension PaykitEndpoint { + var isOnchain: Bool { + PublicPaykitService.MethodId(rawValue: methodId)?.onchainNetwork != nil + } + + var isLnurl: Bool { + methodId == PublicPaykitService.MethodId.bitcoinLightningLnurl.rawValue + } +} + +/// Routes every bitcoin contact payment through bitkit-core's Paykit router: Direct pays one of the contact's +/// endpoints, Service pays through a service the wallet holds a balance on (a Spark withdrawal to the contact's on-chain +/// address), None pays nothing. +enum PaykitRouteService { + /// The source the payment is paid from, as picked on the amount screen. + enum Source { + case spending + case savings + } + + /// Spark can carry a leg while it is ready and holds a sendable balance. + @MainActor + static var canRouteThroughSpark: Bool { + SparkManager.shared.isReady && SparkManager.shared.sendableSats > 0 + } + + /// The route for a contact payment, or nil without bitcoin endpoints. A Spark leg is offered only for a payment the + /// user starts (an incoming request's on-chain proof needs the node's send-attempt store) to a contact with an + /// on-chain endpoint, while Spark can route and the payment can't go directly over Lightning. + static func routeUi( + for context: ContactPaymentContext, + canRouteThroughSpark: Bool, + canPayDirectly: Bool + ) -> PaykitRouteUi? { + let endpoints = context.endpoints + .filter { $0.methodId != .usdtArbitrum } + .map { PaykitEndpoint(methodId: $0.methodId.rawValue, value: $0.value) } + guard !endpoints.isEmpty else { return nil } + let offersSparkLeg = canRouteThroughSpark && !canPayDirectly && context.incomingPaymentRequest == nil && + endpoints.contains(where: \.isOnchain) + return PaykitRouteUi(endpoints: endpoints, offersSparkLeg: offersSparkLeg) + } + + /// What the router is asked from `source`: Spending offers every endpoint, Savings only the on-chain ones. + static func request( + route: PaykitRouteUi, + amountSats: UInt64, + source: Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + serviceLegs: [ServiceRouteLeg] + ) -> PaykitRouteRequest { + switch source { + case .spending: + PaykitRouteRequest( + amountSat: amountSats, + contactEndpoints: route.endpoints, + lightningSpendableSat: lightningSpendableSats, + onchainSpendableSat: 0, + serviceLegs: serviceLegs + ) + case .savings: + PaykitRouteRequest( + amountSat: amountSats, + contactEndpoints: route.onchainEndpoints, + lightningSpendableSat: 0, + onchainSpendableSat: onchainSpendableSats, + serviceLegs: [] + ) + } + } + + /// Asks the router how to pay `amountSats` from `source`, quoting a Spark leg to each on-chain endpoint first when + /// the route offers one. + static func route( + _ route: PaykitRouteUi, + amountSats: UInt64, + source: Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64 + ) async throws -> PaykitRoute { + let serviceLegs = source == .spending && route.offersSparkLeg + ? await sparkLegs(to: route.onchainEndpoints, amountSats: amountSats) + : [] + return try paykitRoutePayment( + request: request( + route: route, + amountSats: amountSats, + source: source, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats, + serviceLegs: serviceLegs + ), + network: Env.bitkitCoreNetwork + ) + } + + private static func sparkLegs(to endpoints: [PaykitEndpoint], amountSats: UInt64) async -> [ServiceRouteLeg] { + var legs: [ServiceRouteLeg] = [] + for endpoint in endpoints { + do { + if let leg = try await SparkManager.shared.withdrawalRouteLeg(endpoint: endpoint, amountSats: amountSats) { + legs.append(leg) + } + } catch { + Logger.warn("No Spark route to \(endpoint.methodId): \(error)", context: "PaykitRoute") + } + } + return legs + } + + /// Whether a None route is a short balance rather than a contact Bitkit can't pay. + static func isBalanceShort(amountSats: UInt64, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64) -> Bool { + amountSats > lightningSpendableSats.saturatingAdd(onchainSpendableSats) + } + + /// Runs a service leg the router picked and returns the txid that pays the contact. + static func pay(_ leg: ServiceRouteLeg, contact: String?) async throws -> String { + guard leg.service == SparkManager.routeService else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "Unsupported route service \(leg.service)") + } + return try await SparkManager.shared.withdraw(to: leg.endpoint.value, amountSats: leg.deliveredSat, contact: contact) + } +} diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift deleted file mode 100644 index 2e13d9375b..0000000000 --- a/Bitkit/Services/PubkySwapsRouteService.swift +++ /dev/null @@ -1,128 +0,0 @@ -import BitkitCore -import Foundation - -/// A Paykit payment routed through a Pubky Swaps provider or a service the wallet holds a balance on: the endpoint, -/// the route once quoted (a provider's quote or a service leg), and the provider's name. -struct PaykitSwapRoute: Equatable { - let endpoint: PaykitEndpoint - var quote: PubkySwapRouteQuote? - var providerName: String? - var serviceLeg: ServiceRouteLeg? - - var deliveredSat: UInt64? { - quote?.deliveredSat ?? serviceLeg?.deliveredSat - } - - var totalFeeSat: UInt64? { - quote?.totalFeeSat ?? serviceLeg.map { $0.debitSat - $0.deliveredSat } - } -} - -/// Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the -/// contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays -/// the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. -enum PubkySwapsRouteService { - private static let claimFeeRateSatVb: UInt64 = 2 - private static let pollInterval: Duration = .seconds(2) - private static let claimTimeout: TimeInterval = 10 * 60 - - static var isEnabled: Bool { - Env.isPubkySwapsRouteEnabled - } - - /// A contact whose only endpoints are on-chain, paid when savings cannot cover it but spending can. - static func route(for context: ContactPaymentContext, address: String, onchainBalanceSats: UInt64, - lightningBalanceSats: UInt64) -> PaykitSwapRoute? - { - guard isEnabled, context.incomingPaymentRequest == nil, !address.isEmpty, - !context.endpoints.isEmpty, context.endpoints.allSatisfy({ $0.methodId.onchainNetwork != nil }), - onchainBalanceSats <= UInt64(Env.dustLimit), lightningBalanceSats > 0, - let methodId = context.endpoints.first?.methodId - else { return nil } - return PaykitSwapRoute(endpoint: PaykitEndpoint(methodId: methodId.rawValue, value: address)) - } - - static func quote( - amountSats: UInt64, - endpoint: PaykitEndpoint, - lightningSpendableSats: UInt64, - onchainSpendableSats: UInt64, - contacts: [String] - ) async throws -> PaykitRoute { - // Providers come from the user's own graph: every contact is asked for its swap offer. - let candidates = contacts + Env.pubkySwapsProviders - let serviceLegs = await serviceLegs(endpoint: endpoint, amountSats: amountSats) - Logger.debug("Routing Paykit payment via \(candidates.map(PubkyPublicKeyFormat.redacted))", context: "PubkySwapsRoute") - let (mnemonic, passphrase) = try secrets() - return try await pubkySwapsRoutePaykitPayment( - request: PaykitRouteRequest( - amountSat: amountSats, - contactEndpoints: [endpoint], - lightningSpendableSat: lightningSpendableSats, - onchainSpendableSat: onchainSpendableSats, - providers: candidates, - feeRateSatVb: claimFeeRateSatVb, - serviceLegs: serviceLegs - ), - network: Env.bitkitCoreNetwork, - mnemonic: mnemonic, - bip39Passphrase: passphrase - ) - } - - /// Legs through the services the wallet holds a balance on, which compete with the providers on fee. - private static func serviceLegs(endpoint: PaykitEndpoint, amountSats: UInt64) async -> [ServiceRouteLeg] { - do { - return try await SparkManager.shared.withdrawalRouteLeg(endpoint: endpoint, amountSats: amountSats).map { [$0] } ?? [] - } catch { - Logger.warn("No Spark route to \(endpoint.methodId): \(error)", context: "PubkySwapsRoute") - return [] - } - } - - /// Runs a service leg the router picked and returns the txid that pays the contact. - static func pay(_ leg: ServiceRouteLeg) async throws -> String { - guard leg.service == SparkManager.routeService else { - throw AppError(message: "Unsupported route service", debugMessage: leg.service) - } - return try await SparkManager.shared.withdraw(to: leg.endpoint.value, amountSats: leg.deliveredSat) - } - - static func commit(quoteId: String) async throws -> PubkySwapRoutePayment { - let (mnemonic, passphrase) = try secrets() - return try await pubkySwapsCommitRoute( - quoteId: quoteId, - electrumUrl: Env.electrumServerUrl, - mnemonic: mnemonic, - bip39Passphrase: passphrase - ) - } - - /// Advance the swap until bitkit-core claims the lockup to the contact, returning the claim txid. - static func awaitClaim(swapId: String) async throws -> String { - let deadline = Date().addingTimeInterval(claimTimeout) - while true { - let (mnemonic, passphrase) = try secrets() - let status = try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase) - switch status.state { - case let .claimed(txid): - return txid - case let .failed(reason): - throw AppError(message: reason, debugMessage: nil) - default: - Logger.debug("Pubky Swaps route \(swapId): \(status.state)", context: "PubkySwapsRoute") - } - guard Date() < deadline else { - throw AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(status.state)") - } - try await Task.sleep(for: pollInterval) - } - } - - private static func secrets() throws -> (String, String?) { - guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: 0)) else { - throw AppError(message: "Mnemonic not found", debugMessage: nil) - } - return (mnemonic, try? Keychain.loadString(key: .bip39Passphrase(index: 0))) - } -} diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 1ce0f7c11f..e76d3d8058 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -167,7 +167,7 @@ class AppViewModel: ObservableObject { @Published var contactPaymentContext: ContactPaymentContext? private(set) var didRejectScannedPayment = false @Published var paykitUsesUsdt = false - @Published var paykitSwapRoute: PaykitSwapRoute? + @Published var paykitRoute: PaykitRouteUi? @Published var paykitReviewedAmount: PaykitAmount? @Published var paykitPaymentTerms: PaykitRequestPricing.Payment? @@ -1038,15 +1038,20 @@ extension AppViewModel { // Fallback to on-chain if address is available guard !invoice.address.isEmpty, validateIncomingOnchainPaymentRequestAmount(requestedAmount ?? invoice.amountSatoshis) else { return } - if let context = contactPaymentContext, let route = PubkySwapsRouteService.route( - for: context, - address: invoice.address, - onchainBalanceSats: max(paymentState.spendableOnchainBalanceSats, alternativeOnchainBalanceSats), - lightningBalanceSats: paymentState.totalLightningBalanceSats - ) { + // An on-chain contact payment opens with Spending as a source while Spark can carry it there, whether or + // not Savings covers it; Spending is the default when Savings holds no more than dust. + if let context = contactPaymentContext, scope != .onchainPayments, + let route = PaykitRouteService.routeUi( + for: context, + canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark, + canPayDirectly: false + ), route.offersSparkLeg + { handleScannedOnchainInvoice(invoice) - paykitSwapRoute = route - selectedWalletToPayFrom = .lightning + paykitRoute = route + if max(paymentState.spendableOnchainBalanceSats, alternativeOnchainBalanceSats) <= UInt64(Env.dustLimit) { + selectedWalletToPayFrom = .lightning + } return } @@ -1395,7 +1400,7 @@ extension AppViewModel { sendStateOwnerID = ownerID sendStateGeneration = UUID() paykitUsesUsdt = false - paykitSwapRoute = nil + paykitRoute = nil paykitReviewedAmount = nil paykitPaymentTerms = nil scannedLightningInvoice = nil diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index f5dfeabeb6..6bf5f33cf9 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -1,3 +1,4 @@ +import BitkitCore import SwiftUI enum SendFundingSource: Equatable { @@ -10,7 +11,6 @@ enum SendFundingSource: Equatable { struct SendAmountView: View { @Environment(\.dismiss) private var dismiss @EnvironmentObject var app: AppViewModel - @EnvironmentObject private var contactsManager: ContactsManager @EnvironmentObject var currency: CurrencyViewModel @EnvironmentObject var settings: SettingsViewModel @EnvironmentObject var wallet: WalletViewModel @@ -44,11 +44,9 @@ struct SendAmountView: View { { return [.usdt] } - if app.paykitSwapRoute != nil { - return [.spending] - } var sources: [SendFundingSource] = [] - if app.scannedLightningInvoice != nil || app.lnurlPayData != nil { + // A Spark leg can carry an on-chain contact payment from Spending. + if app.scannedLightningInvoice != nil || app.lnurlPayData != nil || app.paykitRoute?.offersSparkLeg == true { sources.append(.spending) } if app.scannedOnchainInvoice != nil { @@ -393,6 +391,20 @@ struct SendAmountView: View { return } + if !app.paykitUsesUsdt, let context = app.contactPaymentContext, + let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) + { + switch await routePaykitPayment(route, request: context.incomingPaymentRequest) { + case .leg: + navigationPath.append(.confirm) + return + case .refused: + return + case .direct: + break + } + } + // Lightning payment if app.selectedWalletToPayFrom == .lightning { if UInt64(wallet.maxSendLightningSats) < amountSats { @@ -404,12 +416,6 @@ struct SendAmountView: View { return } - if let route = app.paykitSwapRoute { - guard await quoteSwapRoute(route) else { return } - navigationPath.append(.confirm) - return - } - navigationPath.append(app.lnurlPayData != nil && app.scannedLightningInvoice == nil ? .lnurlPayConfirm : .confirm) return } @@ -458,41 +464,91 @@ struct SendAmountView: View { } } - private func quoteSwapRoute(_ route: PaykitSwapRoute) async -> Bool { + private enum PaykitRouteOutcome { + case direct + case leg + case refused + } + + /// Asks bitkit-core's router how to pay the contact from the selected source. Direct pays the endpoint it names, a + /// service leg opens Confirm with its route and fee, and none stays here with the app's copy. + private func routePaykitPayment(_ route: PaykitRouteUi, request: PaykitPaymentRequest?) async -> PaykitRouteOutcome { + let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings + let lightningSpendable = source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0 + let onchainSpendable = source == .savings ? maxSendableAmount ?? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0 + var unrouted = route + unrouted.serviceLeg = nil do { - let paykitRoute = try await PubkySwapsRouteService.quote( + let picked = try await PaykitRouteService.route( + route, amountSats: amountSats, - endpoint: route.endpoint, - lightningSpendableSats: UInt64(wallet.maxSendLightningSats), - onchainSpendableSats: UInt64(wallet.spendableOnchainBalanceSats), - contacts: contactsManager.contacts.map(\.publicKey) + source: source, + lightningSpendableSats: lightningSpendable, + onchainSpendableSats: onchainSpendable ) - switch paykitRoute { - case let .swap(quote): - var quoted = route - quoted.quote = quote - quoted.serviceLeg = nil - quoted.providerName = contactsManager.contacts - .first { PubkyPublicKeyFormat.matches($0.publicKey, quote.providerPubky) }?.displayName - app.paykitSwapRoute = quoted - return true - case let .none(reason): - app.toast(type: .error, title: t("slashtags__error_pay_title"), description: reason) + switch picked { + case let .direct(endpoint): + app.paykitRoute = unrouted + guard await payDirectly(endpoint) else { return .refused } + if let request { + app.paykitPaymentTerms = try request.payment(using: app.paykitPaymentMethod) + } + return .direct case let .service(leg): - var quoted = route - quoted.quote = nil - quoted.serviceLeg = leg - app.paykitSwapRoute = quoted - return true - case .direct: - app.paykitSwapRoute = nil - app.toast(type: .error, title: t("slashtags__error_pay_title"), description: t("common__error_body")) + var routed = route + routed.serviceLeg = leg + app.paykitRoute = routed + return .leg + case let .none(reason): + Logger.warn("Found no Paykit route: '\(reason)'", context: "SendAmountView") + app.paykitRoute = unrouted + showNoRouteToast(isBalanceShort: PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendable, + onchainSpendableSats: onchainSpendable + )) + return .refused } } catch { - Logger.error("Failed to route Paykit payment through Pubky Swaps: \(error)", context: "SendAmountView") - app.toast(type: .error, title: t("slashtags__error_pay_title"), description: error.localizedDescription) + Logger.error("Failed to route Paykit payment: \(error)", context: "SendAmountView") + showNoRouteToast(isBalanceShort: false) + return .refused + } + } + + /// Switches the send to the endpoint the router picked, when the scan opened another one. + private func payDirectly(_ endpoint: PaykitEndpoint) async -> Bool { + if endpoint.isOnchain { + app.selectedWalletToPayFrom = .onchain + if app.scannedOnchainInvoice?.address != endpoint.value { + app.scannedOnchainInvoice = OnChainInvoice(address: endpoint.value, amountSatoshis: 0, label: nil, message: nil, params: nil) + } + return true + } + app.selectedWalletToPayFrom = .lightning + if endpoint.isLnurl { + return app.lnurlPayData != nil || app.scannedLightningInvoice != nil } - return false + if app.scannedLightningInvoice?.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame { + return true + } + guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { + Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "SendAmountView") + showNoRouteToast(isBalanceShort: false) + return false + } + app.scannedLightningInvoice = invoice + app.lnurlPayData = nil + return true + } + + private func showNoRouteToast(isBalanceShort: Bool) { + app.toast( + type: .error, + title: t(isBalanceShort ? "wallet__send_amount_exceeded__title" : "wallet__send_paykit_no_route__title"), + description: t(isBalanceShort ? "wallet__send_amount_exceeded__description" : "wallet__send_paykit_no_route__description"), + accessibilityIdentifier: isBalanceShort ? "PaykitRouteBalanceToast" : "PaykitRouteNoneToast" + ) } private func updateInputCap() { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 96e907980f..d393c31a7f 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -3,8 +3,6 @@ import LDKNode import SwiftUI struct SendConfirmationView: View { - private static let providerKeyLength = 12 - @Environment(PaykitPaymentRequestManager.self) private var paykitPaymentRequestManager @EnvironmentObject var app: AppViewModel @EnvironmentObject var activityList: ActivityListViewModel @@ -347,7 +345,7 @@ struct SendConfirmationView: View { PaykitAmountText(amount: preparingRequest.amount, size: .display) .accessibilityIdentifier("ReviewAmount") } - } else if let deliveredSat = app.paykitSwapRoute?.deliveredSat { + } else if let deliveredSat = app.paykitRoute?.deliveredSat { MoneyStack( sats: Int(wallet.sendAmountSats ?? deliveredSat), showSymbol: true, @@ -375,8 +373,8 @@ struct SendConfirmationView: View { .padding(.bottom, oneOffPaymentRequest == nil ? 44 : 24) if showDetails { - if let route = app.paykitSwapRoute, let totalFeeSat = route.totalFeeSat { - swapRouteView(route, totalFeeSat: totalFeeSat) + if let route = app.paykitRoute, let totalFeeSat = route.totalFeeSat { + paykitRouteView(route, totalFeeSat: totalFeeSat) } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { onchainView(invoice) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { @@ -728,7 +726,7 @@ struct SendConfirmationView: View { } } - func swapRouteView(_ route: PaykitSwapRoute, totalFeeSat: UInt64) -> some View { + func paykitRouteView(_ route: PaykitRouteUi, totalFeeSat: UInt64) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { SendSectionView(t("wallet__send_from")) { @@ -764,7 +762,7 @@ struct SendConfirmationView: View { } SendSectionView(t("wallet__send_swap_route")) { - BodySSBText(routeName(route)) + BodySSBText(Self.routeName(route)) .lineLimit(2) .accessibilityIdentifier("ReviewSwapRoute") } @@ -784,11 +782,8 @@ struct SendConfirmationView: View { } } - private func routeName(_ route: PaykitSwapRoute) -> String { - if let quote = route.quote { - return "Pubky Swaps · \(route.providerName ?? quote.providerPubky.ellipsis(maxLength: Self.providerKeyLength))" - } - return "Spark" + private static func routeName(_ route: PaykitRouteUi) -> String { + route.serviceLeg?.service == SparkManager.routeService ? "Spark" : route.serviceLeg?.service ?? "" } func lightningView(_ invoice: LightningInvoice) -> some View { @@ -1047,10 +1042,8 @@ struct SendConfirmationView: View { if hwSend.isActive { navigationPath.append(.hardwareSign) - } else if let leg = app.paykitSwapRoute?.serviceLeg { + } else if let leg = app.paykitRoute?.serviceLeg { await performServiceRoutedPayment(leg) - } else if let quote = app.paykitSwapRoute?.quote { - await performSwapRoutedPayment(quote) } else { try await performPayment(isAutomatic: isAutomatic) } @@ -1374,7 +1367,7 @@ struct SendConfirmationView: View { isSubmittingPayment = true defer { isSubmittingPayment = false } do { - let txid = try await PubkySwapsRouteService.pay(leg) + let txid = try await PaykitRouteService.pay(leg, contact: app.contactPaymentContext?.publicKey) Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") navigationPath.append(.success(paymentId: txid)) } catch { @@ -1388,28 +1381,6 @@ struct SendConfirmationView: View { } } - private func performSwapRoutedPayment(_ quote: PubkySwapRouteQuote) async { - isSubmittingPayment = true - defer { isSubmittingPayment = false } - do { - let payment = try await PubkySwapsRouteService.commit(quoteId: quote.quoteId) - Logger.info("Committed Pubky Swaps route \(payment.swapId) to \(payment.destinationAddress)", context: "SendConfirmation") - // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. - let paymentHash = try await LightningService.shared.send(bolt11: payment.invoice) - let claimTxid = try await PubkySwapsRouteService.awaitClaim(swapId: payment.swapId) - Logger.info("Claimed Pubky Swaps route \(payment.swapId) in \(claimTxid)", context: "SendConfirmation") - navigationPath.append(.success(paymentId: String(paymentHash))) - } catch { - Logger.error("Pubky Swaps route payment failed: \(error)", context: "SendConfirmation") - navigationPath.append(.failure(SendFailureContext( - error: error, - retryRoute: .confirm, - routingCacheResetAttempted: routingCacheResetAttempted, - paymentRequest: nil - ))) - } - } - private func performPayment(isAutomatic: Bool) async throws { let paymentActivity = PaykitPaymentActivity.shared.begin() defer { PaykitPaymentActivity.shared.end(paymentActivity) } diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index a4443c4866..7eacef40fe 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -872,8 +872,8 @@ struct SendSheet: View { } } - // Validate onchain payment balance (for pure onchain invoices); a swap route pays it from spending - if app.paykitSwapRoute == nil, let onchainInvoice = app.scannedOnchainInvoice { + // Validate onchain payment balance (for pure onchain invoices); a Spark route can pay it from spending + if app.paykitRoute?.offersSparkLeg != true, let onchainInvoice = app.scannedOnchainInvoice { let onchainBalance = max( LightningService.shared.balances?.spendableOnchainBalanceSats ?? 0, hwWalletManager.maximumFundingBalanceSats diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift new file mode 100644 index 0000000000..dc7c450c1e --- /dev/null +++ b/BitkitTests/PaykitRouteTests.swift @@ -0,0 +1,170 @@ +@testable import Bitkit +import BitkitCore +import BreezSdkSpark +import XCTest + +final class PaykitRouteTests: XCTestCase { + private let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + private let lightning = PaykitEndpoint( + methodId: "btc-lightning-lnurl", + value: "lnurl1dp68gurn8ghj7um9wfmxjcm99e3k7mf0v9cxj0m385ekvcenxc6r2c35xvukxefcv5mkvv34x5ekzd3ev56nyd3hxqurzepexejxxepnxscrvwfnv9nxzcn9xq6xyefhvgcxxcmyxymnserxfq5fns" + ) + + private func sparkLeg(amountSats: UInt64, feeSats: UInt64) -> ServiceRouteLeg { + ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: amountSats, + debitSat: amountSats + feeSats, + atomicity: "trusted", + validUntilUnix: UInt64(Date().timeIntervalSince1970) + 600 + ) + } + + // MARK: - Request + + func testSpendingOffersEveryEndpointAndSavingsOnlyTheOnchainOnes() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + let leg = sparkLeg(amountSats: 20000, feeSats: 300) + + let spending = PaykitRouteService.request( + route: route, amountSats: 20000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 90000, + serviceLegs: [leg] + ) + let savings = PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 50000, onchainSpendableSats: 90000, + serviceLegs: [leg] + ) + + XCTAssertEqual(spending.contactEndpoints, [lightning, onchain]) + XCTAssertEqual(spending.lightningSpendableSat, 50000) + XCTAssertEqual(spending.onchainSpendableSat, 0) + XCTAssertEqual(spending.serviceLegs, [leg]) + XCTAssertEqual(savings.contactEndpoints, [onchain]) + XCTAssertEqual(savings.lightningSpendableSat, 0) + XCTAssertEqual(savings.onchainSpendableSat, 90000) + XCTAssertTrue(savings.serviceLegs.isEmpty) + } + + // MARK: - Router outcomes + + func testRouterPaysTheLnurlEndpointItPicksFromSpending() throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20, source: .spending, lightningSpendableSats: 5000, onchainSpendableSats: 0, + serviceLegs: [] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .direct(endpoint: lightning)) + } + + func testRouterPaysTheOnchainEndpointItPicksFromSavings() throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 0, onchainSpendableSats: 90000, + serviceLegs: [] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .direct(endpoint: onchain)) + } + + func testRouterTakesTheSparkLegToAnOnchainOnlyContactFromSpending() throws { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + let leg = sparkLeg(amountSats: 20000, feeSats: 300) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0, + serviceLegs: [leg] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .service(leg: leg)) + var routed = route + routed.serviceLeg = leg + XCTAssertEqual(routed.totalFeeSat, 300) + XCTAssertEqual(routed.deliveredSat, 20000) + } + + func testRouterFindsNoneWithoutABalanceThatReachesTheContact() throws { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 0, onchainSpendableSats: 5000, + serviceLegs: [] + ), + network: .regtest + ) + + guard case .none = picked else { return XCTFail("Expected no route, got \(picked)") } + XCTAssertTrue(PaykitRouteService.isBalanceShort(amountSats: 20000, lightningSpendableSats: 0, onchainSpendableSats: 5000)) + XCTAssertFalse(PaykitRouteService.isBalanceShort(amountSats: 20000, lightningSpendableSats: 0, onchainSpendableSats: 90000)) + } + + // MARK: - Spark leg offer + + func testSparkLegIsOfferedOnlyForAnOnchainContactPaymentTheUserStarts() { + let onchainOnly = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + + XCTAssertEqual( + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true, canPayDirectly: false)?.offersSparkLeg, + true + ) + XCTAssertEqual( + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: false, canPayDirectly: false)?.offersSparkLeg, + false + ) + XCTAssertEqual( + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true, canPayDirectly: true)?.offersSparkLeg, + false + ) + let usdtOnly = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: [ + Self.endpoint(.usdtArbitrum, "0x0000000000000000000000000000000000000001"), + ]) + XCTAssertNil(PaykitRouteService.routeUi(for: usdtOnly, canRouteThroughSpark: true, canPayDirectly: false)) + } + + // MARK: - Contact withdrawal journal + + func testJournaledWithdrawalSettlesFromTheMatchingSparkPayment() { + let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + let other = Self.withdrawal(id: "other", to: "bcrt1qother", amountSats: 20000, timestamp: 1001) + let earlier = Self.withdrawal(id: "earlier", to: onchain.value, amountSats: 20000, timestamp: 100) + let sent = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + + XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [other, earlier, sent])?.id, "sent") + XCTAssertNil(SparkManager.matchingWithdrawal(pending, in: [other, earlier])) + } + + private static func endpoint(_ methodId: PublicPaykitService.MethodId, _ value: String) -> PublicPaykitService.Endpoint { + PublicPaykitService.Endpoint(methodId: methodId, value: value, min: nil, max: nil, rawPayload: value) + } + + private static func withdrawal(id: String, to address: String, amountSats: UInt64, timestamp: UInt64) -> Payment { + Payment( + id: id, + paymentType: .send, + status: .completed, + amount: U128(amountSats), + fees: 300, + timestamp: timestamp, + method: .withdraw, + details: .withdraw(txId: "tx-\(id)", vout: 0, destinationAddress: address), + conversionDetails: nil + ) + } +} diff --git a/changelog.d/next/1170.added.md b/changelog.d/next/1170.added.md deleted file mode 100644 index d7dfa80257..0000000000 --- a/changelog.d/next/1170.added.md +++ /dev/null @@ -1 +0,0 @@ -Bitkit can pay a contact who only accepts on-chain bitcoin from your spending balance, through a Pubky Swaps provider among your contacts. diff --git a/changelog.d/next/1191.added.md b/changelog.d/next/1191.added.md index 9dd64f6e8c..c908dc605f 100644 --- a/changelog.d/next/1191.added.md +++ b/changelog.d/next/1191.added.md @@ -1 +1 @@ -Paykit contacts who only accept on-chain bitcoin can be paid from Spark when that costs less than a swap. +Paykit contacts who only accept on-chain bitcoin can be paid from Spark. diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml index 9a0cd6d979..2ed0eaa9a7 100644 --- a/journeys/paykit-spark-route.xml +++ b/journeys/paykit-spark-route.xml @@ -5,8 +5,7 @@ and that the contact receives the exact amount on chain. Preconditions: a Debug build with SWIFT_ACTIVE_COMPILATION_CONDITIONS including E2E_BUILD, E2E_BACKEND=local, - E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver, launched with the - -PUBKY_SWAPS_ROUTES=true argument; bitkit-docker's default stack with the marketplace and payment-requests + E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver; bitkit-docker's default stack with the marketplace and payment-requests profiles. The simulator reaches the host's loopback directly, so it needs no port forwarding. The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml deleted file mode 100644 index 3499e94901..0000000000 --- a/journeys/paykit-swap-route.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet that holds only a spending - balance, routes through a Pubky Swaps provider found among the user's own contacts, without the user picking a - swap, and that the contact receives the exact amount on chain. - - Preconditions: a Debug build with SWIFT_ACTIVE_COMPILATION_CONDITIONS including E2E_BUILD, E2E_BACKEND=local, - E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver, launched with the - -PUBKY_SWAPS_ROUTES=true argument; bitkit-docker's default stack with the marketplace, payment-requests and - lnurl-pay profiles; the provider running against bitkit-docker's LND and funded. The simulator reaches the host's - loopback directly, so it needs no port forwarding. - The wallet has a spending balance from an LNURL channel with bitkit-docker's LND and an empty savings balance, - a Pubky profile on the local homeserver, and both the provider's and the fixture-issuer's pubkys saved as contacts. - The contact is bitkit-docker's fixture-issuer, which publishes only a btc-regtest-p2wpkh endpoint. - - - Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 - Tap Send (tag "Send"), then Contact (tag "RecipientContact") - Verify the contact list shows both the fixture-issuer and the provider, and tap the fixture-issuer (tag "SendContact-" followed by its pubky) - Verify the amount screen (tag "SendAmount") offers SPENDING as the source - Enter 20000 and tap Continue (tag "ContinueAmount") - Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") - Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Pubky Swaps" followed by the provider's shortened pubky - Swipe to pay (tag "GRAB") - Once the provider logs "HTLC funded; awaiting client claim", mine one block on bitkit-docker's bitcoind - Verify the Bitcoin Sent screen (tag "SendSuccess") is visible - Verify the provider logs "client claimed; hold invoice settled", and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the fixture-issuer's address - - From 525004a4803d1694295e21ba3f70375ea45a3913 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:01:24 +0100 Subject: [PATCH 10/64] chore: translate the paykit no-route copy --- Bitkit/Resources/Localization/ar.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/ca.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/cs.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/de.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/el.lproj/Localizable.strings | 4 ++-- .../Resources/Localization/es-419.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/es.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/fr.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/it.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/nl.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/pl.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/pt.lproj/Localizable.strings | 4 ++-- Bitkit/Resources/Localization/ru.lproj/Localizable.strings | 4 ++-- 14 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 7963f87a57..881cb4ba2a 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1070,8 +1070,8 @@ "wallet__send_sync_long_description" = "يبدو أنك غير متصل. يرجى التحقق من اتصالك. سيحاول Bitkit إعادة الاتصال كل بضع ثوانٍ."; "wallet__send_to" = "إلى"; "wallet__send_swap_route" = "المسار"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "تعذّر الدفع لجهة الاتصال هذه"; +"wallet__send_paykit_no_route__description" = "ليس لدى جهة الاتصال هذه طريقة دفع يمكن لـ Bitkit استخدامها حاليًا."; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index c4a74f8915..2c597c3c31 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1189,8 +1189,8 @@ "wallet__send_sync_long_description" = "Sembla que estàs desconnectat. Comprova la connexió. Bitkit intentarà tornar a connectar-se cada pocs segons."; "wallet__send_to" = "A"; "wallet__send_swap_route" = "Ruta"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "No es pot pagar aquest contacte"; +"wallet__send_paykit_no_route__description" = "Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara mateix."; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 22d3b357c8..a32e18008e 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1296,8 +1296,8 @@ "wallet__send_sync_long_description" = "Zdá se, že jste odpojeni. Zkontrolujte prosím připojení. Bitkit se bude každých několik sekund pokoušet znovu připojit."; "wallet__send_to" = "Komu"; "wallet__send_swap_route" = "Trasa"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Tomuto kontaktu nelze zaplatit"; +"wallet__send_paykit_no_route__description" = "Tento kontakt teď nemá žádný platební způsob, který by Bitkit mohl použít."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 924505d383..1635854a11 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1294,8 +1294,8 @@ "wallet__send_sync_long_description" = "Anscheinend bist du nicht verbunden. Bitte überprüfe deine Verbindung. Bitkit versucht alle paar Sekunden, sich erneut zu verbinden."; "wallet__send_to" = "An"; "wallet__send_swap_route" = "Route"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Zahlung an diesen Kontakt nicht möglich"; +"wallet__send_paykit_no_route__description" = "Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index dbb52478ec..d999671367 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1088,8 +1088,8 @@ "wallet__send_sync_long_description" = "Φαίνεται ότι είστε αποσυνδεδεμένοι. Ελέγξτε τη σύνδεσή σας. Το Bitkit θα προσπαθεί να επανασυνδεθεί κάθε λίγα δευτερόλεπτα."; "wallet__send_to" = "Προς"; "wallet__send_swap_route" = "Διαδρομή"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Δεν είναι δυνατή η πληρωμή αυτής της επαφής"; +"wallet__send_paykit_no_route__description" = "Αυτή η επαφή δεν έχει αυτή τη στιγμή κάποια μέθοδο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit."; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 19f2a53dfc..6be5c777ff 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1299,8 +1299,8 @@ "wallet__send_sync_long_description" = "Parece que está desconectado. Revise su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Ruta"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar en este momento."; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 8de63a51d7..c8fc4f9ad7 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1207,8 +1207,8 @@ "wallet__send_sync_long_description" = "Parece que está desconectado. Compruebe su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Ruta"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora mismo."; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 293fad89a2..8a9c01ea0b 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1307,8 +1307,8 @@ "wallet__send_sync_long_description" = "Il semble que vous soyez déconnecté. Veuillez vérifier votre connexion. Bitkit tentera de se reconnecter toutes les quelques secondes."; "wallet__send_to" = "Pour"; "wallet__send_swap_route" = "Itinéraire"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Impossible de payer ce contact"; +"wallet__send_paykit_no_route__description" = "Ce contact n’a actuellement aucun moyen de paiement que Bitkit peut utiliser."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 707f161c02..caea01e213 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1272,8 +1272,8 @@ "wallet__send_sync_long_description" = "Sembra che tu sia disconnesso. Controlla la connessione. Bitkit proverà a riconnettersi ogni pochi secondi."; "wallet__send_to" = "A"; "wallet__send_swap_route" = "Percorso"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Impossibile pagare questo contatto"; +"wallet__send_paykit_no_route__description" = "Al momento questo contatto non ha un metodo di pagamento che Bitkit possa usare."; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 3e74cc3a6f..27ba87e02b 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1302,8 +1302,8 @@ "wallet__send_sync_long_description" = "Het lijkt erop dat u niet verbonden bent. Controleer uw verbinding. Bitkit probeert om de paar seconden opnieuw verbinding te maken."; "wallet__send_to" = "Naar"; "wallet__send_swap_route" = "Route"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Kan dit contact niet betalen"; +"wallet__send_paykit_no_route__description" = "Dit contact heeft op dit moment geen betaalmethode die Bitkit kan gebruiken."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 1cd27fb4bb..5bd824ee05 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1306,8 +1306,8 @@ "wallet__send_sync_long_description" = "Wygląda na to, że nie masz połączenia. Sprawdź połączenie. Bitkit będzie próbował połączyć się ponownie co kilka sekund."; "wallet__send_to" = "Do"; "wallet__send_swap_route" = "Trasa"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Nie można zapłacić temu kontaktowi"; +"wallet__send_paykit_no_route__description" = "Ten kontakt nie ma obecnie żadnej metody płatności, której Bitkit może użyć."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 6f91384934..37917d35b1 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1307,8 +1307,8 @@ "wallet__send_sync_long_description" = "Parece que você está desconectado. Verifique sua conexão. A Bitkit tentará se reconectar a cada poucos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Rota"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Não é possível pagar este contato"; +"wallet__send_paykit_no_route__description" = "Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index e01173050a..0e4484eb94 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1061,8 +1061,8 @@ "wallet__send_sync_long_description" = "Parece que está desligado. Verifique a sua ligação. A Bitkit vai tentar voltar a ligar a cada poucos segundos."; "wallet__send_to" = "Para"; "wallet__send_swap_route" = "Rota"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Não é possível pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto não tem neste momento nenhum método de pagamento que a Bitkit possa usar."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index e64980d161..b4d6b8d7e6 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1291,8 +1291,8 @@ "wallet__send_sync_long_description" = "Похоже, вы отключены. Проверьте подключение. Bitkit будет пытаться переподключиться каждые несколько секунд."; "wallet__send_to" = "Кому"; "wallet__send_swap_route" = "Маршрут"; -"wallet__send_paykit_no_route__title" = "Can't pay this contact"; -"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_no_route__title" = "Не удаётся оплатить этому контакту"; +"wallet__send_paykit_no_route__description" = "У этого контакта сейчас нет способа оплаты, который может использовать Bitkit."; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; From 771b250ffee996dd672447a9464d6d9f457c7136 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:10:19 +0100 Subject: [PATCH 11/64] feat: pay paykit requests through the router and spark - A payment request's Confirm, which opens with fixed terms and no amount screen, asks the router too: Direct switches the send to the endpoint it picks. - An on-chain request can be paid from Spending through a Spark withdrawal. Its on-chain proof is started before Spark sends and completed with the withdrawal's txid, the request's payment check runs right before the send, and the withdrawal journal completes or drops the proof when the app stopped mid-send. --- Bitkit/Managers/SparkManager.swift | 38 +++++- .../Services/PaykitPaymentProofService.swift | 36 +++++ Bitkit/Services/PaykitRouteService.swift | 124 +++++++++++++++++- .../Views/Wallets/Send/SendAmountView.swift | 89 +------------ .../Wallets/Send/SendConfirmationView.swift | 70 +++++++++- .../PaykitPaymentProofServiceTests.swift | 45 +++++++ BitkitTests/PaykitRouteTests.swift | 2 +- 7 files changed, 310 insertions(+), 94 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index a12951822a..20a0f63f8d 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -463,16 +463,26 @@ final class SparkManager: ChannelFreeLightningRail { /// Withdraws exactly `amountSats` to a contact's on-chain `address` at medium speed and returns its txid. The /// withdrawal is written to a journal before it is sent, so one interrupted mid-send settles from Spark's payment /// list; a second one is refused while it is open. It is recorded as a sent on-chain activity for the contact. - func withdraw(to address: String, amountSats: UInt64, contact: String?) async throws -> String { + /// A withdrawal that pays a Paykit request (`request`) completes the request's on-chain proof with its txid, also when + /// it settles from the journal. `beforeSend` runs right before Spark sends, after the quote. + func withdraw( + to address: String, + amountSats: UInt64, + contact: String?, + request: SparkContactWithdrawal.PaykitRequest? = nil, + beforeSend: () async throws -> Void = {} + ) async throws -> String { guard Self.pendingContactWithdrawal == nil else { throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") } let prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) + try await beforeSend() let pending = SparkContactWithdrawal( address: address, amountSats: amountSats, contact: contact, - startedAt: UInt64(Date().timeIntervalSince1970) + startedAt: UInt64(Date().timeIntervalSince1970), + request: request ) Self.pendingContactWithdrawal = pending isWithdrawingToContact = true @@ -512,6 +522,9 @@ final class SparkManager: ChannelFreeLightningRail { } else if allowClear { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") Self.pendingContactWithdrawal = nil + if let request = pending.request { + await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) + } } } @@ -527,7 +540,19 @@ final class SparkManager: ChannelFreeLightningRail { private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { Self.pendingContactWithdrawal = nil - guard payment.status != .failed else { return } + guard payment.status != .failed else { + if let request = pending.request { + await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) + } + return + } + if let request = pending.request { + _ = await PaykitPaymentProofService.shared.completeSparkOnchainPayment( + requestId: request.id, + identity: request.identity, + txid: txId + ) + } Self.contactWithdrawalTxIds.insert(txId) _ = await CoreService.shared.activity.createSentOnchainActivityFromSendResult( txid: txId, @@ -1035,10 +1060,17 @@ enum SparkErrorCopy { /// A Spark withdrawal to a contact's on-chain address, journaled before it is sent. struct SparkContactWithdrawal: Codable, Equatable { + /// The Paykit request a withdrawal pays, and the identity its proof belongs to. + struct PaykitRequest: Codable, Equatable { + let id: PaykitPaymentRequest.ID + let identity: String + } + let address: String let amountSats: UInt64 let contact: String? let startedAt: UInt64 + var request: PaykitRequest? } struct SparkWithdrawal: Identifiable, Equatable { diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 3101e72658..0e7c922118 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1329,6 +1329,42 @@ actor PaykitPaymentProofService { return true } + /// Completes the on-chain proof of a request Spark paid by withdrawing to the payee's address. Spark's withdrawal + /// isn't one of the node's send attempts, so its txid is the proof as soon as Spark returns it. + func completeSparkOnchainPayment(requestId: PaykitPaymentRequest.ID, identity: String, txid: String) async -> Bool { + guard Self.isHex(txid, byteCount: 32) else { return false } + do { + let completed: PendingPaykitPaymentProof? = try await mutationLock.withLock { + var proofs = try await loadProofs() + guard let index = proofs.lastIndex(where: { + PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && + $0.paymentStarted && $0.onchainWalletId == nil && + ($0.paymentIdentifier == nil || $0.paymentIdentifier?.caseInsensitiveCompare(txid) == .orderedSame) + }) else { return nil } + proofs[index].paymentIdentifier = txid.lowercased() + proofs[index].proofData = txid.lowercased() + proofs[index].onchainAcceptanceVerified = true + proofs[index].onchainLocalFollowupComplete = true + try await persist(proofs) + return proofs[index] + } + guard let completed else { return false } + submitInBackground(completed, priority: .interactive) + return true + } catch { + logWarning("Failed to retain a Spark on-chain proof for retry: \(error)") + return false + } + } + + /// Drops the started on-chain proof of a request whose Spark withdrawal never went out. + func failSparkOnchainPayment(requestId: PaykitPaymentRequest.ID, identity: String) async { + await removeProofs { + PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && + $0.paymentStarted && $0.onchainWalletId == nil && $0.paymentIdentifier == nil && $0.proofData == nil + } + } + @discardableResult func failOnchainPayment(_ request: PaykitPaymentRequest, paymentIdentity: String? = nil) async -> Bool { let liveIdentity = paymentIdentity == nil ? try? await currentIdentity() : nil diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 56f5b5b3b4..7f32e7bb1f 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -47,9 +47,9 @@ enum PaykitRouteService { SparkManager.shared.isReady && SparkManager.shared.sendableSats > 0 } - /// The route for a contact payment, or nil without bitcoin endpoints. A Spark leg is offered only for a payment the - /// user starts (an incoming request's on-chain proof needs the node's send-attempt store) to a contact with an - /// on-chain endpoint, while Spark can route and the payment can't go directly over Lightning. + /// The route for a contact payment, or nil without bitcoin endpoints. A Spark leg is offered to a contact with an + /// on-chain endpoint while Spark can route and the payment can't go directly over Lightning; a request it pays gets + /// its on-chain proof from the withdrawal's txid. static func routeUi( for context: ContactPaymentContext, canRouteThroughSpark: Bool, @@ -59,8 +59,7 @@ enum PaykitRouteService { .filter { $0.methodId != .usdtArbitrum } .map { PaykitEndpoint(methodId: $0.methodId.rawValue, value: $0.value) } guard !endpoints.isEmpty else { return nil } - let offersSparkLeg = canRouteThroughSpark && !canPayDirectly && context.incomingPaymentRequest == nil && - endpoints.contains(where: \.isOnchain) + let offersSparkLeg = canRouteThroughSpark && !canPayDirectly && endpoints.contains(where: \.isOnchain) return PaykitRouteUi(endpoints: endpoints, offersSparkLeg: offersSparkLeg) } @@ -138,10 +137,121 @@ enum PaykitRouteService { } /// Runs a service leg the router picked and returns the txid that pays the contact. - static func pay(_ leg: ServiceRouteLeg, contact: String?) async throws -> String { + static func pay( + _ leg: ServiceRouteLeg, + contact: String?, + request: SparkContactWithdrawal.PaykitRequest? = nil, + beforeSend: () async throws -> Void = {} + ) async throws -> String { guard leg.service == SparkManager.routeService else { throw AppError(message: "wallet__payment_failed_description", debugMessage: "Unsupported route service \(leg.service)") } - return try await SparkManager.shared.withdraw(to: leg.endpoint.value, amountSats: leg.deliveredSat, contact: contact) + return try await SparkManager.shared.withdraw( + to: leg.endpoint.value, + amountSats: leg.deliveredSat, + contact: contact, + request: request, + beforeSend: beforeSend + ) + } +} + +/// What asking the router did to a contact payment. +enum PaykitRouteOutcome: Equatable { + /// The send pays the endpoint the router picked. + case direct + /// The send pays through the service leg in `AppViewModel.paykitRoute`. + case leg + /// No route pays the contact; the app's copy says why. + case refused +} + +@MainActor +extension AppViewModel { + /// Asks bitkit-core's router how to pay the contact from `source`. Direct switches the send to the endpoint it + /// names, a service leg is kept in `paykitRoute` for Confirm, and none shows the app's copy, its reason going to the + /// log only. + func routeContactPayment( + _ route: PaykitRouteUi, + amountSats: UInt64, + source: PaykitRouteService.Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + request: PaykitPaymentRequest? + ) async -> PaykitRouteOutcome { + var unrouted = route + unrouted.serviceLeg = nil + do { + let picked = try await PaykitRouteService.route( + route, + amountSats: amountSats, + source: source, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + ) + switch picked { + case let .direct(endpoint): + paykitRoute = unrouted + guard await payDirectly(endpoint) else { return .refused } + if let request { + paykitPaymentTerms = try request.payment(using: paykitPaymentMethod) + } + return .direct + case let .service(leg): + var routed = route + routed.serviceLeg = leg + paykitRoute = routed + selectedWalletToPayFrom = .lightning + return .leg + case let .none(reason): + Logger.warn("Found no Paykit route: '\(reason)'", context: "PaykitRoute") + paykitRoute = unrouted + showNoPaykitRouteToast(isBalanceShort: PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + )) + return .refused + } + } catch { + Logger.error("Failed to route Paykit payment: \(error)", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return .refused + } + } + + /// Switches the send to the endpoint the router picked, when the scan opened another one. + private func payDirectly(_ endpoint: PaykitEndpoint) async -> Bool { + if endpoint.isOnchain { + selectedWalletToPayFrom = .onchain + if scannedOnchainInvoice?.address != endpoint.value { + scannedOnchainInvoice = OnChainInvoice(address: endpoint.value, amountSatoshis: 0, label: nil, message: nil, params: nil) + } + return true + } + selectedWalletToPayFrom = .lightning + if endpoint.isLnurl { + return lnurlPayData != nil || scannedLightningInvoice != nil + } + if scannedLightningInvoice?.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame { + return true + } + guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { + Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + scannedLightningInvoice = invoice + lnurlPayData = nil + return true + } + + func showNoPaykitRouteToast(isBalanceShort: Bool) { + toast( + type: .error, + title: t(isBalanceShort ? "wallet__send_amount_exceeded__title" : "wallet__send_paykit_no_route__title"), + description: t(isBalanceShort ? "wallet__send_amount_exceeded__description" : "wallet__send_paykit_no_route__description"), + accessibilityIdentifier: isBalanceShort ? "PaykitRouteBalanceToast" : "PaykitRouteNoneToast" + ) } } diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index 6bf5f33cf9..9577b8d39c 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -464,90 +464,15 @@ struct SendAmountView: View { } } - private enum PaykitRouteOutcome { - case direct - case leg - case refused - } - - /// Asks bitkit-core's router how to pay the contact from the selected source. Direct pays the endpoint it names, a - /// service leg opens Confirm with its route and fee, and none stays here with the app's copy. private func routePaykitPayment(_ route: PaykitRouteUi, request: PaykitPaymentRequest?) async -> PaykitRouteOutcome { let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings - let lightningSpendable = source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0 - let onchainSpendable = source == .savings ? maxSendableAmount ?? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0 - var unrouted = route - unrouted.serviceLeg = nil - do { - let picked = try await PaykitRouteService.route( - route, - amountSats: amountSats, - source: source, - lightningSpendableSats: lightningSpendable, - onchainSpendableSats: onchainSpendable - ) - switch picked { - case let .direct(endpoint): - app.paykitRoute = unrouted - guard await payDirectly(endpoint) else { return .refused } - if let request { - app.paykitPaymentTerms = try request.payment(using: app.paykitPaymentMethod) - } - return .direct - case let .service(leg): - var routed = route - routed.serviceLeg = leg - app.paykitRoute = routed - return .leg - case let .none(reason): - Logger.warn("Found no Paykit route: '\(reason)'", context: "SendAmountView") - app.paykitRoute = unrouted - showNoRouteToast(isBalanceShort: PaykitRouteService.isBalanceShort( - amountSats: amountSats, - lightningSpendableSats: lightningSpendable, - onchainSpendableSats: onchainSpendable - )) - return .refused - } - } catch { - Logger.error("Failed to route Paykit payment: \(error)", context: "SendAmountView") - showNoRouteToast(isBalanceShort: false) - return .refused - } - } - - /// Switches the send to the endpoint the router picked, when the scan opened another one. - private func payDirectly(_ endpoint: PaykitEndpoint) async -> Bool { - if endpoint.isOnchain { - app.selectedWalletToPayFrom = .onchain - if app.scannedOnchainInvoice?.address != endpoint.value { - app.scannedOnchainInvoice = OnChainInvoice(address: endpoint.value, amountSatoshis: 0, label: nil, message: nil, params: nil) - } - return true - } - app.selectedWalletToPayFrom = .lightning - if endpoint.isLnurl { - return app.lnurlPayData != nil || app.scannedLightningInvoice != nil - } - if app.scannedLightningInvoice?.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame { - return true - } - guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { - Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "SendAmountView") - showNoRouteToast(isBalanceShort: false) - return false - } - app.scannedLightningInvoice = invoice - app.lnurlPayData = nil - return true - } - - private func showNoRouteToast(isBalanceShort: Bool) { - app.toast( - type: .error, - title: t(isBalanceShort ? "wallet__send_amount_exceeded__title" : "wallet__send_paykit_no_route__title"), - description: t(isBalanceShort ? "wallet__send_amount_exceeded__description" : "wallet__send_paykit_no_route__description"), - accessibilityIdentifier: isBalanceShort ? "PaykitRouteBalanceToast" : "PaykitRouteNoneToast" + return await app.routeContactPayment( + route, + amountSats: amountSats, + source: source, + lightningSpendableSats: source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0, + onchainSpendableSats: source == .savings ? maxSendableAmount ?? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, + request: request ) } diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index d393c31a7f..6773bfc251 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -28,6 +28,7 @@ struct SendConfirmationView: View { var isSetupPending = false @State private var showDetails = false + @State private var routedIncomingRequestId: PaykitPaymentRequest.ID? @State private var hasShownAmountReview = false @State private var showingBiometricError = false @State private var biometricErrorMessage = "" @@ -464,6 +465,7 @@ struct SendConfirmationView: View { } guard preparingRequest == nil, !isRequestSetupPending, !returnToAmountReviewIfNeeded() else { return } ensureSendAmountFromScannedInvoicesIfNeeded() + await routeIncomingRequestIfNeeded() if app.contactPaymentContext?.isInitialSubscriptionPayment == true, !shouldAutomaticallyPay { showManualConfirmation(reason: "not automatic when opened") } @@ -1363,11 +1365,77 @@ struct SendConfirmationView: View { return note } + /// A request's Confirm opens with fixed terms and no amount screen, so the router is asked here: Direct switches the + /// send to the endpoint it picks, and a Spark leg pays an on-chain request from Spending. + private func routeIncomingRequestIfNeeded() async { + guard let context = app.contactPaymentContext, let request = context.incomingPaymentRequest, + !app.paykitUsesUsdt, !hwSend.isActive, routedIncomingRequestId != request.id, + let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) + else { return } + let amount = app.paykitPaymentTerms?.amount ?? request.amount + guard amount.asset == .btc, amount.atomic > 0 else { return } + routedIncomingRequestId = request.id + let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings + _ = await app.routeContactPayment( + route, + amountSats: amount.atomic, + source: source, + lightningSpendableSats: source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0, + onchainSpendableSats: source == .savings ? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, + request: request + ) + } + + /// Withdraws from Spark to the contact's on-chain address. A request it pays gets an on-chain proof with the + /// withdrawal's txid; the proof is started before the send, and Spark's journal settles it if the app stops mid-send. private func performServiceRoutedPayment(_ leg: ServiceRouteLeg) async { + let paymentActivity = PaykitPaymentActivity.shared.begin() + defer { PaykitPaymentActivity.shared.end(paymentActivity) } isSubmittingPayment = true defer { isSubmittingPayment = false } + let context = app.contactPaymentContext + let request = context?.incomingPaymentRequest + var proofRequest: SparkContactWithdrawal.PaykitRequest? do { - let txid = try await PaykitRouteService.pay(leg, contact: app.contactPaymentContext?.publicKey) + if let request { + guard let privateContext = context?.privatePaymentContext else { throw PaykitPaymentRequestError.requestUnavailable } + try await PaykitPaymentProofService.shared.prepare( + request: request, + paymentAppId: privateContext.paymentAppId(for: leg.endpoint.methodId), + paymentEndpointIdentifier: leg.endpoint.methodId, + kind: .onchain, + paymentTerms: app.paykitPaymentTerms + ) + let identity = try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) + do { + try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( + request, + address: leg.endpoint.value, + paymentIdentity: identity + ) + } catch { + await PaykitPaymentProofService.shared.cancelPreparation(request) + throw error + } + proofRequest = SparkContactWithdrawal.PaykitRequest(id: request.id, identity: identity) + } + let txid: String + do { + txid = try await PaykitRouteService.pay(leg, contact: context?.publicKey, request: proofRequest) { + if let request { + try await paykitPaymentRequestManager.ensurePaymentAllowed(request) + } + } + } catch { + // Refused before Spark's send: nothing left, so the started proof goes. After it, the journal settles it. + let refusedBeforeSend = SparkManager.pendingContactWithdrawal == nil + if let proofRequest, refusedBeforeSend { + await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: proofRequest.id, identity: proofRequest.identity) + } + await context?.resolvePrivatePaymentListConsumption(refusedBeforeSend ? .definitePreBroadcastFailure : .uncertain) + throw error + } + await context?.resolvePrivatePaymentListConsumption(.succeeded) Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") navigationPath.append(.success(paymentId: txid)) } catch { diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index c9db89075d..0a8b934f98 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1879,6 +1879,51 @@ final class PaykitPaymentProofServiceTests: XCTestCase { XCTAssertTrue(remainingProofs.isEmpty) } + func testSparkWithdrawalSubmitsItsTransactionIdAsTheOnchainProof() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let proofRemoved = expectation(description: "On-chain proof removed after submission") + let store = PaymentProofMemoryStore { proofs in + if proofs.isEmpty { + proofRemoved.fulfill() + } + } + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let service = paymentProofService(sdk: sdk, store: store) + let txid = String(repeating: "cd", count: 32) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress) + let completed = await service.completeSparkOnchainPayment(requestId: request.id, identity: identity, txid: txid) + await sdk.waitForSubmissionStart() + await fulfillment(of: [proofRemoved], timeout: 1) + + XCTAssertTrue(completed, "Spark's withdrawal is no node send attempt, yet its txid completes the proof") + let lastSubmission = await sdk.lastSubmission() + let submission = try XCTUnwrap(lastSubmission) + XCTAssertEqual(submission.paymentEndpointIdentifier, endpoint) + XCTAssertEqual( + try proofValues(submission.proof.exportText()), + ["data": txid, "type": PaykitPaymentProofKind.onchain.rawValue] + ) + } + + func testSparkWithdrawalThatNeverWentOutDropsItsStartedProof() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + } + func testOnchainCompletionDoesNotWaitForProofDelivery() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue let record = try paymentRequestRecord(endpoints: [endpoint]) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index dc7c450c1e..1fd62e71f2 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -113,7 +113,7 @@ final class PaykitRouteTests: XCTestCase { // MARK: - Spark leg offer - func testSparkLegIsOfferedOnlyForAnOnchainContactPaymentTheUserStarts() { + func testSparkLegIsOfferedForAnOnchainContactLightningCantPay() { let onchainOnly = ContactPaymentContext( publicKey: "contact", privatePaymentContext: nil, From 0a47cc8d38dce7163ae0ac3b53c483701cb79f78 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:48:05 +0100 Subject: [PATCH 12/64] fix: charge the spark leg its broadcast fee and keep it a send - A Spark leg to a contact's on-chain address now counts the L1 broadcast fee Spark's prepare reports, so Confirm shows the whole fee, and the withdrawal refuses a fee above the one Confirm showed. - A withdrawal to a contact is never marked as a transfer to Savings, so its activity stays a send to the contact. --- Bitkit/Managers/SparkManager.swift | 22 ++++++++++++++++++++-- Bitkit/Services/PaykitRouteService.swift | 1 + BitkitTests/PaykitRouteTests.swift | 16 ++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 20a0f63f8d..f6f2b4c31b 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -448,7 +448,7 @@ final class SparkManager: ChannelFreeLightningRail { guard case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod else { throw AppError(message: "Unexpected Spark payment method", debugMessage: "\(prepared.paymentMethod)") } - let debitSats = amountSats + feeQuote.speedMedium.userFeeSat + let debitSats = Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) guard !feeQuote.isEstimate, balanceSats >= debitSats else { return nil } return ServiceRouteLeg( service: Self.routeService, @@ -460,6 +460,11 @@ final class SparkManager: ChannelFreeLightningRail { ) } + /// What a withdrawal of `amountSats` takes from the balance: the amount, Spark's fee and the L1 broadcast fee. + nonisolated static func withdrawalDebitSats(amountSats: UInt64, fee: SendOnchainSpeedFeeQuote) -> UInt64 { + amountSats.saturatingAdd(fee.userFeeSat).saturatingAdd(fee.l1BroadcastFeeSat) + } + /// Withdraws exactly `amountSats` to a contact's on-chain `address` at medium speed and returns its txid. The /// withdrawal is written to a journal before it is sent, so one interrupted mid-send settles from Spark's payment /// list; a second one is refused while it is open. It is recorded as a sent on-chain activity for the contact. @@ -470,12 +475,20 @@ final class SparkManager: ChannelFreeLightningRail { amountSats: UInt64, contact: String?, request: SparkContactWithdrawal.PaykitRequest? = nil, + maxFeeSats: UInt64? = nil, beforeSend: () async throws -> Void = {} ) async throws -> String { guard Self.pendingContactWithdrawal == nil else { throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") } let prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) + if let maxFeeSats, case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod { + // The fee Confirm showed caps the one sent, broadcast fee included. + try Self.checkWithdrawalFee( + Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) - amountSats, + shownFeeSats: maxFeeSats + ) + } try await beforeSend() let pending = SparkContactWithdrawal( address: address, @@ -746,7 +759,7 @@ final class SparkManager: ChannelFreeLightningRail { await recordActivity(payment) } let contactWithdrawals = Self.contactWithdrawalTxIds - for txId in Self.transferTxIds(unclaimed: unclaimed, payments: payments) where !contactWithdrawals.contains(txId) { + for txId in Self.savingsTransferTxIds(unclaimed: unclaimed, payments: payments, contactWithdrawals: contactWithdrawals) { await CoreService.shared.activity.markOnchainActivityAsTransfer(txId: txId) } for payment in payments where payment.status == .completed { @@ -763,6 +776,11 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// The transfers between Savings and Spark, without the withdrawals that paid contacts, which stay sends to them. + nonisolated static func savingsTransferTxIds(unclaimed: [DepositInfo], payments: [Payment], contactWithdrawals: Set) -> [String] { + transferTxIds(unclaimed: unclaimed, payments: payments).filter { !contactWithdrawals.contains($0) } + } + /// On-chain transactions that moved funds between Savings and Spark, so their activities show as transfers. nonisolated static func transferTxIds(unclaimed: [DepositInfo], payments: [Payment]) -> [String] { unclaimed.map(\.txid) + payments.compactMap { payment in diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 7f32e7bb1f..e8124b5916 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -151,6 +151,7 @@ enum PaykitRouteService { amountSats: leg.deliveredSat, contact: contact, request: request, + maxFeeSats: leg.debitSat.saturatingSub(leg.deliveredSat), beforeSend: beforeSend ) } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 1fd62e71f2..bf413c0752 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -150,6 +150,22 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(SparkManager.matchingWithdrawal(pending, in: [other, earlier])) } + func testSparkLegDebitsTheL1BroadcastFeeToo() { + let fee = SendOnchainSpeedFeeQuote(userFeeSat: 750, l1BroadcastFeeSat: 1440) + + XCTAssertEqual(SparkManager.withdrawalDebitSats(amountSats: 2000, fee: fee), 4190, "Confirm and the fee check use 2,190, not 750") + XCTAssertThrowsError(try SparkManager.checkWithdrawalFee(2190, shownFeeSats: 750)) + } + + func testContactWithdrawalStaysASendNotATransfer() { + let toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + + let transfers = SparkManager.savingsTransferTxIds(unclaimed: [], payments: [toContact, toSavings], contactWithdrawals: ["tx-contact"]) + + XCTAssertEqual(transfers, ["tx-savings"]) + } + private static func endpoint(_ methodId: PublicPaykitService.MethodId, _ value: String) -> PublicPaykitService.Endpoint { PublicPaykitService.Endpoint(methodId: methodId, value: value, min: nil, max: nil, rawPayload: value) } From 4521e568e0a78d2f537e2e83f551731921027e8c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 04:20:36 +0100 Subject: [PATCH 13/64] fix: keep spark contact withdrawals recoverable Keep the withdrawal journal until the proof, activity and tags are saved, match a recovered withdrawal to its own attempt, prepare and release a request on the Spark leg like a direct send, tell a pre-send refusal from the send itself, pick a request's source by what Savings covers, reroute on a source switch, and use the leg's amount and fee in Confirm warnings. --- Bitkit/Managers/SparkManager.swift | 142 ++++++++++++----- .../Services/PaykitPaymentProofService.swift | 6 +- Bitkit/Services/PaykitRouteService.swift | 42 +++++ Bitkit/ViewModels/AppViewModel.swift | 16 ++ .../Wallets/Send/SendConfirmationView.swift | 149 ++++++++++++----- .../PaykitPaymentProofServiceTests.swift | 2 + BitkitTests/PaykitRouteTests.swift | 150 +++++++++++++++++- 7 files changed, 426 insertions(+), 81 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index f6f2b4c31b..db67b65243 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -475,34 +475,49 @@ final class SparkManager: ChannelFreeLightningRail { amountSats: UInt64, contact: String?, request: SparkContactWithdrawal.PaykitRequest? = nil, + tags: [String] = [], maxFeeSats: UInt64? = nil, beforeSend: () async throws -> Void = {} ) async throws -> String { - guard Self.pendingContactWithdrawal == nil else { - throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") - } - let prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) - if let maxFeeSats, case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod { - // The fee Confirm showed caps the one sent, broadcast fee included. - try Self.checkWithdrawalFee( - Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) - amountSats, - shownFeeSats: maxFeeSats - ) + // Everything before the journal is written sends nothing, so a refusal here says so to the caller. + let sdk: BreezSdk + let prepared: PrepareSendPaymentResponse + let earlierPayments: [Payment] + do { + guard Self.pendingContactWithdrawal == nil else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") + } + sdk = try await requireSdk() + prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) + if let maxFeeSats, case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod { + // The fee Confirm showed caps the one sent, broadcast fee included. + try Self.checkWithdrawalFee( + Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) - amountSats, + shownFeeSats: maxFeeSats + ) + } + // Withdrawals Spark already lists for this address and amount belong to earlier attempts, so recovery never + // takes one of them for this attempt. + earlierPayments = try await sdk.listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + try await beforeSend() + } catch { + throw SparkWithdrawalNotSent(underlying: error) } - try await beforeSend() - let pending = SparkContactWithdrawal( + var pending = SparkContactWithdrawal( address: address, amountSats: amountSats, contact: contact, startedAt: UInt64(Date().timeIntervalSince1970), - request: request + request: request, + tags: tags, + earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments) ) Self.pendingContactWithdrawal = pending isWithdrawingToContact = true defer { isWithdrawingToContact = false } let response: SendPaymentResponse do { - response = try await requireSdk().sendPayment(request: SendPaymentRequest( + response = try await sdk.sendPayment(request: SendPaymentRequest( prepareResponse: prepared, options: .bitcoinAddress(confirmationSpeed: .medium) )) @@ -515,6 +530,8 @@ final class SparkManager: ChannelFreeLightningRail { throw error } Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") + pending.paymentId = response.payment.id + Self.pendingContactWithdrawal = pending guard case let .withdraw(txId, _, _) = response.payment.details else { await refreshState() return response.payment.id @@ -524,15 +541,16 @@ final class SparkManager: ChannelFreeLightningRail { return txId } - /// Settles the open contact withdrawal from Spark's payments: a withdrawal of its amount sent since it started is - /// recorded; with `allowClear`, a synced list without one closes it as never sent. + /// Settles the open contact withdrawal from Spark's payments: its own payment, once Spark returned it, or else a + /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear`, a synced list + /// without one closes it as never sent and releases the request's proof. func settleContactWithdrawal(allowClear: Bool) async { guard let pending = Self.pendingContactWithdrawal, !isWithdrawingToContact, let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments else { return } if let payment = Self.matchingWithdrawal(pending, in: payments), case let .withdraw(txId, _, _) = payment.details { await recordContactWithdrawal(payment, txId: txId, pending: pending) - } else if allowClear { + } else if allowClear, pending.paymentId == nil { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") Self.pendingContactWithdrawal = nil if let request = pending.request { @@ -542,43 +560,80 @@ final class SparkManager: ChannelFreeLightningRail { } nonisolated static func matchingWithdrawal(_ pending: SparkContactWithdrawal, in payments: [Payment]) -> Payment? { - payments.first { payment in - guard payment.paymentType == .send, case let .withdraw(_, _, destination) = payment.details else { return false } - return destination == pending.address && sats(payment.amount) == pending.amountSats && - payment.timestamp + contactWithdrawalClockSkewSecs >= pending.startedAt + if let paymentId = pending.paymentId { + return payments.first { $0.id == paymentId } + } + let earlier = Set(pending.earlierPaymentIds ?? []) + return payments.first { payment in + !earlier.contains(payment.id) && withdrawalIds(to: pending.address, amountSats: pending.amountSats, in: [payment]) == [payment.id] } } - private nonisolated static let contactWithdrawalClockSkewSecs: UInt64 = 120 + nonisolated static func withdrawalIds(to address: String, amountSats: UInt64, in payments: [Payment]) -> [String] { + payments.compactMap { payment in + guard payment.paymentType == .send, case let .withdraw(_, _, destination) = payment.details, + destination == address, sats(payment.amount) == amountSats + else { return nil } + return payment.id + } + } + /// Writes the withdrawal's sent activity, tags and request proof, and closes the journal only once all of them are + /// saved, so a failed or interrupted write is retried from the journal. private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { - Self.pendingContactWithdrawal = nil guard payment.status != .failed else { + Self.pendingContactWithdrawal = nil if let request = pending.request { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) } return } - if let request = pending.request { - _ = await PaykitPaymentProofService.shared.completeSparkOnchainPayment( - requestId: request.id, - identity: request.identity, - txid: txId - ) - } Self.contactWithdrawalTxIds.insert(txId) - _ = await CoreService.shared.activity.createSentOnchainActivityFromSendResult( - txid: txId, - address: pending.address, - amount: pending.amountSats, - fee: Self.sats(payment.fees), - feeRate: 0, - contact: pending.contact, - feeIsExact: true + let isDurable = await Self.recordWithdrawalLocally( + saveProof: { + guard let request = pending.request else { return true } + return await PaykitPaymentProofService.shared.completeSparkOnchainPayment( + requestId: request.id, + identity: request.identity, + txid: txId + ) + }, + saveActivity: { + await CoreService.shared.activity.createSentOnchainActivityFromSendResult( + txid: txId, + address: pending.address, + amount: pending.amountSats, + fee: Self.sats(payment.fees), + feeRate: 0, + contact: pending.contact, + feeIsExact: true + ) + }, + saveTags: { + guard let tags = pending.tags, !tags.isEmpty else { return true } + return await (try? CoreService.shared.activity.appendTags(toActivity: txId, tags)) != nil + } ) if payment.status == .completed { await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) } + if isDurable { + Self.pendingContactWithdrawal = nil + } else { + Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") + } + } + + /// Saves the proof, then the activity, then its tags; true only when every write succeeded. + static func recordWithdrawalLocally( + saveProof: () async -> Bool, + saveActivity: () async -> Bool, + saveTags: () async -> Bool + ) async -> Bool { + let proofSaved = await saveProof() + let activitySaved = await saveActivity() + let tagsSaved = activitySaved ? await saveTags() : false + return proofSaved && activitySaved && tagsSaved } private nonisolated static let pendingContactWithdrawalKey = "sparkPendingContactWithdrawal" @@ -1077,6 +1132,11 @@ enum SparkErrorCopy { } /// A Spark withdrawal to a contact's on-chain address, journaled before it is sent. +/// A contact withdrawal refused before its journal was written: nothing was sent. +struct SparkWithdrawalNotSent: Error { + let underlying: Error +} + struct SparkContactWithdrawal: Codable, Equatable { /// The Paykit request a withdrawal pays, and the identity its proof belongs to. struct PaykitRequest: Codable, Equatable { @@ -1089,6 +1149,12 @@ struct SparkContactWithdrawal: Codable, Equatable { let contact: String? let startedAt: UInt64 var request: PaykitRequest? + /// Tags picked on Confirm, saved on the sent activity. + var tags: [String]? + /// Withdrawals to the same address and amount Spark listed before this attempt; recovery skips them. + var earlierPaymentIds: [String]? + /// This attempt's Spark payment, once Spark returned it. + var paymentId: String? } struct SparkWithdrawal: Identifiable, Equatable { diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 0e7c922118..7a856bbb74 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1348,8 +1348,10 @@ actor PaykitPaymentProofService { try await persist(proofs) return proofs[index] } - guard let completed else { return false } - submitInBackground(completed, priority: .interactive) + // No started proof left means an earlier pass already saved it, or the request no longer waits on one. + if let completed { + submitInBackground(completed, priority: .interactive) + } return true } catch { logWarning("Failed to retain a Spark on-chain proof for retry: \(error)") diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index e8124b5916..889bdbbe8a 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -137,10 +137,51 @@ enum PaykitRouteService { } /// Runs a service leg the router picked and returns the txid that pays the contact. + /// Whether a failed leg send releases this call's started proof: only when Spark refused it before sending, and no + /// open journal of the same request (an earlier attempt that may have paid) still owns that proof. Another + /// request's open journal never decides it. + static func legFailureReleasesProof( + _ error: Error, + openJournalRequest: SparkContactWithdrawal.PaykitRequest?, + proofRequest: SparkContactWithdrawal.PaykitRequest + ) -> Bool { + error is SparkWithdrawalNotSent && openJournalRequest != proofRequest + } + + /// Starts the on-chain proof of a request a Spark leg pays, in a direct send's order: the proof is prepared, then the + /// request (its checks and private list consumption), then the proof is marked started. Any failure releases the + /// private payment list as unsent, and one after the proof was prepared cancels it, so the request can be paid again. + static func startLegRequestProof( + prepareProof: () async throws -> Void, + prepareRequest: () async throws -> Void, + paymentIdentity: () async throws -> String, + markStarted: (String) async throws -> Void, + cancelProof: () async -> Void, + releasePaymentList: () async -> Void + ) async throws -> String { + do { + try await prepareProof() + } catch { + await releasePaymentList() + throw error + } + do { + try await prepareRequest() + let identity = try await paymentIdentity() + try await markStarted(identity) + return identity + } catch { + await cancelProof() + await releasePaymentList() + throw error + } + } + static func pay( _ leg: ServiceRouteLeg, contact: String?, request: SparkContactWithdrawal.PaykitRequest? = nil, + tags: [String] = [], beforeSend: () async throws -> Void = {} ) async throws -> String { guard leg.service == SparkManager.routeService else { @@ -151,6 +192,7 @@ enum PaykitRouteService { amountSats: leg.deliveredSat, contact: contact, request: request, + tags: tags, maxFeeSats: leg.debitSat.saturatingSub(leg.deliveredSat), beforeSend: beforeSend ) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index e76d3d8058..739d96a47a 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -824,6 +824,22 @@ extension AppViewModel { isUsdtEnabled: SettingsViewModel.shared.isUsdtEnabled ) || context.incomingPaymentRequest.map { PaykitUsdtPaymentService.shared.hasBinding(for: $0.id) } == true selectedWalletToPayFrom = canUseLightning || (hasLightning && scannedOnchainInvoice == nil) ? .lightning : .onchain + // A Spark leg can pay the on-chain endpoint from Spending here too, when Lightning can't pay directly. + if !canUseLightning, scannedOnchainInvoice != nil, + let route = PaykitRouteService.routeUi( + for: context, + canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark, + canPayDirectly: false + ), route.offersSparkLeg + { + paykitRoute = route + // A request keeps its source here; its Confirm asks the router. + if !hasLightning, context.incomingPaymentRequest == nil, + max(state.spendableOnchainBalanceSats, alternativeOnchainBalanceSats) <= UInt64(Env.dustLimit) + { + selectedWalletToPayFrom = .lightning + } + } let canSelectUsdt = SettingsViewModel.shared.isUsdtEnabled && context.endpoints.contains { $0.methodId == .usdtArbitrum } if !paykitUsesUsdt, !canSelectUsdt, let request = context.incomingPaymentRequest { do { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 6773bfc251..d289467dee 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -29,6 +29,8 @@ struct SendConfirmationView: View { @State private var showDetails = false @State private var routedIncomingRequestId: PaykitPaymentRequest.ID? + /// Set when Confirm picks a request's source itself, so that switch isn't routed twice. + @State private var skipNextSourceReroute = false @State private var hasShownAmountReview = false @State private var showingBiometricError = false @State private var biometricErrorMessage = "" @@ -465,7 +467,7 @@ struct SendConfirmationView: View { } guard preparingRequest == nil, !isRequestSetupPending, !returnToAmountReviewIfNeeded() else { return } ensureSendAmountFromScannedInvoicesIfNeeded() - await routeIncomingRequestIfNeeded() + await routeContactPaymentOnConfirm() if app.contactPaymentContext?.isInitialSubscriptionPayment == true, !shouldAutomaticallyPay { showManualConfirmation(reason: "not automatic when opened") } @@ -505,6 +507,15 @@ struct SendConfirmationView: View { !returnToAmountReviewIfNeeded(rebindMethod: !hwSend.isActive) else { return } ensureSendAmountFromScannedInvoicesIfNeeded() walletSwitchContext = sendContext + if skipNextSourceReroute { + skipNextSourceReroute = false + } else if Self.sourceSwitchNeedsReroute( + route: app.paykitRoute, + walletType: app.selectedWalletToPayFrom, + hasLightningPayment: app.scannedLightningInvoice != nil || app.lnurlPayData != nil + ) { + Task { await routeContactPaymentOnConfirm(sourceChanged: true) } + } } .onChange(of: navigationPath) { previous, path in guard preparingRequest == nil, previous.last == .amount, path.isEmpty, requiresAmountReview, !amountIsRoot else { return } @@ -1044,13 +1055,23 @@ struct SendConfirmationView: View { if hwSend.isActive { navigationPath.append(.hardwareSign) - } else if let leg = app.paykitRoute?.serviceLeg { + } else if !app.paykitUsesUsdt, let leg = app.paykitRoute?.serviceLeg { await performServiceRoutedPayment(leg) } else { try await performPayment(isAutomatic: isAutomatic) } } + /// A source switch on Confirm needs the router only when it moves a Spark leg's send to Savings, or a send that has no + /// Lightning payment to Spending, where a Spark leg can carry it. The app's own switch to a leg's source asks nothing. + static func sourceSwitchNeedsReroute(route: PaykitRouteUi?, walletType: WalletType, hasLightningPayment: Bool) -> Bool { + guard let route else { return false } + if route.serviceLeg != nil { + return walletType != .lightning + } + return walletType == .lightning && !hasLightningPayment && route.offersSparkLeg + } + /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. static func canStartAutomaticPayment( shouldAutomaticallyPay: Bool, @@ -1366,19 +1387,44 @@ struct SendConfirmationView: View { } /// A request's Confirm opens with fixed terms and no amount screen, so the router is asked here: Direct switches the - /// send to the endpoint it picks, and a Spark leg pays an on-chain request from Spending. - private func routeIncomingRequestIfNeeded() async { - guard let context = app.contactPaymentContext, let request = context.incomingPaymentRequest, - !app.paykitUsesUsdt, !hwSend.isActive, routedIncomingRequestId != request.id, - let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) + /// send to the endpoint it picks, and a Spark leg pays an on-chain request from Spending. A source switch on Confirm + /// asks it again for any contact payment, so a leg never pays a send the payer moved to Savings. + private func routeContactPaymentOnConfirm(sourceChanged: Bool = false) async { + guard let context = app.contactPaymentContext, !app.paykitUsesUsdt, !hwSend.isActive, !isSubmittingPayment else { return } + let request = context.incomingPaymentRequest + if !sourceChanged { + guard let request, routedIncomingRequestId != request.id else { return } + } + guard let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) else { return } - let amount = app.paykitPaymentTerms?.amount ?? request.amount - guard amount.asset == .btc, amount.atomic > 0 else { return } - routedIncomingRequestId = request.id + let amountSats: UInt64 + if let request { + let amount = app.paykitPaymentTerms?.amount ?? request.amount + guard amount.asset == .btc else { return } + amountSats = amount.atomic + } else { + amountSats = route.deliveredSat ?? wallet.sendAmountSats ?? 0 + } + guard amountSats > 0 else { return } + if let request { + routedIncomingRequestId = request.id + // A request has no amount screen to pick its source, so pick it as that screen would: Savings when it covers + // the amount and fee, otherwise Spending, where the Spark leg can carry it. + if !sourceChanged, app.selectedWalletToPayFrom == .onchain, app.scannedLightningInvoice == nil, app.lnurlPayData == nil, + await Self.requestStartsOnSpending( + savingsSendableSats: savingsSendableSats(), + amountSats: amountSats, + offersSparkLeg: route.offersSparkLeg + ) + { + skipNextSourceReroute = true + app.selectedWalletToPayFrom = .lightning + } + } let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings _ = await app.routeContactPayment( route, - amountSats: amount.atomic, + amountSats: amountSats, source: source, lightningSpendableSats: source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0, onchainSpendableSats: source == .savings ? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, @@ -1386,6 +1432,17 @@ struct SendConfirmationView: View { ) } + /// What Savings can send to the request's address after the on-chain fee; its balance while no fee rate is known. + private func savingsSendableSats() async -> UInt64 { + let balance = UInt64(max(0, wallet.spendableOnchainBalanceSats)) + guard let address = app.scannedOnchainInvoice?.address, let rate = wallet.selectedFeeRateSatsPerVByte else { return balance } + return await (try? wallet.calculateMaxSendableAmount(address: address, satsPerVByte: rate)) ?? balance + } + + static func requestStartsOnSpending(savingsSendableSats: UInt64, amountSats: UInt64, offersSparkLeg: Bool) -> Bool { + offersSparkLeg && savingsSendableSats < amountSats + } + /// Withdraws from Spark to the contact's on-chain address. A request it pays gets an on-chain proof with the /// withdrawal's txid; the proof is started before the send, and Spark's journal settles it if the app stops mid-send. private func performServiceRoutedPayment(_ leg: ServiceRouteLeg) async { @@ -1399,41 +1456,54 @@ struct SendConfirmationView: View { do { if let request { guard let privateContext = context?.privatePaymentContext else { throw PaykitPaymentRequestError.requestUnavailable } - try await PaykitPaymentProofService.shared.prepare( - request: request, - paymentAppId: privateContext.paymentAppId(for: leg.endpoint.methodId), - paymentEndpointIdentifier: leg.endpoint.methodId, - kind: .onchain, - paymentTerms: app.paykitPaymentTerms + let identity = try await PaykitRouteService.startLegRequestProof( + prepareProof: { + try await PaykitPaymentProofService.shared.prepare( + request: request, + paymentAppId: privateContext.paymentAppId(for: leg.endpoint.methodId), + paymentEndpointIdentifier: leg.endpoint.methodId, + kind: .onchain, + paymentTerms: app.paykitPaymentTerms + ) + }, + prepareRequest: { try await prepareIncomingPaymentRequest() }, + paymentIdentity: { try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) }, + markStarted: { identity in + try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( + request, + address: leg.endpoint.value, + paymentIdentity: identity + ) + }, + cancelProof: { await PaykitPaymentProofService.shared.cancelPreparation(request) }, + releasePaymentList: { await context?.resolvePrivatePaymentListConsumption(.definitePreBroadcastFailure) } ) - let identity = try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) - do { - try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( - request, - address: leg.endpoint.value, - paymentIdentity: identity - ) - } catch { - await PaykitPaymentProofService.shared.cancelPreparation(request) - throw error - } proofRequest = SparkContactWithdrawal.PaykitRequest(id: request.id, identity: identity) } let txid: String do { - txid = try await PaykitRouteService.pay(leg, contact: context?.publicKey, request: proofRequest) { + txid = try await PaykitRouteService.pay( + leg, + contact: context?.publicKey, + request: proofRequest, + tags: tagManager.selectedTagsArray + ) { if let request { try await paykitPaymentRequestManager.ensurePaymentAllowed(request) } } } catch { - // Refused before Spark's send: nothing left, so the started proof goes. After it, the journal settles it. - let refusedBeforeSend = SparkManager.pendingContactWithdrawal == nil - if let proofRequest, refusedBeforeSend { + // Refused before Spark's send: nothing left, so this call's started proof goes. After it, the journal settles it. + let refusedBeforeSend = error is SparkWithdrawalNotSent + if let proofRequest, PaykitRouteService.legFailureReleasesProof( + error, + openJournalRequest: SparkManager.pendingContactWithdrawal?.request, + proofRequest: proofRequest + ) { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: proofRequest.id, identity: proofRequest.identity) } await context?.resolvePrivatePaymentListConsumption(refusedBeforeSend ? .definitePreBroadcastFailure : .uncertain) - throw error + throw (error as? SparkWithdrawalNotSent)?.underlying ?? error } await context?.resolvePrivatePaymentListConsumption(.succeeded) Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") @@ -1875,7 +1945,11 @@ struct SendConfirmationView: View { private func validatePayment() async -> [WarningType] { var warnings: [WarningType] = [] - let amount: UInt64 = if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { + // A Spark leg delivers its amount on-chain from Spending, so its amount and fee get the on-chain checks. + let leg = app.paykitRoute?.serviceLeg + let amount: UInt64 = if let leg { + leg.deliveredSat + } else 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 @@ -1902,13 +1976,14 @@ struct SendConfirmationView: View { } // Check if fee > $10 (only for onchain) - if app.selectedWalletToPayFrom == .onchain { - if let feeUsd = currency.convert(sats: UInt64(transactionFee), to: "USD"), feeUsd.value > 10.0 { + if leg != nil || app.selectedWalletToPayFrom == .onchain { + let fee = leg.map { $0.debitSat.saturatingSub($0.deliveredSat) } ?? UInt64(max(0, transactionFee)) + if let feeUsd = currency.convert(sats: fee, to: "USD"), feeUsd.value > 10.0 { warnings.append(.fee) } // Check if fee > 50% of send amount - if transactionFee > 0 && UInt64(transactionFee) > amount / 2 { + if fee > 0 && fee > amount / 2 { warnings.append(.feePercentage) } diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 0a8b934f98..6d78c9de4d 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1900,6 +1900,8 @@ final class PaykitPaymentProofServiceTests: XCTestCase { await fulfillment(of: [proofRemoved], timeout: 1) XCTAssertTrue(completed, "Spark's withdrawal is no node send attempt, yet its txid completes the proof") + let retried = await service.completeSparkOnchainPayment(requestId: request.id, identity: identity, txid: txid) + XCTAssertTrue(retried, "A journal retry after the proof was saved must not keep the withdrawal open forever") let lastSubmission = await sdk.lastSubmission() let submission = try XCTUnwrap(lastSubmission) XCTAssertEqual(submission.paymentEndpointIdentifier, endpoint) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index bf413c0752..1abf66b2cb 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -140,14 +140,156 @@ final class PaykitRouteTests: XCTestCase { // MARK: - Contact withdrawal journal - func testJournaledWithdrawalSettlesFromTheMatchingSparkPayment() { - let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + func testJournaledWithdrawalMatchesOnlyItsOwnAttempt() { let other = Self.withdrawal(id: "other", to: "bcrt1qother", amountSats: 20000, timestamp: 1001) - let earlier = Self.withdrawal(id: "earlier", to: onchain.value, amountSats: 20000, timestamp: 100) + let earlier = Self.withdrawal(id: "earlier", to: onchain.value, amountSats: 20000, timestamp: 2000) let sent = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + var pending = SparkContactWithdrawal( + address: onchain.value, + amountSats: 20000, + contact: "contact", + startedAt: 1000, + earlierPaymentIds: SparkManager.withdrawalIds(to: onchain.value, amountSats: 20000, in: [other, earlier]) + ) + XCTAssertEqual(pending.earlierPaymentIds, ["earlier"]) XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [other, earlier, sent])?.id, "sent") - XCTAssertNil(SparkManager.matchingWithdrawal(pending, in: [other, earlier])) + XCTAssertNil( + SparkManager.matchingWithdrawal(pending, in: [other, earlier]), + "An earlier withdrawal to the same address is never this attempt" + ) + + pending.paymentId = "sent" + XCTAssertNil(SparkManager.matchingWithdrawal(pending, in: [other, earlier]), "Once Spark returned the attempt, only that payment settles it") + XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [earlier, sent])?.id, "sent") + } + + func testJournalStaysOpenUntilEveryLocalRecordIsSaved() async { + let saved = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { true }) + XCTAssertTrue(saved) + + var tagsTried = false + let activityFailed = await SparkManager.recordWithdrawalLocally( + saveProof: { true }, + saveActivity: { false }, + saveTags: { tagsTried = true; return true } + ) + XCTAssertFalse(activityFailed, "A failed activity write keeps the journal for a retry") + XCTAssertFalse(tagsTried, "Tags wait for the activity they belong to") + + var activityTried = false + let proofFailed = await SparkManager.recordWithdrawalLocally( + saveProof: { false }, + saveActivity: { activityTried = true; return true }, + saveTags: { true } + ) + XCTAssertFalse(proofFailed, "A proof that wasn't saved keeps the journal for a retry") + XCTAssertTrue(activityTried, "The activity is still written when the proof save fails") + + let tagsFailed = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { false }) + XCTAssertFalse(tagsFailed) + } + + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { + var steps: [String] = [] + let identity = try await PaykitRouteService.startLegRequestProof( + prepareProof: { steps.append("proof") }, + prepareRequest: { steps.append("request") }, + paymentIdentity: { steps.append("identity"); return "payer" }, + markStarted: { steps.append("started \($0)") }, + cancelProof: { steps.append("cancel") }, + releasePaymentList: { steps.append("release") } + ) + + XCTAssertEqual(identity, "payer") + XCTAssertEqual(steps, ["proof", "request", "identity", "started payer"], "The request is approved before Spark's payment check") + } + + func testLegThatFailsBeforeSendingFreesTheRequest() async { + struct Refused: Error {} + for failing in ["proof", "request", "started"] { + var steps: [String] = [] + do { + _ = try await PaykitRouteService.startLegRequestProof( + prepareProof: { + if failing == "proof" { + throw Refused() + } + }, + prepareRequest: { + if failing == "request" { + throw Refused() + } + }, + paymentIdentity: { "payer" }, + markStarted: { + _ in if failing == "started" { + throw Refused() + } + }, + cancelProof: { steps.append("cancel") }, + releasePaymentList: { steps.append("release") } + ) + XCTFail("\(failing) must fail the leg") + } catch {} + + XCTAssertEqual(steps, failing == "proof" ? ["release"] : ["cancel", "release"], failing) + } + } + + func testSourceSwitchOnConfirmReroutesOnlyWhenTheLegNoLongerFits() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) + var routed = offered + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .onchain, hasLightningPayment: false)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .lightning, hasLightningPayment: false)) + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning, hasLightningPayment: false)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning, hasLightningPayment: true)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .onchain, hasLightningPayment: false)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain, hasLightningPayment: false)) + } + + func testOnchainRequestStartsOnSpendingWhenSavingsCantCoverIt() { + // Savings 5,000 can't cover a 20,000 request, so Spending (Spark 50,000) pays it through the leg. + XCTAssertTrue(SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 5000, amountSats: 20000, offersSparkLeg: true)) + XCTAssertFalse(SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 48000, amountSats: 20000, offersSparkLeg: true)) + XCTAssertFalse( + SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 5000, amountSats: 20000, offersSparkLeg: false), + "Without a Spark leg the request stays on Savings" + ) + } + + func testRefusalWhileAnOlderJournalIsOpenReleasesThisCallsProof() { + struct Refused: Error {} + let older = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "older", counterparty: "payee"), + identity: "payer" + ) + let this = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "this", counterparty: "payee"), + identity: "payer" + ) + let notSent = SparkWithdrawalNotSent(underlying: Refused()) + + XCTAssertTrue( + PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: older, proofRequest: this), + "An older journal still open must not keep a refused send's proof started" + ) + XCTAssertTrue(PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: nil, proofRequest: this)) + XCTAssertFalse( + PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: this, proofRequest: this), + "An earlier attempt of the same request still owns its proof" + ) + XCTAssertFalse( + PaykitRouteService.legFailureReleasesProof(Refused(), openJournalRequest: this, proofRequest: this), + "A failure once Spark's send started is settled by the journal" + ) } func testSparkLegDebitsTheL1BroadcastFeeToo() { From a2a34000bac11844bde065aa0127837d09ea991c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 04:54:47 +0100 Subject: [PATCH 14/64] fix: settle spark contact withdrawals only after a fresh sync Settle the journal after an uncertain send only when that pass's sync succeeded, and close an attempt Spark never returned nor listed as unsent only after a 10-minute expiry. --- Bitkit/Managers/SparkManager.swift | 20 +++++++++++++++----- BitkitTests/PaykitRouteTests.swift | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index db67b65243..504862eda9 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -524,7 +524,8 @@ final class SparkManager: ChannelFreeLightningRail { } catch { Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") Task { - _ = try? await requireSdk().syncWallet(request: SyncWalletRequest()) + // Only a sync that succeeded now can tell whether this withdrawal went out. + guard await (try? requireSdk().syncWallet(request: SyncWalletRequest())) != nil else { return } await settleContactWithdrawal(allowClear: true) } throw error @@ -542,15 +543,17 @@ final class SparkManager: ChannelFreeLightningRail { } /// Settles the open contact withdrawal from Spark's payments: its own payment, once Spark returned it, or else a - /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear`, a synced list - /// without one closes it as never sent and releases the request's proof. - func settleContactWithdrawal(allowClear: Bool) async { + /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear` (after a sync that + /// succeeded), a list without one closes it as never sent and releases the request's proof, but only once the + /// attempt is past `contactWithdrawalExpirySecs`, so a withdrawal Spark hasn't listed yet is never dropped. One still + /// in flight in this process is never settled. + func settleContactWithdrawal(allowClear: Bool, now: UInt64 = UInt64(Date().timeIntervalSince1970)) async { guard let pending = Self.pendingContactWithdrawal, !isWithdrawingToContact, let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments else { return } if let payment = Self.matchingWithdrawal(pending, in: payments), case let .withdraw(txId, _, _) = payment.details { await recordContactWithdrawal(payment, txId: txId, pending: pending) - } else if allowClear, pending.paymentId == nil { + } else if allowClear, Self.canCloseUnlisted(pending, now: now) { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") Self.pendingContactWithdrawal = nil if let request = pending.request { @@ -559,6 +562,13 @@ final class SparkManager: ChannelFreeLightningRail { } } + nonisolated static let contactWithdrawalExpirySecs: UInt64 = 600 + + /// An attempt Spark never returned nor listed is taken as unsent only after the expiry. + nonisolated static func canCloseUnlisted(_ pending: SparkContactWithdrawal, now: UInt64) -> Bool { + pending.paymentId == nil && now >= pending.startedAt + contactWithdrawalExpirySecs + } + nonisolated static func matchingWithdrawal(_ pending: SparkContactWithdrawal, in payments: [Payment]) -> Payment? { if let paymentId = pending.paymentId { return payments.first { $0.id == paymentId } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 1abf66b2cb..b4a0d3fbac 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -164,6 +164,23 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [earlier, sent])?.id, "sent") } + func testUnlistedWithdrawalIsDroppedOnlyAfterTheExpiry() { + var pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + let expiry = SparkManager.contactWithdrawalExpirySecs + + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, now: 1001), + "A sync right after the send may not list the withdrawal yet" + ) + XCTAssertTrue(SparkManager.canCloseUnlisted(pending, now: 1000 + expiry)) + + pending.paymentId = "sent" + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, now: 1000 + expiry * 10), + "A withdrawal Spark returned went out and is never dropped as unsent" + ) + } + func testJournalStaysOpenUntilEveryLocalRecordIsSaved() async { let saved = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { true }) XCTAssertTrue(saved) From 54a0ff172c0d0d2d07b1d402b171e9978e7bdeff Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:07:14 +0100 Subject: [PATCH 15/64] fix: keep contact payments off the spark transfer list --- Bitkit/Managers/SparkManager.swift | 7 +++++-- BitkitTests/PaykitRouteTests.swift | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 504862eda9..8c4baa5b8e 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -834,9 +834,12 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// Spark's withdrawals to Savings, without the ones that paid contacts. nonisolated static func withdrawals(_ payments: [Payment]) -> [SparkWithdrawal] { - payments.compactMap { payment in - guard payment.status != .failed, case let .withdraw(txId, _, _) = payment.details else { return nil } + let contactWithdrawals = contactWithdrawalTxIds + return payments.compactMap { payment in + guard payment.status != .failed, case let .withdraw(txId, _, _) = payment.details, + !contactWithdrawals.contains(txId) else { return nil } return SparkWithdrawal(txid: txId, amountSats: sats(payment.amount), feeSats: sats(payment.fees)) } } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index b4a0d3fbac..fb121f6eb7 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -325,6 +325,20 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(transfers, ["tx-savings"]) } + func testSparkScreenWithdrawalsLeaveOutContactPayments() { + let saved = SparkManager.contactWithdrawalTxIds + defer { SparkManager.contactWithdrawalTxIds = saved } + SparkManager.contactWithdrawalTxIds = ["tx-contact"] + let toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "A contact payment is not a transfer to savings" + ) + } + private static func endpoint(_ methodId: PublicPaykitService.MethodId, _ value: String) -> PublicPaykitService.Endpoint { PublicPaykitService.Endpoint(methodId: methodId, value: value, min: nil, max: nil, rawPayload: value) } From 0b5b5317d217c4838bcae2b13c67f5bb412b869b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:36:56 +0100 Subject: [PATCH 16/64] fix: keep the swipe off when confirm's reroute is refused A source switch on Confirm reroutes the contact payment. A refused route left the swipe live, so the send consumed the contact's private payment list and then failed on missing invoice data. The refused source now keeps the swipe disabled until another source is picked. --- .../Wallets/Send/SendConfirmationView.swift | 27 +++++++++++++++---- BitkitTests/PaykitRouteTests.swift | 26 ++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index d289467dee..23defbe562 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -31,6 +31,7 @@ struct SendConfirmationView: View { @State private var routedIncomingRequestId: PaykitPaymentRequest.ID? /// Set when Confirm picks a request's source itself, so that switch isn't routed twice. @State private var skipNextSourceReroute = false + @State private var refusedRouteSource: WalletType? @State private var hasShownAmountReview = false @State private var showingBiometricError = false @State private var biometricErrorMessage = "" @@ -1260,9 +1261,10 @@ struct SendConfirmationView: View { isSetupPending: Bool = false, isPreparingWallet: Bool = false, isAmountReviewRequired: Bool = false, - isPreparingOnchainSend: Bool = false + isPreparingOnchainSend: Bool = false, + isRouteRefused: Bool = false ) -> Bool { - isAmountReviewRequired || isPreparingRequest || isSetupPending || isPreparingWallet || isPreparingOnchainSend + isAmountReviewRequired || isPreparingRequest || isSetupPending || isPreparingWallet || isPreparingOnchainSend || isRouteRefused || isHardwareConfirmationUnavailable || isFeeRateMissing(walletType: walletType, isHardwarePayment: isHardwarePayment, feeRate: feeRate) } @@ -1285,7 +1287,8 @@ struct SendConfirmationView: View { isSetupPending: isRequestSetupPending, isPreparingWallet: walletSwitchContext != nil, isAmountReviewRequired: requiresAmountReview, - isPreparingOnchainSend: isPreparingOnchainSend + isPreparingOnchainSend: isPreparingOnchainSend, + isRouteRefused: refusedRouteSource == app.selectedWalletToPayFrom ) } @@ -1421,8 +1424,9 @@ struct SendConfirmationView: View { app.selectedWalletToPayFrom = .lightning } } - let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings - _ = await app.routeContactPayment( + let walletType = app.selectedWalletToPayFrom + let source: PaykitRouteService.Source = walletType == .lightning ? .spending : .savings + let outcome = await app.routeContactPayment( route, amountSats: amountSats, source: source, @@ -1430,6 +1434,19 @@ struct SendConfirmationView: View { onchainSpendableSats: source == .savings ? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, request: request ) + if sourceChanged { + refusedRouteSource = Self.refusedRouteSource(after: outcome, on: walletType, previous: refusedRouteSource) + } + } + + /// A source the router refused on Confirm keeps the swipe off while it's selected, so nothing consumes the contact's + /// private list for a send with nothing to pay; another source is still payable. A late outcome for a source never + /// clears another one's refusal. + static func refusedRouteSource(after outcome: PaykitRouteOutcome, on walletType: WalletType, previous: WalletType?) -> WalletType? { + if outcome == .refused { + return walletType + } + return previous == walletType ? nil : previous } /// What Savings can send to the request's address after the on-chain fee; its balance while no fee rate is known. diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index fb121f6eb7..9fed20e877 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -272,6 +272,32 @@ final class PaykitRouteTests: XCTestCase { XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain, hasLightningPayment: false)) } + func testARefusedRerouteOnConfirmKeepsTheSwipeOffUntilAnotherSourceIsPicked() { + let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) + + XCTAssertEqual(refused, .lightning) + XCTAssertTrue(SendConfirmationView.isSwipeDisabled( + walletType: .lightning, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .lightning + ), "a refused route must keep the swipe off, so no private list is consumed for it") + XCTAssertFalse(SendConfirmationView.isSwipeDisabled( + walletType: .onchain, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .onchain + ), "switching back to Savings pays the contact again") + XCTAssertNil(SendConfirmationView.refusedRouteSource(after: .leg, on: .lightning, previous: refused)) + } + + func testALateRerouteOutcomeKeepsAnotherSourcesRefusal() { + XCTAssertEqual(SendConfirmationView.refusedRouteSource(after: .direct, on: .onchain, previous: .lightning), .lightning) + XCTAssertEqual(SendConfirmationView.refusedRouteSource(after: .refused, on: .onchain, previous: .lightning), .onchain) + } + func testOnchainRequestStartsOnSpendingWhenSavingsCantCoverIt() { // Savings 5,000 can't cover a 20,000 request, so Spending (Spark 50,000) pays it through the leg. XCTAssertTrue(SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 5000, amountSats: 20000, offersSparkLeg: true)) From d7c88bd6f9d500c3fc8b02b9b00d10aa4d8aa7da Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:37:03 +0100 Subject: [PATCH 17/64] fix: give back the private list when a spark withdrawal never sent The Spark leg's on-chain proof now stores the private payment list version the send consumed. When Spark's journal drops that proof as unsent, at relaunch or in process, the version is released exactly: only while the contact's list is still at that version and no automatic attempt owns it. --- .../Services/PaykitPaymentProofService.swift | 40 +++++++++++-- .../Wallets/Send/SendConfirmationView.swift | 9 ++- .../PaykitPaymentProofServiceTests.swift | 56 +++++++++++++++++++ 3 files changed, 99 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 7a856bbb74..25b1b4fa33 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1359,11 +1359,41 @@ actor PaykitPaymentProofService { } } - /// Drops the started on-chain proof of a request whose Spark withdrawal never went out. - func failSparkOnchainPayment(requestId: PaykitPaymentRequest.ID, identity: String) async { - await removeProofs { - PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && - $0.paymentStarted && $0.onchainWalletId == nil && $0.paymentIdentifier == nil && $0.proofData == nil + /// Drops the started on-chain proof of a request whose Spark withdrawal never went out, giving back the private list + /// version it consumed when the contact's list is still at exactly that version. + func failSparkOnchainPayment( + requestId: PaykitPaymentRequest.ID, + identity: String, + privatePaykitService: PrivatePaykitService = .shared + ) async { + do { + try await mutationLock.withLock { + let proofs = try await loadProofs() + let unsent = proofs.filter { + PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && + $0.paymentStarted && $0.onchainWalletId == nil && $0.paymentIdentifier == nil && $0.proofData == nil + } + guard !unsent.isEmpty else { return } + for proof in unsent { + guard let version = proof.privatePaymentListVersion else { continue } + try await privatePaykitService.releaseUnsentPaymentListVersion( + publicKey: proof.requestId.counterparty, + version: version, + previousVersion: proof.previousPrivatePaymentListVersion + ) + } + do { + try await persist(proofs.filter { !unsent.contains($0) }) + } catch { + for proof in unsent { + guard let version = proof.privatePaymentListVersion else { continue } + try await privatePaykitService.retainOriginalPaymentListVersion(publicKey: proof.requestId.counterparty, version: version) + } + throw error + } + } + } catch { + logWarning("Failed to clear an unsent Spark on-chain proof: \(error)") } } diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 23defbe562..5ae8524a88 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1486,10 +1486,17 @@ struct SendConfirmationView: View { prepareRequest: { try await prepareIncomingPaymentRequest() }, paymentIdentity: { try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) }, markStarted: { identity in + // The proof keeps the list version this send consumed, so dropping it as unsent gives the list back. + let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( + publicKey: request.counterparty, + attemptId: context?.id + ) try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( request, address: leg.endpoint.value, - paymentIdentity: identity + paymentIdentity: identity, + privatePaymentListVersion: privateContext.paymentListVersion, + previousPrivatePaymentListVersion: previousVersion ) }, cancelProof: { await PaykitPaymentProofService.shared.cancelPreparation(request) }, diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 6d78c9de4d..2ef8631303 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1926,6 +1926,58 @@ final class PaykitPaymentProofServiceTests: XCTestCase { XCTAssertTrue(remaining.isEmpty) } + func testAnUnsentSparkWithdrawalGivesBackItsPrivateListAfterARelaunch() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: sdk, store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 6), attemptId: UUID()) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted( + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: 6 + ) + // Spark's journal closes the withdrawal as never sent after the app restarted. + let relaunched = paymentProofService(sdk: sdk, store: store) + await relaunched.failSparkOnchainPayment(requestId: request.id, identity: identity, privatePaykitService: privatePaykit) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + let released = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(released, 6) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + } + + func testAnUnsentSparkWithdrawalLeavesAListAnotherPaymentConsumedSince() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted( + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: nil + ) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 8), attemptId: UUID()) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity, privatePaykitService: privatePaykit) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + let consumed = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(consumed, 8) + } + func testOnchainCompletionDoesNotWaitForProofDelivery() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue let record = try paymentRequestRecord(endpoints: [endpoint]) @@ -3442,6 +3494,10 @@ final class PaykitPaymentProofServiceTests: XCTestCase { return (format(start), format(end)) } + private func listContext(version: UInt64) -> PrivatePaykitPaymentContext { + PrivatePaykitPaymentContext(paymentAppsByEndpoint: [:], paymentListVersion: version) + } + private func paymentProofService( sdk: PaymentProofSdkMock, store: PaymentProofMemoryStore, From bbcc069ca84647959b668d244c1eb391505cc857 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:59:41 +0100 Subject: [PATCH 18/64] fix: keep the spark withdrawal journal until its proof is released --- Bitkit/Managers/SparkManager.swift | 27 +++++++++++++------ .../Services/PaykitPaymentProofService.swift | 8 ++++-- .../PaykitPaymentProofServiceTests.swift | 21 +++++++++++++++ BitkitTests/PaykitRouteTests.swift | 18 +++++++++++++ 4 files changed, 64 insertions(+), 10 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index bb6b8b66a7..6fec8b94d3 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -575,10 +575,7 @@ final class SparkManager: ChannelFreeLightningRail { await recordContactWithdrawal(payment, txId: txId, pending: pending) } else if allowClear, Self.canCloseUnlisted(pending, now: now) { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") - Self.pendingContactWithdrawal = nil - if let request = pending.request { - await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) - } + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof) } } @@ -612,10 +609,7 @@ final class SparkManager: ChannelFreeLightningRail { /// saved, so a failed or interrupted write is retried from the journal. private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { guard payment.status != .failed else { - Self.pendingContactWithdrawal = nil - if let request = pending.request { - await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) - } + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof) return } Self.contactWithdrawalTxIds.insert(txId) @@ -654,6 +648,23 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// Closes the journal of a withdrawal that never went out, but only once its request's started proof is released: + /// a proof left behind would block the request, so the journal stays for the next sync to retry. + static func closeUnsentWithdrawal( + _ pending: SparkContactWithdrawal, + releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> Bool + ) async { + if let request = pending.request, await !releaseProof(request) { + Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") + return + } + pendingContactWithdrawal = nil + } + + private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> Bool { + await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) + } + /// Saves the proof, then the activity, then its tags; true only when every write succeeded. static func recordWithdrawalLocally( saveProof: () async -> Bool, diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 25b1b4fa33..d816e93e4c 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1360,12 +1360,14 @@ actor PaykitPaymentProofService { } /// Drops the started on-chain proof of a request whose Spark withdrawal never went out, giving back the private list - /// version it consumed when the contact's list is still at exactly that version. + /// version it consumed when the contact's list is still at exactly that version. False when the proof could not be + /// dropped, so the withdrawal's journal stays open for a retry. + @discardableResult func failSparkOnchainPayment( requestId: PaykitPaymentRequest.ID, identity: String, privatePaykitService: PrivatePaykitService = .shared - ) async { + ) async -> Bool { do { try await mutationLock.withLock { let proofs = try await loadProofs() @@ -1392,8 +1394,10 @@ actor PaykitPaymentProofService { throw error } } + return true } catch { logWarning("Failed to clear an unsent Spark on-chain proof: \(error)") + return false } } diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 2ef8631303..9c170c3e74 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1926,6 +1926,27 @@ final class PaykitPaymentProofServiceTests: XCTestCase { XCTAssertTrue(remaining.isEmpty) } + func testAnUnsentSparkWithdrawalProofThatCantBeDroppedSaysSo() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress) + await store.failNextSave() + let failed = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + XCTAssertFalse(failed, "The journal stays open only when the caller learns the proof is still there") + let remaining = await store.snapshot() + XCTAssertEqual(remaining.count, 1) + let retried = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + XCTAssertTrue(retried) + let afterRetry = await store.snapshot() + XCTAssertTrue(afterRetry.isEmpty) + } + func testAnUnsentSparkWithdrawalGivesBackItsPrivateListAfterARelaunch() async throws { snapshotAppDefaultsDomain() UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 9fed20e877..ea01c0a7e4 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -207,6 +207,24 @@ final class PaykitRouteTests: XCTestCase { XCTAssertFalse(tagsFailed) } + func testUnsentWithdrawalKeepsItsJournalUntilTheProofIsReleased() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + SparkManager.pendingContactWithdrawal = pending + + await SparkManager.closeUnsentWithdrawal(pending) { _ in false } + XCTAssertEqual(SparkManager.pendingContactWithdrawal, pending, "A proof that wasn't released keeps the journal, so the next sync retries it") + + var released: SparkContactWithdrawal.PaykitRequest? + await SparkManager.closeUnsentWithdrawal(pending) { released = $0; return true } + XCTAssertEqual(released, request) + XCTAssertNil(SparkManager.pendingContactWithdrawal) + } + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { var steps: [String] = [] let identity = try await PaykitRouteService.startLegRequestProof( From d7883b01e60b0bf5b7b07c30572dd219834ba2c0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:08:32 +0100 Subject: [PATCH 19/64] fix: count spark-routed requests in the allowance ledger --- Bitkit/Services/PaykitRouteService.swift | 32 ++++++++++++++++ .../Wallets/Send/SendConfirmationView.swift | 32 ++++++++++++---- BitkitTests/PaykitRouteTests.swift | 38 +++++++++++++++++++ 3 files changed, 94 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 889bdbbe8a..c8b33dfd11 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -1,5 +1,6 @@ import BitkitCore import Foundation +import Paykit /// A contact payment bitkit-core's Paykit router picks the way for: the contact's bitcoin endpoints, whether a Spark leg /// may reach its on-chain ones, and the leg once the router picked one. @@ -177,6 +178,37 @@ enum PaykitRouteService { } } + /// Pays a leg as a manual payment the allowance ledger counts, as a direct send is: the attempt is reserved right + /// before Spark's send, marked sending once the request is authorized, and closed with the send's outcome: + /// succeeded with its txid, failed when Spark refused it before sending, and unknown otherwise. + static func payReportingAllowance( + beginAllowance: @escaping () async throws -> String?, + authorize: @escaping () async throws -> Void, + markSending: @escaping (String) async -> Void, + finishAllowance: (String, Paykit.PaymentOutcome, String?) async -> Void, + pay: (_ beforeSend: () async throws -> Void) async throws -> String + ) async throws -> String { + var attemptId: String? + do { + let txid = try await pay { + attemptId = try await beginAllowance() + try await authorize() + if let attemptId { + await markSending(attemptId) + } + } + if let attemptId { + await finishAllowance(attemptId, .succeeded, txid) + } + return txid + } catch { + if let attemptId { + await finishAllowance(attemptId, error is SparkWithdrawalNotSent ? .failed : .unknown, nil) + } + throw error + } + } + static func pay( _ leg: ServiceRouteLeg, contact: String?, diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 5ae8524a88..1dbf11cb17 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1506,15 +1506,31 @@ struct SendConfirmationView: View { } let txid: String do { - txid = try await PaykitRouteService.pay( - leg, - contact: context?.publicKey, - request: proofRequest, - tags: tagManager.selectedTagsArray - ) { - if let request { - try await paykitPaymentRequestManager.ensurePaymentAllowed(request) + txid = try await PaykitRouteService.payReportingAllowance( + beginAllowance: { + guard let request else { return nil } + return try await PaykitAllowanceExecutor.shared.beginManualPayment( + request, + paymentEndpointIdentifier: leg.endpoint.methodId + ) + }, + authorize: { + if let request { + try await paykitPaymentRequestManager.ensurePaymentAllowed(request) + } + }, + markSending: { await PaykitAllowanceExecutor.shared.manualOnchainPaymentSending(attemptId: $0) }, + finishAllowance: { + await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: $0, outcome: $1, transactionId: $2) } + ) { beforeSend in + try await PaykitRouteService.pay( + leg, + contact: context?.publicKey, + request: proofRequest, + tags: tagManager.selectedTagsArray, + beforeSend: beforeSend + ) } } catch { // Refused before Spark's send: nothing left, so this call's started proof goes. After it, the journal settles it. diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index ea01c0a7e4..a88d7eb102 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -1,6 +1,7 @@ @testable import Bitkit import BitkitCore import BreezSdkSpark +import Paykit import XCTest final class PaykitRouteTests: XCTestCase { @@ -225,6 +226,43 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(SparkManager.pendingContactWithdrawal) } + func testLegReportsItsAllowanceAttemptWithTheSendsOutcome() async { + struct Refused: Error {} + struct Lost: Error {} + var events: [String] = [] + func pay( + authorize: @escaping () async throws -> Void = {}, + send: @escaping (() async throws -> Void) async throws -> String + ) async -> String? { + try? await PaykitRouteService.payReportingAllowance( + beginAllowance: { events.append("begin"); return "attempt" }, + authorize: { events.append("authorize"); try await authorize() }, + markSending: { events.append("sending \($0)") }, + finishAllowance: { events.append("finish \($0) \($1) \($2 ?? "-")") }, + pay: send + ) + } + + let txid = await pay { beforeSend in try await beforeSend(); return "txid" } + XCTAssertEqual(txid, "txid") + XCTAssertEqual(events, ["begin", "authorize", "sending attempt", "finish attempt succeeded txid"]) + + events = [] + _ = await pay(authorize: { throw Refused() }) { beforeSend in + do { try await beforeSend() } catch { throw SparkWithdrawalNotSent(underlying: error) } + return "txid" + } + XCTAssertEqual(events, ["begin", "authorize", "finish attempt failed -"], "A send Spark refused paid nothing") + + events = [] + _ = await pay { beforeSend in try await beforeSend(); throw Lost() } + XCTAssertEqual( + events, + ["begin", "authorize", "sending attempt", "finish attempt unknown -"], + "A send that may have gone out stays unknown until recovery settles it" + ) + } + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { var steps: [String] = [] let identity = try await PaykitRouteService.startLegRequestProof( From e88af9720eadb6bb6e3dabd12cfc11b1a22049ef Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:21:22 +0100 Subject: [PATCH 20/64] fix: show an unresolved spark send as pending --- .../Wallets/Send/SendConfirmationView.swift | 26 ++++++++++++++++++- BitkitTests/SendConfirmationViewTests.swift | 20 ++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 1dbf11cb17..60a270956f 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1460,6 +1460,24 @@ struct SendConfirmationView: View { offersSparkLeg && savingsSendableSats < amountSats } + /// Where a failed leg goes: a leg Spark refused before sending paid nothing, so its failure offers Try Again; any + /// other failure may have sent it, so it stays pending until Spark's journal settles it. + static func serviceLegFailureRoute( + _ error: Error, + requestId: PaykitPaymentRequest.ID?, + routingCacheResetAttempted: Bool + ) -> SendRoute { + guard let refusal = error as? SparkWithdrawalNotSent else { + return .pending(paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: requestId) + } + return .failure(SendFailureContext( + error: refusal.underlying, + retryRoute: .confirm, + routingCacheResetAttempted: routingCacheResetAttempted, + paymentRequest: nil + )) + } + /// Withdraws from Spark to the contact's on-chain address. A request it pays gets an on-chain proof with the /// withdrawal's txid; the proof is started before the send, and Spark's journal settles it if the app stops mid-send. private func performServiceRoutedPayment(_ leg: ServiceRouteLeg) async { @@ -1543,7 +1561,13 @@ struct SendConfirmationView: View { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: proofRequest.id, identity: proofRequest.identity) } await context?.resolvePrivatePaymentListConsumption(refusedBeforeSend ? .definitePreBroadcastFailure : .uncertain) - throw (error as? SparkWithdrawalNotSent)?.underlying ?? error + Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") + navigationPath.append(Self.serviceLegFailureRoute( + error, + requestId: request?.id, + routingCacheResetAttempted: routingCacheResetAttempted + )) + return } await context?.resolvePrivatePaymentListConsumption(.succeeded) Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 9ee79a26be..a4e4856920 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -189,4 +189,24 @@ final class SendConfirmationViewTests: XCTestCase { .uncertain ) } + + func testASparkLegThatMayHaveSentStaysPendingInsteadOfOfferingTryAgain() { + struct Refused: Error {} + struct Lost: Error {} + let requestId = PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee") + + let unresolved = SendConfirmationView.serviceLegFailureRoute(Lost(), requestId: requestId, routingCacheResetAttempted: false) + XCTAssertEqual( + unresolved, + .pending(paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: requestId), + "Spark may have sent it, so the request stays pending until the journal settles" + ) + + let refused = SendConfirmationView.serviceLegFailureRoute( + SparkWithdrawalNotSent(underlying: Refused()), + requestId: requestId, + routingCacheResetAttempted: false + ) + guard case .failure = refused else { return XCTFail("A leg Spark refused before sending can be tried again") } + } } From 7db039f867e113e079666da0bbb8562d55598399 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:34:34 +0100 Subject: [PATCH 21/64] fix: settle a spark send's allowance attempt from its journal --- Bitkit/Managers/SparkManager.swift | 26 ++++++++++++++----- Bitkit/Services/PaykitAllowanceExecutor.swift | 11 ++++++++ .../PaykitAllowanceExecutorTests.swift | 20 ++++++++++++++ BitkitTests/PaykitRouteTests.swift | 11 ++++++-- 4 files changed, 59 insertions(+), 9 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 6fec8b94d3..ed83d1a9b3 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -575,7 +575,7 @@ final class SparkManager: ChannelFreeLightningRail { await recordContactWithdrawal(payment, txId: txId, pending: pending) } else if allowClear, Self.canCloseUnlisted(pending, now: now) { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") - await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof) + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) } } @@ -609,7 +609,7 @@ final class SparkManager: ChannelFreeLightningRail { /// saved, so a failed or interrupted write is retried from the journal. private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { guard payment.status != .failed else { - await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof) + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) return } Self.contactWithdrawalTxIds.insert(txId) @@ -642,6 +642,9 @@ final class SparkManager: ChannelFreeLightningRail { await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) } if isDurable { + if let request = pending.request { + await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) + } Self.pendingContactWithdrawal = nil } else { Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") @@ -649,14 +652,19 @@ final class SparkManager: ChannelFreeLightningRail { } /// Closes the journal of a withdrawal that never went out, but only once its request's started proof is released: - /// a proof left behind would block the request, so the journal stays for the next sync to retry. + /// a proof left behind would block the request, so the journal stays for the next sync to retry. The request's + /// allowance attempt, left unknown when the send's outcome was, then fails, so the ledger lets it be paid again. static func closeUnsentWithdrawal( _ pending: SparkContactWithdrawal, - releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> Bool + releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> Bool, + failAllowance: (SparkContactWithdrawal.PaykitRequest) async -> Void ) async { - if let request = pending.request, await !releaseProof(request) { - Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") - return + if let request = pending.request { + guard await releaseProof(request) else { + Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") + return + } + await failAllowance(request) } pendingContactWithdrawal = nil } @@ -665,6 +673,10 @@ final class SparkManager: ChannelFreeLightningRail { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) } + private static func failAllowance(_ request: SparkContactWithdrawal.PaykitRequest) async { + await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .failed) + } + /// Saves the proof, then the activity, then its tags; true only when every write succeeded. static func recordWithdrawalLocally( saveProof: () async -> Bool, diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 3a743e6a9e..fa20526fff 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -1373,6 +1373,17 @@ actor PaykitAllowanceExecutor { } } + /// Settles the manual attempt still open for a request once its outcome is learned later, as a Spark withdrawal's + /// journal learns it, so an unsent send no longer blocks the request on the ledger. + func settleManualPayment(requestId: PaykitPaymentRequest.ID, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async { + guard let identity = activeIdentity, + let entry = localState(identity: identity).journal.last(where: { + !$0.isAutomatic && $0.requestId == requestId && !$0.stage.isTerminal + }) + else { return } + await finishManualPayment(attemptId: entry.attemptId, outcome: outcome, transactionId: transactionId) + } + // MARK: Helpers private func checks(_ request: PaykitPaymentRequest, endpointIdentifier: String, trustedTime: String) throws -> Paykit.PaymentExecutionChecks { diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 1f30747a90..ca39c69d0a 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -1821,6 +1821,26 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertNil(blocked) } + func testALaterSettlementClosesTheOpenManualAttemptOfItsRequest() async throws { + let harness = AllowanceHarness() + await harness.executor.activate(identity: Fixtures.identityKey) + let request = try Fixtures.paymentRequest() + let attemptId = try await harness.executor.beginManualPayment(request, paymentEndpointIdentifier: Fixtures.onchainIdentifier) + let openAttempt = try XCTUnwrap(attemptId) + await harness.executor.finishManualPayment(attemptId: openAttempt, outcome: .unknown) + + await harness.executor.settleManualPayment(requestId: request.id, outcome: .failed) + await harness.executor.settleManualPayment(requestId: request.id, outcome: .succeeded) + + let outcomes = await harness.sdk.recordedOutcomes + XCTAssertEqual(outcomes, [ + Paykit.PaymentOutcomeReport(attemptId: openAttempt, outcome: .unknown), + Paykit.PaymentOutcomeReport(attemptId: openAttempt, outcome: .failed), + ], "Only the open attempt settles, once") + let journal = await harness.executor.localState(identity: Fixtures.identityKey).journal + XCTAssertEqual(journal.map(\.stage), [.failed]) + } + func testRecoverySettlesAManualLightningPaymentRestoredFromABackupTakenBeforeTheSend() async throws { let harness = AllowanceHarness() await harness.executor.activate(identity: Fixtures.identityKey) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index a88d7eb102..8a3272a1cb 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -217,12 +217,19 @@ final class PaykitRouteTests: XCTestCase { let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) SparkManager.pendingContactWithdrawal = pending - await SparkManager.closeUnsentWithdrawal(pending) { _ in false } + var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in false }, failAllowance: { failedAllowances.append($0) }) XCTAssertEqual(SparkManager.pendingContactWithdrawal, pending, "A proof that wasn't released keeps the journal, so the next sync retries it") + XCTAssertEqual(failedAllowances, [], "The attempt stays unknown while the journal is still open") var released: SparkContactWithdrawal.PaykitRequest? - await SparkManager.closeUnsentWithdrawal(pending) { released = $0; return true } + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { released = $0; return true }, + failAllowance: { failedAllowances.append($0) } + ) XCTAssertEqual(released, request) + XCTAssertEqual(failedAllowances, [request], "An unsent withdrawal fails its allowance attempt, so the ledger lets the request be paid again") XCTAssertNil(SparkManager.pendingContactWithdrawal) } From 2dcd5389c94a99285ee8bf75e3b8d10cad80b23a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:04:34 +0100 Subject: [PATCH 22/64] fix: end a spark withdrawal spark returns as failed as a failure --- Bitkit/Managers/SparkManager.swift | 20 ++++++++++++++++---- BitkitTests/PaykitRouteTests.swift | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index ed83d1a9b3..7d76b297e5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -553,12 +553,24 @@ final class SparkManager: ChannelFreeLightningRail { Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") pending.paymentId = response.payment.id Self.pendingContactWithdrawal = pending - guard case let .withdraw(txId, _, _) = response.payment.details else { - await refreshState() - return response.payment.id + if case let .withdraw(txId, _, _) = response.payment.details { + await recordContactWithdrawal(response.payment, txId: txId, pending: pending) } - await recordContactWithdrawal(response.payment, txId: txId, pending: pending) await refreshState() + return try Self.sentWithdrawalId(response.payment) + } + + /// What `withdraw` returns for the payment Spark sent: its txid, or its id while Spark gives none yet. A withdrawal + /// Spark returned as failed paid nothing, so the call ends as a refusal: the caller releases the request's proof, + /// private list and allowance attempt and shows a failure, never a success. + nonisolated static func sentWithdrawalId(_ payment: Payment) throws -> String { + guard payment.status != .failed else { + throw SparkWithdrawalNotSent(underlying: AppError( + message: "wallet__payment_failed_description", + debugMessage: "Spark returned withdrawal '\(payment.id)' as failed" + )) + } + guard case let .withdraw(txId, _, _) = payment.details else { return payment.id } return txId } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 8a3272a1cb..aa49589c99 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -261,6 +261,17 @@ final class PaykitRouteTests: XCTestCase { } XCTAssertEqual(events, ["begin", "authorize", "finish attempt failed -"], "A send Spark refused paid nothing") + events = [] + _ = await pay { beforeSend in + try await beforeSend() + throw SparkWithdrawalNotSent(underlying: Refused()) + } + XCTAssertEqual( + events, + ["begin", "authorize", "sending attempt", "finish attempt failed -"], + "A withdrawal Spark returned as failed paid nothing either" + ) + events = [] _ = await pay { beforeSend in try await beforeSend(); throw Lost() } XCTAssertEqual( @@ -270,6 +281,17 @@ final class PaykitRouteTests: XCTestCase { ) } + func testAWithdrawalSparkReturnsAsFailedEndsAsARefusal() throws { + let sent = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + XCTAssertEqual(try SparkManager.sentWithdrawalId(sent), "tx-sent") + + var failed = sent + failed.status = .failed + XCTAssertThrowsError(try SparkManager.sentWithdrawalId(failed), "A failed withdrawal paid nothing, so it never shows success") { + XCTAssertTrue($0 is SparkWithdrawalNotSent, "A refusal releases the request's proof, private list and allowance attempt") + } + } + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { var steps: [String] = [] let identity = try await PaykitRouteService.startLegRequestProof( From 54c0e0dad9dcdb411d5ec3a6f98840c4ff0bec4e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:59:35 +0100 Subject: [PATCH 23/64] fix: price a spark-funded request at its on-chain endpoint --- Bitkit/ViewModels/AppViewModel.swift | 10 +++++++++- BitkitTests/SendConfirmationLifecycleTests.swift | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 739d96a47a..8699d04dcd 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -760,9 +760,17 @@ extension AppViewModel { return paykitBitcoinMethod(for: selectedWalletToPayFrom) } + /// The method a send prices with. Spending with no Lightning payment to make funds the Spark leg to the on-chain + /// endpoint, so it takes that endpoint's price, the one the leg and its proof pay. func paykitBitcoinMethod(for wallet: WalletType) -> PublicPaykitService.MethodId { if wallet == .lightning { - return lnurlPayData != nil ? .bitcoinLightningLnurl : .bitcoinLightningBolt11 + if lnurlPayData != nil { + return .bitcoinLightningLnurl + } + if scannedLightningInvoice == nil, let address = scannedOnchainInvoice?.address { + return PublicPaykitService.onchainMethodId(for: address) + } + return .bitcoinLightningBolt11 } return PublicPaykitService.onchainMethodId(for: scannedOnchainInvoice?.address ?? "") } diff --git a/BitkitTests/SendConfirmationLifecycleTests.swift b/BitkitTests/SendConfirmationLifecycleTests.swift index a6d960d902..dc6b645b0e 100644 --- a/BitkitTests/SendConfirmationLifecycleTests.swift +++ b/BitkitTests/SendConfirmationLifecycleTests.swift @@ -29,6 +29,22 @@ final class SendConfirmationLifecycleTests: XCTestCase { XCTAssertEqual(wallet.sendAmountSats, 10000) } + func testASparkFundedOnchainRequestKeepsItsOnchainPriceOnSpending() throws { + snapshotAppDefaultsDomain() + let request = try onchainRequest(rates: [ + ConversionRate(asset: "btc", value: "0.000002188"), + ConversionRate(asset: "btc-lightning", value: "0.00002"), + ]) + let app = AppViewModel() + app.scannedOnchainInvoice = invoice + let onchainTerms = try request.payment(using: app.paykitPaymentMethod) + + // Spending funds the Spark leg, which still pays the request's on-chain endpoint. + app.selectedWalletToPayFrom = .lightning + + XCTAssertEqual(try request.payment(using: app.paykitPaymentMethod), onchainTerms) + } + func testQuotedWalletSwitchRebindsAmountOnConfirmation() async throws { snapshotAppDefaultsDomain() snapshotAppGroupDefaults("home_screen_display_currency_code_v1", "home_screen_display_currency_symbol_v1") From 4c735717e9aebf0490dd0256ccb5f934c3016f17 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:03:54 +0100 Subject: [PATCH 24/64] fix: settle a pending spark send from its journal --- Bitkit/Managers/SparkManager.swift | 36 +++++++++++++++++++ .../Wallets/Send/SendConfirmationView.swift | 6 ++-- .../Wallets/Send/SendPendingScreen.swift | 33 +++++++++++++++++ Bitkit/Views/Wallets/Send/SendSheet.swift | 7 ++++ BitkitTests/PaykitRouteTests.swift | 32 +++++++++++++++++ BitkitTests/SendConfirmationViewTests.swift | 14 +++++--- 6 files changed, 120 insertions(+), 8 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 7d76b297e5..2c57e502cc 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -17,6 +17,14 @@ final class SparkManager: ChannelFreeLightningRail { nonisolated static let routeService = "spark" private nonisolated static let routeAtomicity = "trusted" private nonisolated(unsafe) static let exitStateChanged = PassthroughSubject() + private nonisolated(unsafe) static let contactWithdrawalResolutionSubject = PassthroughSubject() + /// How each contact withdrawal's journal closes, which a pending send screen waits on. + static var contactWithdrawalResolutionPublisher: AnyPublisher { + contactWithdrawalResolutionSubject.eraseToAnyPublisher() + } + + /// The latest journal close in this process, for a pending screen that opens after it; a new journal clears it. + private(set) static var lastContactWithdrawalResolution: SparkContactWithdrawalResolution? /// Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. nonisolated static var exitStateChangedPublisher: AnyPublisher { exitStateChanged.eraseToAnyPublisher() @@ -533,6 +541,7 @@ final class SparkManager: ChannelFreeLightningRail { earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments) ) Self.pendingContactWithdrawal = pending + Self.lastContactWithdrawalResolution = nil isWithdrawingToContact = true defer { isWithdrawingToContact = false } let response: SendPaymentResponse @@ -658,6 +667,7 @@ final class SparkManager: ChannelFreeLightningRail { await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) } Self.pendingContactWithdrawal = nil + Self.resolveContactWithdrawal(pending, txId: txId) } else { Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") } @@ -679,6 +689,13 @@ final class SparkManager: ChannelFreeLightningRail { await failAllowance(request) } pendingContactWithdrawal = nil + resolveContactWithdrawal(pending, txId: nil) + } + + static func resolveContactWithdrawal(_ pending: SparkContactWithdrawal, txId: String?) { + let resolution = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: txId) + lastContactWithdrawalResolution = resolution + contactWithdrawalResolutionSubject.send(resolution) } private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> Bool { @@ -1225,6 +1242,25 @@ struct SparkContactWithdrawal: Codable, Equatable { var paymentId: String? } +/// One contact withdrawal, which a pending send screen follows until its journal closes. +struct SparkWithdrawalAttempt: Hashable { + let address: String + let amountSats: UInt64 + let requestId: PaykitPaymentRequest.ID? +} + +/// How a contact withdrawal's journal closed: sent with its txid, or never sent when `txId` is nil. +struct SparkContactWithdrawalResolution: Equatable { + let attempt: SparkWithdrawalAttempt + let txId: String? +} + +extension SparkContactWithdrawal { + var attempt: SparkWithdrawalAttempt { + SparkWithdrawalAttempt(address: address, amountSats: amountSats, requestId: request?.id) + } +} + struct SparkWithdrawal: Identifiable, Equatable { let txid: String let amountSats: UInt64 diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 60a270956f..e6f4eb617e 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1464,11 +1464,11 @@ struct SendConfirmationView: View { /// other failure may have sent it, so it stays pending until Spark's journal settles it. static func serviceLegFailureRoute( _ error: Error, - requestId: PaykitPaymentRequest.ID?, + attempt: SparkWithdrawalAttempt, routingCacheResetAttempted: Bool ) -> SendRoute { guard let refusal = error as? SparkWithdrawalNotSent else { - return .pending(paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: requestId) + return .sparkWithdrawalPending(attempt) } return .failure(SendFailureContext( error: refusal.underlying, @@ -1564,7 +1564,7 @@ struct SendConfirmationView: View { Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") navigationPath.append(Self.serviceLegFailureRoute( error, - requestId: request?.id, + attempt: SparkWithdrawalAttempt(address: leg.endpoint.value, amountSats: leg.deliveredSat, requestId: request?.id), routingCacheResetAttempted: routingCacheResetAttempted )) return diff --git a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift index 3e80b63745..1518692ece 100644 --- a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift +++ b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift @@ -38,6 +38,8 @@ struct SendPendingScreen: View { var hardwareWalletId: String? var hardwareTransactionId: String? var hardwarePaymentIdentity: String? + /// The Spark withdrawal this screen waits on, whose journal settles it. + var sparkWithdrawal: SparkWithdrawalAttempt? var proofService: PaykitPaymentProofService = .shared var requestPinCheck: () async -> Bool = { false } @Binding var navigationPath: [SendRoute] @@ -347,6 +349,37 @@ struct SendPendingScreen: View { .onReceive(PaykitPaymentProofService.onchainPaymentResolutionPublisher.receive(on: DispatchQueue.main)) { resolution in applyOnchainPaymentResolution(resolution) } + .onReceive(SparkManager.contactWithdrawalResolutionPublisher.receive(on: DispatchQueue.main)) { resolution in + applySparkWithdrawalResolution(resolution) + } + .task { + // The journal may have closed before this screen subscribed. + guard let attempt = sparkWithdrawal, SparkManager.pendingContactWithdrawal?.attempt != attempt, + let resolution = SparkManager.lastContactWithdrawalResolution + else { return } + applySparkWithdrawalResolution(resolution) + } + } + + private func applySparkWithdrawalResolution(_ resolution: SparkContactWithdrawalResolution) { + guard !ordinarySendResolved, let attempt = sparkWithdrawal, + let route = Self.sparkWithdrawalRoute(for: resolution, attempt: attempt) + else { return } + ordinarySendResolved = true + navigationPath.append(route) + } + + /// Where the journal's close takes the screen waiting on `attempt`: a success once Spark sent it, a failure that can + /// be tried again once it never did, and nowhere for another withdrawal. + static func sparkWithdrawalRoute(for resolution: SparkContactWithdrawalResolution, attempt: SparkWithdrawalAttempt) -> SendRoute? { + guard resolution.attempt == attempt else { return nil } + if let txId = resolution.txId { + return .success(paymentId: txId) + } + return .failure(SendFailureContext( + error: AppError(message: "wallet__payment_failed_description", debugMessage: "Spark never sent the contact withdrawal"), + retryRoute: .confirm + )) } @MainActor diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 7eacef40fe..4b73c7763f 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -69,6 +69,7 @@ enum SendRoute: Hashable { paykitPaymentRequestId: PaykitPaymentRequest.ID? = nil ) case onchainPending(OnchainSendPendingContext) + case sparkWithdrawalPending(SparkWithdrawalAttempt) case onchainOperationPending(OnchainSendPendingContext, requestId: PaykitPaymentRequest.ID?) case hardwarePending(requestId: PaykitPaymentRequest.ID, walletId: String, transactionId: String, paymentIdentity: String?) case success(paymentId: String, walletId: String = WalletScope.default) @@ -1171,6 +1172,12 @@ struct SendSheet: View { routingCacheResetAttempted: flow.routingCacheResetAttempted, navigationPath: $flow.navigationPath ) + case let .sparkWithdrawalPending(attempt): + SendPendingScreen( + paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: attempt.requestId, + routingCacheResetAttempted: flow.routingCacheResetAttempted, sparkWithdrawal: attempt, + navigationPath: $flow.navigationPath + ) case let .onchainPending(context): SendPendingScreen( paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: nil, diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index aa49589c99..2958039c97 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -292,6 +292,38 @@ final class PaykitRouteTests: XCTestCase { } } + @MainActor + func testAClosedJournalTellsThePendingScreenHowItsWithdrawalEnded() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + SparkManager.pendingContactWithdrawal = pending + var resolutions: [SparkContactWithdrawalResolution] = [] + let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } + defer { subscription.cancel() } + + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in true }, failAllowance: { _ in }) + + let unsent = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: nil) + XCTAssertEqual(resolutions, [unsent]) + XCTAssertEqual(SparkManager.lastContactWithdrawalResolution, unsent, "A screen that opens later still learns it") + guard case .failure = SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: pending.attempt) else { + return XCTFail("A withdrawal that never went out can be tried again") + } + XCTAssertEqual( + SendPendingScreen.sparkWithdrawalRoute( + for: SparkContactWithdrawalResolution(attempt: pending.attempt, txId: "txid"), + attempt: pending.attempt + ), + .success(paymentId: "txid") + ) + let other = SparkWithdrawalAttempt(address: onchain.value, amountSats: 30000, requestId: request.id) + XCTAssertNil(SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: other), "Another withdrawal's close leaves the screen") + } + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { var steps: [String] = [] let identity = try await PaykitRouteService.startLegRequestProof( diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index a4e4856920..8c938d5c5a 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -193,18 +193,22 @@ final class SendConfirmationViewTests: XCTestCase { func testASparkLegThatMayHaveSentStaysPendingInsteadOfOfferingTryAgain() { struct Refused: Error {} struct Lost: Error {} - let requestId = PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee") + let attempt = SparkWithdrawalAttempt( + address: "bcrt1qcontact", + amountSats: 20000, + requestId: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee") + ) - let unresolved = SendConfirmationView.serviceLegFailureRoute(Lost(), requestId: requestId, routingCacheResetAttempted: false) + let unresolved = SendConfirmationView.serviceLegFailureRoute(Lost(), attempt: attempt, routingCacheResetAttempted: false) XCTAssertEqual( unresolved, - .pending(paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: requestId), - "Spark may have sent it, so the request stays pending until the journal settles" + .sparkWithdrawalPending(attempt), + "Spark may have sent it, so the screen follows its journal until it settles" ) let refused = SendConfirmationView.serviceLegFailureRoute( SparkWithdrawalNotSent(underlying: Refused()), - requestId: requestId, + attempt: attempt, routingCacheResetAttempted: false ) guard case .failure = refused else { return XCTFail("A leg Spark refused before sending can be tried again") } From 97280c2ac2e396d528c0894bad38bb319df0a5d9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:06:09 +0100 Subject: [PATCH 25/64] fix: keep a pending spark send off the node's on-chain attempts --- .../Wallets/Send/SendPendingScreen.swift | 22 +++++++++++++++---- BitkitTests/PaykitRouteTests.swift | 11 ++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift index 1518692ece..967f130b6a 100644 --- a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift +++ b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift @@ -109,7 +109,10 @@ struct SendPendingScreen: View { } private var pendingAmountSats: UInt64? { - pendingHardwareWalletId == nil ? onchainAttempt?.amountSats ?? pendingOnchainProof?.onchainAmountSats ?? wallet + if let sparkWithdrawal { + return sparkWithdrawal.amountSats + } + return pendingHardwareWalletId == nil ? onchainAttempt?.amountSats ?? pendingOnchainProof?.onchainAmountSats ?? wallet .sendAmountSats : pendingOnchainProof?.onchainAmountSats } @@ -281,7 +284,7 @@ struct SendPendingScreen: View { { applyOnchainPaymentResolution(resolution) } - } else if !onchainStateUnavailable { + } else if !onchainStateUnavailable, Self.readsNodeOnchainAttempts(sparkWithdrawal: sparkWithdrawal) { do { let loaded = try await Self.loadOrdinaryPending( using: attemptService, context: ordinaryPendingContext, @@ -318,7 +321,7 @@ struct SendPendingScreen: View { await searchForActivity() // Completion events are one-shot. Keep the visible original operation in sync // with its durable result even when an event preceded subscription or initialization. - while paymentHash == nil, paykitPaymentRequestId == nil, pendingHardwareWalletId == nil, + while paymentHash == nil, paykitPaymentRequestId == nil, pendingHardwareWalletId == nil, sparkWithdrawal == nil, !ordinarySendResolved, !Task.isCancelled { do { try await Task.sleep(for: .seconds(2)) } @@ -328,7 +331,9 @@ struct SendPendingScreen: View { } .task { // The request can end, or a failed check recover, while this screen stays open. - while paymentHash == nil, abandonableAttempt == nil, !Task.isCancelled { + while paymentHash == nil, abandonableAttempt == nil, Self.readsNodeOnchainAttempts(sparkWithdrawal: sparkWithdrawal), + !Task.isCancelled + { if pendingHardwareWalletId == nil { guard await loadAbandonableAttempt() else { return } } @@ -369,6 +374,12 @@ struct SendPendingScreen: View { navigationPath.append(route) } + /// Whether the screen reads the node wallet's on-chain send attempts: never for a Spark withdrawal, which creates + /// none, so an unrelated unresolved send never shows as this one; its journal settles it instead. + static func readsNodeOnchainAttempts(sparkWithdrawal: SparkWithdrawalAttempt?) -> Bool { + sparkWithdrawal == nil + } + /// Where the journal's close takes the screen waiting on `attempt`: a success once Spark sent it, a failure that can /// be tried again once it never did, and nowhere for another withdrawal. static func sparkWithdrawalRoute(for resolution: SparkContactWithdrawalResolution, attempt: SparkWithdrawalAttempt) -> SendRoute? { @@ -575,6 +586,9 @@ struct SendPendingScreen: View { } private var onchainPendingMessage: String { + if sparkWithdrawal != nil { + return t("wallet__onchain_unknown_pending") + } if onchainStateUnavailable { return t("wallet__onchain_state_unavailable") } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 2958039c97..52b06e11ea 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -324,6 +324,17 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: other), "Another withdrawal's close leaves the screen") } + @MainActor + func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { + let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) + + XCTAssertFalse( + SendPendingScreen.readsNodeOnchainAttempts(sparkWithdrawal: attempt), + "A Spark withdrawal never creates a node on-chain attempt, so an unrelated one must not show as this send" + ) + XCTAssertTrue(SendPendingScreen.readsNodeOnchainAttempts(sparkWithdrawal: nil)) + } + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { var steps: [String] = [] let identity = try await PaykitRouteService.startLegRequestProof( From 3a310c4fa9ad38f4d0e0aa2f16d533966a498f47 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:22:28 +0100 Subject: [PATCH 26/64] fix: write the spark journal before its request proof starts --- Bitkit/Managers/SparkManager.swift | 31 +++++++++-- Bitkit/Services/PaykitRouteService.swift | 12 ++--- .../Wallets/Send/SendConfirmationView.swift | 53 +++++++++++-------- BitkitTests/PaykitRouteTests.swift | 36 ++++++++++--- 4 files changed, 93 insertions(+), 39 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 51f367de6e..62e8405146 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -537,7 +537,6 @@ final class SparkManager: ChannelFreeLightningRail { // Withdrawals Spark already lists for this address and amount belong to earlier attempts, so recovery never // takes one of them for this attempt. earlierPayments = try await sdk.listPayments(request: ListPaymentsRequest(sortAscending: false)).payments - try await beforeSend() } catch { throw SparkWithdrawalNotSent(underlying: error) } @@ -550,10 +549,19 @@ final class SparkManager: ChannelFreeLightningRail { tags: tags, earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments) ) - Self.pendingContactWithdrawal = pending - Self.lastContactWithdrawalResolution = nil isWithdrawingToContact = true defer { isWithdrawingToContact = false } + let journaled = pending + try await Self.startJournaledWithdrawal( + writeJournal: { + Self.pendingContactWithdrawal = journaled + Self.lastContactWithdrawalResolution = nil + }, + beforeSend: beforeSend, + closeUnsent: { + await Self.closeUnsentWithdrawal(journaled, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + } + ) let response: SendPaymentResponse do { response = try await sdk.sendPayment(request: SendPaymentRequest( @@ -610,6 +618,23 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// Writes the attempt's journal before `beforeSend` starts the request's proof, so a kill between the two leaves a + /// journal that recovery closes as unsent once it expires, releasing the proof; a refusal in `beforeSend` closes it + /// at once, releasing what it started. + static func startJournaledWithdrawal( + writeJournal: () -> Void, + beforeSend: () async throws -> Void, + closeUnsent: () async -> Void + ) async throws { + writeJournal() + do { + try await beforeSend() + } catch { + await closeUnsent() + throw SparkWithdrawalNotSent(underlying: error) + } + } + nonisolated static let contactWithdrawalExpirySecs: UInt64 = 600 /// An attempt Spark never returned nor listed is taken as unsent only after the expiry. diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index c8b33dfd11..aa05e71fda 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -149,14 +149,14 @@ enum PaykitRouteService { error is SparkWithdrawalNotSent && openJournalRequest != proofRequest } - /// Starts the on-chain proof of a request a Spark leg pays, in a direct send's order: the proof is prepared, then the - /// request (its checks and private list consumption), then the proof is marked started. Any failure releases the - /// private payment list as unsent, and one after the proof was prepared cancels it, so the request can be paid again. + /// Prepares the on-chain proof of a request a Spark leg pays, in a direct send's order: the proof is prepared, then + /// the request (its checks and private list consumption). Spark's withdrawal marks the proof started once its journal + /// is written. Any failure releases the private payment list as unsent, and one after the proof was prepared cancels + /// it, so the request can be paid again. static func startLegRequestProof( prepareProof: () async throws -> Void, prepareRequest: () async throws -> Void, paymentIdentity: () async throws -> String, - markStarted: (String) async throws -> Void, cancelProof: () async -> Void, releasePaymentList: () async -> Void ) async throws -> String { @@ -168,9 +168,7 @@ enum PaykitRouteService { } do { try await prepareRequest() - let identity = try await paymentIdentity() - try await markStarted(identity) - return identity + return try await paymentIdentity() } catch { await cancelProof() await releasePaymentList() diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index e6f4eb617e..44d3df6bc8 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1488,6 +1488,7 @@ struct SendConfirmationView: View { let context = app.contactPaymentContext let request = context?.incomingPaymentRequest var proofRequest: SparkContactWithdrawal.PaykitRequest? + var markProofStarted: (() async throws -> Void)? do { if let request { guard let privateContext = context?.privatePaymentContext else { throw PaykitPaymentRequestError.requestUnavailable } @@ -1503,24 +1504,25 @@ struct SendConfirmationView: View { }, prepareRequest: { try await prepareIncomingPaymentRequest() }, paymentIdentity: { try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) }, - markStarted: { identity in - // The proof keeps the list version this send consumed, so dropping it as unsent gives the list back. - let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( - publicKey: request.counterparty, - attemptId: context?.id - ) - try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( - request, - address: leg.endpoint.value, - paymentIdentity: identity, - privatePaymentListVersion: privateContext.paymentListVersion, - previousPrivatePaymentListVersion: previousVersion - ) - }, cancelProof: { await PaykitPaymentProofService.shared.cancelPreparation(request) }, releasePaymentList: { await context?.resolvePrivatePaymentListConsumption(.definitePreBroadcastFailure) } ) proofRequest = SparkContactWithdrawal.PaykitRequest(id: request.id, identity: identity) + // Spark's withdrawal runs this once its journal is written, so recovery owns the started proof. + markProofStarted = { + // The proof keeps the list version this send consumed, so dropping it as unsent gives the list back. + let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( + publicKey: request.counterparty, + attemptId: context?.id + ) + try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( + request, + address: leg.endpoint.value, + paymentIdentity: identity, + privatePaymentListVersion: privateContext.paymentListVersion, + previousPrivatePaymentListVersion: previousVersion + ) + } } let txid: String do { @@ -1542,13 +1544,18 @@ struct SendConfirmationView: View { await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: $0, outcome: $1, transactionId: $2) } ) { beforeSend in - try await PaykitRouteService.pay( - leg, - contact: context?.publicKey, - request: proofRequest, - tags: tagManager.selectedTagsArray, - beforeSend: beforeSend - ) + try await withoutActuallyEscaping(beforeSend) { beforeSend in + try await PaykitRouteService.pay( + leg, + contact: context?.publicKey, + request: proofRequest, + tags: tagManager.selectedTagsArray, + beforeSend: { + try await markProofStarted?() + try await beforeSend() + } + ) + } } } catch { // Refused before Spark's send: nothing left, so this call's started proof goes. After it, the journal settles it. @@ -1560,6 +1567,10 @@ struct SendConfirmationView: View { ) { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: proofRequest.id, identity: proofRequest.identity) } + if refusedBeforeSend, let request { + // A refusal before the proof was marked started leaves it prepared; started proofs stay as they are. + await PaykitPaymentProofService.shared.cancelPreparation(request) + } await context?.resolvePrivatePaymentListConsumption(refusedBeforeSend ? .definitePreBroadcastFailure : .uncertain) Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") navigationPath.append(Self.serviceLegFailureRoute( diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 52b06e11ea..1fc44b7141 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -324,6 +324,32 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: other), "Another withdrawal's close leaves the screen") } + @MainActor + func testAWithdrawalsJournalIsWrittenBeforeItsProofStarts() async { + struct Refused: Error {} + var steps: [String] = [] + + try? await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { steps.append("proof started") }, + closeUnsent: { steps.append("closed") } + ) + XCTAssertEqual(steps, ["journal", "proof started"], "A kill after the proof starts leaves a journal that releases it") + + steps = [] + do { + try await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { steps.append("proof started"); throw Refused() }, + closeUnsent: { steps.append("closed") } + ) + XCTFail("A refusal before the send must reach the caller") + } catch { + XCTAssertTrue(error is SparkWithdrawalNotSent) + } + XCTAssertEqual(steps, ["journal", "proof started", "closed"], "A refusal closes the journal, releasing what it started") + } + @MainActor func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) @@ -341,18 +367,17 @@ final class PaykitRouteTests: XCTestCase { prepareProof: { steps.append("proof") }, prepareRequest: { steps.append("request") }, paymentIdentity: { steps.append("identity"); return "payer" }, - markStarted: { steps.append("started \($0)") }, cancelProof: { steps.append("cancel") }, releasePaymentList: { steps.append("release") } ) XCTAssertEqual(identity, "payer") - XCTAssertEqual(steps, ["proof", "request", "identity", "started payer"], "The request is approved before Spark's payment check") + XCTAssertEqual(steps, ["proof", "request", "identity"], "The request is approved before Spark's payment check") } func testLegThatFailsBeforeSendingFreesTheRequest() async { struct Refused: Error {} - for failing in ["proof", "request", "started"] { + for failing in ["proof", "request"] { var steps: [String] = [] do { _ = try await PaykitRouteService.startLegRequestProof( @@ -367,11 +392,6 @@ final class PaykitRouteTests: XCTestCase { } }, paymentIdentity: { "payer" }, - markStarted: { - _ in if failing == "started" { - throw Refused() - } - }, cancelProof: { steps.append("cancel") }, releasePaymentList: { steps.append("release") } ) From 609be769879d846f18eb9dcd3df7c46366909683 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:33:45 +0100 Subject: [PATCH 27/64] fix: drop a paykit route that returns after its payment changed --- Bitkit/Services/PaykitRouteService.swift | 19 +++++++----- .../Views/Wallets/Send/SendAmountView.swift | 2 +- .../Wallets/Send/SendConfirmationView.swift | 3 ++ BitkitTests/PaykitRouteTests.swift | 29 +++++++++++++++++++ 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index aa05e71fda..e37100db7f 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -237,6 +237,8 @@ enum PaykitRouteOutcome: Equatable { case leg /// No route pays the contact; the app's copy says why. case refused + /// The payment changed while the router answered, so its answer was dropped. + case stale } @MainActor @@ -250,18 +252,18 @@ extension AppViewModel { source: PaykitRouteService.Source, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64, - request: PaykitPaymentRequest? + request: PaykitPaymentRequest?, + router: (PaykitRouteUi, UInt64, PaykitRouteService.Source, UInt64, UInt64) async throws -> PaykitRoute = PaykitRouteService.route ) async -> PaykitRouteOutcome { var unrouted = route unrouted.serviceLeg = nil + let contactId = contactPaymentContext?.id do { - let picked = try await PaykitRouteService.route( - route, - amountSats: amountSats, - source: source, - lightningSpendableSats: lightningSpendableSats, - onchainSpendableSats: onchainSpendableSats - ) + let picked = try await router(route, amountSats, source, lightningSpendableSats, onchainSpendableSats) + // A dismissed or replaced payment's route must never land on the one that followed it. + guard contactPaymentContext?.id == contactId, paykitRoute.map({ $0.endpoints == route.endpoints }) ?? true else { + return .stale + } switch picked { case let .direct(endpoint): paykitRoute = unrouted @@ -288,6 +290,7 @@ extension AppViewModel { } } catch { Logger.error("Failed to route Paykit payment: \(error)", context: "PaykitRoute") + guard contactPaymentContext?.id == contactId else { return .stale } showNoPaykitRouteToast(isBalanceShort: false) return .refused } diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index 9577b8d39c..dddfa14d87 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -398,7 +398,7 @@ struct SendAmountView: View { case .leg: navigationPath.append(.confirm) return - case .refused: + case .refused, .stale: return case .direct: break diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 44d3df6bc8..7e66f328c3 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1446,6 +1446,9 @@ struct SendConfirmationView: View { if outcome == .refused { return walletType } + if outcome == .stale { + return previous + } return previous == walletType ? nil : previous } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 1fc44b7141..85843d5baa 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -350,6 +350,35 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(steps, ["journal", "proof started", "closed"], "A refusal closes the journal, releasing what it started") } + @MainActor + func testARouteThatReturnsAfterItsPaymentChangedNeverLandsOnTheNextOne() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let contactA = ContactPaymentContext(publicKey: "contacta", privatePaymentContext: nil, endpoints: []) + let contactB = ContactPaymentContext(publicKey: "contactb", privatePaymentContext: nil, endpoints: []) + let routeA = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + let routeB = PaykitRouteUi(endpoints: [lightning], offersSparkLeg: false) + app.contactPaymentContext = contactA + app.paykitRoute = routeA + + let outcome = await app.routeContactPayment( + routeA, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // Contact A's sheet is dismissed and contact B's opens while Spark quotes A's leg. + app.contactPaymentContext = contactB + app.paykitRoute = routeB + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(outcome, .stale) + XCTAssertEqual(app.paykitRoute, routeB, "contact A's leg must never pay contact B") + } + @MainActor func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) From 11f743369ec835537297d0ef3cdcd9605aa65813 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:33:47 +0100 Subject: [PATCH 28/64] test: run the spending confirm check on the main actor --- BitkitTests/SparkFundingRecoveryTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/BitkitTests/SparkFundingRecoveryTests.swift b/BitkitTests/SparkFundingRecoveryTests.swift index 7db08162c6..45f6930f55 100644 --- a/BitkitTests/SparkFundingRecoveryTests.swift +++ b/BitkitTests/SparkFundingRecoveryTests.swift @@ -41,6 +41,7 @@ final class SparkFundingRecoveryTests: XCTestCase { XCTAssertEqual(handedOff, 0) } + @MainActor func testSpendingConfirmLeavesOnceItsFundingResolvesOnItsOwn() async throws { let spark = try await resolvedSend(isSparkFunding: true, txid: String(repeating: "7c", count: 32)) let ordinary = try await resolvedSend(isSparkFunding: false, txid: String(repeating: "8d", count: 32)) From d20530ec05f3045cd8f9ce54f86e1faa56367ece Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:38:54 +0100 Subject: [PATCH 29/64] fix: keep an unselected lnurl's price and minimum off a spark leg --- Bitkit/ViewModels/AppViewModel.swift | 4 +++ .../Wallets/Send/SendConfirmationView.swift | 3 +- Bitkit/Views/Wallets/Send/SendSheet.swift | 2 +- .../SendConfirmationLifecycleTests.swift | 28 +++++++++++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 8699d04dcd..07fad3d563 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -764,6 +764,10 @@ extension AppViewModel { /// endpoint, so it takes that endpoint's price, the one the leg and its proof pay. func paykitBitcoinMethod(for wallet: WalletType) -> PublicPaykitService.MethodId { if wallet == .lightning { + // A routed Spark leg pays its on-chain endpoint, whatever Lightning endpoint the contact also has. + if let leg = paykitRoute?.serviceLeg, let method = PublicPaykitService.MethodId(rawValue: leg.endpoint.methodId) { + return method + } if lnurlPayData != nil { return .bitcoinLightningLnurl } diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 7e66f328c3..252f68a7bf 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -2182,7 +2182,8 @@ struct SendConfirmationView: View { } guard request.pricing.conversion != nil else { return false } let terms = try? request.payment(using: app.paykitPaymentMethod, quoteId: app.paykitPaymentTerms?.quoteId) - let minimumAmount = app.selectedWalletToPayFrom == .lightning ? (app.lnurlPayData?.minSendableSat ?? 1) : UInt64(Env.dustLimit) + let paysLightning = app.selectedWalletToPayFrom == .lightning && app.paykitRoute?.serviceLeg == nil + let minimumAmount = paysLightning ? (app.lnurlPayData?.minSendableSat ?? 1) : UInt64(Env.dustLimit) let meetsMinimum = terms.map { $0.amount.atomic >= minimumAmount } == true if rebindMethod, !app.paykitUsesUsdt, !isSubmittingPayment, let previous = app.paykitPaymentTerms, previous.amount.asset == .btc, app.paykitReviewedAmount == previous.amount, diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 4b73c7763f..a89e8925ac 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -768,7 +768,7 @@ struct SendSheet: View { return .failed } - if let lnurlPayData = app.lnurlPayData, let requestedAmount { + if let lnurlPayData = app.lnurlPayData, app.paykitRoute?.serviceLeg == nil, let requestedAmount { let minimumAmount = max(1, lnurlPayData.minSendableSat) guard requestedAmount >= minimumAmount else { showPaymentSetupFailure( diff --git a/BitkitTests/SendConfirmationLifecycleTests.swift b/BitkitTests/SendConfirmationLifecycleTests.swift index dc6b645b0e..bf736eeca6 100644 --- a/BitkitTests/SendConfirmationLifecycleTests.swift +++ b/BitkitTests/SendConfirmationLifecycleTests.swift @@ -45,6 +45,34 @@ final class SendConfirmationLifecycleTests: XCTestCase { XCTAssertEqual(try request.payment(using: app.paykitPaymentMethod), onchainTerms) } + func testASparkLegIgnoresTheUnselectedLnurlsPrice() throws { + snapshotAppDefaultsDomain() + let request = try onchainRequest(acceptsLightning: true, rates: [ + ConversionRate(asset: "btc", value: "0.000002188"), + ConversionRate(asset: "btc-lightning", value: "0.00002"), + ]) + let app = AppViewModel() + app.scannedOnchainInvoice = invoice + let onchainTerms = try request.payment(using: app.paykitPaymentMethod) + let endpoint = PaykitEndpoint(methodId: PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue, value: invoice.address) + app.lnurlPayData = LnurlPayData( + uri: "lnurl1contact", callback: "https://example.com/callback", minSendable: 5_000_000, maxSendable: 100_000_000, + metadataStr: "[]", commentAllowed: nil, allowsNostr: false, nostrPubkey: nil + ) + app.paykitRoute = PaykitRouteUi( + endpoints: [endpoint], + offersSparkLeg: true, + serviceLeg: ServiceRouteLeg( + service: SparkManager.routeService, endpoint: endpoint, deliveredSat: 5000, debitSat: 5300, + atomicity: "trusted", validUntilUnix: 0 + ) + ) + + app.selectedWalletToPayFrom = .lightning + + XCTAssertEqual(try request.payment(using: app.paykitPaymentMethod), onchainTerms, "The leg pays the on-chain endpoint") + } + func testQuotedWalletSwitchRebindsAmountOnConfirmation() async throws { snapshotAppDefaultsDomain() snapshotAppGroupDefaults("home_screen_display_currency_code_v1", "home_screen_display_currency_symbol_v1") From 921c3f8c00865f227224e084fce6e6c2393618c6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:55:58 +0100 Subject: [PATCH 30/64] fix: close only a spark journal's own proof and allowance attempt --- Bitkit/Managers/SparkManager.swift | 13 ++++-- .../Services/PaykitPaymentProofService.swift | 42 +++++++++++++------ .../Wallets/Send/SendConfirmationView.swift | 3 +- .../PaykitPaymentProofServiceTests.swift | 30 +++++++++---- BitkitTests/PaykitRouteTests.swift | 13 ++++-- 5 files changed, 74 insertions(+), 27 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 1d4dc415fa..80a754cc28 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -713,15 +713,20 @@ final class SparkManager: ChannelFreeLightningRail { /// allowance attempt, left unknown when the send's outcome was, then fails, so the ledger lets it be paid again. static func closeUnsentWithdrawal( _ pending: SparkContactWithdrawal, - releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> Bool, + releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease, failAllowance: (SparkContactWithdrawal.PaykitRequest) async -> Void ) async { if let request = pending.request { - guard await releaseProof(request) else { + switch await releaseProof(request) { + case .failed: Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") return + case .released: + // The allowance attempt begins only once the proof started, so only then is there one to fail. + await failAllowance(request) + case .nothingStarted: + break } - await failAllowance(request) } pendingContactWithdrawal = nil resolveContactWithdrawal(pending, txId: nil) @@ -733,7 +738,7 @@ final class SparkManager: ChannelFreeLightningRail { contactWithdrawalResolutionSubject.send(resolution) } - private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> Bool { + private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease { await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) } diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index d816e93e4c..99f04a2876 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -76,6 +76,8 @@ struct PendingPaykitPaymentProof: Codable, Equatable { var onchainLocalFollowupComplete: Bool? /// Retain the bounded original proof until its payer consumes the local resolution. var onchainResolutionAwaitingConsumption: Bool? = false + /// A Spark withdrawal pays this proof, so only that withdrawal's journal may complete or drop it. + var sparkWithdrawal: Bool? var hasUnsupportedOnchainWallet: Bool { kind == .onchain && onchainWalletId != nil && onchainWalletId != WalletScope.default @@ -818,7 +820,8 @@ actor PaykitPaymentProofService { paymentIdentity: String? = nil, signedTx: HwFundingSignedTx? = nil, privatePaymentListVersion: UInt64? = nil, - previousPrivatePaymentListVersion: UInt64? = nil + previousPrivatePaymentListVersion: UInt64? = nil, + sparkWithdrawal: Bool = false ) async throws { let identity = try await currentIdentity() try await mutationLock.withLock { @@ -831,7 +834,8 @@ actor PaykitPaymentProofService { serializedTx: signedTx?.serializedTx, signedTx: signedTx, privatePaymentListVersion: privatePaymentListVersion, - previousPrivatePaymentListVersion: previousPrivatePaymentListVersion + previousPrivatePaymentListVersion: previousPrivatePaymentListVersion, + sparkWithdrawal: sparkWithdrawal ) } } @@ -845,7 +849,8 @@ actor PaykitPaymentProofService { serializedTx: String?, signedTx: HwFundingSignedTx?, privatePaymentListVersion: UInt64?, - previousPrivatePaymentListVersion: UInt64? + previousPrivatePaymentListVersion: UInt64?, + sparkWithdrawal: Bool = false ) async throws { if let hardwareWalletId { guard hardwareWalletId != WalletScope.default, hardwareTransactionLookup.hasWallet(walletId: hardwareWalletId) @@ -887,6 +892,7 @@ actor PaykitPaymentProofService { pendingProofs[index].hardwareDispatchAttempted = signedTx.map { _ in false } pendingProofs[index].privatePaymentListVersion = privatePaymentListVersion pendingProofs[index].previousPrivatePaymentListVersion = privatePaymentListVersion == nil ? nil : previousPrivatePaymentListVersion + pendingProofs[index].sparkWithdrawal = sparkWithdrawal ? true : nil try await persist(pendingProofs) } @@ -1338,7 +1344,7 @@ actor PaykitPaymentProofService { var proofs = try await loadProofs() guard let index = proofs.lastIndex(where: { PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && - $0.paymentStarted && $0.onchainWalletId == nil && + $0.paymentStarted && $0.onchainWalletId == nil && $0.sparkWithdrawal == true && ($0.paymentIdentifier == nil || $0.paymentIdentifier?.caseInsensitiveCompare(txid) == .orderedSame) }) else { return nil } proofs[index].paymentIdentifier = txid.lowercased() @@ -1360,22 +1366,24 @@ actor PaykitPaymentProofService { } /// Drops the started on-chain proof of a request whose Spark withdrawal never went out, giving back the private list - /// version it consumed when the contact's list is still at exactly that version. False when the proof could not be - /// dropped, so the withdrawal's journal stays open for a retry. + /// version it consumed when the contact's list is still at exactly that version. Only a proof the withdrawal started + /// goes, never a direct on-chain send's for the same request. `.failed` when it could not be dropped, so the + /// withdrawal's journal stays open for a retry. @discardableResult func failSparkOnchainPayment( requestId: PaykitPaymentRequest.ID, identity: String, privatePaykitService: PrivatePaykitService = .shared - ) async -> Bool { + ) async -> SparkProofRelease { do { - try await mutationLock.withLock { + return try await mutationLock.withLock { let proofs = try await loadProofs() let unsent = proofs.filter { PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && - $0.paymentStarted && $0.onchainWalletId == nil && $0.paymentIdentifier == nil && $0.proofData == nil + $0.paymentStarted && $0.onchainWalletId == nil && $0.sparkWithdrawal == true && + $0.paymentIdentifier == nil && $0.proofData == nil } - guard !unsent.isEmpty else { return } + guard !unsent.isEmpty else { return .nothingStarted } for proof in unsent { guard let version = proof.privatePaymentListVersion else { continue } try await privatePaykitService.releaseUnsentPaymentListVersion( @@ -1393,11 +1401,11 @@ actor PaykitPaymentProofService { } throw error } + return .released } - return true } catch { logWarning("Failed to clear an unsent Spark on-chain proof: \(error)") - return false + return .failed } } @@ -2032,3 +2040,13 @@ actor PaykitPaymentProofService { } } } + +/// What dropping a Spark withdrawal's started proof did. +enum SparkProofRelease: Equatable { + /// The withdrawal's started proof is gone. + case released + /// The withdrawal never started a proof: a kill came before it, or a direct send owns the request's proof. + case nothingStarted + /// The proof could not be dropped, so it stays for a retry. + case failed +} diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 252f68a7bf..7172ae410a 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1523,7 +1523,8 @@ struct SendConfirmationView: View { address: leg.endpoint.value, paymentIdentity: identity, privatePaymentListVersion: privateContext.paymentListVersion, - previousPrivatePaymentListVersion: previousVersion + previousPrivatePaymentListVersion: previousVersion, + sparkWithdrawal: true ) } } diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 9c170c3e74..f4ad72c03a 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1894,7 +1894,7 @@ final class PaykitPaymentProofServiceTests: XCTestCase { let txid = String(repeating: "cd", count: 32) try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) - try await service.markOnchainPaymentStarted(request, address: onchainAddress) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) let completed = await service.completeSparkOnchainPayment(requestId: request.id, identity: identity, txid: txid) await sdk.waitForSubmissionStart() await fulfillment(of: [proofRemoved], timeout: 1) @@ -1919,30 +1919,46 @@ final class PaykitPaymentProofServiceTests: XCTestCase { let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) - try await service.markOnchainPaymentStarted(request, address: onchainAddress) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) await service.failSparkOnchainPayment(requestId: request.id, identity: identity) let remaining = await store.snapshot() XCTAssertTrue(remaining.isEmpty) } - func testAnUnsentSparkWithdrawalProofThatCantBeDroppedSaysSo() async throws { + func testClosingASparkJournalLeavesADirectOnchainProofForTheSameRequest() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue let record = try paymentRequestRecord(endpoints: [endpoint]) let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) let store = PaymentProofMemoryStore() let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + // A kill left the Spark journal open with only a prepared proof, and the request was then paid directly. try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) try await service.markOnchainPaymentStarted(request, address: onchainAddress) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + let remaining = await store.snapshot() + XCTAssertEqual(remaining.count, 1, "The direct send's proof is not the Spark withdrawal's to drop") + } + + func testAnUnsentSparkWithdrawalProofThatCantBeDroppedSaysSo() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) await store.failNextSave() let failed = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) - XCTAssertFalse(failed, "The journal stays open only when the caller learns the proof is still there") + XCTAssertEqual(failed, .failed, "The journal stays open only when the caller learns the proof is still there") let remaining = await store.snapshot() XCTAssertEqual(remaining.count, 1) let retried = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) - XCTAssertTrue(retried) + XCTAssertEqual(retried, .released) let afterRetry = await store.snapshot() XCTAssertTrue(afterRetry.isEmpty) } @@ -1962,7 +1978,7 @@ final class PaykitPaymentProofServiceTests: XCTestCase { try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) try await service.markOnchainPaymentStarted( - request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: 6 + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: 6, sparkWithdrawal: true ) // Spark's journal closes the withdrawal as never sent after the app restarted. let relaunched = paymentProofService(sdk: sdk, store: store) @@ -1988,7 +2004,7 @@ final class PaykitPaymentProofServiceTests: XCTestCase { try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) try await service.markOnchainPaymentStarted( - request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: nil + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: nil, sparkWithdrawal: true ) try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 8), attemptId: UUID()) await service.failSparkOnchainPayment(requestId: request.id, identity: identity, privatePaykitService: privatePaykit) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 85843d5baa..7b8a49701a 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -218,19 +218,26 @@ final class PaykitRouteTests: XCTestCase { SparkManager.pendingContactWithdrawal = pending var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] - await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in false }, failAllowance: { failedAllowances.append($0) }) + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .failed }, failAllowance: { failedAllowances.append($0) }) XCTAssertEqual(SparkManager.pendingContactWithdrawal, pending, "A proof that wasn't released keeps the journal, so the next sync retries it") XCTAssertEqual(failedAllowances, [], "The attempt stays unknown while the journal is still open") var released: SparkContactWithdrawal.PaykitRequest? await SparkManager.closeUnsentWithdrawal( pending, - releaseProof: { released = $0; return true }, + releaseProof: { released = $0; return .released }, failAllowance: { failedAllowances.append($0) } ) XCTAssertEqual(released, request) XCTAssertEqual(failedAllowances, [request], "An unsent withdrawal fails its allowance attempt, so the ledger lets the request be paid again") XCTAssertNil(SparkManager.pendingContactWithdrawal) + + // A kill before the proof started leaves no Spark attempt, so a direct send's attempt for the request stays. + SparkManager.pendingContactWithdrawal = pending + failedAllowances = [] + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .nothingStarted }, failAllowance: { failedAllowances.append($0) }) + XCTAssertEqual(failedAllowances, [], "Only the Spark withdrawal's own allowance attempt fails") + XCTAssertNil(SparkManager.pendingContactWithdrawal) } func testLegReportsItsAllowanceAttemptWithTheSendsOutcome() async { @@ -305,7 +312,7 @@ final class PaykitRouteTests: XCTestCase { let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } defer { subscription.cancel() } - await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in true }, failAllowance: { _ in }) + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .released }, failAllowance: { _ in }) let unsent = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: nil) XCTAssertEqual(resolutions, [unsent]) From 2555a90d85b3323cc798191c3d751c8c868fed9c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 20:34:20 +0100 Subject: [PATCH 31/64] fix: give back a request's private list when its spark proof never started --- Bitkit/Managers/SparkManager.swift | 14 +++++++++- .../Services/PaykitPaymentProofService.swift | 13 ++++++++- .../Wallets/Send/SendConfirmationView.swift | 19 +++++++++---- .../PaykitPaymentProofServiceTests.swift | 28 +++++++++++++++++++ 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 80a754cc28..3c546d18c9 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -739,7 +739,11 @@ final class SparkManager: ChannelFreeLightningRail { } private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease { - await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: request.id, identity: request.identity) + await PaykitPaymentProofService.shared.failSparkOnchainPayment( + requestId: request.id, + identity: request.identity, + unstartedPaymentList: request.paymentList + ) } private static func failAllowance(_ request: SparkContactWithdrawal.PaykitRequest) async { @@ -1288,6 +1292,14 @@ struct SparkContactWithdrawal: Codable, Equatable { struct PaykitRequest: Codable, Equatable { let id: PaykitPaymentRequest.ID let identity: String + /// The contact's private list the request consumed, given back when the withdrawal never started its proof. + var paymentList: PaymentList? + } + + /// A private payment list version a send consumed, and the one before it. + struct PaymentList: Codable, Equatable { + let version: UInt64 + let previousVersion: UInt64? } let address: String diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 99f04a2876..f58b515ed7 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1373,6 +1373,7 @@ actor PaykitPaymentProofService { func failSparkOnchainPayment( requestId: PaykitPaymentRequest.ID, identity: String, + unstartedPaymentList: SparkContactWithdrawal.PaymentList? = nil, privatePaykitService: PrivatePaykitService = .shared ) async -> SparkProofRelease { do { @@ -1383,7 +1384,17 @@ actor PaykitPaymentProofService { $0.paymentStarted && $0.onchainWalletId == nil && $0.sparkWithdrawal == true && $0.paymentIdentifier == nil && $0.proofData == nil } - guard !unsent.isEmpty else { return .nothingStarted } + guard !unsent.isEmpty else { + // A kill before the proof started leaves the list the request consumed only in the journal. + if let list = unstartedPaymentList { + try await privatePaykitService.releaseUnsentPaymentListVersion( + publicKey: requestId.counterparty, + version: list.version, + previousVersion: list.previousVersion + ) + } + return .nothingStarted + } for proof in unsent { guard let version = proof.privatePaymentListVersion else { continue } try await privatePaykitService.releaseUnsentPaymentListVersion( diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 7172ae410a..441384f0bc 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1510,14 +1510,21 @@ struct SendConfirmationView: View { cancelProof: { await PaykitPaymentProofService.shared.cancelPreparation(request) }, releasePaymentList: { await context?.resolvePrivatePaymentListConsumption(.definitePreBroadcastFailure) } ) - proofRequest = SparkContactWithdrawal.PaykitRequest(id: request.id, identity: identity) + // The proof and the journal keep the list version this send consumed, so dropping the withdrawal as + // unsent gives the list back, also after a kill before the proof started. + let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( + publicKey: request.counterparty, + attemptId: context?.id + ) + proofRequest = SparkContactWithdrawal.PaykitRequest( + id: request.id, + identity: identity, + paymentList: privateContext.paymentListVersion.map { + SparkContactWithdrawal.PaymentList(version: $0, previousVersion: previousVersion) + } + ) // Spark's withdrawal runs this once its journal is written, so recovery owns the started proof. markProofStarted = { - // The proof keeps the list version this send consumed, so dropping it as unsent gives the list back. - let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( - publicKey: request.counterparty, - attemptId: context?.id - ) try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( request, address: leg.endpoint.value, diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index f4ad72c03a..0a847fb51a 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1991,6 +1991,34 @@ final class PaykitPaymentProofServiceTests: XCTestCase { try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) } + func testAKillBeforeTheSparkProofStartsGivesBackTheListAfterARelaunch() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: sdk, store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 6), attemptId: UUID()) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + + // Killed after the journal was written, before the proof was marked started: only the journal knows the list. + let relaunched = paymentProofService(sdk: sdk, store: store) + let release = await relaunched.failSparkOnchainPayment( + requestId: request.id, + identity: identity, + unstartedPaymentList: SparkContactWithdrawal.PaymentList(version: 7, previousVersion: 6), + privatePaykitService: privatePaykit + ) + + XCTAssertEqual(release, .nothingStarted) + let released = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(released, 6, "The unsent request can be paid from its private list again") + } + func testAnUnsentSparkWithdrawalLeavesAListAnotherPaymentConsumedSince() async throws { snapshotAppDefaultsDomain() UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) From 2a91662a07fdff53117fd654183f0a1285fb9b1b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:16:33 +0100 Subject: [PATCH 32/64] fix: clear a spark withdrawal journal only while it is still open --- Bitkit/Managers/SparkManager.swift | 11 +++++++++-- BitkitTests/PaykitRouteTests.swift | 13 +++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 3c546d18c9..dec5b97a21 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -701,7 +701,7 @@ final class SparkManager: ChannelFreeLightningRail { if let request = pending.request { await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) } - Self.pendingContactWithdrawal = nil + Self.clearJournal(pending) Self.resolveContactWithdrawal(pending, txId: txId) } else { Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") @@ -728,10 +728,17 @@ final class SparkManager: ChannelFreeLightningRail { break } } - pendingContactWithdrawal = nil + clearJournal(pending) resolveContactWithdrawal(pending, txId: nil) } + /// Clears `pending`'s journal only while it is still the open one, so a stale recovery never drops a newer + /// withdrawal's journal, which could then be paid twice. + nonisolated static func clearJournal(_ pending: SparkContactWithdrawal) { + guard pendingContactWithdrawal == pending else { return } + pendingContactWithdrawal = nil + } + static func resolveContactWithdrawal(_ pending: SparkContactWithdrawal, txId: String?) { let resolution = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: txId) lastContactWithdrawalResolution = resolution diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 7b8a49701a..2a7ab02224 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -386,6 +386,19 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(app.paykitRoute, routeB, "contact A's leg must never pay contact B") } + @MainActor + func testAStaleRecoveryNeverClearsANewerWithdrawalsJournal() async { + snapshotAppDefaultsDomain() + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 30000, contact: "contact", startedAt: 2000) + // A recovery captured the older withdrawal; another one closed it and the newer withdrawal wrote its journal. + SparkManager.pendingContactWithdrawal = newer + + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _ in .nothingStarted }, failAllowance: { _ in }) + + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer, "Losing the newer journal could pay it twice") + } + @MainActor func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) From 724ec712066086f26641c0427b3a1dc7c45f36be Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:31:04 +0100 Subject: [PATCH 33/64] chore: log private payment list publication --- Bitkit/Services/PrivatePaykitService+Contacts.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Bitkit/Services/PrivatePaykitService+Contacts.swift b/Bitkit/Services/PrivatePaykitService+Contacts.swift index 3056c4b0e1..6c5433eed8 100644 --- a/Bitkit/Services/PrivatePaykitService+Contacts.swift +++ b/Bitkit/Services/PrivatePaykitService+Contacts.swift @@ -894,10 +894,12 @@ extension PrivatePaykitService { updates.removeAll { !knownSavedContactKeys.contains($0.counterparty) } guard generation == preparationGeneration else { throw PrivatePaykitError.privateUnavailable } guard !updates.isEmpty else { + Logger.debug("Skipped private payment list publication during \(reason): no list changed", context: "PrivatePaykit") schedulePendingPrivateMessageDrainRetries(reason: reason, retryKeys: linkRetryKeys) return } let report = try await operations.syncPaymentLists(updates) + Logger.debug("Published private payment lists to \(updates.count) contacts during \(reason)", context: "PrivatePaykit") let deliveryError = applyPrivatePaymentListDeliveryReport(report, reason: reason) firstError = firstError ?? deliveryError let retryKeys = linkRetryKeys + privatePaymentListDeliveryRetryKeys(from: report) From e7a2492aba5b1f8013925d8b90a08c45c5fe3a42 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:14:58 +0100 Subject: [PATCH 34/64] fix: keep a dismissed payment request from popping up again A rejected or canceled request left the presented set as soon as it left pending, so the sheet opened again whenever a later SDK read listed it as proposed. Declined requests now stay marked while their history entry remains. --- .../PaykitPaymentRequestService.swift | 20 ++++++++++++++++--- .../PaykitPaymentRequestServiceTests.swift | 18 +++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/PaykitPaymentRequestService.swift b/Bitkit/Services/PaykitPaymentRequestService.swift index 27d5f5996d..0834ed1e90 100644 --- a/Bitkit/Services/PaykitPaymentRequestService.swift +++ b/Bitkit/Services/PaykitPaymentRequestService.swift @@ -2053,6 +2053,16 @@ final class PaykitPaymentRequestManager { } } + private static let declinedLifecycleStates: [Paykit.PaymentRequestLifecycleState] = [.rejected, .canceled] + + /// Requests the user declined stay marked as presented while the SDK still lists them, so one never pops up again + /// if a later read reports it as proposed. + private var declinedRequestIds: Set { + Set(historyRequests.filter { + $0.direction == .incoming && Self.declinedLifecycleStates.contains($0.lifecycleState) + }.map(\.id)) + } + func canDismiss(_ request: PaykitPaymentRequest) -> Bool { retainedHardwareRetries[request.id] == nil } @@ -2693,7 +2703,7 @@ final class PaykitPaymentRequestManager { clockOffset: subscriptionClockOffset ) let currentRequestIds = Set(pendingRequests.map(\.id)) - presentedRequestIds.formIntersection(currentRequestIds) + presentedRequestIds.formIntersection(currentRequestIds.union(declinedRequestIds)) presentationRetryAttempts = presentationRetryAttempts.filter { currentRequestIds.contains($0.key) } presentationRetryDeadlines = presentationRetryDeadlines.filter { currentRequestIds.contains($0.key) } automaticPresentationDiagnosticReasons = automaticPresentationDiagnosticReasons.filter { currentRequestIds.contains($0.key) } @@ -2804,7 +2814,11 @@ final class PaykitPaymentRequestManager { historyRequests.removeAll { $0.id == request.id } historyRequests.insert(updatedRequest, at: 0) pendingRequests.removeAll { $0.id == request.id } - presentedRequestIds.remove(request.id) + if Self.declinedLifecycleStates.contains(resultingState) { + presentedRequestIds.insert(request.id) + } else { + presentedRequestIds.remove(request.id) + } presentationRetryAttempts.removeValue(forKey: request.id) presentationRetryDeadlines.removeValue(forKey: request.id) automaticPresentationDiagnosticReasons.removeValue(forKey: request.id) @@ -2877,7 +2891,7 @@ final class PaykitPaymentRequestManager { requestedSubscriptionProposalId = nil } let requestIds = Set(pendingRequests.map(\.id)) - presentedRequestIds.formIntersection(requestIds) + presentedRequestIds.formIntersection(requestIds.union(declinedRequestIds)) presentationRetryAttempts = presentationRetryAttempts.filter { requestIds.contains($0.key) } presentationRetryDeadlines = presentationRetryDeadlines.filter { requestIds.contains($0.key) } automaticPresentationDiagnosticReasons = automaticPresentationDiagnosticReasons.filter { requestIds.contains($0.key) } diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index c1c7f06618..818a020b03 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -7110,6 +7110,24 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { XCTAssertFalse(manager.isApprovedForPayment(request)) } + func testDismissedRequestIsNotPresentedAgainWhenTheSdkListsItAsProposedAgain() async throws { + let sdk = try PaymentRequestSdkMock(records: [paymentRequestRecord()]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.requestsForPresentation().first) + XCTAssertTrue(manager.markPresentedIfPending(request)) + + try await manager.dismiss(request) + try await sdk.setRecords([paymentRequestRecord(state: .rejected)]) + await manager.refresh() + XCTAssertTrue(manager.pendingRequests.isEmpty) + + try await sdk.setRecords([paymentRequestRecord()]) + await manager.refresh() + XCTAssertEqual(manager.pendingRequests.map(\.id), [request.id]) + XCTAssertTrue(manager.requestsForPresentation().isEmpty) + } + func testFailedRejectionDropsRequestRemovedFromAuthoritativeQueue() async throws { let sdk = try PaymentRequestSdkMock(records: [paymentRequestRecord()]) let manager = paymentRequestManager(sdk: sdk) From 2b6bf07302d97ccb3f39e87b0e1954afbd3c5ae4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:25:53 +0100 Subject: [PATCH 35/64] fix: offer spending on confirm while spark can pay an on-chain request Confirm listed Spending only for a scanned Lightning invoice, so an on-chain request that Savings covers could not be switched to Spending and paid through the Spark leg, and one that opened on Spending had no way back to it. It now offers what the amount screen offers. --- .../Wallets/Send/SendConfirmationView.swift | 32 ++++++++++++++----- BitkitTests/PaykitRouteTests.swift | 22 +++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 441384f0bc..06ccfa4aee 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -132,18 +132,34 @@ struct SendConfirmationView: View { } private var fundingSources: [SendFundingSource] { + Self.fundingSources( + hasLightningInvoice: app.scannedLightningInvoice != nil, + hasOnchainInvoice: app.scannedOnchainInvoice != nil, + offersSparkLeg: app.paykitRoute?.offersSparkLeg == true, + hardwareWalletIds: hwWalletManager.wallets.compactMap { hardwareWallet in + guard hardwareWallet.fundingBalanceSats > 0 || hardwareWallet.walletId == hwSend.walletId else { + return nil + } + return hardwareWallet.walletId + } + ) + } + + /// The sources the amount screen offers: a Spark leg can carry an on-chain contact payment from Spending, whether or not + /// Savings covers it. + static func fundingSources( + hasLightningInvoice: Bool, + hasOnchainInvoice: Bool, + offersSparkLeg: Bool, + hardwareWalletIds: [String] + ) -> [SendFundingSource] { var sources: [SendFundingSource] = [] - if app.scannedLightningInvoice != nil { + if hasLightningInvoice || offersSparkLeg { sources.append(.spending) } - if app.scannedOnchainInvoice != nil { + if hasOnchainInvoice { sources.append(.savings) - sources.append(contentsOf: hwWalletManager.wallets.compactMap { hardwareWallet in - guard hardwareWallet.fundingBalanceSats > 0 || hardwareWallet.walletId == hwSend.walletId else { - return nil - } - return .hardware(walletId: hardwareWallet.walletId) - }) + sources.append(contentsOf: hardwareWalletIds.map { .hardware(walletId: $0) }) } return sources } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 2a7ab02224..66007d05d4 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -505,6 +505,28 @@ final class PaykitRouteTests: XCTestCase { ) } + func testConfirmOffersSpendingWhileASparkLegCanCarryAnOnchainRequest() { + // Savings covers the request, so its Confirm opens on Savings; Spending through Spark is still a source. + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: []), + [.spending, .savings] + ) + // Savings is short, so the request opens on Spending, which must be in the list to switch back to. + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: ["hw"]), + [.spending, .savings, .hardware(walletId: "hw")] + ) + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: false, hardwareWalletIds: []), + [.savings], + "Without a Spark leg an on-chain request has no Spending source" + ) + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: true, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: []), + [.spending, .savings] + ) + } + func testRefusalWhileAnOlderJournalIsOpenReleasesThisCallsProof() { struct Refused: Error {} let older = SparkContactWithdrawal.PaykitRequest( From c5f9f611ca30e19b92451e4149d154f597bdf60a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:25:54 +0100 Subject: [PATCH 36/64] fix: publish a spark withdrawal's resolution only when its journal closes A stale close left the newer journal open but still published its resolution, which a retry of the same request read as its own. --- Bitkit/Managers/SparkManager.swift | 18 +++++++++++------- BitkitTests/PaykitRouteTests.swift | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index c91f94f2fe..93763fa33c 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -724,8 +724,9 @@ final class SparkManager: ChannelFreeLightningRail { if let request = pending.request { await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) } - Self.clearJournal(pending) - Self.resolveContactWithdrawal(pending, txId: txId) + if Self.clearJournal(pending) { + Self.resolveContactWithdrawal(pending, txId: txId) + } } else { Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") } @@ -751,15 +752,18 @@ final class SparkManager: ChannelFreeLightningRail { break } } - clearJournal(pending) - resolveContactWithdrawal(pending, txId: nil) + if clearJournal(pending) { + resolveContactWithdrawal(pending, txId: nil) + } } /// Clears `pending`'s journal only while it is still the open one, so a stale recovery never drops a newer - /// withdrawal's journal, which could then be paid twice. - nonisolated static func clearJournal(_ pending: SparkContactWithdrawal) { - guard pendingContactWithdrawal == pending else { return } + /// withdrawal's journal, which could then be paid twice. Returns whether it cleared it: only then is the resolution + /// this attempt's to publish, since a retry of the same request shares its attempt. + nonisolated static func clearJournal(_ pending: SparkContactWithdrawal) -> Bool { + guard pendingContactWithdrawal == pending else { return false } pendingContactWithdrawal = nil + return true } static func resolveContactWithdrawal(_ pending: SparkContactWithdrawal, txId: String?) { diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 66007d05d4..d3a0d533ea 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -399,6 +399,28 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer, "Losing the newer journal could pay it twice") } + @MainActor + func testAStaleCloseNeverTellsTheNewerWithdrawalsScreenItEnded() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + // A retry of the same request: same address, amount and request, so both share one attempt. + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 2000, request: request) + XCTAssertEqual(older.attempt, newer.attempt) + SparkManager.pendingContactWithdrawal = newer + var resolutions: [SparkContactWithdrawalResolution] = [] + let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } + defer { subscription.cancel() } + + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _ in .nothingStarted }, failAllowance: { _ in }) + + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer) + XCTAssertEqual(resolutions, [], "An unsent resolution for the newer send's attempt would offer Try Again while it is in flight") + } + @MainActor func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) From 8f5e15f4df85afdb837b45c1334a1127acc8965d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:33:02 +0100 Subject: [PATCH 37/64] fix: keep a stale spark withdrawal settle off a retry's proof and allowance The request's proof and allowance attempt match by request id, so a stale close released a retry's started proof and failed its allowance, and a stale record could complete the retry's proof with the older txid and settle its allowance. Both now act only while their own journal is still open. --- Bitkit/Managers/SparkManager.swift | 10 +++++++++- BitkitTests/PaykitRouteTests.swift | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 93763fa33c..72e231fd5a 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -687,6 +687,8 @@ final class SparkManager: ChannelFreeLightningRail { /// Writes the withdrawal's sent activity, tags and request proof, and closes the journal only once all of them are /// saved, so a failed or interrupted write is retried from the journal. private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { + // A settle that raced this one already saved everything; its request's proof and allowance may be a retry's now. + guard Self.isOpenJournal(pending) else { return } guard payment.status != .failed else { await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) return @@ -740,6 +742,8 @@ final class SparkManager: ChannelFreeLightningRail { releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease, failAllowance: (SparkContactWithdrawal.PaykitRequest) async -> Void ) async { + // The proof and allowance attempt match by request, so a stale close would release a retry's. + guard isOpenJournal(pending) else { return } if let request = pending.request { switch await releaseProof(request) { case .failed: @@ -757,11 +761,15 @@ final class SparkManager: ChannelFreeLightningRail { } } + nonisolated static func isOpenJournal(_ pending: SparkContactWithdrawal) -> Bool { + pendingContactWithdrawal == pending + } + /// Clears `pending`'s journal only while it is still the open one, so a stale recovery never drops a newer /// withdrawal's journal, which could then be paid twice. Returns whether it cleared it: only then is the resolution /// this attempt's to publish, since a retry of the same request shares its attempt. nonisolated static func clearJournal(_ pending: SparkContactWithdrawal) -> Bool { - guard pendingContactWithdrawal == pending else { return false } + guard isOpenJournal(pending) else { return false } pendingContactWithdrawal = nil return true } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index d3a0d533ea..cf5061ed21 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -421,6 +421,30 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(resolutions, [], "An unsent resolution for the newer send's attempt would offer Try Again while it is in flight") } + @MainActor + func testAStaleCloseDuringARetryKeepsTheNewerProofAndAllowanceAttempt() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 2000, request: request) + SparkManager.pendingContactWithdrawal = newer + var released: [SparkContactWithdrawal.PaykitRequest] = [] + var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] + + await SparkManager.closeUnsentWithdrawal( + older, + releaseProof: { released.append($0); return .released }, + failAllowance: { failedAllowances.append($0) } + ) + + XCTAssertEqual(released, [], "The proof matches by request, so a stale close would release the retry's started proof") + XCTAssertEqual(failedAllowances, [], "The retry's allowance attempt stays open while it is in flight") + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer) + } + @MainActor func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) From 5c9179b1186e29fbf570124be407bde9c5c57dc3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 17:40:51 +0100 Subject: [PATCH 38/64] fix: check the quote deadline right before a spark withdrawal sends --- Bitkit/Managers/SparkManager.swift | 14 ++++++++--- Bitkit/Services/PaykitRouteService.swift | 2 ++ .../Wallets/Send/SendConfirmationView.swift | 3 +++ BitkitTests/PaykitRouteTests.swift | 25 +++++++++++++++++++ 4 files changed, 40 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 22842e5174..bcce162820 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -597,6 +597,7 @@ final class SparkManager: ChannelFreeLightningRail { request: SparkContactWithdrawal.PaykitRequest? = nil, tags: [String] = [], maxFeeSats: UInt64? = nil, + paymentDeadline: PaykitPreciseInstant? = nil, beforeSend: () async throws -> Void = {} ) async throws -> String { // Everything before the journal is written sends nothing, so a refusal here says so to the caller. @@ -642,7 +643,8 @@ final class SparkManager: ChannelFreeLightningRail { beforeSend: beforeSend, closeUnsent: { await Self.closeUnsentWithdrawal(journaled, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) - } + }, + paymentDeadline: paymentDeadline ) let response: SendPaymentResponse do { @@ -701,16 +703,20 @@ final class SparkManager: ChannelFreeLightningRail { } /// Writes the attempt's journal before `beforeSend` starts the request's proof, so a kill between the two leaves a - /// journal that recovery closes as unsent once it expires, releasing the proof; a refusal in `beforeSend` closes it - /// at once, releasing what it started. + /// journal that recovery closes as unsent once it expires, releasing the proof; a refusal in `beforeSend`, or a + /// `paymentDeadline` passed by then, closes it at once, releasing what it started. static func startJournaledWithdrawal( writeJournal: () -> Void, beforeSend: () async throws -> Void, - closeUnsent: () async -> Void + closeUnsent: () async -> Void, + paymentDeadline: PaykitPreciseInstant? = nil, + now: () -> Date = Date.init ) async throws { writeJournal() do { try await beforeSend() + // A quote can expire while the request and its allowance are checked, so it is checked last. + try PaykitPaymentRequest.checkPaymentDeadline(paymentDeadline, at: now()) } catch { await closeUnsent() throw SparkWithdrawalNotSent(underlying: error) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index e37100db7f..3c434617db 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -212,6 +212,7 @@ enum PaykitRouteService { contact: String?, request: SparkContactWithdrawal.PaykitRequest? = nil, tags: [String] = [], + paymentDeadline: PaykitPreciseInstant? = nil, beforeSend: () async throws -> Void = {} ) async throws -> String { guard leg.service == SparkManager.routeService else { @@ -224,6 +225,7 @@ enum PaykitRouteService { request: request, tags: tags, maxFeeSats: leg.debitSat.saturatingSub(leg.deliveredSat), + paymentDeadline: paymentDeadline, beforeSend: beforeSend ) } diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 1b98bd1518..bd3709b03c 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1509,6 +1509,8 @@ struct SendConfirmationView: View { var proofRequest: SparkContactWithdrawal.PaykitRequest? var markProofStarted: (() async throws -> Void)? do { + // The selected conversion quote's expiry bounds the send too, as on a direct send. + let paymentDeadline = try request?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId) if let request { guard let privateContext = context?.privatePaymentContext else { throw PaykitPaymentRequestError.requestUnavailable } let identity = try await PaykitRouteService.startLegRequestProof( @@ -1577,6 +1579,7 @@ struct SendConfirmationView: View { contact: context?.publicKey, request: proofRequest, tags: tagManager.selectedTagsArray, + paymentDeadline: paymentDeadline, beforeSend: { try await markProofStarted?() try await beforeSend() diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index cf5061ed21..98ac91cfa0 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -357,6 +357,31 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(steps, ["journal", "proof started", "closed"], "A refusal closes the journal, releasing what it started") } + @MainActor + func testAWithdrawalWhoseQuoteExpiresBeforeItSendsNeverLeaves() async { + var now = Date(timeIntervalSince1970: 1_800_000_000) + var steps: [String] = [] + do { + try await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { + // The quote expires while the allowance and the request are checked. + now = now.addingTimeInterval(120) + steps.append("proof started") + }, + closeUnsent: { steps.append("closed") }, + paymentDeadline: PaykitPreciseInstant(date: now.addingTimeInterval(60)), + now: { now } + ) + XCTFail("An expired quote must stop the send") + } catch let error as SparkWithdrawalNotSent { + XCTAssertEqual(error.underlying as? PaykitPaymentRequestError, .requestExpired) + } catch { + XCTFail("Unexpected error \(error)") + } + XCTAssertEqual(steps, ["journal", "proof started", "closed"], "The refusal closes the journal, releasing the started proof") + } + @MainActor func testARouteThatReturnsAfterItsPaymentChangedNeverLandsOnTheNextOne() async { snapshotAppDefaultsDomain() From 6bb6134f495ab6e3e8cee32e3e7f952a8e517790 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 18:09:15 +0100 Subject: [PATCH 39/64] fix: keep the funding source switchable on a spark route --- .../Wallets/Send/SendConfirmationView.swift | 21 +++++++++++++---- BitkitTests/PaykitRouteTests.swift | 23 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index bd3709b03c..ec519e7a50 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -760,13 +760,17 @@ struct SendConfirmationView: View { VStack(alignment: .leading, spacing: 16) { HStack { SendSectionView(t("wallet__send_from")) { + // The payer can still move a fixed request to Savings or a hardware wallet here, which reroutes it. NumberPadActionButton( text: t("wallet__spending__title"), + imageName: canSwitchFundingSource ? "arrow-up-down" : nil, color: .purpleAccent, - variant: .secondary, - disabled: true - ) {} - .accessibilityIdentifier("SendConfirmAssetButton") + variant: canSwitchFundingSource ? .primary : .secondary, + disabled: !canSwitchFundingSource + ) { + selectNextFundingSource() + } + .accessibilityIdentifier("SendConfirmAssetButton") } Spacer(minLength: 16) @@ -937,6 +941,14 @@ struct SendConfirmationView: View { } } + /// A hardware wallet signs the on-chain send itself and the router never runs for it, so picking one drops the Spark + /// leg; Savings and Spending ask the router again, which settles the leg. + static func route(_ route: PaykitRouteUi?, afterSelecting source: SendFundingSource) -> PaykitRouteUi? { + guard case .hardware = source, var route else { return route } + route.serviceLeg = nil + return route + } + private func selectNextFundingSource() { guard canSwitchFundingSource else { return } let currentIndex = fundingSources.firstIndex(of: selectedFundingSource) @@ -956,6 +968,7 @@ struct SendConfirmationView: View { hwSend.selectWallet(nil) app.selectedWalletToPayFrom = .onchain case let .hardware(walletId): + app.paykitRoute = Self.route(app.paykitRoute, afterSelecting: source) let balance = hwWalletManager.fundingBalance(walletId: walletId) let reserve = HwFundingSigner.feeReserve( balanceSats: balance, diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 98ac91cfa0..5106daf281 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -540,6 +540,29 @@ final class PaykitRouteTests: XCTestCase { XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain, hasLightningPayment: false)) } + func testASparkRoutedConfirmCanMoveToAnotherSource() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + var routed = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: ["hw"]), + [.spending, .savings, .hardware(walletId: "hw")], + "Confirm on a Spark leg still offers Savings and the hardware wallet" + ) + // The router never runs for a hardware wallet, so its pick drops the leg for the on-chain send it signs. + XCTAssertNil(SendConfirmationView.route(routed, afterSelecting: .hardware(walletId: "hw"))?.serviceLeg) + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .hardware(walletId: "hw"))?.endpoints, routed.endpoints) + // Savings and Spending ask the router again, which settles the leg. + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .savings), routed) + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .spending), routed) + XCTAssertNil(SendConfirmationView.route(nil, afterSelecting: .hardware(walletId: "hw"))) + } + func testARefusedRerouteOnConfirmKeepsTheSwipeOffUntilAnotherSourceIsPicked() { let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) From 76a1aee38a3447086569e60760525a7f8b4d04e4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:22:14 +0100 Subject: [PATCH 40/64] test: pin the funding source control on a spark route --- .../Wallets/Send/SendConfirmationView.swift | 28 +++++++++++++++---- BitkitTests/PaykitRouteTests.swift | 18 ++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index ec519e7a50..19532db2f7 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -201,7 +201,23 @@ struct SendConfirmationView: View { } private var canSwitchFundingSource: Bool { - retainedHardwareRetry == nil && fundingSources.count > 1 + Self.canSwitchFundingSource(hasRetainedHardwareRetry: retainedHardwareRetry != nil, fundingSources: fundingSources) + } + + static func canSwitchFundingSource(hasRetainedHardwareRetry: Bool, fundingSources: [SendFundingSource]) -> Bool { + !hasRetainedHardwareRetry && fundingSources.count > 1 + } + + /// What Confirm's FROM control shows and does. + struct FromControl: Equatable { + let titleKey: String + let isSwitchable: Bool + } + + /// A Spark leg pays from Spending, and the payer can still move a fixed request to Savings or a hardware wallet, + /// which reroutes it. + static func sparkRouteFromControl(canSwitchFundingSource: Bool) -> FromControl { + FromControl(titleKey: "wallet__spending__title", isSwitchable: canSwitchFundingSource) } var canSwitchWallet: Bool { @@ -760,13 +776,13 @@ struct SendConfirmationView: View { VStack(alignment: .leading, spacing: 16) { HStack { SendSectionView(t("wallet__send_from")) { - // The payer can still move a fixed request to Savings or a hardware wallet here, which reroutes it. + let control = Self.sparkRouteFromControl(canSwitchFundingSource: canSwitchFundingSource) NumberPadActionButton( - text: t("wallet__spending__title"), - imageName: canSwitchFundingSource ? "arrow-up-down" : nil, + text: t(control.titleKey), + imageName: control.isSwitchable ? "arrow-up-down" : nil, color: .purpleAccent, - variant: canSwitchFundingSource ? .primary : .secondary, - disabled: !canSwitchFundingSource + variant: control.isSwitchable ? .primary : .secondary, + disabled: !control.isSwitchable ) { selectNextFundingSource() } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 5106daf281..928d613462 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -563,6 +563,24 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(SendConfirmationView.route(nil, afterSelecting: .hardware(walletId: "hw"))) } + func testTheFromControlStaysSwitchableOnASparkRoute() { + let sources = SendConfirmationView.fundingSources( + hasLightningInvoice: false, + hasOnchainInvoice: true, + offersSparkLeg: true, + hardwareWalletIds: [] + ) + let canSwitch = SendConfirmationView.canSwitchFundingSource(hasRetainedHardwareRetry: false, fundingSources: sources) + + let control = SendConfirmationView.sparkRouteFromControl(canSwitchFundingSource: canSwitch) + + XCTAssertTrue(control.isSwitchable, "After picking Spark, FROM still moves a fixed request to Savings") + XCTAssertEqual(control.titleKey, "wallet__spending__title") + // A retained hardware retry pins the source, on a Spark route too. + let pinned = SendConfirmationView.canSwitchFundingSource(hasRetainedHardwareRetry: true, fundingSources: sources) + XCTAssertFalse(SendConfirmationView.sparkRouteFromControl(canSwitchFundingSource: pinned).isSwitchable) + } + func testARefusedRerouteOnConfirmKeepsTheSwipeOffUntilAnotherSourceIsPicked() { let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) From 2eea8e5842d42f44462ae70ad6a47150b3068528 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 22:16:01 +0100 Subject: [PATCH 41/64] fix: keep a failed spark withdrawal open after a sync that never reached spark --- Bitkit/Managers/SparkManager.swift | 47 +++++++++++++++++++++++++++--- BitkitTests/PaykitRouteTests.swift | 27 +++++++++++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index bcce162820..e5a7595a55 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -384,6 +384,14 @@ final class SparkManager: ChannelFreeLightningRail { return ChannelFreeRailSendRefused(reason: t("other__scan__error__expired")) } + nonisolated func hasSynced(after seconds: UInt64?) async -> Bool { + guard let info = try? await requireSdk().getInfo(request: GetInfoRequest(ensureSynced: false)), + info.lastSyncError == nil + else { return false } + guard let seconds else { return true } + return info.lastSyncedAt.map { $0 > seconds } ?? false + } + nonisolated func lightningPayments() async throws -> [ChannelFreeRailPayment] { let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments return payments.compactMap { payment in @@ -654,10 +662,14 @@ final class SparkManager: ChannelFreeLightningRail { )) } catch { Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") + let failedAt = UInt64(Date().timeIntervalSince1970) Task { - // Only a sync that succeeded now can tell whether this withdrawal went out. - guard await (try? requireSdk().syncWallet(request: SyncWalletRequest())) != nil else { return } - await settleContactWithdrawal(allowClear: true) + await Self.settleAfterFailedWithdrawal( + failedAt: failedAt, + syncWallet: { _ = try await self.requireSdk().syncWallet(request: SyncWalletRequest()) }, + hasSynced: { await self.hasSynced(after: $0) }, + settle: { await self.settleContactWithdrawal(allowClear: $0) } + ) } throw error } @@ -702,6 +714,29 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// Settles a withdrawal whose send failed or has an unknown outcome from the sync after it. That sync returns even + /// when it never reached Spark, so only one that completed after `failedAt` may close an unlisted one as unsent. + static func settleAfterFailedWithdrawal( + failedAt: UInt64, + syncWallet: () async throws -> Void, + hasSynced: (UInt64) async -> Bool, + settle: (_ allowClear: Bool) async -> Void + ) async { + guard await (try? syncWallet()) != nil else { return } + await settleAfterSync(since: failedAt, hasSynced: hasSynced, settle: settle) + } + + /// Spark reports a sync that never reached it as done too, its `.synced` event included, so only one that completed + /// after `since` may close an unlisted withdrawal as unsent. + static func settleAfterSync( + since: UInt64, + hasSynced: (UInt64) async -> Bool, + settle: (_ allowClear: Bool) async -> Void + ) async { + let synced = await hasSynced(since) + await settle(synced) + } + /// Writes the attempt's journal before `beforeSend` starts the request's proof, so a kill between the two leaves a /// journal that recovery closes as unsent once it expires, releasing the proof; a refusal in `beforeSend`, or a /// `paymentDeadline` passed by then, closes it at once, releasing what it started. @@ -1222,7 +1257,11 @@ final class SparkManager: ChannelFreeLightningRail { switch event { case .synced: await refreshState() - await settleContactWithdrawal(allowClear: true) + await Self.settleAfterSync( + since: Self.pendingContactWithdrawal?.startedAt ?? 0, + hasSynced: { await self.hasSynced(after: $0) }, + settle: { await self.settleContactWithdrawal(allowClear: $0) } + ) case .newDeposits, .claimedDeposits: await refreshState() case let .unclaimedDeposits(deposits): diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 928d613462..16a2ebfe95 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -182,6 +182,33 @@ final class PaykitRouteTests: XCTestCase { ) } + func testAFailedWithdrawalStaysOpenAfterASyncThatNeverReachedSpark() async { + var allowedClears: [Bool] = [] + // The sync call returns, but Spark keeps its failed sync in `lastSyncError`, so it never synced after the failure. + await SparkManager.settleAfterFailedWithdrawal( + failedAt: 1000, + syncWallet: {}, + hasSynced: { _ in false }, + settle: { allowedClears.append($0) } + ) + XCTAssertEqual(allowedClears, [false], "A sync that never reached Spark can't show the withdrawal was never sent") + + var syncedAfter: UInt64? + await SparkManager.settleAfterFailedWithdrawal( + failedAt: 1000, + syncWallet: {}, + hasSynced: { syncedAfter = $0; return true }, + settle: { allowedClears.append($0) } + ) + XCTAssertEqual(syncedAfter, 1000) + XCTAssertEqual(allowedClears, [false, true]) + + // Spark's `.synced` event also follows a sync that never reached it. + await SparkManager.settleAfterSync(since: 900, hasSynced: { syncedAfter = $0; return false }, settle: { allowedClears.append($0) }) + XCTAssertEqual(syncedAfter, 900) + XCTAssertEqual(allowedClears, [false, true, false], "A synced event alone can't show the withdrawal was never sent") + } + func testJournalStaysOpenUntilEveryLocalRecordIsSaved() async { let saved = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { true }) XCTAssertTrue(saved) From a21a20d5a9690df58af9b2a4af4ab93d44b4b194 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:20:00 +0100 Subject: [PATCH 42/64] fix: drop a paykit route quote once its source or amount changed --- Bitkit/Services/PaykitRouteService.swift | 16 ++++-- Bitkit/ViewModels/AppViewModel.swift | 2 + BitkitTests/PaykitRouteTests.swift | 62 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 5 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 3c434617db..37f0ec50ec 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -260,12 +260,18 @@ extension AppViewModel { var unrouted = route unrouted.serviceLeg = nil let contactId = contactPaymentContext?.id + paykitRoutingGeneration += 1 + let generation = paykitRoutingGeneration + // A dismissed or replaced payment, a newer routing request (a new amount or source) or a source picked since + // makes the answer stale, so it never lands on what followed it. + let isCurrent = { + self.contactPaymentContext?.id == contactId && self.paykitRoutingGeneration == generation && + (self.selectedWalletToPayFrom == .lightning) == (source == .spending) && + (self.paykitRoute.map { $0.endpoints == route.endpoints } ?? true) + } do { let picked = try await router(route, amountSats, source, lightningSpendableSats, onchainSpendableSats) - // A dismissed or replaced payment's route must never land on the one that followed it. - guard contactPaymentContext?.id == contactId, paykitRoute.map({ $0.endpoints == route.endpoints }) ?? true else { - return .stale - } + guard isCurrent() else { return .stale } switch picked { case let .direct(endpoint): paykitRoute = unrouted @@ -292,7 +298,7 @@ extension AppViewModel { } } catch { Logger.error("Failed to route Paykit payment: \(error)", context: "PaykitRoute") - guard contactPaymentContext?.id == contactId else { return .stale } + guard isCurrent() else { return .stale } showNoPaykitRouteToast(isBalanceShort: false) return .refused } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index f4f1932a65..b86db90633 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -172,6 +172,8 @@ class AppViewModel: ObservableObject { private(set) var didRejectScannedPayment = false @Published var paykitUsesUsdt = false @Published var paykitRoute: PaykitRouteUi? + /// Bumped by each routing request, so only the latest one's answer lands. + var paykitRoutingGeneration = 0 @Published var paykitReviewedAmount: PaykitAmount? @Published var paykitPaymentTerms: PaykitRequestPricing.Payment? diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 16a2ebfe95..8468af73eb 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -438,6 +438,68 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(app.paykitRoute, routeB, "contact A's leg must never pay contact B") } + @MainActor + func testARouteThatReturnsAfterTheSourceChangedNeverRestoresIt() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.paykitRoute = route + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + route, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // The user goes back to Savings while Spark quotes the Spending leg. + app.selectedWalletToPayFrom = .onchain + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(outcome, .stale) + XCTAssertEqual(app.selectedWalletToPayFrom, .onchain, "a superseded Spending quote must not take the source back") + XCTAssertNil(app.paykitRoute?.serviceLeg) + } + + @MainActor + func testARouteSupersededByANewerOneIsDropped() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.paykitRoute = route + app.selectedWalletToPayFrom = .lightning + var newer: PaykitRouteOutcome? + + let older = await app.routeContactPayment( + route, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // A new amount asks the router again before the first quote returns. + newer = await app.routeContactPayment( + route, + amountSats: 30000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in .service(leg: self.sparkLeg(amountSats: 30000, feeSats: 300)) } + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(newer, .leg) + XCTAssertEqual(older, .stale) + XCTAssertEqual(app.paykitRoute?.serviceLeg?.deliveredSat, 30000, "the older amount's leg must not replace the newer one") + } + @MainActor func testAStaleRecoveryNeverClearsANewerWithdrawalsJournal() async { snapshotAppDefaultsDomain() From 6957828af5ee45188064182e502f53040a0bcd82 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:20:00 +0100 Subject: [PATCH 43/64] fix: settle an unsent spark withdrawal's allowance before dropping its proof --- Bitkit/Managers/SparkManager.swift | 30 +++++++------- Bitkit/Services/PaykitAllowanceExecutor.swift | 24 +++++++---- .../Services/PaykitPaymentProofService.swift | 6 ++- .../PaykitPaymentProofServiceTests.swift | 41 +++++++++++++++++++ BitkitTests/PaykitRouteTests.swift | 32 +++++++++++---- 5 files changed, 98 insertions(+), 35 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index e5a7595a55..517a5646ed 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -839,22 +839,16 @@ final class SparkManager: ChannelFreeLightningRail { /// allowance attempt, left unknown when the send's outcome was, then fails, so the ledger lets it be paid again. static func closeUnsentWithdrawal( _ pending: SparkContactWithdrawal, - releaseProof: (SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease, - failAllowance: (SparkContactWithdrawal.PaykitRequest) async -> Void + releaseProof: (SparkContactWithdrawal.PaykitRequest, _ failAllowance: () async -> Bool) async -> SparkProofRelease, + failAllowance: @escaping (SparkContactWithdrawal.PaykitRequest) async -> Bool ) async { // The proof and allowance attempt match by request, so a stale close would release a retry's. guard isOpenJournal(pending) else { return } - if let request = pending.request { - switch await releaseProof(request) { - case .failed: - Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") - return - case .released: - // The allowance attempt begins only once the proof started, so only then is there one to fail. - await failAllowance(request) - case .nothingStarted: - break - } + // The allowance attempt begins only once the proof started, so only a started proof fails one, and it fails + // before that proof goes, so a restart in between still finds the proof to settle it from. + if let request = pending.request, await releaseProof(request, { await failAllowance(request) }) == .failed { + Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") + return } if clearJournal(pending) { resolveContactWithdrawal(pending, txId: nil) @@ -880,15 +874,19 @@ final class SparkManager: ChannelFreeLightningRail { contactWithdrawalResolutionSubject.send(resolution) } - private static func releaseUnsentProof(_ request: SparkContactWithdrawal.PaykitRequest) async -> SparkProofRelease { + private static func releaseUnsentProof( + _ request: SparkContactWithdrawal.PaykitRequest, + failAllowance: () async -> Bool + ) async -> SparkProofRelease { await PaykitPaymentProofService.shared.failSparkOnchainPayment( requestId: request.id, identity: request.identity, - unstartedPaymentList: request.paymentList + unstartedPaymentList: request.paymentList, + settleAllowance: failAllowance ) } - private static func failAllowance(_ request: SparkContactWithdrawal.PaykitRequest) async { + private static func failAllowance(_ request: SparkContactWithdrawal.PaykitRequest) async -> Bool { await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .failed) } diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index fa20526fff..d69eb7eeb8 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -1358,8 +1358,10 @@ actor PaykitAllowanceExecutor { setStage(.sending, attemptId: attemptId, identity: identity) } - func finishManualPayment(attemptId: String, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async { - guard let identity = activeIdentity else { return } + /// Returns whether the outcome was recorded. + @discardableResult + func finishManualPayment(attemptId: String, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async -> Bool { + guard let identity = activeIdentity else { return false } if let transactionId { updateLocalState(identity: identity) { state in guard let index = state.journal.firstIndex(where: { $0.attemptId == attemptId }) else { return } @@ -1368,20 +1370,24 @@ actor PaykitAllowanceExecutor { } do { try await record(attemptId: attemptId, outcome: outcome, identity: identity) + return true } catch { Logger.warn("Failed to record a manual payment outcome: \(error)", context: "PaykitAllowance") + return false } } /// Settles the manual attempt still open for a request once its outcome is learned later, as a Spark withdrawal's /// journal learns it, so an unsent send no longer blocks the request on the ledger. - func settleManualPayment(requestId: PaykitPaymentRequest.ID, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async { - guard let identity = activeIdentity, - let entry = localState(identity: identity).journal.last(where: { - !$0.isAutomatic && $0.requestId == requestId && !$0.stage.isTerminal - }) - else { return } - await finishManualPayment(attemptId: entry.attemptId, outcome: outcome, transactionId: transactionId) + /// Returns whether no attempt is left open for the request. + @discardableResult + func settleManualPayment(requestId: PaykitPaymentRequest.ID, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async -> Bool { + guard let identity = activeIdentity else { return false } + guard let entry = localState(identity: identity).journal.last(where: { + !$0.isAutomatic && $0.requestId == requestId && !$0.stage.isTerminal + }) + else { return true } + return await finishManualPayment(attemptId: entry.attemptId, outcome: outcome, transactionId: transactionId) } // MARK: Helpers diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 1a6a472b7e..1681752454 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1374,7 +1374,8 @@ actor PaykitPaymentProofService { requestId: PaykitPaymentRequest.ID, identity: String, unstartedPaymentList: SparkContactWithdrawal.PaymentList? = nil, - privatePaykitService: PrivatePaykitService = .shared + privatePaykitService: PrivatePaykitService = .shared, + settleAllowance: () async -> Bool = { true } ) async -> SparkProofRelease { do { return try await mutationLock.withLock { @@ -1395,6 +1396,9 @@ actor PaykitPaymentProofService { } return .nothingStarted } + // The allowance attempt is settled before the proof goes: a restart in between, or a failed ledger + // write, leaves the proof and so the journal, which retry the settlement. + guard await settleAllowance() else { return .failed } for proof in unsent { guard let version = proof.privatePaymentListVersion else { continue } try await privatePaykitService.releaseUnsentPaymentListVersion( diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 0a847fb51a..b261b51cb8 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1926,6 +1926,47 @@ final class PaykitPaymentProofServiceTests: XCTestCase { XCTAssertTrue(remaining.isEmpty) } + func testAnUnsentSparkWithdrawalKeepsItsProofUntilItsAllowanceAttemptIsSettled() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) + + let unsettled = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { false }) + XCTAssertEqual(unsettled, .failed, "A failed allowance write keeps the journal open for a retry") + let kept = await store.snapshot() + XCTAssertEqual(kept.count, 1, "The proof stays until its allowance attempt is settled, so a restart still settles it") + + var proofsWhileSettling: Int? + let released = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { + proofsWhileSettling = await store.snapshot().count + return true + }) + XCTAssertEqual(released, .released) + XCTAssertEqual(proofsWhileSettling, 1, "The allowance attempt is settled before its proof is removed") + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + } + + func testAnUnstartedSparkWithdrawalSettlesNoAllowanceAttempt() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: PaymentProofMemoryStore()) + var settled = false + + let release = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { + settled = true + return true + }) + + XCTAssertEqual(release, .nothingStarted) + XCTAssertFalse(settled, "Only a started Spark proof has an allowance attempt to settle") + } + func testClosingASparkJournalLeavesADirectOnchainProofForTheSameRequest() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue let record = try paymentRequestRecord(endpoints: [endpoint]) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 8468af73eb..6a54a0663c 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -245,15 +245,22 @@ final class PaykitRouteTests: XCTestCase { SparkManager.pendingContactWithdrawal = pending var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] - await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .failed }, failAllowance: { failedAllowances.append($0) }) + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { _, _ in .failed }, + failAllowance: { failedAllowances.append($0); return true } + ) XCTAssertEqual(SparkManager.pendingContactWithdrawal, pending, "A proof that wasn't released keeps the journal, so the next sync retries it") XCTAssertEqual(failedAllowances, [], "The attempt stays unknown while the journal is still open") var released: SparkContactWithdrawal.PaykitRequest? await SparkManager.closeUnsentWithdrawal( pending, - releaseProof: { released = $0; return .released }, - failAllowance: { failedAllowances.append($0) } + releaseProof: { request, failAllowance in + released = request + return await failAllowance() ? .released : .failed + }, + failAllowance: { failedAllowances.append($0); return true } ) XCTAssertEqual(released, request) XCTAssertEqual(failedAllowances, [request], "An unsent withdrawal fails its allowance attempt, so the ledger lets the request be paid again") @@ -262,7 +269,11 @@ final class PaykitRouteTests: XCTestCase { // A kill before the proof started leaves no Spark attempt, so a direct send's attempt for the request stays. SparkManager.pendingContactWithdrawal = pending failedAllowances = [] - await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .nothingStarted }, failAllowance: { failedAllowances.append($0) }) + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { _, _ in .nothingStarted }, + failAllowance: { failedAllowances.append($0); return true } + ) XCTAssertEqual(failedAllowances, [], "Only the Spark withdrawal's own allowance attempt fails") XCTAssertNil(SparkManager.pendingContactWithdrawal) } @@ -339,7 +350,7 @@ final class PaykitRouteTests: XCTestCase { let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } defer { subscription.cancel() } - await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _ in .released }, failAllowance: { _ in }) + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _, _ in .released }, failAllowance: { _ in true }) let unsent = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: nil) XCTAssertEqual(resolutions, [unsent]) @@ -508,7 +519,7 @@ final class PaykitRouteTests: XCTestCase { // A recovery captured the older withdrawal; another one closed it and the newer withdrawal wrote its journal. SparkManager.pendingContactWithdrawal = newer - await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _ in .nothingStarted }, failAllowance: { _ in }) + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _, _ in .nothingStarted }, failAllowance: { _ in true }) XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer, "Losing the newer journal could pay it twice") } @@ -529,7 +540,7 @@ final class PaykitRouteTests: XCTestCase { let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } defer { subscription.cancel() } - await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _ in .nothingStarted }, failAllowance: { _ in }) + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _, _ in .nothingStarted }, failAllowance: { _ in true }) XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer) XCTAssertEqual(resolutions, [], "An unsent resolution for the newer send's attempt would offer Try Again while it is in flight") @@ -550,8 +561,11 @@ final class PaykitRouteTests: XCTestCase { await SparkManager.closeUnsentWithdrawal( older, - releaseProof: { released.append($0); return .released }, - failAllowance: { failedAllowances.append($0) } + releaseProof: { request, failAllowance in + released.append(request) + return await failAllowance() ? .released : .failed + }, + failAllowance: { failedAllowances.append($0); return true } ) XCTAssertEqual(released, [], "The proof matches by request, so a stale close would release the retry's started proof") From 88fb385036e3d586a9652cc9ce8e558ecbf83645 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:26:19 +0100 Subject: [PATCH 44/64] fix: hide boost on a pending spark withdrawal --- Bitkit/Managers/SparkManager.swift | 24 +++++++++++++++++++ .../Wallets/Activity/ActivityItemView.swift | 5 +++- BitkitTests/SparkWithdrawalTests.swift | 21 ++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index f1ccc071cc..d30b8582b6 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -575,6 +575,30 @@ final class SparkManager: ChannelFreeLightningRail { sent.contains(txid) || withdrawals.contains { $0.txid == txid } } + /// Whether `txid` is a Spark withdrawal, which LDK never held and so can't boost: one this app sent, to Savings or a + /// contact, or one Spark lists. + func isSparkWithdrawal(txid: String) async -> Bool { + let known = sentWithdrawalTxIds.union(Self.contactWithdrawalTxIds).union(withdrawals.map(\.txid)) + if Self.isSparkWithdrawal(txid: txid, known: known, payments: []) { + return true + } + guard isReady else { return false } + do { + let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + return Self.isSparkWithdrawal(txid: txid, known: known, payments: payments) + } catch { + Logger.warn("Failed to list Spark payments for \(txid): \(error)", context: "SparkManager") + return false + } + } + + nonisolated static func isSparkWithdrawal(txid: String, known: Set, payments: [Payment]) -> Bool { + known.contains(txid) || payments.contains { payment in + guard case let .withdraw(txId, _, _) = payment.details else { return false } + return txId == txid + } + } + /// Reuses the provider's withdrawal quote while it holds for the same address and balance, so the withdrawal /// pays the fee the confirm screen showed; a second full-balance quote can take minutes. private func prepareWithdrawAll(to address: String) async throws -> PrepareSendPaymentResponse { diff --git a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift index ce4422c4dd..3d62f68496 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift @@ -19,6 +19,8 @@ struct ActivityItemView: View { @StateObject private var viewModel: ActivityItemViewModel @State private var boostTxDoesExist: [String: Bool] = [:] // Maps boostTxId -> doesExist @State private var isCpfpChild: Bool = false + /// Spark sent this transaction, so LDK holds no input of it to boost. + @State private var isSparkWithdrawal = false private var isPaykitUIActive: Bool { PaykitFeatureFlags.isUIAvailable && isPaykitUIEnabled @@ -148,7 +150,7 @@ struct ActivityItemView: View { case .lightning: return true case let .onchain(activity): - if isCpfpChild { + if isCpfpChild || isSparkWithdrawal { return true } if !activity.doesExist { @@ -257,6 +259,7 @@ struct ActivityItemView: View { // Check if this is a CPFP child transaction if case let .onchain(activity) = viewModel.activity { isCpfpChild = await CoreService.shared.activity.isCpfpChildTransaction(txId: activity.txId, walletId: activity.walletId) + isSparkWithdrawal = await SparkManager.shared.isSparkWithdrawal(txid: activity.txId) } // Load boostTxIds doesExist status to determine RBF vs CPFP diff --git a/BitkitTests/SparkWithdrawalTests.swift b/BitkitTests/SparkWithdrawalTests.swift index ae2d778693..166ab522ee 100644 --- a/BitkitTests/SparkWithdrawalTests.swift +++ b/BitkitTests/SparkWithdrawalTests.swift @@ -295,6 +295,27 @@ final class SparkWithdrawalTests: XCTestCase { XCTAssertFalse(SparkManager.isWithdrawal(txid: "payment", sent: ["sent"], withdrawals: listed)) } + func testASparkWithdrawalIsNeverBoosted() { + let pending = Payment( + id: "pending", + paymentType: .send, + status: .pending, + amount: 20000, + fees: 300, + timestamp: 1, + method: .withdraw, + details: .withdraw(txId: "listed", vout: 0, destinationAddress: "bcrt1qcontact"), + conversionDetails: nil + ) + + XCTAssertTrue(SparkManager.isSparkWithdrawal(txid: "contact", known: ["contact"], payments: [])) + XCTAssertTrue( + SparkManager.isSparkWithdrawal(txid: "listed", known: [], payments: [pending]), + "a pending withdrawal Spark lists can't be boosted" + ) + XCTAssertFalse(SparkManager.isSparkWithdrawal(txid: "savings", known: ["contact"], payments: [pending])) + } + @MainActor private func waitUntilPriced(_ transfer: TransferViewModel) async { for _ in 0 ..< 100 where transfer.isPricingSparkWithdrawal { From b96e53efe29cd00e38318615501b7c1dc370ffb5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:26:19 +0100 Subject: [PATCH 45/64] fix: restore the endpoint a paykit reroute picks --- Bitkit/Services/PaykitRouteService.swift | 41 ++++++++----- BitkitTests/PaykitRouteTests.swift | 74 ++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 13 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 37f0ec50ec..4acda6ce25 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -3,11 +3,13 @@ import Foundation import Paykit /// A contact payment bitkit-core's Paykit router picks the way for: the contact's bitcoin endpoints, whether a Spark leg -/// may reach its on-chain ones, and the leg once the router picked one. +/// may reach its on-chain ones, the leg once the router picked one, and the decoded invoice and LNURL a Direct pick pays. struct PaykitRouteUi: Equatable { let endpoints: [PaykitEndpoint] let offersSparkLeg: Bool var serviceLeg: ServiceRouteLeg? + var invoice: LightningInvoice? + var lnurl: LnurlPayData? var deliveredSat: UInt64? { serviceLeg?.deliveredSat @@ -259,6 +261,8 @@ extension AppViewModel { ) async -> PaykitRouteOutcome { var unrouted = route unrouted.serviceLeg = nil + unrouted.invoice = route.invoice ?? scannedLightningInvoice + unrouted.lnurl = route.lnurl ?? lnurlPayData let contactId = contactPaymentContext?.id paykitRoutingGeneration += 1 let generation = paykitRoutingGeneration @@ -275,13 +279,13 @@ extension AppViewModel { switch picked { case let .direct(endpoint): paykitRoute = unrouted - guard await payDirectly(endpoint) else { return .refused } + guard await payDirectly(endpoint, route: unrouted) else { return .refused } if let request { paykitPaymentTerms = try request.payment(using: paykitPaymentMethod) } return .direct case let .service(leg): - var routed = route + var routed = unrouted routed.serviceLeg = leg paykitRoute = routed selectedWalletToPayFrom = .lightning @@ -304,8 +308,9 @@ extension AppViewModel { } } - /// Switches the send to the endpoint the router picked, when the scan opened another one. - private func payDirectly(_ endpoint: PaykitEndpoint) async -> Bool { + /// Switches the send to exactly the endpoint the router picked, clearing the other Lightning one. An earlier pick may + /// have cleared the picked one, so it comes back from `route`. + private func payDirectly(_ endpoint: PaykitEndpoint, route: PaykitRouteUi) async -> Bool { if endpoint.isOnchain { selectedWalletToPayFrom = .onchain if scannedOnchainInvoice?.address != endpoint.value { @@ -315,17 +320,27 @@ extension AppViewModel { } selectedWalletToPayFrom = .lightning if endpoint.isLnurl { - return lnurlPayData != nil || scannedLightningInvoice != nil - } - if scannedLightningInvoice?.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame { + guard let lnurl = lnurlPayData ?? route.lnurl else { + Logger.warn("Found no LNURL for the endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + lnurlPayData = lnurl + scannedLightningInvoice = nil return true } - guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { - Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "PaykitRoute") - showNoPaykitRouteToast(isBalanceShort: false) - return false + let known = [scannedLightningInvoice, route.invoice].compactMap { $0 } + .first { $0.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame } + if let known { + scannedLightningInvoice = known + } else { + guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { + Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + scannedLightningInvoice = invoice } - scannedLightningInvoice = invoice lnurlPayData = nil return true } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 6a54a0663c..86e528eb0a 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -511,6 +511,80 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(app.paykitRoute?.serviceLeg?.deliveredSat, 30000, "the older amount's leg must not replace the newer one") } + @MainActor + func testADirectRerouteFromBolt11BackToLnurlPaysTheLnurl() async { + let (app, route, bolt11, lnurl) = openLightningContact() + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value, "the LNURL pick must pay the LNURL, not the skipped invoice") + XCTAssertNil(app.scannedLightningInvoice) + } + + @MainActor + func testADirectRerouteFromLnurlBackToBolt11PaysTheInvoice() async { + let (app, route, bolt11, lnurl) = openLightningContact() + + let first = await routeDirectly(app, route, to: lnurl) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.scannedLightningInvoice, "the LNURL pick must not leave the invoice to pay") + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: bolt11) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.scannedLightningInvoice?.bolt11, bolt11.value) + XCTAssertNil(app.lnurlPayData) + } + + @MainActor + private func openLightningContact() -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let bolt11 = PaykitEndpoint( + methodId: PublicPaykitService.MethodId.bitcoinLightningBolt11.rawValue, + value: "lnbcrt1contactreroute" + ) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.scannedLightningInvoice = LightningInvoice( + bolt11: bolt11.value, + paymentHash: Data(), + amountSatoshis: 0, + timestampSeconds: 1, + expirySeconds: 3600, + isExpired: false, + description: nil, + networkType: .regtest, + payeeNodeId: nil + ) + app.lnurlPayData = LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: 1000, + maxSendable: 100_000_000, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + app.selectedWalletToPayFrom = .lightning + return (app, PaykitRouteUi(endpoints: [bolt11, lightning], offersSparkLeg: false), bolt11, lightning) + } + + @MainActor + private func routeDirectly(_ app: AppViewModel, _ route: PaykitRouteUi, to endpoint: PaykitEndpoint) async -> PaykitRouteOutcome { + await app.routeContactPayment( + route, + amountSats: 2000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in .direct(endpoint: endpoint) } + } + @MainActor func testAStaleRecoveryNeverClearsANewerWithdrawalsJournal() async { snapshotAppDefaultsDomain() From daec38b4dc5f7b9c58ad7397290f83f0c05f26e4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:34:01 +0100 Subject: [PATCH 46/64] fix: validate a spark withdrawal against its debit and spark's balance --- Bitkit/Services/PaykitRouteService.swift | 11 ++++++ .../Views/Wallets/Send/SendAmountView.swift | 27 ++++++++++++-- BitkitTests/PaykitRouteTests.swift | 35 +++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 4acda6ce25..f2029554aa 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -134,6 +134,17 @@ enum PaykitRouteService { return legs } + /// Whether a Spark withdrawal carries `amountSats` on `route`, or nil when Lightning's limit decides. A withdrawal + /// is paid from Spark's whole balance, so Lightning's limit never caps it: a quoted leg fits when its debit, fees + /// included, does, and before the quote an amount the balance covers lets Continue ask for one. + static func sparkWithdrawalValidity(route: PaykitRouteUi?, amountSats: UInt64, sparkBalanceSats: UInt64) -> Bool? { + guard let route, route.offersSparkLeg, amountSats > 0 else { return nil } + if let leg = route.serviceLeg, leg.deliveredSat == amountSats { + return sparkBalanceSats >= leg.debitSat + } + return sparkBalanceSats >= amountSats ? true : nil + } + /// Whether a None route is a short balance rather than a contact Bitkit can't pay. static func isBalanceShort(amountSats: UInt64, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64) -> Bool { amountSats > lightningSpendableSats.saturatingAdd(onchainSpendableSats) diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index dddfa14d87..2554e4e3be 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -121,6 +121,9 @@ struct SendAmountView: View { } let minAmount = app.selectedWalletToPayFrom == .lightning ? 1 : Env.dustLimit + if !hwSend.isActive, app.selectedWalletToPayFrom == .lightning, let valid = sparkWithdrawalValidity { + return valid + } if app.selectedWalletToPayFrom == .lightning, let data = app.lnurlPayData, !data.accepts(amountSats: amountSats) { @@ -129,6 +132,26 @@ struct SendAmountView: View { return amountSats >= minAmount && amountSats <= availableAmount } + /// Spark's whole balance pays a withdrawal to the contact, so Lightning's limit never caps it. + private var sparkWithdrawalBalanceSats: UInt64 { + guard app.contactPaymentContext != nil, app.paykitRoute?.offersSparkLeg == true, SparkManager.shared.isReady else { return 0 } + return SparkManager.shared.balanceSats + } + + private var sparkWithdrawalValidity: Bool? { + PaykitRouteService.sparkWithdrawalValidity( + route: app.paykitRoute, + amountSats: amountSats, + sparkBalanceSats: sparkWithdrawalBalanceSats + ) + } + + /// The pad's cap: what Spending can send, or Spark's whole balance when a withdrawal can carry more. + private var inputCapSats: UInt64 { + guard !hwSend.isActive, app.selectedWalletToPayFrom == .lightning else { return availableAmount } + return max(availableAmount, sparkWithdrawalBalanceSats) + } + /// Determines if the current amount is a max amount send var isMaxAmountSend: Bool { guard app.selectedWalletToPayFrom == .onchain, app.contactPaymentContext?.incomingPaymentRequest == nil else { return false } @@ -339,7 +362,7 @@ struct SendAmountView: View { } } } - .onChange(of: availableAmount, initial: true) { updateInputCap() } + .onChange(of: inputCapSats, initial: true) { updateInputCap() } .onChange(of: amountViewModel.maxExceededCount) { showMaxExceededToast() } } @@ -478,7 +501,7 @@ struct SendAmountView: View { private func updateInputCap() { // Don't cap when nothing is sendable, so the pad stays usable (Continue stays disabled instead). - amountViewModel.maxAmountOverride = availableAmount > 0 ? availableAmount : nil + amountViewModel.maxAmountOverride = inputCapSats > 0 ? inputCapSats : nil } private var fundingSourceMenu: some View { diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 86e528eb0a..5b616a7af3 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -139,6 +139,41 @@ final class PaykitRouteTests: XCTestCase { XCTAssertNil(PaykitRouteService.routeUi(for: usdtOnly, canRouteThroughSpark: true, canPayDirectly: false)) } + func testASparkWithdrawalIsWeighedAgainstSparksBalanceNotTheLightningLimit() { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + var quoted = route + quoted.serviceLeg = sparkLeg(amountSats: 999_000, feeSats: 500) + + // Lightning's limit of 997,506 sats never caps a withdrawal from Spark's 1,000,000. + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: route, amountSats: 999_000, sparkBalanceSats: 1_000_000), + true, + "continue asks spark for a quote" + ) + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: quoted, amountSats: 999_000, sparkBalanceSats: 1_000_000), + true, + "the quoted debit fits spark's balance" + ) + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: quoted, amountSats: 999_000, sparkBalanceSats: 999_499), + false, + "a debit past spark's balance can't be sent" + ) + XCTAssertNil( + PaykitRouteService.sparkWithdrawalValidity(route: route, amountSats: 1_000_001, sparkBalanceSats: 1_000_000), + "past spark's balance, lightning's limit decides" + ) + XCTAssertNil( + PaykitRouteService.sparkWithdrawalValidity( + route: PaykitRouteUi(endpoints: [onchain], offersSparkLeg: false), + amountSats: 999_000, + sparkBalanceSats: 1_000_000 + ), + "without a spark leg, lightning's limit decides" + ) + } + // MARK: - Contact withdrawal journal func testJournaledWithdrawalMatchesOnlyItsOwnAttempt() { From ec8daf97220fb85e17ff324ed6f77cc8f299497e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:02:24 +0100 Subject: [PATCH 47/64] fix: check a rerouted lnurl's minimum before confirm --- Bitkit/Services/PaykitRouteService.swift | 17 +++++++++ .../Views/Wallets/Send/SendAmountView.swift | 4 ++- BitkitTests/PaykitRouteTests.swift | 35 ++++++++++++++++--- 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index f2029554aa..911d110354 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -364,4 +364,21 @@ extension AppViewModel { accessibilityIdentifier: isBalanceShort ? "PaykitRouteBalanceToast" : "PaykitRouteNoneToast" ) } + + /// The route can restore an LNURL a BOLT11 pick cleared, so Amount checks its minimum after routing. + func validateRoutedLnurlMinimum(amountSats: UInt64) -> Bool { + guard let lnurlPayData else { return true } + let minimumAmount = max(1, lnurlPayData.minSendableSat) + guard amountSats < minimumAmount else { return true } + toast( + type: .error, + title: t("wallet__lnurl_pay__error_min__title"), + description: t( + "wallet__lnurl_pay__error_min__description", + variables: ["amount": CurrencyFormatter.formatSats(minimumAmount)] + ), + accessibilityIdentifier: "LnurlPayAmountTooLowToast" + ) + return false + } } diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index 2554e4e3be..b87d9d0a04 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -439,7 +439,9 @@ struct SendAmountView: View { return } - navigationPath.append(app.lnurlPayData != nil && app.scannedLightningInvoice == nil ? .lnurlPayConfirm : .confirm) + let paysLnurl = app.lnurlPayData != nil && app.scannedLightningInvoice == nil + guard !paysLnurl || app.validateRoutedLnurlMinimum(amountSats: amountSats) else { return } + navigationPath.append(paysLnurl ? .lnurlPayConfirm : .confirm) return } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 5b616a7af3..09da118233 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -575,7 +575,29 @@ final class PaykitRouteTests: XCTestCase { } @MainActor - private func openLightningContact() -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { + func testARerouteFromBolt11ToLnurlBelowItsMinimumShowsTheMinimumToast() async { + let (app, route, bolt11, lnurl) = openLightningContact(lnurlMinSendableMsats: 1_000_000) + defer { ToastWindowManager.shared.hideToast() } + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl, amountSats: 500) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value) + XCTAssertFalse(app.validateRoutedLnurlMinimum(amountSats: 500), "the restored LNURL's minimum must stop Confirm") + let toast = ToastWindowManager.shared.currentToast + XCTAssertEqual(toast?.accessibilityIdentifier, "LnurlPayAmountTooLowToast") + XCTAssertEqual(toast?.title, t("wallet__lnurl_pay__error_min__title")) + XCTAssertEqual(toast?.description, t( + "wallet__lnurl_pay__error_min__description", + variables: ["amount": CurrencyFormatter.formatSats(1000)] + )) + } + + @MainActor + private func openLightningContact(lnurlMinSendableMsats: UInt64 = 1000) -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { snapshotAppDefaultsDomain() let app = AppViewModel() let bolt11 = PaykitEndpoint( @@ -597,7 +619,7 @@ final class PaykitRouteTests: XCTestCase { app.lnurlPayData = LnurlPayData( uri: lightning.value, callback: "https://example.com/pay", - minSendable: 1000, + minSendable: lnurlMinSendableMsats, maxSendable: 100_000_000, metadataStr: "[]", commentAllowed: nil, @@ -609,10 +631,15 @@ final class PaykitRouteTests: XCTestCase { } @MainActor - private func routeDirectly(_ app: AppViewModel, _ route: PaykitRouteUi, to endpoint: PaykitEndpoint) async -> PaykitRouteOutcome { + private func routeDirectly( + _ app: AppViewModel, + _ route: PaykitRouteUi, + to endpoint: PaykitEndpoint, + amountSats: UInt64 = 2000 + ) async -> PaykitRouteOutcome { await app.routeContactPayment( route, - amountSats: 2000, + amountSats: amountSats, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0, From f0f06df5efb2cfa9ef20736b9a920f0a1c41ba9e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:16:33 +0100 Subject: [PATCH 48/64] fix: check a rerouted lnurl's maximum before confirm --- Bitkit/Services/PaykitRouteService.swift | 34 ++++++++++++------- .../Views/Wallets/Send/SendAmountView.swift | 2 +- BitkitTests/PaykitRouteTests.swift | 28 +++++++++++++-- 3 files changed, 47 insertions(+), 17 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 911d110354..a847d5720d 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -365,20 +365,28 @@ extension AppViewModel { ) } - /// The route can restore an LNURL a BOLT11 pick cleared, so Amount checks its minimum after routing. - func validateRoutedLnurlMinimum(amountSats: UInt64) -> Bool { - guard let lnurlPayData else { return true } + /// The route can restore an LNURL a BOLT11 pick cleared, so Amount checks its limits after routing. + func validateRoutedLnurlAmount(amountSats: UInt64) -> Bool { + guard let lnurlPayData, !lnurlPayData.accepts(amountSats: amountSats) else { return true } let minimumAmount = max(1, lnurlPayData.minSendableSat) - guard amountSats < minimumAmount else { return true } - toast( - type: .error, - title: t("wallet__lnurl_pay__error_min__title"), - description: t( - "wallet__lnurl_pay__error_min__description", - variables: ["amount": CurrencyFormatter.formatSats(minimumAmount)] - ), - accessibilityIdentifier: "LnurlPayAmountTooLowToast" - ) + if amountSats < minimumAmount { + toast( + type: .error, + title: t("wallet__lnurl_pay__error_min__title"), + description: t( + "wallet__lnurl_pay__error_min__description", + variables: ["amount": CurrencyFormatter.formatSats(minimumAmount)] + ), + accessibilityIdentifier: "LnurlPayAmountTooLowToast" + ) + } else { + toast( + type: .error, + title: t("wallet__lnurl_pay__error_max__title"), + description: t("wallet__lnurl_pay__error_max__description"), + accessibilityIdentifier: "LnurlPayAmountTooHighToast" + ) + } return false } } diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index b87d9d0a04..3ffb8d65f2 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -440,7 +440,7 @@ struct SendAmountView: View { } let paysLnurl = app.lnurlPayData != nil && app.scannedLightningInvoice == nil - guard !paysLnurl || app.validateRoutedLnurlMinimum(amountSats: amountSats) else { return } + guard !paysLnurl || app.validateRoutedLnurlAmount(amountSats: amountSats) else { return } navigationPath.append(paysLnurl ? .lnurlPayConfirm : .confirm) return } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 09da118233..e46c6b370f 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -586,7 +586,7 @@ final class PaykitRouteTests: XCTestCase { let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl, amountSats: 500) XCTAssertEqual(second, .direct) XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value) - XCTAssertFalse(app.validateRoutedLnurlMinimum(amountSats: 500), "the restored LNURL's minimum must stop Confirm") + XCTAssertFalse(app.validateRoutedLnurlAmount(amountSats: 500), "the restored LNURL's minimum must stop Confirm") let toast = ToastWindowManager.shared.currentToast XCTAssertEqual(toast?.accessibilityIdentifier, "LnurlPayAmountTooLowToast") XCTAssertEqual(toast?.title, t("wallet__lnurl_pay__error_min__title")) @@ -597,7 +597,29 @@ final class PaykitRouteTests: XCTestCase { } @MainActor - private func openLightningContact(lnurlMinSendableMsats: UInt64 = 1000) -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { + func testARerouteFromBolt11ToLnurlAboveItsMaximumShowsTheMaximumToast() async { + let (app, route, bolt11, lnurl) = openLightningContact(lnurlMaxSendableMsats: 3_000_000) + defer { ToastWindowManager.shared.hideToast() } + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl, amountSats: 4000) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value) + XCTAssertFalse(app.validateRoutedLnurlAmount(amountSats: 4000), "the restored LNURL's maximum must stop Confirm") + let toast = ToastWindowManager.shared.currentToast + XCTAssertEqual(toast?.accessibilityIdentifier, "LnurlPayAmountTooHighToast") + XCTAssertEqual(toast?.title, t("wallet__lnurl_pay__error_max__title")) + XCTAssertEqual(toast?.description, t("wallet__lnurl_pay__error_max__description")) + } + + @MainActor + private func openLightningContact( + lnurlMinSendableMsats: UInt64 = 1000, + lnurlMaxSendableMsats: UInt64 = 100_000_000 + ) -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { snapshotAppDefaultsDomain() let app = AppViewModel() let bolt11 = PaykitEndpoint( @@ -620,7 +642,7 @@ final class PaykitRouteTests: XCTestCase { uri: lightning.value, callback: "https://example.com/pay", minSendable: lnurlMinSendableMsats, - maxSendable: 100_000_000, + maxSendable: lnurlMaxSendableMsats, metadataStr: "[]", commentAllowed: nil, allowsNostr: false, From 238abe5795e5d5df4fed040e10b4e00560f006ab Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:39:59 +0100 Subject: [PATCH 49/64] fix: settle pending spark withdrawals and guard contact routing --- Bitkit/Managers/SparkManager.swift | 115 ++++++++++---- Bitkit/Services/PaykitRouteService.swift | 8 +- .../Wallets/Activity/ActivityItemView.swift | 2 +- .../Views/Wallets/Send/SendAmountView.swift | 26 +++- Bitkit/Views/Wallets/Send/SendSheet.swift | 8 +- BitkitTests/PaykitRouteTests.swift | 141 ++++++++++++++++++ BitkitTests/SparkWithdrawalTests.swift | 13 +- 7 files changed, 272 insertions(+), 41 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index d30b8582b6..39d1dbf236 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -577,23 +577,25 @@ final class SparkManager: ChannelFreeLightningRail { /// Whether `txid` is a Spark withdrawal, which LDK never held and so can't boost: one this app sent, to Savings or a /// contact, or one Spark lists. - func isSparkWithdrawal(txid: String) async -> Bool { + func isSparkWithdrawal(txid: String, isSent: Bool) async -> Bool { let known = sentWithdrawalTxIds.union(Self.contactWithdrawalTxIds).union(withdrawals.map(\.txid)) - if Self.isSparkWithdrawal(txid: txid, known: known, payments: []) { + if Self.isSparkWithdrawal(txid: txid, isSent: isSent, known: known, payments: []) { return true } guard isReady else { return false } do { let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments - return Self.isSparkWithdrawal(txid: txid, known: known, payments: payments) + return Self.isSparkWithdrawal(txid: txid, isSent: isSent, known: known, payments: payments) } catch { Logger.warn("Failed to list Spark payments for \(txid): \(error)", context: "SparkManager") return false } } - nonisolated static func isSparkWithdrawal(txid: String, known: Set, payments: [Payment]) -> Bool { - known.contains(txid) || payments.contains { payment in + nonisolated static func isSparkWithdrawal(txid: String, isSent: Bool, known: Set, payments: [Payment]) -> Bool { + // Only the sent side was Spark's; Savings owns the output a withdrawal to it pays, so its receipt can be boosted. + guard isSent else { return false } + return known.contains(txid) || payments.contains { payment in guard case let .withdraw(txId, _, _) = payment.details else { return false } return txId == txid } @@ -661,9 +663,12 @@ final class SparkManager: ChannelFreeLightningRail { let prepared: PrepareSendPaymentResponse let earlierPayments: [Payment] do { - guard Self.pendingContactWithdrawal == nil else { - throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") - } + try claimContactWithdrawal() + } catch { + throw SparkWithdrawalNotSent(underlying: error) + } + defer { releaseContactWithdrawalClaim() } + do { sdk = try await requireSdk() prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) if let maxFeeSats, case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod { @@ -688,8 +693,6 @@ final class SparkManager: ChannelFreeLightningRail { tags: tags, earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments) ) - isWithdrawingToContact = true - defer { isWithdrawingToContact = false } let journaled = pending try await Self.startJournaledWithdrawal( writeJournal: { @@ -709,20 +712,26 @@ final class SparkManager: ChannelFreeLightningRail { options: .bitcoinAddress(confirmationSpeed: .medium) )) } catch { - Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") - let failedAt = UInt64(Date().timeIntervalSince1970) - Task { - await Self.settleAfterFailedWithdrawal( - failedAt: failedAt, - syncWallet: { - _ = try await self.requireSdk().syncWallet(request: SyncWalletRequest()) - self.syncedThisRun = true - }, - hasSynced: { await self.hasSynced(after: $0) }, - settle: { await self.settleContactWithdrawal(allowClear: $0) } - ) - } - throw error + throw await Self.withdrawalSendFailure( + error, + closeUnsent: { + await Self.closeUnsentWithdrawal(journaled, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + }, + settleLater: { + let failedAt = UInt64(Date().timeIntervalSince1970) + Task { + await Self.settleAfterFailedWithdrawal( + failedAt: failedAt, + syncWallet: { + _ = try await self.requireSdk().syncWallet(request: SyncWalletRequest()) + self.syncedThisRun = true + }, + hasSynced: { await self.hasSynced(after: $0) }, + settle: { await self.settleContactWithdrawal(allowClear: $0) } + ) + } + } + ) } Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") pending.paymentId = response.payment.id @@ -734,6 +743,19 @@ final class SparkManager: ChannelFreeLightningRail { return try Self.sentWithdrawalId(response.payment) } + /// Claims the one contact withdrawal slot before anything awaits, so a second send started meanwhile is refused + /// instead of overwriting the first one's journal. + func claimContactWithdrawal() throws { + guard Self.pendingContactWithdrawal == nil, !isWithdrawingToContact else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") + } + isWithdrawingToContact = true + } + + func releaseContactWithdrawalClaim() { + isWithdrawingToContact = false + } + /// What `withdraw` returns for the payment Spark sent: its txid, or its id while Spark gives none yet. A withdrawal /// Spark returned as failed paid nothing, so the call ends as a refusal: the caller releases the request's proof, /// private list and allowance attempt and shows a failure, never a success. @@ -748,6 +770,25 @@ final class SparkManager: ChannelFreeLightningRail { return txId } + /// What a failed `sendPayment` of a journaled withdrawal means. A refusal Spark makes before anything reaches the + /// operators, as on the Lightning rail, closes the journal at once; an outcome that may have sent it stays journaled + /// and settles from the sync after it. + static func withdrawalSendFailure( + _ error: Error, + closeUnsent: () async -> Void, + settleLater: () -> Void + ) async -> Error { + let failure = sendPaymentFailure(error) + if failure is ChannelFreeRailSendRefused { + Logger.warn("Spark refused a withdrawal to a contact before sending it: \(error)", context: "SparkManager") + await closeUnsent() + return SparkWithdrawalNotSent(underlying: failure) + } + Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") + settleLater() + return error + } + /// Settles the open contact withdrawal from Spark's payments: its own payment, once Spark returned it, or else a /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear` (after a sync that /// succeeded), a list without one closes it as never sent and releases the request's proof, but only once the @@ -835,14 +876,29 @@ final class SparkManager: ChannelFreeLightningRail { } } + /// What an open withdrawal's journal does with the payment Spark returned or lists for it. Spark keeps a withdrawal + /// pending until the provider accepts its payout, and one it never accepts still fails, so only a completed one paid. + nonisolated static func settlement(of status: BreezSdkSpark.PaymentStatus) -> SparkWithdrawalSettlement { + switch status { + case .completed: .record + case .failed: .closeUnsent + case .pending: .wait + } + } + /// Writes the withdrawal's sent activity, tags and request proof, and closes the journal only once all of them are /// saved, so a failed or interrupted write is retried from the journal. private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { // A settle that raced this one already saved everything; its request's proof and allowance may be a retry's now. guard Self.isOpenJournal(pending) else { return } - guard payment.status != .failed else { + switch Self.settlement(of: payment.status) { + case .wait: + return + case .closeUnsent: await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) return + case .record: + break } Self.contactWithdrawalTxIds.insert(txId) let isDurable = await Self.recordWithdrawalLocally( @@ -1572,6 +1628,15 @@ enum SparkErrorCopy { /// A Spark withdrawal to a contact's on-chain address, journaled before it is sent. /// A contact withdrawal refused before its journal was written: nothing was sent. +enum SparkWithdrawalSettlement: Equatable { + /// Paid: its records are saved and its journal closes. + case record + /// Never paid: its journal closes as unsent, releasing what it started. + case closeUnsent + /// Still in flight: its journal stays open until Spark settles it. + case wait +} + struct SparkWithdrawalNotSent: Error { let underlying: Error } diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index a847d5720d..62e472d709 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -66,7 +66,8 @@ enum PaykitRouteService { return PaykitRouteUi(endpoints: endpoints, offersSparkLeg: offersSparkLeg) } - /// What the router is asked from `source`: Spending offers every endpoint, Savings only the on-chain ones. + /// What the router is asked from `source`: Spending offers every endpoint but an LNURL whose limits refuse the amount, + /// Savings only the on-chain ones. static func request( route: PaykitRouteUi, amountSats: UInt64, @@ -79,7 +80,7 @@ enum PaykitRouteService { case .spending: PaykitRouteRequest( amountSat: amountSats, - contactEndpoints: route.endpoints, + contactEndpoints: route.endpoints.filter { !$0.isLnurl || route.lnurl?.accepts(amountSats: amountSats) != false }, lightningSpendableSat: lightningSpendableSats, onchainSpendableSat: 0, serviceLegs: serviceLegs @@ -285,7 +286,8 @@ extension AppViewModel { (self.paykitRoute.map { $0.endpoints == route.endpoints } ?? true) } do { - let picked = try await router(route, amountSats, source, lightningSpendableSats, onchainSpendableSats) + // The known invoice and LNURL go to the router too, so it never picks an LNURL whose limits refuse the amount. + let picked = try await router(unrouted, amountSats, source, lightningSpendableSats, onchainSpendableSats) guard isCurrent() else { return .stale } switch picked { case let .direct(endpoint): diff --git a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift index 3d62f68496..821dd7d425 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift @@ -259,7 +259,7 @@ struct ActivityItemView: View { // Check if this is a CPFP child transaction if case let .onchain(activity) = viewModel.activity { isCpfpChild = await CoreService.shared.activity.isCpfpChildTransaction(txId: activity.txId, walletId: activity.walletId) - isSparkWithdrawal = await SparkManager.shared.isSparkWithdrawal(txid: activity.txId) + isSparkWithdrawal = await SparkManager.shared.isSparkWithdrawal(txid: activity.txId, isSent: activity.txType == .sent) } // Load boostTxIds doesExist status to determine RBF vs CPFP diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index 3ffb8d65f2..42dc012b3d 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -624,14 +624,8 @@ struct SendAmountView: View { conversionError = nil app.paykitUsesUsdt = source == .usdt switch source { - case .usdt: - hwSend.selectWallet(nil) - case .spending: + case .usdt, .spending, .savings: hwSend.selectWallet(nil) - app.selectedWalletToPayFrom = .lightning - case .savings: - hwSend.selectWallet(nil) - app.selectedWalletToPayFrom = .onchain case let .hardware(walletId): let balance = hwWalletManager.fundingBalance(walletId: walletId) let reserve = HwFundingSigner.feeReserve( @@ -643,11 +637,27 @@ struct SendAmountView: View { initialAvailableSats: balance > reserve ? balance - reserve : 0, showsLoading: true ) - app.selectedWalletToPayFrom = .onchain } + Self.selectWallet(of: source, app: app) updateFixedLightningAmount() } + /// Points the send at the wallet `source` pays from. A hardware wallet skips the router on Continue, so a Spark leg + /// routed for Spending is dropped here, as Confirm's own switch does. + static func selectWallet(of source: SendFundingSource, app: AppViewModel) { + switch source { + case .usdt: + break + case .spending: + app.selectedWalletToPayFrom = .lightning + case .savings: + app.selectedWalletToPayFrom = .onchain + case .hardware: + app.paykitRoute = SendConfirmationView.route(app.paykitRoute, afterSelecting: source) + app.selectedWalletToPayFrom = .onchain + } + } + private func updateFixedLightningAmount() { guard app.contactPaymentContext?.incomingPaymentRequest == nil, let amount = app.fixedLightningAmountSats else { return } amountViewModel.updateFromSats(amount, currency: currency) diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 074f79b77b..0cafa3a9d8 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -934,6 +934,12 @@ struct SendSheet: View { } } + /// Whether a request Savings and the hardware wallets can't cover is rejected before Confirm. One Spark can carry + /// reaches Confirm, which routes it from Spending, as a pure on-chain payment's check does. + static func rejectsUnfundedOnchainRequest(route: PaykitRouteUi?) -> Bool { + route?.offersSparkLeg != true + } + private func selectHardwareFundingSourceIfNeeded( amountSats: UInt64, requestId: PaykitPaymentRequest.ID @@ -1045,7 +1051,7 @@ struct SendSheet: View { // A failed estimate is not proof of insufficient funds. Keep the sheet open so the normal // confirmation path can retry instead of rejecting a payable request. - guard !hasUnavailableSource else { return true } + guard !hasUnavailableSource, Self.rejectsUnfundedOnchainRequest(route: app.paykitRoute) else { return true } let maximumAvailable = max(savingsAvailable ?? 0, hardwareSources.map(\.available).max() ?? 0) _ = validateOnchainBalanceAndDismissIfInsufficient( invoiceAmount: amountSats, diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index e46c6b370f..1462a292ba 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -455,6 +455,147 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(steps, ["journal", "proof started", "closed"], "The refusal closes the journal, releasing the started proof") } + func testAPendingWithdrawalStaysOpenUntilSparkAcceptsItsPayout() { + XCTAssertEqual( + SparkManager.settlement(of: .pending), + .wait, + "Spark keeps a withdrawal pending until the provider accepts its payout, and it can still fail" + ) + XCTAssertEqual(SparkManager.settlement(of: .completed), .record) + XCTAssertEqual(SparkManager.settlement(of: .failed), .closeUnsent) + } + + @MainActor + func testADefiniteSparkRefusalClosesTheWithdrawalAtOnce() async { + var steps: [String] = [] + let refused = await SparkManager.withdrawalSendFailure( + SdkError.InsufficientFunds(tokenIdentifier: nil), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertTrue(refused is SparkWithdrawalNotSent, "Spark picks leaves before anything reaches the operators") + XCTAssertEqual(steps, ["closed"], "A refusal releases the journal at once instead of after the expiry") + + steps = [] + let unknown = await SparkManager.withdrawalSendFailure( + SdkError.SparkError("operators"), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertFalse(unknown is SparkWithdrawalNotSent) + XCTAssertEqual(steps, ["settle later"], "An outcome that may have sent it settles from the sync after it") + } + + @MainActor + func testASecondContactWithdrawalIsRefusedWhileTheFirstPrepares() throws { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = nil + let spark = SparkManager.shared + try spark.claimContactWithdrawal() + defer { spark.releaseContactWithdrawalClaim() } + + XCTAssertThrowsError(try spark.claimContactWithdrawal(), "A second send must never overwrite the first one's journal") + spark.releaseContactWithdrawalClaim() + XCTAssertNoThrow(try spark.claimContactWithdrawal()) + } + + func testAnUnfundedRequestReachesConfirmWhileSparkCanCarryIt() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) + let direct = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: false)) + + XCTAssertFalse(SendSheet.rejectsUnfundedOnchainRequest(route: offered), "Confirm routes it from Spending through Spark") + XCTAssertTrue(SendSheet.rejectsUnfundedOnchainRequest(route: direct)) + XCTAssertTrue(SendSheet.rejectsUnfundedOnchainRequest(route: nil)) + } + + @MainActor + func testAHardwareWalletPickOnAmountDropsTheSparkLeg() { + snapshotAppDefaultsDomain() + let app = AppViewModel() + var routed = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + app.paykitRoute = routed + app.selectedWalletToPayFrom = .lightning + + SendAmountView.selectWallet(of: .hardware(walletId: "trezor"), app: app) + + XCTAssertEqual(app.selectedWalletToPayFrom, .onchain) + XCTAssertNil(app.paykitRoute?.serviceLeg, "Confirm must never describe the Spark leg for a hardware wallet's send") + XCTAssertEqual(app.paykitRoute?.endpoints, routed.endpoints) + + app.paykitRoute = routed + SendAmountView.selectWallet(of: .savings, app: app) + XCTAssertEqual(app.paykitRoute, routed, "Savings asks the router again on Continue") + } + + func testAnLnurlOutsideItsLimitsLeavesTheSparkLegToTheRouter() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true, lnurl: lnurlData(minSendableMsats: 5_000_000)) + let leg = sparkLeg(amountSats: 1000, feeSats: 2190) + + let below = PaykitRouteService.request( + route: route, + amountSats: 1000, + source: .spending, + lightningSpendableSats: 4000, + onchainSpendableSats: 0, + serviceLegs: [leg] + ) + XCTAssertEqual(below.contactEndpoints, [onchain], "An LNURL that refuses the amount must never win over the Spark leg") + + let within = PaykitRouteService.request( + route: route, + amountSats: 6000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + serviceLegs: [] + ) + XCTAssertEqual(within.contactEndpoints, [lightning, onchain]) + } + + @MainActor + func testTheRouterIsAskedWithTheLnurlItsLimitsComeFrom() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.lnurlPayData = lnurlData(minSendableMsats: 5_000_000) + app.selectedWalletToPayFrom = .lightning + var asked: PaykitRouteUi? + + _ = await app.routeContactPayment( + route, + amountSats: 1000, + source: .spending, + lightningSpendableSats: 4000, + onchainSpendableSats: 0, + request: nil + ) { route, _, _, _, _ in + asked = route + return .service(leg: self.sparkLeg(amountSats: 1000, feeSats: 2190)) + } + + XCTAssertEqual(asked?.lnurl, app.lnurlPayData, "The router must see the LNURL's limits") + } + + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { + LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: minSendableMsats, + maxSendable: 100_000_000, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + } + @MainActor func testARouteThatReturnsAfterItsPaymentChangedNeverLandsOnTheNextOne() async { snapshotAppDefaultsDomain() diff --git a/BitkitTests/SparkWithdrawalTests.swift b/BitkitTests/SparkWithdrawalTests.swift index 166ab522ee..4091cee0c3 100644 --- a/BitkitTests/SparkWithdrawalTests.swift +++ b/BitkitTests/SparkWithdrawalTests.swift @@ -308,12 +308,19 @@ final class SparkWithdrawalTests: XCTestCase { conversionDetails: nil ) - XCTAssertTrue(SparkManager.isSparkWithdrawal(txid: "contact", known: ["contact"], payments: [])) + XCTAssertTrue(SparkManager.isSparkWithdrawal(txid: "contact", isSent: true, known: ["contact"], payments: [])) XCTAssertTrue( - SparkManager.isSparkWithdrawal(txid: "listed", known: [], payments: [pending]), + SparkManager.isSparkWithdrawal(txid: "listed", isSent: true, known: [], payments: [pending]), "a pending withdrawal Spark lists can't be boosted" ) - XCTAssertFalse(SparkManager.isSparkWithdrawal(txid: "savings", known: ["contact"], payments: [pending])) + XCTAssertFalse(SparkManager.isSparkWithdrawal(txid: "savings", isSent: true, known: ["contact"], payments: [pending])) + } + + func testASparkWithdrawalsSavingsReceiptCanStillBeBoosted() { + XCTAssertFalse( + SparkManager.isSparkWithdrawal(txid: "transfer", isSent: false, known: ["transfer"], payments: []), + "Savings owns the output a Spark withdrawal pays it, so its receipt keeps CPFP" + ) } @MainActor From 412ddd736e317cf4a908451acd03f571fcb7e718 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:39:59 +0100 Subject: [PATCH 50/64] fix: offer the spark leg when lightning pays the lnurl minimum --- Bitkit/Services/PaykitRouteService.swift | 12 +-- Bitkit/ViewModels/AppViewModel.swift | 20 ++--- .../Views/Wallets/Send/SendAmountView.swift | 2 +- .../Wallets/Send/SendConfirmationView.swift | 2 +- BitkitTests/PaykitRouteTests.swift | 77 ++++++++++++++++--- 5 files changed, 79 insertions(+), 34 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 62e472d709..b3072f7042 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -51,18 +51,14 @@ enum PaykitRouteService { } /// The route for a contact payment, or nil without bitcoin endpoints. A Spark leg is offered to a contact with an - /// on-chain endpoint while Spark can route and the payment can't go directly over Lightning; a request it pays gets - /// its on-chain proof from the withdrawal's txid. - static func routeUi( - for context: ContactPaymentContext, - canRouteThroughSpark: Bool, - canPayDirectly: Bool - ) -> PaykitRouteUi? { + /// on-chain endpoint while Spark can route, whatever Lightning can pay, since the router still picks a direct payment + /// that works; a request it pays gets its on-chain proof from the withdrawal's txid. + static func routeUi(for context: ContactPaymentContext, canRouteThroughSpark: Bool) -> PaykitRouteUi? { let endpoints = context.endpoints .filter { $0.methodId != .usdtArbitrum } .map { PaykitEndpoint(methodId: $0.methodId.rawValue, value: $0.value) } guard !endpoints.isEmpty else { return nil } - let offersSparkLeg = canRouteThroughSpark && !canPayDirectly && endpoints.contains(where: \.isOnchain) + let offersSparkLeg = canRouteThroughSpark && endpoints.contains(where: \.isOnchain) return PaykitRouteUi(endpoints: endpoints, offersSparkLeg: offersSparkLeg) } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index b86db90633..1ba6248ba5 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -117,6 +117,7 @@ struct ScanPaymentOperations { let state: () -> ScanPaymentState let canSendLightning: (_ amountSats: UInt64) -> Bool var decodeInvoice: (String) async throws -> BitkitCore.Scanner = { try await decode(invoice: $0) } + var canRouteThroughSpark: @MainActor () -> Bool = { PaykitRouteService.canRouteThroughSpark } @MainActor static func live(lightningService: LightningService) -> ScanPaymentOperations { @@ -842,13 +843,11 @@ extension AppViewModel { isUsdtEnabled: SettingsViewModel.shared.isUsdtEnabled ) || context.incomingPaymentRequest.map { PaykitUsdtPaymentService.shared.hasBinding(for: $0.id) } == true selectedWalletToPayFrom = canUseLightning || (hasLightning && scannedOnchainInvoice == nil) ? .lightning : .onchain - // A Spark leg can pay the on-chain endpoint from Spending here too, when Lightning can't pay directly. - if !canUseLightning, scannedOnchainInvoice != nil, - let route = PaykitRouteService.routeUi( - for: context, - canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark, - canPayDirectly: false - ), route.offersSparkLeg + // A Spark leg can pay the on-chain endpoint from Spending here too, whatever Lightning can pay now: an amount + // entered later can pass Lightning's limit, and the router still picks a direct payment that works. + if scannedOnchainInvoice != nil, + let route = PaykitRouteService.routeUi(for: context, canRouteThroughSpark: scanPaymentOperations.canRouteThroughSpark()), + route.offersSparkLeg { paykitRoute = route // A request keeps its source here; its Confirm asks the router. @@ -1075,11 +1074,8 @@ extension AppViewModel { // An on-chain contact payment opens with Spending as a source while Spark can carry it there, whether or // not Savings covers it; Spending is the default when Savings holds no more than dust. if let context = contactPaymentContext, scope != .onchainPayments, - let route = PaykitRouteService.routeUi( - for: context, - canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark, - canPayDirectly: false - ), route.offersSparkLeg + let route = PaykitRouteService.routeUi(for: context, canRouteThroughSpark: scanPaymentOperations.canRouteThroughSpark()), + route.offersSparkLeg { handleScannedOnchainInvoice(invoice) paykitRoute = route diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index 42dc012b3d..5bf522324d 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -415,7 +415,7 @@ struct SendAmountView: View { } if !app.paykitUsesUsdt, let context = app.contactPaymentContext, - let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) + let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark) { switch await routePaykitPayment(route, request: context.incomingPaymentRequest) { case .leg: diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 19532db2f7..1ffe8834ea 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1443,7 +1443,7 @@ struct SendConfirmationView: View { if !sourceChanged { guard let request, routedIncomingRequestId != request.id else { return } } - guard let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: true) + guard let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark) else { return } let amountSats: UInt64 if let request { diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 1462a292ba..7b1b3d7353 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -114,7 +114,7 @@ final class PaykitRouteTests: XCTestCase { // MARK: - Spark leg offer - func testSparkLegIsOfferedForAnOnchainContactLightningCantPay() { + func testSparkLegIsOfferedForAnOnchainContactWhileSparkCanRoute() { let onchainOnly = ContactPaymentContext( publicKey: "contact", privatePaymentContext: nil, @@ -122,21 +122,17 @@ final class PaykitRouteTests: XCTestCase { ) XCTAssertEqual( - PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true, canPayDirectly: false)?.offersSparkLeg, + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true)?.offersSparkLeg, true ) XCTAssertEqual( - PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: false, canPayDirectly: false)?.offersSparkLeg, - false - ) - XCTAssertEqual( - PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true, canPayDirectly: true)?.offersSparkLeg, + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: false)?.offersSparkLeg, false ) let usdtOnly = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: [ Self.endpoint(.usdtArbitrum, "0x0000000000000000000000000000000000000001"), ]) - XCTAssertNil(PaykitRouteService.routeUi(for: usdtOnly, canRouteThroughSpark: true, canPayDirectly: false)) + XCTAssertNil(PaykitRouteService.routeUi(for: usdtOnly, canRouteThroughSpark: true)) } func testASparkWithdrawalIsWeighedAgainstSparksBalanceNotTheLightningLimit() { @@ -505,8 +501,8 @@ final class PaykitRouteTests: XCTestCase { privatePaymentContext: nil, endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] ) - let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) - let direct = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false, canPayDirectly: false)) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) + let direct = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false)) XCTAssertFalse(SendSheet.rejectsUnfundedOnchainRequest(route: offered), "Confirm routes it from Spending through Spark") XCTAssertTrue(SendSheet.rejectsUnfundedOnchainRequest(route: direct)) @@ -583,6 +579,63 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(asked?.lnurl, app.lnurlPayData, "The router must see the LNURL's limits") } + @MainActor + func testAContactWhoseLnurlMinimumLightningPaysStillOffersSparkPastTheLightningLimit() async throws { + snapshotAppDefaultsDomain() + let lnurl = LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: 1_000_000, + maxSendable: 2_000_000_000, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + let address = onchain.value + let app = AppViewModel( + sheetViewModel: SheetViewModel(), + navigationViewModel: NavigationViewModel(), + scanPaymentOperations: ScanPaymentOperations( + state: { + ScanPaymentState( + isNodeRunning: true, + spendableOnchainBalanceSats: 0, + totalLightningBalanceSats: 997_506, + hasChannels: false, + hasUsableChannels: false + ) + }, + canSendLightning: { $0 <= 997_506 }, + decodeInvoice: { value in + value == address + ? .onChain(invoice: OnChainInvoice(address: address, amountSatoshis: 0, label: nil, message: nil, params: nil)) + : .lnurlPay(data: lnurl) + }, + canRouteThroughSpark: { true } + ) + ) + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [ + Self.endpoint(.bitcoinLightningLnurl, lightning.value), + Self.endpoint(.regtestOnchainP2wpkh, address), + Self.endpoint(.usdtArbitrum, "0x1111111111111111111111111111111111111111"), + ] + ) + XCTAssertTrue(app.claimContactPaymentContext(context)) + + try await app.handleScannedData(lightning.value, claimedContactPaymentContext: context) + + XCTAssertEqual(app.lnurlPayData, lnurl) + XCTAssertEqual( + app.paykitRoute?.offersSparkLeg, + true, + "Lightning pays the LNURL's minimum, but a 999,000-sat payment past its 997,506 limit still needs Spark" + ) + } + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { LnurlPayData( uri: lightning.value, @@ -930,7 +983,7 @@ final class PaykitRouteTests: XCTestCase { privatePaymentContext: nil, endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] ) - let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) var routed = offered routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) @@ -948,7 +1001,7 @@ final class PaykitRouteTests: XCTestCase { privatePaymentContext: nil, endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] ) - var routed = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true, canPayDirectly: false)) + var routed = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) XCTAssertEqual( From 9f7afa9921b76a73b86a35a063fcc4258bd31172 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:58:01 +0100 Subject: [PATCH 51/64] fix: skip the spark quote when lightning pays a contact --- Bitkit/Services/PaykitRouteService.swift | 42 ++++++++++++++---------- BitkitTests/PaykitRouteTests.swift | 23 +++++++++++++ 2 files changed, 47 insertions(+), 18 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index b3072f7042..6bdc4a16d7 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -92,29 +92,33 @@ enum PaykitRouteService { } } - /// Asks the router how to pay `amountSats` from `source`, quoting a Spark leg to each on-chain endpoint first when - /// the route offers one. + /// Asks the router how to pay `amountSats` from `source`. The router pays directly before it weighs any leg, so a + /// Spark leg to each on-chain endpoint is quoted only when the route offers one and no balance pays. static func route( _ route: PaykitRouteUi, amountSats: UInt64, source: Source, lightningSpendableSats: UInt64, - onchainSpendableSats: UInt64 + onchainSpendableSats: UInt64, + quoteLegs: ([PaykitEndpoint], UInt64) async -> [ServiceRouteLeg] = { await sparkLegs(to: $0, amountSats: $1) } ) async throws -> PaykitRoute { - let serviceLegs = source == .spending && route.offersSparkLeg - ? await sparkLegs(to: route.onchainEndpoints, amountSats: amountSats) - : [] - return try paykitRoutePayment( - request: request( - route: route, - amountSats: amountSats, - source: source, - lightningSpendableSats: lightningSpendableSats, - onchainSpendableSats: onchainSpendableSats, - serviceLegs: serviceLegs - ), - network: Env.bitkitCoreNetwork - ) + func pick(_ serviceLegs: [ServiceRouteLeg]) throws -> PaykitRoute { + try paykitRoutePayment( + request: request( + route: route, + amountSats: amountSats, + source: source, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats, + serviceLegs: serviceLegs + ), + network: Env.bitkitCoreNetwork + ) + } + let direct = try pick([]) + guard case .none = direct, source == .spending, route.offersSparkLeg else { return direct } + let serviceLegs = await quoteLegs(route.onchainEndpoints, amountSats) + return serviceLegs.isEmpty ? direct : try pick(serviceLegs) } private static func sparkLegs(to endpoints: [PaykitEndpoint], amountSats: UInt64) async -> [ServiceRouteLeg] { @@ -265,7 +269,9 @@ extension AppViewModel { lightningSpendableSats: UInt64, onchainSpendableSats: UInt64, request: PaykitPaymentRequest?, - router: (PaykitRouteUi, UInt64, PaykitRouteService.Source, UInt64, UInt64) async throws -> PaykitRoute = PaykitRouteService.route + router: (PaykitRouteUi, UInt64, PaykitRouteService.Source, UInt64, UInt64) async throws -> PaykitRoute = { + try await PaykitRouteService.route($0, amountSats: $1, source: $2, lightningSpendableSats: $3, onchainSpendableSats: $4) + } ) async -> PaykitRouteOutcome { var unrouted = route unrouted.serviceLeg = nil diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 7b1b3d7353..846c1fcf28 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -636,6 +636,29 @@ final class PaykitRouteTests: XCTestCase { ) } + func testALightningPayableContactRoutesDirectWithoutASparkQuote() async throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + var quotes = 0 + + let direct = try await PaykitRouteService.route( + route, amountSats: 2000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0 + ) { _, _ in quotes += 1; return [] } + XCTAssertEqual(direct, .direct(endpoint: lightning)) + XCTAssertEqual(quotes, 0, "Spark's quote is never fetched for a payment Lightning makes") + + let leg = sparkLeg(amountSats: 60000, feeSats: 300) + let routed = try await PaykitRouteService.route( + route, amountSats: 60000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0 + ) { endpoints, amountSats in + quotes += 1 + XCTAssertEqual(endpoints, [self.onchain]) + XCTAssertEqual(amountSats, 60000) + return [leg] + } + XCTAssertEqual(routed, .service(leg: leg), "An amount past Lightning's limit still takes the quoted Spark leg") + XCTAssertEqual(quotes, 1) + } + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { LnurlPayData( uri: lightning.value, From 8f66a5dcc56fb8bb1674979be935af42f595ca0a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:58:02 +0100 Subject: [PATCH 52/64] fix: name the lnurl limit when no route pays a contact --- Bitkit/Services/PaykitRouteService.swift | 16 ++++++++++++--- BitkitTests/PaykitRouteTests.swift | 26 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 6bdc4a16d7..b1b2e59860 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -308,11 +308,15 @@ extension AppViewModel { case let .none(reason): Logger.warn("Found no Paykit route: '\(reason)'", context: "PaykitRoute") paykitRoute = unrouted - showNoPaykitRouteToast(isBalanceShort: PaykitRouteService.isBalanceShort( + let isBalanceShort = PaykitRouteService.isBalanceShort( amountSats: amountSats, lightningSpendableSats: lightningSpendableSats, onchainSpendableSats: onchainSpendableSats - )) + ) + // The router never saw an LNURL whose limits refuse the amount, so its limit says why. + if isBalanceShort || unrouted.lnurl.map({ validateLnurlAmount($0, amountSats: amountSats) }) != false { + showNoPaykitRouteToast(isBalanceShort: isBalanceShort) + } return .refused } } catch { @@ -371,7 +375,13 @@ extension AppViewModel { /// The route can restore an LNURL a BOLT11 pick cleared, so Amount checks its limits after routing. func validateRoutedLnurlAmount(amountSats: UInt64) -> Bool { - guard let lnurlPayData, !lnurlPayData.accepts(amountSats: amountSats) else { return true } + guard let lnurlPayData else { return true } + return validateLnurlAmount(lnurlPayData, amountSats: amountSats) + } + + /// Shows `lnurl`'s too-low or too-high toast when `amountSats` is outside its limits; true when it accepts it. + func validateLnurlAmount(_ lnurlPayData: LnurlPayData, amountSats: UInt64) -> Bool { + guard !lnurlPayData.accepts(amountSats: amountSats) else { return true } let minimumAmount = max(1, lnurlPayData.minSendableSat) if amountSats < minimumAmount { toast( diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 846c1fcf28..80eb21a5e2 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -659,6 +659,32 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(quotes, 1) } + @MainActor + func testANoneRouteNamesTheLnurlLimitTheAmountMissed() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.lnurlPayData = lnurlData(minSendableMsats: 1_000_000) + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [lightning], offersSparkLeg: false), + amountSats: 500, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "LnurlPayAmountTooLowToast", + "A contact with a working LNURL is payable, only not at this amount" + ) + } + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { LnurlPayData( uri: lightning.value, From a2d84a7585b67719cd6610bd4c3c6e616d487a4d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:58:03 +0100 Subject: [PATCH 53/64] fix: hold a pending spark withdrawal until spark completes it --- Bitkit/Managers/SparkManager.swift | 6 +++++- BitkitTests/PaykitRouteTests.swift | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 39d1dbf236..0f5eea0ab9 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -758,7 +758,8 @@ final class SparkManager: ChannelFreeLightningRail { /// What `withdraw` returns for the payment Spark sent: its txid, or its id while Spark gives none yet. A withdrawal /// Spark returned as failed paid nothing, so the call ends as a refusal: the caller releases the request's proof, - /// private list and allowance attempt and shows a failure, never a success. + /// private list and allowance attempt and shows a failure, never a success. One still pending can fail until the + /// provider accepts its payout, so the caller holds it as unknown, on the pending screen, until its journal settles. nonisolated static func sentWithdrawalId(_ payment: Payment) throws -> String { guard payment.status != .failed else { throw SparkWithdrawalNotSent(underlying: AppError( @@ -766,6 +767,9 @@ final class SparkManager: ChannelFreeLightningRail { debugMessage: "Spark returned withdrawal '\(payment.id)' as failed" )) } + guard payment.status == .completed else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "Spark withdrawal '\(payment.id)' is still pending") + } guard case let .withdraw(txId, _, _) = payment.details else { return payment.id } return txId } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 80eb21a5e2..84e1595230 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -685,6 +685,24 @@ final class PaykitRouteTests: XCTestCase { ) } + @MainActor + func testAPendingWithdrawalSendIsHeldUntilItsJournalSettles() { + var pending = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + pending.status = .pending + + XCTAssertThrowsError(try SparkManager.sentWithdrawalId(pending), "A pending withdrawal can still fail, so it never shows success") { + XCTAssertFalse($0 is SparkWithdrawalNotSent, "It may still pay, so its proof and allowance attempt stay") + XCTAssertEqual( + SendConfirmationView.serviceLegFailureRoute( + $0, + attempt: SparkWithdrawalAttempt(address: self.onchain.value, amountSats: 20000, requestId: nil), + routingCacheResetAttempted: false + ), + .sparkWithdrawalPending(SparkWithdrawalAttempt(address: self.onchain.value, amountSats: 20000, requestId: nil)) + ) + } + } + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { LnurlPayData( uri: lightning.value, From b2614727fbe01b18f89b3c483108a1a36069bd27 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:07:22 +0100 Subject: [PATCH 54/64] fix: route a mixed bitcoin contact through spark when no endpoint pays --- .../Utilities/PaymentNavigationHelper.swift | 6 +-- Bitkit/ViewModels/AppViewModel.swift | 17 ++++++- Bitkit/Views/Wallets/Send/SendSheet.swift | 4 +- BitkitTests/PaykitRouteTests.swift | 49 +++++++++++++++++++ 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/Bitkit/Utilities/PaymentNavigationHelper.swift b/Bitkit/Utilities/PaymentNavigationHelper.swift index cf5fcab780..b7ca2c3c28 100644 --- a/Bitkit/Utilities/PaymentNavigationHelper.swift +++ b/Bitkit/Utilities/PaymentNavigationHelper.swift @@ -50,7 +50,7 @@ struct PaymentNavigationHelper { sheetViewModel.showSheet(.send, data: SendConfig(view: route)) return } - if app.contactPaymentContext?.requiresAssetSelection == true { + if app.contactPaymentPicksSource { sheetViewModel.showSheet(.send, data: SendConfig(view: .amount)) return } @@ -117,7 +117,7 @@ struct PaymentNavigationHelper { spendStore: QuickPaySpendStore = .shared, coordinator: QuickPayPaymentCoordinator? = nil ) -> SendRoute? { - if app.contactPaymentContext?.requiresAssetSelection == true, app.paykitPaymentTerms == nil { + if app.contactPaymentPicksSource, app.paykitPaymentTerms == nil { return .amount } if let lnurlWithdrawData = app.lnurlWithdrawData { @@ -218,7 +218,7 @@ struct PaymentNavigationHelper { spendStore: QuickPaySpendStore = .shared, coordinator: QuickPayPaymentCoordinator? = nil ) -> SendRoute? { - if app.contactPaymentContext?.requiresAssetSelection == true { + if app.contactPaymentPicksSource { if app.paykitPaymentTerms == nil { return .amount } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 1ba6248ba5..6a1fae05a3 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -37,6 +37,12 @@ struct ContactPaymentContext: Equatable { incomingPaymentRequest.map { $0.amount.asset != .btc || $0.pricing.conversion != nil } == true } + /// An on-chain and a Lightning endpoint, between which the router picks, Spark's leg to the on-chain one included. + var hasMixedBitcoinEndpoints: Bool { + endpoints.contains { $0.methodId.onchainNetwork != nil } && + endpoints.contains { $0.methodId == .bitcoinLightningLnurl || $0.methodId == .bitcoinLightningBolt11 } + } + func initialUsdtSubscriptionPayment(at date: Date = Date()) -> PaykitRequestPricing.Payment? { guard isInitialSubscriptionPayment, let request = incomingPaymentRequest, request.billingPeriod != nil, Set(request.acceptedPaymentEndpointIdentifiers) == [PublicPaykitService.MethodId.usdtArbitrum.rawValue], @@ -769,6 +775,13 @@ extension AppViewModel { /// The method a send prices with. Spending with no Lightning payment to make funds the Spark leg to the on-chain /// endpoint, so it takes that endpoint's price, the one the leg and its proof pay. + /// Amount picks the source and the asset: for a contact that lists USDT or is priced in another asset, and for a mixed + /// Bitcoin contact while Spark can carry a leg, so an amount no Lightning endpoint takes still reaches the router. + var contactPaymentPicksSource: Bool { + guard let context = contactPaymentContext else { return false } + return context.requiresAssetSelection || (context.hasMixedBitcoinEndpoints && paykitRoute?.offersSparkLeg == true) + } + func paykitBitcoinMethod(for wallet: WalletType) -> PublicPaykitService.MethodId { if wallet == .lightning { // A routed Spark leg pays its on-chain endpoint, whatever Lightning endpoint the contact also has. @@ -817,7 +830,9 @@ extension AppViewModel { } } - if let context = claimedContactPaymentContext, context.requiresAssetSelection, scope != .onchainPayments { + if let context = claimedContactPaymentContext, scope != .onchainPayments, + context.requiresAssetSelection || context.hasMixedBitcoinEndpoints && scanPaymentOperations.canRouteThroughSpark() + { resetSendState(preservingContactPaymentContext: true, ownerID: sendPresentationID) expectedGeneration = sendStateGeneration for endpoint in context.endpoints where endpoint.methodId != .usdtArbitrum { diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 0cafa3a9d8..04a8de7f04 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -300,7 +300,7 @@ struct SendSheet: View { /// For onchain: only need node running. private var shouldShowSyncOverlay: Bool { if isPreparingRequest || hwSend.isActive || flow.isResumingAcceptedOrdinarySend || app.paykitUsesUsdt || - (app.contactPaymentContext?.requiresAssetSelection == true && currentRoot == .amount && flow.navigationPath.isEmpty) + (app.contactPaymentPicksSource && currentRoot == .amount && flow.navigationPath.isEmpty) { return false } @@ -761,7 +761,7 @@ struct SendSheet: View { return .ready } if app - .paykitUsesUsdt || (app.contactPaymentContext?.requiresAssetSelection == true && currentRoot == .amount && flow.navigationPath.isEmpty) + .paykitUsesUsdt || (app.contactPaymentPicksSource && currentRoot == .amount && flow.navigationPath.isEmpty) { flow.hasValidatedAfterSync = true return .ready diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 84e1595230..8edae0e7d6 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -703,6 +703,55 @@ final class PaykitRouteTests: XCTestCase { } } + @MainActor + func testAMixedBitcoinContactWithoutUsdtOpensOnAmountWithTheSparkLeg() async throws { + snapshotAppDefaultsDomain() + let lnurl = lnurlData(minSendableMsats: 5_000_000) + let address = onchain.value + let sheets = SheetViewModel() + let app = AppViewModel( + sheetViewModel: sheets, + navigationViewModel: NavigationViewModel(), + scanPaymentOperations: ScanPaymentOperations( + state: { + ScanPaymentState( + isNodeRunning: true, + spendableOnchainBalanceSats: 0, + totalLightningBalanceSats: 10000, + hasChannels: false, + hasUsableChannels: false + ) + }, + canSendLightning: { $0 <= 10000 }, + decodeInvoice: { value in + value == address + ? .onChain(invoice: OnChainInvoice(address: address, amountSatoshis: 0, label: nil, message: nil, params: nil)) + : .lnurlPay(data: lnurl) + }, + canRouteThroughSpark: { true } + ) + ) + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.bitcoinLightningLnurl, lightning.value), Self.endpoint(.regtestOnchainP2wpkh, address)] + ) + XCTAssertFalse(context.requiresAssetSelection) + XCTAssertTrue(app.claimContactPaymentContext(context)) + + try await app.handleScannedData(lightning.value, claimedContactPaymentContext: context) + PaymentNavigationHelper.openPaymentSheet( + app: app, + currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, + sheetViewModel: sheets + ) + + XCTAssertEqual(app.paykitRoute?.offersSparkLeg, true, "2,000 sats below the LNURL's 5,000 minimum can still go through Spark") + XCTAssertEqual(app.scannedOnchainInvoice?.address, address) + XCTAssertEqual(sheets.sendSheetItem?.initialRoute, .amount, "Amount picks the source, so the amount reaches the router") + } + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { LnurlPayData( uri: lightning.value, From 32b33794d22dc7af6a8f326e79f6bec78bfa3b69 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:33:15 +0100 Subject: [PATCH 55/64] fix: show the balance copy when spark's fee takes a contact payment past it --- Bitkit/Managers/SparkManager.swift | 40 +++++++++++++++---- Bitkit/Services/PaykitRouteService.swift | 51 +++++++++++++++++------- BitkitTests/PaykitRouteTests.swift | 36 +++++++++++++++++ 3 files changed, 105 insertions(+), 22 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 2cb7181c00..82cc48aacd 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -623,22 +623,42 @@ final class SparkManager: ChannelFreeLightningRail { /// A Paykit route that withdraws exactly `amountSats` to the contact's on-chain `endpoint` at medium speed, with /// Spark's fee on top, or nil while Spark cannot send it. bitkit-core's Paykit router weighs it against the contact's - /// other endpoints. + /// other endpoints. Throws `SparkLegUnaffordable` when the balance can't cover the amount and its fee. func withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: UInt64) async throws -> ServiceRouteLeg? { - guard isReady, balanceSats >= amountSats else { return nil } + guard isReady else { return nil } + guard balanceSats >= amountSats else { throw SparkLegUnaffordable(debitSats: amountSats, balanceSats: balanceSats) } let prepared = try await prepareSend(paymentRequest: endpoint.value, amountSats: amountSats) guard case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod else { throw AppError(message: "Unexpected Spark payment method", debugMessage: "\(prepared.paymentMethod)") } - let debitSats = Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) - guard !feeQuote.isEstimate, balanceSats >= debitSats else { return nil } + guard !feeQuote.isEstimate else { return nil } + return try Self.withdrawalRouteLeg( + endpoint: endpoint, + amountSats: amountSats, + fee: feeQuote.speedMedium, + validUntilUnix: feeQuote.expiresAt, + balanceSats: balanceSats + ) + } + + /// The leg that withdraws `amountSats` to `endpoint` with `fee` on top. Throws `SparkLegUnaffordable` when + /// `balanceSats` can't cover both. + nonisolated static func withdrawalRouteLeg( + endpoint: PaykitEndpoint, + amountSats: UInt64, + fee: SendOnchainSpeedFeeQuote, + validUntilUnix: UInt64, + balanceSats: UInt64 + ) throws -> ServiceRouteLeg { + let debitSats = withdrawalDebitSats(amountSats: amountSats, fee: fee) + guard balanceSats >= debitSats else { throw SparkLegUnaffordable(debitSats: debitSats, balanceSats: balanceSats) } return ServiceRouteLeg( - service: Self.routeService, + service: routeService, endpoint: endpoint, deliveredSat: amountSats, debitSat: debitSats, - atomicity: Self.routeAtomicity, - validUntilUnix: feeQuote.expiresAt + atomicity: routeAtomicity, + validUntilUnix: validUntilUnix ) } @@ -1655,6 +1675,12 @@ struct SparkWithdrawalNotSent: Error { let underlying: Error } +/// Spark's balance can't cover a contact withdrawal's amount and fee, so the route offers no Spark leg. +struct SparkLegUnaffordable: Error { + let debitSats: UInt64 + let balanceSats: UInt64 +} + struct SparkContactWithdrawal: Codable, Equatable { /// The Paykit request a withdrawal pays, and the identity its proof belongs to. struct PaykitRequest: Codable, Equatable { diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index b1b2e59860..29d3bddc3e 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -100,7 +100,7 @@ enum PaykitRouteService { source: Source, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64, - quoteLegs: ([PaykitEndpoint], UInt64) async -> [ServiceRouteLeg] = { await sparkLegs(to: $0, amountSats: $1) } + quoteLegs: ([PaykitEndpoint], UInt64) async throws -> [ServiceRouteLeg] = { try await sparkLegs(to: $0, amountSats: $1) } ) async throws -> PaykitRoute { func pick(_ serviceLegs: [ServiceRouteLeg]) throws -> PaykitRoute { try paykitRoutePayment( @@ -117,21 +117,34 @@ enum PaykitRouteService { } let direct = try pick([]) guard case .none = direct, source == .spending, route.offersSparkLeg else { return direct } - let serviceLegs = await quoteLegs(route.onchainEndpoints, amountSats) + let serviceLegs = try await quoteLegs(route.onchainEndpoints, amountSats) return serviceLegs.isEmpty ? direct : try pick(serviceLegs) } - private static func sparkLegs(to endpoints: [PaykitEndpoint], amountSats: UInt64) async -> [ServiceRouteLeg] { + /// Spark's leg to each of `endpoints`, from `quote`. Throws `SparkLegUnaffordable` when no leg is quoted and one + /// was dropped because Spark's balance can't cover the amount and its fee. + static func sparkLegs( + to endpoints: [PaykitEndpoint], + amountSats: UInt64, + quote: (PaykitEndpoint, UInt64) async throws -> ServiceRouteLeg? = { + try await SparkManager.shared.withdrawalRouteLeg(endpoint: $0, amountSats: $1) + } + ) async throws -> [ServiceRouteLeg] { var legs: [ServiceRouteLeg] = [] + var unaffordable: SparkLegUnaffordable? for endpoint in endpoints { do { - if let leg = try await SparkManager.shared.withdrawalRouteLeg(endpoint: endpoint, amountSats: amountSats) { + if let leg = try await quote(endpoint, amountSats) { legs.append(leg) } } catch { + unaffordable = unaffordable ?? error as? SparkLegUnaffordable Logger.warn("No Spark route to \(endpoint.methodId): \(error)", context: "PaykitRoute") } } + if legs.isEmpty, let unaffordable { + throw unaffordable + } return legs } @@ -282,6 +295,20 @@ extension AppViewModel { let generation = paykitRoutingGeneration // A dismissed or replaced payment, a newer routing request (a new amount or source) or a source picked since // makes the answer stale, so it never lands on what followed it. + // A short balance names itself first, then the limit of an LNURL that refused the amount (the router never saw + // it), then a Spark leg the balance can't cover with its fee. + func refuse(sparkLegShort: Bool) -> PaykitRouteOutcome { + paykitRoute = unrouted + let isBalanceShort = PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + ) + if isBalanceShort || unrouted.lnurl.map({ validateLnurlAmount($0, amountSats: amountSats) }) != false { + showNoPaykitRouteToast(isBalanceShort: isBalanceShort || sparkLegShort) + } + return .refused + } let isCurrent = { self.contactPaymentContext?.id == contactId && self.paykitRoutingGeneration == generation && (self.selectedWalletToPayFrom == .lightning) == (source == .spending) && @@ -307,18 +334,12 @@ extension AppViewModel { return .leg case let .none(reason): Logger.warn("Found no Paykit route: '\(reason)'", context: "PaykitRoute") - paykitRoute = unrouted - let isBalanceShort = PaykitRouteService.isBalanceShort( - amountSats: amountSats, - lightningSpendableSats: lightningSpendableSats, - onchainSpendableSats: onchainSpendableSats - ) - // The router never saw an LNURL whose limits refuse the amount, so its limit says why. - if isBalanceShort || unrouted.lnurl.map({ validateLnurlAmount($0, amountSats: amountSats) }) != false { - showNoPaykitRouteToast(isBalanceShort: isBalanceShort) - } - return .refused + return refuse(sparkLegShort: false) } + } catch let error as SparkLegUnaffordable { + Logger.warn("Found no Paykit route: \(error)", context: "PaykitRoute") + guard isCurrent() else { return .stale } + return refuse(sparkLegShort: true) } catch { Logger.error("Failed to route Paykit payment: \(error)", context: "PaykitRoute") guard isCurrent() else { return .stale } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 8edae0e7d6..33754a3c6c 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -685,6 +685,42 @@ final class PaykitRouteTests: XCTestCase { ) } + @MainActor + func testASparkLegItsFeeTakesPastTheBalanceShowsTheBalanceCopy() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let fee = SendOnchainSpeedFeeQuote(userFeeSat: 750, l1BroadcastFeeSat: 1440) + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 9000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { endpoints, amountSats in + try await PaykitRouteService.sparkLegs(to: endpoints, amountSats: amountSats) { endpoint, amountSats in + try SparkManager.withdrawalRouteLeg( + endpoint: endpoint, amountSats: amountSats, fee: fee, validUntilUnix: 0, balanceSats: 10000 + ) + } + } + } + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "PaykitRouteBalanceToast", + "Spark holds 10,000 but the 9,000 withdrawal takes 11,190 with its fee, so the balance is what falls short" + ) + } + @MainActor func testAPendingWithdrawalSendIsHeldUntilItsJournalSettles() { var pending = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) From aedeee5a41b55f571cd7cbaf02e2875240f6d102 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:26:59 +0100 Subject: [PATCH 56/64] fix: leave an open contact withdrawal off spark's transfers to savings --- Bitkit/Managers/SparkManager.swift | 6 ++++-- BitkitTests/PaykitRouteTests.swift | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 82cc48aacd..8e0c087b75 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1280,11 +1280,13 @@ final class SparkManager: ChannelFreeLightningRail { return unclaimed.filter { !claimedOutputs.contains("\($0.txid.lowercased()):\($0.vout)") } } - /// Spark's withdrawals to Savings, without the ones that paid contacts. + /// Spark's withdrawals to Savings, without the ones that paid contacts: those recorded as sent, and the open + /// journal's, which Spark keeps pending until its payout is accepted. nonisolated static func withdrawals(_ payments: [Payment]) -> [SparkWithdrawal] { let contactWithdrawals = contactWithdrawalTxIds + let journaledId = pendingContactWithdrawal.flatMap { matchingWithdrawal($0, in: payments)?.id } return payments.compactMap { payment in - guard payment.status != .failed, case let .withdraw(txId, _, _) = payment.details, + guard payment.status != .failed, payment.id != journaledId, case let .withdraw(txId, _, _) = payment.details, !contactWithdrawals.contains(txId) else { return nil } return SparkWithdrawal(txid: txId, amountSats: sats(payment.amount), feeSats: sats(payment.fees)) } diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 33754a3c6c..fa85265905 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -1303,6 +1303,29 @@ final class PaykitRouteTests: XCTestCase { ) } + func testSparkScreenWithdrawalsLeaveOutAPendingContactPayment() { + snapshotAppDefaultsDomain() + SparkManager.contactWithdrawalTxIds = [] + var toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + toContact.status = .pending + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + var journal = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1) + SparkManager.pendingContactWithdrawal = journal + + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "Before Spark returns it, the open journal's address and amount tell the contact payment apart" + ) + journal.paymentId = "contact" + SparkManager.pendingContactWithdrawal = journal + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "A contact payment Spark keeps pending is not a transfer to savings" + ) + } + private static func endpoint(_ methodId: PublicPaykitService.MethodId, _ value: String) -> PublicPaykitService.Endpoint { PublicPaykitService.Endpoint(methodId: methodId, value: value, min: nil, max: nil, rawPayload: value) } From 1a3a1799fc12b2280377865ec975c03f7b3f2104 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:36:03 +0100 Subject: [PATCH 57/64] fix: close a contact withdrawal spark refuses for a fee rise at once --- Bitkit/Managers/SparkManager.swift | 9 ++++++++- BitkitTests/PaykitRouteTests.swift | 11 +++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 8e0c087b75..1fd15f324e 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -807,7 +807,7 @@ final class SparkManager: ChannelFreeLightningRail { settleLater: () -> Void ) async -> Error { let failure = sendPaymentFailure(error) - if failure is ChannelFreeRailSendRefused { + if failure is ChannelFreeRailSendRefused || isWithdrawalFeeRise(error) { Logger.warn("Spark refused a withdrawal to a contact before sending it: \(error)", context: "SparkManager") await closeUnsent() return SparkWithdrawalNotSent(underlying: failure) @@ -817,6 +817,13 @@ final class SparkManager: ChannelFreeLightningRail { return error } + /// Spark refetches a withdrawal's quote near its expiry and refuses one whose fee rose past the prepared one at every + /// speed with this input error, before it withdraws (`affordable_speed` in the 0.28.0 SDK's `send/bitcoin_address.rs`). + nonisolated static func isWithdrawalFeeRise(_ error: Error) -> Bool { + guard case let SdkError.InvalidInput(message) = error else { return false } + return message.localizedCaseInsensitiveContains("onchain fee rose to") + } + /// Settles the open contact withdrawal from Spark's payments: its own payment, once Spark returned it, or else a /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear` (after a sync that /// succeeded), a list without one closes it as never sent and releases the request's proof, but only once the diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index fa85265905..958c5dbc06 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -472,6 +472,17 @@ final class PaykitRouteTests: XCTestCase { XCTAssertTrue(refused is SparkWithdrawalNotSent, "Spark picks leaves before anything reaches the operators") XCTAssertEqual(steps, ["closed"], "A refusal releases the journal at once instead of after the expiry") + steps = [] + let feeRose = await SparkManager.withdrawalSendFailure( + SdkError.InvalidInput( + "The onchain fee rose to 900 sats at the slowest speed, above the 500 sats quoted for this payment. Please re-prepare the payment." + ), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertTrue(feeRose is SparkWithdrawalNotSent, "Spark checks a refreshed quote's fee before it withdraws") + XCTAssertEqual(steps, ["closed"]) + steps = [] let unknown = await SparkManager.withdrawalSendFailure( SdkError.SparkError("operators"), From e24e37cc774268e0026d3fad1942cc575e51144b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:36:04 +0100 Subject: [PATCH 58/64] fix: refuse a spark contact leg while an earlier withdrawal settles --- .../Localization/en.lproj/Localizable.strings | 1 + Bitkit/Services/PaykitRouteService.swift | 28 +++++- BitkitTests/PaykitRouteSettlingTests.swift | 87 +++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 BitkitTests/PaykitRouteSettlingTests.swift diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 75355b37f1..a5d98f18bf 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1313,6 +1313,7 @@ "wallet__send_swap_route" = "Route"; "wallet__send_paykit_no_route__title" = "Can't pay this contact"; "wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_withdrawal_settling__description" = "An earlier withdrawal from your spending balance is still settling. Try again once it completes."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Paste Invoice"; "wallet__recipient_manual" = "Enter Manually"; diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 29d3bddc3e..44525342c1 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -93,7 +93,9 @@ enum PaykitRouteService { } /// Asks the router how to pay `amountSats` from `source`. The router pays directly before it weighs any leg, so a - /// Spark leg to each on-chain endpoint is quoted only when the route offers one and no balance pays. + /// Spark leg to each on-chain endpoint is quoted only when the route offers one and no balance pays. Spark takes one + /// contact withdrawal at a time, so while an earlier one's journal is open no leg is quoted and this throws + /// `SparkWithdrawalSettling`. static func route( _ route: PaykitRouteUi, amountSats: UInt64, @@ -117,6 +119,7 @@ enum PaykitRouteService { } let direct = try pick([]) guard case .none = direct, source == .spending, route.offersSparkLeg else { return direct } + guard SparkManager.pendingContactWithdrawal == nil else { throw SparkWithdrawalSettling() } let serviceLegs = try await quoteLegs(route.onchainEndpoints, amountSats) return serviceLegs.isEmpty ? direct : try pick(serviceLegs) } @@ -258,6 +261,9 @@ enum PaykitRouteService { } } +/// Only a Spark leg could pay, but an earlier contact withdrawal's journal is still open. +struct SparkWithdrawalSettling: Error {} + /// What asking the router did to a contact payment. enum PaykitRouteOutcome: Equatable { /// The send pays the endpoint the router picked. @@ -336,6 +342,26 @@ extension AppViewModel { Logger.warn("Found no Paykit route: '\(reason)'", context: "PaykitRoute") return refuse(sparkLegShort: false) } + } catch is SparkWithdrawalSettling { + Logger.warn("Found no Paykit route: an earlier Spark contact withdrawal is still settling", context: "PaykitRoute") + guard isCurrent() else { return .stale } + // A short balance and an LNURL limit name themselves first, as for any other refusal. + let lnurlRefuses = unrouted.lnurl.map { !$0.accepts(amountSats: amountSats) } ?? false + if lnurlRefuses || PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + ) { + return refuse(sparkLegShort: false) + } + paykitRoute = unrouted + toast( + type: .error, + title: t("wallet__send_paykit_no_route__title"), + description: t("wallet__send_paykit_withdrawal_settling__description"), + accessibilityIdentifier: "PaykitRouteSettlingToast" + ) + return .refused } catch let error as SparkLegUnaffordable { Logger.warn("Found no Paykit route: \(error)", context: "PaykitRoute") guard isCurrent() else { return .stale } diff --git a/BitkitTests/PaykitRouteSettlingTests.swift b/BitkitTests/PaykitRouteSettlingTests.swift new file mode 100644 index 0000000000..b6c6dc4e3f --- /dev/null +++ b/BitkitTests/PaykitRouteSettlingTests.swift @@ -0,0 +1,87 @@ +@testable import Bitkit +import BitkitCore +import Paykit +import XCTest + +final class PaykitRouteSettlingTests: XCTestCase { + private let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + + @MainActor + func testASparkLegIsRefusedWhileAnEarlierContactWithdrawalSettles() async { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = SparkContactWithdrawal( + address: "bcrt1qearlier", + amountSats: 5000, + contact: "earlier", + startedAt: 1 + ) + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let onchain = onchain + var quoted = false + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 9000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { _, amountSats in + quoted = true + return [ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: amountSats, + debitSat: amountSats + 300, + atomicity: "trusted", + validUntilUnix: 0 + )] + } + } + + XCTAssertEqual(outcome, .refused, "Spark takes one contact withdrawal at a time, so Confirm must not offer a second") + XCTAssertFalse(quoted, "No Spark leg is quoted while the earlier withdrawal's journal is open") + XCTAssertEqual(ToastWindowManager.shared.currentToast?.accessibilityIdentifier, "PaykitRouteSettlingToast") + } + + @MainActor + func testAShortBalanceNamesItselfBeforeASettlingWithdrawal() async { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = SparkContactWithdrawal( + address: "bcrt1qearlier", + amountSats: 5000, + contact: "earlier", + startedAt: 1 + ) + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 20000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { _, _ in [] } + } + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "PaykitRouteBalanceToast", + "No balance covers 20,000, whatever an earlier withdrawal does, as on Android" + ) + } +} From da90a393d7e6d36fa16f37d3b27fa41fe71cfa26 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:40:58 +0100 Subject: [PATCH 59/64] fix: keep confirm's first route refusal and block its payment --- .../Wallets/Send/SendConfirmationView.swift | 17 +++++++++------- BitkitTests/SendConfirmationViewTests.swift | 20 +++++++++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 1ffe8834ea..6831d797cd 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -625,7 +625,8 @@ struct SendConfirmationView: View { shouldAutomaticallyPay: shouldAutomaticallyPay, hasStartedAutomaticPayment: hasStartedAutomaticPayment, isSetupPending: isSetupPending, - isPreparingWallet: walletSwitchContext != nil + isPreparingWallet: walletSwitchContext != nil, + isRouteRefused: refusedRouteSource == app.selectedWalletToPayFrom ) else { return } hasStartedAutomaticPayment = true do { @@ -1002,6 +1003,7 @@ struct SendConfirmationView: View { private func submitPayment(isAutomatic: Bool = false) async throws { guard !isSubmittingPayment else { return } guard !requiresAmountReview, preparingRequest == nil, !isRequestSetupPending, walletSwitchContext == nil, + refusedRouteSource != app.selectedWalletToPayFrom, isAutomatic || !prepareRequestCoinsIfNeeded() else { throw CancellationError() } // An automatic payment settles the fee itself below. if !isAutomatic, isPreparingOnchainSend { @@ -1118,14 +1120,16 @@ struct SendConfirmationView: View { return walletType == .lightning && !hasLightningPayment && route.offersSparkLeg } - /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. + /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. A source the + /// router refused has nothing to pay, so it never starts. static func canStartAutomaticPayment( shouldAutomaticallyPay: Bool, hasStartedAutomaticPayment: Bool, isSetupPending: Bool, - isPreparingWallet: Bool + isPreparingWallet: Bool, + isRouteRefused: Bool = false ) -> Bool { - shouldAutomaticallyPay && !hasStartedAutomaticPayment && !isSetupPending && !isPreparingWallet + shouldAutomaticallyPay && !hasStartedAutomaticPayment && !isSetupPending && !isPreparingWallet && !isRouteRefused } static func requiresManualConfirmation(isAutomatic: Bool, isHardwarePayment: Bool) -> Bool { @@ -1479,9 +1483,8 @@ struct SendConfirmationView: View { onchainSpendableSats: source == .savings ? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, request: request ) - if sourceChanged { - refusedRouteSource = Self.refusedRouteSource(after: outcome, on: walletType, previous: refusedRouteSource) - } + // The first call when Confirm opens keeps a refusal too, so a request with no route offers no swipe. + refusedRouteSource = Self.refusedRouteSource(after: outcome, on: walletType, previous: refusedRouteSource) } /// A source the router refused on Confirm keeps the swipe off while it's selected, so nothing consumes the contact's diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 8c938d5c5a..a1aefad92c 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -68,6 +68,26 @@ final class SendConfirmationViewTests: XCTestCase { )) } + func testARouteRefusedWhenConfirmOpensKeepsTheSwipeAndTheAutomaticPaymentOff() { + // Confirm's first routing call keeps a refusal the way a source switch does. + let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) + + XCTAssertFalse(SendConfirmationView.canStartAutomaticPayment( + shouldAutomaticallyPay: true, + hasStartedAutomaticPayment: false, + isSetupPending: false, + isPreparingWallet: false, + isRouteRefused: refused == .lightning + ), "an automatic attempt must not pay a source the router refused") + XCTAssertTrue(SendConfirmationView.isSwipeDisabled( + walletType: .lightning, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .lightning + )) + } + func testAutomaticPaymentAwaitsFeeRateOnlyWhileItIsLoading() { XCTAssertTrue(SendConfirmationView.automaticPaymentAwaitsFeeRate(isFeeRateMissing: true, feeRateLoadFailed: false)) XCTAssertFalse(SendConfirmationView.automaticPaymentAwaitsFeeRate(isFeeRateMissing: true, feeRateLoadFailed: true)) From d1efd4f3969b3d0e43f455e2714764e4d902ba5d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:32:40 +0100 Subject: [PATCH 60/64] fix: re-route when the source changes on confirm A switch to Spending on Confirm now always asks the router for a contact a Spark leg can reach, also when a decoded invoice or LNURL is kept from an earlier Savings pick, so an amount past Lightning's limit goes through an affordable Spark withdrawal. A Direct LNURL pick there continues on the LNURL's own confirm, since Confirm has no LNURL send. --- .../Wallets/Send/SendConfirmationView.swift | 30 +++++++++++++------ BitkitTests/PaykitRouteTests.swift | 26 ++++++++++++---- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 6831d797cd..11760f5e9c 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -542,11 +542,7 @@ struct SendConfirmationView: View { walletSwitchContext = sendContext if skipNextSourceReroute { skipNextSourceReroute = false - } else if Self.sourceSwitchNeedsReroute( - route: app.paykitRoute, - walletType: app.selectedWalletToPayFrom, - hasLightningPayment: app.scannedLightningInvoice != nil || app.lnurlPayData != nil - ) { + } else if Self.sourceSwitchNeedsReroute(route: app.paykitRoute, walletType: app.selectedWalletToPayFrom) { Task { await routeContactPaymentOnConfirm(sourceChanged: true) } } } @@ -1110,14 +1106,15 @@ struct SendConfirmationView: View { } } - /// A source switch on Confirm needs the router only when it moves a Spark leg's send to Savings, or a send that has no - /// Lightning payment to Spending, where a Spark leg can carry it. The app's own switch to a leg's source asks nothing. - static func sourceSwitchNeedsReroute(route: PaykitRouteUi?, walletType: WalletType, hasLightningPayment: Bool) -> Bool { + /// A source switch on Confirm needs the router only when it moves a Spark leg's send to Savings, or any send to + /// Spending, where a Spark leg can carry it: a mixed contact paid from Savings keeps its decoded Lightning payment, + /// which can't pay past Lightning's limit. The app's own switch to a leg's source asks nothing. + static func sourceSwitchNeedsReroute(route: PaykitRouteUi?, walletType: WalletType) -> Bool { guard let route else { return false } if route.serviceLeg != nil { return walletType != .lightning } - return walletType == .lightning && !hasLightningPayment && route.offersSparkLeg + return walletType == .lightning && route.offersSparkLeg } /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. A source the @@ -1485,6 +1482,20 @@ struct SendConfirmationView: View { ) // The first call when Confirm opens keeps a refusal too, so a request with no route offers no swipe. refusedRouteSource = Self.refusedRouteSource(after: outcome, on: walletType, previous: refusedRouteSource) + if Self.reroutePaysLnurl( + outcome: outcome, + walletType: app.selectedWalletToPayFrom, + hasInvoice: app.scannedLightningInvoice != nil, + hasLnurl: app.lnurlPayData != nil + ) { + navigationPath.append(.lnurlPayConfirm) + } + } + + /// Confirm has no LNURL send, so a Direct LNURL pick from Spending pays on the LNURL's own confirm, as one picked on + /// Continue does. + static func reroutePaysLnurl(outcome: PaykitRouteOutcome, walletType: WalletType, hasInvoice: Bool, hasLnurl: Bool) -> Bool { + outcome == .direct && walletType == .lightning && hasLnurl && !hasInvoice } /// A source the router refused on Confirm keeps the swipe off while it's selected, so nothing consumes the contact's @@ -2623,3 +2634,4 @@ struct SendConfirmationView: View { } } } + diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 958c5dbc06..6ba7bdbb04 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -1150,12 +1150,26 @@ final class PaykitRouteTests: XCTestCase { var routed = offered routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) - XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .onchain, hasLightningPayment: false)) - XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .lightning, hasLightningPayment: false)) - XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning, hasLightningPayment: false)) - XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning, hasLightningPayment: true)) - XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .onchain, hasLightningPayment: false)) - XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain, hasLightningPayment: false)) + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .onchain)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .lightning)) + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .onchain)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain)) + } + + func testADirectLnurlPickOnConfirmPaysOnTheLnurlConfirm() { + XCTAssertTrue(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .lightning, hasInvoice: false, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .lightning, hasInvoice: true, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .leg, walletType: .lightning, hasInvoice: false, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .onchain, hasInvoice: false, hasLnurl: true)) + } + + /// A mixed contact paid directly from Savings keeps its decoded Lightning payment, so a switch to Spending must still + /// ask the router: over Lightning's limit only a Spark withdrawal pays it. + func testSourceSwitchToSpendingReroutesAMixedContactRoutedDirectFromSavings() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: route, walletType: .lightning)) } func testASparkRoutedConfirmCanMoveToAnotherSource() throws { From 313c683ebb90fe6c8f2cf9839da339ee11c81cee Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:32:40 +0100 Subject: [PATCH 61/64] fix: confirm a spark withdrawal from the chain Spark lists a withdrawal completed once its provider accepts the payout, before the payout transaction is broadcast or mined (spark-sdk 0.28.0, crates/spark/src/ssp/graphql/models.rs:187-209 and crates/breez-sdk/core/src/models/adaptors.rs:339-347). A contact withdrawal's activity now stays unconfirmed until Electrum lists its payout output in a block. --- Bitkit/Managers/SparkManager.swift | 66 ++++++++++++++++++-- BitkitTests/SparkWithdrawalTests.swift | 83 ++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 6 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index b2799110c6..2f0e3a03c2 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -962,9 +962,7 @@ final class SparkManager: ChannelFreeLightningRail { return await (try? CoreService.shared.activity.appendTags(toActivity: txId, tags)) != nil } ) - if payment.status == .completed { - await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) - } + Self.confirmMinedContactPayouts(Self.completedContactPayouts([payment], contactWithdrawals: [txId])) if isDurable { if let request = pending.request { await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) @@ -1248,9 +1246,65 @@ final class SparkManager: ChannelFreeLightningRail { for txId in Self.savingsTransferTxIds(unclaimed: unclaimed, payments: payments, contactWithdrawals: contactWithdrawals) { await CoreService.shared.activity.markOnchainActivityAsTransfer(txId: txId) } - for payment in payments where payment.status == .completed { - if case let .withdraw(txId, _, _) = payment.details, contactWithdrawals.contains(txId) { - await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: txId) + Self.confirmMinedContactPayouts(Self.completedContactPayouts(payments, contactWithdrawals: contactWithdrawals)) + } + + /// The output of a contact withdrawal's transaction that pays the contact. + struct ContactPayout: Equatable { + let txId: String + let vout: UInt32 + let address: String + } + + /// The payouts of the contact withdrawals Spark lists as completed. + nonisolated static func completedContactPayouts(_ payments: [Payment], contactWithdrawals: Set) -> [ContactPayout] { + payments.compactMap { payment in + guard payment.status == .completed, case let .withdraw(txId, vout, address) = payment.details, + contactWithdrawals.contains(txId) + else { return nil } + return ContactPayout(txId: txId, vout: vout, address: address) + } + } + + /// Looks the payouts up on chain off the refresh, so a slow Electrum server never holds a send that waits for it. + private static func confirmMinedContactPayouts(_ payouts: [ContactPayout]) { + guard !payouts.isEmpty else { return } + Task { + await confirmMinedPayouts( + payouts, + needsConfirmation: { txId in + await (try? CoreService.shared.activity.getOnchainActivityByTxId(txid: txId))?.confirmed == false + }, + unspentOutputs: { address in + try await OnChainHwService.shared.getAddressInfo( + address: address, + electrumUrl: OnChainHwService.getElectrumUrl(), + network: OnChainHwService.appDefaultCoinType + ).utxos + }, + markConfirmed: { await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: $0) } + ) + } + } + + /// Spark lists a withdrawal completed once its provider took the payout on, which can be before the payout transaction + /// is broadcast or mined, so a payout's activity is confirmed only once the chain lists its output in a block. An + /// output the contact already spent drops out of that list, so its activity then stays unconfirmed. + nonisolated static func confirmMinedPayouts( + _ payouts: [ContactPayout], + needsConfirmation: (String) async -> Bool, + unspentOutputs: (String) async throws -> [AccountUtxo], + markConfirmed: (String) async -> Void + ) async { + for payout in payouts { + guard await needsConfirmation(payout.txId) else { continue } + do { + let outputs = try await unspentOutputs(payout.address) + if outputs.contains(where: { $0.txid == payout.txId && $0.vout == payout.vout && $0.confirmations > 0 }) { + await markConfirmed(payout.txId) + } + } catch { + Logger.warn("Failed to look up the payout of Spark withdrawal '\(payout.txId)': \(error)", context: "SparkManager") } } } diff --git a/BitkitTests/SparkWithdrawalTests.swift b/BitkitTests/SparkWithdrawalTests.swift index 4091cee0c3..238a3250de 100644 --- a/BitkitTests/SparkWithdrawalTests.swift +++ b/BitkitTests/SparkWithdrawalTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import BitkitCore import BreezSdkSpark import XCTest @@ -323,6 +324,80 @@ final class SparkWithdrawalTests: XCTestCase { ) } + // MARK: - Payout confirmation + + /// Spark lists a withdrawal completed once its provider took the payout on, before it is mined, so only a payout + /// output the chain lists in a block confirms its activity. + func testACompletedContactWithdrawalIsConfirmedOnlyOnceThePayoutIsMined() async { + let payouts = SparkManager.completedContactPayouts( + [ + withdrawal(txId: "mined", status: .completed), + withdrawal(txId: "mempool", status: .completed), + withdrawal(txId: "unlisted", status: .completed), + withdrawal(txId: "pending", status: .pending), + withdrawal(txId: "savings", status: .completed), + ], + contactWithdrawals: ["mined", "mempool", "unlisted", "pending"] + ) + let marked = TxIds() + + await SparkManager.confirmMinedPayouts( + payouts, + needsConfirmation: { _ in true }, + unspentOutputs: { _ in [Self.output(txId: "mined", confirmations: 1), Self.output(txId: "mempool", confirmations: 0)] }, + markConfirmed: { await marked.insert($0) } + ) + + let confirmed = await marked.ids + XCTAssertEqual(confirmed, ["mined"], "a payout still in the mempool or not yet broadcast stays unconfirmed") + } + + func testAConfirmedContactWithdrawalIsNotLookedUpAgain() async { + let lookups = TxIds() + + await SparkManager.confirmMinedPayouts( + [SparkManager.ContactPayout(txId: "mined", vout: 0, address: "bcrt1qcontact")], + needsConfirmation: { _ in false }, + unspentOutputs: { address in + await lookups.insert(address) + return [] + }, + markConfirmed: { _ in } + ) + + let looked = await lookups.ids + XCTAssertTrue(looked.isEmpty) + } + + private func withdrawal(txId: String, status: BreezSdkSpark.PaymentStatus) -> BreezSdkSpark.Payment { + Payment( + id: txId, + paymentType: .send, + status: status, + amount: 20000, + fees: 300, + timestamp: 1, + method: .withdraw, + details: .withdraw(txId: txId, vout: 1, destinationAddress: "bcrt1qcontact"), + conversionDetails: nil + ) + } + + private static func output(txId: String, confirmations: UInt32) -> AccountUtxo { + AccountUtxo( + txid: txId, + vout: 1, + amount: 20000, + blockHeight: confirmations > 0 ? 100 : 0, + address: "bcrt1qcontact", + path: "", + confirmations: confirmations, + coinbase: false, + own: false, + required: nil + ) + } + @MainActor private func waitUntilPriced(_ transfer: TransferViewModel) async { for _ in 0 ..< 100 where transfer.isPricingSparkWithdrawal { @@ -359,3 +434,11 @@ private actor PriceGate { private final class WithdrawnFee { var feeSats: UInt64? } + +private actor TxIds { + private(set) var ids: [String] = [] + + func insert(_ id: String) { + ids.append(id) + } +} From 46ccee93ac0dbf4587028e26d5738bbaa08e75ed Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:32:40 +0100 Subject: [PATCH 62/64] fix: resolve an lnurl the router picks A route built after the scan, once Spark became ready, can hold a contact's LNURL that was never decoded. The router can pick it, so the pick now decodes it instead of refusing the payment. --- Bitkit/Services/PaykitRouteService.swift | 31 +++++++++++++++------- BitkitTests/PaykitRouteTests.swift | 33 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 44525342c1..79439a3a1f 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -290,7 +290,8 @@ extension AppViewModel { request: PaykitPaymentRequest?, router: (PaykitRouteUi, UInt64, PaykitRouteService.Source, UInt64, UInt64) async throws -> PaykitRoute = { try await PaykitRouteService.route($0, amountSats: $1, source: $2, lightningSpendableSats: $3, onchainSpendableSats: $4) - } + }, + decodeEndpoint: (String) async throws -> BitkitCore.Scanner = { try await decode(invoice: $0) } ) async -> PaykitRouteOutcome { var unrouted = route unrouted.serviceLeg = nil @@ -327,7 +328,7 @@ extension AppViewModel { switch picked { case let .direct(endpoint): paykitRoute = unrouted - guard await payDirectly(endpoint, route: unrouted) else { return .refused } + guard await payDirectly(endpoint, route: unrouted, decode: decodeEndpoint) else { return .refused } if let request { paykitPaymentTerms = try request.payment(using: paykitPaymentMethod) } @@ -375,8 +376,12 @@ extension AppViewModel { } /// Switches the send to exactly the endpoint the router picked, clearing the other Lightning one. An earlier pick may - /// have cleared the picked one, so it comes back from `route`. - private func payDirectly(_ endpoint: PaykitEndpoint, route: PaykitRouteUi) async -> Bool { + /// have cleared the picked one, so it comes back from `route`; one never decoded is decoded here. + private func payDirectly( + _ endpoint: PaykitEndpoint, + route: PaykitRouteUi, + decode: (String) async throws -> BitkitCore.Scanner + ) async -> Bool { if endpoint.isOnchain { selectedWalletToPayFrom = .onchain if scannedOnchainInvoice?.address != endpoint.value { @@ -386,12 +391,18 @@ extension AppViewModel { } selectedWalletToPayFrom = .lightning if endpoint.isLnurl { - guard let lnurl = lnurlPayData ?? route.lnurl else { - Logger.warn("Found no LNURL for the endpoint the router picked", context: "PaykitRoute") - showNoPaykitRouteToast(isBalanceShort: false) - return false + if let lnurl = lnurlPayData ?? route.lnurl { + lnurlPayData = lnurl + } else { + // A route built once Spark became ready after the scan holds the contact's LNURL undecoded. + guard case let .lnurlPay(data) = try? await decode(endpoint.value) else { + Logger.warn("Failed to decode the LNURL endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + lnurlPayData = data + paykitRoute?.lnurl = data } - lnurlPayData = lnurl scannedLightningInvoice = nil return true } @@ -400,7 +411,7 @@ extension AppViewModel { if let known { scannedLightningInvoice = known } else { - guard case let .lightning(invoice) = try? await decode(invoice: endpoint.value) else { + guard case let .lightning(invoice) = try? await decode(endpoint.value) else { Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "PaykitRoute") showNoPaykitRouteToast(isBalanceShort: false) return false diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index 6ba7bdbb04..b2fd031872 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -565,6 +565,39 @@ final class PaykitRouteTests: XCTestCase { XCTAssertEqual(within.contactEndpoints, [lightning, onchain]) } + /// A route built after the scan, once Spark became ready, holds a contact's LNURL that was never decoded; the router + /// can still pick it, so the pick decodes it. + @MainActor + func testAnLnurlTheRouterPicksWithoutDecodedDataIsDecoded() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + let decoded = lnurlData(minSendableMsats: 1000) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let lightning = lightning + var decodedValues: [String] = [] + + let outcome = await app.routeContactPayment( + route, + amountSats: 2000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil, + router: { _, _, _, _, _ in .direct(endpoint: lightning) }, + decodeEndpoint: { value in + decodedValues.append(value) + return .lnurlPay(data: decoded) + } + ) + + XCTAssertEqual(outcome, .direct) + XCTAssertEqual(decodedValues, [lightning.value]) + XCTAssertEqual(app.lnurlPayData, decoded) + XCTAssertEqual(app.paykitRoute?.lnurl, decoded, "a later pick reuses the decoded LNURL") + } + @MainActor func testTheRouterIsAskedWithTheLnurlItsLimitsComeFrom() async { snapshotAppDefaultsDomain() From c8d16ff493ce43bbc41108e448b56547ca92123c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:32:41 +0100 Subject: [PATCH 63/64] fix: show the request note on a spark leg Confirm's expanded details for a Spark leg now show the payment request's note, as the on-chain and Lightning details do. --- .../Wallets/Send/SendConfirmationView.swift | 48 ++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 11760f5e9c..7e9f632d8a 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -410,7 +410,7 @@ struct SendConfirmationView: View { if showDetails { if let route = app.paykitRoute, let totalFeeSat = route.totalFeeSat { - paykitRouteView(route, totalFeeSat: totalFeeSat) + paykitRouteView(route, totalFeeSat: totalFeeSat, note: oneOffPaymentRequestNote) } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { onchainView(invoice) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { @@ -769,7 +769,7 @@ struct SendConfirmationView: View { } } - func paykitRouteView(_ route: PaykitRouteUi, totalFeeSat: UInt64) -> some View { + func paykitRouteView(_ route: PaykitRouteUi, totalFeeSat: UInt64, note: String?) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { SendSectionView(t("wallet__send_from")) { @@ -826,6 +826,10 @@ struct SendConfirmationView: View { } } } + + if let note { + PaymentRequestInvoiceNote(note: note) + } } } @@ -2635,3 +2639,43 @@ struct SendConfirmationView: View { } } +#Preview("Spark leg with a request note") { + let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + let leg = ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: 20000, + debitSat: 22190, + atomicity: "trusted", + validUntilUnix: 0 + ) + ScrollView { + SendConfirmationView( + navigationPath: .constant([]), + isSubmittingPayment: .constant(false), + hwSend: HwSendCoordinator(walletId: nil), + requestPinCheck: { true }, + prepareIncomingPaymentRequest: {}, + routingCacheResetAttempted: false, + isAmountReviewRequired: .constant(false) + ) + .paykitRouteView( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true, serviceLeg: leg), + totalFeeSat: 2190, + note: "Dinner on Friday" + ) + .padding(16) + } + .background(Color.black) + .environmentObject(AppViewModel()) + .environmentObject(ActivityListViewModel()) + .environmentObject(ContactsManager()) + .environmentObject(CurrencyViewModel()) + .environmentObject(FeeEstimatesManager()) + .environmentObject(SettingsViewModel.shared) + .environmentObject(SheetViewModel()) + .environmentObject(WalletViewModel()) + .environmentObject(TagManager()) + .environment(HwWalletManager()) + .preferredColorScheme(.dark) +} From c2346f340d2e8de0194f9cc7a4935a0c9519a592 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:58:20 +0100 Subject: [PATCH 64/64] fix: match a spark withdrawal by its idempotency key --- Bitkit/Managers/SparkManager.swift | 27 ++++++++++++++++++--------- BitkitTests/PaykitRouteTests.swift | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 2f0e3a03c2..29386d23bc 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -716,7 +716,8 @@ final class SparkManager: ChannelFreeLightningRail { startedAt: UInt64(Date().timeIntervalSince1970), request: request, tags: tags, - earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments) + earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments), + idempotencyKey: UUID().uuidString.lowercased() ) let journaled = pending try await Self.startJournaledWithdrawal( @@ -734,7 +735,8 @@ final class SparkManager: ChannelFreeLightningRail { do { response = try await sdk.sendPayment(request: SendPaymentRequest( prepareResponse: prepared, - options: .bitcoinAddress(confirmationSpeed: .medium) + options: .bitcoinAddress(confirmationSpeed: .medium), + idempotencyKey: pending.idempotencyKey )) } catch { throw await Self.withdrawalSendFailure( @@ -834,9 +836,10 @@ final class SparkManager: ChannelFreeLightningRail { guard let pending = Self.pendingContactWithdrawal, !isWithdrawingToContact, let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments else { return } - if let payment = Self.matchingWithdrawal(pending, in: payments), case let .withdraw(txId, _, _) = payment.details { + let payment = Self.matchingWithdrawal(pending, in: payments) + if let payment, case let .withdraw(txId, _, _) = payment.details { await recordContactWithdrawal(payment, txId: txId, pending: pending) - } else if allowClear, Self.canCloseUnlisted(pending, now: now) { + } else if allowClear, Self.canCloseUnlisted(pending, listed: payment, now: now) { Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) } @@ -888,15 +891,19 @@ final class SparkManager: ChannelFreeLightningRail { nonisolated static let contactWithdrawalExpirySecs: UInt64 = 600 - /// An attempt Spark never returned nor listed is taken as unsent only after the expiry. - nonisolated static func canCloseUnlisted(_ pending: SparkContactWithdrawal, now: UInt64) -> Bool { - pending.paymentId == nil && now >= pending.startedAt + contactWithdrawalExpirySecs + /// An attempt Spark never returned nor listed is taken as unsent only after the expiry. Spark can list its payment + /// without withdrawal details while the payout may still go out, so only one it failed is unsent too. + nonisolated static func canCloseUnlisted(_ pending: SparkContactWithdrawal, listed: Payment? = nil, now: UInt64) -> Bool { + pending.paymentId == nil && (listed?.status ?? .failed) == .failed && now >= pending.startedAt + contactWithdrawalExpirySecs } + /// The attempt's own payment, by the id Spark returned or the idempotency key it keeps as the id, also while Spark + /// lists it without withdrawal details; else, for one Spark never returned, a new withdrawal to its address and amount. nonisolated static func matchingWithdrawal(_ pending: SparkContactWithdrawal, in payments: [Payment]) -> Payment? { - if let paymentId = pending.paymentId { - return payments.first { $0.id == paymentId } + if let ownId = pending.paymentId ?? pending.idempotencyKey, let own = payments.first(where: { $0.id == ownId }) { + return own } + guard pending.paymentId == nil else { return nil } let earlier = Set(pending.earlierPaymentIds ?? []) return payments.first { payment in !earlier.contains(payment.id) && withdrawalIds(to: pending.address, amountSats: pending.amountSats, in: [payment]) == [payment.id] @@ -1778,6 +1785,8 @@ struct SparkContactWithdrawal: Codable, Equatable { var earlierPaymentIds: [String]? /// This attempt's Spark payment, once Spark returned it. var paymentId: String? + /// The UUID the send passed as its idempotency key, which Spark keeps as the payment's id. + var idempotencyKey: String? } /// One contact withdrawal, which a pending send screen follows until its journal closes. diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index b2fd031872..39d557b917 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -213,6 +213,33 @@ final class PaykitRouteTests: XCTestCase { ) } + func testAWithdrawalSparkListsWithoutDetailsIsMatchedByItsKeyAndKeptOpen() { + let pending = SparkContactWithdrawal( + address: onchain.value, + amountSats: 20000, + contact: "contact", + startedAt: 1000, + idempotencyKey: "key" + ) + var listed = Self.withdrawal(id: "key", to: onchain.value, amountSats: 20000, timestamp: 1001) + listed.status = .pending + listed.details = nil + let past = 1000 + SparkManager.contactWithdrawalExpirySecs * 10 + + let matched = SparkManager.matchingWithdrawal(pending, in: [listed]) + XCTAssertEqual(matched?.id, "key", "Spark keeps the send's idempotency key as the payment's id") + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, listed: matched, now: past), + "A withdrawal Spark lists without its details may still pay out, so its journal stays open" + ) + + listed.status = .failed + XCTAssertTrue( + SparkManager.canCloseUnlisted(pending, listed: SparkManager.matchingWithdrawal(pending, in: [listed]), now: past), + "One Spark failed before it had withdrawal details never pays out" + ) + } + func testAFailedWithdrawalStaysOpenAfterASyncThatNeverReachedSpark() async { var allowedClears: [Bool] = [] // The sync call returns, but Spark keeps its failed sync in `lastSyncError`, so it never synced after the failure.