Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
12ff24f
fix: hold the funding ask while a savings send is unresolved
ovitrif Nov 26, 2026
cd40eb2
fix: hold the ask only for a send that may still land, read before th…
ovitrif Nov 26, 2026
759f323
fix: end a retried savings send only once a node accepted it
ovitrif Nov 26, 2026
5cef1d8
fix: read the savings send after any start payment
ovitrif Nov 26, 2026
628ccb5
fix: say a savings payment may still land only while the exit waits f…
ovitrif Nov 26, 2026
80bde21
fix: end a retried savings send only once a node accepted it
ovitrif Nov 26, 2026
7e8f98b
fix: refresh the savings send after a retry
ovitrif Nov 26, 2026
3f8bbfc
fix: show the savings note as soon as the payment state changes
ovitrif Nov 26, 2026
bfff3d4
fix: bring the ask back once the exit forgot its payment
ovitrif Nov 26, 2026
eaa1799
fix: drop a cached paid state once the exit adopted the payment
ovitrif Nov 26, 2026
a5cc409
Merge remote-tracking branch 'origin/master' into fix/spark-exit-hold…
ovitrif Nov 26, 2026
1910f79
fix: read the savings sends through master's journal read
ovitrif Nov 26, 2026
ef18c55
fix: keep the remainder asked when the funding re-read fails
ovitrif Nov 26, 2026
97bb885
fix: hold the ask after a failed start or an unsaved retry payment
ovitrif Nov 26, 2026
cd847b3
fix: refresh the funding after a background run forgets the exit's pa…
ovitrif Nov 26, 2026
c8fd11e
fix: pay a refused savings payment again only while it is still refused
ovitrif Nov 26, 2026
3ce2533
Merge remote-tracking branch 'origin/master' into fix/spark-exit-hold…
ovitrif Nov 26, 2026
27ef013
Merge remote-tracking branch 'origin/master' into fix/spark-exit-hold…
ovitrif Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 82 additions & 16 deletions Bitkit/Managers/SparkExitManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,17 @@ final class SparkExitManager {
private(set) var isFeeBumpLeavingLeaves = false
/// What the running exit shows about its fee funding while it lacks some.
var fundingState: SparkExitFundingState? {
Self.isFundingOfExit(fundingExitCreatedAt, record: record) ? storedFundingState : nil
guard Self.isFundingOfExit(fundingExitCreatedAt, record: record) else { return nil }
return Self.currentFundingState(storedFundingState, record: record)
}

/// A payment the exit forgot or adopted since the funding was read, as a background run or a tick may, no longer
/// holds the ask: Progress reads the record's own state until the next read.
nonisolated static func currentFundingState(_ stored: SparkExitFundingState?, record: SparkExitRecord?) -> SparkExitFundingState? {
if case let .paid(txid) = stored, record?.isAwaitingOwnPayment != true || record?.fundingPaymentTxid != txid {
return nil
}
return stored
}

/// The full funding the Progress top-up asks for, every extra payment's input fee included.
Expand Down Expand Up @@ -276,6 +286,8 @@ final class SparkExitManager {
}
let record = record
Task {
// Progress says at once whether a savings payment may still land, before the first tick's network reads.
await refreshSends()
if let record {
await settleIfFinished(record)
}
Expand Down Expand Up @@ -359,6 +371,19 @@ final class SparkExitManager {
record.map { Self.isSavingsPaymentRefused($0, attempt: refusedSavingsPayment, fundingSeenSats: fundingSeenSats) } ?? false
}

/// The exit waits for its own savings payment, which the send journal has not seen accepted yet: it may still land,
/// so Progress says to wait for it before paying from another wallet.
var isSavingsSendLanding: Bool {
record.map { Self.isSavingsSendLanding($0, unresolvedSendAddress: unresolvedSendAddress) } ?? false
}

/// Only while `record` still waits for that payment: once the own-payment wait forgets it, the ask comes back.
/// A refused payment is never awaited (its txid is not kept), so a refusal needs no check of its own.
nonisolated static func isSavingsSendLanding(_ record: SparkExitRecord, unresolvedSendAddress: String?) -> Bool {
guard record.isAwaitingOwnPayment, let unresolvedSendAddress else { return false }
return record.funding.contains { $0.address == unresolvedSendAddress }
}

/// A node refused the savings payment of `record`'s fee funding, and none was adopted since: only before the exit
/// is funded, for the payment the start made. Never once funding from another wallet reached the address, as the
/// last read of it saw: the same payment again would fund it twice.
Expand All @@ -382,12 +407,16 @@ final class SparkExitManager {
record: SparkExitRecord,
fundingSeenSats: UInt64 = 0,
retrySamePayment: (OnchainSendPendingContext) async throws -> OnchainSendResult
) async throws -> String? {
) async throws -> (txid: String, isAccepted: Bool)? {
guard isSavingsPaymentRefused(record, attempt: refused, fundingSeenSats: fundingSeenSats), refused.canRetrySamePayment else {
throw OnchainSendAttemptError.unresolved
}
let result = try await retrySamePayment(OnchainSendPendingContext(attemptId: refused.id, walletId: refused.walletId, txid: refused.txid))
return fundingTxid(result)
guard let txid = fundingTxid(result) else { return nil }
if case .accepted = result {
return (txid, true)
}
return (txid, false)
}

func retrySavingsPayment() async throws {
Expand All @@ -401,6 +430,8 @@ final class SparkExitManager {
if let stored = try? Self.loadRecord(store: store, lostLeafStore: lostLeafStore) {
record = stored
}
// Read again under the lock: a retry from Send Pending may have sent it since the last tick.
await refreshRefusedSavingsPayment()
guard let current = record, let refused = refusedSavingsPayment else { return }
// Funded or forgotten while this waited for the lock: nothing left to pay.
guard Self.isSavingsPaymentRefused(current, attempt: refused) else { return }
Expand All @@ -411,20 +442,37 @@ final class SparkExitManager {
}
guard Self.isSavingsPaymentRefused(current, attempt: refused, fundingSeenSats: fundingSeenSats) else { return }
let attempts = OnchainSendAttemptService.shared
let txid = try await Self.payRefusedAgain(refused, record: current, fundingSeenSats: fundingSeenSats) { context in
try await attempts.retrySamePayment(using: LightningService.shared, context: context) { attempt, _ in
guard attempt.id == refused.id, attempt.address == refused.address else { throw OnchainSendAttemptError.unresolved }
let paidAgain: (txid: String, isAccepted: Bool)?
do {
paidAgain = try await Self.payRefusedAgain(refused, record: current, fundingSeenSats: fundingSeenSats) { context in
try await attempts.retrySamePayment(using: LightningService.shared, context: context) { attempt, _ in
guard attempt.id == refused.id, attempt.address == refused.address, attempt.status == .rejected
else { throw OnchainSendAttemptError.unresolved }
}
}
} catch {
await refreshSends()
await refreshRefusedSavingsPayment()
throw error
}
await refreshRefusedSavingsPayment()
guard let txid else {
guard let (txid, isAccepted) = paidAgain else {
throw AppError(message: t("wallet__send_error_tx_failed"), debugMessage: "Spark exit savings payment refused again")
}
_ = try? await attempts.resumeAcceptedOrdinarySend(walletId: refused.walletId, observedTxid: txid)
// Only an accepted payment ends its send: one of unknown outcome may still land, and Progress says so.
if isAccepted {
_ = try? await attempts.resumeAcceptedOrdinarySend(walletId: refused.walletId, observedTxid: txid)
}
await refreshSends()
guard var paid = record, paid.createdAt == current.createdAt, paid.isActive else { return }
paid.fundingPaymentTxid = txid
paid.savingsRefusal = nil
try saveRecord(paid)
// Kept as paid even when the save fails, so progress never offers to pay it again.
do {
try saveRecord(paid)
} catch {
Logger.error("Failed to save the Spark exit funding payment: \(error)", context: "SparkExitManager")
}
record = paid
setFunding(SparkExitMath.fundingState(paid, utxos: nil), for: paid)
refusedSavingsPayment = nil
Expand Down Expand Up @@ -803,11 +851,12 @@ final class SparkExitManager {
}
await refreshRefusedSavingsPayment()
await refreshNetworkFees(chain: chain)
await refreshFundingSeen(chain: chain, record: current)
let seen = await refreshFundingSeen(chain: chain, record: current)
var updated = try await driver.tick(current)
// A tick that adopted the funding and came up short would otherwise keep showing that payment as seen.
if updated.phase != current.phase {
await refreshFundingSeen(chain: chain, record: updated)
// A tick that adopted the funding and came up short would otherwise keep showing that payment as seen, and
// one that forgot the exit's own payment would keep hiding the ask.
if updated.phase != current.phase || updated.fundingPaymentTxid != current.fundingPaymentTxid {
await refreshFundingSeen(chain: chain, record: updated, earlier: seen)
}
// The result may have been opened while this tick ran; a reset the driver made, such as for change kept
// after the result was opened, stays.
Expand Down Expand Up @@ -888,9 +937,12 @@ final class SparkExitManager {
}

/// Only new funding counts: the adopted inputs and the CPFP change at the address are already part of the exit.
/// The address read, or nil when it could not be read or the exit has nothing to fund.
/// Reads the funding address for `record`, falling back to `earlier` when the read fails; the UTXOs it went by, or
/// nil when it could not be read or the exit has nothing to fund.
@discardableResult
private func refreshFundingSeen(chain: SparkExitChain, record: SparkExitRecord) async -> [EsploraUtxo]? {
private func refreshFundingSeen(
chain: SparkExitChain, record: SparkExitRecord, earlier: [EsploraUtxo]? = nil
) async -> [EsploraUtxo]? {
guard let address = record.funding.first?.address else { return nil }
fundingAddress = address
guard record.fundingShortfallSats != nil else {
Expand All @@ -900,11 +952,17 @@ final class SparkExitManager {
setFunding(nil, for: record)
return nil
}
let utxos = try? await chain.utxos(address: address)
let utxos = await Self.fundingReread(try? chain.utxos(address: address), earlier: earlier)
noteFundingSeen(record, utxos: utxos)
return utxos
}

/// The funding address read again after a tick changed the exit, or the tick's first read when that one failed: a
/// short savings payment the first read saw still counts, so the ask is for the rest, never the whole shortfall.
nonisolated static func fundingReread(_ read: [EsploraUtxo]?, earlier: [EsploraUtxo]?) -> [EsploraUtxo]? {
read ?? earlier
}

/// What `utxos` at the funding address, nil when unread, says the exit still needs.
private func noteFundingSeen(_ record: SparkExitRecord, utxos: [EsploraUtxo]?) {
if let utxos {
Expand Down Expand Up @@ -1268,6 +1326,7 @@ final class SparkExitManager {
} catch {
// A refused payment shows on progress at once, with the offer to pay again.
noteSavingsRefusal(started, sats: savingsSats, after: error)
await refreshSends()
await refreshRefusedSavingsPayment()
throw error
}
Expand Down Expand Up @@ -1538,6 +1597,8 @@ final class SparkExitManager {
} else {
Logger.warn("Spark exit funding \(txid) has an unknown outcome; kept as pending", context: "SparkExitManager")
}
// Progress says at once whether the payment may still land.
await refreshSends()
return txid
}

Expand Down Expand Up @@ -1653,6 +1714,11 @@ final class SparkExitManager {
)
if let updated = outcome.record {
record = updated
// As after a tick: a run that forgot the exit's own payment (it confirmed short) or changed the phase reads
// the address, so Progress asks only for the rest.
if updated.phase != previous?.phase || updated.fundingPaymentTxid != previous?.fundingPaymentTxid {
await refreshFundingSeen(chain: chain, record: updated)
}
if let previous, Self.isFundingAskWithdrawn(updated, previous: previous) {
Self.dismissDeliveredFundingNotifications(record: updated)
}
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/ar.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@
"lightning__spark_exit__fees" = "رسوم الشبكة";
"lightning__spark_exit__receive" = "ستستلم (تقديريًا)";
"lightning__spark_exit__savings_refused" = "لم يكتمل دفعك من المدخرات. ادفع مرة أخرى، أو موّل من محفظة أخرى.";
"lightning__spark_exit__savings_unresolved" = "لم يتأكد دفعك من المدخرات بعد. انتظره قبل أن تدفع من محفظة أخرى.";
"lightning__spark_exit__quote_loading" = "جارٍ الحصول على التكاليف…";
"lightning__spark_exit__quote_settling" = "بانتظار أن ينتهي Spark من نقل رصيدك. قد يستغرق ذلك حتى 5 دقائق.";
"lightning__spark_exit__quote_error" = "تعذّر الحصول على تكاليف التحويل. حاول مرة أخرى.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/ca.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@
"lightning__spark_exit__fees" = "Comissions de xarxa";
"lightning__spark_exit__receive" = "Rebràs (estimació)";
"lightning__spark_exit__savings_refused" = "El teu pagament dels estalvis no s'ha completat. Torna a pagar o finança des d'un altre moneder.";
"lightning__spark_exit__savings_unresolved" = "El teu pagament dels estalvis encara no s'ha confirmat. Espera'l abans de pagar des d'un altre moneder.";
"lightning__spark_exit__quote_loading" = "Obtenint els costos…";
"lightning__spark_exit__quote_settling" = "Esperant que Spark acabi de moure el teu saldo. Pot trigar fins a 5 minuts.";
"lightning__spark_exit__quote_error" = "No s'han pogut obtenir els costos de la transferència. Torna-ho a intentar.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/cs.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@
"lightning__spark_exit__fees" = "Síťové poplatky";
"lightning__spark_exit__receive" = "Obdržíte (odhad)";
"lightning__spark_exit__savings_refused" = "Vaše platba z úspor neprošla. Zaplaťte znovu, nebo financujte z jiné peněženky.";
"lightning__spark_exit__savings_unresolved" = "Vaše platba z úspor ještě není potvrzena. Počkejte na ni, než zaplatíte z jiné peněženky.";
"lightning__spark_exit__quote_loading" = "Zjišťuji náklady…";
"lightning__spark_exit__quote_settling" = "Čekáme, až Spark dokončí přesun vašeho zůstatku. Může to trvat až 5 minut.";
"lightning__spark_exit__quote_error" = "Náklady na převod se nepodařilo zjistit. Zkuste to znovu.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/de.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@
"lightning__spark_exit__fees" = "Netzwerkgebühren";
"lightning__spark_exit__receive" = "Du erhältst (Schätzung)";
"lightning__spark_exit__savings_refused" = "Deine Zahlung vom Sparkonto ist nicht durchgegangen. Zahle erneut oder finanziere aus einer anderen Wallet.";
"lightning__spark_exit__savings_unresolved" = "Deine Zahlung vom Sparkonto ist noch nicht bestätigt. Warte darauf, bevor du aus einer anderen Wallet zahlst.";
"lightning__spark_exit__quote_loading" = "Kosten werden abgerufen…";
"lightning__spark_exit__quote_settling" = "Warte, bis Spark dein Guthaben fertig verschoben hat. Das kann bis zu 5 Minuten dauern.";
"lightning__spark_exit__quote_error" = "Die Übertragungskosten konnten nicht abgerufen werden. Versuche es erneut.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/el.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@
"lightning__spark_exit__fees" = "Τέλη δικτύου";
"lightning__spark_exit__receive" = "Λαμβάνετε (εκτίμηση)";
"lightning__spark_exit__savings_refused" = "Η πληρωμή σας από αποταμιεύσεις δεν ολοκληρώθηκε. Πληρώστε ξανά ή χρηματοδοτήστε από άλλο πορτοφόλι.";
"lightning__spark_exit__savings_unresolved" = "Η πληρωμή σας από αποταμιεύσεις δεν έχει επιβεβαιωθεί ακόμη. Περιμένετέ την πριν πληρώσετε από άλλο πορτοφόλι.";
"lightning__spark_exit__quote_loading" = "Λήψη κόστους…";
"lightning__spark_exit__quote_settling" = "Αναμονή για να ολοκληρώσει το Spark τη μεταφορά του υπολοίπου σας. Αυτό μπορεί να διαρκέσει έως 5 λεπτά.";
"lightning__spark_exit__quote_error" = "Δεν ήταν δυνατή η λήψη του κόστους μεταφοράς. Δοκιμάστε ξανά.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@
"lightning__spark_exit__fees" = "Network fees";
"lightning__spark_exit__receive" = "You receive (estimate)";
"lightning__spark_exit__savings_refused" = "Your savings payment didn't go through. Pay again, or fund from another wallet.";
"lightning__spark_exit__savings_unresolved" = "Your savings payment hasn't confirmed yet. Wait for it before you pay from another wallet.";
"lightning__spark_exit__quote_loading" = "Getting the costs…";
"lightning__spark_exit__quote_settling" = "Waiting for Spark to finish moving your balance. This can take up to 5 minutes.";
"lightning__spark_exit__quote_error" = "Could not get the transfer costs. Try again.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@
"lightning__spark_exit__fees" = "Comisiones de red";
"lightning__spark_exit__receive" = "Recibes (estimado)";
"lightning__spark_exit__savings_refused" = "Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otra billetera.";
"lightning__spark_exit__savings_unresolved" = "Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otra billetera.";
"lightning__spark_exit__quote_loading" = "Obteniendo los costos…";
"lightning__spark_exit__quote_settling" = "Esperando a que Spark termine de mover tu saldo. Esto puede tardar hasta 5 minutos.";
"lightning__spark_exit__quote_error" = "No se pudieron obtener los costos de la transferencia. Intenta de nuevo.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/es.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@
"lightning__spark_exit__fees" = "Comisiones de red";
"lightning__spark_exit__receive" = "Recibes (estimado)";
"lightning__spark_exit__savings_refused" = "Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otro monedero.";
"lightning__spark_exit__savings_unresolved" = "Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otro monedero.";
"lightning__spark_exit__quote_loading" = "Obteniendo los costes…";
"lightning__spark_exit__quote_settling" = "Esperando a que Spark termine de mover tu saldo. Esto puede tardar hasta 5 minutos.";
"lightning__spark_exit__quote_error" = "No se pudieron obtener los costes de la transferencia. Inténtalo de nuevo.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/fr.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@
"lightning__spark_exit__fees" = "Frais de réseau";
"lightning__spark_exit__receive" = "Vous recevez (estimation)";
"lightning__spark_exit__savings_refused" = "Votre paiement depuis l'épargne n'a pas abouti. Payez à nouveau ou financez depuis un autre portefeuille.";
"lightning__spark_exit__savings_unresolved" = "Votre paiement depuis l'épargne n'est pas encore confirmé. Attendez-le avant de payer depuis un autre portefeuille.";
"lightning__spark_exit__quote_loading" = "Obtention des coûts…";
"lightning__spark_exit__quote_settling" = "En attente que Spark termine le transfert de votre solde. Cela peut prendre jusqu'à 5 minutes.";
"lightning__spark_exit__quote_error" = "Impossible d'obtenir les coûts du transfert. Réessayez.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/it.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,7 @@
"lightning__spark_exit__fees" = "Commissioni di rete";
"lightning__spark_exit__receive" = "Riceverai (stima)";
"lightning__spark_exit__savings_refused" = "Il tuo pagamento dai risparmi non è andato a buon fine. Paga di nuovo o finanzia da un altro portafoglio.";
"lightning__spark_exit__savings_unresolved" = "Il tuo pagamento dai risparmi non è ancora confermato. Attendilo prima di pagare da un altro portafoglio.";
"lightning__spark_exit__quote_loading" = "Calcolo dei costi…";
"lightning__spark_exit__quote_settling" = "In attesa che Spark finisca di spostare il tuo saldo. Può richiedere fino a 5 minuti.";
"lightning__spark_exit__quote_error" = "Impossibile ottenere i costi del trasferimento. Riprova.";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/nl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@
"lightning__spark_exit__fees" = "Netwerkkosten";
"lightning__spark_exit__receive" = "U ontvangt (schatting)";
"lightning__spark_exit__savings_refused" = "Je betaling uit spaargeld is niet gelukt. Betaal opnieuw of financier vanuit een andere wallet.";
"lightning__spark_exit__savings_unresolved" = "Je betaling uit spaargeld is nog niet bevestigd. Wacht erop voordat je vanuit een andere wallet betaalt.";
"lightning__spark_exit__quote_loading" = "Kosten ophalen…";
"lightning__spark_exit__quote_settling" = "Wachten tot Spark klaar is met het verplaatsen van je saldo. Dit kan tot 5 minuten duren.";
"lightning__spark_exit__quote_error" = "Kon de kosten van de overboeking niet ophalen. Probeer opnieuw.";
Expand Down
Loading
Loading