Skip to content

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

Open
coreyphillips wants to merge 7 commits into
masterfrom
feat/resume-unfinished-swaps
Open

coreyphillips wants to merge 7 commits 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 thread Bitkit/Services/PubkySwapsTracker.swift Resolved

@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)

Comment thread Bitkit/AppScene.swift Resolved
/// 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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, but the app can't make the link with today's bitkit-core: the restore report lists only swap IDs, and a swap rebuilt from a provider's listing keeps no hold invoice. bitkit-core can derive any swap's payment hash (record_payment_hash), so the fix is to return payment_hash_hex in PubkySwapRouteStatus; the tracker then records it on the first advance and checks the node's payment by hash (restore only adopts swaps whose payment the node sent). That needs a bitkit-core release, so it's tracked in synonymdev/bitkit-core#232. Leaving this open until it lands.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code scan at c049ace: one LOW inline (dev-gated). No double-claim, wrong-address or lost-funds path beyond the threads already open.

Checked and clean:

  • Double claim: bitkit-core serialises per swap (advancing_lock), saves the claim before broadcasting and rebroadcasts only a saved tx that spends the found lockup. resume() skips ids in claiming, and advanceInBackground is one task per id.
  • Destination: the app store holds only swap ids and the hold payment. The address comes from the core record, and resume passes none.
  • The hold-failure check returns true only when Spark reports failed for that invoice, or when the node lists it failed and Spark shows no send. A stopped node, an unconnected rail or a throwing rail all return false, and one swap sends its hold over one rail only.
  • Failed from next_step means no lockup at the timeout, a lockup spent without the preimage, or an unpublished claim too close to the timeout. A published claim is rebroadcast regardless, so untracking on failed does not abandon a claimable swap.
  • Kill points (before and after didCommit, mid-send, between the two untrack writes) leave nothing harmful. Wipe clears both keys, and cancelled loops return before untrack.
  • v3.1.1 has no Pubky Swaps code, so the two new UserDefaults keys have no earlier format.
  • synonymdev/bitkit-core#190 (Boltz removal) does not touch pubky_swaps. The neighbouring ensureSwapUpdatesRunning() line may conflict textually.

Addendum to the open AppScene.swift:1195 thread: node starts that bypass startWallet (retryWalletStart :1364, NodeStateView.swift:63,71, AppStatusView.swift:60,68, SendFailure.swift:178) also skip resume(), so the fix there should cover them.

The Android twin (synonymdev/bitkit-android#1923, merged) has the same uncapped background loop.

perf: relevant (polling now runs for the app's whole foreground lifetime per unfinished swap). To measure: Electrum connections and requests per minute per swap, Spark status calls per minute for a Spark-paid hold, and time from relaunch to claim broadcast.

Device gate (partial): c049ace — not run yet; a relaunch with an unfinished swap on regtest and the request rates above. Result to follow.

Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating and verifying; Fable 5.2 (claude-fable-5-2) primary review
Reasoning effort: Not exposed

Comment thread Bitkit/Services/PubkySwapsTracker.swift Resolved

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving at c049ace with the one LOW open (no backoff when advance keeps throwing). Fix it here or in a follow-up issue, your choice; please reply on the thread with which.

Device gate: c049ace — manual tests: 1 passed (3 runs), 2 passed (both variants); perf: 1 advance per 30 s per unfinished swap = about 2 Electrum connections and 6 requests per minute; unreachable Electrum: an advance attempt every 30–31 s with no backoff (the LOW); l10n: no UI text changed

  • Setup: debug build launched with PUBKY_SWAPS_ROUTES, the bitkit-docker pubky-swap provider, a fixture issuer contact with only an on-chain endpoint, and the local regtest chain on an iPhone 17 Pro simulator.
  • Test 1 (force quit before the claim, mine, relaunch): three swaps claimed after relaunch, 10 s, 13 s and 15 s from launch to claimBroadcast, and confirmed 25–30 s after the next block. On swap 1d3f7970, for example, claim aba71736… spends the lockup and pays exactly 20 000 sats to the issuer, and the provider logged "client claimed; hold invoice settled". Each swap was untracked afterwards (unfinishedPubkySwaps empty).
  • Test 2: the hold was made to fail with the provider paused after the commit, then lncli cancelinvoice.
    • With the send still open, the app logged "Stopping Pubky Swaps route … after its hold payment failed" 3 s after the cancel, and logged nothing for that swap in the 80 s after relaunch.
    • With the app closed, relaunch logged holdFailed 13 s after launch and emptied both keys. A second relaunch was silent for 85 s.
  • Counted through a per-swap Electrum proxy:
    • Each awaitingLockup advance is 1 connection and 3 requests.
    • The claiming advance is 2 connections and 6 requests.
    • With the proxy down, 7 consecutive Failed to advance Pubky Swaps route … Connection refused lines came at 30–31 s intervals. The next tick after recovery claimed.
  • ⚠️ Not verified: 5-minute count windows and a relaunch while Electrum is unreachable. On the second run the provider stopped answering quote requests after the first swap (iroh relay disconnects in its log), so tests 2 and 3 above come from the runbook author's run at this head.

CI at c049ace: green.

Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating and verifying; Fable 5.2 (claude-fable-5-2) primary review and runbook (runbook effort: medium, run record); Sonnet 5.5 (claude-sonnet-5-5) device driver
Reasoning effort: Not exposed, except where noted

…hed-swaps

# Conflicts:
#	Bitkit/AppScene.swift
#	Bitkit/Utilities/AppReset.swift
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.
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.
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.
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.
The test target compiles its own copy of Errors.swift, so an unqualified
AppError there is a type the app classifier does not recognize.
@coreyphillips

Copy link
Copy Markdown
Contributor Author

@jvsena42 could you re-approve when you get a chance? Since your approval I merged master (8a85c7fa) and fixed the review threads, including your backoff (5c8a6bf0, with your test). Each thread has a reply. CI is green on 5a4240c0, and the ruleset needs an approval of the latest push. Ben's restore thread stays open until synonymdev/bitkit-core#232 lands.

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

4 participants