Repository navigation
feat: resume unfinished swaps until their claim confirms - #1386
coreyphillips wants to merge 1 commit into
Conversation
[Medium impact] The PR affects the Pubky Swaps payment workflow. Fix uncertain-send cleanup and foreground waits surviving a wipe before merging. FindingsSummarySaves unfinished Pubky swaps and their hold payments, then resumes them on wallet startup.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Commit swap] --> B[Save swap and hold payment]
B --> C[Send hold payment]
C -->|Returns| D[Wait for claim broadcast]
D --> E[Poll until claim confirms]
F[Wallet startup] --> E
E -->|Confirmed or failed| G[Forget swap]
C -->|Uncertain Spark error| H[Swap incorrectly forgotten]
I[Wallet wipe] --> J[Cancel background loops]
I --> K[Foreground wait remains active]
K --> E
Reviews (1) · Last reviewed commit: "feat: resume unfinished swaps until thei..." · Reviewed by Greptile |
| if let swapId = unpaidSwapId { | ||
| await PubkySwapsRouteService.dropFailedSwap(swapId: swapId) |
There was a problem hiding this comment.
LightningService.send can throw after Spark submits the hold payment. It marks that outcome as uncertain, but this catch drops the swap and deletes its saved hold payment. If Spark finishes the send later, subsequent launches no longer resume the swap. The contact stays unpaid while the sender's funds remain held until the payment expires.
Drop only sends known to have been refused before submission. Keep uncertain sends tracked.
| func resetForWipe() { | ||
| advancing.values.forEach { $0.cancel() } | ||
| advancing.removeAll() | ||
| claiming.removeAll() | ||
| committed.removeAll() | ||
| dropped.removeAll() | ||
| store.clear() |
There was a problem hiding this comment.
resetForWipe cancels only tasks in advancing. Clearing claiming does not stop an active awaitClaim, so a send or restore still waiting can keep calling advance during the wipe. On success or timeout, it can create another background loop with no timeout. Each advance reads the wallet's current seed.
Track and stop foreground waits too, and reject results from work started before the wipe so those waits cannot restart polling.
talosmachina
left a comment
There was a problem hiding this comment.
1 finding (P2). Keeps committed and restored Pubky Swaps routes advancing across launches until the claim confirms, and stops a swap whose hold payment failed. Reviewed c049ace, full tier, static: an auto review never builds a Bitkit app branch, so this is read from the code and CI.
What I checked, and 5 candidates I ruled out
Read in full: PubkySwapsTracker.swift, the PubkySwapsRouteService.swift diff, the SendConfirmationView.swift swap send and driveSwapClaim, AppScene.startWallet and restorePubkySwaps, LightningService.send(bolt11:)
Traced into bitkit-core 0.8.0-rc15 (045c7ff): pubky_swaps_advance / advance_swap, claim::next_step, store::load (the NotFound that isUnknownSwap keys on)
CI: SwiftFormat, validate and Greptile green; Run Tests, Run Integration Tests and build-local still pending at the time of this review
Ruled out
- Unbounded background loop now that the hour cap is gone:
next_stepreportsFailedwhen no lockup appears by the timeout and when the lockup is spent without the preimage, so a swap whose claim never confirms still ends. - A resumed loop and the send flow's
awaitClaimadvancing one swap at once:resume()skips ids inclaiming, and bitkit-core serialisesadvance_swapper swap id withadvancing_lockanyway. - A wipe leaving a loop that re-tracks its swap:
awaitConfirmationreturns on cancellation beforestore.untrack, andresetForWipeclears both keys. - A swap bitkit-core does not know polling forever:
store::loadreturnsPubkySwapError::NotFoundfor a missing record, whichpollClaimrethrows and the loop untracks. - Stale Spark failure dropping a swap retried over a channel:
emitChannelFreeRailEventfiltersisStaleFailurebefore thepaymentFailedhandler indriveSwapClaimsees it.
Merge confidence: 4/5, one P2 on a narrow path, and the unit and integration runs had not finished.
Reviewer model: claude-opus-5-5
Reasoning effort: Unknown (the run metadata available to this review does not carry it)
| } catch { | ||
| Logger.error("Pubky Swaps route payment failed: \(error)", context: "SendConfirmation") | ||
| if let swapId = unpaidSwapId { | ||
| await PubkySwapsRouteService.dropFailedSwap(swapId: swapId) |
There was a problem hiding this comment.
P2: a hold payment whose send threw may still go out, but the swap is dropped for good.
unpaidSwapId is cleared only after LightningService.shared.send(bolt11:) returns, so any throw from it drops the swap here. On the Spark path that send can throw after submission: the generic catch in LightningService.send (markRailSendUncertain, commented "A send that failed once submitted may still go out, so its outcome waits for a later sync") rethrows without proving nothing left. If that payment does land, the provider locks funds for a swap that is now in dropped and untracked in UnfinishedPubkySwapsStore, so neither this session nor the next launch's resume() advances it: no claim goes out, the contact is not paid, and the sender's funds stay held in the hold HTLC until the lockup times out.
The hold is already recorded by watchHold before the send, and isHoldPaymentFailed exists to settle exactly this question on the background loop. Dropping only on a refusal that proves nothing left (ChannelFreeRailSendRefused, or a throw before beforeSubmission ran) and otherwise leaving the swap tracked for the hold check would keep the PR's promise that a hold which never goes out is dropped while a hold that did is still claimed.
| // and auto-claim once their lockup confirms. Retries until the stream starts. | ||
| wallet.ensureSwapUpdatesRunning() | ||
| if PubkySwapsRouteService.isEnabled { | ||
| await PubkySwapsRouteService.resumeUnfinishedSwaps() |
There was a problem hiding this comment.
syncLdkNodePayments() can throw after the node starts. That skips swap recovery, and the automatic retries see a running node, so a paid swap can sit unclaimed until the next launch. Could we resume swaps on every successful node start, before syncing activity?
| /// 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) |
There was a problem hiding this comment.
Restoring a swap saves its ID, but drops the link to its hold payment. Restore can pick up a pending hold, so if it later fails, the tracker keeps advancing the swap even after a relaunch. Could we keep the hold payment association for restored swaps too?
Fixes #1262
Twin: synonymdev/bitkit-android#1923
Description
Out of Scope
paymentFailed.Design
N/A: no UI changes.
Preview
N/A
QA Notes
Setup
A regtest debug build with
PUBKY_SWAPS_ROUTESon, a reachable Pubky Swaps provider, and a contact with only an on-chain endpoint.Journeys
N/A: not drivable; see Manual Tests.
Manual Tests
Automated Checks
PubkySwapsTrackerTests.swift: a committed swap is kept for the next launch, resume advances until the claim confirms, transient failures keep it advancing, a failed, unknown or hold-failed swap is forgotten, restores leave this session's swaps to the send flow, and a wipe forgets every swap.Evidence
c049ace, iPhone 17 simulator, bitkit-core 0.8.0-rc15: SwiftFormat lint passes; the CI test selection passes (4,164 unit tests).Gaps