Skip to content

feat: resume unfinished swaps until their claim confirms - #1386

Open
coreyphillips wants to merge 1 commit into
masterfrom
feat/resume-unfinished-swaps
Open

coreyphillips wants to merge 1 commit into
masterfrom
feat/resume-unfinished-swaps

Conversation

@coreyphillips

Copy link
Copy Markdown
Contributor

Fixes #1262

Twin: synonymdev/bitkit-android#1923

Description

  • Committed and restored swaps are saved with their hold payment and advanced again on each start, until the claim confirms, the swap fails or bitkit-core no longer knows it. The background advance no longer stops after an hour, so the doc comments feat: resume unfinished swaps until their claim confirms #1262 names hold again.
  • A failed hold payment, on the node or Spark, stops the swap, also after a restart. A hold payment that never goes out drops it. A wipe clears them.

Out of Scope

Design

N/A: no UI changes.

Preview

N/A

QA Notes

Setup

A regtest debug build with PUBKY_SWAPS_ROUTES on, a reachable Pubky Swaps provider, and a contact with only an on-chain endpoint.

Journeys

N/A: not drivable; see Manual Tests.

Manual Tests

  • 1. Pay the contact through a swap, force quit before the claim, mine the lockup's confirmations, relaunch: the claim goes out and later confirms.
  • 2. regression: a swap whose hold payment fails is not advanced again after a relaunch.

Automated Checks

  • new 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

  • Manual tests not run.

@greptile-apps

greptile-apps Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The PR affects the Pubky Swaps payment workflow.

Fix uncertain-send cleanup and foreground waits surviving a wipe before merging.

Findings

  1. P1 Live swaps get forgotten ▶
  2. P1 Swap waits survive a wipe ▶

Summary

Saves unfinished Pubky swaps and their hold payments, then resumes them on wallet startup.

  • Unfinished Pubky Swaps routes resume until their claims confirm or end.
  • Failed or unsent hold payments stop their Pubky Swaps routes.

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
Loading

Reviews (1) · Last reviewed commit: "feat: resume unfinished swaps until thei..." · Reviewed by Greptile

Comment on lines +1624 to +1625
if let swapId = unpaidSwapId {
await PubkySwapsRouteService.dropFailedSwap(swapId: swapId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Live swaps get forgotten

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.

Comment on lines +146 to +152
func resetForWipe() {
advancing.values.forEach { $0.cancel() }
advancing.removeAll()
claiming.removeAll()
committed.removeAll()
dropped.removeAll()
store.clear()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Swap waits survive a wipe

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 talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_step reports Failed when 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 awaitClaim advancing one swap at once: resume() skips ids in claiming, and bitkit-core serialises advance_swap per swap id with advancing_lock anyway.
  • A wipe leaving a loop that re-tracks its swap: awaitConfirmation returns on cancellation before store.untrack, and resetForWipe clears both keys.
  • A swap bitkit-core does not know polling forever: store::load returns PubkySwapError::NotFound for a missing record, which pollClaim rethrows and the loop untracks.
  • Stale Spark failure dropping a swap retried over a channel: emitChannelFreeRailEvent filters isStaleFailure before the paymentFailed handler in driveSwapClaim sees 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread Bitkit/AppScene.swift
// and auto-claim once their lockup confirms. Retries until the stream starts.
wallet.ensureSwapUpdatesRunning()
if PubkySwapsRouteService.isEnabled {
await PubkySwapsRouteService.resumeUnfinishedSwaps()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: resume unfinished swaps until their claim confirms

3 participants