From 512d553dffd101bb6c198c07ed1338be7760e9bb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 12:49:43 +0100 Subject: [PATCH 1/8] fix: hold the funding ask while a savings send is unresolved A savings payment that ends with no answer keeps its transaction as the exit's own payment, as one of unknown result already did, so Progress shows it paid and the own-payment wait brings the ask back if it never lands. Progress says to wait for it while the send journal has not seen it accepted. Verified: SparkExit unit tests, detekt --- .../to/bitkit/repositories/SparkExitRepo.kt | 50 +++++++++++++++---- .../lightning/SparkExitProgressScreen.kt | 8 +++ .../settings/lightning/SparkExitViewModel.kt | 7 +++ app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../bitkit/repositories/SparkExitRepoTest.kt | 3 ++ .../lightning/SparkExitViewModelTest.kt | 20 ++++++++ changelog.d/next/2059.fixed.md | 1 + 22 files changed, 95 insertions(+), 10 deletions(-) create mode 100644 changelog.d/next/2059.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 28ed612fde..0197281bfc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -947,18 +947,42 @@ class SparkExitRepo @Inject constructor( // Refused by a node, or with no answer, it went out: its own retry or the exit's wait takes over. if (it is OnchainSendPendingError || it is SparkExitError) noteSavingsRefusal(null) } - .getOrThrow() - val record = _state.value.record ?: return@withLock - val paid = record.copy(fundingPaymentTxid = txid, savingsRefusal = null) - // Kept as paid even when the save fails, so progress never offers to pay it again; a later tick saves it. - runCatching { saveRecord(paid) } - .onFailure { Logger.error("Failed to save the Spark exit funding payment '$txid'", it, context = TAG) } - _state.update { - it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) - } + .getOrElse { + pendingFundingTxid(it, address)?.let { pending -> keepFundingPayment(pending) } + throw it + } + keepFundingPayment(txid) } } + /** + * Keeps [txid] as the exit's savings payment: progress shows it paid, with no ask, until it lands or the + * own-payment wait forgets it. Kept even when the save fails, so progress never offers to pay it again; a later + * tick saves it. + */ + private fun keepFundingPayment(txid: String) { + val record = _state.value.record ?: return + val paid = record.copy(fundingPaymentTxid = txid, savingsRefusal = null) + runCatching { saveRecord(paid) } + .onFailure { Logger.error("Failed to save the Spark exit funding payment '$txid'", it, context = TAG) } + _state.update { + it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) + } + } + + /** + * The transaction of a savings payment to [address] with no answer yet: it may still go out, so it is kept like + * one of unknown result. From the error, or else from the send journal. + */ + private suspend fun pendingFundingTxid(error: Throwable, address: String): String? { + if (error !is OnchainSendPendingError) return null + error.txid?.let { return it } + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + val isPending = attempt?.evidence == OnchainSendEvidence.Pending || + attempt?.evidence == OnchainSendEvidence.Unknown + return attempt?.takeIf { it.address == address && isPending }?.txid + } + private fun noteSavingsRefusal(sats: ULong, feeSats: ULong) = noteSavingsRefusal(SparkExitRecord.SavingsRefusal(sats, feeSats)) @@ -1119,7 +1143,13 @@ class SparkExitRepo @Inject constructor( walletId = refused.walletId, feeRateSatsPerVByte = refused.feeRateSatsPerVByte, ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } - .getOrThrow() + .getOrElse { + pendingFundingTxid(it, refused.address)?.let { pending -> + keepFundingPayment(pending) + _state.update { exit -> exit.copy(isSavingsPaymentRefused = false) } + } + throw it + } val txid = fundingTxid(outcome, refused.amountSats) val current = _state.value.record ?: return@withLock val paid = current.copy(fundingPaymentTxid = txid, savingsRefusal = null) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 490228ca7f..b728a74bd3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -220,6 +220,14 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, modifier = Modifier.testTag("SparkExitSavingsRefused") ) } + if (uiState.isSavingsSendLanding) { + VerticalSpacer(24.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__savings_unresolved), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitSavingsUnresolved") + ) + } if (funding is SparkExitFundingState.Ask && address != null) { VerticalSpacer(24.dp) SparkExitFeesRow( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index afe85f86be..023196cc8d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -507,6 +507,13 @@ data class SparkExitUiState( /** Progress says the savings payment didn't go through and offers to pay it again. */ val offersSavingsRetry: Boolean get() = isSavingsPaymentRefused || savingsRetryOffer != null + /** + * 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. + */ + val isSavingsSendLanding: Boolean + get() = record?.isAwaitingOwnPayment == true && isSavingsSendUnresolved && !isSavingsPaymentRefused + /** Progress offers Pay a higher fee. */ val canPayHigherFee: Boolean get() = record?.canPayHigherFee(tipHeight, networkFees) == true diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 77614b84c1..8d48895103 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -334,6 +334,7 @@ تعذّر على Bitkit قراءة التقدم المحفوظ لهذا التحويل، لذا يعيد بناءه من السلسلة. ستستلم (تقديريًا) لم يكتمل دفعك من المدخرات. ادفع مرة أخرى، أو موّل من محفظة أخرى. + لم يتأكد دفعك من المدخرات بعد. انتظره قبل أن تدفع من محفظة أخرى. إرسال إلى العنوان تأكيد رسوم الطوارئ نشر معاملة الخروج diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 06b95bfe98..719d0cd30c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -341,6 +341,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otra billetera. + Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otra billetera. Enviar a dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d6d4a9f2cb..cd214cf2c2 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -338,6 +338,7 @@ Bitkit no ha pogut llegir el progrés desat d\'aquesta transferència, així que el reconstrueix a partir de la cadena. Rebràs (estimació) El teu pagament dels estalvis no s\'ha completat. Torna a pagar o finança des d\'un altre moneder. + El teu pagament dels estalvis encara no s\'ha confirmat. Espera\'l abans de pagar des d\'un altre moneder. Enviar a l\'adreça Confirmació de les comissions d\'emergència Publicació de la transacció de sortida diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 82f4fd4833..46cba33f2f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -341,6 +341,7 @@ Bitkit nemohl přečíst uložený průběh tohoto převodu, proto ho znovu sestaví z blockchainu. Obdržíte (odhad) Vaše platba z úspor neprošla. Zaplaťte znovu, nebo financujte z jiné peněženky. + Vaše platba z úspor ještě není potvrzena. Počkejte na ni, než zaplatíte z jiné peněženky. Odeslat na adresu Potvrzení nouzových poplatků Zveřejnění transakce odchodu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b596372ffc..6c0c92a6eb 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -223,6 +223,7 @@ Bitkit konnte den gespeicherten Fortschritt dieser Übertragung nicht lesen und stellt ihn daher aus der Chain wieder her. Du erhältst (Schätzung) Deine Zahlung vom Sparkonto ist nicht durchgegangen. Zahle erneut oder finanziere aus einer anderen Wallet. + Deine Zahlung vom Sparkonto ist noch nicht bestätigt. Warte darauf, bevor du aus einer anderen Wallet zahlst. An Adresse senden Bestätigung der Notfallgebühren Veröffentlichung der Ausstiegstransaktion diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 42a34f22fe..954f084df2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -334,6 +334,7 @@ Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της μεταφοράς, γι\' αυτό την ανακατασκευάζει από την αλυσίδα. Λαμβάνετε (εκτίμηση) Η πληρωμή σας από αποταμιεύσεις δεν ολοκληρώθηκε. Πληρώστε ξανά ή χρηματοδοτήστε από άλλο πορτοφόλι. + Η πληρωμή σας από αποταμιεύσεις δεν έχει επιβεβαιωθεί ακόμη. Περιμένετέ την πριν πληρώσετε από άλλο πορτοφόλι. Αποστολή σε διεύθυνση Επιβεβαίωση έκτακτων τελών Δημοσίευση συναλλαγής εξόδου diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6dc0e1e3d2..6b25de874f 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -340,6 +340,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se ha completado. Paga de nuevo o financia desde otro monedero. + Tu pago desde ahorros aún no se ha confirmado. Espéralo antes de pagar desde otro monedero. Enviar a la dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 263394119f..586c8de23a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -282,6 +282,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otro monedero. + Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otro monedero. Enviar a la dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f5a04008e8..10986173b2 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -222,6 +222,7 @@ Bitkit n\'a pas pu lire la progression enregistrée de ce transfert, il la reconstruit donc à partir de la chaîne. Vous recevez (estimation) Votre paiement depuis l\'épargne n\'a pas abouti. Payez à nouveau ou financez depuis un autre portefeuille. + Votre paiement depuis l\'épargne n\'est pas encore confirmé. Attendez-le avant de payer depuis un autre portefeuille. Envoyer à l\'adresse Confirmation des frais d\'urgence Publication de la transaction de sortie diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 93b5988584..04c3a8e3df 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -339,6 +339,7 @@ Bitkit non è riuscito a leggere l\'avanzamento salvato di questo trasferimento, quindi lo ricostruisce dalla blockchain. Riceverai (stima) Il tuo pagamento dai risparmi non è andato a buon fine. Paga di nuovo o finanzia da un altro portafoglio. + Il tuo pagamento dai risparmi non è ancora confermato. Attendilo prima di pagare da un altro portafoglio. Invia all\'indirizzo Conferma delle commissioni di emergenza Pubblicazione della transazione di uscita diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index da06deedb7..0ddaae8d43 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -338,6 +338,7 @@ Bitkit kon de opgeslagen voortgang van deze overboeking niet lezen en bouwt die daarom opnieuw op vanaf de chain. Je ontvangt (schatting) Je betaling uit spaargeld is niet gelukt. Betaal opnieuw of financier vanuit een andere wallet. + Je betaling uit spaargeld is nog niet bevestigd. Wacht erop voordat je vanuit een andere wallet betaalt. Naar adres sturen Bevestiging van noodkosten Exittransactie publiceren diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2eca3d9717..70adfdfcfc 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -224,6 +224,7 @@ Bitkit nie mógł odczytać zapisanego postępu tego transferu, więc odbudowuje go z łańcucha. Otrzymasz (szacunkowo) Twoja płatność z Oszczędności nie przeszła. Zapłać ponownie lub sfinansuj z innego portfela. + Twoja płatność z Oszczędności nie jest jeszcze potwierdzona. Poczekaj na nią, zanim zapłacisz z innego portfela. Wyślij na adres Potwierdzenie opłat awaryjnych Publikowanie transakcji wyjścia diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ecf958ac73..504a6bcc94 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -342,6 +342,7 @@ A Bitkit não conseguiu ler o progresso salvo desta transferência, então o reconstrói a partir da blockchain. Você recebe (estimativa) Seu pagamento da poupança não foi concluído. Pague novamente ou financie de outra carteira. + Seu pagamento da poupança ainda não foi confirmado. Aguarde antes de pagar de outra carteira. Enviar para o endereço Confirmação das taxas de emergência Publicação da transação de saída diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe167db418..fa27892541 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -219,6 +219,7 @@ A Bitkit não conseguiu ler o progresso guardado desta transferência, por isso reconstrói-o a partir da blockchain. Recebe (estimativa) O seu pagamento da poupança não foi concluído. Pague novamente ou financie a partir de outra carteira. + O seu pagamento da poupança ainda não foi confirmado. Aguarde antes de pagar a partir de outra carteira. Enviar para o endereço Confirmação das taxas de emergência Publicação da transação de saída diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 08e92af37c..3fc7e03eff 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -350,6 +350,7 @@ Bitkit не смог прочитать сохранённый прогресс этого перевода, поэтому восстанавливает его по блокчейну. Вы получите (оценка) Платёж из сбережений не прошёл. Оплатите снова или пополните с другого кошелька. + Платёж из сбережений ещё не подтверждён. Дождитесь его, прежде чем платить с другого кошелька. Отправить на адрес Подтверждение экстренных комиссий Публикация транзакции выхода diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47968335dd..fec690af0a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -502,6 +502,7 @@ Bitkit couldn\'t read this transfer\'s saved progress, so it rebuilds it from the chain. You receive (estimate) Your savings payment didn\'t go through. Pay again, or fund from another wallet. + Your savings payment hasn\'t confirmed yet. Wait for it before you pay from another wallet. Send to address Confirmation of emergency fees Publishing of exit transaction diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f15d0a2772..796ccd71a9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1687,6 +1687,9 @@ class SparkExitRepoTest : BaseUnitTest() { outcome = Result.failure(OnchainSendPendingError(IOException("no answer"), "pending")) assertTrue(sut.paySavingsRefusal(retry).isFailure) assertNull(assertNotNull(store.load()).savingsRefusal) + // Kept as the exit's payment, so progress holds the ask until it lands or the own-payment wait forgets it. + assertEquals("pending", store.load()?.fundingPaymentTxid) + assertEquals(SparkExitFundingState.Paid, sut.state.value.fundingState) sut.onAppBackgrounded() verify(lightning, times(2)).sendOnChain( diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index e4420f60c5..fe4def6765 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -425,6 +425,26 @@ class SparkExitViewModelTest : BaseUnitTest() { ) } + @Test + fun `progress says a savings payment may still land only while the exit waits for it`() { + val paid = SparkExitFixtures.record().copy(fundingPaymentTxid = "pending") + val landing = SparkExitUiState( + record = paid, + fundingState = SparkExitFundingState.Paid, + isSavingsSendUnresolved = true, + ) + + assertTrue(landing.isSavingsSendLanding) + assertEquals(SparkExitFundingState.Paid, landing.progressFunding) + assertFalse(landing.copy(isSavingsSendUnresolved = false).isSavingsSendLanding, "accepted") + assertFalse(landing.copy(isSavingsPaymentRefused = true).isSavingsSendLanding, "refused: its own retry shows") + // Once the own-payment wait forgets it, the ask comes back, even with the journal still unresolved. + val ask = SparkExitFundingState.Ask(20_000uL) + val forgotten = landing.copy(record = paid.copy(fundingPaymentTxid = null), fundingState = ask) + assertFalse(forgotten.isSavingsSendLanding) + assertEquals(ask, forgotten.progressFunding) + } + /** The qa-03 rerun, case 5: one 32,768-sat leaf lost to an older owner, 1,696 sats Spark could not exit. */ @Test fun `a stopped exit names what spark's live balance holds beyond its leaves`() = test { diff --git a/changelog.d/next/2059.fixed.md b/changelog.d/next/2059.fixed.md new file mode 100644 index 0000000000..a2ea8418dd --- /dev/null +++ b/changelog.d/next/2059.fixed.md @@ -0,0 +1 @@ +Fixed force transfer progress asking for the emergency fees while a payment of them from savings could still confirm. From 8cb926aa13bb8fb67ac09f73d376a301b4e2c24a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 13:37:24 +0100 Subject: [PATCH 2/8] test: stop the foreground loop before the kept-payment checks A failed check now ends the test instead of leaving runTest driving the loop. Verified: SparkExit unit tests, detekt; the kept-payment check fails without the fix --- app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 796ccd71a9..9db2329cef 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1686,11 +1686,12 @@ class SparkExitRepoTest : BaseUnitTest() { // A payment with no answer may have gone out: it is never offered again. outcome = Result.failure(OnchainSendPendingError(IOException("no answer"), "pending")) assertTrue(sut.paySavingsRefusal(retry).isFailure) + // Stops the foreground loop before the checks, or runTest drives it forever when one fails. + sut.onAppBackgrounded() assertNull(assertNotNull(store.load()).savingsRefusal) // Kept as the exit's payment, so progress holds the ask until it lands or the own-payment wait forgets it. assertEquals("pending", store.load()?.fundingPaymentTxid) assertEquals(SparkExitFundingState.Paid, sut.state.value.fundingState) - sut.onAppBackgrounded() verify(lightning, times(2)).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), From b11c7672afdfce8a96aca61a94802ff3d2698ddd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 13:46:13 +0100 Subject: [PATCH 3/8] fix: refresh the savings send after every exit payment A retry, accepted or not, and a start paid with no answer now update whether a savings send may still land, so Progress shows its note only while it may. A tick that forgets the exit's own payment brings the ask back at once. Verified: none (tests run after this commit) --- .../to/bitkit/repositories/SparkExitRepo.kt | 31 +++++++--------- .../bitkit/repositories/SparkExitRepoTest.kt | 36 ++++++++++++++++++- 2 files changed, 47 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 0197281bfc..1c9a937e75 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -324,7 +324,10 @@ class SparkExitRepo @Inject constructor( rememberLostLeaves(updated) _state.update { it.copy(record = updated, lastError = null) } // A tick that changed the phase, such as a build short of fees, needs the funding state of the new phase. - if (updated.phase != current.phase) refreshFundingSeen(chain, updated) + // So does one that forgot the exit's own payment, which brings the ask back. + if (updated.phase != current.phase || updated.fundingPaymentTxid != current.fundingPaymentTxid) { + refreshFundingSeen(chain, updated) + } // Spark's balance next to the exit's leaves shows value outside the exit. if (recovering != null) _state.update { it.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps @@ -871,8 +874,9 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) } - // A refused payment shows on progress at once, with the offer to pay again. - .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + // A refused payment shows on progress at once, with the offer to pay again, and one that may + // still land with its note. + .also { _state.value.record?.let { current -> noteSavingsSend(current) } } .getOrThrow() } } @@ -1056,7 +1060,7 @@ class SparkExitRepo @Inject constructor( } } // A payment that went out and failed shows as such, with its own retry. - .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + .also { _state.value.record?.let { current -> noteSavingsSend(current) } } .recover { if (isKept) Unit else throw it } .getOrThrow() } @@ -1144,23 +1148,12 @@ class SparkExitRepo @Inject constructor( feeRateSatsPerVByte = refused.feeRateSatsPerVByte, ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } .getOrElse { - pendingFundingTxid(it, refused.address)?.let { pending -> - keepFundingPayment(pending) - _state.update { exit -> exit.copy(isSavingsPaymentRefused = false) } - } + pendingFundingTxid(it, refused.address)?.let { pending -> keepFundingPayment(pending) } + _state.value.record?.let { current -> noteSavingsSend(current) } throw it } - val txid = fundingTxid(outcome, refused.amountSats) - val current = _state.value.record ?: return@withLock - val paid = current.copy(fundingPaymentTxid = txid, savingsRefusal = null) - saveRecord(paid) - _state.update { - it.copy( - record = paid, - fundingState = SparkExitMath.fundingState(paid, utxos = null), - isSavingsPaymentRefused = false, - ) - } + keepFundingPayment(fundingTxid(outcome, refused.amountSats)) + _state.value.record?.let { current -> noteSavingsSend(current) } } } } finally { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 9db2329cef..9b9c0e153a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1919,13 +1919,19 @@ class SparkExitRepoTest : BaseUnitTest() { whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) whenever( lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) - ).thenReturn(Result.success(OnchainSendOutcome.Accepted("again"))) + ).doSuspendableAnswer { + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refused.copy(evidence = OnchainSendEvidence.Accepted, txid = "again")) + Result.success(OnchainSendOutcome.Accepted("again")) + } whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) val sut = quotedSut(FakeSparkExitRecovering()) sut.load().getOrThrow() sut.tick().getOrThrow() + assertTrue(sut.state.value.isSavingsSendUnresolved) sut.retrySavingsPayment().getOrThrow() + sut.onAppBackgrounded() // The same attempt at the rate the user approved: it spends the refused payment's inputs, so at most one of // the two can ever confirm. No new payment picks other coins. @@ -1940,7 +1946,35 @@ class SparkExitRepoTest : BaseUnitTest() { ) assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) assertFalse(sut.state.value.isSavingsPaymentRefused) + assertFalse(sut.state.value.isSavingsSendUnresolved, "an accepted payment says nothing about landing") + } + + @Test + fun `paying again from savings with no answer keeps the payment as the exit's own`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val refused = refusedSavingsPayment() + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).doSuspendableAnswer { + // The error carries no txid: the send journal holds it, unresolved, for the funding address. + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refused.copy(evidence = OnchainSendEvidence.Unknown, txid = "maybe")) + Result.failure(OnchainSendPendingError(IOException("no answer"))) + } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + assertTrue(sut.retrySavingsPayment().isFailure) sut.onAppBackgrounded() + + assertEquals("maybe", assertNotNull(store.load()).fundingPaymentTxid) + assertEquals(SparkExitFundingState.Paid, sut.state.value.fundingState) + assertFalse(sut.state.value.isSavingsPaymentRefused, "it may still land, so it is not offered again") + assertTrue(sut.state.value.isSavingsSendUnresolved) + assertFalse(sut.canCancel, "savings may have paid this exit") } @OptIn(ExperimentalCoroutinesApi::class) From 1240c0b12824c0adf5f520f917ed1352b1359e53 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 13:55:51 +0100 Subject: [PATCH 4/8] fix: keep only a savings payment that may have gone out A retry the send journal rolled back to refused is never kept as the exit's payment. Progress shows the may-still-land note only while the funding is paid from savings, and holds the ask before the first read of the funding address when the record keeps a payment. Verified: SparkExit unit tests and detekt --- .../main/java/to/bitkit/repositories/SparkExitRepo.kt | 9 ++++++--- .../bitkit/ui/settings/lightning/SparkExitViewModel.kt | 10 +++++++--- .../ui/settings/lightning/SparkExitViewModelTest.kt | 4 ++++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 1c9a937e75..fac46d4f68 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -976,15 +976,17 @@ class SparkExitRepo @Inject constructor( /** * The transaction of a savings payment to [address] with no answer yet: it may still go out, so it is kept like - * one of unknown result. From the error, or else from the send journal. + * one of unknown result. From the error, or else from the send journal. A retry the journal rolled back to refused + * never went out, whatever txid its error names. */ private suspend fun pendingFundingTxid(error: Throwable, address: String): String? { if (error !is OnchainSendPendingError) return null - error.txid?.let { return it } val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + ?.takeIf { it.address == address } + if (attempt?.evidence == OnchainSendEvidence.Rejected) return null val isPending = attempt?.evidence == OnchainSendEvidence.Pending || attempt?.evidence == OnchainSendEvidence.Unknown - return attempt?.takeIf { it.address == address && isPending }?.txid + return error.txid ?: attempt?.takeIf { isPending }?.txid } private fun noteSavingsRefusal(sats: ULong, feeSats: ULong) = @@ -1154,6 +1156,7 @@ class SparkExitRepo @Inject constructor( } keepFundingPayment(fundingTxid(outcome, refused.amountSats)) _state.value.record?.let { current -> noteSavingsSend(current) } + Unit } } } finally { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 023196cc8d..5e437077cb 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -512,7 +512,8 @@ data class SparkExitUiState( * so progress says to wait for it before paying from another wallet. */ val isSavingsSendLanding: Boolean - get() = record?.isAwaitingOwnPayment == true && isSavingsSendUnresolved && !isSavingsPaymentRefused + get() = record?.isAwaitingOwnPayment == true && isSavingsSendUnresolved && !isSavingsPaymentRefused && + progressFunding == SparkExitFundingState.Paid /** Progress offers Pay a higher fee. */ val canPayHigherFee: Boolean get() = record?.canPayHigherFee(tipHeight, networkFees) == true @@ -567,8 +568,11 @@ data class SparkExitUiState( */ val progressFunding: SparkExitFundingState? get() { - val shortfall = record?.fundingShortfallSats ?: return null - return fundingState ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) + val current = record ?: return null + val shortfall = current.fundingShortfallSats ?: return null + // Before the first read, a payment the record keeps still holds the ask. + return fundingState ?: SparkExitFundingState.Paid.takeIf { current.isAwaitingOwnPayment } + ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index fe4def6765..b124d9998c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -438,6 +438,10 @@ class SparkExitViewModelTest : BaseUnitTest() { assertEquals(SparkExitFundingState.Paid, landing.progressFunding) assertFalse(landing.copy(isSavingsSendUnresolved = false).isSavingsSendLanding, "accepted") assertFalse(landing.copy(isSavingsPaymentRefused = true).isSavingsSendLanding, "refused: its own retry shows") + val seen = landing.copy(fundingState = SparkExitFundingState.Seen) + assertFalse(seen.isSavingsSendLanding, "it reached the address") + // Before the first read of the address, the kept payment still holds the ask. + assertEquals(SparkExitFundingState.Paid, landing.copy(fundingState = null).progressFunding) // Once the own-payment wait forgets it, the ask comes back, even with the journal still unresolved. val ask = SparkExitFundingState.Ask(20_000uL) val forgotten = landing.copy(record = paid.copy(fundingPaymentTxid = null), fundingState = ask) From 544ec0242ea523253943d04774837aed352c03b4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 14:08:55 +0100 Subject: [PATCH 5/8] test: cover the kept, rolled-back and forgotten savings payments Verified: SparkExit unit tests and detekt --- .../bitkit/repositories/SparkExitRepoTest.kt | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 9b9c0e153a..50e6e510fc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1755,7 +1755,11 @@ class SparkExitRepoTest : BaseUnitTest() { @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a savings payment with an unknown result counts as paid and keeps the exit`() = test { - stubFunding { Result.success(OnchainSendOutcome.Unknown("maybe")) } + stubFunding { + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refusedSavingsPayment().copy(evidence = OnchainSendEvidence.Unknown, txid = "maybe")) + Result.success(OnchainSendOutcome.Unknown("maybe")) + } val sut = quotedSut(FakeSparkExitRecovering()) sut.loadQuote().getOrThrow() @@ -1765,6 +1769,7 @@ class SparkExitRepoTest : BaseUnitTest() { val record = assertNotNull(sut.state.value.record) assertEquals("maybe", record.fundingPaymentTxid) assertTrue(record.isAwaitingOwnPayment) + assertTrue(sut.state.value.isSavingsSendUnresolved, "progress says at once that it may still land") assertFalse(sut.canCancel) assertTrue(sut.cancel().isFailure) val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) @@ -1977,6 +1982,41 @@ class SparkExitRepoTest : BaseUnitTest() { assertFalse(sut.canCancel, "savings may have paid this exit") } + @Test + fun `paying again from savings keeps no payment the send journal rolled back to refused`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refusedSavingsPayment()) + // It failed before it went out: the journal stays refused, though the error names the unsent candidate. + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).thenReturn(Result.failure(OnchainSendPendingError(IOException("not sent"), "candidate"))) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + assertTrue(sut.retrySavingsPayment().isFailure) + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + assertTrue(sut.state.value.isSavingsPaymentRefused, "the retry is offered again") + } + + @Test + fun `a tick that forgets the exit's own payment brings the ask back at once`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + // Seen at height 800, and the tip is 1000: the own-payment wait is over. + store.save(awaitingRecord(paidTxid = "lost").copy(fundingPaymentSeenAtHeight = 800u)) + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain()) + sut.load().getOrThrow() + + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + assertIs(sut.state.value.fundingState) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a cancel while savings pays again waits for the payment and then keeps the exit`() = test { From 23dfe0d4eb9d96a13c911f910fe8b4808900ddb9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 16:17:05 +0100 Subject: [PATCH 6/8] fix: keep the remainder asked when the funding re-read fails A tick that forgets the exit's own payment reads the funding address again; when that read fails it now goes by the tick's first read, so a short savings payment still counts and only the rest is asked for. Verified: ./gradlew testDevDebugUnitTest --tests '*SparkExit*' (the new test failed before the fix) --- .../to/bitkit/repositories/SparkExitRepo.kt | 20 ++++++++++++----- .../bitkit/repositories/SparkExitRepoTest.kt | 22 +++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index fac46d4f68..59f70327a3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -311,7 +311,7 @@ class SparkExitRepo @Inject constructor( _state.update { it.copy(tipHeight = tip ?: it.tipHeight) } tip?.let { height -> sparkExitTip.height.update { height } } refreshNetworkFees(chain) - refreshFundingSeen(chain, current) + val seen = refreshFundingSeen(chain, current) if (current.isActive) noteSavingsSend(current) val store = store // A reconnect for the exit that failed left Spark ready but disconnected: the tick connects it again. @@ -325,8 +325,9 @@ class SparkExitRepo @Inject constructor( _state.update { it.copy(record = updated, lastError = null) } // A tick that changed the phase, such as a build short of fees, needs the funding state of the new phase. // So does one that forgot the exit's own payment, which brings the ask back. + // A failed read then keeps the first: a short payment it saw still counts, so only the rest is asked for. if (updated.phase != current.phase || updated.fundingPaymentTxid != current.fundingPaymentTxid) { - refreshFundingSeen(chain, updated) + refreshFundingSeen(chain, updated, earlier = seen) } // Spark's balance next to the exit's leaves shows value outside the exit. if (recovering != null) _state.update { it.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } @@ -421,14 +422,21 @@ class SparkExitRepo @Inject constructor( _state.update { it.copy(networkFees = fees ?: it.networkFees) } } - private suspend fun refreshFundingSeen(chain: SparkExitChain, record: SparkExitRecord) { - val address = record.funding.firstOrNull()?.address ?: return + /** Reads the funding address for [record], or goes by [earlier] when the read fails; returns the UTXOs used. */ + private suspend fun refreshFundingSeen( + chain: SparkExitChain, + record: SparkExitRecord, + earlier: List? = null, + ): List? { + val address = record.funding.firstOrNull()?.address ?: return null _state.update { it.copy(fundingAddress = address) } if (record.fundingShortfallSats == null) { _state.update { it.copy(fundingState = null) } - return + return null } - noteFundingSeen(record, runSuspendCatching { chain.utxos(address) }.getOrNull()) + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: earlier + noteFundingSeen(record, utxos) + return utxos } /** What [utxos] at the funding address, null when unread, says the exit still needs. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 50e6e510fc..b53984a4bd 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -2017,6 +2017,28 @@ class SparkExitRepoTest : BaseUnitTest() { assertIs(sut.state.value.fundingState) } + @Test + fun `a short savings payment keeps its remainder asked when the refresh after it fails`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val paid = "e1".repeat(32) + store.save(awaitingRecord(paidTxid = paid).copy(fundingPaymentSeenAtHeight = 990u)) + val short = """[{"txid":"$paid","vout":0,"value":8000,"status":{"confirmed":true}}]""" + lateinit var sut: SparkExitRepo + // The tick's reads see the short payment confirmed; the refresh after the exit forgets it fails. + sut = quotedSut( + FakeSparkExitRecovering(), + fundingChain { short.takeIf { sut.state.value.record?.fundingPaymentTxid != null } }, + ) + sut.load().getOrThrow() + + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + val ask = assertIs(sut.state.value.fundingState) + assertEquals(8000uL, ask.receivedSats, "the payment the first read found still counts") + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a cancel while savings pays again waits for the payment and then keeps the exit`() = test { From 6264a22d76299761dfa0fd156586bc4448653f26 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 16:31:04 +0100 Subject: [PATCH 7/8] fix: keep a higher fee paid from savings with no answer A higher fee whose savings payment got no answer may still go out: the exit now keeps it like one of unknown result, with its fee bump, and Progress says it may still land. Verified: ./gradlew testDevDebugUnitTest --tests '*SparkExit*' --- .../to/bitkit/repositories/SparkExitRepo.kt | 9 ++++++++- .../to/bitkit/repositories/SparkExitRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 59f70327a3..4dad9819bc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -660,7 +660,12 @@ class SparkExitRepo @Inject constructor( // On a chain Spark does not read, the exit would never see the payment. require(option.extraSats == 0uL || sharesNodeChain()) { "Spark does not read the node's chain" } val txid = if (option.extraSats > 0uL) { - sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) + runSuspendCatching { + sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) + }.getOrElse { + // With no answer it may still go out: kept like a payment of unknown result. + pendingFundingTxid(it, address) ?: throw it + } } else { null } @@ -687,6 +692,8 @@ class SparkExitRepo @Inject constructor( it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) } } + // Progress says at once whether the payment may still land. + _state.value.record?.takeIf { it.isActive }?.let { noteSavingsSend(it) } if (_state.value.record?.needsDriving == true) work.schedulePeriodic() Logger.info( "Raised the Spark exit fee to '${option.rateSatPerVbyte}' sat/vB, paying '${option.extraSats}' sats", diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index b53984a4bd..bc64801a5f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -2162,6 +2162,23 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(ended.payHigherFee(option).isFailure) } + @Test + fun `a higher fee paid from savings with no answer is kept as the exit's payment`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + stubFunding { Result.failure(OnchainSendPendingError(IOException("no answer"), "bump")) } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + + sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)).getOrThrow() + sut.onAppBackgrounded() + + // It may still go out, so the exit keeps it and its higher fee, and watches for it. + val record = assertNotNull(store.load()) + assertEquals("bump", record.fundingPaymentTxid) + assertEquals(9uL, record.feeRateSatPerVbyte) + } + @Test fun `a higher fee is never paid from savings on a chain spark does not read`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 1eef286473eadad81a1e01b191dfc025783cc028 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 16:46:15 +0100 Subject: [PATCH 8/8] test: a higher fee with no answer shows it may still land Verified: ./gradlew testDevDebugUnitTest --tests '*SparkExit*', ./gradlew detekt --- .../main/java/to/bitkit/repositories/SparkExitRepo.kt | 5 ++--- .../java/to/bitkit/repositories/SparkExitRepoTest.kt | 9 ++++++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 4dad9819bc..b8cba1e4b6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -660,9 +660,8 @@ class SparkExitRepo @Inject constructor( // On a chain Spark does not read, the exit would never see the payment. require(option.extraSats == 0uL || sharesNodeChain()) { "Spark does not read the node's chain" } val txid = if (option.extraSats > 0uL) { - runSuspendCatching { - sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) - }.getOrElse { + val approvedFeeSats = option.totalSats.safe() - option.extraSats.safe() + runSuspendCatching { sendFunding(address, option.extraSats, option.feeRates, approvedFeeSats) }.getOrElse { // With no answer it may still go out: kept like a payment of unknown result. pendingFundingTxid(it, address) ?: throw it } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index bc64801a5f..62abd8b7d2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -2166,11 +2166,18 @@ class SparkExitRepoTest : BaseUnitTest() { fun `a higher fee paid from savings with no answer is kept as the exit's payment`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) store.save(runningRecord()) - stubFunding { Result.failure(OnchainSendPendingError(IOException("no answer"), "bump")) } + stubFunding { + // The error carries no txid: the send journal holds it, unresolved, for the funding address. + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refusedSavingsPayment().copy(evidence = OnchainSendEvidence.Unknown, txid = "bump")) + Result.failure(OnchainSendPendingError(IOException("no answer"))) + } val sut = quotedSut(FakeSparkExitRecovering()) sut.load().getOrThrow() sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)).getOrThrow() + // Progress says at once that it may still land, before any tick. + assertTrue(sut.state.value.isSavingsSendUnresolved) sut.onAppBackgrounded() // It may still go out, so the exit keeps it and its higher fee, and watches for it.