From c049acec62c0035c1d28994428e0bb30b17742b5 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Fri, 20 Nov 2026 16:33:44 -0500 Subject: [PATCH 1/6] feat: resume unfinished swaps until their claim confirms --- Bitkit/AppScene.swift | 3 + Bitkit/Services/PubkySwapsRouteService.swift | 124 +++++---- Bitkit/Services/PubkySwapsTracker.swift | 245 ++++++++++++++++++ Bitkit/Utilities/AppReset.swift | 1 + .../Wallets/Send/SendConfirmationView.swift | 27 +- BitkitTests/PubkySwapsTrackerTests.swift | 217 ++++++++++++++++ 6 files changed, 549 insertions(+), 68 deletions(-) create mode 100644 Bitkit/Services/PubkySwapsTracker.swift create mode 100644 BitkitTests/PubkySwapsTrackerTests.swift diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 0647db8fd0..732ea930f3 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1191,6 +1191,9 @@ struct AppScene: View { // Open the swap updates stream so any pending LN -> onchain swaps resume // and auto-claim once their lockup confirms. Retries until the stream starts. wallet.ensureSwapUpdatesRunning() + if PubkySwapsRouteService.isEnabled { + await PubkySwapsRouteService.resumeUnfinishedSwaps() + } // Schedule full backup after wallet create/restore to prevent epoch dates in backup status await BackupService.shared.scheduleFullBackup() diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift index e98da354cc..864f20c031 100644 --- a/Bitkit/Services/PubkySwapsRouteService.swift +++ b/Bitkit/Services/PubkySwapsRouteService.swift @@ -8,10 +8,11 @@ struct PaykitSwapRoute: Equatable { var providerName: String? } -/// How a swap's claim wait ended without a claim: bitkit-core failed the swap, or the wait ran out with the outcome -/// still open, when the provider may yet settle the hold invoice. +/// How a swap's claim wait ended without a claim: bitkit-core failed the swap, its hold payment failed so the provider +/// never funds it, or the wait ran out with the outcome still open, when the provider may yet settle the hold invoice. enum PubkySwapClaimError: Error { case failed(String) + case holdFailed case timedOut(Error) } @@ -20,12 +21,7 @@ enum PubkySwapClaimError: Error { /// 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 - /// How often a broadcast claim is advanced, so bitkit-core rebroadcasts it until it confirms. - private static let confirmationPollInterval: Duration = .seconds(30) - /// How long a swap is advanced in the background, after its claim broadcast or claim wait, before polling stops. - private static let confirmationTimeout: TimeInterval = 60 * 60 static var isEnabled: Bool { Env.isPubkySwapsRouteEnabled @@ -91,7 +87,7 @@ enum PubkySwapsRouteService { if !report.incompleteProviders.isEmpty { Logger.warn("Swap lists incomplete from \(report.incompleteProviders)", context: "PubkySwapsRoute") } - return (report.restored, report.known) + return await PubkySwapsTracker.shared.adoptRestored(restored: report.restored, known: report.known) } /// Providers come from the user's own graph: every contact is asked for its swap offer. bitkit-core caps the @@ -120,84 +116,82 @@ enum PubkySwapsRouteService { } } + /// Commits the quote and keeps its swap until its claim confirms or it fails, so a later start resumes it. static func commit(quoteId: String) async throws -> PubkySwapRoutePayment { let (mnemonic, passphrase) = try secrets() - return try await pubkySwapsCommitRoute( + let payment = try await pubkySwapsCommitRoute( quoteId: quoteId, electrumUrl: Env.electrumServerUrl, mnemonic: mnemonic, bip39Passphrase: passphrase ) + await PubkySwapsTracker.shared.didCommit(payment.swapId) + return payment + } + + /// Records the hold payment of a committed swap, so its failure stops the swap, also after a restart. + static func watchHold(swapId: String, paymentHash: String, invoice: String) async { + await PubkySwapsTracker.shared.watchHold(PubkySwapHoldPayment(paymentHash: paymentHash, invoice: invoice), swapId: swapId) + } + + /// Stops a swap whose hold payment failed or never went out: the provider never funds it. + static func dropFailedSwap(swapId: String) async { + Logger.info("Stopping Pubky Swaps route \(swapId) after its hold payment failed", context: "PubkySwapsRoute") + await PubkySwapsTracker.shared.drop(swapId) + } + + /// Advances each swap a closed app left unfinished until its claim confirms or it fails: the provider settles the + /// hold invoice once it sees the claim, so a claim that never confirms could leave the contact unpaid. + static func resumeUnfinishedSwaps() async { + await PubkySwapsTracker.shared.resume() + } + + static func resetForWipe() async { + await PubkySwapsTracker.shared.resetForWipe() } /// Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider /// settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the - /// background so bitkit-core rebroadcasts it until it confirms. + /// background until it confirms, so bitkit-core rebroadcasts it if it drops out of the mempool. /// A wait that runs out keeps advancing the swap in the background too, so it can still claim and settle the hold /// payment, and throws `PubkySwapClaimError.timedOut`. static func awaitClaim(swapId: String) async throws -> String { - do { - let txid = try await pollClaim(swapId: swapId, interval: pollInterval, timeout: claimTimeout, untilConfirmed: false) - advanceInBackground(swapId: swapId) - return txid - } catch let PubkySwapClaimError.timedOut(lastFailure) { - advanceInBackground(swapId: swapId) - throw PubkySwapClaimError.timedOut(lastFailure) - } + try await PubkySwapsTracker.shared.awaitClaim(swapId: swapId, timeout: claimTimeout) } - private static func advanceInBackground(swapId: String) { - Task.detached { - do { - let confirmed = try await pollClaim( - swapId: swapId, interval: confirmationPollInterval, timeout: confirmationTimeout, untilConfirmed: true - ) - Logger.info("Confirmed Pubky Swaps claim \(confirmed) for \(swapId)", context: "PubkySwapsRoute") - } catch { - Logger.warn("Failed to confirm Pubky Swaps claim for \(swapId): \(error)", context: "PubkySwapsRoute") - } - } + static func advance(swapId: String) async throws -> PubkySwapRouteState { + let (mnemonic, passphrase) = try secrets() + return try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase).state + } + + static func isUnknownSwap(_ error: Error) -> Bool { + guard case .NotFound? = error as? PubkySwapError else { return false } + return true } - private static func pollClaim( - swapId: String, - interval: Duration, - timeout: TimeInterval, - untilConfirmed: Bool - ) async throws -> String { - let deadline = Date().addingTimeInterval(timeout) - var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) - while true { - try Task.checkCancellation() - let (mnemonic, passphrase) = try secrets() - let state: PubkySwapRouteState? - do { - state = try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase).state - } catch { - // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. - Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(error)", context: "PubkySwapsRoute") - lastFailure = error - state = nil - } - switch state { - case let .claimed(txid)?: - return txid - case let .claimBroadcast(txid)? where !untilConfirmed: - return txid - case let .failed(reason)?: - throw PubkySwapClaimError.failed(reason) - case let state?: - Logger.debug("Pubky Swaps route \(swapId): \(state)", context: "PubkySwapsRoute") - lastFailure = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(state)") - case nil: - break - } - guard Date() < deadline else { throw PubkySwapClaimError.timedOut(lastFailure) } - try await Task.sleep(for: interval) + /// Whether the hold payment failed. It goes out over the node or the channel-free rail, which shares its hash, and + /// the rail decides a send the node failed. While the rail can't be asked, it counts as not failed. + static func isHoldPaymentFailed(_ hold: PubkySwapHoldPayment) async -> Bool { + let lightning = LightningService.shared + let nodeStatus = await lightning.listPayments()?.first { payment in + guard case let .bolt11(hash, _, _, _, _) = payment.kind else { return false } + return hash.caseInsensitiveCompare(hold.paymentHash) == .orderedSame + }?.status + if let nodeStatus, nodeStatus != .failed { + return false + } + guard let rail = lightning.channelFreeRail ?? lightning.channelFreePaymentHistory else { + return await lightning.channelFreeRailSupported() ? false : nodeStatus == .failed + } + do { + guard let railStatus = try await rail.lightningSendStatus(bolt11: hold.invoice) else { return nodeStatus == .failed } + return railStatus == .failed + } catch { + return false } } - private static func secrets() throws -> (String, String?) { + 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) } diff --git a/Bitkit/Services/PubkySwapsTracker.swift b/Bitkit/Services/PubkySwapsTracker.swift new file mode 100644 index 0000000000..9331744251 --- /dev/null +++ b/Bitkit/Services/PubkySwapsTracker.swift @@ -0,0 +1,245 @@ +import BitkitCore +import Foundation + +/// The hold payment of a committed swap: its hash, and its invoice, which the channel-free rail is asked about. +struct PubkySwapHoldPayment: Codable, Equatable { + let paymentHash: String + let invoice: String +} + +/// The swaps committed or restored whose claim has not confirmed, with the hold payment of each committed one, kept +/// across launches so each start resumes them. A wipe clears it with the rest of the app's defaults. +struct UnfinishedPubkySwapsStore { + static let swapIdsKey = "unfinishedPubkySwaps" + static let holdPaymentsKey = "pubkySwapHoldPayments" + + var defaults: UserDefaults = .standard + + var swapIds: [String] { + defaults.stringArray(forKey: Self.swapIdsKey) ?? [] + } + + func track(_ ids: [String]) { + var tracked = swapIds + for id in ids where !tracked.contains(id) { + tracked.append(id) + } + defaults.set(tracked, forKey: Self.swapIdsKey) + } + + func untrack(_ id: String) { + defaults.set(swapIds.filter { $0 != id }, forKey: Self.swapIdsKey) + var payments = holdPayments + payments[id] = nil + save(payments) + } + + func holdPayment(for id: String) -> PubkySwapHoldPayment? { + holdPayments[id] + } + + func setHoldPayment(_ payment: PubkySwapHoldPayment, for id: String) { + var payments = holdPayments + payments[id] = payment + save(payments) + } + + func clear() { + defaults.removeObject(forKey: Self.swapIdsKey) + defaults.removeObject(forKey: Self.holdPaymentsKey) + } + + private var holdPayments: [String: PubkySwapHoldPayment] { + guard let data = defaults.data(forKey: Self.holdPaymentsKey) else { return [:] } + return (try? JSONDecoder().decode([String: PubkySwapHoldPayment].self, from: data)) ?? [:] + } + + private func save(_ payments: [String: PubkySwapHoldPayment]) { + guard let data = try? JSONEncoder().encode(payments) else { return } + defaults.set(data, forKey: Self.holdPaymentsKey) + } +} + +/// Keeps each committed or restored swap advancing until its claim confirms or it fails, also after a restart: the +/// provider settles the hold invoice once it sees the claim, so a claim that never confirms could leave the contact +/// unpaid. +actor PubkySwapsTracker { + typealias Advance = @Sendable (_ swapId: String) async throws -> PubkySwapRouteState + typealias HoldPaymentCheck = @Sendable (PubkySwapHoldPayment) async -> Bool + + static let shared = PubkySwapsTracker( + advance: { try await PubkySwapsRouteService.advance(swapId: $0) }, + isHoldPaymentFailed: { await PubkySwapsRouteService.isHoldPaymentFailed($0) } + ) + + private let store: UnfinishedPubkySwapsStore + private let advance: Advance + private let isHoldPaymentFailed: HoldPaymentCheck + private let claimPollInterval: Duration + private let confirmationPollInterval: Duration + + /// Swaps a caller awaits the claim of, which no resume advances beside it. + private var claiming: Set = [] + /// The loop advancing each swap in the background, one per swap. + private var advancing: [String: Task] = [:] + /// Swaps this session committed, which the send flow drives, so a restore listing them leaves them alone. + private var committed: Set = [] + /// Swaps whose hold payment failed this session, which nothing advances again. + private var dropped: Set = [] + + init( + store: UnfinishedPubkySwapsStore = UnfinishedPubkySwapsStore(), + advance: @escaping Advance, + isHoldPaymentFailed: @escaping HoldPaymentCheck, + claimPollInterval: Duration = .seconds(2), + confirmationPollInterval: Duration = .seconds(30) + ) { + self.store = store + self.advance = advance + self.isHoldPaymentFailed = isHoldPaymentFailed + self.claimPollInterval = claimPollInterval + self.confirmationPollInterval = confirmationPollInterval + } + + var unfinishedSwapIds: [String] { + store.swapIds + } + + func isAdvancing(_ swapId: String) -> Bool { + advancing[swapId] != nil + } + + func didCommit(_ swapId: String) { + committed.insert(swapId) + store.track([swapId]) + } + + /// Recorded before the hold payment goes out, so a hold failing at any point stops the swap, also after a restart. + func watchHold(_ payment: PubkySwapHoldPayment, swapId: String) { + store.setHoldPayment(payment, for: swapId) + } + + /// Takes up the swaps a restore found. A swap committed or dropped this session is the send flow's, so the known + /// swaps returned leave it out. + func adoptRestored(restored: [String], known: [String]) -> (restored: [String], known: [String]) { + let known = known.filter { !committed.contains($0) && !dropped.contains($0) } + store.track(restored + known) + return (restored, known) + } + + /// Advances each swap a closed app left unfinished until its claim confirms or it fails. + func resume() { + for swapId in store.swapIds where !claiming.contains(swapId) { + advanceInBackground(swapId) + } + } + + /// Stops a swap whose hold payment failed or never went out: the provider never funds it, so advancing it would + /// only poll until bitkit-core gives up. + func drop(_ swapId: String) { + dropped.insert(swapId) + advancing.removeValue(forKey: swapId)?.cancel() + store.untrack(swapId) + } + + /// Stops the wiped wallet's swaps, so a wallet restored next starts from nothing. + func resetForWipe() { + advancing.values.forEach { $0.cancel() } + advancing.removeAll() + claiming.removeAll() + committed.removeAll() + dropped.removeAll() + store.clear() + } + + /// Advances the swap until bitkit-core broadcasts the claim, returning the claim txid, then keeps advancing it in the + /// background until the claim confirms. A wait that runs out, or a caller that stops waiting, leaves it advancing in + /// the background too, as the provider may still settle the hold payment. + func awaitClaim(swapId: String, timeout: TimeInterval) async throws -> String { + guard !dropped.contains(swapId) else { throw PubkySwapClaimError.holdFailed } + claiming.insert(swapId) + defer { claiming.remove(swapId) } + do { + let txid = try await pollClaim(swapId: swapId, interval: claimPollInterval, timeout: timeout, untilConfirmed: false) + advanceInBackground(swapId) + return txid + } catch let PubkySwapClaimError.timedOut(lastFailure) { + advanceInBackground(swapId) + throw PubkySwapClaimError.timedOut(lastFailure) + } catch is CancellationError { + advanceInBackground(swapId) + throw CancellationError() + } catch { + store.untrack(swapId) + throw error + } + } + + private func advanceInBackground(_ swapId: String) { + guard advancing[swapId] == nil, !dropped.contains(swapId) else { return } + advancing[swapId] = Task { await self.awaitConfirmation(swapId) } + } + + private func awaitConfirmation(_ swapId: String) async { + do { + let txid = try await pollClaim(swapId: swapId, interval: confirmationPollInterval, timeout: nil, untilConfirmed: true) + Logger.info("Confirmed Pubky Swaps claim \(txid) for \(swapId)", context: "PubkySwapsRoute") + } catch is CancellationError { + return + } catch { + if case PubkySwapClaimError.holdFailed = error { + dropped.insert(swapId) + } + Logger.warn("Failed to confirm Pubky Swaps claim for \(swapId): \(error)", context: "PubkySwapsRoute") + } + // A drop or a wipe that cancelled this loop already removed it. + guard !Task.isCancelled else { return } + advancing[swapId] = nil + store.untrack(swapId) + } + + private func pollClaim(swapId: String, interval: Duration, timeout: TimeInterval?, untilConfirmed: Bool) async throws -> String { + let deadline = timeout.map { Date().addingTimeInterval($0) } + var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) + while true { + try Task.checkCancellation() + // A swap whose hold failed, also while the app was closed or over Spark, is never funded. + if dropped.contains(swapId) { + throw PubkySwapClaimError.holdFailed + } + if untilConfirmed, let hold = store.holdPayment(for: swapId), await isHoldPaymentFailed(hold) { + throw PubkySwapClaimError.holdFailed + } + let state: PubkySwapRouteState? + do { + state = try await advance(swapId) + } catch { + // A swap bitkit-core has no record of, as one carried over by a backup, never advances. + if PubkySwapsRouteService.isUnknownSwap(error) { + throw error + } + // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. + Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(error)", context: "PubkySwapsRoute") + lastFailure = error + state = nil + } + switch state { + case let .claimed(txid)?: + return txid + case let .claimBroadcast(txid)? where !untilConfirmed: + return txid + case let .failed(reason)?: + throw PubkySwapClaimError.failed(reason) + case let state?: + Logger.debug("Pubky Swaps route \(swapId): \(state)", context: "PubkySwapsRoute") + lastFailure = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(state)") + case nil: + break + } + if let deadline, Date() >= deadline { + throw PubkySwapClaimError.timedOut(lastFailure) + } + try await Task.sleep(for: interval) + } + } +} diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index de1529e881..2b0f0cdea3 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -85,6 +85,7 @@ final class AppReset: WipeStepExecutor { VssStoreIdProvider.shared.clearCache() OnChainHwService.shared.stopAllWatchers() MoveToSparkManager.shared.resetForWipe() + await PubkySwapsRouteService.resetForWipe() // Before the paired devices are wiped, so a reconnect still running cannot save one back. try await Self.bounded("hardware wallets") { await Self.hardwareWallets?.resetForWipe() } do { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 72e9534ccf..88b8191fb4 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1560,6 +1560,15 @@ struct SendConfirmationView: View { startedPresentationID != nil && startedPresentationID == activePresentationID && quoteId == activeQuoteId } + /// A failed hold payment cancels the claim wait, or ends it as `holdFailed` when the swap stopped first. + static func endedOnHoldPaymentFailure(_ error: Error) -> Bool { + if error is CancellationError { + return true + } + guard case PubkySwapClaimError.holdFailed = error else { return false } + return true + } + /// Only a swap bitkit-core failed ends a sent hold payment for sure; any other claim error leaves it open. static func isDefiniteSwapFailure(_ error: Error) -> Bool { guard case PubkySwapClaimError.failed = error else { return false } @@ -1582,10 +1591,13 @@ struct SendConfirmationView: View { ) } var createdMetadataPaymentId: String? + // A swap whose hold payment never went out is never funded, so a failure before then stops it. + var unpaidSwapId: String? do { // The quote must deliver the amount the user confirmed. guard quote.deliveredSat == wallet.sendAmountSats else { throw PaykitPaymentRequestError.amountMismatch } let payment = try await PubkySwapsRouteService.commit(quoteId: quote.quoteId) + unpaidSwapId = payment.swapId Logger.info("Committed Pubky Swaps route \(payment.swapId) to \(payment.destinationAddress)", context: "SendConfirmation") guard case let .lightning(holdInvoice) = try await decode(invoice: payment.invoice) else { throw AppError(message: t("common__error_body"), debugMessage: "Swap hold invoice is not a Lightning invoice") @@ -1593,8 +1605,11 @@ struct SendConfirmationView: View { let paymentHash = holdInvoice.paymentHash.hex createdMetadataPaymentId = paymentHash await createPreActivityMetadata(paymentId: paymentHash, paymentHash: paymentHash) + // Recorded before the payment goes out, so a hold failing at any point stops the swap. + await PubkySwapsRouteService.watchHold(swapId: payment.swapId, paymentHash: paymentHash, invoice: payment.invoice) // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. _ = try await LightningService.shared.send(bolt11: payment.invoice) + unpaidSwapId = nil // The hold payment's tags stay with it from here. createdMetadataPaymentId = nil // The provider settles the hold payment once it sees the claim, so the send waits on it like a pending @@ -1606,6 +1621,9 @@ struct SendConfirmationView: View { driveSwapClaim(payment, paymentHash: paymentHash, contactPaymentContext: contactPaymentContext, isSendCurrent: isSendCurrent) } catch { Logger.error("Pubky Swaps route payment failed: \(error)", context: "SendConfirmation") + if let swapId = unpaidSwapId { + await PubkySwapsRouteService.dropFailedSwap(swapId: swapId) + } if let paymentId = createdMetadataPaymentId { try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentId) } @@ -1641,10 +1659,13 @@ struct SendConfirmationView: View { ) { let eventId = "swap-route-\(payment.swapId)" let claim = Task { try await PubkySwapsRouteService.awaitClaim(swapId: payment.swapId) } - // A failed hold payment ends the wait at once instead of polling the swap until the claim timeout. + // A failed hold payment stops the swap at once instead of polling it until the claim timeout. wallet.addOnEvent(id: eventId) { event in guard case let .paymentFailed(_, failedHash, _) = event, failedHash == paymentHash else { return } - claim.cancel() + Task { + await PubkySwapsRouteService.dropFailedSwap(swapId: payment.swapId) + claim.cancel() + } } Task { @MainActor in defer { wallet.removeOnEvent(id: eventId) } @@ -1655,7 +1676,7 @@ struct SendConfirmationView: View { await syncContactForActivity(paymentId: paymentHash, contactPaymentContext: contactPaymentContext) } catch { // A failed hold payment cancels the wait, and its tags go with it. - if error is CancellationError { + if Self.endedOnHoldPaymentFailure(error) { try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentHash) } guard Self.isDefiniteSwapFailure(error) else { diff --git a/BitkitTests/PubkySwapsTrackerTests.swift b/BitkitTests/PubkySwapsTrackerTests.swift new file mode 100644 index 0000000000..ea205dacc8 --- /dev/null +++ b/BitkitTests/PubkySwapsTrackerTests.swift @@ -0,0 +1,217 @@ +@testable import Bitkit +import BitkitCore +import XCTest + +final class PubkySwapsTrackerTests: XCTestCase { + private var defaults: UserDefaults! + private var suiteName: String! + + override func setUp() { + super.setUp() + suiteName = "PubkySwapsTrackerTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + super.tearDown() + } + + func testACommittedSwapIsKeptForTheNextLaunch() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingPayment)])) + await tracker.didCommit("swap") + XCTAssertEqual(store.swapIds, ["swap"]) + } + + func testResumeAdvancesUntilTheClaimConfirmsThenForgetsTheSwap() async throws { + let advance = ScriptedAdvance([.success(.claimBroadcast(txid: "tx")), .success(.claimBroadcast(txid: "tx")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 3) + } + + func testATransientAdvanceFailureKeepsAdvancing() async throws { + let advance = ScriptedAdvance([.failure(PubkySwapError.Transport(errorDetails: "offline")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 2) + } + + func testResumeForgetsAFailedSwapOrOneBitkitCoreDoesNotKnow() async throws { + let outcomes: [Result] = [ + .success(.failed(reason: "refunded")), + .failure(PubkySwapError.NotFound(errorDetails: "swap")), + ] + for outcome in outcomes { + let advance = ScriptedAdvance([outcome, .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 1) + } + } + + func testResumeStopsASwapWhoseHoldPaymentFailed() async throws { + let advance = ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))]) + let tracker = makeTracker(advance, isHoldPaymentFailed: { $0.paymentHash == "hash" }) + await tracker.didCommit("swap") + await tracker.watchHold(PubkySwapHoldPayment(paymentHash: "hash", invoice: "lnbcrt1"), swapId: "swap") + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + XCTAssertNil(store.holdPayment(for: "swap")) + let calls = await advance.calls + XCTAssertEqual(calls, 0) + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 1) + XCTFail("A swap whose hold failed is not awaited") + } catch PubkySwapClaimError.holdFailed {} + } + + func testDropStopsAdvancingAndForgetsTheSwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + await tracker.resume() + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertTrue(isAdvancing) + + await tracker.drop("swap") + + let isStillAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isStillAdvancing) + XCTAssertEqual(store.swapIds, []) + await tracker.resume() + let isAdvancingAgain = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancingAgain) + } + + func testAwaitClaimReturnsAtTheBroadcastAndKeepsAdvancingUntilConfirmed() async throws { + let advance = ScriptedAdvance([.success(.claimBroadcast(txid: "tx")), .success(.claimBroadcast(txid: "tx")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + await tracker.didCommit("swap") + + let txid = try await tracker.awaitClaim(swapId: "swap", timeout: 5) + + XCTAssertEqual(txid, "tx") + XCTAssertEqual(store.swapIds, ["swap"]) + try await waitUntilFinished(tracker, "swap") + } + + func testAwaitClaimThatRunsOutKeepsAdvancing() async throws { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 0) + XCTFail("The wait should run out") + } catch PubkySwapClaimError.timedOut {} + + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertTrue(isAdvancing) + XCTAssertEqual(store.swapIds, ["swap"]) + await tracker.resetForWipe() + } + + func testAwaitClaimForgetsAFailedSwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.failed(reason: "refunded"))])) + await tracker.didCommit("swap") + + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 5) + XCTFail("The swap failed") + } catch PubkySwapClaimError.failed {} catch { + XCTFail("Unexpected \(error)") + } + + XCTAssertEqual(store.swapIds, []) + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancing) + } + + func testRestoreLeavesTheSwapsThisSessionCommittedOrDroppedToTheSendFlow() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingPayment)])) + await tracker.didCommit("committed") + await tracker.didCommit("dropped") + await tracker.drop("dropped") + + let adopted = await tracker.adoptRestored(restored: ["restored"], known: ["committed", "dropped", "known"]) + + XCTAssertEqual(adopted.restored, ["restored"]) + XCTAssertEqual(adopted.known, ["known"]) + XCTAssertEqual(Set(store.swapIds), ["committed", "restored", "known"]) + } + + func testWipeStopsAndForgetsEverySwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + await tracker.watchHold(PubkySwapHoldPayment(paymentHash: "hash", invoice: "lnbcrt1"), swapId: "swap") + await tracker.resume() + + await tracker.resetForWipe() + + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancing) + XCTAssertEqual(store.swapIds, []) + XCTAssertNil(store.holdPayment(for: "swap")) + } + + // MARK: - Helpers + + private var store: UnfinishedPubkySwapsStore { + UnfinishedPubkySwapsStore(defaults: defaults) + } + + private func makeTracker( + _ advance: ScriptedAdvance, + isHoldPaymentFailed: @escaping @Sendable (PubkySwapHoldPayment) async -> Bool = { _ in false } + ) -> PubkySwapsTracker { + PubkySwapsTracker( + store: store, + advance: { _ in try await advance.next() }, + isHoldPaymentFailed: isHoldPaymentFailed, + claimPollInterval: .milliseconds(5), + confirmationPollInterval: .milliseconds(5) + ) + } + + private func waitUntilFinished(_ tracker: PubkySwapsTracker, _ swapId: String) async throws { + for _ in 0 ..< 400 { + let isAdvancing = await tracker.isAdvancing(swapId) + if !isAdvancing, !store.swapIds.contains(swapId) { + return + } + try await Task.sleep(for: .milliseconds(5)) + } + XCTFail("Swap \(swapId) still advancing") + } +} + +/// Answers each advance with the next scripted outcome, repeating the last one. +actor ScriptedAdvance { + private let outcomes: [Result] + private(set) var calls = 0 + + init(_ outcomes: [Result]) { + self.outcomes = outcomes + } + + func next() throws -> PubkySwapRouteState { + defer { calls += 1 } + return try outcomes[min(calls, outcomes.count - 1)].get() + } +} From cb1b8cadf40f50131ccb0bb04c3d58ea7a390219 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Wed, 2 Dec 2026 08:42:30 -0500 Subject: [PATCH 2/6] fix: keep a swap whose hold payment may still go out A hold payment whose send threw after Spark submitted it may still go out, so the swap now continues as paid: pending, with its claim driven and stopped if the hold payment fails. Only a refusal that proves nothing left the wallet drops the swap. --- .../Views/Wallets/Send/SendConfirmationView.swift | 14 +++++++++++++- BitkitTests/SendConfirmationViewTests.swift | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index b6bdaf15c6..04d4f876f8 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1688,6 +1688,12 @@ struct SendConfirmationView: View { return true } + /// Whether a hold payment whose send threw may still go out: only a refusal before submission, such as Spark's, proves + /// nothing left the wallet. + static func holdPaymentMayHaveLeft(_ error: Error) -> Bool { + !PaykitPaymentProofService.submissionSentNothing(error) + } + /// Only a swap bitkit-core failed ends a sent hold payment for sure; any other claim error leaves it open. static func isDefiniteSwapFailure(_ error: Error) -> Bool { guard case PubkySwapClaimError.failed = error else { return false } @@ -1727,7 +1733,13 @@ struct SendConfirmationView: View { // Recorded before the payment goes out, so a hold failing at any point stops the swap. await PubkySwapsRouteService.watchHold(swapId: payment.swapId, paymentHash: paymentHash, invoice: payment.invoice) // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. - _ = try await LightningService.shared.send(bolt11: payment.invoice) + do { + _ = try await LightningService.shared.send(bolt11: payment.invoice) + } catch let error where Self.holdPaymentMayHaveLeft(error) { + // Spark settles a send that failed once submitted at a later sync, so the swap is driven as paid: its hold + // payment failing stops it, and pending has no way back to a fresh quote that could pay the contact twice. + Logger.warn("Hold payment of Pubky Swaps route \(payment.swapId) may still go out: \(error)", context: "SendConfirmation") + } unpaidSwapId = nil // The hold payment's tags stay with it from here. createdMetadataPaymentId = nil diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 1960a7f72a..69f212b72c 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -378,6 +378,17 @@ final class SendConfirmationViewTests: XCTestCase { XCTAssertFalse(SendConfirmationView.isDefiniteSwapFailure(electrumError)) } + func testOnlyARefusalBeforeSubmissionStopsASwapHoldPayment() { + struct Lost: Error {} + XCTAssertFalse(SendConfirmationView.holdPaymentMayHaveLeft(Bitkit.ChannelFreeRailSendRefused(reason: "refused"))) + XCTAssertFalse(SendConfirmationView.holdPaymentMayHaveLeft(AppError(serviceError: .nodeNotStarted))) + XCTAssertTrue(SendConfirmationView.holdPaymentMayHaveLeft(Lost()), "Spark may have submitted it before the call failed") + XCTAssertTrue( + SendConfirmationView.holdPaymentMayHaveLeft(NodeError.DuplicatePayment(message: "pending")), + "An earlier attempt of the hold invoice is still in flight" + ) + } + func testASparkLegThatMayHaveSentStaysPendingInsteadOfOfferingTryAgain() { struct Refused: Error {} struct Lost: Error {} From 0c60dae7cbd4b39e9eba0942f7f028826cd90462 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Wed, 2 Dec 2026 08:43:07 -0500 Subject: [PATCH 3/6] fix: end claim waits that a wipe started before A wipe now ends a claim wait still running at its next step, and an answer that arrives after the wipe no longer restarts the background loop, which would advance the wiped wallet's swap with whatever seed is current. --- Bitkit/Services/PubkySwapsTracker.swift | 63 ++++++++++++++++++------ BitkitTests/PubkySwapsTrackerTests.swift | 22 +++++++++ 2 files changed, 70 insertions(+), 15 deletions(-) diff --git a/Bitkit/Services/PubkySwapsTracker.swift b/Bitkit/Services/PubkySwapsTracker.swift index 9331744251..6722929bf0 100644 --- a/Bitkit/Services/PubkySwapsTracker.swift +++ b/Bitkit/Services/PubkySwapsTracker.swift @@ -86,6 +86,8 @@ actor PubkySwapsTracker { private var committed: Set = [] /// Swaps whose hold payment failed this session, which nothing advances again. private var dropped: Set = [] + /// Counts wipes, so a claim wait started for a wiped wallet ends at its next step and its result advances nothing. + private var generation = 0 init( store: UnfinishedPubkySwapsStore = UnfinishedPubkySwapsStore(), @@ -142,8 +144,10 @@ actor PubkySwapsTracker { store.untrack(swapId) } - /// Stops the wiped wallet's swaps, so a wallet restored next starts from nothing. + /// Stops the wiped wallet's swaps, so a wallet restored next starts from nothing. A claim wait still running ends at + /// its next step, without advancing its swap in the background. func resetForWipe() { + generation += 1 advancing.values.forEach { $0.cancel() } advancing.removeAll() claiming.removeAll() @@ -157,17 +161,23 @@ actor PubkySwapsTracker { /// the background too, as the provider may still settle the hold payment. func awaitClaim(swapId: String, timeout: TimeInterval) async throws -> String { guard !dropped.contains(swapId) else { throw PubkySwapClaimError.holdFailed } + let started = generation claiming.insert(swapId) defer { claiming.remove(swapId) } do { - let txid = try await pollClaim(swapId: swapId, interval: claimPollInterval, timeout: timeout, untilConfirmed: false) + let txid = try await pollClaim( + swapId: swapId, generation: started, interval: claimPollInterval, timeout: timeout, untilConfirmed: false + ) advanceInBackground(swapId) return txid } catch let PubkySwapClaimError.timedOut(lastFailure) { advanceInBackground(swapId) throw PubkySwapClaimError.timedOut(lastFailure) } catch is CancellationError { - advanceInBackground(swapId) + // A swap of a wallet wiped since the wait began is no one's to advance. + if generation == started { + advanceInBackground(swapId) + } throw CancellationError() } catch { store.untrack(swapId) @@ -177,12 +187,15 @@ actor PubkySwapsTracker { private func advanceInBackground(_ swapId: String) { guard advancing[swapId] == nil, !dropped.contains(swapId) else { return } - advancing[swapId] = Task { await self.awaitConfirmation(swapId) } + let started = generation + advancing[swapId] = Task { await self.awaitConfirmation(swapId, generation: started) } } - private func awaitConfirmation(_ swapId: String) async { + private func awaitConfirmation(_ swapId: String, generation started: Int) async { do { - let txid = try await pollClaim(swapId: swapId, interval: confirmationPollInterval, timeout: nil, untilConfirmed: true) + let txid = try await pollClaim( + swapId: swapId, generation: started, interval: confirmationPollInterval, timeout: nil, untilConfirmed: true + ) Logger.info("Confirmed Pubky Swaps claim \(txid) for \(swapId)", context: "PubkySwapsRoute") } catch is CancellationError { return @@ -198,30 +211,50 @@ actor PubkySwapsTracker { store.untrack(swapId) } - private func pollClaim(swapId: String, interval: Duration, timeout: TimeInterval?, untilConfirmed: Bool) async throws -> String { + /// Ends work started for a wallet wiped since, as a wipe can land while it awaits. + private func checkNotWiped(since started: Int) throws { + guard generation == started else { throw CancellationError() } + } + + private func pollClaim( + swapId: String, + generation started: Int, + interval: Duration, + timeout: TimeInterval?, + untilConfirmed: Bool + ) async throws -> String { let deadline = timeout.map { Date().addingTimeInterval($0) } var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) while true { try Task.checkCancellation() + try checkNotWiped(since: started) // A swap whose hold failed, also while the app was closed or over Spark, is never funded. if dropped.contains(swapId) { throw PubkySwapClaimError.holdFailed } - if untilConfirmed, let hold = store.holdPayment(for: swapId), await isHoldPaymentFailed(hold) { - throw PubkySwapClaimError.holdFailed + if untilConfirmed, let hold = store.holdPayment(for: swapId) { + let holdFailed = await isHoldPaymentFailed(hold) + try checkNotWiped(since: started) + if holdFailed { + throw PubkySwapClaimError.holdFailed + } } - let state: PubkySwapRouteState? + var state: PubkySwapRouteState? + var advanceFailure: Error? do { state = try await advance(swapId) } catch { + advanceFailure = error + } + try checkNotWiped(since: started) + if let advanceFailure { // A swap bitkit-core has no record of, as one carried over by a backup, never advances. - if PubkySwapsRouteService.isUnknownSwap(error) { - throw error + if PubkySwapsRouteService.isUnknownSwap(advanceFailure) { + throw advanceFailure } // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. - Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(error)", context: "PubkySwapsRoute") - lastFailure = error - state = nil + Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(advanceFailure)", context: "PubkySwapsRoute") + lastFailure = advanceFailure } switch state { case let .claimed(txid)?: diff --git a/BitkitTests/PubkySwapsTrackerTests.swift b/BitkitTests/PubkySwapsTrackerTests.swift index ea205dacc8..fe89a544e4 100644 --- a/BitkitTests/PubkySwapsTrackerTests.swift +++ b/BitkitTests/PubkySwapsTrackerTests.swift @@ -170,6 +170,28 @@ final class PubkySwapsTrackerTests: XCTestCase { XCTAssertNil(store.holdPayment(for: "swap")) } + func testAWipeEndsAClaimWaitWithoutAdvancingItsSwapAgain() async throws { + let advance = ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))]) + let tracker = makeTracker(advance) + await tracker.didCommit("swap") + let wait = Task { try await tracker.awaitClaim(swapId: "swap", timeout: 5) } + try await Task.sleep(for: .milliseconds(20)) + + await tracker.resetForWipe() + + do { + _ = try await wait.value + XCTFail("A wipe ends the wait") + } catch is CancellationError {} + let callsAtWipe = await advance.calls + try await Task.sleep(for: .milliseconds(50)) + let callsLater = await advance.calls + XCTAssertEqual(callsLater, callsAtWipe, "Nothing advances the wiped wallet's swap") + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancing) + XCTAssertEqual(store.swapIds, []) + } + // MARK: - Helpers private var store: UnfinishedPubkySwapsStore { From 5c8a6bf08eb3661a07af98de72e9f5c970c84a67 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Wed, 2 Dec 2026 08:43:28 -0500 Subject: [PATCH 4/6] fix: back off a swap whose advance keeps failing The background loop now doubles its wait after each advance that failed in a row, up to 64 intervals (32 minutes at 30 seconds), and resets on any answer, so a swap whose Electrum server stays unreachable no longer retries every 30 seconds forever. A claim wait keeps its fixed interval. The test is jvsena42's. --- Bitkit/Services/PubkySwapsTracker.swift | 12 +++++++++++- BitkitTests/PubkySwapsTrackerTests.swift | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/PubkySwapsTracker.swift b/Bitkit/Services/PubkySwapsTracker.swift index 6722929bf0..88f1083447 100644 --- a/Bitkit/Services/PubkySwapsTracker.swift +++ b/Bitkit/Services/PubkySwapsTracker.swift @@ -225,6 +225,7 @@ actor PubkySwapsTracker { ) async throws -> String { let deadline = timeout.map { Date().addingTimeInterval($0) } var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) + var consecutiveFailures = 0 while true { try Task.checkCancellation() try checkNotWiped(since: started) @@ -255,6 +256,9 @@ actor PubkySwapsTracker { // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(advanceFailure)", context: "PubkySwapsRoute") lastFailure = advanceFailure + consecutiveFailures += 1 + } else { + consecutiveFailures = 0 } switch state { case let .claimed(txid)?: @@ -272,7 +276,13 @@ actor PubkySwapsTracker { if let deadline, Date() >= deadline { throw PubkySwapClaimError.timedOut(lastFailure) } - try await Task.sleep(for: interval) + try await Task.sleep(for: interval * Self.backoff(afterFailures: consecutiveFailures, untilConfirmed: untilConfirmed)) } } + + /// The background loop waits twice as long after each advance that failed in a row, as against an Electrum server + /// that stays unreachable, up to 64 intervals (32 minutes at 30 seconds). A claim wait keeps its interval. + static func backoff(afterFailures failures: Int, untilConfirmed: Bool) -> Int { + untilConfirmed ? 1 << min(failures, 6) : 1 + } } diff --git a/BitkitTests/PubkySwapsTrackerTests.swift b/BitkitTests/PubkySwapsTrackerTests.swift index fe89a544e4..fc3bec8bd1 100644 --- a/BitkitTests/PubkySwapsTrackerTests.swift +++ b/BitkitTests/PubkySwapsTrackerTests.swift @@ -47,6 +47,27 @@ final class PubkySwapsTrackerTests: XCTestCase { XCTAssertEqual(calls, 2) } + func testAnAdvanceThatKeepsFailingBacksOff() async throws { + let advance = ScriptedAdvance([.failure(PubkySwapError.Transport(errorDetails: "unreachable electrum"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + try await Task.sleep(for: .seconds(1)) + + let calls = await advance.calls + await tracker.resetForWipe() + // 1 s at a 5 ms interval: a loop that never backs off advances ~100+ times. + XCTAssertLessThanOrEqual(calls, 20, "advance called \(calls) times in 1 s while every call failed: no backoff") + } + + func testOnlyTheBackgroundLoopBacksOffAndAtMost64Intervals() { + XCTAssertEqual(PubkySwapsTracker.backoff(afterFailures: 0, untilConfirmed: true), 1) + XCTAssertEqual(PubkySwapsTracker.backoff(afterFailures: 3, untilConfirmed: true), 8) + XCTAssertEqual(PubkySwapsTracker.backoff(afterFailures: 40, untilConfirmed: true), 64) + XCTAssertEqual(PubkySwapsTracker.backoff(afterFailures: 3, untilConfirmed: false), 1) + } + func testResumeForgetsAFailedSwapOrOneBitkitCoreDoesNotKnow() async throws { let outcomes: [Result] = [ .success(.failed(reason: "refunded")), From fe22f8ec2b3ee4ac3cf21e0d8b4a61540e6938b3 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Wed, 2 Dec 2026 08:43:54 -0500 Subject: [PATCH 5/6] fix: resume unfinished swaps on every node start Swaps resumed only after the launch's activity sync, which can throw after the node starts, and the automatic retries see a running node, so a paid swap could wait for the next launch. The wallet now resumes them on every node start, before anything that can throw. --- Bitkit/AppScene.swift | 4 ---- Bitkit/ViewModels/WalletViewModel.swift | 6 ++++++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 73ffa8f687..d21deab3d5 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1193,10 +1193,6 @@ struct AppScene: View { guard !wipeCoordinator.isGateUp else { return } try await activity.syncLdkNodePayments() - if PubkySwapsRouteService.isEnabled { - await PubkySwapsRouteService.resumeUnfinishedSwaps() - } - // Schedule full backup after wallet create/restore to prevent epoch dates in backup status await BackupService.shared.scheduleFullBackup() } catch { diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index 723823c93c..e051bcd5f6 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -232,6 +232,12 @@ class WalletViewModel: ObservableObject { // A start that finished late does nothing more once a wipe is under way guard !isStartAdmissionClosedForWipe, !WipeCoordinator.shared.isGateUp else { return } + // Every node start resumes the unfinished swaps, before steps that can throw, such as the caller's activity sync: + // a paid swap is claimed only while the app advances it. + if PubkySwapsRouteService.isEnabled { + await PubkySwapsRouteService.resumeUnfinishedSwaps() + } + do { try await lightningService.disconnectIdlePeers() } catch { From 5a4240c0f06e3d4f54812901cf12c4234a5e55dc Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Wed, 2 Dec 2026 09:46:44 -0500 Subject: [PATCH 6/6] test: use the app AppError in the hold payment test The test target compiles its own copy of Errors.swift, so an unqualified AppError there is a type the app classifier does not recognize. --- BitkitTests/SendConfirmationViewTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 69f212b72c..4b43a7b5b1 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -381,7 +381,7 @@ final class SendConfirmationViewTests: XCTestCase { func testOnlyARefusalBeforeSubmissionStopsASwapHoldPayment() { struct Lost: Error {} XCTAssertFalse(SendConfirmationView.holdPaymentMayHaveLeft(Bitkit.ChannelFreeRailSendRefused(reason: "refused"))) - XCTAssertFalse(SendConfirmationView.holdPaymentMayHaveLeft(AppError(serviceError: .nodeNotStarted))) + XCTAssertFalse(SendConfirmationView.holdPaymentMayHaveLeft(Bitkit.AppError(serviceError: .nodeNotStarted))) XCTAssertTrue(SendConfirmationView.holdPaymentMayHaveLeft(Lost()), "Spark may have submitted it before the call failed") XCTAssertTrue( SendConfirmationView.holdPaymentMayHaveLeft(NodeError.DuplicatePayment(message: "pending")),