From a409579e13fa0fff3d0f6c904835d9cc38581555 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 07:48:53 -0300 Subject: [PATCH 01/40] fix: let send reach spark before the node runs Hide the sync overlay on the recipient steps, so a Lightning invoice Spark can pay is decoded without waiting for the node. Let Spark take an amountless invoice's amount, and check the entered amount when deciding whether the review can skip the node. Refs #2032 Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 59 +++++++++++++++++-- .../ui/sheets/SendSheetSyncOverlayTest.kt | 33 +++++++++++ changelog.d/next/2032.fixed.md | 1 + 3 files changed, 87 insertions(+), 6 deletions(-) create mode 100644 changelog.d/next/2032.fixed.md diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 4d2b495d8e..881da9e66d 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -116,6 +116,25 @@ private val CHANNELS_REFRESH_INTERVAL = 1.seconds internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) +/** + * The amount Spark would pay for the scanned invoice: its own amount, or for an amountless one the amount entered, so + * the review of an amountless invoice Spark can pay goes ahead without the node too. + */ +internal fun sendInvoiceSats(invoiceSats: ULong?, enteredSats: ULong): ULong? = + invoiceSats?.takeIf { it > 0uL } ?: enteredSats.takeIf { invoiceSats != null && it > 0uL } + +/** + * Whether the amount of an amountless Lightning invoice can be entered without the node: Spark can send, so an amount + * within its balance pays without channels. An LNURL payment still waits for the node. + */ +internal fun sparkCanTakeAmount( + payMethod: SendMethod, + invoiceSats: ULong?, + isLnurl: Boolean, + sparkState: SparkState, +): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats == 0uL && !isLnurl && + sparkState.isUsable && sparkState.sendableSats > 0uL + /** Whether Spark can pay a Quick Pay invoice; an LNURL one still waits for the node. */ internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean = data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState) @@ -140,6 +159,19 @@ internal fun waitsForNode( return hasAnyChannels && !hasUsableChannels } +/** + * Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the + * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. + */ +internal fun isRecipientStep(route: SendRoute): Boolean = when (route) { + SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner -> true + else -> false +} + +internal fun NavDestination.isRecipientStep(): Boolean = + hasRoute() || hasRoute() || + hasRoute() || hasRoute() + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -193,7 +225,23 @@ fun SendSheet( val hasAnyChannels = lightningState.channels.isNotEmpty() val syncNodeVariant = if (hasAnyChannels) SyncNodeVariant.LIGHTNING else SyncNodeVariant.BITCOIN val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() - val sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, sendUiState.decodedInvoice?.amountSatoshis, sparkState) + val invoiceSats = sendUiState.decodedInvoice?.amountSatoshis + val sparkCanPay = sparkCanPayInvoice( + sendUiState.payMethod, + sendInvoiceSats(invoiceSats, sendUiState.amount), + sparkState, + ) + val sparkTakesAmount = sparkCanTakeAmount( + payMethod = sendUiState.payMethod, + invoiceSats = invoiceSats, + isLnurl = sendUiState.lnurl != null, + sparkState = sparkState, + ) + val navController = rememberNavController() + val entry by navController.currentBackStackEntryAsState() + // Until navigation settles the entry is null, and the sheet shows its start destination + val isRecipientStep = entry?.destination?.isRecipientStep() ?: isRecipientStep(startDestination) + val isAmountStep = entry?.destination?.hasRoute() ?: (startDestination == SendRoute.Amount) val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false if (sendUiState.hardwareWalletId != null) return@run false @@ -201,7 +249,7 @@ fun SendSheet( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, - sparkCanPay = sparkCanPay, + sparkCanPay = sparkCanPay || isAmountStep && sparkTakesAmount, ) } @@ -239,8 +287,6 @@ fun SendSheet( .imePadding() .testTag("SendSheet"), ) { - val navController = rememberNavController() - val entry by navController.currentBackStackEntryAsState() val reviewing = entry?.destination?.isPaymentReview() == true LaunchedEffect(reviewing, lifecycle, appViewModel) { if (!reviewing) return@LaunchedEffect @@ -465,7 +511,8 @@ fun SendSheet( val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() SendAmountScreen( uiState = uiState, - nodeLifecycleState = if (uiState.hardwareWalletId != null) { + // Spark takes an amountless invoice's amount without the node, as a hardware wallet does + nodeLifecycleState = if (uiState.hardwareWalletId != null || sparkTakesAmount) { NodeLifecycleState.Running } else { lightningState.nodeLifecycleState @@ -957,7 +1004,7 @@ fun SendSheet( } AnimatedVisibility( - visible = shouldShowSyncOverlay && !isOffline, + visible = shouldShowSyncOverlay && !isRecipientStep && !isOffline, enter = fadeIn(), exit = fadeOut(), ) { diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 8c6a44719e..49c7dd95da 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -4,7 +4,9 @@ import org.junit.Test import to.bitkit.repositories.SparkState import to.bitkit.viewmodels.QuickPayData import to.bitkit.viewmodels.SendMethod +import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SendSheetSyncOverlayTest { @@ -45,4 +47,35 @@ class SendSheetSyncOverlayTest { assertTrue(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = false)) assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = true, sparkCanPay = false)) } + + @Test + fun `recipient steps never wait for the node`() { + listOf(SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner).forEach { + assertTrue(isRecipientStep(it)) + } + listOf(SendRoute.Amount, SendRoute.Confirm, SendRoute.QuickPay).forEach { + assertFalse(isRecipientStep(it)) + } + } + + @Test + fun `an amountless invoice spark pays uses the entered amount`() { + assertEquals(1_000uL, sendInvoiceSats(invoiceSats = 1_000uL, enteredSats = 5uL)) + assertEquals(5uL, sendInvoiceSats(invoiceSats = 0uL, enteredSats = 5uL)) + assertNull(sendInvoiceSats(invoiceSats = 0uL, enteredSats = 0uL)) + assertNull(sendInvoiceSats(invoiceSats = null, enteredSats = 5uL)) + assertTrue(sparkCanPayInvoice(SendMethod.LIGHTNING, sendInvoiceSats(0uL, 1_000uL), funded)) + } + + @Test + fun `spark takes the amount of an amountless invoice only`() { + assertTrue(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 1_000uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, null, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = true, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.ONCHAIN, 0uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(isReady = false))) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(balanceSats = 0uL))) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(isExiting = true))) + } } diff --git a/changelog.d/next/2032.fixed.md b/changelog.d/next/2032.fixed.md new file mode 100644 index 0000000000..03f98cebe5 --- /dev/null +++ b/changelog.d/next/2032.fixed.md @@ -0,0 +1 @@ +Fixed the Send sheet waiting for the Lightning node before you can pick a recipient, and before you can enter the amount of an invoice your spending balance can pay. From cc01758ed5181a2cf43488bfc746fd316cac8671 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 07:53:32 -0300 Subject: [PATCH 02/40] chore: name the changelog fragment after the pr Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/{2032.fixed.md => 2244.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{2032.fixed.md => 2244.fixed.md} (100%) diff --git a/changelog.d/next/2032.fixed.md b/changelog.d/next/2244.fixed.md similarity index 100% rename from changelog.d/next/2032.fixed.md rename to changelog.d/next/2244.fixed.md From b3377474509b2d93010a6ce77dfdec34be02d0f7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 08:05:05 -0300 Subject: [PATCH 03/40] fix: show the node wait on recipient steps and cap amount at spark A scanned payment Spark can't cover still waits for the node from the recipient steps, so show the sync overlay there while that wait runs. While the node is down, cap amount entry for an amountless invoice at Spark's sendable balance, since the cached limit is not refreshed. Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/ui/sheets/SendSheet.kt | 13 ++++++++++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 17 ++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 881da9e66d..c14cbed0c5 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -57,6 +57,7 @@ import to.bitkit.repositories.ConnectivityState import to.bitkit.repositories.PaykitPaymentRequest import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.repositories.SparkState +import to.bitkit.ui.LocalBalances import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.SyncNodeVariant import to.bitkit.ui.components.SyncNodeView @@ -219,6 +220,7 @@ fun SendSheet( val isOffline by remember { derivedStateOf { connectivityState != ConnectivityState.CONNECTED } } val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val sendUiState by appViewModel.sendUiState.collectAsStateWithLifecycle() + val isWaitingForNode by appViewModel.isSendWaitingForNode.collectAsStateWithLifecycle() val contacts by appViewModel.pubkyContacts.collectAsStateWithLifecycle() var routingCacheResetAttempted by rememberSaveable(startDestination) { mutableStateOf(false) } @@ -519,6 +521,14 @@ fun SendSheet( }, canGoBack = startDestination != SendRoute.Amount || uiState.isPaymentRequest, syncNodeVariant = syncNodeVariant, + // The cached limit is not refreshed while the node is down; only Spark can pay then + balances = LocalBalances.current.let { balances -> + if (sparkTakesAmount && !lightningState.nodeLifecycleState.isRunning()) { + balances.copy(maxSendLightningSats = sparkState.sendableSats) + } else { + balances + } + }, onBack = { if (!navController.popBackStack()) { appViewModel.hideSheet() @@ -1004,7 +1014,8 @@ fun SendSheet( } AnimatedVisibility( - visible = shouldShowSyncOverlay && !isRecipientStep && !isOffline, + // A recipient step shows it only while a scanned payment waits for the node + visible = (if (isRecipientStep) isWaitingForNode else shouldShowSyncOverlay) && !isOffline, enter = fadeIn(), exit = fadeOut(), ) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 7dd6254161..c5f5b678ee 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -434,6 +434,12 @@ class AppViewModel @Inject constructor( * usable channel: a running node only publishes its current channels, which the send limit reads, and a node not * running yet is skipped, so a payment opened right after launch does not wait for the node to start. */ + /** Scanned payments Spark can't cover that wait for the node or a usable channel before they can be reviewed. */ + private val _isSendWaitingForNode = MutableStateFlow(0) + val isSendWaitingForNode: StateFlow = _isSendWaitingForNode + .map { it > 0 } + .stateIn(viewModelScope, SharingStarted.Eagerly, false) + private suspend fun waitForUsableChannels( walletGeneration: Long? = connectionRecovery.currentGeneration(), amountSats: ULong? = null, @@ -441,7 +447,16 @@ class AppViewModel @Inject constructor( requireCurrentPaymentPreparation(walletGeneration) val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() val sparkCovers = amountSats != null && lightningRepo.canSendWithSpark(amountSats) - if (isNodeRunning || !sparkCovers) lightningRepo.waitForUsableChannels(awaitUsable = !sparkCovers) + if (isNodeRunning || !sparkCovers) { + // Only waits Spark doesn't skip are shown: the recipient steps have no overlay of their own + val showsWait = !sparkCovers + if (showsWait) _isSendWaitingForNode.update { it + 1 } + try { + lightningRepo.waitForUsableChannels(awaitUsable = !sparkCovers) + } finally { + if (showsWait) _isSendWaitingForNode.update { it - 1 } + } + } requireCurrentPaymentPreparation(walletGeneration) walletRepo.refreshMaxSendLightning() requireCurrentPaymentPreparation(walletGeneration) From 272067dfa83ba26626e8b80c68a90b24045956ff Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 08:12:50 -0300 Subject: [PATCH 04/40] fix: show the node id wait on recipient steps On a cold start the own-invoice check waits for the node id, so count that wait like the channel wait and show the overlay meanwhile. Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c5f5b678ee..c735501ddf 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -429,17 +429,27 @@ class AppViewModel @Inject constructor( if (canPresent()) _mainScreenEffect.emit(effect) } - /** - * Waits for the node's channels before a Lightning send. When Spark covers [amountSats] there is no wait for a - * usable channel: a running node only publishes its current channels, which the send limit reads, and a node not - * running yet is skipped, so a payment opened right after launch does not wait for the node to start. - */ - /** Scanned payments Spark can't cover that wait for the node or a usable channel before they can be reviewed. */ + /** Scanned payments that wait for the node or a usable channel before they can be reviewed. */ private val _isSendWaitingForNode = MutableStateFlow(0) val isSendWaitingForNode: StateFlow = _isSendWaitingForNode .map { it > 0 } .stateIn(viewModelScope, SharingStarted.Eagerly, false) + /** Runs [wait] counted in [isSendWaitingForNode], since the recipient steps have no overlay of their own. */ + private suspend fun showingNodeWait(wait: suspend () -> T): T { + _isSendWaitingForNode.update { it + 1 } + return try { + wait() + } finally { + _isSendWaitingForNode.update { it - 1 } + } + } + + /** + * Waits for the node's channels before a Lightning send. When Spark covers [amountSats] there is no wait for a + * usable channel: a running node only publishes its current channels, which the send limit reads, and a node not + * running yet is skipped, so a payment opened right after launch does not wait for the node to start. + */ private suspend fun waitForUsableChannels( walletGeneration: Long? = connectionRecovery.currentGeneration(), amountSats: ULong? = null, @@ -447,15 +457,10 @@ class AppViewModel @Inject constructor( requireCurrentPaymentPreparation(walletGeneration) val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() val sparkCovers = amountSats != null && lightningRepo.canSendWithSpark(amountSats) - if (isNodeRunning || !sparkCovers) { - // Only waits Spark doesn't skip are shown: the recipient steps have no overlay of their own - val showsWait = !sparkCovers - if (showsWait) _isSendWaitingForNode.update { it + 1 } - try { - lightningRepo.waitForUsableChannels(awaitUsable = !sparkCovers) - } finally { - if (showsWait) _isSendWaitingForNode.update { it - 1 } - } + when { + // A wait for a usable channel is shown; with Spark covering, only the channels are published + !sparkCovers -> showingNodeWait { lightningRepo.waitForUsableChannels(awaitUsable = true) } + isNodeRunning -> lightningRepo.waitForUsableChannels(awaitUsable = false) } requireCurrentPaymentPreparation(walletGeneration) walletRepo.refreshMaxSendLightning() @@ -3862,7 +3867,10 @@ class AppViewModel @Inject constructor( return@takeIf canSend } - private suspend fun LightningInvoice.isOwnInvoice(): Boolean = isPayee(lightningRepo.awaitNodeId()) + /** On a cold start the node id is known only once the node runs, so that wait is shown. */ + private suspend fun LightningInvoice.isOwnInvoice(): Boolean = isPayee( + lightningRepo.getLastKnownNodeId() ?: showingNodeWait { lightningRepo.awaitNodeId() } + ) private fun LightningInvoice.isPayee(nodeId: String?): Boolean { val payee = payeeNodeId?.toHex() ?: return false From 1064562536c7a879068a6f9ecca528618c4e8bf6 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 09:31:15 -0300 Subject: [PATCH 05/40] fix: keep the sync overlay off a submitted send A Spark payment can be submitted before the node runs, and its balance then no longer covers it, so the overlay came back over the pending or result screen. Skip it on the routes after submission. Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index c14cbed0c5..5dd118bc9f 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -173,6 +173,11 @@ internal fun NavDestination.isRecipientStep(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() +/** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */ +internal fun NavDestination.isPastReview(): Boolean = + hasRoute() || hasRoute() || hasRoute() || + hasRoute() || hasRoute() + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -244,9 +249,11 @@ fun SendSheet( // Until navigation settles the entry is null, and the sheet shows its start destination val isRecipientStep = entry?.destination?.isRecipientStep() ?: isRecipientStep(startDestination) val isAmountStep = entry?.destination?.hasRoute() ?: (startDestination == SendRoute.Amount) + // A Spark payment can be submitted before the node runs, and its balance then no longer covers it + val isPastReview = entry?.destination?.isPastReview() == true val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false - if (sendUiState.hardwareWalletId != null) return@run false + if (sendUiState.hardwareWalletId != null || isPastReview) return@run false waitsForNode( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), hasAnyChannels = hasAnyChannels, From 1b89d0fbe5f05c6b7e19803d67fcbbe9de9af827 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 11:05:48 -0300 Subject: [PATCH 06/40] fix: accept amounts spark can pay above the cached limit Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../bitkit/viewmodels/AppViewModelSendFlowTest.kt | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c735501ddf..e8056a1f3e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5573,7 +5573,9 @@ class AppViewModel @Inject constructor( sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() when (val lnurl = _sendUiState.value.lnurl) { - null -> amount <= maxSendable && lightningRepo.canSend(amount) + // The cached limit is re-derived only once the node runs, so it can trail Spark's balance + null -> (amount <= maxSendable || lightningRepo.canSendWithSpark(amount)) && + lightningRepo.canSend(amount) is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat() is LnurlParams.LnurlPay -> { val maxSat = lnurl.data.maxSendableSat() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bde5131368..98a1f167e7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -4407,6 +4407,20 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(hwWalletRepo).cancelPairingCode() } + @Test + fun `amount Spark can pay is valid above a stale spending limit`() = test { + // The cached limit is only re-derived once the node runs, so it can trail Spark's balance + balanceState.value = BalanceState(maxSendLightningSats = 1_000u) + whenever(lightningRepo.canSendWithSpark(5_000u)).thenReturn(true) + whenever(lightningRepo.canSend(5_000u)).thenReturn(true) + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING)) + + sut.setSendEvent(SendEvent.AmountChange(5_000u)) + advanceUntilIdle() + + assertTrue(sut.sendUiState.value.isAmountInputValid) + } + @Test fun `canSwitchWallet is false when not unified`() = test { sut.setSendEvent(SendEvent.AmountChange(1000u)) From cf5826592ad4d6bc655976662a114ec338150dcb Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 11:06:02 -0300 Subject: [PATCH 07/40] fix: cap the amount pad at spark's balance before the node runs Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt index 265f54f871..746e789995 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt @@ -194,6 +194,7 @@ fun SendAmountScreen( amountInputViewModel = amountInputViewModel, syncNodeVariant = syncNodeVariant, currencies = currencies, + balances = balances, onBack = { onEvent(SendEvent.AmountReset) onBack() From 90fddb07c1d6438bb131ac9feef97eba0c33e68f Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 11:26:41 -0300 Subject: [PATCH 08/40] fix: wait for the node before rejecting a typed invoice Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e8056a1f3e..31819805a1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3692,6 +3692,8 @@ class AppViewModel @Inject constructor( } if (invoice.amountSatoshis > 0uL) { + // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount + waitForUsableChannels(amountSats = invoice.amountSatoshis) lightningRepo.syncState() if (!lightningRepo.canSend(invoice.amountSatoshis)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 98a1f167e7..31bd91ed4b 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5561,6 +5561,24 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(coreService, never()).decode(any()) } + @Test + fun `manual invoice Spark cannot cover waits for the node before checking capacity`() = test { + val bolt11 = "lnbcrt1manualwait" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + inOrder(lightningRepo) { + verify(lightningRepo).waitForUsableChannels(awaitUsable = true) + verify(lightningRepo).canSend(50_000u) + } + assertTrue(sut.sendUiState.value.isAddressInputValid) + } + @Test fun `manual own USDT address explains why sending is blocked`() = test { if (!Env.isUsdtEnabled) return@test From 652c67b1028c9274e102ebd5368a7cebec14a7ef Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 12:18:39 -0300 Subject: [PATCH 09/40] fix: skip the typed invoice node wait once the node runs Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 31819805a1..fb6315b15f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3693,7 +3693,9 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount - waitForUsableChannels(amountSats = invoice.amountSatoshis) + if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + waitForUsableChannels(amountSats = invoice.amountSatoshis) + } lightningRepo.syncState() if (!lightningRepo.canSend(invoice.amountSatoshis)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 31bd91ed4b..960f0fe619 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5579,6 +5579,23 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isAddressInputValid) } + @Test + fun `manual invoice with the node running checks capacity without waiting`() = test { + val bolt11 = "lnbcrt1manualrunning" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + verify(lightningRepo).canSend(50_000u) + } + @Test fun `manual own USDT address explains why sending is blocked`() = test { if (!Env.isUsdtEnabled) return@test From fa15097594e418804313d29edb6ca52c8916c534 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 13:27:43 -0300 Subject: [PATCH 10/40] fix: keep the routing fee reserve for spark amounts Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index fb6315b15f..9935cc65ad 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5576,9 +5576,11 @@ class AppViewModel @Inject constructor( SendMethod.LIGHTNING -> { sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() + // Spark keeps the routing reserve that Available leaves out + val sparkDebit = amount.safe() + _sendUiState.value.estimatedRoutingFee.safe() when (val lnurl = _sendUiState.value.lnurl) { // The cached limit is re-derived only once the node runs, so it can trail Spark's balance - null -> (amount <= maxSendable || lightningRepo.canSendWithSpark(amount)) && + null -> (amount <= maxSendable || lightningRepo.canSendWithSpark(sparkDebit)) && lightningRepo.canSend(amount) is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat() is LnurlParams.LnurlPay -> { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 960f0fe619..622c52a75f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5596,6 +5596,24 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo).canSend(50_000u) } + @Test + fun `amount Spark can pay keeps the routing fee reserve`() = test { + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSendWithSpark(9_950u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(10_000u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(10_050u)).thenReturn(false) + whenever(lightningRepo.canSend(any())).thenReturn(true) + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, estimatedRoutingFee = 100u)) + + sut.setSendEvent(SendEvent.AmountChange(9_950u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isAmountInputValid) + + sut.setSendEvent(SendEvent.AmountChange(9_900u)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid) + } + @Test fun `manual own USDT address explains why sending is blocked`() = test { if (!Env.isUsdtEnabled) return@test From 7c9ab3653a45d1c3936192d18981eba873b3d0da Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 13:44:52 -0300 Subject: [PATCH 11/40] fix: cancel typed invoice validation when leaving it Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 2 ++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 5dd118bc9f..b3f866cbca 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue @@ -465,6 +466,7 @@ fun SendSheet( } composableWithDefaultTransitions { val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle() + DisposableEffect(Unit) { onDispose { appViewModel.cancelAddressValidation() } } SendAddressScreen( uiState = uiState, onBack = { navController.popBackStack() }, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9935cc65ad..96464341a8 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3595,6 +3595,11 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToAddress) } + /** A typed address can wait for the node, so leaving it must stop that wait and its late result. */ + fun cancelAddressValidation() { + addressValidationJob?.cancel() + } + private fun resetAddressInput() { addressValidationJob?.cancel() _sendUiState.update { state -> @@ -9569,6 +9574,7 @@ class AppViewModel @Inject constructor( // A read still preparing belongs to this Send visit: it must not reopen a sheet or reach QuickPay. // A scan that closes Send itself keeps running, and no later visit may cancel it. if (isRunningScan.get() != true) cancelSendVisitScan() else sendVisitScanJob = null + cancelAddressValidation() hasLeftSendRecipient = true sendStateGeneration++ // A closed send is over: a swap failing for it later gives no contact back to whatever comes next. diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 622c52a75f..6570a3ac07 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5596,6 +5596,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo).canSend(50_000u) } + @Test + fun `closing Send cancels a typed invoice's node wait`() = test { + val bolt11 = "lnbcrt1manualclosed" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val nodeReady = CompletableDeferred() + whenever(lightningRepo.waitForUsableChannels(any())).doSuspendableAnswer { nodeReady.await() } + sut.showSheet(Sheet.Send()) + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceTimeBy(5_000) + runCurrent() + assertTrue(sut.isSendWaitingForNode.value) + + sut.hideSheet() + runCurrent() + nodeReady.complete(Unit) + advanceUntilIdle() + + assertFalse(sut.isSendWaitingForNode.value) + assertFalse(sut.sendUiState.value.isAddressInputValid) + } + @Test fun `amount Spark can pay keeps the routing fee reserve`() = test { balanceState.value = BalanceState(maxSendLightningSats = 10_000u) From 54c3525918516b05b1c98e9b6bfa5244e3be4f5a Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 15:30:13 -0300 Subject: [PATCH 12/40] fix: show coming soon at once while the node starts Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 4 ++-- .../java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index b3f866cbca..bce57bc38d 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -166,13 +166,13 @@ internal fun waitsForNode( * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. */ internal fun isRecipientStep(route: SendRoute): Boolean = when (route) { - SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner -> true + SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner, SendRoute.ComingSoon -> true else -> false } internal fun NavDestination.isRecipientStep(): Boolean = hasRoute() || hasRoute() || - hasRoute() || hasRoute() + hasRoute() || hasRoute() || hasRoute() /** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */ internal fun NavDestination.isPastReview(): Boolean = diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 49c7dd95da..9d8d43698c 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -50,7 +50,14 @@ class SendSheetSyncOverlayTest { @Test fun `recipient steps never wait for the node`() { - listOf(SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner).forEach { + // Coming Soon is Contact's fallback while Paykit is off, so it shows at once too + listOf( + SendRoute.Recipient, + SendRoute.Address, + SendRoute.ContactSelect, + SendRoute.QrScanner, + SendRoute.ComingSoon, + ).forEach { assertTrue(isRecipientStep(it)) } listOf(SendRoute.Amount, SendRoute.Confirm, SendRoute.QuickPay).forEach { From e5584b29eb143370fde3465201b06cb6181c8c74 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 15:30:30 -0300 Subject: [PATCH 13/40] fix: quote the max routing fee from spark's live limit Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/repositories/LightningRepo.kt | 3 +++ .../main/java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../bitkit/viewmodels/AppViewModelSendFlowTest.kt | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..3918353e7f 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3133,6 +3133,9 @@ class LightningRepo @Inject constructor( /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) + /** The most Spark can send now, its own fee kept, which the cached Spending limit trails until the node runs. */ + fun sparkSendableSats(): ULong = sparkRepo.state.value.sendableSats + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 96464341a8..8fb8e96cdd 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -9230,7 +9230,9 @@ class AppViewModel @Inject constructor( val decodedInvoice = currentState.decodedInvoice ?: return val bolt11 = decodedInvoice.bolt11 - val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats + // The cached limit is re-derived only once the node runs, so Spark's live amount is quoted while it trails + val cachedMax = walletRepo.balanceState.value.maxSendLightningSats + val maxSendLightning = maxOf(cachedMax, lightningRepo.sparkSendableSats()) if (maxSendLightning == 0uL) { _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } return diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6570a3ac07..c3054135e9 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5637,6 +5637,20 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isAmountInputValid) } + @Test + fun `max routing fee is quoted from Spark while the cached limit trails it`() = test { + val bolt11 = "lnbcrt1maxspark" + balanceState.value = BalanceState(maxSendLightningSats = 0u) + whenever(lightningRepo.sparkSendableSats()).thenReturn(40_000u) + whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).thenReturn(Result.success(120u)) + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u))) + + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee) + advanceUntilIdle() + + assertEquals(120uL, sut.sendUiState.value.estimatedRoutingFee) + } + @Test fun `manual own USDT address explains why sending is blocked`() = test { if (!Env.isUsdtEnabled) return@test From 37f8ec486c745af636ea0cc69d24dde0e61d4263 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 3 Dec 2026 15:30:30 -0300 Subject: [PATCH 14/40] fix: keep typed invoices pending through a queued node start Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/LightningRepo.kt | 15 ++++++++++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++ .../bitkit/repositories/LightningRepoTest.kt | 29 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 16 ++++++++++ 4 files changed, 64 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 3918353e7f..b2ec8575cb 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3136,6 +3136,21 @@ class LightningRepo @Inject constructor( /** The most Spark can send now, its own fee kept, which the cached Spending limit trails until the node runs. */ fun sparkSendableSats(): ULong = sparkRepo.state.value.sendableSats + /** + * Waits, up to [NODE_RUN_WAIT_TIMEOUT], while the node is stopping or a start is queued, so a caller that then + * checks channels sees the restarted node rather than the stop. Returns at once when no start is coming. + */ + suspend fun awaitPendingNodeStart() { + val changes = combine(_lightningState, pendingStartCount) { _, _ -> } + withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { + changes.first { + val lifecycle = _lightningState.value.nodeLifecycleState + val isComing = lifecycle is NodeLifecycleState.Stopping || pendingStartCount.value > 0 + lifecycle.canRun() || !isComing + } + } + } + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 8fb8e96cdd..9bbdb5ca91 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3699,6 +3699,10 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + // A foreground start can queue behind a background stop, which reads as unable to run + if (!lightningRepo.canSendWithSpark(invoice.amountSatoshis)) { + showingNodeWait { lightningRepo.awaitPendingNodeStart() } + } waitForUsableChannels(amountSats = invoice.amountSatoshis) } lightningRepo.syncState() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a0aa9ec43e..de67f24a9f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1967,6 +1967,35 @@ class LightningRepoTest : BaseUnitTest() { } } + @Test + fun `a pending node start is awaited through a stop it queued behind`() = test { + startNodeForTesting() + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + val wait = async { sut.awaitPendingNodeStart() } + val start = launch { sut.start() } + runCurrent() + assertFalse(wait.isCompleted, "The wait ended while the node was stopping") + stopped.complete(Unit) + stop.join() + start.join() + wait.await() + + assertTrue(sut.lightningState.value.nodeLifecycleState.isRunning()) + } + } + + @Test + fun `a pending node start returns at once when the node is stopped with no start coming`() = test { + startNodeForTesting() + sut.stop() + + sut.awaitPendingNodeStart() + + assertEquals(NodeLifecycleState.Stopped, sut.lightningState.value.nodeLifecycleState) + } + @Test fun `a spark send held while the node stops fails once it is stopped with no start coming`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index c3054135e9..8a52792d78 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5573,12 +5573,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() inOrder(lightningRepo) { + verify(lightningRepo).awaitPendingNodeStart() verify(lightningRepo).waitForUsableChannels(awaitUsable = true) verify(lightningRepo).canSend(50_000u) } assertTrue(sut.sendUiState.value.isAddressInputValid) } + @Test + fun `manual invoice Spark covers skips the queued node start`() = test { + val bolt11 = "lnbcrt1manualspark" + stubLightningScan(bolt11 = bolt11, amountSats = 5_000u) + whenever(lightningRepo.canSendWithSpark(5_000u)).thenReturn(true) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + verify(lightningRepo, never()).awaitPendingNodeStart() + verify(lightningRepo, never()).waitForUsableChannels(awaitUsable = true) + } + @Test fun `manual invoice with the node running checks capacity without waiting`() = test { val bolt11 = "lnbcrt1manualrunning" From c03deaae490bdfb153c5fc20c389abc8bd3544c0 Mon Sep 17 00:00:00 2001 From: Piotr Stachyra Date: Fri, 4 Dec 2026 09:09:27 +0100 Subject: [PATCH 15/40] fix: quote the visible Lightning limit and validate Spark Max in the current Send --- .../to/bitkit/repositories/LightningRepo.kt | 3 - .../screens/wallets/send/SendAmountScreen.kt | 7 +- .../java/to/bitkit/ui/sheets/SendSheet.kt | 19 ++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 87 +++++++++++++------ .../ui/sheets/SendSheetSyncOverlayTest.kt | 9 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 56 ++++++++++-- journeys/send/onchain-connecting-view.xml | 13 ++- 7 files changed, 142 insertions(+), 52 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index b2ec8575cb..ad51a99c0c 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3133,9 +3133,6 @@ class LightningRepo @Inject constructor( /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) - /** The most Spark can send now, its own fee kept, which the cached Spending limit trails until the node runs. */ - fun sparkSendableSats(): ULong = sparkRepo.state.value.sendableSats - /** * Waits, up to [NODE_RUN_WAIT_TIMEOUT], while the node is stopping or a start is queued, so a caller that then * checks channels sees the restarted node rather than the stop. Returns at once when no start is coming. diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt index 746e789995..a4c339543b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt @@ -182,9 +182,10 @@ fun SendAmountScreen( } } - LaunchedEffect(uiState.decodedInvoice, uiState.payMethod) { + LaunchedEffect(uiState.decodedInvoice, uiState.payMethod, balances.maxSendLightningSats) { if (uiState.payMethod == SendMethod.LIGHTNING && uiState.decodedInvoice != null) { - currentOnEvent(SendEvent.EstimateMaxRoutingFee) + val quote = SendEvent.EstimateMaxRoutingFee(uiState.decodedInvoice.bolt11, balances.maxSendLightningSats) + currentOnEvent(quote) } } @@ -464,7 +465,7 @@ private fun SendAmountNodeRunning( PrimaryButton( text = stringResource(R.string.common__continue), - enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading, + enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading && !uiState.awaitsSparkMaxFee, isLoading = uiState.isLoading, onClick = onContinue, textStyle = if (uiState.paykitUsesUsdt) AppTextStyles.BodySSB.copy(letterSpacing = 0.sp) else null, diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index bce57bc38d..570c5df809 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -137,6 +137,12 @@ internal fun sparkCanTakeAmount( ): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats == 0uL && !isLnurl && sparkState.isUsable && sparkState.sendableSats > 0uL +internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, isNodeRunning: Boolean): ULong = when { + sparkMax == null -> cachedMax + isNodeRunning -> maxOf(cachedMax, sparkMax) + else -> sparkMax +} + /** Whether Spark can pay a Quick Pay invoice; an LNURL one still waits for the node. */ internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean = data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState) @@ -530,13 +536,14 @@ fun SendSheet( }, canGoBack = startDestination != SendRoute.Amount || uiState.isPaymentRequest, syncNodeVariant = syncNodeVariant, - // The cached limit is not refreshed while the node is down; only Spark can pay then balances = LocalBalances.current.let { balances -> - if (sparkTakesAmount && !lightningState.nodeLifecycleState.isRunning()) { - balances.copy(maxSendLightningSats = sparkState.sendableSats) - } else { - balances - } + balances.copy( + maxSendLightningSats = lightningAmountLimit( + cachedMax = balances.maxSendLightningSats, + sparkMax = sparkState.sendableSats.takeIf { sparkTakesAmount }, + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + ), + ) }, onBack = { if (!navController.popBackStack()) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 2df401cd04..089d27e327 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -476,6 +476,7 @@ class AppViewModel @Inject constructor( /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ @Volatile private var sendSession = 0L + private var maxRoutingFeeJob: Job? = null /** Swipes and payments still running from the confirm screen, by [sendSession]; see [isSendSwipeRunning]. */ private val sendSwipeRuns = mutableMapOf() @@ -3637,9 +3638,7 @@ class AppViewModel @Inject constructor( SendEvent.CancelInitialSubscriptionPayment -> onCancelInitialSubscriptionPayment() is SendEvent.ConfirmAmountWarning -> onConfirmAmountWarning(it.warning) SendEvent.DismissAmountWarning -> onDismissAmountWarning() - SendEvent.EstimateMaxRoutingFee -> viewModelScope.launch { - estimateMaxAmountRoutingFee() - } + is SendEvent.EstimateMaxRoutingFee -> estimateMaxAmountRoutingFee(it) SendEvent.PayConfirmed -> onConfirmPay() SendEvent.ClearPayConfirmation -> _sendUiState.update { s -> s.copy(shouldConfirmPay = false) } @@ -5222,6 +5221,7 @@ class AppViewModel @Inject constructor( private suspend fun onAmountContinue() { if (_sendUiState.value.isLoading || !reviewPaykitAmount()) return + if (!isAmountlessInvoiceWithinLimit()) return _sendUiState.update { it.copy( selectedUtxos = null, @@ -5259,7 +5259,12 @@ class AppViewModel @Inject constructor( } updateCanSwitchWallet() - setSendEffect(SendEffect.NavigateToConfirm) + setSendEffect(SendEffect.NavigateToConfirm) { isAmountlessInvoiceWithinLimit() } + } + + private suspend fun isAmountlessInvoiceWithinLimit(): Boolean { + val state = _sendUiState.value + return !state.isAmountlessLightningInvoice || (!state.awaitsSparkMaxFee && validateAmount(state.amount)) } /** @@ -5671,15 +5676,19 @@ class AppViewModel @Inject constructor( private suspend fun validateAmount( amount: ULong, payMethod: SendMethod = _sendUiState.value.payMethod, + routingFee: ULong = _sendUiState.value.estimatedRoutingFee, ): Boolean { if (amount == 0uL) return false return when (payMethod) { SendMethod.LIGHTNING -> { sparkWithdrawalValidity(amount)?.let { return it } - val maxSendable = maxSendableLightningSats() + val maxSendable = maxSendableLightningSats(routingFee) // Spark keeps the routing reserve that Available leaves out - val sparkDebit = amount.safe() + _sendUiState.value.estimatedRoutingFee.safe() + val sparkDebit = amount.safe() + routingFee.safe() + if (onlySparkTakesInvoiceAmount(_sendUiState.value)) { + return lightningRepo.canSendWithSpark(sparkDebit) + } when (val lnurl = _sendUiState.value.lnurl) { // The cached limit is re-derived only once the node runs, so it can trail Spark's balance null -> (amount <= maxSendable || lightningRepo.canSendWithSpark(sparkDebit)) && @@ -5745,9 +5754,8 @@ class AppViewModel @Inject constructor( return true.takeIf { lightningRepo.canWithdrawWithSpark(amount) } } - private fun maxSendableLightningSats(): ULong { + private fun maxSendableLightningSats(fee: ULong = _sendUiState.value.estimatedRoutingFee): ULong { val max = walletRepo.balanceState.value.maxSendLightningSats - val fee = _sendUiState.value.estimatedRoutingFee return max.safe() - fee.safe() } @@ -9320,26 +9328,40 @@ class AppViewModel @Inject constructor( } } - private suspend fun estimateMaxAmountRoutingFee() { - val currentState = _sendUiState.value - if (currentState.payMethod != SendMethod.LIGHTNING) return + private fun onlySparkTakesInvoiceAmount(state: SendUiState) = + state.isAmountlessLightningInvoice && !lightningRepo.lightningState.value.nodeLifecycleState.isRunning() && + lightningRepo.canSendWithSpark(1u) - val decodedInvoice = currentState.decodedInvoice ?: return - val bolt11 = decodedInvoice.bolt11 - - // The cached limit is re-derived only once the node runs, so Spark's live amount is quoted while it trails - val cachedMax = walletRepo.balanceState.value.maxSendLightningSats - val maxSendLightning = maxOf(cachedMax, lightningRepo.sparkSendableSats()) - if (maxSendLightning == 0uL) { - _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } - return - } - - lightningRepo.estimateMaxSendFee(bolt11, maxSendLightning).onSuccess { fee -> - _sendUiState.update { it.copy(estimatedRoutingFee = fee) } - }.onFailure { e -> - Logger.error("Failed to estimate routing fee for max amount", e, context = TAG) - _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } + private fun estimateMaxAmountRoutingFee(quote: SendEvent.EstimateMaxRoutingFee) { + val session = sendSession + val current = _sendUiState.value + if (current.payMethod != SendMethod.LIGHTNING || current.decodedInvoice?.bolt11 != quote.bolt11) return + maxRoutingFeeJob?.cancel() + val pendingInvoice = quote.bolt11.takeIf { onlySparkTakesInvoiceAmount(current) } + _sendUiState.update { it.copy(pendingSparkMaxInvoice = pendingInvoice) } + maxRoutingFeeJob = viewModelScope.launch { + val fee = if (quote.maxSendSats == 0uL) { + 0uL + } else { + lightningRepo.estimateMaxSendFee(quote.bolt11, quote.maxSendSats).getOrElse { error -> + Logger.warn("Failed to estimate routing fee for max amount", error, context = TAG) + 0uL + } + } + ensureActive() + _sendUiState.update { state -> + if (session != sendSession || state.payMethod != SendMethod.LIGHTNING || + state.decodedInvoice?.bolt11 != quote.bolt11 + ) { + return@update state + } + val valid = if (state.isAmountlessLightningInvoice) { + validateAmount(state.amount, routingFee = fee) + } else { + state.isAmountInputValid + } + state.copy(estimatedRoutingFee = fee, isAmountInputValid = valid, pendingSparkMaxInvoice = null) + } } } @@ -11149,6 +11171,7 @@ data class SendUiState( val onchainFeeUi: OnchainFeeUi = OnchainFeeUi(), val lightningFeeSats: Long? = null, val estimatedRoutingFee: ULong = 0uL, + val pendingSparkMaxInvoice: String? = null, val lastLightningFee: Long = 0L, val contactPaymentProfile: PubkyProfile? = null, val isPaymentRequest: Boolean = false, @@ -11203,6 +11226,14 @@ data class SendUiState( val routedPaykitRoute: PaykitRouteUi? get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } + val awaitsSparkMaxFee: Boolean + get() = isAmountlessLightningInvoice && pendingSparkMaxInvoice != null && + pendingSparkMaxInvoice == decodedInvoice?.bolt11 + + val isAmountlessLightningInvoice: Boolean + get() = payMethod == SendMethod.LIGHTNING && decodedInvoice?.amountSatoshis == 0uL && + lnurl == null && paykitRoute == null && !isPaymentRequest && !paykitUsesUsdt + /** Whether bitkit-core's router picks how this contact payment is paid; USDT and hardware wallets pay as picked. */ val routesPaykitPayment: Boolean get() = !paykitUsesUsdt && hardwareWalletId == null && lnurl !is LnurlParams.LnurlWithdraw @@ -11493,7 +11524,7 @@ sealed interface SendEvent { data object PaymentMethodSwitch : SendEvent data class PaymentMethodSelect(val source: SendFundingSource) : SendEvent data class ConfirmAmountWarning(val warning: SanityWarning) : SendEvent - data object EstimateMaxRoutingFee : SendEvent + data class EstimateMaxRoutingFee(val bolt11: String, val maxSendSats: ULong) : SendEvent data object DismissAmountWarning : SendEvent data object PayConfirmed : SendEvent data object ClearPayConfirmation : SendEvent diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 9d8d43698c..d758f03dbc 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -74,6 +74,15 @@ class SendSheetSyncOverlayTest { assertTrue(sparkCanPayInvoice(SendMethod.LIGHTNING, sendInvoiceSats(0uL, 1_000uL), funded)) } + @Test + fun `amount entry and its Max quote use the capacity of the available rails`() { + assertEquals(40_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, null, isNodeRunning = true)) + } + @Test fun `spark takes the amount of an amountless invoice only`() { assertTrue(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 0c20e6d065..536a1b526f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5656,17 +5656,63 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `max routing fee is quoted from Spark while the cached limit trails it`() = test { + fun `max quote uses the displayed Spark limit and revalidates the entered amount`() = test { val bolt11 = "lnbcrt1maxspark" - balanceState.value = BalanceState(maxSendLightningSats = 0u) - whenever(lightningRepo.sparkSendableSats()).thenReturn(40_000u) - whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).thenReturn(Result.success(120u)) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.canSendWithSpark(1u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(40_000u)).thenReturn(true) + val quote = CompletableDeferred>() + whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).doSuspendableAnswer { quote.await() } setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u))) - sut.setSendEvent(SendEvent.EstimateMaxRoutingFee) + sut.setSendEvent(SendEvent.AmountMax(40_000u)) advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid) + + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 40_000u)) + runCurrent() + assertTrue(sut.sendUiState.value.awaitsSparkMaxFee) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + quote.complete(Result.success(120u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.awaitsSparkMaxFee) assertEquals(120uL, sut.sendUiState.value.estimatedRoutingFee) + assertFalse(sut.sendUiState.value.isAmountInputValid) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + } + + @Test + fun `a delayed Max quote cannot update another invoice or a reopened Send`() = test { + val bolt11 = "lnbcrt1maxfirst" + val first = SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u)) + for (reopen in listOf(false, true)) { + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + setSendState(first) + val quote = CompletableDeferred>() + whenever(lightningRepo.estimateMaxSendFee(bolt11, 1000u)).doSuspendableAnswer { quote.await() } + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 1000u)) + runCurrent() + if (reopen) { + sut.hideSheet() + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + } + val nextInvoice = if (reopen) bolt11 else "lnbcrt1maxsecond" + setSendState(first.copy(decodedInvoice = lightningInvoice(nextInvoice, 0u), estimatedRoutingFee = 10u)) + quote.complete(if (reopen) Result.failure(IllegalStateException("old quote")) else Result.success(76u)) + advanceUntilIdle() + assertEquals(10uL, sut.sendUiState.value.estimatedRoutingFee) + } } @Test diff --git a/journeys/send/onchain-connecting-view.xml b/journeys/send/onchain-connecting-view.xml index 3b28bbdf9f..93ab406334 100644 --- a/journeys/send/onchain-connecting-view.xml +++ b/journeys/send/onchain-connecting-view.xml @@ -6,19 +6,18 @@ "Please wait for Bitkit to connect to the bitcoin network (±10 seconds)." A wallet whose channels have loaded keeps the purple Spending variant. - The view shows only until the node runs. A cold launch shows home only once the node runs, so - restart the node from the LDK debug screen and open Send at once; the view then shows for about - 2 seconds. Take a screenshot or record as soon as Send opens. iOS reaches the view by another - route; see its journey and journeys/README.md. - - Precondition: onboarded dev wallet with no Lightning channels. Start on the wallet home screen. + Precondition: onboarded regtest wallet with confirmed Savings and no channels. Copy another + regtest wallet's on-chain address without an amount. Restart the node from the LDK debug screen with node startup + held long enough to paste the address, then release startup at the step below. Tap the header menu (testTag "HeaderMenu") and then Settings (testTag "DrawerSettings") Tap the Advanced tab (testTag "Tab-advanced"), then Dev Settings (testTag "DevSettings"), then LDK Tap Restart, go back to the wallet home screen at once and tap Send (testTag "Send") + Verify Recipient shows Scan, Paste and Enter Manually and the connecting overlay is absent + Tap Paste to open Amount for the copied on-chain address Verify the Send sheet shows the "Send Bitcoin" header, "Connecting to network" with "Connecting" in orange, the bitcoin coin inside orange rings, the text "Please wait for Bitkit to connect to the bitcoin network (±10 seconds)." and a spinner - Verify the view gives way to the Send recipient screen once the node runs + Release node startup and verify the overlay clears to Amount with Savings available and the number pad enabled Close the Send sheet From c7c0c1fc3c0805f05cfd0439bcdbd71239b10842 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 06:43:49 -0300 Subject: [PATCH 16/40] fix: wait for a slow or queued node start before checking channels Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/LightningRepo.kt | 10 ++++++---- .../java/to/bitkit/viewmodels/AppViewModel.kt | 12 ++++++------ .../bitkit/repositories/LightningRepoTest.kt | 18 ++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 17 +++++++++++++++++ 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index ad51a99c0c..cfef315d02 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3134,16 +3134,18 @@ class LightningRepo @Inject constructor( fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) /** - * Waits, up to [NODE_RUN_WAIT_TIMEOUT], while the node is stopping or a start is queued, so a caller that then - * checks channels sees the restarted node rather than the stop. Returns at once when no start is coming. + * Waits, up to [NODE_RUN_WAIT_TIMEOUT], until the node runs while it is starting, stopping or has a start queued, + * so a caller that then checks channels sees the running node rather than a start the channel wait gives up on. + * Returns at once when the node runs or no start is coming. */ suspend fun awaitPendingNodeStart() { val changes = combine(_lightningState, pendingStartCount) { _, _ -> } withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { changes.first { val lifecycle = _lightningState.value.nodeLifecycleState - val isComing = lifecycle is NodeLifecycleState.Stopping || pendingStartCount.value > 0 - lifecycle.canRun() || !isComing + val isStopping = lifecycle is NodeLifecycleState.Stopping + val isComing = lifecycle.canRun() || isStopping || pendingStartCount.value > 0 + lifecycle.isRunning() || !isComing } } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 089d27e327..5a7414df47 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -458,8 +458,12 @@ class AppViewModel @Inject constructor( val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() val sparkCovers = amountSats != null && lightningRepo.canSendWithSpark(amountSats) when { - // A wait for a usable channel is shown; with Spark covering, only the channels are published - !sparkCovers -> showingNodeWait { lightningRepo.waitForUsableChannels(awaitUsable = true) } + // A wait for a usable channel is shown, past a slow or queued start; with Spark covering, only the + // channels are published + !sparkCovers -> showingNodeWait { + lightningRepo.awaitPendingNodeStart() + lightningRepo.waitForUsableChannels(awaitUsable = true) + } isNodeRunning -> lightningRepo.waitForUsableChannels(awaitUsable = false) } requireCurrentPaymentPreparation(walletGeneration) @@ -3791,10 +3795,6 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { - // A foreground start can queue behind a background stop, which reads as unable to run - if (!lightningRepo.canSendWithSpark(invoice.amountSatoshis)) { - showingNodeWait { lightningRepo.awaitPendingNodeStart() } - } waitForUsableChannels(amountSats = invoice.amountSatoshis) } lightningRepo.syncState() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index de67f24a9f..8e2b8c6459 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1986,6 +1986,24 @@ class LightningRepoTest : BaseUnitTest() { } } + @Test + fun `a pending node start is awaited while the node is still starting`() = test { + val starting = CompletableDeferred() + whenever(lightningService.start(anyOrNull(), any())).doSuspendableAnswer { starting.await() } + val start = launch { sut.start() } + runCurrent() + assertTrue(sut.lightningState.value.nodeLifecycleState.isStarting()) + + val wait = async { sut.awaitPendingNodeStart() } + runCurrent() + assertFalse(wait.isCompleted, "The wait ended while the node was starting") + starting.complete(Unit) + start.join() + wait.await() + + assertTrue(sut.lightningState.value.nodeLifecycleState.isRunning()) + } + @Test fun `a pending node start returns at once when the node is stopped with no start coming`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 536a1b526f..74c232e29a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5582,6 +5582,23 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isAddressInputValid) } + @Test + fun `scanned invoice Spark cannot cover waits for a pending node start before checking capacity`() = test { + val bolt11 = "lnbcrt1scanwait" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + inOrder(lightningRepo) { + verify(lightningRepo).awaitPendingNodeStart() + verify(lightningRepo).waitForUsableChannels(awaitUsable = true) + verify(lightningRepo).canSend(50_000u) + } + } + @Test fun `manual invoice Spark covers skips the queued node start`() = test { val bolt11 = "lnbcrt1manualspark" From f467ac09f651c97dea21bc1030f2e56a0dfc4807 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 06:43:49 -0300 Subject: [PATCH 17/40] fix: wait for reconnecting channels on a typed invoice Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 5a7414df47..52e406975a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3793,8 +3793,11 @@ class AppViewModel @Inject constructor( } if (invoice.amountSatoshis > 0uL) { - // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount - if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + // Manual entry opens before the node runs or its channels reconnect, so wait for them unless Spark covers + // the amount + val lightning = lightningRepo.lightningState.value + val isReconnecting = lightning.channels.isNotEmpty() && lightning.channels.none { it.isUsable } + if (!lightning.nodeLifecycleState.isRunning() || isReconnecting) { waitForUsableChannels(amountSats = invoice.amountSatoshis) } lightningRepo.syncState() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 74c232e29a..140e89ec09 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -134,6 +134,7 @@ import to.bitkit.domain.commands.NotifyPaymentReceivedHandler import to.bitkit.env.Defaults import to.bitkit.env.Env import to.bitkit.ext.callbackAmountMsats +import to.bitkit.ext.createChannelDetails import to.bitkit.ext.fromHex import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.toHex @@ -5582,6 +5583,32 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isAddressInputValid) } + @Test + fun `manual invoice waits for a running node's channels to reconnect`() = test { + val bolt11 = "lnbcrt1manualreconnect" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val reconnecting = createChannelDetails().copy(channelId = "reconnecting", isUsable = false) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = persistentListOf(reconnecting), + ) + ) + ) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + inOrder(lightningRepo) { + verify(lightningRepo).waitForUsableChannels(awaitUsable = true) + verify(lightningRepo).canSend(50_000u) + } + } + @Test fun `scanned invoice Spark cannot cover waits for a pending node start before checking capacity`() = test { val bolt11 = "lnbcrt1scanwait" From 4ca8c9131b5f5d6c04c25c1d18adcd3a13a3fb79 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 06:43:49 -0300 Subject: [PATCH 18/40] fix: hold continue for any in-flight max fee quote Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 3 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 52e406975a..dc92ccf41e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -9340,7 +9340,8 @@ class AppViewModel @Inject constructor( val current = _sendUiState.value if (current.payMethod != SendMethod.LIGHTNING || current.decodedInvoice?.bolt11 != quote.bolt11) return maxRoutingFeeJob?.cancel() - val pendingInvoice = quote.bolt11.takeIf { onlySparkTakesInvoiceAmount(current) } + // Any rail's late reserve can lower the limit, so Continue waits for the quote before it leaves Amount + val pendingInvoice = quote.bolt11.takeIf { current.isAmountlessLightningInvoice } _sendUiState.update { it.copy(pendingSparkMaxInvoice = pendingInvoice) } maxRoutingFeeJob = viewModelScope.launch { val fee = if (quote.maxSendSats == 0uL) { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 140e89ec09..1de940a86a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5734,6 +5734,33 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `max quote holds Continue with the node running too`() = test { + val bolt11 = "lnbcrt1maxrunning" + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + balanceState.value = BalanceState(maxSendLightningSats = 40_000u) + whenever(lightningRepo.canSendWithSpark(any())).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + val quote = CompletableDeferred>() + whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).doSuspendableAnswer { quote.await() } + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u))) + + sut.setSendEvent(SendEvent.AmountMax(40_000u)) + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 40_000u)) + runCurrent() + + assertTrue(sut.sendUiState.value.awaitsSparkMaxFee) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + quote.complete(Result.success(120u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.awaitsSparkMaxFee) + } + @Test fun `a delayed Max quote cannot update another invoice or a reopened Send`() = test { val bolt11 = "lnbcrt1maxfirst" From e5826ce2b4d6885ec484a4248c1b3e6bb76a5bcc Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 06:43:49 -0300 Subject: [PATCH 19/40] refactor: share the recipient route list across both checks Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/ui/sheets/SendSheet.kt | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 570c5df809..2c62430211 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -171,14 +171,18 @@ internal fun waitsForNode( * Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. */ -internal fun isRecipientStep(route: SendRoute): Boolean = when (route) { - SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner, SendRoute.ComingSoon -> true - else -> false -} +/** The steps that pick a recipient, which never wait for the node. Coming Soon is Contact's Paykit-off fallback. */ +private val recipientRoutes = setOf( + SendRoute.Recipient::class, + SendRoute.Address::class, + SendRoute.ContactSelect::class, + SendRoute.QrScanner::class, + SendRoute.ComingSoon::class, +) + +internal fun isRecipientStep(route: SendRoute): Boolean = route::class in recipientRoutes -internal fun NavDestination.isRecipientStep(): Boolean = - hasRoute() || hasRoute() || - hasRoute() || hasRoute() || hasRoute() +internal fun NavDestination.isRecipientStep(): Boolean = recipientRoutes.any { hasRoute(it) } /** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */ internal fun NavDestination.isPastReview(): Boolean = From 3b46d03c2bf1b9493eac3b3e86ce9ce97f70dad9 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 07:51:33 -0300 Subject: [PATCH 20/40] fix: refresh channels before checking for a reconnect Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 3 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index dc92ccf41e..03b0d11c8d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3794,7 +3794,8 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { // Manual entry opens before the node runs or its channels reconnect, so wait for them unless Spark covers - // the amount + // the amount. The published channels go stale once a peer drops, so refresh them first. + lightningRepo.syncState() val lightning = lightningRepo.lightningState.value val isReconnecting = lightning.channels.isNotEmpty() && lightning.channels.none { it.isUsable } if (!lightning.nodeLifecycleState.isRunning() || isReconnecting) { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 1de940a86a..255bf9fc72 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5609,6 +5609,33 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `manual invoice refreshes channels a dropped peer left marked usable`() = test { + val bolt11 = "lnbcrt1manualstale" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val usable = createChannelDetails().copy(channelId = "dropped", isUsable = true) + val state = MutableStateFlow( + LightningState(nodeLifecycleState = NodeLifecycleState.Running, channels = persistentListOf(usable)) + ) + whenever(lightningRepo.lightningState).thenReturn(state) + doAnswer { + state.value = state.value.copy(channels = persistentListOf(usable.copy(isUsable = false))) + null + }.whenever(lightningRepo).syncState() + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + inOrder(lightningRepo) { + verify(lightningRepo).syncState() + verify(lightningRepo).waitForUsableChannels(awaitUsable = true) + verify(lightningRepo).canSend(50_000u) + } + } + @Test fun `scanned invoice Spark cannot cover waits for a pending node start before checking capacity`() = test { val bolt11 = "lnbcrt1scanwait" From a1570482c8f15bf68236d4f843a84efdd08c5f50 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 08:38:01 -0300 Subject: [PATCH 21/40] perf: refresh node state once for an invoice with usable channels Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 13 ++++++----- .../viewmodels/AppViewModelSendFlowTest.kt | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 03b0d11c8d..86302096ed 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3794,14 +3794,15 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { // Manual entry opens before the node runs or its channels reconnect, so wait for them unless Spark covers - // the amount. The published channels go stale once a peer drops, so refresh them first. - lightningRepo.syncState() - val lightning = lightningRepo.lightningState.value - val isReconnecting = lightning.channels.isNotEmpty() && lightning.channels.none { it.isUsable } - if (!lightning.nodeLifecycleState.isRunning() || isReconnecting) { + // the amount. The published channels go stale once a peer drops, so a running node refreshes them first. + val isRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() + if (isRunning) lightningRepo.syncState() + val channels = lightningRepo.lightningState.value.channels + val isReconnecting = channels.isNotEmpty() && channels.none { it.isUsable } + if (!isRunning || isReconnecting) { waitForUsableChannels(amountSats = invoice.amountSatoshis) + lightningRepo.syncState() } - lightningRepo.syncState() if (!lightningRepo.canSend(invoice.amountSatoshis)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = invoice.amountSatoshis.safe() - maxSendLightning.safe() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 255bf9fc72..fc5dc8e5cd 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5609,6 +5609,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `manual invoice with usable channels refreshes node state once`() = test { + val bolt11 = "lnbcrt1manualusable" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val usable = createChannelDetails().copy(channelId = "usable", isUsable = true) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState(nodeLifecycleState = NodeLifecycleState.Running, channels = persistentListOf(usable)) + ) + ) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + verify(lightningRepo, times(1)).syncState() + verify(lightningRepo, never()).waitForUsableChannels(any()) + verify(lightningRepo).canSend(50_000u) + } + @Test fun `manual invoice refreshes channels a dropped peer left marked usable`() = test { val bolt11 = "lnbcrt1manualstale" From 02dd9d161381c3e2cb5241bec81e58987893584c Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 08:39:04 -0300 Subject: [PATCH 22/40] fix: cap amount entry at spark until a channel is usable Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 8 +++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 +++-- .../ui/sheets/SendSheetSyncOverlayTest.kt | 10 +++--- .../viewmodels/AppViewModelSendFlowTest.kt | 33 +++++++++++++++++++ 4 files changed, 49 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 2c62430211..7f726f63af 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -137,9 +137,10 @@ internal fun sparkCanTakeAmount( ): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats == 0uL && !isLnurl && sparkState.isUsable && sparkState.sendableSats > 0uL -internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, isNodeRunning: Boolean): ULong = when { +/** Until a channel is usable only Spark pays, so Available stays at Spark's limit while channels reconnect. */ +internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, hasUsableChannels: Boolean): ULong = when { sparkMax == null -> cachedMax - isNodeRunning -> maxOf(cachedMax, sparkMax) + hasUsableChannels -> maxOf(cachedMax, sparkMax) else -> sparkMax } @@ -545,7 +546,8 @@ fun SendSheet( maxSendLightningSats = lightningAmountLimit( cachedMax = balances.maxSendLightningSats, sparkMax = sparkState.sendableSats.takeIf { sparkTakesAmount }, - isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + hasUsableChannels = lightningState.nodeLifecycleState.isRunning() && + lightningState.channels.any { it.isUsable }, ), ) }, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 86302096ed..a2de8fc346 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -9333,9 +9333,12 @@ class AppViewModel @Inject constructor( } } - private fun onlySparkTakesInvoiceAmount(state: SendUiState) = - state.isAmountlessLightningInvoice && !lightningRepo.lightningState.value.nodeLifecycleState.isRunning() && - lightningRepo.canSendWithSpark(1u) + /** Until a channel is usable only Spark can take the amount, even with the node running. */ + private fun onlySparkTakesInvoiceAmount(state: SendUiState): Boolean { + val lightning = lightningRepo.lightningState.value + val hasUsableChannels = lightning.nodeLifecycleState.isRunning() && lightning.channels.any { it.isUsable } + return state.isAmountlessLightningInvoice && !hasUsableChannels && lightningRepo.canSendWithSpark(1u) + } private fun estimateMaxAmountRoutingFee(quote: SendEvent.EstimateMaxRoutingFee) { val session = sendSession diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index d758f03dbc..4252b8b0dd 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -76,11 +76,11 @@ class SendSheetSyncOverlayTest { @Test fun `amount entry and its Max quote use the capacity of the available rails`() { - assertEquals(40_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = false)) - assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = false)) - assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = true)) - assertEquals(100_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = true)) - assertEquals(100_000uL, lightningAmountLimit(100_000u, null, isNodeRunning = true)) + assertEquals(40_000uL, lightningAmountLimit(100_000u, 40_000u, hasUsableChannels = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, hasUsableChannels = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, hasUsableChannels = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, 40_000u, hasUsableChannels = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, null, hasUsableChannels = true)) } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index fc5dc8e5cd..ebbe383e45 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5748,6 +5748,39 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isAmountInputValid) } + @Test + fun `amount over Spark's reserve is refused while a running node's channels reconnect`() = test { + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + val reconnecting = createChannelDetails().copy(channelId = "reconnecting", isUsable = false) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = persistentListOf(reconnecting), + ) + ) + ) + whenever(lightningRepo.canSendWithSpark(1u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(40_000u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(40_050u)).thenReturn(false) + whenever(lightningRepo.canSend(any())).thenReturn(true) + setSendState( + SendUiState( + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11 = "lnbcrt1amountless", amountSats = 0u), + estimatedRoutingFee = 100u, + ) + ) + + sut.setSendEvent(SendEvent.AmountChange(39_950u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isAmountInputValid) + + sut.setSendEvent(SendEvent.AmountChange(39_900u)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid) + } + @Test fun `max quote uses the displayed Spark limit and revalidates the entered amount`() = test { val bolt11 = "lnbcrt1maxspark" From abf849f2220d30f3cabe36ca4018373719d1af16 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 08:39:05 -0300 Subject: [PATCH 23/40] fix: keep the overlay off a send confirm submitted Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 7 ++++++- .../java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 7f726f63af..80324a67fc 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -190,6 +190,10 @@ internal fun NavDestination.isPastReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() || hasRoute() +/** A send Confirm submitted keeps its progress visible: Spark's balance can drop before the result route arrives. */ +internal fun isPastSubmission(isPastReview: Boolean, isSendSwipeRunning: Boolean): Boolean = + isPastReview || isSendSwipeRunning + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -238,6 +242,7 @@ fun SendSheet( val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val sendUiState by appViewModel.sendUiState.collectAsStateWithLifecycle() val isWaitingForNode by appViewModel.isSendWaitingForNode.collectAsStateWithLifecycle() + val isSendSwipeRunning by appViewModel.isSendSwipeRunning.collectAsStateWithLifecycle() val contacts by appViewModel.pubkyContacts.collectAsStateWithLifecycle() var routingCacheResetAttempted by rememberSaveable(startDestination) { mutableStateOf(false) } @@ -265,7 +270,7 @@ fun SendSheet( val isPastReview = entry?.destination?.isPastReview() == true val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false - if (sendUiState.hardwareWalletId != null || isPastReview) return@run false + if (sendUiState.hardwareWalletId != null || isPastSubmission(isPastReview, isSendSwipeRunning)) return@run false waitsForNode( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), hasAnyChannels = hasAnyChannels, diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 4252b8b0dd..e4d6e7fd81 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -83,6 +83,13 @@ class SendSheetSyncOverlayTest { assertEquals(100_000uL, lightningAmountLimit(100_000u, null, hasUsableChannels = true)) } + @Test + fun `a submitted send keeps the overlay off until its result route`() { + assertTrue(isPastSubmission(isPastReview = false, isSendSwipeRunning = true)) + assertTrue(isPastSubmission(isPastReview = true, isSendSwipeRunning = false)) + assertFalse(isPastSubmission(isPastReview = false, isSendSwipeRunning = false)) + } + @Test fun `spark takes the amount of an amountless invoice only`() { assertTrue(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded)) From c1eef6290520d2f60a938f01c3665e33230fd49f Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 09:48:09 -0300 Subject: [PATCH 24/40] docs: fix the spark payment and recipient step comments Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 80324a67fc..79b8ade6de 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -114,7 +114,7 @@ private const val HARDWARE_SEND_FALLBACK_SATS_PER_VBYTE = 3uL /** A peer reconnecting makes a channel usable again without any node event, so the overlay polls. */ private val CHANNELS_REFRESH_INTERVAL = 1.seconds -/** Whether Spark can pay the scanned Lightning invoice's own amount, so an amountless one still waits for the node. */ +/** Whether Spark can pay a Lightning invoice's amount: its own, or for an amountless one the amount entered. */ internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) @@ -168,10 +168,6 @@ internal fun waitsForNode( return hasAnyChannels && !hasUsableChannels } -/** - * Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the - * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. - */ /** The steps that pick a recipient, which never wait for the node. Coming Soon is Contact's Paykit-off fallback. */ private val recipientRoutes = setOf( SendRoute.Recipient::class, @@ -181,6 +177,10 @@ private val recipientRoutes = setOf( SendRoute.ComingSoon::class, ) +/** + * Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the + * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. + */ internal fun isRecipientStep(route: SendRoute): Boolean = route::class in recipientRoutes internal fun NavDestination.isRecipientStep(): Boolean = recipientRoutes.any { hasRoute(it) } From f77fd4768fbe4cc1b0ed9ee53ae6734f72ff6518 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 09:48:09 -0300 Subject: [PATCH 25/40] fix: keep confirm's progress up after spark debits a submitted send Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 14 +++++++++++--- .../bitkit/ui/sheets/SendSheetSyncOverlayTest.kt | 8 ++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 79b8ade6de..112d12b752 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -148,9 +148,16 @@ internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, hasUsableC internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean = data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState) -/** Whether a send can go ahead now: the node runs, a hardware wallet signs it, or Spark pays it without the node. */ -internal fun canSendWithoutWaiting(isNodeRunning: Boolean, isHardwareWallet: Boolean, sparkCanPay: Boolean): Boolean = - isNodeRunning || isHardwareWallet || sparkCanPay +/** + * Whether a send can go ahead now: the node runs, a hardware wallet signs it, or Spark pays it without the node. A send + * already submitted keeps its progress, since Spark's balance can drop below it before the result arrives. + */ +internal fun canSendWithoutWaiting( + isNodeRunning: Boolean, + isHardwareWallet: Boolean, + sparkCanPay: Boolean, + isSubmitted: Boolean = false, +): Boolean = isNodeRunning || isHardwareWallet || sparkCanPay || isSubmitted /** * A Lightning payment Spark can pay goes ahead without the node. Otherwise the node must run, and with channels a @@ -666,6 +673,7 @@ fun SendSheet( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), isHardwareWallet = uiState.hardwareWalletId != null, sparkCanPay = sparkCanPay, + isSubmitted = isSendSwipeRunning, ), canAutoStart = !isOffline && !shouldShowSyncOverlay, syncNodeVariant = syncNodeVariant, diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index e4d6e7fd81..8802e61502 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -25,6 +25,14 @@ class SendSheetSyncOverlayTest { fun `confirm and quick pay go ahead without the node when spark can pay`() { assertTrue(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = true)) assertFalse(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = false)) + assertTrue( + canSendWithoutWaiting( + isNodeRunning = false, + isHardwareWallet = false, + sparkCanPay = false, + isSubmitted = true, + ) + ) assertTrue(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded)) assertFalse(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded.copy(isReady = false))) } From a56b71479a5a826638f8ded7663d814c3559c727 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 09:48:23 -0300 Subject: [PATCH 26/40] fix: poll channels while they reconnect behind amount Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 20 +++++++++++++++++-- .../ui/sheets/SendSheetSyncOverlayTest.kt | 17 ++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 112d12b752..b5e0324be9 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -111,7 +111,7 @@ import kotlin.time.Duration.Companion.seconds private const val HARDWARE_SEND_FALLBACK_SATS_PER_VBYTE = 3uL -/** A peer reconnecting makes a channel usable again without any node event, so the overlay polls. */ +/** A peer reconnecting makes a channel usable again without any node event, so the sheet polls. */ private val CHANNELS_REFRESH_INTERVAL = 1.seconds /** Whether Spark can pay a Lightning invoice's amount: its own, or for an amountless one the amount entered. */ @@ -198,6 +198,17 @@ internal fun NavDestination.isPastReview(): Boolean = hasRoute() || hasRoute() /** A send Confirm submitted keeps its progress visible: Spark's balance can drop before the result route arrives. */ +/** + * Whether the sheet polls channels: while its overlay waits for a usable one, and while a running node's channels + * reconnect behind Amount, whose Spark cap lifts only once the list shows a usable channel. + */ +internal fun pollsChannels( + isNodeRunning: Boolean, + shouldShowSyncOverlay: Boolean, + hasAnyChannels: Boolean, + hasUsableChannels: Boolean, +): Boolean = isNodeRunning && (shouldShowSyncOverlay || hasAnyChannels && !hasUsableChannels) + internal fun isPastSubmission(isPastReview: Boolean, isSendSwipeRunning: Boolean): Boolean = isPastReview || isSendSwipeRunning @@ -287,7 +298,12 @@ fun SendSheet( } val lifecycle = LocalLifecycleOwner.current.lifecycle - val isWaitingForUsableChannel = shouldShowSyncOverlay && lightningState.nodeLifecycleState.isRunning() + val isWaitingForUsableChannel = pollsChannels( + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + shouldShowSyncOverlay = shouldShowSyncOverlay, + hasAnyChannels = hasAnyChannels, + hasUsableChannels = lightningState.channels.any { it.isUsable }, + ) LaunchedEffect(isWaitingForUsableChannel) { if (!isWaitingForUsableChannel) return@LaunchedEffect lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 8802e61502..de3d8205f3 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -91,6 +91,23 @@ class SendSheetSyncOverlayTest { assertEquals(100_000uL, lightningAmountLimit(100_000u, null, hasUsableChannels = true)) } + private fun polls(running: Boolean, overlay: Boolean, any: Boolean, usable: Boolean) = + pollsChannels( + isNodeRunning = running, + shouldShowSyncOverlay = overlay, + hasAnyChannels = any, + hasUsableChannels = usable, + ) + + @Test + fun `channels are polled while they reconnect even with the overlay off`() { + assertTrue(polls(running = true, overlay = false, any = true, usable = false)) + assertTrue(polls(running = true, overlay = true, any = true, usable = false)) + assertFalse(polls(running = true, overlay = false, any = true, usable = true)) + assertFalse(polls(running = true, overlay = false, any = false, usable = false)) + assertFalse(polls(running = false, overlay = true, any = true, usable = false)) + } + @Test fun `a submitted send keeps the overlay off until its result route`() { assertTrue(isPastSubmission(isPastReview = false, isSendSwipeRunning = true)) From a1a137be5f656d6357a9d6f13a9ac018de309857 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 09:49:09 -0300 Subject: [PATCH 27/40] fix: show a wait toast for a payment waiting outside send Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 23 ++++++++++++++++- app/src/main/res/values/strings.xml | 1 + .../viewmodels/AppViewModelSendFlowTest.kt | 25 +++++++++++++++++-- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a2de8fc346..9e8f987da9 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -435,12 +435,31 @@ class AppViewModel @Inject constructor( .map { it > 0 } .stateIn(viewModelScope, SharingStarted.Eagerly, false) - /** Runs [wait] counted in [isSendWaitingForNode], since the recipient steps have no overlay of their own. */ + /** + * Runs [wait] counted in [isSendWaitingForNode], since the recipient steps have no overlay of their own. Outside + * the Send sheet nothing reads the count, so a deeplink or home-scanner payment that waits past + * [NODE_WAIT_TOAST_DELAY] shows a toast instead. + */ private suspend fun showingNodeWait(wait: suspend () -> T): T { _isSendWaitingForNode.update { it + 1 } + var waitToast: Toast? = null + val toastJob = viewModelScope.launch { + delay(NODE_WAIT_TOAST_DELAY) + if (_currentSheet.value is Sheet.Send) return@launch + waitToast = Toast( + type = Toast.ToastType.INFO, + title = context.getString(R.string.lightning__sync_connecting_toast), + description = context.getString(R.string.lightning__wait_text_top), + autoHide = false, + testTag = NODE_WAIT_TOAST_TAG, + isLoading = true, + ).also { toastManager.enqueue(it) } + } return try { wait() } finally { + toastJob.cancel() + waitToast?.let { toastManager.dismiss(it) } _isSendWaitingForNode.update { it - 1 } } } @@ -11099,6 +11118,8 @@ class AppViewModel @Inject constructor( /** Test tag of the toast shown while a sign-in link waits for the Pubky session. */ internal const val PUBKY_AUTH_WAIT_TOAST_TAG = "PubkyAuthWaitToast" + internal const val NODE_WAIT_TOAST_TAG = "NodeWaitToast" + private val NODE_WAIT_TOAST_DELAY = 1.seconds private const val BITKIT_SCHEME = "bitkit" private const val RECOVERY_MODE_DEEPLINK = "recovery-mode" diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c930a202b0..e7f5b0001f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -534,6 +534,7 @@ Transfer\n<accent>speed</accent> Status Support + Connecting to network <accent>Connecting</accent>\nto network Total Anchor Channels Reserve Total Lightning diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ebbe383e45..df56beaca7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5675,6 +5675,27 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `a home-scanner invoice waiting for the node shows a wait toast until the wait ends`() = test { + val bolt11 = "lnbcrt1scantoast" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val nodeStarted = CompletableDeferred() + whenever(lightningRepo.awaitPendingNodeStart()).doSuspendableAnswer { nodeStarted.await() } + sut.setIsAuthenticated(true) + runCurrent() + clearInvocations(toastManager) + + sut.onScanResult(bolt11) + advanceTimeBy(2.seconds.inWholeMilliseconds) + verify(toastManager).enqueue(check { assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) }) + + nodeStarted.complete(Unit) + advanceUntilIdle() + verify(toastManager).dismiss(check { assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) }) + } + @Test fun `manual invoice Spark covers skips the queued node start`() = test { val bolt11 = "lnbcrt1manualspark" @@ -12582,7 +12603,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() val toastCaptor = argumentCaptor() - verify(toastManager).enqueue(toastCaptor.capture()) + verify(toastManager, atLeastOnce()).enqueue(toastCaptor.capture()) assertEquals("SelfPaymentToast", toastCaptor.lastValue.testTag) verify(quickPayRepo, never()).canApply(any()) assertNull(sut.quickPayData.value) @@ -12605,7 +12626,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() val toastCaptor = argumentCaptor() - verify(toastManager).enqueue(toastCaptor.capture()) + verify(toastManager, atLeastOnce()).enqueue(toastCaptor.capture()) assertEquals("SelfPaymentToast", toastCaptor.lastValue.testTag) verify(lightningRepo, never()).waitForUsableChannels() verify(lightningRepo, never()).canSend(any()) From 3ee4ade5ccfe9f06b38fd03483f8c7d28d69a10e Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 10:17:59 -0300 Subject: [PATCH 28/40] fix: stop polling channels once a send is submitted Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 13 ++++++++----- .../to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt | 4 +++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index b5e0324be9..de0b7b5d1a 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -198,19 +198,21 @@ internal fun NavDestination.isPastReview(): Boolean = hasRoute() || hasRoute() /** A send Confirm submitted keeps its progress visible: Spark's balance can drop before the result route arrives. */ +internal fun isPastSubmission(isPastReview: Boolean, isSendSwipeRunning: Boolean): Boolean = + isPastReview || isSendSwipeRunning + /** * Whether the sheet polls channels: while its overlay waits for a usable one, and while a running node's channels - * reconnect behind Amount, whose Spark cap lifts only once the list shows a usable channel. + * reconnect behind Amount, whose Spark cap lifts only once the list shows a usable channel. A submitted send has + * nothing left that reads them. */ internal fun pollsChannels( isNodeRunning: Boolean, + isPastSubmission: Boolean, shouldShowSyncOverlay: Boolean, hasAnyChannels: Boolean, hasUsableChannels: Boolean, -): Boolean = isNodeRunning && (shouldShowSyncOverlay || hasAnyChannels && !hasUsableChannels) - -internal fun isPastSubmission(isPastReview: Boolean, isSendSwipeRunning: Boolean): Boolean = - isPastReview || isSendSwipeRunning +): Boolean = isNodeRunning && !isPastSubmission && (shouldShowSyncOverlay || hasAnyChannels && !hasUsableChannels) internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || @@ -300,6 +302,7 @@ fun SendSheet( val lifecycle = LocalLifecycleOwner.current.lifecycle val isWaitingForUsableChannel = pollsChannels( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + isPastSubmission = isPastSubmission(isPastReview, isSendSwipeRunning), shouldShowSyncOverlay = shouldShowSyncOverlay, hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index de3d8205f3..5593793f55 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -91,9 +91,10 @@ class SendSheetSyncOverlayTest { assertEquals(100_000uL, lightningAmountLimit(100_000u, null, hasUsableChannels = true)) } - private fun polls(running: Boolean, overlay: Boolean, any: Boolean, usable: Boolean) = + private fun polls(running: Boolean, overlay: Boolean, any: Boolean, usable: Boolean, submitted: Boolean = false) = pollsChannels( isNodeRunning = running, + isPastSubmission = submitted, shouldShowSyncOverlay = overlay, hasAnyChannels = any, hasUsableChannels = usable, @@ -102,6 +103,7 @@ class SendSheetSyncOverlayTest { @Test fun `channels are polled while they reconnect even with the overlay off`() { assertTrue(polls(running = true, overlay = false, any = true, usable = false)) + assertFalse(polls(running = true, overlay = false, any = true, usable = false, submitted = true)) assertTrue(polls(running = true, overlay = true, any = true, usable = false)) assertFalse(polls(running = true, overlay = false, any = true, usable = true)) assertFalse(polls(running = true, overlay = false, any = false, usable = false)) From 04244cd91bee55cb714e8c8c4aca886e1740ae85 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 10:18:19 -0300 Subject: [PATCH 29/40] fix: dismiss the wait toast in the coroutine that shows it Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 20 ++++++++++++++----- app/src/main/res/values/strings.xml | 1 - .../viewmodels/AppViewModelSendFlowTest.kt | 9 ++++++++- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9e8f987da9..6d08cc8365 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -61,6 +61,7 @@ import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.asContextElement import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay @@ -442,24 +443,29 @@ class AppViewModel @Inject constructor( */ private suspend fun showingNodeWait(wait: suspend () -> T): T { _isSendWaitingForNode.update { it + 1 } - var waitToast: Toast? = null + // Shown and dismissed in one coroutine, so a wait ending as the toast appears cannot leave it behind val toastJob = viewModelScope.launch { delay(NODE_WAIT_TOAST_DELAY) if (_currentSheet.value is Sheet.Send) return@launch - waitToast = Toast( + val waitToast = Toast( type = Toast.ToastType.INFO, - title = context.getString(R.string.lightning__sync_connecting_toast), + title = context.getString(R.string.lightning__sync_connecting).withoutAccentMarkup(), description = context.getString(R.string.lightning__wait_text_top), autoHide = false, testTag = NODE_WAIT_TOAST_TAG, isLoading = true, - ).also { toastManager.enqueue(it) } + ) + toastManager.enqueue(waitToast) + try { + awaitCancellation() + } finally { + toastManager.dismiss(waitToast) + } } return try { wait() } finally { toastJob.cancel() - waitToast?.let { toastManager.dismiss(it) } _isSendWaitingForNode.update { it - 1 } } } @@ -11119,6 +11125,10 @@ class AppViewModel @Inject constructor( /** Test tag of the toast shown while a sign-in link waits for the Pubky session. */ internal const val PUBKY_AUTH_WAIT_TOAST_TAG = "PubkyAuthWaitToast" internal const val NODE_WAIT_TOAST_TAG = "NodeWaitToast" + private val ACCENT_MARKUP = Regex("") + + /** The overlay's translated "Connecting to network", as one plain line. */ + private fun String.withoutAccentMarkup(): String = replace(ACCENT_MARKUP, "").replace('\n', ' ') private val NODE_WAIT_TOAST_DELAY = 1.seconds private const val BITKIT_SCHEME = "bitkit" diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e7f5b0001f..c930a202b0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -534,7 +534,6 @@ Transfer\n<accent>speed</accent> Status Support - Connecting to network <accent>Connecting</accent>\nto network Total Anchor Channels Reserve Total Lightning diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index df56beaca7..935c8527b1 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5683,13 +5683,20 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) val nodeStarted = CompletableDeferred() whenever(lightningRepo.awaitPendingNodeStart()).doSuspendableAnswer { nodeStarted.await() } + whenever(context.getString(R.string.lightning__sync_connecting)) + .thenReturn("Connecting\nto network") sut.setIsAuthenticated(true) runCurrent() clearInvocations(toastManager) sut.onScanResult(bolt11) advanceTimeBy(2.seconds.inWholeMilliseconds) - verify(toastManager).enqueue(check { assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) }) + verify(toastManager).enqueue( + check { + assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) + assertEquals("Connecting to network", it.title) + } + ) nodeStarted.complete(Unit) advanceUntilIdle() From f3e88d539d490688a4f229ca83617055de04b5d7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 10:49:16 -0300 Subject: [PATCH 30/40] fix: finish the wait toast before the scan continues Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/viewmodels/AppViewModel.kt | 11 +++++------ .../to/bitkit/viewmodels/AppViewModelSendFlowTest.kt | 6 +++++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6d08cc8365..16b1bdec9f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -62,6 +62,7 @@ import kotlinx.coroutines.asContextElement import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay @@ -286,6 +287,7 @@ import to.bitkit.ui.sheets.hardware.HardwareRoute import to.bitkit.ui.theme.TRANSITION_SCREEN_MS import to.bitkit.ui.utils.ScreenDeepLinks import to.bitkit.ui.utils.localizedPubkyAuthMessage +import to.bitkit.ui.utils.removeAccentTags import to.bitkit.usecases.FormatMoneyValue import to.bitkit.usecases.KeepContactPaymentsOnUseCase import to.bitkit.usecases.RefreshContactPaykitLinkUseCase @@ -449,7 +451,7 @@ class AppViewModel @Inject constructor( if (_currentSheet.value is Sheet.Send) return@launch val waitToast = Toast( type = Toast.ToastType.INFO, - title = context.getString(R.string.lightning__sync_connecting).withoutAccentMarkup(), + title = context.getString(R.string.lightning__sync_connecting).removeAccentTags().replace('\n', ' '), description = context.getString(R.string.lightning__wait_text_top), autoHide = false, testTag = NODE_WAIT_TOAST_TAG, @@ -465,7 +467,8 @@ class AppViewModel @Inject constructor( return try { wait() } finally { - toastJob.cancel() + // Joined so the toast is gone before the caller can enqueue a result toast that would re-queue it + withContext(NonCancellable) { toastJob.cancelAndJoin() } _isSendWaitingForNode.update { it - 1 } } } @@ -11125,10 +11128,6 @@ class AppViewModel @Inject constructor( /** Test tag of the toast shown while a sign-in link waits for the Pubky session. */ internal const val PUBKY_AUTH_WAIT_TOAST_TAG = "PubkyAuthWaitToast" internal const val NODE_WAIT_TOAST_TAG = "NodeWaitToast" - private val ACCENT_MARKUP = Regex("") - - /** The overlay's translated "Connecting to network", as one plain line. */ - private fun String.withoutAccentMarkup(): String = replace(ACCENT_MARKUP, "").replace('\n', ' ') private val NODE_WAIT_TOAST_DELAY = 1.seconds private const val BITKIT_SCHEME = "bitkit" diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 935c8527b1..6282b5b3c7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5700,7 +5700,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { nodeStarted.complete(Unit) advanceUntilIdle() - verify(toastManager).dismiss(check { assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) }) + // Dismissed before the scan goes on to a result toast, which would otherwise re-queue it + inOrder(toastManager, lightningRepo) { + verify(toastManager).dismiss(check { assertEquals(AppViewModel.NODE_WAIT_TOAST_TAG, it.testTag) }) + verify(lightningRepo).canSend(50_000u) + } } @Test From 6c6e88c3668f411f34d76623881689eed1edbece Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 11:24:27 -0300 Subject: [PATCH 31/40] fix: drop the time estimate from the node wait toast Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 16b1bdec9f..fbbf8636e9 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -452,7 +452,7 @@ class AppViewModel @Inject constructor( val waitToast = Toast( type = Toast.ToastType.INFO, title = context.getString(R.string.lightning__sync_connecting).removeAccentTags().replace('\n', ' '), - description = context.getString(R.string.lightning__wait_text_top), + // No time estimate: this wait can include a node start of up to a minute autoHide = false, testTag = NODE_WAIT_TOAST_TAG, isLoading = true, From 546e800fcd8f2351799ed313023d1faefdcf294a Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 12:16:43 -0300 Subject: [PATCH 32/40] fix: drop the manual entry request when back leaves it Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 7 ++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 26 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index de0b7b5d1a..712ccf16ab 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -509,9 +509,14 @@ fun SendSheet( composableWithDefaultTransitions { val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle() DisposableEffect(Unit) { onDispose { appViewModel.cancelAddressValidation() } } + val back = { + appViewModel.onAddressBack() + navController.popBackStack() + } + BackHandler(onBack = { back() }) SendAddressScreen( uiState = uiState, - onBack = { navController.popBackStack() }, + onBack = { back() }, onEvent = { appViewModel.setSendEvent(it) }, ) } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index fbbf8636e9..074ff5af0f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3719,6 +3719,12 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToAddress) } + /** Back from manual entry drops the request its Continue was preparing, so it cannot open Amount later. */ + fun onAddressBack() { + cancelAddressValidation() + cancelSendVisitScan() + } + /** A typed address can wait for the node, so leaving it must stop that wait and its late result. */ fun cancelAddressValidation() { addressValidationJob?.cancel() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6282b5b3c7..7d06383dee 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12182,6 +12182,32 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return input } + @Test + fun `back from manual entry drops the request its continue was preparing`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(input)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(input)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.onAddressBack() + release.complete(Unit) + advanceUntilIdle() + + expectNoEvents() + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `onchain validation mismatch is silent after wallet replacement`() = test { val input = "bitcoin:$REGTEST_ADDRESS?amount=0.0001" From 488b7dea4f7c324be101a14e1bb52aa36bd1fe8e Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 12:16:43 -0300 Subject: [PATCH 33/40] fix: check fresh savings before refusing an address while node is down Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 39 ++++++++++++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 074ff5af0f..0a1cbc11ba 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3899,6 +3899,9 @@ class AppViewModel @Inject constructor( invoice.amountSatoshis, ) + // Savings cached while the node is down can predate a deposit: Continue checks it after the node starts + val isCachedSavings = hardwareWalletId == null && + !lightningRepo.lightningState.value.nodeLifecycleState.isRunning() if (maxSendOnchain == 0uL) { if (hardwareWalletId == null && hasOwnLightningInvoice(invoice.params)) { showAddressValidationError( @@ -3908,6 +3911,8 @@ class AppViewModel @Inject constructor( ) return } + } + if (maxSendOnchain == 0uL && !isCachedSavings) { showAddressValidationError( titleRes = R.string.other__pay_insufficient_savings, descriptionRes = R.string.other__pay_insufficient_savings_description, @@ -3916,7 +3921,7 @@ class AppViewModel @Inject constructor( return } - if (invoice.amountSatoshis > 0uL && invoice.amountSatoshis > maxSendOnchain) { + if (invoice.amountSatoshis > 0uL && invoice.amountSatoshis > maxSendOnchain && !isCachedSavings) { val shortfall = invoice.amountSatoshis - maxSendOnchain showAddressValidationError( titleRes = R.string.other__pay_insufficient_savings, @@ -6360,7 +6365,7 @@ class AppViewModel @Inject constructor( } else { walletRepo.balanceState.value.maxSendOnchainSats } - val maxSendOnchain = maxSendOnchainWithRetainedRetry( + var maxSendOnchain = maxSendOnchainWithRetainedRetry( maximumAvailableOnchainSats(selectedMaxSendOnchain, hardwareWalletId), hardwareWalletId, invoice.address, @@ -6489,6 +6494,15 @@ class AppViewModel @Inject constructor( return } + if (_sendUiState.value.payMethod == SendMethod.ONCHAIN) { + maxSendOnchain = liveMaxSendOnchain( + cachedMax = maxSendOnchain, + amountSats = invoice.amountSatoshis, + hardwareWalletId = hardwareWalletId, + walletGeneration = walletGeneration, + ) + } + // Check on-chain balance before proceeding to amount screen if (maxSendOnchain == 0uL && _sendUiState.value.payMethod == SendMethod.ONCHAIN) { if (hardwareWalletId == null && hasOwnLightningInvoice(invoice.params, walletGeneration)) { @@ -6631,6 +6645,27 @@ class AppViewModel @Inject constructor( private fun maximumHardwareFundingBalanceSats(): ULong = hwWalletRepo.wallets.value.maxOfOrNull { it.fundingBalanceSats } ?: 0uL + /** + * Savings cached from the last run can predate a deposit, so while the node is down a refusal waits for the node + * and its fresh balances instead of turning the recipient away. A hardware wallet reads its own balance. + */ + private suspend fun liveMaxSendOnchain( + cachedMax: ULong, + amountSats: ULong, + hardwareWalletId: String?, + walletGeneration: Long?, + ): ULong { + val refuses = cachedMax == 0uL || amountSats > cachedMax + val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() + if (!refuses || hardwareWalletId != null || isNodeRunning) return cachedMax + showingNodeWait { + lightningRepo.awaitPendingNodeStart() + walletRepo.syncNodeAndWallet() + } + requireCurrentPaymentPreparation(walletGeneration) + return maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) + } + private fun maximumAvailableOnchainSats(selectedMax: ULong, hardwareWalletId: String?): ULong = if (hardwareWalletId == null) maxOf(selectedMax, maximumHardwareFundingBalanceSats()) else selectedMax diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 7d06383dee..db659d163c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12182,6 +12182,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return input } + @Test + fun `an address refused by savings cached while the node is down waits for fresh balances`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + whenever(walletRepo.syncNodeAndWallet()).doSuspendableAnswer { + balanceState.value = BalanceState(maxSendOnchainSats = 50_000u) + Result.success(Unit) + } + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + clearInvocations(toastManager) + + sut.setSendEvent(SendEvent.AddressContinue(input)) + advanceUntilIdle() + + inOrder(lightningRepo, walletRepo) { + verify(lightningRepo).awaitPendingNodeStart() + verify(walletRepo).syncNodeAndWallet() + } + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + assertEquals(10_000uL, sut.sendUiState.value.amount) + } + @Test fun `back from manual entry drops the request its continue was preparing`() = test { val input = stubOnchainAmountScan(amountSats = 10_000u) From 78481b0fa0499c3c2cf3c225b96004edd44e89e7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 14:36:55 -0300 Subject: [PATCH 34/40] fix: treat savings as cached until the started node syncs Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 16 ++++++++----- .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 0a1cbc11ba..963db073c3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3899,9 +3899,8 @@ class AppViewModel @Inject constructor( invoice.amountSatoshis, ) - // Savings cached while the node is down can predate a deposit: Continue checks it after the node starts - val isCachedSavings = hardwareWalletId == null && - !lightningRepo.lightningState.value.nodeLifecycleState.isRunning() + // Savings cached until the node syncs can predate a deposit: Continue checks it after the sync + val isCachedSavings = hardwareWalletId == null && !hasSyncedSavings() if (maxSendOnchain == 0uL) { if (hardwareWalletId == null && hasOwnLightningInvoice(invoice.params)) { showAddressValidationError( @@ -6646,7 +6645,7 @@ class AppViewModel @Inject constructor( hwWalletRepo.wallets.value.maxOfOrNull { it.fundingBalanceSats } ?: 0uL /** - * Savings cached from the last run can predate a deposit, so while the node is down a refusal waits for the node + * Savings cached from the last run can predate a deposit, so until the node has synced a refusal waits for the node * and its fresh balances instead of turning the recipient away. A hardware wallet reads its own balance. */ private suspend fun liveMaxSendOnchain( @@ -6656,8 +6655,7 @@ class AppViewModel @Inject constructor( walletGeneration: Long?, ): ULong { val refuses = cachedMax == 0uL || amountSats > cachedMax - val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() - if (!refuses || hardwareWalletId != null || isNodeRunning) return cachedMax + if (!refuses || hardwareWalletId != null || hasSyncedSavings()) return cachedMax showingNodeWait { lightningRepo.awaitPendingNodeStart() walletRepo.syncNodeAndWallet() @@ -6666,6 +6664,12 @@ class AppViewModel @Inject constructor( return maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) } + /** A node that has not synced since it started still publishes the Savings balance cached from the last run. */ + private fun hasSyncedSavings(): Boolean { + val state = lightningRepo.lightningState.value + return state.nodeLifecycleState.isRunning() && state.lastSuccessfulSyncAt != null + } + private fun maximumAvailableOnchainSats(selectedMax: ULong, hardwareWalletId: String?): ULong = if (hardwareWalletId == null) maxOf(selectedMax, maximumHardwareFundingBalanceSats()) else selectedMax diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index db659d163c..6a18ca414e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12205,6 +12205,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(10_000uL, sut.sendUiState.value.amount) } + @Test + fun `an address refused by savings a just-started node has not synced waits for fresh balances`() = test { + val input = stubOnchainAmountScan(amountSats = 30_000u) + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)), + ) + whenever(walletRepo.syncNodeAndWallet()).doSuspendableAnswer { + balanceState.value = BalanceState(maxSendOnchainSats = 80_000u) + Result.success(Unit) + } + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + clearInvocations(toastManager) + + sut.setSendEvent(SendEvent.AddressContinue(input)) + advanceUntilIdle() + + verify(walletRepo).syncNodeAndWallet() + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + assertEquals(30_000uL, sut.sendUiState.value.amount) + } + @Test fun `back from manual entry drops the request its continue was preparing`() = test { val input = stubOnchainAmountScan(amountSats = 10_000u) From b156c2b2ed2f47f33b575d22881f2b47957aff30 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 14:36:55 -0300 Subject: [PATCH 35/40] fix: wait for fresh savings before replacing the send state Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 18 ++++++------ .../viewmodels/AppViewModelSendFlowTest.kt | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 963db073c3..7b8c9603b9 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6383,6 +6383,15 @@ class AppViewModel @Inject constructor( if (lnInvoice != null) MethodId.Bolt11 else PublicPaykitRepo.onchainMethodId(invoice.address), Clock.System.now() )?.amount?.atomic ?: lnInvoice?.amountSatoshis?.takeIf { it > 0uL } ?: invoice.amountSatoshis + // Before the send state changes, so a request left during this wait leaves the current review as it was + if (lnInvoice == null) { + maxSendOnchain = liveMaxSendOnchain( + cachedMax = maxSendOnchain, + amountSats = invoice.amountSatoshis, + hardwareWalletId = hardwareWalletId, + walletGeneration = walletGeneration, + ) + } _sendUiState.update { it.copy( address = invoice.address, @@ -6493,15 +6502,6 @@ class AppViewModel @Inject constructor( return } - if (_sendUiState.value.payMethod == SendMethod.ONCHAIN) { - maxSendOnchain = liveMaxSendOnchain( - cachedMax = maxSendOnchain, - amountSats = invoice.amountSatoshis, - hardwareWalletId = hardwareWalletId, - walletGeneration = walletGeneration, - ) - } - // Check on-chain balance before proceeding to amount screen if (maxSendOnchain == 0uL && _sendUiState.value.payMethod == SendMethod.ONCHAIN) { if (hardwareWalletId == null && hasOwnLightningInvoice(invoice.params, walletGeneration)) { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6a18ca414e..e061a730a6 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12228,6 +12228,34 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(30_000uL, sut.sendUiState.value.amount) } + @Test + fun `back during the savings wait never fills the review with the abandoned recipient`() = test { + val first = stubOnchainAmountScan(amountSats = 12_000u) + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.setSendEvent(SendEvent.AddressContinue(first)) + advanceUntilIdle() + assertEquals(12_000uL, sut.sendUiState.value.amount) + + val replacement = "bitcoin:$REGTEST_ADDRESS?amount=0.0012" + whenever(coreService.decode(replacement)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 120_000u, null, null, null)), + ) + val synced = CompletableDeferred() + whenever(walletRepo.syncNodeAndWallet()).doSuspendableAnswer { + synced.await() + balanceState.value = BalanceState(maxSendOnchainSats = 200_000u) + Result.success(Unit) + } + sut.setSendEvent(SendEvent.AddressContinue(replacement)) + advanceUntilIdle() + sut.onAddressBack() + synced.complete(Unit) + advanceUntilIdle() + + assertNotEquals(120_000uL, sut.sendUiState.value.amount) + } + @Test fun `back from manual entry drops the request its continue was preparing`() = test { val input = stubOnchainAmountScan(amountSats = 10_000u) From 5ef6500b5e2b9cd121202a3f8dd7e9499d66e1da Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 14:57:34 -0300 Subject: [PATCH 36/40] fix: re-read savings after the lightning wait of a unified request Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 7b8c9603b9..5592dbad04 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6654,8 +6654,11 @@ class AppViewModel @Inject constructor( hardwareWalletId: String?, walletGeneration: Long?, ): ULong { - val refuses = cachedMax == 0uL || amountSats > cachedMax - if (!refuses || hardwareWalletId != null || hasSyncedSavings()) return cachedMax + if (hardwareWalletId != null) return cachedMax + // Re-read: a Lightning check before this one can have waited for the node while Savings was published + val currentMax = maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) + val refuses = currentMax == 0uL || amountSats > currentMax + if (!refuses || hasSyncedSavings()) return currentMax showingNodeWait { lightningRepo.awaitPendingNodeStart() walletRepo.syncNodeAndWallet() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index e061a730a6..a199d45730 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12799,6 +12799,35 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.sendUiState.value.decodedInvoice) } + @Test + fun `unified fallback reads savings published during its lightning wait`() = test { + val bolt11 = "lnbcrt1foreignunifiedfreshsavings" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.009&lightning=$bolt11" + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 900_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + balanceState.value = BalanceState(maxSendOnchainSats = 799_821u) + whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.canSend(any())).thenReturn(false) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState(nodeLifecycleState = NodeLifecycleState.Running, lastSuccessfulSyncAt = 1L), + ), + ) + whenever(lightningRepo.waitForUsableChannels(any())).doSuspendableAnswer { + balanceState.value = BalanceState(maxSendOnchainSats = 1_099_753u) + Unit + } + sut.setIsAuthenticated(true) + runCurrent() + clearInvocations(toastManager) + + sut.onScanResult(uri) + advanceUntilIdle() + + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + assertEquals(900_000uL, sut.sendUiState.value.amount) + } + @Test fun `unified scan with foreign lightning invoice and no savings keeps insufficient savings toast`() = test { val bolt11 = "lnbcrt1foreignunifiednosavings" From 187e50726eb64b34aad5b6b2e875c2531ee4d352 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 14:57:35 -0300 Subject: [PATCH 37/40] fix: ignore max quotes from an amount screen already left Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt | 12 +++++++++++- .../to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 712ccf16ab..6ef2e33c28 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -192,6 +192,13 @@ internal fun isRecipientStep(route: SendRoute): Boolean = route::class in recipi internal fun NavDestination.isRecipientStep(): Boolean = recipientRoutes.any { hasRoute(it) } +/** + * A Max quote from an Amount screen already left (still composed while it animates out) must not reprice the amount + * Continue accepted, or it can disable Confirm without a word. + */ +internal fun forwardsAmountEvent(event: SendEvent, isAmountActive: Boolean): Boolean = + event !is SendEvent.EstimateMaxRoutingFee || isAmountActive + /** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */ internal fun NavDestination.isPastReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || @@ -592,7 +599,10 @@ fun SendSheet( appViewModel.hideSheet() } }, - onEvent = { appViewModel.setSendEvent(it) } + onEvent = { event -> + val isAmountActive = navController.currentDestination?.hasRoute() == true + if (forwardsAmountEvent(event, isAmountActive)) appViewModel.setSendEvent(event) + } ) } composableWithDefaultTransitions { diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 5593793f55..278bf4504c 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -3,6 +3,7 @@ package to.bitkit.ui.sheets import org.junit.Test import to.bitkit.repositories.SparkState import to.bitkit.viewmodels.QuickPayData +import to.bitkit.viewmodels.SendEvent import to.bitkit.viewmodels.SendMethod import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -12,6 +13,14 @@ import kotlin.test.assertTrue class SendSheetSyncOverlayTest { private val funded = SparkState(isSupported = true, isReady = true, balanceSats = 100_000uL) + @Test + fun `a max quote reaches the view model only while amount entry is active`() { + val quote = SendEvent.EstimateMaxRoutingFee("lnbcrt1quote", 100_000u) + assertTrue(forwardsAmountEvent(quote, isAmountActive = true)) + assertFalse(forwardsAmountEvent(quote, isAmountActive = false)) + assertTrue(forwardsAmountEvent(SendEvent.AmountContinue, isAmountActive = false)) + } + @Test fun `a scanned invoice a ready funded spark can pay skips the wait for a stopped node`() { val sparkCanPay = sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded) From 31b8a8a84faf52d6cfd87c69f37a7ce66717fc05 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 15:08:33 -0300 Subject: [PATCH 38/40] fix: derive savings on refusal when sync ended before publishing Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 13 ++++++---- .../viewmodels/AppViewModelSendFlowTest.kt | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 5592dbad04..2eefdf4a1a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6658,10 +6658,15 @@ class AppViewModel @Inject constructor( // Re-read: a Lightning check before this one can have waited for the node while Savings was published val currentMax = maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) val refuses = currentMax == 0uL || amountSats > currentMax - if (!refuses || hasSyncedSavings()) return currentMax - showingNodeWait { - lightningRepo.awaitPendingNodeStart() - walletRepo.syncNodeAndWallet() + if (!refuses) return currentMax + if (hasSyncedSavings()) { + // The node's sync can end before its balances are published: derive them from the node now + walletRepo.syncBalances() + } else { + showingNodeWait { + lightningRepo.awaitPendingNodeStart() + walletRepo.syncNodeAndWallet() + } } requireCurrentPaymentPreparation(walletGeneration) return maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index a199d45730..f951f81a61 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12828,6 +12828,30 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(900_000uL, sut.sendUiState.value.amount) } + @Test + fun `a refusal after the node synced derives savings the sync has not yet published`() = test { + val input = stubOnchainAmountScan(amountSats = 30_000u) + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState(nodeLifecycleState = NodeLifecycleState.Running, lastSuccessfulSyncAt = 1L), + ), + ) + whenever(walletRepo.syncBalances()).doSuspendableAnswer { + balanceState.value = BalanceState(maxSendOnchainSats = 79_890u) + Unit + } + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + clearInvocations(toastManager) + + sut.setSendEvent(SendEvent.AddressContinue(input)) + advanceUntilIdle() + + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + assertEquals(30_000uL, sut.sendUiState.value.amount) + } + @Test fun `unified scan with foreign lightning invoice and no savings keeps insufficient savings toast`() = test { val bolt11 = "lnbcrt1foreignunifiednosavings" From 2b5c54977d6ea0351cabc38a9517048966205893 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 16:48:41 -0300 Subject: [PATCH 39/40] fix: wait for a running sync before refusing on savings Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 2eefdf4a1a..e510d742ab 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6668,6 +6668,13 @@ class AppViewModel @Inject constructor( walletRepo.syncNodeAndWallet() } } + // A sync already running makes another return at once: its deposit is applied only when it ends + if (lightningRepo.lightningState.value.isSyncingWallet) { + showingNodeWait { + lightningRepo.lightningState.first { !it.isSyncingWallet } + walletRepo.syncBalances() + } + } requireCurrentPaymentPreparation(walletGeneration) return maximumAvailableOnchainSats(walletRepo.balanceState.value.maxSendOnchainSats, null) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index f951f81a61..ec0f326c97 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12228,6 +12228,37 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(30_000uL, sut.sendUiState.value.amount) } + @Test + fun `a savings refusal waits for a sync already running to apply the deposit`() = test { + val input = stubOnchainAmountScan(amountSats = 30_000u) + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + val lightning = MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + lastSuccessfulSyncAt = 1L, + isSyncingWallet = true, + ), + ) + whenever(lightningRepo.lightningState).thenReturn(lightning) + whenever(walletRepo.syncBalances()).doSuspendableAnswer { + if (!lightning.value.isSyncingWallet) balanceState.value = BalanceState(maxSendOnchainSats = 80_000u) + Unit + } + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + clearInvocations(toastManager) + + sut.setSendEvent(SendEvent.AddressContinue(input)) + advanceUntilIdle() + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + + lightning.value = lightning.value.copy(isSyncingWallet = false) + advanceUntilIdle() + + verify(toastManager, never()).enqueue(check { assertEquals("InsufficientSavingsToast", it.testTag) }) + assertEquals(30_000uL, sut.sendUiState.value.amount) + } + @Test fun `back during the savings wait never fills the review with the abandoned recipient`() = test { val first = stubOnchainAmountScan(amountSats = 12_000u) From 0022954b2d8ca5a3cc66188b23a873783b4e7505 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 4 Dec 2026 16:48:41 -0300 Subject: [PATCH 40/40] fix: refuse a below-minimum request before the savings wait Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e510d742ab..33a4afc22a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6383,8 +6383,10 @@ class AppViewModel @Inject constructor( if (lnInvoice != null) MethodId.Bolt11 else PublicPaykitRepo.onchainMethodId(invoice.address), Clock.System.now() )?.amount?.atomic ?: lnInvoice?.amountSatoshis?.takeIf { it > 0uL } ?: invoice.amountSatoshis - // Before the send state changes, so a request left during this wait leaves the current review as it was - if (lnInvoice == null) { + // Before the send state changes, so a request left during this wait leaves the current review as it was. + // A request below the on-chain minimum is refused on its amount alone, without that wait. + val isBelowRequestMinimum = incomingPaymentRequest != null && amount <= Defaults.dustLimit.toULong() + if (lnInvoice == null && !isBelowRequestMinimum) { maxSendOnchain = liveMaxSendOnchain( cachedMax = maxSendOnchain, amountSats = invoice.amountSatoshis, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ec0f326c97..90312ada5c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -14966,6 +14966,30 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) } + @Test + fun `a below minimum request is refused without waiting for savings`() = test { + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__title)).thenReturn("Amount Too Low") + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__description)) + .thenReturn("The minimum amount for this invoice is ₿ {amount}.") + whenever(formatMoneyValue(547uL)).thenReturn("547") + sut.setIsAuthenticated(true) + runCurrent() + val request = paymentRequest().copy(amount = PaykitAmount(PaykitAsset.BTC, 100uL)) + stubIncomingOnchainRequest(request) + + sut.openContactPayment( + paymentRequest = REGTEST_ADDRESS, + publicKey = testPublicKey, + incomingPaymentRequest = request, + ) + runCurrent() + + verify(toastManager).enqueue(check { assertEquals("PaymentRequestAmountTooLowToast", it.testTag) }) + assertNull(activeContactPaymentContext()) + verify(walletRepo, never()).syncNodeAndWallet() + } + @Test fun `below minimum request closes preparation and does not block another request`() = test { val request = paymentRequest().copy(amount = PaykitAmount(PaykitAsset.BTC, 100uL))