From 7e44462f13744f5fae40b602a3997f7a59ac6a88 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:07:38 +0100 Subject: [PATCH 01/23] feat: update spending balance modal Verified: just format, just compile, just test, just lint, androidTest compile --- app/lint.xml | 1 - .../receive/ReceiveAutoTabSelectionTest.kt | 2 - .../receive/ReceiveHardwareFlowTest.kt | 1 - .../wallets/receive/ReceiveNavigationTest.kt | 8 +- .../bitkit/models/ReceiveLiquidityDecision.kt | 42 --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 117 +++++- .../java/to/bitkit/repositories/WalletRepo.kt | 7 +- app/src/main/java/to/bitkit/ui/ContentView.kt | 38 +- .../java/to/bitkit/ui/components/SheetHost.kt | 1 + .../wallets/receive/EditInvoiceScreen.kt | 47 +-- .../screens/wallets/receive/EditInvoiceVM.kt | 66 ---- .../wallets/receive/ReceiveQrScreen.kt | 122 +------ .../screens/wallets/receive/ReceiveSheet.kt | 17 - .../receive/TransferUnavailableScreen.kt | 40 --- .../screens/wallets/send/SendConfirmScreen.kt | 27 +- .../lightning/CloseConnectionViewModel.kt | 18 +- .../lightning/LightningConnectionsScreen.kt | 3 +- .../settings/lightning/MoveToSparkManager.kt | 29 +- .../settings/lightning/MoveToSparkScreen.kt | 340 ------------------ .../lightning/MoveToSparkViewModel.kt | 28 +- .../to/bitkit/ui/sheets/MoveToSparkSheet.kt | 301 ++++++++++++++-- .../to/bitkit/usecases/CloseChannelUseCase.kt | 56 +++ .../usecases/DeriveBalanceStateUseCase.kt | 9 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 94 ++++- app/src/main/res/drawable/arrow.xml | 9 - app/src/main/res/values-ar/strings.xml | 14 - app/src/main/res/values-b+es+419/strings.xml | 14 - app/src/main/res/values-ca/strings.xml | 14 - app/src/main/res/values-cs/strings.xml | 14 - app/src/main/res/values-de/strings.xml | 14 - app/src/main/res/values-el/strings.xml | 14 - app/src/main/res/values-es-rES/strings.xml | 14 - app/src/main/res/values-es/strings.xml | 14 - app/src/main/res/values-fr/strings.xml | 14 - app/src/main/res/values-it/strings.xml | 14 - app/src/main/res/values-nl/strings.xml | 14 - app/src/main/res/values-pl/strings.xml | 14 - app/src/main/res/values-pt-rBR/strings.xml | 14 - app/src/main/res/values-pt/strings.xml | 14 - app/src/main/res/values-ru/strings.xml | 14 - app/src/main/res/values/strings.xml | 25 +- .../models/ReceiveLiquidityDecisionTest.kt | 40 --- .../repositories/MoveToSparkRepoTest.kt | 148 ++++++++ .../to/bitkit/repositories/WalletRepoTest.kt | 10 - .../wallets/receive/EditInvoiceVMTest.kt | 98 ----- .../wallets/receive/ReceiveQrScreenTest.kt | 50 +-- .../send/SendConfirmLnurlOnchainTest.kt | 4 +- .../lightning/MoveToSparkViewModelTest.kt | 64 +++- .../usecases/CloseChannelUseCaseTest.kt | 91 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 141 +++++++- docs/screens-map.md | 6 +- journeys/paykit-spark-route.xml | 2 +- journeys/receive/receive-tabs-wraparound.xml | 23 +- journeys/receive/usdt-receive-swipe-tabs.xml | 7 +- .../send/update-spending-balance-payment.xml | 23 ++ journeys/transfer/move-to-spark.xml | 29 +- .../transfer/transfer-unavailable-sheet.xml | 8 +- 57 files changed, 1126 insertions(+), 1276 deletions(-) delete mode 100644 app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt delete mode 100644 app/src/main/java/to/bitkit/ui/screens/wallets/receive/TransferUnavailableScreen.kt delete mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkScreen.kt create mode 100644 app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt delete mode 100644 app/src/main/res/drawable/arrow.xml delete mode 100644 app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt create mode 100644 app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt create mode 100644 journeys/send/update-spending-balance-payment.xml diff --git a/app/lint.xml b/app/lint.xml index 025cf2c6cd..7723018923 100644 --- a/app/lint.xml +++ b/app/lint.xml @@ -29,7 +29,6 @@ - diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveAutoTabSelectionTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveAutoTabSelectionTest.kt index 72a69ac745..0d3aad6957 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveAutoTabSelectionTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveAutoTabSelectionTest.kt @@ -32,7 +32,6 @@ class ReceiveAutoTabSelectionTest { fun keepsTabPickedByTapWhenAutoBecomesAvailable() { setContent() - composeTestRule.onNodeWithTag("Tab-spending").performClick() composeTestRule.onNodeWithTag("Tab-savings").performClick() composeTestRule.waitForIdle() @@ -58,7 +57,6 @@ class ReceiveAutoTabSelectionTest { walletState = WALLET_STATE, lightningState = lightningState, onClickEditInvoice = { editedTabs += it }, - onClickReceiveCjit = {}, ) } } diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveHardwareFlowTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveHardwareFlowTest.kt index 8fbcc945c9..342dad48c6 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveHardwareFlowTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveHardwareFlowTest.kt @@ -57,7 +57,6 @@ class ReceiveHardwareFlowTest { walletState = WALLET_STATE, lightningState = LightningState(), onClickEditInvoice = {}, - onClickReceiveCjit = {}, onClickHardwareEditInvoice = { editState.beginHardwareEdit() isEditing = true diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveNavigationTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveNavigationTest.kt index bf29025c58..676ad33865 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveNavigationTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/wallets/receive/ReceiveNavigationTest.kt @@ -35,10 +35,10 @@ class ReceiveNavigationTest { private var sheetDismissed = false @Test - fun deepLinkedTransferUnavailableReturnsToQr() { - setGraph(ReceiveRoute.TransferUnavailable) + fun deepLinkedEditInvoiceReturnsToQr() { + setGraph(ReceiveRoute.EditInvoice) - assertOn(ReceiveRoute.TransferUnavailable::class) + assertOn(ReceiveRoute.EditInvoice::class) pressBack() assertOn(ReceiveRoute.QR::class) assertFalse(sheetDismissed) @@ -97,7 +97,7 @@ class ReceiveNavigationTest { LaunchedEffect(startRoute) { controller.navigateToReceiveStart(startRoute) } NavHost(navController = controller, startDestination = startRoute.rootRoute()) { composable { Text("QR") } - composable { Text("Transfer Unavailable") } + composable { Text("Edit Invoice") } composable { Text("Details") } composable { Text("Recipient") } composable { Text("Sent") } diff --git a/app/src/main/java/to/bitkit/models/ReceiveLiquidityDecision.kt b/app/src/main/java/to/bitkit/models/ReceiveLiquidityDecision.kt index cf30c1d05b..ac5f8d1f3a 100644 --- a/app/src/main/java/to/bitkit/models/ReceiveLiquidityDecision.kt +++ b/app/src/main/java/to/bitkit/models/ReceiveLiquidityDecision.kt @@ -1,24 +1,5 @@ package to.bitkit.models -enum class ReceiveLiquiditySource { - SAVINGS, - AUTO, - SPENDING, -} - -sealed interface ReceiveAdditionalLiquidityAction { - data object None : ReceiveAdditionalLiquidityAction - - /** More inbound capacity needs a new channel, and Blocktank no longer sells them. */ - data object TransferUnavailable : ReceiveAdditionalLiquidityAction -} - -data class ReceiveAdditionalLiquidityParams( - val source: ReceiveLiquiditySource, - val invoiceAmountSats: ULong, - val inboundCapacitySats: ULong?, -) - object ReceiveLiquidityDecision { fun canCreateLightningInvoice( hasReadyChannels: Boolean, @@ -33,27 +14,4 @@ object ReceiveLiquidityDecision { return invoiceAmountSats <= inboundCapacitySats } - - fun additionalLiquidityAction(params: ReceiveAdditionalLiquidityParams): ReceiveAdditionalLiquidityAction { - return when { - params.source != ReceiveLiquiditySource.SPENDING -> ReceiveAdditionalLiquidityAction.None - !needsInboundLiquidity(params.invoiceAmountSats, params.inboundCapacitySats) -> - ReceiveAdditionalLiquidityAction.None - (params.inboundCapacitySats ?: 0uL) == 0uL -> ReceiveAdditionalLiquidityAction.None - else -> ReceiveAdditionalLiquidityAction.TransferUnavailable - } - } - - fun needsInboundLiquidity( - invoiceAmountSats: ULong, - inboundCapacitySats: ULong?, - ): Boolean { - val inbound = inboundCapacitySats ?: 0uL - - if (invoiceAmountSats == 0uL) { - return inbound == 0uL - } - - return invoiceAmountSats > inbound - } } diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 35566bcecf..963929901f 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -4,11 +4,14 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Bolt11Invoice @@ -19,8 +22,10 @@ import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.data.CacheStore import to.bitkit.di.BgDispatcher +import to.bitkit.ext.filterOpen import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.totalNextOutboundHtlcLimitSats +import to.bitkit.models.msatFloorOf import to.bitkit.models.safe import to.bitkit.utils.AppError import to.bitkit.utils.LdkError @@ -57,6 +62,12 @@ class MoveToSparkRepo internal constructor( /** How often a move waiting past its timeout reads the node's stored payment again, as the node may be down. */ private val STORED_PAYMENT_RECHECK = 30.seconds + /** How long a payment after an update waits for Spark to show the moved balance. */ + private val SPARK_BALANCE_WAIT = 1.minutes + + /** How often that wait reads Spark's balance again. */ + private val SPARK_BALANCE_RECHECK = 2.seconds + /** The failures that mean no route carried the amount, so a smaller one may route. */ private val NO_ROUTE_REASONS = setOf(PaymentFailureReason.ROUTE_NOT_FOUND, PaymentFailureReason.RETRIES_EXHAUSTED) @@ -71,6 +82,9 @@ class MoveToSparkRepo internal constructor( ) : this(bgDispatcher, lightningRepo, sparkRepo, cacheStore, { Bolt11Invoice.fromStr(it).paymentHash() }) private val watchedPaymentHashes = ConcurrentHashMap.newKeySet() + + /** One move at a time: the modal's and a payment's update would otherwise pay from the same channel balance. */ + private val moveLock = Mutex() private val reportedPaymentHashes = ConcurrentHashMap.newKeySet() /** @@ -98,6 +112,61 @@ class MoveToSparkRepo internal constructor( /** The most the channels can send now, before routing fees. */ fun movableSats(): ULong = MoveToSparkMath.movableSats(lightningRepo.lightningState.value.channels) + /** The most a Lightning payment can send once the channels' balance is updated to Spark first. */ + fun combinedSendableSats(): ULong = MoveToSparkMath.combinedSendableSats( + channels = lightningRepo.lightningState.value.channels.takeIf { canRunNode() }, + spark = sparkRepo.state.value, + ) + + /** Whether paying [amountSats] needs the channels' balance updated to Spark first, as neither rail covers it. */ + fun needsUpdateToSend(amountSats: ULong): Boolean = MoveToSparkMath.needsUpdateToSend( + amountSats = amountSats, + channels = lightningRepo.lightningState.value.channels.takeIf { canRunNode() }, + spark = sparkRepo.state.value, + ) + + private fun canRunNode(): Boolean = lightningRepo.lightningState.value.nodeLifecycleState.canRun() + + /** + * Updates the spending balance for a payment of [amountSats]: moves the channels' balance to Spark with + * [knownQuote], or a new quote, and waits until Spark can pay the amount. A move still in flight, or a balance + * Spark does not show in time, fails with [MoveToSparkError.UpdateUnsettled]; the funds then reach Spark on their + * own. [onMove] gets the move's outcome as soon as the move returns, before the wait. + */ + suspend fun updateToSend( + knownQuote: MoveToSparkQuote?, + amountSats: ULong, + onMove: (MoveToSparkOutcome) -> Unit = {}, + ): Result = + withContext(bgDispatcher) { + runSuspendCatching { + val usedQuote = knownQuote ?: quote().getOrThrow() + val outcome = move(usedQuote).getOrThrow().also(onMove) + val moved = outcome as? MoveToSparkOutcome.Moved ?: throw MoveToSparkError.UpdateUnsettled() + val shown = withTimeoutOrNull(SPARK_BALANCE_WAIT) { + while (!sparkRepo.canSend(amountSats)) { + sparkRepo.refreshState() + if (!sparkRepo.canSend(amountSats)) delay(SPARK_BALANCE_RECHECK) + } + } + if (shown == null) throw MoveToSparkError.UpdateUnsettled() + moved + }.onFailure { + Logger.warn("Failed to update the spending balance for '$amountSats' sats", it, context = TAG) + } + } + + /** + * The fee Spark charges for paying [bolt11] once the spending balance is updated; Spark's service fee alone when + * Spark cannot price it before the moved balance arrives. + */ + suspend fun estimateFeeAfterUpdate(bolt11: String, amountSats: ULong): ULong = withContext(bgDispatcher) { + sparkRepo.estimateFeeSats(bolt11, amountSats).getOrElse { + Logger.debug("Fell back to Spark's service fee for an update payment", context = TAG) + SparkFees.serviceFeeSats(amountSats) + } + } + /** * Quotes moving [targetSats], or everything the channels can send, to a new Spark invoice. * The amount leaves room for the routing fee, which the quote carries and the move caps the payment at. @@ -138,13 +207,15 @@ class MoveToSparkRepo internal constructor( /** Pays [quote] over the channels and waits for it to settle in Spark. */ suspend fun move(quote: MoveToSparkQuote): Result = withContext(bgDispatcher) { runSuspendCatching { - val paymentHash = paymentHashOf(quote.invoice) - cacheStore.addMoveToSparkHash(paymentHash) - watchedPaymentHashes += paymentHash - try { - payAndWait(quote, paymentHash) - } finally { - watchedPaymentHashes -= paymentHash + moveLock.withLock { + val paymentHash = paymentHashOf(quote.invoice) + cacheStore.addMoveToSparkHash(paymentHash) + watchedPaymentHashes += paymentHash + try { + payAndWait(quote, paymentHash) + } finally { + watchedPaymentHashes -= paymentHash + } } }.onFailure { Logger.error("Failed to move '${quote.amountSats}' sats to Spark", it, context = TAG) @@ -288,8 +359,37 @@ object MoveToSparkMath { /** The routing fee cap for the payment: exactly the quoted fee, so it never pays more than shown. */ fun feeCapMsat(feeSats: ULong): ULong = feeSats.safe() * 1000uL.safe() + /** The most a Lightning payment can send: over the channels, from Spark, or from Spark after an update. */ + fun maxSendSats(channels: List?, spark: SparkState): ULong = + maxOf(movableSats(channels), spark.sendableSats, combinedSendableSats(channels, spark)) + /** The smaller amount to offer after one did not route: half of it, or nothing below the minimum. */ fun smallerAmount(sats: ULong): ULong? = (sats / 2uL).takeIf { it >= MIN_MOVE_SATS } + + /** + * The most Spark can send once the channels' balance less a guessed routing fee has moved to it; 0 when nothing + * can move. + */ + fun combinedSendableSats(channels: List?, spark: SparkState): ULong { + if (!canMove(channels, spark)) return 0uL + val limitSats = movableSats(channels) + return SparkFees.sendableSats(spark.balanceSats.safe() + firstCandidate(limitSats, limitSats).safe()) + } + + /** Whether [amountSats] fits neither the channels nor Spark alone, but fits Spark once the channels moved to it. */ + fun needsUpdateToSend(amountSats: ULong, channels: List?, spark: SparkState): Boolean { + val singleRailSats = maxOf(movableSats(channels), spark.sendableSats.takeIf { spark.isReady } ?: 0uL) + return amountSats > singleRailSats && amountSats <= combinedSendableSats(channels, spark) + } + + /** The open channels in [after] that could send at least [MIN_MOVE_SATS] in [before] and no longer can. */ + fun emptiedChannels(before: List, after: List?): List { + val beforeSats = before.associate { it.channelId to msatFloorOf(it.nextOutboundHtlcLimitMsat) } + return after.orEmpty().filterOpen().filter { + val wasSats = beforeSats[it.channelId] ?: return@filter false + wasSats >= MIN_MOVE_SATS && msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS + } + } } data class MoveToSparkQuote( @@ -322,6 +422,9 @@ sealed class MoveToSparkError(message: String, cause: Throwable? = null) : AppEr val reason: PaymentFailureReason? = null, ) : MoveToSparkError("Could not route '$amountSats' sats to Spark, reason '$reason'", cause) + /** The update moved the balance, but Spark cannot pay with it yet: the move or Spark's balance has not settled. */ + class UpdateUnsettled : MoveToSparkError("The update to Spark has not settled yet") + /** The payment failed for a reason other than its route, such as an expired invoice. */ class PaymentFailed(val reason: PaymentFailureReason?) : MoveToSparkError("Failed to pay Spark, reason '$reason'") } diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index 8f7b7084e9..6086afa541 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -41,7 +41,6 @@ import to.bitkit.ext.calculateRemoteBalance import to.bitkit.ext.nowTimestamp import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.toHex -import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.ALL_ADDRESS_TYPE_STRINGS import to.bitkit.models.AddressModel import to.bitkit.models.BalanceState @@ -449,7 +448,7 @@ class WalletRepo @Inject constructor( fun refreshMaxSendLightning() { val state = lightningRepo.lightningState.value if (!state.nodeLifecycleState.isRunning()) return - val maxSendSats = maxOf(state.channels.totalNextOutboundHtlcLimitSats(), sparkRepo.state.value.sendableSats) + val maxSendSats = MoveToSparkMath.maxSendSats(state.channels, sparkRepo.state.value) _balanceState.update { it.copy(maxSendLightningSats = maxSendSats) } } @@ -1030,10 +1029,6 @@ class WalletRepo @Inject constructor( /** Spark receives any amount without inbound liquidity, so no channel or CJIT is needed. */ fun canReceiveWithSpark(): Boolean = sparkRepo.canReceive() - suspend fun inboundLiquiditySats(): ULong = withContext(bgDispatcher) { - return@withContext currentReadyChannels().calculateRemoteBalance() - } - private fun canCreateLightningInvoice(amountSats: ULong?): Boolean { if (sparkRepo.canReceive()) return true val readyChannels = currentReadyChannels() diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index fcb11ea2e9..af83e13a5e 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -207,7 +207,6 @@ import to.bitkit.ui.settings.lightning.ChannelDetailScreen import to.bitkit.ui.settings.lightning.CloseConnectionScreen import to.bitkit.ui.settings.lightning.LightningConnectionsScreen import to.bitkit.ui.settings.lightning.LightningConnectionsViewModel -import to.bitkit.ui.settings.lightning.MoveToSparkScreen import to.bitkit.ui.settings.lightning.SparkDetailScreen import to.bitkit.ui.settings.lightning.SparkExitConfirmScreen import to.bitkit.ui.settings.lightning.SparkExitFeeBumpScreen @@ -670,10 +669,6 @@ fun ContentView( hardwareWalletId = sheet.hardwareWalletId, walletState = walletState, isOffline = connectivityState != ConnectivityState.CONNECTED, - navigateToExternalConnection = { - navController.navigateTo(ExternalConnection()) - appViewModel.hideSheet() - }, ) } } @@ -722,6 +717,10 @@ fun ContentView( } is Sheet.LnurlAuth -> LnurlAuthSheet(sheet, appViewModel) Sheet.ForceTransfer -> ForceTransferSheet(appViewModel, transferViewModel) + Sheet.MoveToSpark -> MoveToSparkSheet( + viewModel = hiltViewModel(), + onDismiss = { appViewModel.hideSheet() }, + ) Sheet.ConnectionClosed -> ConnectionClosedSheet( onDismiss = { appViewModel.hideSheet() }, ) @@ -793,11 +792,8 @@ fun ContentView( } TimedSheetType.MOVE_TO_SPARK -> MoveToSparkSheet( - onLater = { appViewModel.dismissTimedSheet() }, - onMove = { - appViewModel.dismissTimedSheet() - navController.navigateTo(Routes.MoveToSpark) - }, + viewModel = hiltViewModel(), + onDismiss = { appViewModel.dismissTimedSheet() }, ) TimedSheetType.HIGH_BALANCE -> { @@ -1055,7 +1051,7 @@ private fun RootNavHost( cjitDetailSettings(navController) swapsSettings(navController) swapDetailSettings(navController) - lightningConnections(navController) + lightningConnections(navController, onMoveToSpark = { appViewModel.showSheet(Sheet.MoveToSpark) }) activityItem(activityListViewModel, navController, settingsViewModel) authCheck(navController) logs(navController) @@ -1421,7 +1417,7 @@ private fun NavGraphBuilder.home( channels = lightningState.channels, hasSparkBalance = sparkState.shownSpendingSats > 0uL, canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), - onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, + onMoveToSparkClick = { appViewModel.showSheet(Sheet.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { @@ -2051,6 +2047,7 @@ private fun NavGraphBuilder.swapDetailSettings( private fun NavGraphBuilder.lightningConnections( navController: NavHostController, + onMoveToSpark: () -> Unit, ) { navigationWithDefaultTransitions( startDestination = Routes.LightningConnections, @@ -2058,7 +2055,7 @@ private fun NavGraphBuilder.lightningConnections( deepLinkableComposable { val parentEntry = remember(it) { navController.getBackStackEntry(Routes.ConnectionsNav) } val viewModel = hiltViewModel(parentEntry) - LightningConnectionsScreen(navController, viewModel) + LightningConnectionsScreen(navController, viewModel, onMoveToSpark) } deepLinkableComposable { val route = it.toRoute() @@ -2085,18 +2082,6 @@ private fun NavGraphBuilder.lightningConnections( ) } sparkExit(navController) - composableWithDefaultTransitions { - MoveToSparkScreen( - viewModel = hiltViewModel(), - onBack = { navController.popBackStack() }, - onCloseChannel = { channelId -> - // Closing returns to Lightning Connections, so the close screen opens on top of it. - navController.popBackStack() - navController.navigateTo(Routes.LightningConnections) - channelId?.let { navController.navigateTo(Routes.CloseConnection(it)) } - }, - ) - } deepLinkableComposable { val route = it.toRoute() CloseConnectionScreen( @@ -2658,9 +2643,6 @@ sealed interface Routes { @Serializable data object SparkExitFeeBump : Routes.InternalOnly - @Serializable - data object MoveToSpark : Routes.InternalOnly - @Serializable data object DevSettings : Routes.DeepLinkable diff --git a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt index 12d42a7539..f764e63e0a 100644 --- a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt +++ b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt @@ -96,6 +96,7 @@ sealed interface Sheet { data object ActivityTagSelector : Sheet data class LnurlAuth(val domain: String, val lnurl: String, val k1: String) : Sheet data object ForceTransfer : Sheet + data object MoveToSpark : Sheet data object ConnectionClosed : Sheet data object TransferUnavailable : Sheet data class BTCPayConnection( diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceScreen.kt index 2ba848186d..d39a62a6df 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceScreen.kt @@ -21,11 +21,9 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.TextField import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -35,16 +33,10 @@ import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import to.bitkit.R -import to.bitkit.models.ReceiveAdditionalLiquidityAction -import to.bitkit.models.ReceiveLiquiditySource -import to.bitkit.models.ReceiveLiquiditySource.AUTO -import to.bitkit.models.ReceiveLiquiditySource.SAVINGS -import to.bitkit.models.ReceiveLiquiditySource.SPENDING import to.bitkit.repositories.CurrencyState import to.bitkit.repositories.WalletState import to.bitkit.ui.LocalCurrencies @@ -75,7 +67,6 @@ import to.bitkit.viewmodels.previewAmountInputViewModel fun EditInvoiceScreen( amountInputViewModel: AmountInputViewModel, walletUiState: WalletState, - sourceTab: ReceiveTab, updateInvoice: (ULong?) -> Unit, onClickAddTag: () -> Unit, onClickTag: (String) -> Unit, @@ -85,32 +76,10 @@ fun EditInvoiceScreen( onBack: () -> Unit, onchainOnly: Boolean = false, updateOnchainInvoice: (ULong?) -> Unit = {}, - navigateTransferUnavailable: () -> Unit, currencies: CurrencyState = LocalCurrencies.current, - editInvoiceVM: EditInvoiceVM = hiltViewModel(), ) { var keyboardVisible by remember { mutableStateOf(false) } val amountInputUiState by amountInputViewModel.uiState.collectAsStateWithLifecycle() - val currentReceiveSats by rememberUpdatedState(amountInputUiState.sats.toULong()) - val isLoading by editInvoiceVM.isLoading.collectAsStateWithLifecycle() - - LaunchedEffect(onchainOnly) { - if (onchainOnly) return@LaunchedEffect - editInvoiceVM.editInvoiceEffect.collect { effect -> - val receiveSats = currentReceiveSats - when (effect) { - is EditInvoiceVM.EditInvoiceScreenEffects.ApplyReceiveLiquidityAction -> { - when (val action = effect.action) { - ReceiveAdditionalLiquidityAction.None -> { - updateInvoice(receiveSats) - onBack() - } - ReceiveAdditionalLiquidityAction.TransferUnavailable -> navigateTransferUnavailable() - } - } - } - } - } EditInvoiceContent( amountInputViewModel = amountInputViewModel, @@ -129,16 +98,13 @@ fun EditInvoiceScreen( }, onContinueKeyboard = { keyboardVisible = false }, onContinueGeneral = { - editInvoiceVM.onClickContinue( - source = sourceTab.toReceiveLiquiditySource(), - amountSats = amountInputUiState.sats.toULong(), - ) + updateInvoice(amountInputUiState.sats.toULong()) + onBack() }, onContinueOnchain = { amountSats -> updateOnchainInvoice(amountSats) onBack() }, - isLoading = isLoading, onClickAddTag = onClickAddTag, onClickTag = onClickTag, showPaymentRequestButton = showPaymentRequestButton, @@ -149,15 +115,6 @@ fun EditInvoiceScreen( ) } -private fun ReceiveTab.toReceiveLiquiditySource(): ReceiveLiquiditySource { - return when (this) { - ReceiveTab.SAVINGS -> SAVINGS - ReceiveTab.AUTO -> AUTO - ReceiveTab.SPENDING -> SPENDING - ReceiveTab.HARDWARE, ReceiveTab.USDT -> SAVINGS - } -} - @Suppress("ViewModelForwarding") @Composable fun EditInvoiceContent( diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt deleted file mode 100644 index 2131aec56b..0000000000 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt +++ /dev/null @@ -1,66 +0,0 @@ -package to.bitkit.ui.screens.wallets.receive - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asSharedFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import to.bitkit.models.ReceiveAdditionalLiquidityAction -import to.bitkit.models.ReceiveAdditionalLiquidityParams -import to.bitkit.models.ReceiveLiquidityDecision -import to.bitkit.models.ReceiveLiquiditySource -import to.bitkit.repositories.WalletRepo -import javax.inject.Inject - -@HiltViewModel -class EditInvoiceVM @Inject constructor( - private val walletRepo: WalletRepo, -) : ViewModel() { - - private val _editInvoiceEffect = MutableSharedFlow(extraBufferCapacity = 1) - val editInvoiceEffect = _editInvoiceEffect.asSharedFlow() - - private val _isLoading = MutableStateFlow(false) - val isLoading = _isLoading.asStateFlow() - - private fun editInvoiceEffect(effect: EditInvoiceScreenEffects) = viewModelScope.launch { - _editInvoiceEffect.emit( - effect - ) - } - - fun onClickContinue( - source: ReceiveLiquiditySource, - amountSats: ULong, - ) { - viewModelScope.launch { - if (walletRepo.canReceiveWithSpark()) { - editInvoiceEffect( - EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None) - ) - return@launch - } - _isLoading.update { true } - val inboundCapacitySats = walletRepo.inboundLiquiditySats() - val action = ReceiveLiquidityDecision.additionalLiquidityAction( - ReceiveAdditionalLiquidityParams( - source = source, - invoiceAmountSats = amountSats, - inboundCapacitySats = inboundCapacitySats, - ) - ) - editInvoiceEffect(EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(action)) - _isLoading.update { false } - } - } - - sealed interface EditInvoiceScreenEffects { - data class ApplyReceiveLiquidityAction( - val action: ReceiveAdditionalLiquidityAction, - ) : EditInvoiceScreenEffects - } -} diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt index 8b894f7d9a..1a408dbfce 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt @@ -13,9 +13,7 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow @@ -40,7 +38,6 @@ import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.hapticfeedback.HapticFeedbackType @@ -77,8 +74,6 @@ import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.BottomSheetPreview import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up -import to.bitkit.ui.components.Display -import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.QrCodeImage @@ -98,31 +93,10 @@ import to.bitkit.ui.shared.util.shareText import to.bitkit.ui.theme.AppShapes import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors -import to.bitkit.ui.utils.screenHeight -import to.bitkit.ui.utils.screenWidth -import to.bitkit.ui.utils.withAccent -/** The Spending onboarding card's height against the screen's, as Figma draws it 343 pt tall on an 812 pt screen. */ -private const val CJIT_CARD_SCREEN_SHARE = 343f / 812f - -/** The gap from the onboarding card's bottom to the button's top, as Figma's 122 pt on an 812 pt screen. */ -private const val CJIT_CARD_BOTTOM_GAP_SHARE = 122f / 812f - -/** The spacing the screen already keeps above its bottom button. */ +/** The spacing the screen keeps above its bottom button. */ private val BUTTON_TOP_SPACING = 24.dp -/** The arrow under the onboarding card, as iOS draws it: 210 pt tall on an 874 pt screen. */ -private const val CJIT_ARROW_HEIGHT_SHARE = 210f / 874f - -/** The arrow's offset from the card's bottom left, as iOS's 70 pt on a 402 pt wide screen. */ -private const val CJIT_ARROW_X_SHARE = 70f / 402f - -/** The arrow's drop below the card's bottom, as iOS's 110 pt on an 874 pt screen. */ -private const val CJIT_ARROW_Y_SHARE = 110f / 874f - -/** Screens shorter than this leave out the arrow, as iOS does on its small screens. */ -private val CJIT_ARROW_MIN_SCREEN_HEIGHT = 800.dp - @OptIn(FlowPreview::class) @Composable @Suppress("CyclomaticComplexMethod") @@ -130,7 +104,6 @@ fun ReceiveQrScreen( walletState: WalletState, lightningState: LightningState, onClickEditInvoice: (ReceiveTab) -> Unit, - onClickReceiveCjit: () -> Unit, modifier: Modifier = Modifier, onClickHardwareEditInvoice: () -> Unit = { onClickEditInvoice(ReceiveTab.HARDWARE) }, initialTab: ReceiveTab? = null, @@ -179,10 +152,11 @@ fun ReceiveQrScreen( add(ReceiveTab.HARDWARE) } add(ReceiveTab.SAVINGS) + // Without a usable Spark wallet or channel there is no Lightning invoice, so Auto and Spending hide. if (canCreateLightningInvoice) { add(ReceiveTab.AUTO) + add(ReceiveTab.SPENDING) } - add(ReceiveTab.SPENDING) if (usdtEnabled) add(ReceiveTab.USDT) }.toImmutableList() } @@ -321,9 +295,6 @@ fun ReceiveQrScreen( } } - // Shown while the node starts too, with its button disabled until the node runs. - val showingCjitOnboarding = !canCreateLightningInvoice - fun selectReceiveTab(tab: ReceiveTab) { val wrapsToFirst = selectedTab == visibleTabs.last() && tab == visibleTabs.first() selectedTab = tab @@ -447,22 +418,6 @@ fun ReceiveQrScreen( .fillParentMaxHeight() ) { when { - showingCjitOnboarding && tab == ReceiveTab.SPENDING -> { - Box( - contentAlignment = Alignment.BottomCenter, - modifier = Modifier - .fillMaxWidth() - .weight(1f) - ) { - CjitOnBoardingView( - modifier = Modifier - .fillMaxWidth() - .height(screenHeight() * CJIT_CARD_SCREEN_SHARE) - ) - } - VerticalSpacer(screenHeight() * CJIT_CARD_BOTTOM_GAP_SHARE - BUTTON_TOP_SPACING) - } - tab == ReceiveTab.HARDWARE && hardwareReceiveState.address == null -> { HardwareAddressLoadingView( isLoading = hardwareReceiveState.isLoadingAddress, @@ -529,9 +484,7 @@ fun ReceiveQrScreen( VerticalSpacer(BUTTON_TOP_SPACING) - val showCjitButton = showingCjitOnboarding && selectedTab == ReceiveTab.SPENDING val buttonVariant = when { - showCjitButton -> BottomButtonVariant.CJIT showDetails -> BottomButtonVariant.SHOW_QR else -> BottomButtonVariant.SHOW_DETAILS } @@ -540,26 +493,6 @@ fun ReceiveQrScreen( label = "ReceiveBottomButtonCrossfade", ) { variant -> when (variant) { - BottomButtonVariant.CJIT -> PrimaryButton( - text = stringResource(R.string.wallet__receive__cjit), - icon = { - Icon( - painter = painterResource(R.drawable.ic_lightning_alt), - tint = Colors.Purple, - contentDescription = null, - ) - }, - onClick = { - onClickReceiveCjit() - showDetails = false - }, - enabled = lightningState.nodeLifecycleState.isRunning(), - fullWidth = true, - modifier = Modifier - .padding(horizontal = 16.dp) - .testTag("ShowDetails") - ) - BottomButtonVariant.SHOW_QR -> Column( verticalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.padding(horizontal = 16.dp) @@ -737,48 +670,6 @@ fun ReceiveQrView( } } -@Composable -fun CjitOnBoardingView(modifier: Modifier = Modifier) { - val screenHeight = screenHeight() - Box(modifier = modifier) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - modifier = Modifier - .fillMaxSize() - .testTag("ReceiveSpendingCard") - .clip(AppShapes.small) - .background(color = Colors.Black) - .padding(32.dp) - ) { - Display(stringResource(R.string.wallet__receive_onboarding_title).withAccent(accentColor = Colors.Purple)) - VerticalSpacer(8.dp) - BodyM( - stringResource(R.string.wallet__receive_onboarding_description), - color = Colors.White64, - modifier = Modifier.fillMaxWidth() - ) - FillHeight() - Icon( - painter = painterResource(R.drawable.ic_lightning_alt), - tint = Colors.Purple, - contentDescription = null, - modifier = Modifier.size(64.dp) - ) - } - if (screenHeight >= CJIT_ARROW_MIN_SCREEN_HEIGHT) { - Icon( - painter = painterResource(R.drawable.arrow), - tint = Colors.Purple, - contentDescription = null, - modifier = Modifier - .align(Alignment.BottomStart) - .offset(x = screenWidth() * CJIT_ARROW_X_SHARE, y = screenHeight * CJIT_ARROW_Y_SHARE) - .height(screenHeight * CJIT_ARROW_HEIGHT_SHARE) - ) - } - } -} - @Composable private fun ReceiveDetailsView( tab: ReceiveTab, @@ -939,7 +830,7 @@ private fun ReceiveInvoiceErrorView( } } -private enum class BottomButtonVariant { CJIT, SHOW_QR, SHOW_DETAILS } +private enum class BottomButtonVariant { SHOW_QR, SHOW_DETAILS } enum class CopyAddressType { ONCHAIN, LIGHTNING } @@ -1067,7 +958,6 @@ private fun PreviewSavingsMode() { onClickEditInvoice = {}, modifier = Modifier.sheetHeight(), initialTab = ReceiveTab.SAVINGS, - onClickReceiveCjit = {}, ) } } @@ -1138,7 +1028,6 @@ private fun PreviewAutoMode() { onClickEditInvoice = {}, modifier = Modifier.sheetHeight(), initialTab = ReceiveTab.AUTO, - onClickReceiveCjit = {}, ) } } @@ -1204,7 +1093,6 @@ private fun PreviewSpendingMode() { onClickEditInvoice = {}, modifier = Modifier.sheetHeight(), initialTab = ReceiveTab.SPENDING, - onClickReceiveCjit = {}, ) } } @@ -1220,7 +1108,6 @@ private fun PreviewNodeNotReady() { lightningState = LightningState( nodeLifecycleState = NodeLifecycleState.Starting, ), - onClickReceiveCjit = {}, onClickEditInvoice = {}, modifier = Modifier.sheetHeight(), ) @@ -1240,7 +1127,6 @@ private fun PreviewSmall() { ), onClickEditInvoice = {}, modifier = Modifier.sheetHeight(), - onClickReceiveCjit = {}, ) } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt index f0feb93258..ea9b0cdddc 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt @@ -59,7 +59,6 @@ import kotlin.time.ExperimentalTime @Composable fun ReceiveSheet( appViewModel: AppViewModel, - navigateToExternalConnection: () -> Unit, walletState: WalletState, isOffline: Boolean, startRoute: ReceiveRoute = ReceiveRoute.QR, @@ -82,7 +81,6 @@ fun ReceiveSheet( LaunchedEffect(startRoute) { navController.navigateToReceiveStart(startRoute) } - var editInvoiceSourceTab by remember { mutableStateOf(ReceiveTab.SAVINGS) } val lightningState: LightningState by wallet.lightningState.collectAsStateWithLifecycle() val sparkState by wallet.sparkState.collectAsStateWithLifecycle() val paymentRequestTargets by appViewModel.eligiblePaymentRequestTargets.collectAsStateWithLifecycle() @@ -150,15 +148,12 @@ fun ReceiveSheet( walletState = walletState, lightningState = lightningState, canReceiveWithSpark = sparkState.isUsable, - onClickReceiveCjit = { navController.navigateTo(ReceiveRoute.TransferUnavailable) }, onClickEditInvoice = { - editInvoiceSourceTab = it invoiceEditState.beginSoftwareEdit(it) resetEditInvoiceAmount() navController.navigateTo(ReceiveRoute.EditInvoice) }, onClickHardwareEditInvoice = { - editInvoiceSourceTab = ReceiveTab.HARDWARE invoiceEditState.beginHardwareEdit() resetEditInvoiceAmount() navController.navigateTo(ReceiveRoute.EditInvoice) @@ -269,19 +264,12 @@ fun ReceiveSheet( ) } } - composableWithDefaultTransitions { - TransferUnavailableScreen( - onBack = { navController.popBackStack() }, - onContinue = navigateToExternalConnection, - ) - } composableWithDefaultTransitions { val walletUiState by wallet.walletState.collectAsStateWithLifecycle() @Suppress("ViewModelForwarding") EditInvoiceScreen( amountInputViewModel = editInvoiceAmountViewModel, walletUiState = walletUiState, - sourceTab = editInvoiceSourceTab, onBack = { navController.popBackStack() }, updateInvoice = wallet::updateBip21Invoice, onClickAddTag = { navController.navigateTo(ReceiveRoute.AddTag) }, @@ -301,7 +289,6 @@ fun ReceiveSheet( }, onchainOnly = invoiceEditState.isHardwareInvoice, updateOnchainInvoice = wallet::setBip21AmountSats, - navigateTransferUnavailable = { navController.navigateTo(ReceiveRoute.TransferUnavailable) }, ) } composableWithDefaultTransitions { @@ -400,15 +387,11 @@ sealed interface ReceiveRoute { @Serializable data object PaymentRequestSent : InternalOnly - @Serializable - data object TransferUnavailable : DeepLinkStart - companion object { private val DEEP_LINK_STARTS: List = listOf( QR, EditInvoice, AddTag, - TransferUnavailable, ) fun fromDeepLink(path: String): DeepLinkStart? = diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/TransferUnavailableScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/TransferUnavailableScreen.kt deleted file mode 100644 index 6c62cf1f8f..0000000000 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/TransferUnavailableScreen.kt +++ /dev/null @@ -1,40 +0,0 @@ -package to.bitkit.ui.screens.wallets.receive - -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.tooling.preview.Preview -import to.bitkit.R -import to.bitkit.ui.components.BottomSheetPreview -import to.bitkit.ui.shared.modifiers.sheetHeight -import to.bitkit.ui.sheets.TransferUnavailableContent -import to.bitkit.ui.theme.AppThemeSurface - -@Composable -fun TransferUnavailableScreen( - onBack: () -> Unit, - onContinue: () -> Unit, - modifier: Modifier = Modifier, -) { - TransferUnavailableContent( - navTitle = stringResource(R.string.lightning__transfer_unavailable__nav_title), - description = stringResource(R.string.lightning__transfer_unavailable__text), - onContinue = onContinue, - onBack = onBack, - modifier = modifier, - ) -} - -@Preview(showSystemUi = true) -@Composable -private fun Preview() { - AppThemeSurface { - BottomSheetPreview { - TransferUnavailableScreen( - onBack = {}, - onContinue = {}, - modifier = Modifier.sheetHeight(), - ) - } - } -} diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index a3d45a4bf9..95147f78fa 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -878,6 +878,8 @@ private fun LightningDetails( } } + UpdateFeeCell(uiState.sparkUpdateQuote?.feeSats) + val swapRoute = uiState.paykitSwapRoute val swapQuote = swapRoute?.quote if (swapQuote != null) { @@ -890,14 +892,6 @@ private fun LightningDetails( modifier = Modifier.testTag("ReviewSwapRoute") ) } - } else if (uiState.routedPaykitRoute?.serviceLeg != null) { - SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { - BodySSB( - text = stringResource(R.string.wallet__send_swap_route_spark), - maxLines = 1, - modifier = Modifier.testTag("ReviewSwapRoute") - ) - } } if (!isLnurlPay && !description.isNullOrEmpty() && description.trim() != uiState.confirmationRequestNote) { @@ -1002,6 +996,8 @@ private fun LnurlPayDetails( } } + UpdateFeeCell(uiState.sparkUpdateQuote?.feeSats) + if (lnurlPay.data.commentAllowed()) { LnurlCommentSection(uiState, onEvent) } @@ -1365,3 +1361,18 @@ private fun PreviewNodeNotRunning() { } } } + +/** The fee of the spending balance update a payment that fits only across the channels and Spark runs first. */ +@Composable +private fun UpdateFeeCell(feeSats: ULong?) { + if (feeSats == null) return + SendCell(caption = stringResource(R.string.wallet__send_update_fee)) { + BodySSB( + text = (rememberMoneyText(feeSats.toLong(), showSymbol = true) ?: "").withAccent( + accentColor = Colors.White + ), + maxLines = 1, + modifier = Modifier.testTag("ReviewUpdateFee") + ) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionViewModel.kt index ad0d437eaf..cf64ae8847 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionViewModel.kt @@ -10,13 +10,10 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R -import to.bitkit.ext.amountOnClose import to.bitkit.models.Toast -import to.bitkit.models.TransferType import to.bitkit.repositories.LightningRepo -import to.bitkit.repositories.TransferRepo -import to.bitkit.repositories.WalletRepo import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.usecases.CloseChannelUseCase import to.bitkit.utils.Logger import javax.inject.Inject @@ -24,8 +21,7 @@ import javax.inject.Inject class CloseConnectionViewModel @Inject constructor( @ApplicationContext private val context: Context, private val lightningRepo: LightningRepo, - private val walletRepo: WalletRepo, - private val transferRepo: TransferRepo, + private val closeChannelUseCase: CloseChannelUseCase, ) : ViewModel() { companion object { @@ -46,16 +42,8 @@ class CloseConnectionViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } - lightningRepo.closeChannel(channel).fold( + closeChannelUseCase(channel).fold( onSuccess = { - transferRepo.createTransfer( - type = TransferType.COOP_CLOSE, - amountSats = channel.amountOnClose.toLong(), - channelId = channel.channelId, - fundingTxId = channel.fundingTxo?.txid, - ) - walletRepo.syncNodeAndWallet() - ToastEventBus.send( type = Toast.ToastType.SUCCESS, title = context.getString(R.string.lightning__close_success_title), diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt index f7959f2bc7..1ada3c8d13 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt @@ -89,6 +89,7 @@ object LightningConnectionsTestTags { fun LightningConnectionsScreen( navController: NavController, viewModel: LightningConnectionsViewModel, + onClickMoveToSpark: () -> Unit, ) { val context = LocalContext.current val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -108,7 +109,7 @@ fun LightningConnectionsScreen( navController.navigateTo(Routes.ChannelDetail(channelUi.details.channelId)) }, onClickSpark = { navController.navigateTo(Routes.SparkDetail) }, - onClickMoveToSpark = { navController.navigateTo(Routes.MoveToSpark) }, + onClickMoveToSpark = onClickMoveToSpark, onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, onRefresh = { viewModel.onPullToRefresh() diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index 7d5c15e691..794f766f80 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -9,22 +9,24 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import org.lightningdevkit.ldknode.ChannelDetails import to.bitkit.async.appScope import to.bitkit.di.BgDispatcher -import to.bitkit.ext.filterOpen import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.MoveToSparkError import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.WalletRepo +import to.bitkit.usecases.CloseChannelUseCase import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject import javax.inject.Singleton /** - * Holds the Move to Spark screen's state for the app's lifetime, so a move and its outcome outlive the screen: leaving - * while the payment is under way no longer stops the wait, and opening the screen again shows that move. + * Holds the Update Spending Balance modal's state for the app's lifetime, so a move and its outcome outlive the modal: + * leaving while the payment is under way no longer stops the wait, and opening the modal again shows that move. Once a + * move settles, it closes the channels the move emptied. */ @Singleton class MoveToSparkManager @Inject constructor( @@ -32,6 +34,7 @@ class MoveToSparkManager @Inject constructor( private val moveToSparkRepo: MoveToSparkRepo, private val lightningRepo: LightningRepo, private val walletRepo: WalletRepo, + private val closeChannelUseCase: CloseChannelUseCase, ) { companion object { private const val TAG = "MoveToSparkManager" @@ -107,6 +110,7 @@ class MoveToSparkManager @Inject constructor( val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return if (confirm.isMoving) return val quote = confirm.quote + val channelsBefore = lightningRepo.lightningState.value.channels.toList() val moveGeneration = generation.incrementAndGet() keepsOutcome = true isMoveInFlight = true @@ -120,7 +124,11 @@ class MoveToSparkManager @Inject constructor( } val done = done(outcome) if (generation.get() == moveGeneration) _uiState.update { done } - settled?.await()?.let { showLateOutcome(it, moveGeneration) } + if (outcome is MoveToSparkOutcome.Moved) closeEmptied(channelsBefore) + settled?.await()?.let { + showLateOutcome(it, moveGeneration) + if (it.isSuccess) closeEmptied(channelsBefore) + } }, onFailure = { error -> if (generation.get() == moveGeneration) _uiState.update { error.toUiState() } @@ -135,7 +143,14 @@ class MoveToSparkManager @Inject constructor( private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { walletRepo.syncNodeAndWallet() val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) - return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) + return MoveToSparkUiState.Done(outcome, hasRest) + } + + private fun closeEmptied(channelsBefore: List) { + scope.launch { + walletRepo.syncNodeAndWallet() + closeChannelUseCase.closeEmptiedByMove(channelsBefore) + } } private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { @@ -150,10 +165,6 @@ class MoveToSparkManager @Inject constructor( private fun MoveToSparkUiState.isInFlight(): Boolean = this is MoveToSparkUiState.Done && outcome is MoveToSparkOutcome.InFlight - /** The channel to close after the move, when exactly one is open; with several, the user picks in Connections. */ - private fun emptiedChannelId(): String? = lightningRepo.lightningState.value.channels.filterOpen() - .singleOrNull()?.channelId - private fun Throwable.toUiState(): MoveToSparkUiState = when (this) { is MoveToSparkError.TooLarge -> MoveToSparkUiState.TooLarge( amountSats = amountSats, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkScreen.kt deleted file mode 100644 index 99bc9f8d70..0000000000 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkScreen.kt +++ /dev/null @@ -1,340 +0,0 @@ -package to.bitkit.ui.settings.lightning - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.aspectRatio -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.sizeIn -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.scale -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import to.bitkit.R -import to.bitkit.repositories.MoveToSparkOutcome -import to.bitkit.repositories.MoveToSparkQuote -import to.bitkit.ui.components.BodyM -import to.bitkit.ui.components.Display -import to.bitkit.ui.components.GradientCircularProgressIndicator -import to.bitkit.ui.components.MoneyCaptionB -import to.bitkit.ui.components.PrimaryButton -import to.bitkit.ui.components.SecondaryButton -import to.bitkit.ui.components.SwipeToConfirm -import to.bitkit.ui.components.VerticalSpacer -import to.bitkit.ui.components.rememberMoneyText -import to.bitkit.ui.scaffold.AppTopBar -import to.bitkit.ui.scaffold.ScreenColumn -import to.bitkit.ui.theme.AppThemeSurface -import to.bitkit.ui.theme.Colors -import to.bitkit.ui.utils.withAccent -import to.bitkit.ui.utils.withAccentBoldBright - -/** Moves the channels' balance to the user's Spark wallet over Lightning, then offers to close the emptied channel. */ -@Composable -fun MoveToSparkScreen( - viewModel: MoveToSparkViewModel, - onBack: () -> Unit, - onCloseChannel: (channelId: String?) -> Unit, -) { - val uiState by viewModel.uiState.collectAsStateWithLifecycle() - Content( - uiState = uiState, - onBack = onBack, - onMove = viewModel::move, - onRetry = viewModel::quote, - onCloseChannel = onCloseChannel, - ) -} - -@Composable -private fun Content( - uiState: MoveToSparkUiState, - onBack: () -> Unit = {}, - onMove: () -> Unit = {}, - onRetry: (ULong?) -> Unit = {}, - onCloseChannel: (String?) -> Unit = {}, -) { - ScreenColumn { - AppTopBar( - titleText = stringResource(R.string.lightning__move_to_spark__nav_title), - onBackClick = onBack, - ) - Column( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 16.dp) - ) { - when (uiState) { - MoveToSparkUiState.Quoting -> Quoting() - is MoveToSparkUiState.Confirm -> Confirm(uiState.quote, uiState.isMoving, onMove) - is MoveToSparkUiState.Done -> Done(uiState, onBack, onRetry, onCloseChannel) - is MoveToSparkUiState.TooLarge -> TooLarge(uiState, onBack, onRetry) - is MoveToSparkUiState.Failed -> Failed(uiState.failure, onBack, onRetry) - } - VerticalSpacer(16.dp) - } - } -} - -@Composable -private fun Header(title: String, text: String) { - VerticalSpacer(32.dp) - Display(text = title.withAccent(accentColor = Colors.Purple)) - VerticalSpacer(8.dp) - BodyM(text = text.withAccentBoldBright(), color = Colors.White64) -} - -/** Takes the height between the content and the bottom buttons, so the buttons stay at the screen's bottom. */ -@Composable -private fun ColumnScope.Illustration(@DrawableRes drawable: Int) { - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .padding(vertical = 16.dp) - ) { - Image( - painter = painterResource(drawable), - contentDescription = null, - contentScale = ContentScale.Fit, - modifier = Modifier - .sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) - .aspectRatio(1f) - .scale(illustrationScale(drawable)) - ) - } -} - -/** Scales each illustration so its drawing fills its box like the zap; the others have wider transparent margins. */ -private fun illustrationScale(@DrawableRes drawable: Int): Float = when (drawable) { - R.drawable.check -> 1.25f - R.drawable.cross -> 1.4f - R.drawable.exclamation_mark -> 1.1f - else -> 1f -} - -@Composable -private fun ColumnScope.Quoting() { - Header( - title = stringResource(R.string.lightning__move_to_spark__confirm_title), - text = stringResource(R.string.lightning__move_to_spark__quoting), - ) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .weight(1f) - .fillMaxWidth() - ) { - GradientCircularProgressIndicator(modifier = Modifier.size(64.dp)) - } -} - -@Composable -private fun ColumnScope.Confirm(quote: MoveToSparkQuote, isMoving: Boolean, onMove: () -> Unit) { - Header( - title = stringResource(R.string.lightning__move_to_spark__confirm_title), - text = stringResource(R.string.lightning__move_to_spark__confirm_text), - ) - VerticalSpacer(32.dp) - AmountRow(stringResource(R.string.lightning__move_to_spark__amount), quote.amountSats, "MoveToSparkAmount") - AmountRow(stringResource(R.string.lightning__move_to_spark__fee), quote.feeSats, "MoveToSparkFee") - Illustration(R.drawable.lightning) - SwipeToConfirm( - text = stringResource(R.string.lightning__move_to_spark__swipe), - color = Colors.Purple, - loading = isMoving, - enabled = !isMoving, - onConfirm = onMove, - modifier = Modifier.testTag("MoveToSparkSwipe") - ) -} - -@Composable -private fun AmountRow(label: String, sats: ULong, testTag: String) { - SectionRow( - name = label, - valueContent = { MoneyCaptionB(sats = sats.toLong(), symbol = true, modifier = Modifier.testTag(testTag)) }, - ) -} - -@Composable -private fun ColumnScope.Done( - uiState: MoveToSparkUiState.Done, - onDone: () -> Unit, - onMoveRest: (ULong?) -> Unit, - onCloseChannel: (String?) -> Unit, -) { - val outcome = uiState.outcome - val isInFlight = outcome is MoveToSparkOutcome.InFlight - Header( - title = stringResource( - if (isInFlight) { - R.string.lightning__move_to_spark__in_flight_title - } else { - R.string.lightning__move_to_spark__done_title - } - ), - text = stringResource( - when { - isInFlight -> R.string.lightning__move_to_spark__in_flight_text - uiState.hasRest -> R.string.lightning__move_to_spark__done_rest_text - else -> R.string.lightning__move_to_spark__done_text - } - ), - ) - VerticalSpacer(32.dp) - AmountRow(stringResource(R.string.lightning__move_to_spark__amount), outcome.amountSats, "MoveToSparkMoved") - if (outcome is MoveToSparkOutcome.Moved) { - AmountRow(stringResource(R.string.lightning__move_to_spark__fee), outcome.feeSats, "MoveToSparkFeePaid") - } - Illustration(if (isInFlight) R.drawable.lightning else R.drawable.check) - // While the payment is in flight its amount may still return to the channel, so closing is not offered yet. - if (isInFlight) { - PrimaryButton(text = stringResource(R.string.common__ok), onClick = onDone) - return - } - if (uiState.hasRest) { - Buttons( - secondaryText = stringResource(R.string.common__later), - onSecondary = onDone, - primaryText = stringResource(R.string.lightning__move_to_spark__move_rest), - onPrimary = { onMoveRest(null) }, - primaryTestTag = "MoveToSparkMoveRest", - ) - return - } - Buttons( - secondaryText = stringResource(R.string.common__later), - onSecondary = onDone, - primaryText = stringResource(R.string.common__close), - onPrimary = { onCloseChannel(uiState.closeChannelId) }, - primaryTestTag = "MoveToSparkClose", - ) -} - -@Composable -private fun ColumnScope.TooLarge( - uiState: MoveToSparkUiState.TooLarge, - onBack: () -> Unit, - onRetry: (ULong?) -> Unit, -) { - val amount = amountText(uiState.amountSats) - Header( - title = stringResource(R.string.lightning__move_to_spark__too_large_title), - text = stringResource(R.string.lightning__move_to_spark__too_large_text, amount) + " " + stringResource( - when (uiState.smallerSats) { - null -> R.string.lightning__move_to_spark__too_large_none - else -> R.string.lightning__move_to_spark__too_large_smaller - } - ), - ) - Illustration(R.drawable.exclamation_mark) - val smallerSats = uiState.smallerSats - if (smallerSats == null) { - PrimaryButton(text = stringResource(R.string.common__back), onClick = onBack) - return - } - Buttons( - secondaryText = stringResource(R.string.common__cancel), - onSecondary = onBack, - primaryText = stringResource(R.string.lightning__move_to_spark__move_half), - onPrimary = { onRetry(smallerSats) }, - primaryTestTag = "MoveToSparkTrySmaller", - ) -} - -@Composable -private fun ColumnScope.Failed(failure: MoveToSparkFailure, onBack: () -> Unit, onRetry: (ULong?) -> Unit) { - Header( - title = stringResource(R.string.lightning__move_to_spark__failed_title), - text = stringResource( - when (failure) { - MoveToSparkFailure.NOTHING_TO_MOVE -> R.string.lightning__move_to_spark__failed_nothing - MoveToSparkFailure.SPARK_UNAVAILABLE -> R.string.lightning__move_to_spark__failed_spark - MoveToSparkFailure.UNKNOWN -> R.string.lightning__move_to_spark__failed_unknown - } - ), - ) - Illustration(R.drawable.cross) - if (failure == MoveToSparkFailure.NOTHING_TO_MOVE) { - PrimaryButton(text = stringResource(R.string.common__back), onClick = onBack) - return - } - Buttons( - secondaryText = stringResource(R.string.common__cancel), - onSecondary = onBack, - primaryText = stringResource(R.string.common__try_again), - onPrimary = { onRetry(null) }, - primaryTestTag = "MoveToSparkRetry", - ) -} - -/** The amount, ₿ included, as one inline accent of the body text. */ -@Composable -private fun amountText(sats: ULong): String { - val money = rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() - return "$money" -} - -@Composable -private fun Buttons( - secondaryText: String, - onSecondary: () -> Unit, - primaryText: String, - onPrimary: () -> Unit, - primaryTestTag: String, -) { - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.fillMaxWidth(), - ) { - SecondaryButton(text = secondaryText, onClick = onSecondary, modifier = Modifier.weight(1f)) - PrimaryButton( - text = primaryText, - onClick = onPrimary, - modifier = Modifier - .weight(1f) - .testTag(primaryTestTag) - ) - } -} - -@Preview(showSystemUi = true) -@Composable -private fun PreviewConfirm() { - AppThemeSurface { - Content(uiState = MoveToSparkUiState.Confirm(MoveToSparkQuote("lnbc", 98_500uL, 12uL))) - } -} - -@Preview(showSystemUi = true) -@Composable -private fun PreviewDone() { - AppThemeSurface { - Content(uiState = MoveToSparkUiState.Done(MoveToSparkOutcome.Moved(98_500uL, 9uL), "channel")) - } -} - -@Preview(showSystemUi = true) -@Composable -private fun PreviewTooLarge() { - AppThemeSurface { - Content(uiState = MoveToSparkUiState.TooLarge(98_500uL, 49_250uL)) - } -} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt index d883139998..05e80cc671 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt @@ -7,7 +7,10 @@ import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkQuote import javax.inject.Inject -/** The Move to Spark screen's view of [MoveToSparkManager], which keeps a move running after the screen closes. */ +/** + * The Update Spending Balance modal's view of [MoveToSparkManager], which keeps a move running after the modal closes. + * The modal is a sheet that outlives no navigation entry, so it calls [open] and [close] as it shows and hides. + */ @HiltViewModel class MoveToSparkViewModel @Inject constructor( private val manager: MoveToSparkManager, @@ -15,16 +18,25 @@ class MoveToSparkViewModel @Inject constructor( val uiState = manager.uiState - private val screen = manager.start() + private var screen: Int? = null + + /** Quotes a new move when the modal shows, unless a move is running or still shows its outcome. */ + fun open() { + if (screen == null) screen = manager.start() + } + + /** Forgets a settled move once the modal hides, so the next opening quotes anew. */ + fun close() { + screen?.let { manager.reset(it) } + screen = null + } /** Quotes moving [targetSats], or everything the channels can send. */ fun quote(targetSats: ULong? = null) = manager.quote(targetSats) fun move() = manager.move() - override fun onCleared() { - manager.reset(screen) - } + override fun onCleared() = close() } @Immutable @@ -34,11 +46,7 @@ sealed interface MoveToSparkUiState { data class Confirm(val quote: MoveToSparkQuote, val isMoving: Boolean = false) : MoveToSparkUiState /** [hasRest]: the channels can still send enough to move again, as after a smaller amount. */ - data class Done( - val outcome: MoveToSparkOutcome, - val closeChannelId: String?, - val hasRest: Boolean = false, - ) : MoveToSparkUiState + data class Done(val outcome: MoveToSparkOutcome, val hasRest: Boolean = false) : MoveToSparkUiState /** [amountSats] did not route in one payment; [smallerSats] is the next amount to try, if any is left. */ data class TooLarge(val amountSats: ULong, val smallerSats: ULong?) : MoveToSparkUiState diff --git a/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt index 63f1706fb9..49cef78d41 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt @@ -1,17 +1,23 @@ package to.bitkit.ui.sheets +import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.FlowRowScope +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag @@ -19,26 +25,251 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkQuote import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BottomSheetPreview import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.components.rememberMoneyText import to.bitkit.ui.scaffold.SheetTopBar +import to.bitkit.ui.settings.lightning.MoveToSparkFailure +import to.bitkit.ui.settings.lightning.MoveToSparkUiState +import to.bitkit.ui.settings.lightning.MoveToSparkViewModel import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright -/** Tells channel holders that Blocktank closes its channels and that moving the balance to Spark costs least. */ +/** + * The Update Spending Balance modal: quotes moving the channels' balance to Spark when it opens, moves it on Update and + * reports the outcome in place, from Spending Balance Updated to the states that need another step. + */ @Composable -fun MoveToSparkSheet(onLater: () -> Unit, onMove: () -> Unit, modifier: Modifier = Modifier) { +fun MoveToSparkSheet( + viewModel: MoveToSparkViewModel, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + DisposableEffect(viewModel) { + viewModel.open() + onDispose { viewModel.close() } + } + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + Content( + uiState = uiState, + onDismiss = onDismiss, + onUpdate = viewModel::move, + onQuote = viewModel::quote, + modifier = modifier, + ) +} + +@Composable +private fun Content( + uiState: MoveToSparkUiState, + modifier: Modifier = Modifier, + onDismiss: () -> Unit = {}, + onUpdate: () -> Unit = {}, + onQuote: (ULong?) -> Unit = {}, +) { + when (uiState) { + MoveToSparkUiState.Quoting -> Update(null, true, onDismiss, onUpdate, modifier) + is MoveToSparkUiState.Confirm -> Update(uiState.quote.feeSats, uiState.isMoving, onDismiss, onUpdate, modifier) + is MoveToSparkUiState.Done -> Done(uiState, onDismiss, onQuote, modifier) + is MoveToSparkUiState.TooLarge -> TooLarge(uiState, onDismiss, onQuote, modifier) + is MoveToSparkUiState.Failed -> Failed(uiState.failure, onDismiss, onQuote, modifier) + } +} + +@Composable +private fun Update( + feeSats: ULong?, + isLoading: Boolean, + onDismiss: () -> Unit, + onUpdate: () -> Unit, + modifier: Modifier = Modifier, +) { + val text = stringResource(R.string.lightning__move_to_spark__update_text) + val fee = feeSats?.let { stringResource(R.string.lightning__move_to_spark__update_fee, plainMoney(it)) } + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__update_nav_title), + drawable = R.drawable.lightning, + title = stringResource(R.string.lightning__move_to_spark__update_title), + text = fee?.let { "$text $it" } ?: text, + testTag = "UpdateSpendingBalance", + modifier = modifier, + ) { + SecondaryButton( + stringResource(R.string.common__later), + onClick = onDismiss, + testTag = "UpdateSpendingBalanceLater", + modifier = Modifier.weight(1f) + ) + PrimaryButton( + stringResource(R.string.lightning__move_to_spark__update), + onClick = onUpdate, + isLoading = isLoading, + enabled = !isLoading, + modifier = Modifier.weight(1f).testTag("UpdateSpendingBalanceUpdate") + ) + } +} + +@Composable +private fun Done( + uiState: MoveToSparkUiState.Done, + onDismiss: () -> Unit, + onQuote: (ULong?) -> Unit, + modifier: Modifier = Modifier, +) { + // While the payment is in flight its amount may still return to the channel, so nothing is closed yet. + if (uiState.outcome is MoveToSparkOutcome.InFlight) { + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__update_nav_title), + drawable = R.drawable.lightning, + title = stringResource(R.string.lightning__move_to_spark__in_flight_title), + text = stringResource(R.string.lightning__move_to_spark__in_flight_text), + testTag = "MoveToSparkInFlight", + modifier = modifier, + ) { + PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + } + return + } + if (uiState.hasRest) { + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__update_nav_title), + drawable = R.drawable.check, + title = stringResource(R.string.lightning__move_to_spark__done_title), + text = stringResource(R.string.lightning__move_to_spark__updated_rest_text), + testTag = "MoveToSparkPartlyMoved", + modifier = modifier, + ) { + SecondaryButton( + stringResource(R.string.common__later), + onClick = onDismiss, + modifier = Modifier.weight(1f) + ) + PrimaryButton( + stringResource(R.string.lightning__move_to_spark__move_rest), + onClick = { onQuote(null) }, + modifier = Modifier.weight(1f).testTag("MoveToSparkMoveRest") + ) + } + return + } + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__updated_nav_title), + drawable = R.drawable.check, + title = stringResource(R.string.lightning__move_to_spark__updated_title), + text = stringResource(R.string.lightning__move_to_spark__updated_text), + testTag = "SpendingBalanceUpdated", + modifier = modifier, + ) { + PrimaryButton( + stringResource(R.string.common__ok), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag("SpendingBalanceUpdatedOk") + ) + } +} + +@Composable +private fun TooLarge( + uiState: MoveToSparkUiState.TooLarge, + onDismiss: () -> Unit, + onQuote: (ULong?) -> Unit, + modifier: Modifier = Modifier, +) { + val amount = "${plainMoney(uiState.amountSats)}" + val smallerSats = uiState.smallerSats + val next = stringResource( + if (smallerSats == null) { + R.string.lightning__move_to_spark__too_large_none + } else { + R.string.lightning__move_to_spark__too_large_smaller + } + ) + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__update_nav_title), + drawable = R.drawable.exclamation_mark, + title = stringResource(R.string.lightning__move_to_spark__too_large_title), + text = stringResource(R.string.lightning__move_to_spark__too_large_text, amount) + " " + next, + testTag = "MoveToSparkTooLarge", + modifier = modifier, + ) { + if (smallerSats == null) { + PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + return@Modal + } + SecondaryButton(stringResource(R.string.common__cancel), onClick = onDismiss, modifier = Modifier.weight(1f)) + PrimaryButton( + stringResource(R.string.lightning__move_to_spark__move_half), + onClick = { onQuote(smallerSats) }, + modifier = Modifier.weight(1f).testTag("MoveToSparkTrySmaller") + ) + } +} + +@Composable +private fun Failed( + failure: MoveToSparkFailure, + onDismiss: () -> Unit, + onQuote: (ULong?) -> Unit, + modifier: Modifier = Modifier, +) { + Modal( + navTitle = stringResource(R.string.lightning__move_to_spark__update_nav_title), + drawable = R.drawable.cross, + title = stringResource(R.string.lightning__move_to_spark__failed_title), + text = stringResource( + when (failure) { + MoveToSparkFailure.NOTHING_TO_MOVE -> R.string.lightning__move_to_spark__failed_nothing + MoveToSparkFailure.SPARK_UNAVAILABLE -> R.string.lightning__move_to_spark__failed_spark + MoveToSparkFailure.UNKNOWN -> R.string.lightning__move_to_spark__failed_unknown + } + ), + testTag = "MoveToSparkFailed", + modifier = modifier, + ) { + if (failure == MoveToSparkFailure.NOTHING_TO_MOVE) { + PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + return@Modal + } + SecondaryButton(stringResource(R.string.common__cancel), onClick = onDismiss, modifier = Modifier.weight(1f)) + PrimaryButton( + stringResource(R.string.common__try_again), + onClick = { onQuote(null) }, + modifier = Modifier.weight(1f).testTag("MoveToSparkRetry") + ) + } +} + +/** The amount in the primary currency with its symbol, without the symbol's accent. */ +@Composable +private fun plainMoney(sats: ULong): String = + rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() + +@Composable +private fun Modal( + navTitle: String, + @DrawableRes drawable: Int, + title: String, + text: String, + testTag: String, + modifier: Modifier = Modifier, + buttons: @Composable FlowRowScope.() -> Unit, +) { Column( - modifier = modifier.sheetHeight().navigationBarsPadding().testTag("MoveToSparkIntro") + modifier = modifier.sheetHeight().navigationBarsPadding().testTag(testTag) ) { - SheetTopBar(stringResource(R.string.lightning__move_to_spark__nav_title)) + SheetTopBar(navTitle) Column(modifier = Modifier.weight(1f).padding(horizontal = 16.dp)) { // The illustration shrinks on small screens so the copy below it stays whole. Box( @@ -46,44 +277,62 @@ fun MoveToSparkSheet(onLater: () -> Unit, onMove: () -> Unit, modifier: Modifier modifier = Modifier.weight(1f).fillMaxWidth() ) { Image( - painter = painterResource(R.drawable.lightning), + painter = painterResource(drawable), contentDescription = null, contentScale = ContentScale.Fit, - modifier = Modifier.sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) + modifier = Modifier + .sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) + .aspectRatio(1f) + .scale(illustrationScale(drawable)) ) } VerticalSpacer(32.dp) - Display( - stringResource(R.string.lightning__move_to_spark__intro_title).withAccent(accentColor = Colors.Purple) - ) + Display(title.withAccent(accentColor = Colors.Purple)) VerticalSpacer(8.dp) - BodyM(stringResource(R.string.lightning__move_to_spark__intro_text), color = Colors.White64) + BodyM(text.withAccentBoldBright(), color = Colors.White64) } VerticalSpacer(32.dp) FlowRow( horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), maxItemsInEachRow = if (LocalDensity.current.fontScale > 1.3f) 1 else 2, - modifier = Modifier.padding(horizontal = 16.dp) - ) { - SecondaryButton( - stringResource(R.string.common__later), - onClick = onLater, - testTag = "MoveToSparkIntroLater", - modifier = Modifier.weight(1f) - ) - PrimaryButton( - stringResource(R.string.lightning__move_to_spark__move_now), - onClick = onMove, - modifier = Modifier.weight(1f).testTag("MoveToSparkIntroMove") - ) - } + modifier = Modifier.padding(horizontal = 16.dp), + content = buttons, + ) VerticalSpacer(16.dp) } } +/** Scales each illustration so its drawing fills its box like the zap; the others have wider transparent margins. */ +private fun illustrationScale(@DrawableRes drawable: Int): Float = when (drawable) { + R.drawable.check -> 1.25f + R.drawable.cross -> 1.4f + R.drawable.exclamation_mark -> 1.1f + else -> 1f +} + @Preview(showSystemUi = true) @Composable -private fun Preview() { - AppThemeSurface { BottomSheetPreview { MoveToSparkSheet({}, {}) } } +private fun PreviewUpdate() { + AppThemeSurface { + BottomSheetPreview { + Content(uiState = MoveToSparkUiState.Confirm(MoveToSparkQuote("lnbc", 98_500uL, 12uL))) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun PreviewUpdated() { + AppThemeSurface { + BottomSheetPreview { Content(uiState = MoveToSparkUiState.Done(MoveToSparkOutcome.Moved(98_500uL, 9uL))) } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun PreviewTooLarge() { + AppThemeSurface { + BottomSheetPreview { Content(uiState = MoveToSparkUiState.TooLarge(98_500uL, 49_250uL)) } + } } diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt new file mode 100644 index 0000000000..e1aff341aa --- /dev/null +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -0,0 +1,56 @@ +package to.bitkit.usecases + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import org.lightningdevkit.ldknode.ChannelDetails +import to.bitkit.di.IoDispatcher +import to.bitkit.ext.amountOnClose +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.TransferType +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.TransferRepo +import to.bitkit.repositories.WalletRepo +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** Closes a channel cooperatively and records its transfer to Savings, so the close shows in Activity. */ +@Singleton +class CloseChannelUseCase @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val lightningRepo: LightningRepo, + private val transferRepo: TransferRepo, + private val walletRepo: WalletRepo, +) { + companion object { + private const val TAG = "CloseChannelUseCase" + } + + suspend operator fun invoke(channel: ChannelDetails): Result = withContext(ioDispatcher) { + runSuspendCatching { + lightningRepo.closeChannel(channel).getOrThrow() + transferRepo.createTransfer( + type = TransferType.COOP_CLOSE, + amountSats = channel.amountOnClose.toLong(), + channelId = channel.channelId, + fundingTxId = channel.fundingTxo?.txid, + ) + walletRepo.syncNodeAndWallet() + Unit + } + } + + /** + * Closes each channel a move to Spark emptied: one that could send at least the move minimum in [before] and can + * no longer. A close that fails leaves its channel listed for a manual close. + */ + suspend fun closeEmptiedByMove(before: List) = withContext(ioDispatcher) { + val emptied = MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) + emptied.forEach { channel -> + invoke(channel) + .onSuccess { Logger.info("Closed channel '${channel.channelId}' emptied by a move", context = TAG) } + .onFailure { Logger.warn("Failed to close channel '${channel.channelId}'", it, context = TAG) } + } + } +} diff --git a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index b6ef2e6da2..ece819767d 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -13,13 +13,13 @@ import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.ext.amountSats import to.bitkit.ext.channelId -import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.BalanceState import to.bitkit.models.TransferType import to.bitkit.models.safe import to.bitkit.models.toBalance import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo @@ -65,11 +65,8 @@ class DeriveBalanceStateUseCase @Inject constructor( totalOnchainSats = totalOnchainSats, channelFundableBalance = channelFundableBalance, totalLightningSats = totalLightningSats, - // A payment goes over one rail, so the larger of the two balances caps it; Spark keeps its fee. - maxSendLightningSats = maxOf( - lightningRepo.getChannels().totalNextOutboundHtlcLimitSats(), - sparkRepo.state.value.sendableSats, - ), + // A payment goes over one rail, or over Spark once the channels' balance is updated to it. + maxSendLightningSats = MoveToSparkMath.maxSendSats(lightningRepo.getChannels(), sparkRepo.state.value), maxSendOnchainSats = getMaxSendAmount(balanceDetails), balanceInTransferToSavings = (toSavingsAmount.safe() - coopCloseSavingsSats.safe()).safe() + sparkExitSats.safe(), diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index dbe871fef6..dd29a8338d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -88,6 +88,7 @@ import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Bolt11Invoice import org.lightningdevkit.ldknode.ChannelDataMigration +import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.ClosureReason import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason @@ -184,6 +185,8 @@ import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LnurlPayInvoiceMismatchError import to.bitkit.repositories.MethodId +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkQuote import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.NodeEventUpdate import to.bitkit.repositories.OnchainPreparedReceipt @@ -270,6 +273,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.usecases.CloseChannelUseCase import to.bitkit.usecases.FormatMoneyValue import to.bitkit.usecases.KeepContactPaymentsOnUseCase import to.bitkit.usecases.RefreshContactPaykitLinkUseCase @@ -358,6 +362,7 @@ class AppViewModel @Inject constructor( private val highBalanceSheet: HighBalanceTimedSheet, private val moveToSparkSheet: MoveToSparkTimedSheet, private val moveToSparkRepo: MoveToSparkRepo, + private val closeChannelUseCase: CloseChannelUseCase, private val formatMoneyValue: FormatMoneyValue, private val widgetsRepo: WidgetsRepo, private val wakeRepo: WakeRepo, @@ -3475,7 +3480,7 @@ class AppViewModel @Inject constructor( if (invoice.amountSatoshis > 0uL) { lightningRepo.syncState() - if (!lightningRepo.canSend(invoice.amountSatoshis)) { + if (!canSendLightning(invoice.amountSatoshis)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = invoice.amountSatoshis.safe() - maxSendLightning.safe() showAddressValidationError( @@ -3626,7 +3631,7 @@ class AppViewModel @Inject constructor( return@takeIf false } waitForUsableChannels(walletGeneration) - val canSend = lightningRepo.canSend(lnInv.amountSatoshis.coerceAtLeast(1u)) + val canSend = canSendLightning(lnInv.amountSatoshis.coerceAtLeast(1u)) if (!canSend) { val nodeState = lightningRepo.lightningState.value.nodeLifecycleState if (nodeState is NodeLifecycleState.Stopped) { @@ -5304,11 +5309,11 @@ class AppViewModel @Inject constructor( sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() when (val lnurl = _sendUiState.value.lnurl) { - null -> amount <= maxSendable && lightningRepo.canSend(amount) + null -> amount <= maxSendable && canSendLightning(amount) is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat() is LnurlParams.LnurlPay -> { val maxSat = lnurl.data.maxSendableSat() - amount <= maxSat && amount <= maxSendable && lightningRepo.canSend(amount) + amount <= maxSat && amount <= maxSendable && canSendLightning(amount) } } } @@ -5335,6 +5340,10 @@ class AppViewModel @Inject constructor( return true.takeIf { lightningRepo.canWithdrawWithSpark(amount) } } + /** Whether a Lightning send can pay [amount]: over one rail, or from Spark once the spending balance is updated. */ + private fun canSendLightning(amount: ULong): Boolean = + lightningRepo.canSend(amount) || moveToSparkRepo.needsUpdateToSend(amount) + private fun maxSendableLightningSats(): ULong { val max = walletRepo.balanceState.value.maxSendLightningSats val fee = _sendUiState.value.estimatedRoutingFee @@ -5940,7 +5949,7 @@ class AppViewModel @Inject constructor( PublicPaykitRepo.onchainMethodId(invoice.address), Clock.System.now() ).amount.atomic - if (!lightningRepo.canSend(amount) && onchainAmount <= maxSendOnchain) { + if (!canSendLightning(amount) && onchainAmount <= maxSendOnchain) { amount = onchainAmount _sendUiState.update { it.copy(payMethod = SendMethod.ONCHAIN, amount = onchainAmount) } } @@ -6332,7 +6341,7 @@ class AppViewModel @Inject constructor( if (quickPayHandled) return waitForUsableChannels(walletGeneration) - if (!lightningRepo.canSend(amount)) { + if (!canSendLightning(amount)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = amount.safe() - maxSendLightning.safe() toast( @@ -6412,7 +6421,7 @@ class AppViewModel @Inject constructor( val paymentAmount = incomingAmount ?: displaySats waitForUsableChannels(walletGeneration) - if (!lightningRepo.canSend(paymentAmount.coerceAtLeast(1u))) { + if (!canSendLightning(paymentAmount.coerceAtLeast(1u))) { toast( type = Toast.ToastType.WARNING, title = context.getString(R.string.other__lnurl_pay_error), @@ -6604,6 +6613,8 @@ class AppViewModel @Inject constructor( if (hasActiveContactPaymentContext()) return false val invoiceHash = invoice?.paymentHash?.toHex()?.takeIf { it.isNotBlank() } val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) + // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. + if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) if (!canApply) return false @@ -7782,16 +7793,21 @@ class AppViewModel @Inject constructor( allowanceAttemptId?.let { paykitAllowanceRepo.manualLightningPaymentSent(it, paymentHash) } var authorizationError: Throwable? = null - val result = sendLightning( - decodedInvoice.bolt11, - paymentAmount, - incomingPaymentRequest?.submissionDeadline(paykitPaymentTerms), - ) { - authorizationError = incomingPaymentRequest?.let { - paykitPaymentRequestRepo.ensurePaymentAllowed(it).exceptionOrNull() - } - authorizationError == null - } + val result = updateSpendingBalanceIfNeeded(displayAmountSats).fold( + onSuccess = { + sendLightning( + decodedInvoice.bolt11, + paymentAmount, + incomingPaymentRequest?.submissionDeadline(paykitPaymentTerms), + ) { + authorizationError = incomingPaymentRequest?.let { + paykitPaymentRequestRepo.ensurePaymentAllowed(it).exceptionOrNull() + } + authorizationError == null + } + }, + onFailure = { Result.failure(it) }, + ) authorizationError?.let { paykitPaymentProofRepo.failLightningPayment(paymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) @@ -7843,6 +7859,26 @@ class AppViewModel @Inject constructor( } } + /** + * Before a payment of [amountSats] that fits only across the channels and Spark, moves the channels' balance to + * Spark. Once the move settles, closes the channels it emptied in the background, even when the payment then fails. + * A failure after the move leaves the funds in Spark. + */ + private suspend fun updateSpendingBalanceIfNeeded(amountSats: ULong): Result { + if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) + val channelsBefore = lightningRepo.lightningState.value.channels.toList() + return moveToSparkRepo.updateToSend(_sendUiState.value.sparkUpdateQuote, amountSats) { + closeChannelsEmptiedBy(it, channelsBefore) + }.map { } + } + + private fun closeChannelsEmptiedBy(outcome: MoveToSparkOutcome, channelsBefore: List) { + viewModelScope.launch(bgDispatcher) { + if (outcome is MoveToSparkOutcome.InFlight && moveToSparkRepo.awaitSettled(outcome).isFailure) return@launch + closeChannelUseCase.closeEmptiedByMove(channelsBefore) + } + } + private suspend fun savePendingLnurlComment(invoice: LightningInvoice, paymentHash: String): String? { val state = _sendUiState.value if (state.lnurl !is LnurlParams.LnurlPay || state.comment.isBlank()) return null @@ -8538,6 +8574,12 @@ class AppViewModel @Inject constructor( // A Spark leg pays the contact's other endpoint, so its fee is the leg's, never the retained invoice's. if (currentState.routedPaykitRoute?.serviceLeg != null) return val decodedInvoice = currentState.decodedInvoice ?: return + val payAmount = decodedInvoice.amountSatoshis.takeIf { it > 0uL } ?: currentState.amount + if (moveToSparkRepo.needsUpdateToSend(payAmount)) { + estimateSparkUpdateFees(decodedInvoice.bolt11, payAmount, generation, walletGeneration) + return + } + _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(sparkUpdateQuote = null) } val feeResult = if (decodedInvoice.amountSatoshis > 0uL) { lightningRepo.estimateRoutingFees(decodedInvoice.bolt11) @@ -8557,6 +8599,22 @@ class AppViewModel @Inject constructor( } } + /** Quotes the spending balance update a payment of [payAmount] needs, and Spark's fee for the payment after it. */ + private suspend fun estimateSparkUpdateFees( + bolt11: String, + payAmount: ULong, + generation: Long, + walletGeneration: Long?, + ) { + val quote = moveToSparkRepo.quote().getOrNull() + val fee = moveToSparkRepo.estimateFeeAfterUpdate(bolt11, payAmount) + requireCurrentPaymentPreparation(walletGeneration) + _sendUiState.update { + if (generation != sendStateGeneration) return@update it + it.copy(lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), sparkUpdateQuote = quote) + } + } + private suspend fun estimateMaxAmountRoutingFee() { val currentState = _sendUiState.value if (currentState.payMethod != SendMethod.LIGHTNING) return @@ -10236,6 +10294,8 @@ data class SendUiState( val feeRates: FeeRates? = null, val onchainFeeUi: OnchainFeeUi = OnchainFeeUi(), val lightningFeeSats: Long? = null, + /** The spending balance update a Lightning payment that fits only across the channels and Spark runs first. */ + val sparkUpdateQuote: MoveToSparkQuote? = null, val estimatedRoutingFee: ULong = 0uL, val lastLightningFee: Long = 0L, val contactPaymentProfile: PubkyProfile? = null, diff --git a/app/src/main/res/drawable/arrow.xml b/app/src/main/res/drawable/arrow.xml deleted file mode 100644 index 9d3ab6b589..0000000000 --- a/app/src/main/res/drawable/arrow.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6b2b63d0d4..3fa23cbdff 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -167,27 +167,16 @@ قابل للاستخدام أرصدة Lightning ارتفاع أرشفة مراقب القناة - المبلغ - سينتقل رصيدك إلى Spark عبر Lightning، وهي أقل طريقة رسومًا للإبقاء عليه في الإنفاق. رسوم التوجيه أدناه هي أقصى ما تدفعه. - النقل إلى\n<accent>Spark</accent> - جزء من رصيدك على Spark الآن. انقل الباقي بالطريقة نفسها، ثم أغلق الاتصال الذي فرغ. - رصيدك على Spark الآن. أغلق الاتصال الذي فرغ لإعادة احتياطيه إلى المدخرات. تم النقل إلى\n<accent>Spark</accent> لم يعد في اتصالات Lightning الخاصة بك رصيد للنقل. Spark غير جاهز للاستلام بعد. حاول مرة أخرى بعد قليل. تعذّر\n<accent>النقل</accent> حدث خطأ أثناء تجهيز النقل. حاول مرة أخرى. - رسوم التوجيه الدفعة في طريقها وستظهر في Spark بمجرد اكتمالها. إذا فشلت، يبقى المبلغ في اتصالك. جارٍ النقل إلى\n<accent>Spark</accent> - يغلق Blocktank اتصالات Lightning الخاصة به. انقل رصيدك إلى Spark الآن: إنه الخيار الأقل رسومًا، ويبقى في الإنفاق. - اتصالك\n<accent>يُغلق</accent> انقل النصف - انقل الآن انقل الباقي النقل إلى Spark - جارٍ البحث عن مسار ورسومه… - اسحب للنقل أغلق الاتصال بدلًا من ذلك لإعادة الرصيد إلى المدخرات. يمكنك نقله على أجزاء أصغر. %1$s كبير جدًا بحيث لا يمكن توجيهه إلى Spark في دفعة واحدة. @@ -1105,14 +1094,11 @@ جارٍ إرسال الإيصال تم إرسال الإيصال استلام - استلام أموال Lightning استلام Bitcoin فاتورة Bitcoin تم نسخ الفاتورة إلى الحافظة فاتورة Lightning ملاحظة اختيارية للدافع - استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. - استلم على <accent>رصيد الإنفاق</accent> عرض التفاصيل عرض رمز QR تعديل الفاتورة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 990f8a7c97..c884044bc4 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -174,27 +174,16 @@ Es utilizable Saldos Lightning Altura de archivo del monitor de canal - Monto - Tu saldo pasa a Spark por Lightning, la forma de menor comisión para mantenerlo en Gastos. La comisión de enrutamiento de abajo es lo máximo que pagas. - Mover a\n<accent>Spark</accent> - Una parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y luego cierra la conexión vacía. - Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorros. Movido a\n<accent>Spark</accent> Tus conexiones Lightning ya no tienen saldo para mover. Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. No se pudo\n<accent>mover</accent> Algo salió mal al preparar el movimiento. Inténtalo de nuevo. - Comisión de enrutamiento El pago está en camino y aparecerá en Spark cuando se complete. Si falla, el monto permanece en tu conexión. Moviendo a\n<accent>Spark</accent> - Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se queda en Gastos. - Tu conexión\n<accent>se está cerrando</accent> Mover la mitad - Mover ahora Mover el resto Mover a Spark - Buscando una ruta y su comisión… - Desliza para mover Mejor cierra la conexión para devolver el saldo a Ahorros. Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. @@ -1135,14 +1124,11 @@ Enviando recibo Recibo enviado Recibir - Recibir fondos Lightning Recibir Bitcoin Factura Bitcoin Factura copiada en el portapapeles Factura Lightning Nota opcional para el pagador - Disfruta transacciones instantáneas y baratas con amigos, familia y comercios. - Recibe en <accent>saldo de gastos</accent> Ver detalles Mostrar código QR Editar factura diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 19a78ec4fa..73e13ed1df 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -171,27 +171,16 @@ És utilitzable Saldos Lightning Alçada d\'arxiu del monitor de canal - Import - El teu saldo passa a Spark per Lightning, la manera amb menys comissió de mantenir-lo a despesa. La comissió d\'encaminament de sota és el màxim que pagues. - Mou a\n<accent>Spark</accent> - Una part del teu saldo ja és a Spark. Mou la resta de la mateixa manera i després tanca la connexió buida. - El teu saldo ja és a Spark. Tanca la connexió buida per retornar-ne la reserva als estalvis. Mogut a\n<accent>Spark</accent> Les teves connexions Lightning ja no tenen saldo per moure. Spark encara no està a punt per rebre. Torna-ho a provar d\'aquí a un moment. No s\'ha pogut\n<accent>moure</accent> Alguna cosa ha fallat en preparar el moviment. Torna-ho a provar. - Comissió d\'encaminament El pagament està en camí i apareixerà a Spark quan es completi. Si falla, l\'import es queda a la teva connexió. Movent a\n<accent>Spark</accent> - Blocktank tanca les seves connexions Lightning. Mou ara el teu saldo a Spark: és l\'opció amb menys comissió i es queda a despesa. - La teva connexió\n<accent>es tanca</accent> Mou la meitat - Mou ara Mou la resta Moure a Spark - Cercant una ruta i la seva comissió… - Desplaça per moure Tanca la connexió per retornar el saldo als estalvis. Pots moure\'l en parts més petites. %1$s és massa gran per encaminar-se a Spark en un sol pagament. @@ -1129,14 +1118,11 @@ S\'està enviant el rebut Rebut enviat Rebre - Rebre fons Lightning Rebre Bitcoin Factura de Bitcoin Factura copiada al porta-retalls Factura Lightning Nota opcional per al pagador - Gaudeix de transaccions instantànies i barates amb amics, família i comerciants. - Rebre al <accent>saldo de despesa</accent> Mostrar detalls Mostra el codi QR Editar factura diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 6707b699ee..2deb172fe7 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -174,27 +174,16 @@ Je použitelný? Lightning zůstatky Archivní výška monitoru kanálu - Částka - Váš zůstatek se přesune do Spark přes Lightning, což je nejlevnější způsob, jak ho ponechat ve výdajích. Poplatek za směrování níže je nejvíc, co zaplatíte. - Přesun do\n<accent>Spark</accent> - Část vašeho zůstatku je nyní ve Spark. Zbytek přesuňte stejným způsobem a pak zavřete vyprázdněné spojení. - Váš zůstatek je nyní ve Spark. Zavřete vyprázdněné spojení, aby se jeho rezerva vrátila do úspor. Přesunuto do\n<accent>Spark</accent> Vaše spojení Lightning už nemají žádný zůstatek k přesunu. Spark ještě není připraven přijímat. Zkuste to za chvíli znovu. Přesun se\n<accent>nezdařil</accent> Při přípravě přesunu se něco pokazilo. Zkuste to znovu. - Poplatek za směrování Platba je na cestě a po dokončení se zobrazí ve Spark. Pokud selže, částka zůstane ve vašem spojení. Přesun do\n<accent>Spark</accent> - Blocktank zavírá svá spojení Lightning. Přesuňte svůj zůstatek do Spark hned: je to nejlevnější možnost a zůstane ve výdajích. - Vaše spojení\n<accent>se zavírá</accent> Přesunout polovinu - Přesunout hned Přesunout zbytek Přesun do Spark - Hledání trasy a jejího poplatku… - Přejetím přesunout Místo toho zavřete spojení, aby se zůstatek vrátil do úspor. Můžete ho přesunout po menších částech. %1$s je příliš velká částka na směrování do Spark jednou platbou. @@ -1133,14 +1122,11 @@ Odesílání potvrzení Potvrzení odesláno Přijmout - Přijímat Lightning prostředky Přijmout bitcoin bitcoinová faktura Faktura zkopírovaná do schránky Lightningová faktura Nepovinná poznámka pro plátce - Užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky. - Přijímat na disponibilní zůstatek Zobrazit podrobnosti Zobrazit QR kód Upravit fakturu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 36dddb6c6c..17a06aea19 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -102,27 +102,16 @@ Anderes Wallet verwenden Von HW-Wallet übertragen Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden. - Betrag - Dein Guthaben wird über Lightning zu Spark verschoben, der gebührengünstigsten Möglichkeit, es in den Ausgaben zu behalten. Die Routing-Gebühr unten ist das Maximum, das du zahlst. - Zu\n<accent>Spark</accent> verschieben - Ein Teil deines Guthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise und schließe dann die geleerte Verbindung. - Dein Guthaben ist jetzt auf Spark. Schließe die geleerte Verbindung, um ihre Reserve zurück aufs Sparkonto zu holen. Zu\n<accent>Spark</accent> verschoben Deine Lightning-Verbindungen haben kein Guthaben mehr zum Verschieben. Spark ist noch nicht bereit zum Empfangen. Versuche es gleich noch einmal. Verschieben\n<accent>fehlgeschlagen</accent> Beim Vorbereiten des Verschiebens ist etwas schiefgelaufen. Versuche es erneut. - Routing-Gebühr Die Zahlung ist unterwegs und erscheint in Spark, sobald sie abgeschlossen ist. Schlägt sie fehl, bleibt der Betrag in deiner Verbindung. Verschiebe zu\n<accent>Spark</accent> - Blocktank schließt seine Lightning-Verbindungen. Verschiebe dein Guthaben jetzt zu Spark: Das ist die gebührengünstigste Option, und es bleibt in den Ausgaben. - Deine Verbindung\n<accent>wird geschlossen</accent> Hälfte verschieben - Jetzt verschieben Rest verschieben Zu Spark verschieben - Route und Gebühr werden gesucht… - Swipe zum Verschieben Schließe stattdessen die Verbindung, um das Guthaben aufs Sparkonto zurückzuholen. Du kannst es in kleineren Teilen verschieben. %1$s ist zu groß, um in einer Zahlung zu Spark geroutet zu werden. @@ -1128,9 +1117,6 @@ Lightning-Rechnung Optionale Notiz an den Zahler QR-Code anzeigen - Lightning-Gelder empfangen - Empfangen auf <accent>Ausgabenguthaben</accent> - Genieße sofortige und günstige Transaktionen mit Freunden, Familie und Händlern. Details anzeigen Auto Sparkonto diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5384e45e8c..4c634664c3 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -167,27 +167,16 @@ Είναι χρησιμοποιήσιμο Υπόλοιπα Lightning Ύψος αρχειοθέτησης παρακολούθησης καναλιού - Ποσό - Το υπόλοιπό σου μεταφέρεται στο Spark μέσω Lightning, τον τρόπο με τα χαμηλότερα τέλη για να παραμείνει στις Δαπάνες. Τα τέλη δρομολόγησης παρακάτω είναι το μέγιστο που πληρώνεις. - Μεταφορά στο\n<accent>Spark</accent> - Μέρος του υπολοίπου σου βρίσκεται πλέον στο Spark. Μετάφερε το υπόλοιπο με τον ίδιο τρόπο και μετά κλείσε την άδεια σύνδεση. - Το υπόλοιπό σου βρίσκεται πλέον στο Spark. Κλείσε την άδεια σύνδεση για να επιστρέψει το απόθεμά της στις Αποταμιεύσεις. Μεταφέρθηκε στο\n<accent>Spark</accent> Οι συνδέσεις Lightning σου δεν έχουν πλέον υπόλοιπο για μεταφορά. Το Spark δεν είναι ακόμη έτοιμο να λάβει. Δοκίμασε ξανά σε λίγο. Αδυναμία\n<accent>μεταφοράς</accent> Κάτι πήγε στραβά κατά την προετοιμασία της μεταφοράς. Δοκίμασε ξανά. - Τέλη δρομολόγησης Η πληρωμή βρίσκεται καθ\'οδόν και θα εμφανιστεί στο Spark μόλις διακανονιστεί. Αν αποτύχει, το ποσό παραμένει στη σύνδεσή σου. Μεταφορά στο\n<accent>Spark</accent> - Το Blocktank κλείνει τις συνδέσεις Lightning του. Μετάφερε τώρα το υπόλοιπό σου στο Spark: είναι η επιλογή με τα χαμηλότερα τέλη και παραμένει στις Δαπάνες. - Η σύνδεσή σου\n<accent>κλείνει</accent> Μεταφορά του μισού - Μεταφορά τώρα Μεταφορά του υπολοίπου Μεταφορά στο Spark - Αναζήτηση διαδρομής και των τελών της… - Σύρε για μεταφορά Κλείσε αντί γι\' αυτό τη σύνδεση για να επιστρέψει το υπόλοιπο στις Αποταμιεύσεις. Μπορείς να το μεταφέρεις σε μικρότερα μέρη. Το %1$s είναι πολύ μεγάλο για να δρομολογηθεί στο Spark με μία πληρωμή. @@ -1110,14 +1099,11 @@ Αποστολή απόδειξης Η απόδειξη στάλθηκε Λήψη - Λήψη κεφαλαίων Lightning Λήψη Bitcoin Τιμολόγιο Bitcoin Το τιμολόγιο αντιγράφηκε στο πρόχειρο Τιμολόγιο Lightning Προαιρετική σημείωση προς τον πληρωτή - Απόλαυσε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. - Λήψη σε <accent>υπόλοιπο δαπανών</accent> Εμφάνιση λεπτομερειών Εμφάνιση κωδικού QR Επεξεργασία τιμολογίου diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6ff0e34176..b8ba340275 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -173,27 +173,16 @@ ¿Es utilizable? Saldos Lightning Altura de archivo del monitor de canales - Importe - Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. - Mover a\n<accent>Spark</accent> - Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. - Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. Movido a\n<accent>Spark</accent> Tus conexiones Lightning ya no tienen saldo que mover. Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. No se pudo\n<accent>mover</accent> Algo salió mal al preparar el movimiento. Inténtalo de nuevo. - Comisión de enrutamiento El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el importe permanece en tu conexión. Moviendo a\n<accent>Spark</accent> - Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. - Tu conexión\n<accent>se está cerrando</accent> Mover la mitad - Mover ahora Mover el resto Mover a Spark - Buscando una ruta y su comisión… - Desliza para mover Cierra la conexión en su lugar para devolver el saldo a Ahorro. Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. @@ -1130,14 +1119,11 @@ Enviando recibo Recibo enviado Recibir - Recibir fondos Lightning Recibir Bitcoin Factura bitcoin Factura copiada al portapapeles Factura Lightning Nota opcional para el pagador - Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. - Recibe en el <accent>saldo de gasto</accent> Mostrar detalles Mostrar código QR Editar Factura diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c41ca5c6eb..1c53435e98 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -140,27 +140,16 @@ HTLC de entrada mínimo Saldos Lightning Altura de archivo del monitor de canal - Monto - Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. - Mover a\n<accent>Spark</accent> - Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. - Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. Movido a\n<accent>Spark</accent> Tus conexiones Lightning ya no tienen saldo que mover. Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. No se pudo\n<accent>mover</accent> Algo salió mal al preparar el movimiento. Inténtalo de nuevo. - Comisión de enrutamiento El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el monto permanece en tu conexión. Moviendo a\n<accent>Spark</accent> - Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. - Tu conexión\n<accent>se está cerrando</accent> Mover la mitad - Mover ahora Mover el resto Mover a Spark - Buscando una ruta y su comisión… - Desliza para mover Cierra la conexión en su lugar para devolver el saldo a Ahorro. Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. @@ -1115,14 +1104,11 @@ Factura bitcoin Factura Lightning Nota opcional para el pagador - Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. - Recibir en <accent>saldo de gastos</accent> Mostrar Detalles Mostrar código QR Auto Ahorros Gastos - Recibir fondos Lightning Actividad Mostrar todo Aún no hay actividad diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index fbe60802f5..3f1f385453 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -101,27 +101,16 @@ Utiliser un autre portefeuille Transfert depuis le portefeuille HW Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille. - Montant - Votre solde passe vers Spark via Lightning, le moyen le moins cher de le garder dans Dépenses. Les frais de routage ci-dessous sont le maximum que vous payez. - Passer à\n<accent>Spark</accent> - Une partie de votre solde est maintenant sur Spark. Déplacez le reste de la même façon, puis fermez la connexion vidée. - Votre solde est maintenant sur Spark. Fermez la connexion vidée pour rendre sa réserve à l\'épargne. Passé à\n<accent>Spark</accent> Vos connexions Lightning n\'ont plus de solde à déplacer. Spark n\'est pas encore prêt à recevoir. Réessayez dans un instant. Impossible de\n<accent>déplacer</accent> Une erreur s\'est produite lors de la préparation du transfert. Réessayez. - Frais de routage Le paiement est en route et apparaîtra dans Spark une fois réglé. En cas d\'échec, le montant reste dans votre connexion. Passage à\n<accent>Spark</accent> - Blocktank ferme ses connexions Lightning. Déplacez dès maintenant votre solde vers Spark : c\'est l\'option la moins chère, et il reste dans Dépenses. - Votre connexion\n<accent>se ferme</accent> Déplacer la moitié - Déplacer maintenant Déplacer le reste Passer à Spark - Recherche d\'une route et de ses frais… - Glissez pour déplacer Fermez plutôt la connexion pour rendre le solde à l\'épargne. Vous pouvez le déplacer en plusieurs parties plus petites. %1$s est trop élevé pour être acheminé vers Spark en un seul paiement. @@ -1233,9 +1222,6 @@ Le montant minimum pour cette facture est de ₿ {amount}. Pair déconnecté. Erreur de démarrage de Lightning - Recevoir des fonds Lightning - Profitez de transactions instantanées et peu coûteuses avec vos amis, votre famille et les commerçants. - Recevoir sur le <accent>solde dépenses</accent> Afficher les détails Auto Épargne diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 71e80c3c6b..e36bf9a472 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -172,27 +172,16 @@ È utilizzabile? Saldi Lightning Altezza Archivio Monitor Canali - Importo - Il tuo saldo passa a Spark tramite Lightning, il modo con le commissioni più basse per tenerlo nel conto Spesa. La commissione di instradamento qui sotto è il massimo che paghi. - Sposta su\n<accent>Spark</accent> - Una parte del tuo saldo è ora su Spark. Sposta il resto allo stesso modo, poi chiudi la connessione svuotata. - Il tuo saldo è ora su Spark. Chiudi la connessione svuotata per restituire la sua riserva ai Risparmi. Spostato su\n<accent>Spark</accent> Le tue connessioni Lightning non hanno più saldo da spostare. Spark non è ancora pronto a ricevere. Riprova tra un momento. Impossibile\n<accent>spostare</accent> Qualcosa è andato storto durante la preparazione dello spostamento. Riprova. - Commissione di instradamento Il pagamento è in corso e comparirà su Spark una volta completato. Se fallisce, l\'importo resta nella tua connessione. Spostamento su\n<accent>Spark</accent> - Blocktank sta chiudendo le sue connessioni Lightning. Sposta subito il tuo saldo su Spark: è l\'opzione con le commissioni più basse e resta nel conto Spesa. - La tua connessione\n<accent>si sta chiudendo</accent> Sposta Metà - Sposta Ora Sposta Il Resto Sposta Su Spark - Ricerca di un percorso e della sua commissione… - Swipe Per Spostare Chiudi invece la connessione per restituire il saldo ai Risparmi. Puoi spostarlo in parti più piccole. %1$s è troppo grande per essere instradato su Spark in un solo pagamento. @@ -1131,14 +1120,11 @@ Invio della ricevuta Ricevuta inviata Ricevi - Ricevi fondi Lightning Ricevi Bitcoin Bitcoin invoice Fattura copiata negli appunti Lightning invoice Nota opzionale per chi paga - Goditi transazioni istantanee ed economiche con amici, familiari ed esercenti. - Ricevi sul <accent>conto di spesa</accent> Mostra Dettagli Visualizza QR Code Modifica Fattura diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index f94d19ffed..4f782beff5 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -171,27 +171,16 @@ Is bruikbaar Lightning-saldi Kanaalmonitor archiveringshoogte - Bedrag - Je saldo gaat via Lightning naar Spark, de goedkoopste manier om het in je bestedingssaldo te houden. De routeringskosten hieronder zijn het maximum dat je betaalt. - Verplaatsen naar\n<accent>Spark</accent> - Een deel van je saldo staat nu op Spark. Verplaats de rest op dezelfde manier en sluit daarna de lege verbinding. - Je saldo staat nu op Spark. Sluit de lege verbinding om de reserve terug te zetten naar spaargeld. Verplaatst naar\n<accent>Spark</accent> Je Lightning-verbindingen hebben geen saldo meer om te verplaatsen. Spark is nog niet klaar om te ontvangen. Probeer het zo opnieuw. Verplaatsen\n<accent>mislukt</accent> Er ging iets mis bij het voorbereiden van de verplaatsing. Probeer opnieuw. - Routeringskosten De betaling is onderweg en verschijnt in Spark zodra ze is afgerond. Als ze mislukt, blijft het bedrag in je verbinding. Verplaatsen naar\n<accent>Spark</accent> - Blocktank sluit zijn Lightning-verbindingen. Verplaats je saldo nu naar Spark: dat is de goedkoopste optie en het blijft in je bestedingssaldo. - Je verbinding\n<accent>wordt gesloten</accent> Helft verplaatsen - Nu verplaatsen Rest verplaatsen Verplaatsen naar Spark - Route en kosten zoeken… - Veeg om te verplaatsen Sluit in plaats daarvan de verbinding om het saldo terug te zetten naar spaargeld. Je kunt het in kleinere delen verplaatsen. %1$s is te groot om in één betaling naar Spark te routeren. @@ -1126,14 +1115,11 @@ Ontvangstbewijs verzenden Ontvangstbewijs verzonden Ontvangen - Lightning-geld ontvangen Bitcoin ontvangen Bitcoin-factuur Factuur gekopieerd naar klembord Lightning-factuur Optionele notitie voor betaler - Geniet van directe en goedkope transacties met vrienden, familie en winkeliers. - Ontvangen op <accent>bestedingssaldo</accent> Details tonen QR-code tonen Factuur bewerken diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ec7b060058..a6a721ca75 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -103,27 +103,16 @@ Użyj innego portfela Prześlij z portfela HW Najłatwiejszą opcją jest użycie oszczędności Bitkit lub wysłanie bitcoinów z innego portfela. - Kwota - Twoje saldo przechodzi do Spark przez Lightning, najtańszym sposobem na zachowanie go w Wydatkach. Opłata za routing poniżej to maksimum, jakie zapłacisz. - Przenieś do\n<accent>Spark</accent> - Część Twojego salda jest już w Spark. Przenieś resztę w ten sam sposób, a potem zamknij opróżnione połączenie. - Twoje saldo jest już w Spark. Zamknij opróżnione połączenie, aby zwrócić jego rezerwę do Oszczędności. Przeniesiono do\n<accent>Spark</accent> Twoje połączenia Lightning nie mają już salda do przeniesienia. Spark nie jest jeszcze gotowy do odbioru. Spróbuj ponownie za chwilę. Nie udało się\n<accent>przenieść</accent> Coś poszło nie tak podczas przygotowywania przeniesienia. Spróbuj ponownie. - Opłata za routing Płatność jest w drodze i pojawi się w Spark po rozliczeniu. Jeśli się nie powiedzie, kwota pozostanie w Twoim połączeniu. Przenoszenie do\n<accent>Spark</accent> - Blocktank zamyka swoje połączenia Lightning. Przenieś teraz saldo do Spark: to najtańsza opcja i środki pozostają w Wydatkach. - Twoje połączenie\n<accent>się zamyka</accent> Przenieś połowę - Przenieś teraz Przenieś resztę Przenieś do Spark - Szukanie trasy i opłaty… - Przesuń, aby przenieść Zamiast tego zamknij połączenie, aby zwrócić saldo do Oszczędności. Możesz je przenieść w mniejszych częściach. Kwota %1$s jest zbyt duża, aby przesłać ją do Spark jedną płatnością. @@ -1239,9 +1228,6 @@ Minimalna kwota dla tej faktury wynosi ₿ {amount}. Węzeł rozłączony. Błąd uruchamiania Lightning - Odbierz środki Lightning - Ciesz się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. - Odbierz na <accent>saldo wydatków</accent> Pokaż szczegóły Auto Oszczędności diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 6dff2afc45..2187c0c522 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -175,27 +175,16 @@ É utilizável Saldos Lightning Altura de Arquivamento do Monitor de Canal - Valor - Seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. - Mover para a\n<accent>Spark</accent> - Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. - Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à poupança. Movido para a\n<accent>Spark</accent> Suas conexões Lightning não têm mais saldo para mover. A Spark ainda não está pronta para receber. Tente novamente em instantes. Não foi possível\n<accent>mover</accent> Algo deu errado ao preparar a movimentação. Tente novamente. - Taxa de roteamento O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o valor fica na sua conexão. Movendo para a\n<accent>Spark</accent> - A Blocktank está fechando as suas conexões Lightning. Mova já seu saldo para a Spark: é a opção mais barata e fica nos Gastos. - Sua conexão\n<accent>está fechando</accent> Mover metade - Mover agora Mover o restante Mover para a Spark - Buscando rota e taxa… - Deslizar Para Mover Em vez disso, feche a conexão para devolver o saldo à poupança. Você pode movê-lo em partes menores. %1$s é grande demais para ser roteado para a Spark num único pagamento. @@ -1135,14 +1124,11 @@ Enviando recibo Recibo enviado Receber - Receber fundos Lightning Receber Bitcoin Invoice Bitcoin Invoice copiado para a área de transferência. Invoice Lightning Comentário opcional para o pagador - Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. - Receba no <accent>saldo de gastos</accent> Mostrar Detalhes Mostrar código QR Editar Invoice diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 96468c81c9..4c0372c62e 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -98,27 +98,16 @@ Transferir de Outra Carteira Transferir da carteira HW A forma mais fácil é usar as suas poupanças Bitkit ou enviar bitcoin de uma carteira diferente. - Montante - O seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. - Mover para a\n<accent>Spark</accent> - Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. - O seu saldo já está na Spark. Feche a conexão esvaziada para devolver a sua reserva à poupança. Movido para a\n<accent>Spark</accent> As suas conexões Lightning já não têm saldo para mover. A Spark ainda não está pronta para receber. Tente novamente dentro de instantes. Não foi possível\n<accent>mover</accent> Algo correu mal ao preparar a movimentação. Tente novamente. - Taxa de roteamento O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o montante fica na sua conexão. A mover para a\n<accent>Spark</accent> - A Blocktank está a fechar as suas conexões Lightning. Mova já o seu saldo para a Spark: é a opção mais barata e fica nos Gastos. - A sua conexão\n<accent>está a fechar</accent> Mover metade - Mover agora Mover o resto Mover para a Spark - A procurar rota e taxa… - Deslizar Para Mover Em vez disso, feche a conexão para devolver o saldo à poupança. Pode movê-lo em partes mais pequenas. %1$s é demasiado grande para ser encaminhado para a Spark num único pagamento. @@ -1083,13 +1072,10 @@ Valor muito baixo O valor mínimo para este invoice é de ₿ {amount}. Erro de inicialização da Lightning - Receber fundos Lightning Auto Poupança Gastos Mostrar Detalhes - Receba no <accent>saldo de gastos</accent> - Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. Transação Substituída Sua transação foi substituída por um aumento de taxa Transação Recebida Substituída diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e73eeec7b1..0c58fab1cb 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -183,27 +183,16 @@ Можно Использовать Балансы Lightning Архивная высота мониторинга канала - Сумма - Ваш баланс переходит в Spark через Lightning — это самый дешёвый способ сохранить его в расходах. Комиссия за маршрутизацию ниже — максимум, который вы заплатите. - Перенос в\n<accent>Spark</accent> - Часть вашего баланса уже в Spark. Перенесите остаток так же, затем закройте опустевшее соединение. - Ваш баланс уже в Spark. Закройте опустевшее соединение, чтобы вернуть его резерв в сбережения. Перенесено в\n<accent>Spark</accent> В ваших Lightning-соединениях не осталось баланса для переноса. Spark пока не готов к получению. Попробуйте ещё раз чуть позже. Не удалось\n<accent>перенести</accent> Что-то пошло не так при подготовке переноса. Попробуйте ещё раз. - Комиссия за маршрутизацию Платёж в пути и появится в Spark после завершения. Если он не пройдёт, сумма останется в вашем соединении. Перенос в\n<accent>Spark</accent> - Blocktank закрывает свои Lightning-соединения. Перенесите баланс в Spark сейчас: это самый дешёвый вариант, и средства остаются в расходах. - Ваше соединение\n<accent>закрывается</accent> Перенести половину - Перенести сейчас Перенести остаток Перенос в Spark - Поиск маршрута и комиссии… - Проведите для переноса Вместо этого закройте соединение, чтобы вернуть баланс в сбережения. Вы можете перенести его меньшими частями. %1$s слишком много для маршрутизации в Spark одним платежом. @@ -1148,14 +1137,11 @@ Отправка квитанции Квитанция отправлена Получить - Получить Lightning средства Получить Биткоин Биткоин инвойс Инвойс скопирован в буфер обмена Лайтнинг инвойс Опциональная заметка для плательщика - Наслаждайтесь мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. - Получить на <accent>баланс расходов</accent> Показать детали Показать QR-код Редактировать Инвойс diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e2368b2cb9..9a22eee279 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -321,31 +321,29 @@ Is Usable Lightning Balances Channel Monitor Archival Height - Amount - Your balance moves to Spark over Lightning, the lowest-fee way to keep it in Spending. The routing fee below is the most you pay. - Move to\n<accent>Spark</accent> - Part of your balance is on Spark now. Move the rest the same way, then close the emptied connection. - Your balance is on Spark now. Close the emptied connection to return its reserve to Savings. Moved to\n<accent>Spark</accent> Your Lightning connections have no balance left to move. Spark is not ready to receive yet. Try again in a moment. Could not\n<accent>move</accent> Something went wrong while preparing the move. Try again. - Routing fee The payment is on its way and shows in Spark once it settles. If it fails, the amount stays in your connection. Moving to\n<accent>Spark</accent> - Blocktank is closing its Lightning connections. Move your balance to Spark now: it is the lowest-fee option, and it stays in Spending. - Your connection\n<accent>is closing</accent> Move Half - Move Now Move Rest Move To Spark - Finding a route and its fee… - Swipe To Move Close the connection instead to return the balance to Savings. You can move it in smaller parts. %1$s is too large to route to Spark in one payment. Amount\n<accent>too large</accent> + Update + Update fee: %1$s + Update Spending Balance + Bitkit is switching Lightning providers. Update your spending balance to continue making instant, cheap payments. + Update\n<accent>Spending Balance</accent> + Spending Balance Updated + Part of your spending balance is on Spark now. Move the rest the same way. + Your spending balance has been successfully migrated to Spark, Bitkit’s new Lightning service provider. + Spending\nBalance <accent>Updated</accent> Next Outbound HTLC Limit Next Outbound HTLC Min Before you can transfer funds from your savings balance, you need to send bitcoin to your Bitkit wallet. @@ -1683,14 +1681,11 @@ Sending receipt Receipt sent Receive - Receive Lightning Funds Receive Bitcoin Bitcoin invoice Invoice copied to clipboard Lightning invoice Optional note to payer - Enjoy instant and cheap transactions with friends, family, and merchants. - Receive on <accent>spending balance</accent> Show Details QR Code Edit Invoice @@ -1774,9 +1769,9 @@ Bitcoin Sent Route Pubky Swaps · %1$s - Spark Swipe To Pay To + Update fee Yes, Send <accent>Send\nbitcoin</accent>\nto your\nspending balance Spending diff --git a/app/src/test/java/to/bitkit/models/ReceiveLiquidityDecisionTest.kt b/app/src/test/java/to/bitkit/models/ReceiveLiquidityDecisionTest.kt index 0961142888..e4f1899d67 100644 --- a/app/src/test/java/to/bitkit/models/ReceiveLiquidityDecisionTest.kt +++ b/app/src/test/java/to/bitkit/models/ReceiveLiquidityDecisionTest.kt @@ -1,18 +1,11 @@ package to.bitkit.models import org.junit.Test -import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class ReceiveLiquidityDecisionTest { - private val defaultAdditionalLiquidityParams = ReceiveAdditionalLiquidityParams( - source = ReceiveLiquiditySource.SPENDING, - invoiceAmountSats = 10_000u, - inboundCapacitySats = 1_000u, - ) - @Test fun `lightning invoice requires ready channel`() { assertFalse( @@ -61,37 +54,4 @@ class ReceiveLiquidityDecisionTest { ) ) } - - @Test - fun `zero inbound needs no additional liquidity`() { - assertEquals( - ReceiveAdditionalLiquidityAction.None, - additionalLiquidityAction( - defaultAdditionalLiquidityParams.copy(inboundCapacitySats = 0u) - ) - ) - } - - @Test - fun `savings and auto edits need no additional liquidity`() { - listOf(ReceiveLiquiditySource.SAVINGS, ReceiveLiquiditySource.AUTO).forEach { - assertEquals( - ReceiveAdditionalLiquidityAction.None, - additionalLiquidityAction( - defaultAdditionalLiquidityParams.copy(source = it) - ) - ) - } - } - - @Test - fun `spending above inbound routes to transfer unavailable`() { - assertEquals( - ReceiveAdditionalLiquidityAction.TransferUnavailable, - additionalLiquidityAction(defaultAdditionalLiquidityParams) - ) - } - - private fun additionalLiquidityAction(params: ReceiveAdditionalLiquidityParams) = - ReceiveLiquidityDecision.additionalLiquidityAction(params) } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index bb2f4f51bb..97fac46e76 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -24,9 +24,11 @@ import org.mockito.kotlin.whenever import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.ext.createChannelDetails +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.LdkError +import kotlin.random.Random import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNull @@ -302,4 +304,150 @@ class MoveToSparkRepoTest : BaseUnitTest() { status = status, latestUpdateTimestamp = 0uL, ) + + @Test + fun `combined sendable is what Spark can send once the channels' balance less the fee guess moved`() { + val channels = listOf(channel("c1", 100_000uL)) + + val combined = MoveToSparkMath.combinedSendableSats( + channels, + SparkState(isReady = true, balanceSats = 50_000uL) + ) + + // The fee guess on 100 000 sats is 500, so 99 498 move; Spark keeps 0.25% of 149 498. + assertEquals(149_125uL, combined) + } + + @Test + fun `combined sendable is zero without a usable Spark or a balance worth moving`() { + val channels = listOf(channel("c1", 100_000uL)) + assertEquals(0uL, MoveToSparkMath.combinedSendableSats(channels, SparkState(isReady = false))) + assertEquals(0uL, MoveToSparkMath.combinedSendableSats(channels, SparkState(isReady = true, isExiting = true))) + assertEquals(0uL, MoveToSparkMath.combinedSendableSats(emptyList(), SparkState(isReady = true))) + } + + @Test + fun `a payment needs the update only above both rails and within the combined balance`() { + val channels = listOf(channel("c1", 100_000uL)) + val spark = SparkState(isReady = true, balanceSats = 50_000uL) + + assertTrue(!MoveToSparkMath.needsUpdateToSend(100_000uL, channels, spark)) + assertTrue(!MoveToSparkMath.needsUpdateToSend(spark.sendableSats, channels, spark)) + assertTrue(MoveToSparkMath.needsUpdateToSend(100_001uL, channels, spark)) + assertTrue(MoveToSparkMath.needsUpdateToSend(149_125uL, channels, spark)) + assertTrue(!MoveToSparkMath.needsUpdateToSend(149_126uL, channels, spark)) + } + + @Test + fun `max send counts the combined balance`() { + val channels = listOf(channel("c1", 100_000uL)) + val spark = SparkState(isReady = true, balanceSats = 50_000uL) + + assertEquals(149_125uL, MoveToSparkMath.maxSendSats(channels, spark)) + assertEquals(100_000uL, MoveToSparkMath.maxSendSats(channels, SparkState(isReady = false))) + } + + @Test + fun `emptied channels are the open ones a move took from the minimum to below it`() { + val before = listOf( + channel("emptied", 50_000uL), + channel("small", 500uL), + channel("kept", 20_000uL), + ) + val after = listOf( + channel("emptied", 0uL), + channel("small", 0uL), + channel("kept", 10_000uL), + channel("new", 0uL), + channel("emptied_pending", 0uL).copy(isChannelReady = false), + ) + + assertEquals(listOf("emptied"), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) + } + + @Test + fun `combined amounts keep their invariants for generated balances`() { + val random = Random(seed = 64) + repeat(1_000) { + val channels = List(random.nextInt(0, 4)) { index -> + channel("c$index", random.nextLong(0L, 2_000_000L).toULong()) + } + val spark = SparkState( + isReady = random.nextBoolean(), + isExiting = random.nextInt(10) == 0, + balanceSats = random.nextLong(0L, 2_000_000L).toULong(), + ) + val movable = MoveToSparkMath.movableSats(channels) + val combined = MoveToSparkMath.combinedSendableSats(channels, spark) + val max = MoveToSparkMath.maxSendSats(channels, spark) + + assertTrue(combined <= SparkFees.sendableSats(spark.balanceSats + movable), "combined '$combined'") + assertTrue(max >= movable && max >= spark.sendableSats && max >= combined, "max '$max'") + if (MoveToSparkMath.canMove(channels, spark)) assertTrue(combined >= spark.sendableSats) + val amount = random.nextLong(1L, 4_000_000L).toULong() + if (MoveToSparkMath.needsUpdateToSend(amount, channels, spark)) { + assertTrue(amount > movable && amount <= combined && amount <= max, "amount '$amount'") + } + } + } + + @Test + fun `update to send moves the balance, then waits until Spark can pay`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + whenever(sparkRepo.canSend(60_000uL)).thenReturn(false, false, true) + whenever(sparkRepo.refreshState()).thenReturn(Result.success(Unit)) + val updating = async { sut.updateToSend(quote, 60_000uL) } + + nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL), updating.await().getOrThrow()) + verify(sparkRepo).refreshState() + } + + @Test + fun `update to send fails as unsettled while the move is in flight`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + + var moved: MoveToSparkOutcome? = null + + val result = sut.updateToSend(quote, 60_000uL) { moved = it } + + assertIs(result.exceptionOrNull()) + assertIs(moved) + verify(sparkRepo, never()).refreshState() + } + + @Test + fun `update to send reports a settled move even when Spark never shows the balance`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + whenever(sparkRepo.canSend(60_000uL)).thenReturn(false) + whenever(sparkRepo.refreshState()).thenReturn(Result.success(Unit)) + var moved: MoveToSparkOutcome? = null + val updating = async { sut.updateToSend(quote, 60_000uL) { moved = it } } + + nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) + + assertIs(updating.await().exceptionOrNull()) + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL), moved) + } + + @Test + fun `the fee after an update falls back to Spark's service fee when Spark cannot price it yet`() = test { + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + + assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) + } + + private fun channel(id: String, sendableSats: ULong) = createChannelDetails().copy( + channelId = id, + isUsable = true, + isChannelReady = true, + nextOutboundHtlcLimitMsat = sendableSats * 1000uL, + ) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index 4c3789c5fb..ee33452c24 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -1648,16 +1648,6 @@ class WalletRepoTest : BaseUnitTest() { } } - @Test - fun `inboundLiquiditySats should count ready channels`() = test { - val mixedChannels = (channels + readyButNotUsableChannels).toImmutableList() - whenever(lightningRepo.lightningState) - .thenReturn(MutableStateFlow(LightningState(channels = mixedChannels))) - whenever(lightningRepo.getChannels()).thenReturn(mixedChannels) - - assertEquals(2_000uL, sut.inboundLiquiditySats()) - } - @Test fun `updateBip21Invoice should build correct BIP21 URL`() = test { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(onchainAddress = ADDRESS))) diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt deleted file mode 100644 index b6a92f02b0..0000000000 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt +++ /dev/null @@ -1,98 +0,0 @@ -package to.bitkit.ui.screens.wallets.receive - -import app.cash.turbine.test -import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.mock -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever -import to.bitkit.models.ReceiveAdditionalLiquidityAction -import to.bitkit.models.ReceiveLiquiditySource -import to.bitkit.repositories.WalletRepo -import to.bitkit.test.BaseUnitTest -import to.bitkit.ui.screens.wallets.receive.EditInvoiceVM.EditInvoiceScreenEffects -import kotlin.test.assertEquals - -class EditInvoiceVMTest : BaseUnitTest() { - - private lateinit var sut: EditInvoiceVM - private val walletRepo: WalletRepo = mock() - - @Before - fun setUp() = runBlocking { - whenever(walletRepo.inboundLiquiditySats()).thenReturn(1_000u) - sut = EditInvoiceVM(walletRepo) - } - - @Test - fun `onClickContinue should emit none for auto when amount exceeds inbound`() = test { - sut.editInvoiceEffect.test { - sut.onClickContinue( - source = ReceiveLiquiditySource.AUTO, - amountSats = 10_000u, - ) - - assertEquals( - EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None), - awaitItem(), - ) - cancelAndIgnoreRemainingEvents() - } - verify(walletRepo, times(1)).inboundLiquiditySats() - } - - @Test - fun `onClickContinue should emit none for spending above inbound when Spark can receive`() = test { - whenever(walletRepo.canReceiveWithSpark()).thenReturn(true) - - sut.editInvoiceEffect.test { - sut.onClickContinue( - source = ReceiveLiquiditySource.SPENDING, - amountSats = 10_000u, - ) - - assertEquals( - EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None), - awaitItem(), - ) - cancelAndIgnoreRemainingEvents() - } - verify(walletRepo, times(0)).inboundLiquiditySats() - } - - @Test - fun `onClickContinue should emit transfer unavailable for spending above inbound`() = test { - sut.editInvoiceEffect.test { - sut.onClickContinue( - source = ReceiveLiquiditySource.SPENDING, - amountSats = 10_000u, - ) - - assertEquals( - EditInvoiceScreenEffects.ApplyReceiveLiquidityAction( - ReceiveAdditionalLiquidityAction.TransferUnavailable - ), - awaitItem(), - ) - cancelAndIgnoreRemainingEvents() - } - } - - @Test - fun `onClickContinue should emit none for spending within inbound`() = test { - sut.editInvoiceEffect.test { - sut.onClickContinue( - source = ReceiveLiquiditySource.SPENDING, - amountSats = 500u, - ) - - assertEquals( - EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None), - awaitItem(), - ) - cancelAndIgnoreRemainingEvents() - } - } -} diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt index e7d74e0549..e114ec4130 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt @@ -1,27 +1,16 @@ package to.bitkit.ui.screens.wallets.receive -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.unit.height -import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config -import org.robolectric.shadows.ShadowSystemClock import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.LightningState import to.bitkit.repositories.WalletState import to.bitkit.ui.theme.AppThemeSurface -import kotlin.test.assertEquals -import kotlin.time.Duration.Companion.seconds -import kotlin.time.toJavaDuration @Config(sdk = [34]) @RunWith(RobolectricTestRunner::class) @@ -30,49 +19,34 @@ class ReceiveQrScreenTest { val composeRule = createComposeRule() @Test - fun `the spending onboarding shows while the node starts with its button disabled`() { - setContent(NodeLifecycleState.Starting) + fun `without a way to receive over Lightning the spending and auto tabs are hidden`() { + setContent(canReceiveWithSpark = false) - composeRule.onNodeWithText("Enjoy instant and cheap transactions", substring = true).assertExists() - composeRule.onNodeWithText("Receive Lightning Funds").assertExists() - composeRule.onNodeWithTag("ShowDetails").assertIsNotEnabled() + composeRule.onNodeWithTag("Tab-savings").assertExists() + composeRule.onNodeWithTag("Tab-spending").assertDoesNotExist() + composeRule.onNodeWithTag("Tab-auto").assertDoesNotExist() } @Test - fun `the spending onboarding button is enabled once the node runs`() { - setContent(NodeLifecycleState.Running) + fun `a usable spark wallet shows the spending and auto tabs`() { + setContent(canReceiveWithSpark = true) - composeRule.onNodeWithTag("ShowDetails").assertIsEnabled() + composeRule.onNodeWithTag("Tab-spending").assertExists() + composeRule.onNodeWithTag("Tab-auto").assertExists() } - @Config(sdk = [34], qualifiers = "w448dp-h997dp") - @Test - fun `the spending onboarding card takes figma's share of the screen height and gap`() { - setContent(NodeLifecycleState.Running) - - val card = composeRule.onNodeWithTag("ReceiveSpendingCard").getUnclippedBoundsInRoot() - val button = composeRule.onNodeWithTag("ShowDetails").getUnclippedBoundsInRoot() - - assertEquals(997f * 343f / 812f, card.height.value, 0.5f) - assertEquals(448f - 2 * 16f, card.width.value, 0.5f) - assertEquals(997f * 122f / 812f, (button.top - card.bottom).value, 0.5f) - } - - /** Opens the Spending tab, as the screen starts on Savings while Lightning can't receive. */ - private fun setContent(nodeState: NodeLifecycleState) { + private fun setContent(canReceiveWithSpark: Boolean) { composeRule.setContent { AppThemeSurface { ReceiveQrScreen( walletState = WalletState(), - lightningState = LightningState(nodeLifecycleState = nodeState), - onClickReceiveCjit = {}, + lightningState = LightningState(nodeLifecycleState = NodeLifecycleState.Running), onClickEditInvoice = {}, initialTab = ReceiveTab.SPENDING, + canReceiveWithSpark = canReceiveWithSpark, ) } } - ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) - composeRule.onNodeWithTag("Tab-spending").performClick() composeRule.waitForIdle() } } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt index 3f24c2b268..ad9708ff07 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt @@ -73,7 +73,7 @@ class SendConfirmLnurlOnchainTest { ), ) - composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("ReviewSwapRoute").assertDoesNotExist() composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) } @@ -100,7 +100,7 @@ class SendConfirmLnurlOnchainTest { ), ) - composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("ReviewSwapRoute").assertDoesNotExist() composeRule.onNodeWithTag("CommentInput").assertDoesNotExist() composeRule.onNodeWithTag("TagsAddSend").assertExists() } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index cc870e26f8..051d30b1dd 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -5,10 +5,12 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Before import org.junit.Test +import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -22,6 +24,7 @@ import to.bitkit.repositories.MoveToSparkQuote import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.WalletRepo import to.bitkit.test.BaseUnitTest +import to.bitkit.usecases.CloseChannelUseCase import kotlin.test.assertEquals import kotlin.test.assertIs @@ -29,6 +32,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { private val moveToSparkRepo = mock() private val lightningRepo = mock() private val walletRepo = mock() + private val closeChannelUseCase = mock() private val quote = MoveToSparkQuote(invoice = "lnbcrt1spark", amountSats = 50_000uL, feeSats = 10uL) private val firstMove = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash_1", paymentId = "id_1") @@ -38,7 +42,15 @@ class MoveToSparkViewModelTest : BaseUnitTest() { private val secondMove = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash_2", paymentId = "id_2") private val firstSettled = CompletableDeferred>() private val secondSettled = CompletableDeferred>() - private val manager by lazy { MoveToSparkManager(testDispatcher, moveToSparkRepo, lightningRepo, walletRepo) } + private val manager by lazy { + MoveToSparkManager( + testDispatcher, + moveToSparkRepo, + lightningRepo, + walletRepo, + closeChannelUseCase + ) + } @Before fun setUp() { @@ -81,7 +93,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { firstSettled.complete(Result.success(moved)) - assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = "channel_1", hasRest = true), sut.uiState.value) + assertEquals(MoveToSparkUiState.Done(moved, hasRest = true), sut.uiState.value) } @Test @@ -114,7 +126,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { payment.complete(Result.success(moved)) - assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + assertEquals(MoveToSparkUiState.Done(moved), reopened.uiState.value) verify(moveToSparkRepo, times(1)).quote(anyOrNull()) } @@ -126,7 +138,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { val reopened = createViewModel() firstSettled.complete(Result.success(moved)) - assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + assertEquals(MoveToSparkUiState.Done(moved), reopened.uiState.value) } @Test @@ -163,5 +175,47 @@ class MoveToSparkViewModelTest : BaseUnitTest() { verify(moveToSparkRepo, times(2)).quote(anyOrNull()) } - private fun createViewModel() = MoveToSparkViewModel(manager) + @Test + fun `a settled move closes the channels it emptied once it moved`() = test { + lightningState.value = LightningState(channels = persistentListOf(openChannel)) + whenever(moveToSparkRepo.move(eq(quote))).thenReturn(Result.success(moved)) + + createViewModel().move() + + verify(closeChannelUseCase).closeEmptiedByMove(listOf(openChannel)) + } + + @Test + fun `an in-flight move closes nothing until it settles`() = test { + lightningState.value = LightningState(channels = persistentListOf(openChannel)) + createViewModel().move() + verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + + firstSettled.complete(Result.success(moved)) + + verify(closeChannelUseCase).closeEmptiedByMove(listOf(openChannel)) + } + + @Test + fun `a move that fails late closes nothing`() = test { + createViewModel().move() + + firstSettled.complete(Result.failure(MoveToSparkError.PaymentFailed(null))) + + verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + } + + @Test + fun `closing the modal after a settled move quotes anew on the next opening`() = test { + whenever(moveToSparkRepo.move(eq(quote))).thenReturn(Result.success(moved)) + val sut = createViewModel() + sut.move() + + sut.close() + sut.open() + + assertEquals(MoveToSparkUiState.Confirm(quote), sut.uiState.value) + } + + private fun createViewModel() = MoveToSparkViewModel(manager).also { it.open() } } diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt new file mode 100644 index 0000000000..2d3ad954ef --- /dev/null +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -0,0 +1,91 @@ +package to.bitkit.usecases + +import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.ext.amountOnClose +import to.bitkit.ext.createChannelDetails +import to.bitkit.models.TransferType +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.LightningState +import to.bitkit.repositories.TransferRepo +import to.bitkit.repositories.WalletRepo +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertTrue + +class CloseChannelUseCaseTest : BaseUnitTest() { + private val lightningRepo = mock() + private val transferRepo = mock() + private val walletRepo = mock() + private val lightningState = MutableStateFlow(LightningState()) + private val channel = channel("channel_1", 50_000uL) + private lateinit var sut: CloseChannelUseCase + + @Before + fun setUp() { + whenever(lightningRepo.lightningState).thenReturn(lightningState) + whenever { lightningRepo.closeChannel(any(), any(), anyOrNull()) }.thenReturn(Result.success(Unit)) + whenever { + transferRepo.createTransfer( + any(), + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + }.thenReturn(Result.success("transfer")) + whenever { walletRepo.syncNodeAndWallet(anyOrNull()) }.thenReturn(Result.success(Unit)) + sut = CloseChannelUseCase(testDispatcher, lightningRepo, transferRepo, walletRepo) + } + + @Test + fun `closing records the channel's transfer to Savings`() = test { + assertTrue(sut(channel).isSuccess) + + verify(transferRepo).createTransfer( + type = TransferType.COOP_CLOSE, + amountSats = channel.amountOnClose.toLong(), + channelId = "channel_1", + fundingTxId = channel.fundingTxo?.txid, + ) + } + + @Test + fun `a failed close records no transfer`() = test { + whenever(lightningRepo.closeChannel(any(), any(), anyOrNull())).thenReturn(Result.failure(Exception("peer"))) + + assertTrue(sut(channel).isFailure) + + verify(transferRepo, never()) + .createTransfer(any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a move's close takes only the channels it emptied`() = test { + val kept = channel("channel_2", 20_000uL) + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL), kept)) + + sut.closeEmptiedByMove(listOf(channel, kept)) + + verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) + verify(lightningRepo, never()).closeChannel(eq(kept), any(), anyOrNull()) + } + + private fun channel(id: String, sendableSats: ULong) = createChannelDetails().copy( + channelId = id, + isUsable = true, + isChannelReady = true, + nextOutboundHtlcLimitMsat = sendableSats * 1000uL, + ) +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 71f471fbbf..d2518e4b74 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -173,6 +173,10 @@ import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.MethodId +import to.bitkit.repositories.MoveToSparkError +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkQuote +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.NodeEventUpdate import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.OnchainSendAttemptUnreadableError @@ -262,6 +266,7 @@ import to.bitkit.ui.sheets.hardware.HardwareRoute import to.bitkit.ui.theme.TRANSITION_SCREEN_MS import to.bitkit.ui.utils.NumberPadInputHandler import to.bitkit.ui.utils.ScreenDeepLinks +import to.bitkit.usecases.CloseChannelUseCase import to.bitkit.usecases.FormatMoneyValue import to.bitkit.usecases.KeepContactPaymentsOnUseCase import to.bitkit.usecases.RefreshContactPaykitLinkUseCase @@ -313,6 +318,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val notifyChannelReadyHandler = mock() private val cacheStore = mock() private val quickPayRepo = mock() + private val moveToSparkRepo = mock { + on { canMove } doReturn emptyFlow() + onBlocking { isMovePayment(any()) } doReturn false + } + private val closeChannelUseCase = mock() private val quickPayUnhandledFailures = MutableSharedFlow(extraBufferCapacity = 8) private val transferRepo = mock() private val sparkExitRepo = mock() @@ -1045,10 +1055,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { on { type } doReturn TimedSheetType.MOVE_TO_SPARK onBlocking { shouldShow() } doReturn false }, - moveToSparkRepo = mock { - on { canMove } doReturn emptyFlow() - onBlocking { isMovePayment(any()) } doReturn false - }, + moveToSparkRepo = moveToSparkRepo, + closeChannelUseCase = closeChannelUseCase, formatMoneyValue = formatMoneyValue, widgetsRepo = widgetsRepo, wakeRepo = wakeRepo, @@ -20519,6 +20527,131 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return contexts[paymentHash] } + @Test + fun `a payment that fits only across channels and spark updates the spending balance before paying`() = test { + val bolt11 = "lnbcrt1update" + val quote = MoveToSparkQuote("lnbcrt1spark", amountSats = 50_000uL, feeSats = 12uL) + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + val moved = MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL) + whenever(moveToSparkRepo.updateToSend(eq(quote), eq(60_000uL), any())).thenReturn(Result.success(moved)) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = quote, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + inOrder(moveToSparkRepo, lightningRepo) { + verify(moveToSparkRepo).updateToSend(eq(quote), eq(60_000uL), onMove.capture()) + verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) + } + onMove.firstValue(moved) + advanceUntilIdle() + verify(closeChannelUseCase).closeEmptiedByMove(any()) + } + + @Test + fun `a failed spending balance update shows the payment error and pays nothing`() = test { + val bolt11 = "lnbcrt1updatefails" + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + } + + @Test + fun `a settled move closes the emptied channels even when the payment after it fails`() = test { + val bolt11 = "lnbcrt1movedunsettled" + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + verify(moveToSparkRepo).updateToSend(anyOrNull(), eq(60_000uL), onMove.capture()) + onMove.firstValue(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL)) + advanceUntilIdle() + verify(closeChannelUseCase).closeEmptiedByMove(any()) + } + + @Test + fun `an in-flight move closes the emptied channels once it settles`() = test { + val bolt11 = "lnbcrt1inflight" + val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + whenever(moveToSparkRepo.awaitSettled(inFlight)) + .thenReturn(Result.success(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL))) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + verify(moveToSparkRepo).updateToSend(anyOrNull(), eq(60_000uL), onMove.capture()) + onMove.firstValue(inFlight) + advanceUntilIdle() + verify(moveToSparkRepo).awaitSettled(inFlight) + verify(closeChannelUseCase).closeEmptiedByMove(any()) + } + + @Test + fun `a payment that needs the update is never sent by QuickPay`() = test { + val bolt11 = "lnbcrt1quickpayupdate" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(moveToSparkRepo.needsUpdateToSend(500uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(MoveToSparkQuote("lnbcrt1spark", 500uL, 1uL))) + whenever(moveToSparkRepo.estimateFeeAfterUpdate(bolt11, 500uL)).thenReturn(2uL) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(quickPayRepo, never()).canApply(any()) + } + @Suppress("UNCHECKED_CAST") private fun setSendState(state: SendUiState) { val field = AppViewModel::class.java.getDeclaredField("_sendUiState") diff --git a/docs/screens-map.md b/docs/screens-map.md index 7ef0a7c707..2f80fd0e6b 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -189,7 +189,6 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | - | - | | EditInvoiceScreen.kt | Send (Contact) (Lightning) › Edit invoice populated | | ReceiveQrScreen.kt | Receive Lightning Active › Receive Auto (Unified QR) | -| TransferUnavailableScreen.kt | `todo` | ## ui/screens/wallets/send @@ -316,7 +315,6 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | ChannelDetailScreen.kt | Settings > Advanced › Connection details | | CloseConnectionScreen.kt | Settings > Advanced › Close connection | | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | -| MoveToSparkScreen.kt | `todo` | | SparkDetailScreen.kt | `todo` | | SparkExitConfirmScreen.kt | `todo` | | SparkExitFeeBumpScreen.kt | `todo` | @@ -369,3 +367,7 @@ Amount entry stays in dollars with a BTC equivalent; QR and shared payment amoun `UsdtIntroSheet.kt` implements [New: USDT](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=50228-146387). `SettingsScreen.kt` includes the [USDT (Tether) switch](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=48063-277709). Both are covered by `journeys/usdt-opt-in.xml`. `UsdtNetworkPicker.kt` shares the receive network rows with the [send network sheet](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=50231-146880); all available routes remain scrollable. + +### Update spending balance + +`MoveToSparkSheet.kt` implements [Modal Update Spending Balance](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=52052-404808) and [Spending Balance Updated](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=52052-409823) in Wallet Lightning - Transfer to Spending Balance. Its in-flight, move-rest, too-large and failed states have no frame and keep their earlier copy in the same sheet. Covered by `journeys/transfer/move-to-spark.xml`; the update before a payment is covered by `journeys/send/update-spending-balance-payment.xml`. diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml index 814c9a75d0..21f0b38254 100644 --- a/journeys/paykit-spark-route.xml +++ b/journeys/paykit-spark-route.xml @@ -19,7 +19,7 @@ Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source Enter 20000 and tap Continue (tag "ContinueAmount") Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") - Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Spark" + Verify FROM is SPENDING, TO is the contact, and no ROUTE row (tag "ReviewSwapRoute") shows Swipe to pay (tag "GRAB") Verify the Bitcoin Sent screen (tag "SendSuccess") shows 20 000 Verify Lightspark's regtest mempool shows the withdrawal transaction paying exactly 20 000 sats to the fixture-issuer's address diff --git a/journeys/receive/receive-tabs-wraparound.xml b/journeys/receive/receive-tabs-wraparound.xml index 0f9067e707..af32e9f925 100644 --- a/journeys/receive/receive-tabs-wraparound.xml +++ b/journeys/receive/receive-tabs-wraparound.xml @@ -6,9 +6,9 @@ the Receive sheet, also when it is released above the sheet, and a tap on a QR still copies it. Precondition: onboarded dev wallet with USDT enabled (introductory sheet or Settings, General, - Payments), no open Spending channel and no hardware wallet paired, so the - tabs are Savings, Spending and USDT; a usable channel adds the Auto tab. Start on the wallet home - screen. The USDT address loads without funding; wait for the QR before swiping. + Payments), a usable Spark wallet (or a usable channel) and no hardware wallet paired, so the + tabs are Savings, Auto, Spending and USDT; without a way to receive over Lightning the Auto and + Spending tabs are hidden. Start on the wallet home screen with the Lightning node running. The USDT address loads without funding; wait for the QR before swiping. Swipe with `adb shell input swipe` across the middle of the QR, about 60% of its width, in 300 ms (`adb shell input swipe 220 1176 860 1176 300` to the right on a 1080 px wide screen). A @@ -18,21 +18,20 @@ (`adb shell input swipe 150 1176 900 1176 1200`); the USDT QR takes the 300 ms swipe. - Tap Receive (testTag "Receive") and verify the Savings tab (testTag "Tab-savings") is selected + Tap Receive (testTag "Receive"), verify the Auto tab (testTag "Tab-auto") is selected, then tap the Savings tab (testTag "Tab-savings") and verify it is selected Swipe right across the Savings QR; verify the USDT tab (testTag "Tab-usdt") is selected and wait until the USDT QR is visible Swipe left across the USDT QR; verify the Savings tab is selected Start a screen recording, tap the USDT tab (testTag "Tab-usdt") and wait until the USDT QR is visible, then swipe left across the USDT QR; verify the Savings tab is selected and the recording goes straight from the USDT QR to the Savings QR, with no Auto or Spending QR and no second USDT screen in between Start a screen recording, tap the USDT tab and wait until the USDT QR is visible, then tap the Savings tab; verify the Savings tab is selected and the recording shows the same direct change from USDT to Savings - Swipe left across the Savings QR in 1200 ms (`adb shell input swipe 900 1176 150 1176 1200`); verify the Spending tab (testTag "Tab-spending") is selected - Swipe left across the Spending content in 1200 ms; verify the USDT tab is selected and wait until its QR is visible + Swipe left across the Savings QR in 1200 ms (`adb shell input swipe 900 1176 150 1176 1200`); verify the Auto tab is selected + Swipe left across the Auto QR in 1200 ms; verify the Spending tab (testTag "Tab-spending") is selected + Swipe left across the Spending QR in 1200 ms; verify the USDT tab is selected and wait until its QR is visible Swipe left from the top right of the USDT QR to above the sheet (`adb shell input swipe 950 720 100 200 300`); verify the Receive sheet is still open and the Savings tab is selected Swipe right from the top left of the Savings QR to above the sheet (`adb shell input swipe 100 720 950 200 1200`); verify the Receive sheet is still open and the USDT tab is selected Swipe left across the USDT QR, then tap the Savings QR once; verify the "copied" tooltip appears - Close Receive, turn USDT off (Settings, General, Payments), return to the wallet home screen and tap Receive; verify the Savings tab is selected and only Savings and Spending show - Swipe right across the Savings QR; verify the Spending tab is selected - Swipe right across the Spending content; verify the Savings tab is selected - Swipe left across the Savings QR; verify the Spending tab is selected - Swipe left across the Spending content; verify the Savings tab is selected - Swipe left across the Savings QR; verify the Spending tab is selected + Close Receive, turn USDT off (Settings, General, Payments), return to the wallet home screen and tap Receive; verify the Auto tab is selected and only Savings, Auto and Spending show + Tap the Savings tab, then swipe right across the Savings QR in 1200 ms; verify the Spending tab is selected + Swipe left across the Spending QR in 1200 ms; verify the Savings tab is selected + Swipe left across the Savings QR in 1200 ms; verify the Auto tab is selected diff --git a/journeys/receive/usdt-receive-swipe-tabs.xml b/journeys/receive/usdt-receive-swipe-tabs.xml index dc465a5883..338d96ddac 100644 --- a/journeys/receive/usdt-receive-swipe-tabs.xml +++ b/journeys/receive/usdt-receive-swipe-tabs.xml @@ -14,14 +14,15 @@ screenshot taken right after the swipe. Swipe with `adb shell input swipe` across the middle of the QR, about 60% of its width, in 300 ms. Back from Spending to USDT goes through the tab pager, which snaps back from a 300 ms synthetic swipe on the emulator; a 600 ms swipe moves it. - On a wallet without a Lightning channel, Spending shows its setup view instead of a QR. + The Spending tab shows only while the wallet can receive over Lightning (a usable Spark wallet or channel), so + this journey needs one; without it the tab before USDT is Savings. Tap Receive (testTag "Receive") Tap the USDT tab (testTag "Tab-usdt") and wait until the USDT QR is visible Swipe right across the QR and take a screenshot right away - Verify the Spending tab (testTag "Tab-spending") is selected, the Lightning receive content or the Spending setup is shown, and the screenshot shows no "copied" tooltip - Swipe left across the middle of the Spending content, whether it shows a Lightning QR or the Spending setup, in 600 ms (`adb shell input swipe 900 1200 150 1200 600`); verify the USDT tab is selected and wait until its QR is visible + Verify the Spending tab (testTag "Tab-spending") is selected, the Lightning receive QR is shown, and the screenshot shows no "copied" tooltip + Swipe left across the middle of the Spending QR in 600 ms (`adb shell input swipe 900 1200 150 1200 600`); verify the USDT tab is selected and wait until its QR is visible Tap the USDT QR once and verify the "copied" tooltip appears Wait until the tooltip is gone, swipe left across the USDT QR and take a screenshot right away; verify the Savings tab (testTag "Tab-savings") is selected and the screenshot shows no "copied" tooltip diff --git a/journeys/send/update-spending-balance-payment.xml b/journeys/send/update-spending-balance-payment.xml new file mode 100644 index 0000000000..79cc555b97 --- /dev/null +++ b/journeys/send/update-spending-balance-payment.xml @@ -0,0 +1,23 @@ + + + Verifies that a Lightning payment that fits neither the LDK channel nor Spark alone, but fits both combined, runs + as one payment: the confirm screen shows "Update fee" (testTag "ReviewUpdateFee") next to the payment's own fee, + and one swipe first moves the channel's balance to Spark, then pays the invoice from Spark. The move shows in + Activity as a "Move to Spark" row, and the emptied channel closes in the background. If the payment fails after the + move, the funds stay in Spark and the usual payment error shows. QuickPay never sends such a payment; it always + opens the confirm screen. + + Precondition: dev build pointed at a local Spark regtest (spark-sdk regtest/local), QuickPay off, a wallet with an + open channel to that stack's SSP Lightning node that can send about 30 000 sats and a Spark balance of about + 30 000 sats, and a second wallet (or the stack's Lightning node) that can issue a 50 000-sat invoice. Start on the + wallet home screen. + + + On the receiving side, create a 50 000-sat Lightning invoice and open it on the sending wallet with a lightning: deep link + Verify the Confirm screen (testTag "SendConfirm") shows 50 000 sats, then tap Show Details (testTag "SendConfirmToggleDetails") + Verify the fee row shows the payment's own fee and the "Update fee" row (testTag "ReviewUpdateFee") shows an amount, without "up to", and that no "Route" row shows + Swipe to pay (testTag "GRAB") and verify the Bitcoin Sent screen (testTag "SendSuccess") shows 50 000 + Go back to Home and verify Activity lists a "Move to Spark" transfer row and the 50 000-sat Lightning payment + Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed + + diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index 0b7e1fc20e..a1dd32d689 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -1,11 +1,13 @@ - Verifies the post-update "Move to Spark" sheet and the move itself. With an LDK channel that can send at least - 1,000 sats and Spark connected, Home shows the "Move To Spark" sheet once (testTag "MoveToSparkIntro"); Spending - and Lightning Connections show a "Move To Spark" button (testTag "MoveToSpark") while the channel can still send. - The move quotes the routing fee over the channel only, pays the amount to a new invoice of the user's own Spark - wallet, and then offers to close the emptied connection. A wallet without such a channel never gets the sheet or - the button. + Verifies the "Update Spending Balance" modal and the move behind it. With an LDK channel that can send at least + 1,000 sats and Spark connected, Home shows the modal once (testTag "UpdateSpendingBalance"); Spending and Lightning + Connections show a "Move To Spark" button (testTag "MoveToSpark") that opens the same modal while the channel can + still send. The modal quotes the routing fee over the channel only and shows it as "Update fee: " in the primary + currency (testTag "UpdateSpendingBalanceUpdate" is the Update button, loading while it quotes and moves). Update + pays the amount to a new invoice of the user's own Spark wallet and shows "Spending Balance Updated" (testTag + "SpendingBalanceUpdated"); once the move settles, the app closes the emptied channel cooperatively in the + background, which writes a transfer to Savings. A wallet without such a channel never gets the modal or the button. The "too large to route" state (testTag "MoveToSparkTrySmaller") needs a route that cannot carry the balance; on a direct channel to the Spark service provider every amount routes, so it is covered by the quote's unit tests and the @@ -17,14 +19,15 @@ app freshly launched. - Wait on Home and verify the "Move To Spark" sheet (testTag "MoveToSparkIntro") shows, saying Blocktank is closing its Lightning connections - Tap "Later" (testTag "MoveToSparkIntroLater") and verify the sheet closes - Relaunch the app, wait on Home and verify the sheet does not show again + Wait on Home and verify the "Update Spending Balance" modal (testTag "UpdateSpendingBalance") shows "UPDATE SPENDING BALANCE" and "Bitkit is switching Lightning providers. Update your spending balance to continue making instant, cheap payments." followed by "Update fee: " and an amount + Tap "Later" (testTag "UpdateSpendingBalanceLater") and verify the modal closes + Relaunch the app, wait on Home and verify the modal does not show again Open the Spending wallet and verify the "Move To Spark" button (testTag "MoveToSpark") shows - Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") - Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") - Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no open connection and the Spark balance grew by the moved amount - Go back to Home and verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and that its detail screen is titled "Move to Spark" + Tap "Move To Spark" and verify the "Update Spending Balance" modal opens and shows "Update fee: " with an amount once the Update button (testTag "UpdateSpendingBalanceUpdate") stops loading + Tap "Update" and verify the modal titled "Spending Balance Updated" (testTag "SpendingBalanceUpdated") shows "SPENDING BALANCE UPDATED" and "Your spending balance has been successfully migrated to Spark, Bitkit’s new Lightning service provider." + Tap "OK" (testTag "SpendingBalanceUpdatedOk") and verify the modal closes + Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed, with no open connection left, and the Spark balance grew by the moved amount + Go back to Home and verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, whose detail screen is titled "Move to Spark", and a transfer to Savings for the closed channel Open Spending and verify the "Move To Spark" button is gone diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index e8160a993f..443f04ebd3 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -5,8 +5,8 @@ with no network check first, and the transfer purchase flow no longer exists. The sheet shows "MANUAL SETUP REQUIRED" (testTag "TransferUnavailableTitle") and the buttons "Learn More" (testTag "TransferUnavailableLearnMore"), which opens https://blog.bitkit.to/ in the browser, and "Continue" - (testTag "TransferUnavailableContinue"), which opens the existing Manual Setup screen. Receive's Lightning - path shows the same sheet content. + (testTag "TransferUnavailableContinue"), which opens the existing Manual Setup screen. Receive has no Lightning + path here: without a usable Spark wallet or channel its Spending and Auto tabs are hidden. Precondition: dev build, onboarded wallet with a positive on-chain Savings balance, no channels and Spark not running (a build without a Breez API key, or Spark's regtest unreachable), or a regtest build without @@ -23,8 +23,6 @@ Open Settings › Advanced › Lightning Connections, tap add connection (testTag "add_connection_button") and verify the screen text reads "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider." Verify "Manual Setup" (testTag "FundManual") is the first option and enabled, and "Transfer From Savings" (testTag "FundTransfer"), "Transfer from HW wallet" (testTag "FundHardware") and "Use Other Wallet" (testTag "FundReceive") below it are disabled; tap "Transfer From Savings" and verify nothing opens Tap "Learn More" (testTag "FundLearnMore") at the bottom and verify the browser opens blog.bitkit.to, then return to Bitkit and go back to the wallet home - Tap "Receive" (testTag "Receive"), select the Spending tab (testTag "Tab-spending") and tap "Receive Lightning Funds" - Verify the screen titled "Transfer Unavailable" shows "MANUAL SETUP REQUIRED" and "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider.", with a back button - Tap "Continue" and verify the sheet closes and the "MANUAL SETUP" screen opens + Tap "Receive" (testTag "Receive") and verify the tab row shows Savings (testTag "Tab-savings") but no Spending tab (testTag "Tab-spending" absent) and no Auto tab (testTag "Tab-auto" absent) From 1f912de0d157bc0f785a26515da19fae3308958b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:40:49 +0100 Subject: [PATCH 02/23] fix: guard the spending balance update before payments Verified: just format, just compile, just test, just lint, androidTest compile --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 30 ++- .../settings/lightning/MoveToSparkManager.kt | 5 +- .../java/to/bitkit/ui/sheets/SendSheet.kt | 4 + .../to/bitkit/usecases/CloseChannelUseCase.kt | 5 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 48 +++- .../repositories/MoveToSparkRepoTest.kt | 35 +++ .../usecases/CloseChannelUseCaseTest.kt | 18 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 220 ++++++++++++++++++ journeys/transfer/move-to-spark.xml | 2 +- 9 files changed, 351 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 963929901f..a10e05d9c9 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -118,6 +118,12 @@ class MoveToSparkRepo internal constructor( spark = sparkRepo.state.value, ) + /** The most a Lightning payment can send over the channels or Spark alone, without an update. */ + fun singleRailSendableSats(): ULong = MoveToSparkMath.singleRailSendableSats( + channels = lightningRepo.lightningState.value.channels.takeIf { canRunNode() }, + spark = sparkRepo.state.value, + ) + /** Whether paying [amountSats] needs the channels' balance updated to Spark first, as neither rail covers it. */ fun needsUpdateToSend(amountSats: ULong): Boolean = MoveToSparkMath.needsUpdateToSend( amountSats = amountSats, @@ -131,7 +137,8 @@ class MoveToSparkRepo internal constructor( * Updates the spending balance for a payment of [amountSats]: moves the channels' balance to Spark with * [knownQuote], or a new quote, and waits until Spark can pay the amount. A move still in flight, or a balance * Spark does not show in time, fails with [MoveToSparkError.UpdateUnsettled]; the funds then reach Spark on their - * own. [onMove] gets the move's outcome as soon as the move returns, before the wait. + * own. [onMove] gets the move's outcome as soon as the move returns, before the wait. A quote whose amount, with + * Spark's balance, would not cover the payment fails with [MoveToSparkError.UpdateFallsShort] before any move. */ suspend fun updateToSend( knownQuote: MoveToSparkQuote?, @@ -141,6 +148,9 @@ class MoveToSparkRepo internal constructor( withContext(bgDispatcher) { runSuspendCatching { val usedQuote = knownQuote ?: quote().getOrThrow() + if (!MoveToSparkMath.coversPayment(usedQuote, sparkRepo.state.value, amountSats)) { + throw MoveToSparkError.UpdateFallsShort(amountSats) + } val outcome = move(usedQuote).getOrThrow().also(onMove) val moved = outcome as? MoveToSparkOutcome.Moved ?: throw MoveToSparkError.UpdateUnsettled() val shown = withTimeoutOrNull(SPARK_BALANCE_WAIT) { @@ -376,11 +386,17 @@ object MoveToSparkMath { return SparkFees.sendableSats(spark.balanceSats.safe() + firstCandidate(limitSats, limitSats).safe()) } + /** The most the channels or a ready Spark can send alone. */ + fun singleRailSendableSats(channels: List?, spark: SparkState): ULong = + maxOf(movableSats(channels), spark.sendableSats.takeIf { spark.isReady } ?: 0uL) + /** Whether [amountSats] fits neither the channels nor Spark alone, but fits Spark once the channels moved to it. */ - fun needsUpdateToSend(amountSats: ULong, channels: List?, spark: SparkState): Boolean { - val singleRailSats = maxOf(movableSats(channels), spark.sendableSats.takeIf { spark.isReady } ?: 0uL) - return amountSats > singleRailSats && amountSats <= combinedSendableSats(channels, spark) - } + fun needsUpdateToSend(amountSats: ULong, channels: List?, spark: SparkState): Boolean = + amountSats > singleRailSendableSats(channels, spark) && amountSats <= combinedSendableSats(channels, spark) + + /** Whether Spark can pay [amountSats], its service fee included, once [quote] has moved to it. */ + fun coversPayment(quote: MoveToSparkQuote, spark: SparkState, amountSats: ULong): Boolean = + spark.isUsable && SparkFees.sendableSats(spark.balanceSats.safe() + quote.amountSats.safe()) >= amountSats /** The open channels in [after] that could send at least [MIN_MOVE_SATS] in [before] and no longer can. */ fun emptiedChannels(before: List, after: List?): List { @@ -422,6 +438,10 @@ sealed class MoveToSparkError(message: String, cause: Throwable? = null) : AppEr val reason: PaymentFailureReason? = null, ) : MoveToSparkError("Could not route '$amountSats' sats to Spark, reason '$reason'", cause) + /** The quoted move, with Spark's balance, would not cover a payment of [amountSats], so nothing moved. */ + class UpdateFallsShort(val amountSats: ULong) : + MoveToSparkError("An update would not cover a payment of '$amountSats' sats") + /** The update moved the balance, but Spark cannot pay with it yet: the move or Spark's balance has not settled. */ class UpdateUnsettled : MoveToSparkError("The update to Spark has not settled yet") diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index 794f766f80..a4f0e1add5 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -147,10 +147,7 @@ class MoveToSparkManager @Inject constructor( } private fun closeEmptied(channelsBefore: List) { - scope.launch { - walletRepo.syncNodeAndWallet() - closeChannelUseCase.closeEmptiedByMove(channelsBefore) - } + scope.launch { closeChannelUseCase.closeEmptiedByMove(channelsBefore) } } private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { 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 3dddda875e..2cbc186df8 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -325,6 +325,10 @@ fun SendSheet( is SendEffect.NavigateToScan -> navController.navigateTo(SendRoute.QrScanner) is SendEffect.NavigateToCoinSelection -> navController.navigateToCoinSelection() is SendEffect.NavigateToConfirm -> navController.navigateTo(SendRoute.Confirm) + is SendEffect.ResetConfirm -> + navController.currentBackStackEntry + ?.savedStateHandle + ?.set(SEND_CONFIRM_RESET_RESULT_KEY, true) is SendEffect.NavigateToUsdtReview -> navController.navigateTo(SendRoute.UsdtReview) is SendEffect.ShowPaykitConfirmation -> { // Replace the other asset's confirmation, so Back never returns to its stale terms. diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index e1aff341aa..cc8df01d79 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -43,9 +43,12 @@ class CloseChannelUseCase @Inject constructor( /** * Closes each channel a move to Spark emptied: one that could send at least the move minimum in [before] and can - * no longer. A close that fails leaves its channel listed for a manual close. + * no longer, read from the node after a sync. A close that fails leaves its channel listed for a manual close. */ suspend fun closeEmptiedByMove(before: List) = withContext(ioDispatcher) { + walletRepo.syncNodeAndWallet() + // A sync already running returns at once, so the channels are read from the node directly. + lightningRepo.syncState() val emptied = MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) emptied.forEach { channel -> invoke(channel) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index dd29a8338d..9b84c33f4a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -185,6 +185,7 @@ import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LnurlPayInvoiceMismatchError import to.bitkit.repositories.MethodId +import to.bitkit.repositories.MoveToSparkError import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkQuote import to.bitkit.repositories.MoveToSparkRepo @@ -4951,7 +4952,8 @@ class AppViewModel @Inject constructor( val result = pubkySwapsRouteRepo.route( amountSats = _sendUiState.value.amount, endpoints = listOf(route.endpoint), - lightningSpendableSats = maxSendableLightningSats(), + // The hold payment goes out over one rail, never after a spending balance update. + lightningSpendableSats = minOf(maxSendableLightningSats(), moveToSparkRepo.singleRailSendableSats()), onchainSpendableSats = balances.maxSendOnchainSats, ) _sendUiState.update { it.copy(isLoading = false) } @@ -6829,6 +6831,7 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToAmount) return } + if (!confirmSparkUpdateQuote()) return val incomingPaymentRequest = contactPaymentContext?.incomingPaymentRequest val proofPreparation = preparePaymentProof(incomingPaymentRequest) @@ -7792,8 +7795,16 @@ class AppViewModel @Inject constructor( // The node's payment events settle this attempt by hash, like an automatic one. allowanceAttemptId?.let { paykitAllowanceRepo.manualLightningPaymentSent(it, paymentHash) } - var authorizationError: Throwable? = null - val result = updateSpendingBalanceIfNeeded(displayAmountSats).fold( + // A request refused before the update must move nothing, so its allowance is checked before the move too. + val refusedBeforeUpdate = incomingPaymentRequest + ?.takeIf { moveToSparkRepo.needsUpdateToSend(displayAmountSats) } + ?.let { paykitPaymentRequestRepo.ensurePaymentAllowed(it).exceptionOrNull() } + var authorizationError: Throwable? = refusedBeforeUpdate + val result = if (refusedBeforeUpdate != null) { + Result.failure(refusedBeforeUpdate) + } else { + updateSpendingBalanceIfNeeded(displayAmountSats) + }.fold( onSuccess = { sendLightning( decodedInvoice.bolt11, @@ -7872,6 +7883,31 @@ class AppViewModel @Inject constructor( }.map { } } + /** + * Quotes the spending balance update again when the payment needs one, before anything is prepared or sent. A + * quote the user did not see, or a fee above the one shown, stops the swipe and shows the new fee instead. + */ + private suspend fun confirmSparkUpdateQuote(): Boolean { + val state = _sendUiState.value + if (state.payMethod != SendMethod.LIGHTNING || state.routedPaykitRoute?.serviceLeg != null) return true + if (state.activePaykitSwapRoute != null) return true + val payAmount = state.decodedInvoice?.amountSatoshis?.takeIf { it > 0uL } ?: state.amount + if (!moveToSparkRepo.needsUpdateToSend(payAmount)) return true + val generation = sendStateGeneration + val fresh = moveToSparkRepo.quote().getOrElse { + val failure = it.toSendFailureDetails(context, state.currentLightningPaymentRequest()) + setSendEffect(SendEffect.NavigateToError(failure)) + return false + } + if (generation != sendStateGeneration) return false + val shown = state.sparkUpdateQuote + _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } + if (shown != null && fresh.feeSats <= shown.feeSats) return true + Logger.info("Stopped a payment to show the update fee '${fresh.feeSats}'", context = TAG) + setSendEffect(SendEffect.ResetConfirm) + return false + } + private fun closeChannelsEmptiedBy(outcome: MoveToSparkOutcome, channelsBefore: List) { viewModelScope.launch(bgDispatcher) { if (outcome is MoveToSparkOutcome.InFlight && moveToSparkRepo.awaitSettled(outcome).isFailure) return@launch @@ -7894,7 +7930,8 @@ class AppViewModel @Inject constructor( ): Boolean = when (error) { is PaymentPendingException -> false else if !isPaymentRequest -> true - is LightningPaymentFailedError -> { + // A failed spending balance update happens before the invoice is paid, so nothing was sent. + is LightningPaymentFailedError, is MoveToSparkError -> { paykitPaymentProofRepo.failLightningPayment(paymentHash) true } @@ -8569,6 +8606,7 @@ class AppViewModel @Inject constructor( ) { requireCurrentPaymentPreparation(walletGeneration) val generation = sendStateGeneration + _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(sparkUpdateQuote = null) } val currentState = _sendUiState.value if (currentState.payMethod != SendMethod.LIGHTNING) return // A Spark leg pays the contact's other endpoint, so its fee is the leg's, never the retained invoice's. @@ -8579,7 +8617,6 @@ class AppViewModel @Inject constructor( estimateSparkUpdateFees(decodedInvoice.bolt11, payAmount, generation, walletGeneration) return } - _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(sparkUpdateQuote = null) } val feeResult = if (decodedInvoice.amountSatoshis > 0uL) { lightningRepo.estimateRoutingFees(decodedInvoice.bolt11) @@ -10485,6 +10522,7 @@ sealed class SendEffect { data object NavigateToAmount : SendEffect() data object NavigateToScan : SendEffect() data object NavigateToConfirm : SendEffect() + data object ResetConfirm : SendEffect() data object NavigateToUsdtReview : SendEffect() data class ShowPaykitConfirmation(val route: SendRoute) : SendEffect() data object NavigateToHardwareSign : SendEffect() diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 97fac46e76..7ff5ef7243 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -391,8 +391,41 @@ class MoveToSparkRepoTest : BaseUnitTest() { } } + @Test + fun `update to send moves nothing when the quote and Spark's balance fall short of the payment`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 5_000uL) + + val result = sut.updateToSend(quote, 60_000uL) + + assertIs(result.exceptionOrNull()) + verify(lightningRepo, never()).payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a quote covers a payment once Spark can pay it with its service fee`() { + val spark = SparkState(isReady = true, balanceSats = 10_000uL) + val sendable = SparkFees.sendableSats(10_000uL + quote.amountSats) + + assertTrue(MoveToSparkMath.coversPayment(quote, spark, sendable)) + assertTrue(!MoveToSparkMath.coversPayment(quote, spark, sendable + 1uL)) + assertTrue(!MoveToSparkMath.coversPayment(quote, spark.copy(isExiting = true), 1_000uL)) + } + + @Test + fun `single rail sendable is the larger of the channels and a ready Spark`() { + val channels = listOf(channel("a", 30_000uL)) + + assertEquals(30_000uL, MoveToSparkMath.singleRailSendableSats(channels, SparkState(isReady = true))) + assertEquals( + SparkFees.sendableSats(50_000uL), + MoveToSparkMath.singleRailSendableSats(channels, SparkState(isReady = true, balanceSats = 50_000uL)), + ) + assertEquals(30_000uL, MoveToSparkMath.singleRailSendableSats(channels, SparkState(balanceSats = 50_000uL))) + } + @Test fun `update to send moves the balance, then waits until Spark can pay`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) @@ -408,6 +441,7 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send fails as unsettled while the move is in flight`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) @@ -423,6 +457,7 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send reports a settled move even when Spark never shows the balance`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index 2d3ad954ef..5fd8d48e68 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -7,6 +7,7 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -82,6 +83,23 @@ class CloseChannelUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(eq(kept), any(), anyOrNull()) } + @Test + fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { + lightningState.value = LightningState(channels = persistentListOf(channel)) + whenever(lightningRepo.syncState()).thenAnswer { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + Unit + } + + sut.closeEmptiedByMove(listOf(channel)) + + inOrder(walletRepo, lightningRepo) { + verify(walletRepo).syncNodeAndWallet(anyOrNull()) + verify(lightningRepo).syncState() + verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) + } + } + private fun channel(id: String, sendableSats: ULong) = createChannelDetails().copy( channelId = id, isUsable = true, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d2518e4b74..e632b84ea4 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20533,6 +20533,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val quote = MoveToSparkQuote("lnbcrt1spark", amountSats = 50_000uL, feeSats = 12uL) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) val moved = MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(quote)) whenever(moveToSparkRepo.updateToSend(eq(quote), eq(60_000uL), any())).thenReturn(Result.success(moved)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) setSendState( @@ -20561,6 +20562,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `a failed spending balance update shows the payment error and pays nothing`() = test { val bolt11 = "lnbcrt1updatefails" + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) @@ -20570,6 +20572,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = 60_000uL, payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20585,6 +20588,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `a settled move closes the emptied channels even when the payment after it fails`() = test { val bolt11 = "lnbcrt1movedunsettled" + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) @@ -20594,6 +20598,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = 60_000uL, payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20611,6 +20616,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `an in-flight move closes the emptied channels once it settles`() = test { val bolt11 = "lnbcrt1inflight" + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) @@ -20623,6 +20629,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = 60_000uL, payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20652,6 +20659,218 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(quickPayRepo, never()).canApply(any()) } + @Test + fun `a failed spending balance update on a payment request shows the error and releases the request`() = test { + val request = paymentRequest() + val bolt11 = "lnbcrt1updaterequest" + val paymentHash = "010203" + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever( + paykitPaymentProofRepo.prepare( + request, + MethodId.Bolt11.rawValue, + "bitkit", + PaykitPaymentProofKind.Lightning + ) + ) + .doSuspendableAnswer { + setSendState( + sut.sendUiState.value.copy(decodedInvoice = lightningInvoice(bolt11, request.amount.atomic)) + ) + Result.success(Unit) + } + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitAllowanceRepo.beginManualPayment(eq(request), any(), anyOrNull())) + .thenReturn(Result.success("update-attempt")) + whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(request.amount.atomic), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = bolt11, + amount = request.amount.atomic, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(pendingPaymentRepo, never()).track(any()) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).cancelPreparation(request) + verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(paykitAllowanceRepo).finishManualPayment("update-attempt", false, null) + } + + @Test + fun `a refused payment request moves nothing and closes nothing`() = test { + val request = paymentRequest() + val bolt11 = "lnbcrt1refusedrequest" + val paymentHash = "010203" + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever( + paykitPaymentProofRepo.prepare( + request, + MethodId.Bolt11.rawValue, + "bitkit", + PaykitPaymentProofKind.Lightning + ) + ) + .doSuspendableAnswer { + setSendState( + sut.sendUiState.value.copy(decodedInvoice = lightningInvoice(bolt11, request.amount.atomic)) + ) + Result.success(Unit) + } + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitAllowanceRepo.beginManualPayment(eq(request), any(), anyOrNull())) + .thenReturn(Result.success("refused-attempt")) + whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)) + .thenReturn(Result.failure(PaykitPaymentRequestError.RequestUnavailable)) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = bolt11, + amount = request.amount.atomic, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + verify(pendingPaymentRepo, never()).track(any()) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).cancelPreparation(request) + verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(paykitAllowanceRepo).finishManualPayment("refused-attempt", false, null) + } + + @Test + fun `a swipe without a shown update fee shows the fee instead of moving`() = test { + val bolt11 = "lnbcrt1noshownfee" + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + } + assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + } + + @Test + fun `a swipe whose update fee rose shows the new fee instead of moving`() = test { + val bolt11 = "lnbcrt1feerose" + val raised = UPDATE_QUOTE.copy(feeSats = UPDATE_QUOTE.feeSats + 1uL) + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(raised)) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + } + assertEquals(raised, sut.sendUiState.value.sparkUpdateQuote) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + } + + @Test + fun `a swipe whose update cannot be quoted shows the error and moves nothing`() = test { + val bolt11 = "lnbcrt1noquote" + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.failure(MoveToSparkError.NothingToMove())) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + } + + @Test + fun `a fee estimate that stops early drops a stale update quote`() = test { + setSendState( + SendUiState( + amount = 1_000uL, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + assertNull(sut.sendUiState.value.sparkUpdateQuote) + } + + @Test + fun `a swap route is quoted with what one rail can pay, never the update's combined amount`() = test { + whenever(moveToSparkRepo.singleRailSendableSats()).thenReturn(20_000uL) + openSwapRoutedContactPayment() + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(pubkySwapsRouteRepo).route(any(), any(), eq(20_000uL), any(), any()) + } + @Suppress("UNCHECKED_CAST") private fun setSendState(state: SendUiState) { val field = AppViewModel::class.java.getDeclaredField("_sendUiState") @@ -22128,6 +22347,7 @@ private const val SWAP_HOLD_INVOICE = "lnbcrt1swaphold" /** The hex of [lightningInvoice]'s payment hash. */ private const val SWAP_HOLD_HASH = "010203" +private val UPDATE_QUOTE = MoveToSparkQuote("lnbcrt1spark", amountSats = 50_000uL, feeSats = 12uL) private const val SWAP_CLAIM_TXID = "claimtxid" private const val SWAP_DELIVERED_SATS = 20_000uL private const val SWAP_DEBIT_SATS = 20_100uL diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index a1dd32d689..5c52a7d947 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -26,7 +26,7 @@ Tap "Move To Spark" and verify the "Update Spending Balance" modal opens and shows "Update fee: " with an amount once the Update button (testTag "UpdateSpendingBalanceUpdate") stops loading Tap "Update" and verify the modal titled "Spending Balance Updated" (testTag "SpendingBalanceUpdated") shows "SPENDING BALANCE UPDATED" and "Your spending balance has been successfully migrated to Spark, Bitkit’s new Lightning service provider." Tap "OK" (testTag "SpendingBalanceUpdatedOk") and verify the modal closes - Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed, with no open connection left, and the Spark balance grew by the moved amount + Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed, and that it shows no channel under OPEN CONNECTIONS, only Spark via Breez, whose balance grew by the moved amount Go back to Home and verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, whose detail screen is titled "Move to Spark", and a transfer to Savings for the closed channel Open Spending and verify the "Move To Spark" button is gone From 2ada21c753bb8f815b98712eeb799e6e07fdf2ba Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 01:27:43 +0100 Subject: [PATCH 03/23] fix: update spending balance journeys to the app's current steps Verified: none (journey text only) --- journeys/send/update-spending-balance-payment.xml | 3 ++- journeys/transfer/transfer-unavailable-sheet.xml | 12 +++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/journeys/send/update-spending-balance-payment.xml b/journeys/send/update-spending-balance-payment.xml index 79cc555b97..774015f4cf 100644 --- a/journeys/send/update-spending-balance-payment.xml +++ b/journeys/send/update-spending-balance-payment.xml @@ -16,7 +16,8 @@ On the receiving side, create a 50 000-sat Lightning invoice and open it on the sending wallet with a lightning: deep link Verify the Confirm screen (testTag "SendConfirm") shows 50 000 sats, then tap Show Details (testTag "SendConfirmToggleDetails") Verify the fee row shows the payment's own fee and the "Update fee" row (testTag "ReviewUpdateFee") shows an amount, without "up to", and that no "Route" row shows - Swipe to pay (testTag "GRAB") and verify the Bitcoin Sent screen (testTag "SendSuccess") shows 50 000 + Swipe to pay (testTag "GRAB"); the payment is over half of the Spending balance, so verify the "Are You Sure?" dialog warns about sending over 50% of the balance and tap "Yes, Send" + Verify the Bitcoin Sent screen (testTag "SendSuccess") shows 50 000 Go back to Home and verify Activity lists a "Move to Spark" transfer row and the 50 000-sat Lightning payment Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index 443f04ebd3..913c5003c6 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -8,11 +8,13 @@ (testTag "TransferUnavailableContinue"), which opens the existing Manual Setup screen. Receive has no Lightning path here: without a usable Spark wallet or channel its Spending and Auto tabs are hidden. - Precondition: dev build, onboarded wallet with a positive on-chain Savings balance, no channels and Spark - not running (a build without a Breez API key, or Spark's regtest unreachable), or a regtest build without - `ESPLORA_URL`, whose deposits Spark can't see; with Spark ready on its chain, see - spark-transfer-to-spending.xml. Start on - the wallet home screen. + Precondition: dev build, onboarded wallet with a positive on-chain Savings balance, an empty Spending + balance, no channels and Spark failing to start. On regtest Spark needs no Breez key and starts from local + state even when its servers are blocked; on a debug build, stop it by replacing the app's + `files/regtest/wallet0/spark` directory with a plain file through `run-as`, then relaunch (the log shows + "Failed to start Spark wallet"). A build without `ESPLORA_URL` reaches the sheet from the Transfer To + Spending entries, but Lightning Connections and Receive need Spark down; with Spark connected, see + spark-transfer-to-spending.xml. Start on the wallet home screen. Tap the Savings balance card (testTag "ActivitySavings") and verify "Transfer To Spending" (testTag "TransferToSpending") is shown From 94a891540e828c01e0bf8864f48161c82b5b0399 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 02:01:25 +0100 Subject: [PATCH 04/23] chore: translate spending balance update strings Verified: just compile, just test, just lint --- app/src/main/res/values-ar/strings.xml | 10 ++++++++++ app/src/main/res/values-b+es+419/strings.xml | 10 ++++++++++ app/src/main/res/values-ca/strings.xml | 10 ++++++++++ app/src/main/res/values-cs/strings.xml | 10 ++++++++++ app/src/main/res/values-de/strings.xml | 10 ++++++++++ app/src/main/res/values-el/strings.xml | 10 ++++++++++ app/src/main/res/values-es-rES/strings.xml | 10 ++++++++++ app/src/main/res/values-es/strings.xml | 10 ++++++++++ app/src/main/res/values-fr/strings.xml | 10 ++++++++++ app/src/main/res/values-it/strings.xml | 10 ++++++++++ app/src/main/res/values-nl/strings.xml | 10 ++++++++++ app/src/main/res/values-pl/strings.xml | 10 ++++++++++ app/src/main/res/values-pt-rBR/strings.xml | 10 ++++++++++ app/src/main/res/values-pt/strings.xml | 10 ++++++++++ app/src/main/res/values-ru/strings.xml | 10 ++++++++++ changelog.d/next/1946.changed.md | 1 + 16 files changed, 151 insertions(+) create mode 100644 changelog.d/next/1946.changed.md diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3fa23cbdff..9eba420f15 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -181,6 +181,15 @@ يمكنك نقله على أجزاء أصغر. %1$s كبير جدًا بحيث لا يمكن توجيهه إلى Spark في دفعة واحدة. المبلغ\n<accent>كبير جدًا</accent> + تحديث + رسوم التحديث: %1$s + تحديث رصيد الإنفاق + يغيّر Bitkit مزوّد Lightning. حدّث رصيد الإنفاق لمواصلة الدفعات الفورية والرخيصة. + تحديث\n<accent>رصيد الإنفاق</accent> + تم تحديث رصيد الإنفاق + جزء من رصيد الإنفاق موجود الآن على Spark. انقل الباقي بالطريقة نفسها. + تم نقل رصيد الإنفاق بنجاح إلى Spark، مزوّد خدمة Lightning الجديد في Bitkit. + رصيد الإنفاق\n<accent>محدَّث</accent> حد HTLC الصادر التالي الحد الأدنى لـ HTLC الصادر التالي قبل أن تتمكن من تحويل الأموال من رصيد مدخراتك، تحتاج إلى إرسال Bitcoin إلى محفظة Bitkit الخاصة بك. @@ -1156,6 +1165,7 @@ المسار اسحب للدفع إلى + رسوم التحديث نعم، أرسل <accent>أرسل\nBitcoin</accent>\nإلى\nرصيد إنفاقك الإنفاق diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index c884044bc4..7fc2599103 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -188,6 +188,15 @@ Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. Monto\n<accent>demasiado grande</accent> + Actualizar + Comisión de actualización: %1$s + Actualizar saldo de gastos + Bitkit está cambiando de proveedor Lightning. Actualiza tu saldo de gastos para seguir haciendo pagos instantáneos y baratos. + Actualizar\n<accent>saldo de gastos</accent> + Saldo de gastos actualizado + Parte de tu saldo de gastos ya está en Spark. Mueve el resto de la misma forma. + Tu saldo de gastos se migró correctamente a Spark, el nuevo proveedor de servicios Lightning de Bitkit. + Saldo de gastos\n<accent>actualizado</accent> Límite del próximo HTLC saliente Mínimo del próximo HTLC saliente Para transferir fondos a su saldo de ahorros, primero tiene que enviar bitcoin a su billetera Bitkit. @@ -1189,6 +1198,7 @@ Ruta Deslizar para pagar Para + Comisión de actualización Sí, enviar <accent>Enviar\nbitcoin</accent>\na su\nsaldo de gastos Gasto diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 73e13ed1df..e03a7dba8e 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -185,6 +185,15 @@ Pots moure\'l en parts més petites. %1$s és massa gran per encaminar-se a Spark en un sol pagament. Import\n<accent>massa gran</accent> + Actualitzar + Comissió d’actualització: %1$s + Actualitzar el saldo de despesa + Bitkit està canviant de proveïdor Lightning. Actualitza el teu saldo de despesa per continuar fent pagaments instantanis i barats. + Actualitzar\n<accent>saldo de despesa</accent> + Saldo de despesa actualitzat + Part del teu saldo de despesa ja és a Spark. Mou la resta de la mateixa manera. + El teu saldo de despesa s’ha migrat correctament a Spark, el nou proveïdor de serveis Lightning de Bitkit. + Saldo de despesa\n<accent>actualitzat</accent> Límit del pròxim HTLC de sortida Mínim del pròxim HTLC de sortida Abans de poder transferir fons del teu saldo d\'estalvis, has d\'enviar bitcoin a la teva cartera Bitkit. @@ -1182,6 +1191,7 @@ Ruta Desplaça per pagar A + Comissió d’actualització Sí, Enviar <accent>Envia\nbitcoin</accent>\nal teu\nsaldo de despesa Despesa diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2deb172fe7..8e9015268b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -188,6 +188,15 @@ Můžete ho přesunout po menších částech. %1$s je příliš velká částka na směrování do Spark jednou platbou. Částka je\n<accent>příliš velká</accent> + Aktualizovat + Poplatek za aktualizaci: %1$s + Aktualizovat výdajový zůstatek + Bitkit mění poskytovatele Lightning. Aktualizujte svůj výdajový zůstatek, abyste mohli dál platit okamžitě a levně. + Aktualizovat\n<accent>výdajový zůstatek</accent> + Výdajový zůstatek aktualizován + Část vašeho výdajového zůstatku je nyní na Spark. Zbytek přesuňte stejným způsobem. + Váš výdajový zůstatek byl úspěšně převeden na Spark, nového poskytovatele služeb Lightning pro Bitkit. + Výdajový zůstatek\n<accent>aktualizován</accent> Limit dalšího odchozího HTLC Min dalšího odchozího HTLC Než budete moci převést prostředky ze svého zůstatku na spořicím účtu, musíte poslat bitcoiny do peněženky Bitkit. @@ -1187,6 +1196,7 @@ Trasa Zaplatit přejetím prstem Komu + Poplatek za aktualizaci Ano, odeslat <accent>Odeslat\nbitcoin</accent>\ndo vašeho\ndisponibilního zůstatku Útraty diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 17a06aea19..05753b3b9d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -116,6 +116,15 @@ Du kannst es in kleineren Teilen verschieben. %1$s ist zu groß, um in einer Zahlung zu Spark geroutet zu werden. Betrag\n<accent>zu groß</accent> + Aktualisieren + Aktualisierungsgebühr: %1$s + Ausgabenguthaben aktualisieren + Bitkit wechselt den Lightning-Anbieter. Aktualisiere dein Ausgabenguthaben, um weiterhin sofort und günstig zu bezahlen. + Ausgabenguthaben\n<accent>aktualisieren</accent> + Ausgabenguthaben aktualisiert + Ein Teil deines Ausgabenguthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise. + Dein Ausgabenguthaben wurde erfolgreich zu Spark übertragen, Bitkits neuem Lightning-Dienstanbieter. + Ausgabenguthaben\n<accent>aktualisiert</accent> Übertragung\n<accent>fehlgeschlagen</accent> Genehmigen <accent>Die Gebühr für die schnelle Übertragung beträgt jetzt ₿ {amount}.</accent> Genehmige, um schnell auf deine Gelder zuzugreifen, oder warte ±30 Min. @@ -1037,6 +1046,7 @@ Rechnungsverfall Route Zum Bezahlen wischen + Aktualisierungsgebühr Ja, senden Es scheint, dass du über $100 sendest. Möchtest du fortfahren? Es scheint, dass du über 50% deines Gesamtguthabens sendest. Möchtest du fortfahren? diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4c634664c3..5830b264e3 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -181,6 +181,15 @@ Μπορείς να το μεταφέρεις σε μικρότερα μέρη. Το %1$s είναι πολύ μεγάλο για να δρομολογηθεί στο Spark με μία πληρωμή. Πολύ μεγάλο\n<accent>ποσό</accent> + Ενημέρωση + Χρέωση ενημέρωσης: %1$s + Ενημέρωση υπολοίπου δαπανών + Το Bitkit αλλάζει πάροχο Lightning. Ενημερώστε το υπόλοιπο δαπανών σας για να συνεχίσετε να κάνετε άμεσες, φθηνές πληρωμές. + Ενημέρωση\n<accent>υπολοίπου δαπανών</accent> + Το υπόλοιπο δαπανών ενημερώθηκε + Μέρος του υπολοίπου δαπανών σας βρίσκεται τώρα στο Spark. Μεταφέρετε το υπόλοιπο με τον ίδιο τρόπο. + Το υπόλοιπο δαπανών σας μεταφέρθηκε με επιτυχία στο Spark, τον νέο πάροχο υπηρεσιών Lightning του Bitkit. + Υπόλοιπο δαπανών\n<accent>ενημερώθηκε</accent> Όριο επόμενου εξερχόμενου HTLC Ελάχιστο επόμενο εξερχόμενο HTLC Πριν μπορέσεις να μεταφέρεις κεφάλαια από το υπόλοιπο αποταμιεύσεων, πρέπει να στείλεις bitcoin στο πορτοφόλι Bitkit. @@ -1161,6 +1170,7 @@ Διαδρομή Σύρε για πληρωμή Προς + Χρέωση ενημέρωσης Ναι, Στείλε <accent>Στείλε\nbitcoin</accent>\nστο υπόλοιπο\nδαπανών Δαπάνες diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index b8ba340275..f12f0f9efb 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -187,6 +187,15 @@ Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. Importe\n<accent>demasiado grande</accent> + Actualizar + Comisión de actualización: %1$s + Actualizar saldo de gastos + Bitkit está cambiando de proveedor Lightning. Actualiza tu saldo de gastos para seguir haciendo pagos instantáneos y baratos. + Actualizar\n<accent>saldo de gastos</accent> + Saldo de gastos actualizado + Parte de tu saldo de gastos ya está en Spark. Mueve el resto de la misma forma. + Tu saldo de gastos se ha migrado correctamente a Spark, el nuevo proveedor de servicios Lightning de Bitkit. + Saldo de gastos\n<accent>actualizado</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -1182,6 +1191,7 @@ Ruta Deslizar para pagar Para + Comisión de actualización Sí, enviar <accent>Envía\nbitcoin</accent>\na tu\nsaldo de gastos Gasto diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1c53435e98..f78b18a07d 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -154,6 +154,15 @@ Puedes moverlo en partes más pequeñas. %1$s es demasiado grande para enrutarse a Spark en un solo pago. Monto\n<accent>demasiado grande</accent> + Actualizar + Comisión de actualización: %1$s + Actualizar saldo de gastos + Bitkit está cambiando de proveedor Lightning. Actualiza tu saldo de gastos para seguir haciendo pagos instantáneos y baratos. + Actualizar\n<accent>saldo de gastos</accent> + Saldo de gastos actualizado + Parte de tu saldo de gastos ya está en Spark. Mueve el resto de la misma forma. + Tu saldo de gastos se ha migrado correctamente a Spark, el nuevo proveedor de servicios Lightning de Bitkit. + Saldo de gastos\n<accent>actualizado</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -1029,6 +1038,7 @@ Expiración de la factura Ruta Deslizar para pagar + Comisión de actualización Sí, enviar Parece que está enviando más de 100 dólares. ¿Desea continuar? Parece que está enviando más del 50% de su saldo total. ¿Desea continuar? diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 3f1f385453..eb1ecee058 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -115,6 +115,15 @@ Vous pouvez le déplacer en plusieurs parties plus petites. %1$s est trop élevé pour être acheminé vers Spark en un seul paiement. Montant\n<accent>trop élevé</accent> + Mettre à jour + Frais de mise à jour : %1$s + Mettre à jour le solde de dépenses + Bitkit change de fournisseur Lightning. Mettez à jour votre solde de dépenses pour continuer à payer instantanément et à moindre coût. + Mettre à jour\n<accent>le solde de dépenses</accent> + Solde de dépenses mis à jour + Une partie de votre solde de dépenses est maintenant sur Spark. Déplacez le reste de la même façon. + Votre solde de dépenses a bien été migré vers Spark, le nouveau fournisseur de services Lightning de Bitkit. + Solde de dépenses\n<accent>mis à jour</accent> Transfert\n<accent>échoué</accent> Approuver <accent>Les frais de transfert rapide sont maintenant de ₿ {amount}.</accent> Approuvez pour accéder rapidement à vos fonds, ou attendez ±30 min. @@ -1038,6 +1047,7 @@ Expiration de la facture Itinéraire Glisser pour payer + Frais de mise à jour Oui, Envoyer Il apparaît que vous envoyez plus de 100 $. Voulez-vous continuer ? Il apparaît que vous envoyez plus de 50 % de votre solde total. Voulez-vous continuer ? diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index e36bf9a472..11ec1a9e22 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -186,6 +186,15 @@ Puoi spostarlo in parti più piccole. %1$s è troppo grande per essere instradato su Spark in un solo pagamento. Importo\n<accent>troppo grande</accent> + Aggiorna + Commissione di aggiornamento: %1$s + Aggiorna saldo di spesa + Bitkit sta cambiando fornitore Lightning. Aggiorna il tuo saldo di spesa per continuare a fare pagamenti istantanei ed economici. + Aggiorna\n<accent>saldo di spesa</accent> + Saldo di spesa aggiornato + Parte del tuo saldo di spesa ora è su Spark. Sposta il resto allo stesso modo. + Il tuo saldo di spesa è stato migrato con successo su Spark, il nuovo fornitore di servizi Lightning di Bitkit. + Saldo di spesa\n<accent>aggiornato</accent> Limite HTLC in Uscita Successivo HTLC Min in Uscita Successivo Prima di poter trasferire fondi dal tuo conto di risparmio, devi inviare bitcoin al tuo portafoglio Bitkit. @@ -1185,6 +1194,7 @@ Percorso Scorri per Pagare A + Commissione di aggiornamento Si, Invia <accent>Invia\nbitcoin</accent>\nal tuo\nconto di spesa Spesa diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 4f782beff5..aaaf88046f 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -185,6 +185,15 @@ Je kunt het in kleinere delen verplaatsen. %1$s is te groot om in één betaling naar Spark te routeren. Bedrag\n<accent>te groot</accent> + Bijwerken + Kosten bijwerking: %1$s + Bestedingssaldo bijwerken + Bitkit stapt over op een andere Lightning-provider. Werk je bestedingssaldo bij om snelle, goedkope betalingen te blijven doen. + Bestedingssaldo\n<accent>bijwerken</accent> + Bestedingssaldo bijgewerkt + Een deel van je bestedingssaldo staat nu op Spark. Verplaats de rest op dezelfde manier. + Je bestedingssaldo is overgezet naar Spark, de nieuwe Lightning-dienstverlener van Bitkit. + Bestedingssaldo\n<accent>bijgewerkt</accent> Volgende uitgaande HTLC-limiet Volgende uitgaande HTLC min Voordat je geld van je spaargeld kunt overboeken, moet je bitcoin naar je Bitkit-wallet sturen. @@ -1180,6 +1189,7 @@ Route Veeg om te betalen Naar + Kosten bijwerking Ja, verzenden <accent>Stuur\nbitcoin</accent>\nnaar je\nbestedingssaldo Bestedingssaldo diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a6a721ca75..a59f72e58b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -117,6 +117,15 @@ Możesz je przenieść w mniejszych częściach. Kwota %1$s jest zbyt duża, aby przesłać ją do Spark jedną płatnością. Kwota\n<accent>zbyt duża</accent> + Aktualizuj + Opłata za aktualizację: %1$s + Aktualizuj saldo wydatków + Bitkit zmienia dostawcę Lightning. Zaktualizuj saldo wydatków, aby dalej płacić natychmiast i tanio. + Aktualizuj\n<accent>saldo wydatków</accent> + Saldo wydatków zaktualizowane + Część Twojego salda wydatków jest już na Spark. Przenieś resztę w ten sam sposób. + Twoje saldo wydatków zostało przeniesione do Spark, nowego dostawcy usług Lightning w Bitkit. + Saldo wydatków\n<accent>zaktualizowane</accent> Transfer\n<accent>nieudany</accent> Zatwierdź <accent>Opłata za szybki transfer wynosi teraz ₿ {amount}.</accent> Zatwierdź, aby szybko uzyskać dostęp do środków, lub poczekaj ±30 min. @@ -1040,6 +1049,7 @@ Termin faktury Trasa Przesuń, aby zapłacić + Opłata za aktualizację Tak, wyślij Wygląda na to, że wysyłasz ponad $100. Czy kontynuować? Wygląda na to, że wysyłasz ponad 50% swojego salda. Czy kontynuować? diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 2187c0c522..2476e68b5c 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -189,6 +189,15 @@ Você pode movê-lo em partes menores. %1$s é grande demais para ser roteado para a Spark num único pagamento. Valor\n<accent>grande demais</accent> + Atualizar + Taxa de atualização: %1$s + Atualizar saldo de gastos + A Bitkit está mudando de provedor Lightning. Atualize seu saldo de gastos para continuar fazendo pagamentos instantâneos e baratos. + Atualizar\n<accent>saldo de gastos</accent> + Saldo de gastos atualizado + Parte do seu saldo de gastos já está na Spark. Mova o restante da mesma forma. + Seu saldo de gastos foi migrado com sucesso para a Spark, o novo provedor de serviços Lightning da Bitkit. + Saldo de gastos\n<accent>atualizado</accent> Limite do Próximo HTLC de Saída HTLC de Saída Mín Próximo Antes de transferir fundos de seu saldo de poupança, receba bitcoin na sua carteira Bitkit. @@ -1189,6 +1198,7 @@ Rota Deslize para Pagar Para + Taxa de atualização Sim, Enviar <accent>Transfira\nbitcoin</accent>\npara seu\nsaldo de gastos Gastos diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 4c0372c62e..2d3cc97e6b 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -112,6 +112,15 @@ Pode movê-lo em partes mais pequenas. %1$s é demasiado grande para ser encaminhado para a Spark num único pagamento. Montante\n<accent>demasiado grande</accent> + Atualizar + Taxa de atualização: %1$s + Atualizar saldo de gastos + A Bitkit está a mudar de fornecedor Lightning. Atualize o seu saldo de gastos para continuar a fazer pagamentos instantâneos e baratos. + Atualizar\n<accent>saldo de gastos</accent> + Saldo de gastos atualizado + Parte do seu saldo de gastos já está na Spark. Mova o resto da mesma forma. + O seu saldo de gastos foi migrado com sucesso para a Spark, o novo fornecedor de serviços Lightning da Bitkit. + Saldo de gastos\n<accent>atualizado</accent> Transferência\n<accent>falhada</accent> Aprovar <accent>A taxa da transferência rápida é agora ₿ {amount}.</accent> Aprove para aceder rapidamente aos seus fundos ou aguarde ±30 min. @@ -901,6 +910,7 @@ Vencimento do invoice Rota Deslize para Pagar + Taxa de atualização Sim, Enviar Parece que você está enviando mais de US$ 100. Deseja continuar? Parece que você está enviando mais de 50% do seu saldo total. Deseja continuar? diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 0c58fab1cb..2485d6f119 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -197,6 +197,15 @@ Вы можете перенести его меньшими частями. %1$s слишком много для маршрутизации в Spark одним платежом. Сумма\n<accent>слишком велика</accent> + Обновить + Комиссия за обновление: %1$s + Обновить баланс расходов + Bitkit меняет Lightning-провайдера. Обновите баланс расходов, чтобы и дальше платить мгновенно и дёшево. + Обновить\n<accent>баланс расходов</accent> + Баланс расходов обновлён + Часть вашего баланса расходов уже в Spark. Перенесите остаток тем же способом. + Ваш баланс расходов успешно перенесён в Spark, нового поставщика Lightning-услуг Bitkit. + Баланс расходов\n<accent>обновлён</accent> Лимит след. исходящего HTLC Мин. след. исходящего HTLC Прежде чем вы сможете перевести средства со своего баланса сбережений, вам нужно отправить биткойны в ваш кошелёк Bitkit. @@ -1203,6 +1212,7 @@ Маршрут Отправить Кому + Комиссия за обновление Да, Отправить <accent>Отправьте\nбиткоин</accent>\nна ваш\nБаланс Расходов Расходы diff --git a/changelog.d/next/1946.changed.md b/changelog.d/next/1946.changed.md new file mode 100644 index 0000000000..50ab04acde --- /dev/null +++ b/changelog.d/next/1946.changed.md @@ -0,0 +1 @@ +Moving the spending balance to Spark now runs from one Update modal, closes the channels it empties and lets a Lightning payment combine both balances with one swipe; the CJIT receive card is removed. From aff7c0a7f667f618b4c438f0f1cfd87abdd392f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 02:49:43 +0100 Subject: [PATCH 05/23] fix: price spark's routing fee before an update moves funds Verified: just format, just compile, just test, just lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 28 ++++++--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 8 +-- .../repositories/MoveToSparkRepoTest.kt | 59 +++++++++++++++---- .../viewmodels/AppViewModelSendFlowTest.kt | 24 ++++---- 4 files changed, 85 insertions(+), 34 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index a10e05d9c9..db5a0e7a7c 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -138,17 +138,20 @@ class MoveToSparkRepo internal constructor( * [knownQuote], or a new quote, and waits until Spark can pay the amount. A move still in flight, or a balance * Spark does not show in time, fails with [MoveToSparkError.UpdateUnsettled]; the funds then reach Spark on their * own. [onMove] gets the move's outcome as soon as the move returns, before the wait. A quote whose amount, with - * Spark's balance, would not cover the payment fails with [MoveToSparkError.UpdateFallsShort] before any move. + * Spark's balance, would not cover the payment of [bolt11] and Spark's fee for it, or a fee nothing can price, + * fails with [MoveToSparkError.UpdateFallsShort] before any move. */ suspend fun updateToSend( knownQuote: MoveToSparkQuote?, + bolt11: String, amountSats: ULong, onMove: (MoveToSparkOutcome) -> Unit = {}, ): Result = withContext(bgDispatcher) { runSuspendCatching { val usedQuote = knownQuote ?: quote().getOrThrow() - if (!MoveToSparkMath.coversPayment(usedQuote, sparkRepo.state.value, amountSats)) { + val feeSats = feeAfterUpdateOrNull(bolt11, amountSats) ?: throw MoveToSparkError.UpdateFallsShort(amountSats) + if (!MoveToSparkMath.coversPayment(usedQuote, sparkRepo.state.value, amountSats, feeSats)) { throw MoveToSparkError.UpdateFallsShort(amountSats) } val outcome = move(usedQuote).getOrThrow().also(onMove) @@ -168,15 +171,24 @@ class MoveToSparkRepo internal constructor( /** * The fee Spark charges for paying [bolt11] once the spending balance is updated; Spark's service fee alone when - * Spark cannot price it before the moved balance arrives. + * nothing can price it. */ suspend fun estimateFeeAfterUpdate(bolt11: String, amountSats: ULong): ULong = withContext(bgDispatcher) { - sparkRepo.estimateFeeSats(bolt11, amountSats).getOrElse { + feeAfterUpdateOrNull(bolt11, amountSats) ?: SparkFees.serviceFeeSats(amountSats).also { Logger.debug("Fell back to Spark's service fee for an update payment", context = TAG) - SparkFees.serviceFeeSats(amountSats) } } + /** + * Spark's fee for paying [bolt11] once the spending balance is updated: its own quote, or, while Spark cannot price + * an amount above its balance, its service fee plus the routing fee the payment's route costs; null when neither + * prices it. + */ + private suspend fun feeAfterUpdateOrNull(bolt11: String, amountSats: ULong): ULong? = + sparkRepo.estimateFeeSats(bolt11, amountSats).getOrNull() + ?: lightningRepo.estimateLdkRoutingFeesForAmount(bolt11, amountSats).getOrNull() + ?.let { SparkFees.serviceFeeSats(amountSats).safe() + it.safe() } + /** * Quotes moving [targetSats], or everything the channels can send, to a new Spark invoice. * The amount leaves room for the routing fee, which the quote carries and the move caps the payment at. @@ -394,9 +406,9 @@ object MoveToSparkMath { fun needsUpdateToSend(amountSats: ULong, channels: List?, spark: SparkState): Boolean = amountSats > singleRailSendableSats(channels, spark) && amountSats <= combinedSendableSats(channels, spark) - /** Whether Spark can pay [amountSats], its service fee included, once [quote] has moved to it. */ - fun coversPayment(quote: MoveToSparkQuote, spark: SparkState, amountSats: ULong): Boolean = - spark.isUsable && SparkFees.sendableSats(spark.balanceSats.safe() + quote.amountSats.safe()) >= amountSats + /** Whether Spark can pay [amountSats] and its [feeSats] for the payment once [quote] has moved to it. */ + fun coversPayment(quote: MoveToSparkQuote, spark: SparkState, amountSats: ULong, feeSats: ULong): Boolean = + spark.isUsable && spark.balanceSats.safe() + quote.amountSats.safe() >= amountSats.safe() + feeSats.safe() /** The open channels in [after] that could send at least [MIN_MOVE_SATS] in [before] and no longer can. */ fun emptiedChannels(before: List, after: List?): List { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9b84c33f4a..ef137d149b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7803,7 +7803,7 @@ class AppViewModel @Inject constructor( val result = if (refusedBeforeUpdate != null) { Result.failure(refusedBeforeUpdate) } else { - updateSpendingBalanceIfNeeded(displayAmountSats) + updateSpendingBalanceIfNeeded(decodedInvoice.bolt11, displayAmountSats) }.fold( onSuccess = { sendLightning( @@ -7871,14 +7871,14 @@ class AppViewModel @Inject constructor( } /** - * Before a payment of [amountSats] that fits only across the channels and Spark, moves the channels' balance to + * Before a payment of [bolt11] for [amountSats] that fits only across the channels and Spark, moves the channels' balance to * Spark. Once the move settles, closes the channels it emptied in the background, even when the payment then fails. * A failure after the move leaves the funds in Spark. */ - private suspend fun updateSpendingBalanceIfNeeded(amountSats: ULong): Result { + private suspend fun updateSpendingBalanceIfNeeded(bolt11: String, amountSats: ULong): Result { if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) val channelsBefore = lightningRepo.lightningState.value.channels.toList() - return moveToSparkRepo.updateToSend(_sendUiState.value.sparkUpdateQuote, amountSats) { + return moveToSparkRepo.updateToSend(_sendUiState.value.sparkUpdateQuote, bolt11, amountSats) { closeChannelsEmptiedBy(it, channelsBefore) }.map { } } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 7ff5ef7243..e1c992e42d 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -37,6 +37,7 @@ import kotlin.test.assertTrue class MoveToSparkRepoTest : BaseUnitTest() { companion object { private const val INVOICE = "lnbcrt1spark" + private const val SPARK_FEE = 200uL } private val lightningRepo = mock() @@ -395,20 +396,45 @@ class MoveToSparkRepoTest : BaseUnitTest() { fun `update to send moves nothing when the quote and Spark's balance fall short of the payment`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 5_000uL) - val result = sut.updateToSend(quote, 60_000uL) + val result = sut.updateToSend(quote, INVOICE, 60_000uL) assertIs(result.exceptionOrNull()) verify(lightningRepo, never()).payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) } @Test - fun `a quote covers a payment once Spark can pay it with its service fee`() { + fun `update to send moves nothing when Spark's routing fee would leave the payment short`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 10_000uL) + whenever(sparkRepo.estimateFeeSats(INVOICE, 59_800uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 59_800uL)).thenReturn(Result.success(500uL)) + + val result = sut.updateToSend(quote, INVOICE, 59_800uL) + + assertIs(result.exceptionOrNull()) + verify(lightningRepo, never()).payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `update to send moves nothing when no fee for the payment can be priced`() = test { + sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)) + .thenReturn(Result.failure(SparkError.SendRefused(""))) + + val result = sut.updateToSend(quote, INVOICE, 60_000uL) + + assertIs(result.exceptionOrNull()) + verify(lightningRepo, never()).payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a quote covers a payment once Spark can pay it with its fee`() { val spark = SparkState(isReady = true, balanceSats = 10_000uL) - val sendable = SparkFees.sendableSats(10_000uL + quote.amountSats) + val total = 10_000uL + quote.amountSats - assertTrue(MoveToSparkMath.coversPayment(quote, spark, sendable)) - assertTrue(!MoveToSparkMath.coversPayment(quote, spark, sendable + 1uL)) - assertTrue(!MoveToSparkMath.coversPayment(quote, spark.copy(isExiting = true), 1_000uL)) + assertTrue(MoveToSparkMath.coversPayment(quote, spark, total - SPARK_FEE, SPARK_FEE)) + assertTrue(!MoveToSparkMath.coversPayment(quote, spark, total - SPARK_FEE + 1uL, SPARK_FEE)) + assertTrue(!MoveToSparkMath.coversPayment(quote, spark.copy(isExiting = true), 1_000uL, SPARK_FEE)) } @Test @@ -426,12 +452,13 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send moves the balance, then waits until Spark can pay`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.success(SPARK_FEE)) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) whenever(sparkRepo.canSend(60_000uL)).thenReturn(false, false, true) whenever(sparkRepo.refreshState()).thenReturn(Result.success(Unit)) - val updating = async { sut.updateToSend(quote, 60_000uL) } + val updating = async { sut.updateToSend(quote, INVOICE, 60_000uL) } nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) @@ -442,13 +469,14 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send fails as unsettled while the move is in flight`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.success(SPARK_FEE)) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) var moved: MoveToSparkOutcome? = null - val result = sut.updateToSend(quote, 60_000uL) { moved = it } + val result = sut.updateToSend(quote, INVOICE, 60_000uL) { moved = it } assertIs(result.exceptionOrNull()) assertIs(moved) @@ -458,13 +486,14 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send reports a settled move even when Spark never shows the balance`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.success(SPARK_FEE)) whenever( lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) ).thenReturn(Result.success("id")) whenever(sparkRepo.canSend(60_000uL)).thenReturn(false) whenever(sparkRepo.refreshState()).thenReturn(Result.success(Unit)) var moved: MoveToSparkOutcome? = null - val updating = async { sut.updateToSend(quote, 60_000uL) { moved = it } } + val updating = async { sut.updateToSend(quote, INVOICE, 60_000uL) { moved = it } } nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) @@ -473,8 +502,18 @@ class MoveToSparkRepoTest : BaseUnitTest() { } @Test - fun `the fee after an update falls back to Spark's service fee when Spark cannot price it yet`() = test { + fun `the fee after an update adds the routing fee to Spark's service fee when Spark cannot price it yet`() = test { + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)).thenReturn(Result.success(40uL)) + + assertEquals(SparkFees.serviceFeeSats(60_000uL) + 40uL, sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) + } + + @Test + fun `the fee after an update falls back to Spark's service fee when nothing can price it`() = test { whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)) + .thenReturn(Result.failure(SparkError.SendRefused(""))) assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index e632b84ea4..53d575f3ce 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20534,7 +20534,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) val moved = MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL) whenever(moveToSparkRepo.quote()).thenReturn(Result.success(quote)) - whenever(moveToSparkRepo.updateToSend(eq(quote), eq(60_000uL), any())).thenReturn(Result.success(moved)) + whenever(moveToSparkRepo.updateToSend(eq(quote), any(), eq(60_000uL), any())).thenReturn(Result.success(moved)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) setSendState( SendUiState( @@ -20551,7 +20551,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() inOrder(moveToSparkRepo, lightningRepo) { - verify(moveToSparkRepo).updateToSend(eq(quote), eq(60_000uL), onMove.capture()) + verify(moveToSparkRepo).updateToSend(eq(quote), any(), eq(60_000uL), onMove.capture()) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } onMove.firstValue(moved) @@ -20564,7 +20564,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val bolt11 = "lnbcrt1updatefails" whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setSendState( SendUiState( @@ -20590,7 +20590,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val bolt11 = "lnbcrt1movedunsettled" whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setSendState( SendUiState( @@ -20607,7 +20607,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() - verify(moveToSparkRepo).updateToSend(anyOrNull(), eq(60_000uL), onMove.capture()) + verify(moveToSparkRepo).updateToSend(anyOrNull(), any(), eq(60_000uL), onMove.capture()) onMove.firstValue(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL)) advanceUntilIdle() verify(closeChannelUseCase).closeEmptiedByMove(any()) @@ -20619,7 +20619,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) whenever(moveToSparkRepo.awaitSettled(inFlight)) .thenReturn(Result.success(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL))) @@ -20637,7 +20637,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() - verify(moveToSparkRepo).updateToSend(anyOrNull(), eq(60_000uL), onMove.capture()) + verify(moveToSparkRepo).updateToSend(anyOrNull(), any(), eq(60_000uL), onMove.capture()) onMove.firstValue(inFlight) advanceUntilIdle() verify(moveToSparkRepo).awaitSettled(inFlight) @@ -20687,7 +20687,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success("update-attempt")) whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), eq(request.amount.atomic), any())) + whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(request.amount.atomic), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( @@ -20758,7 +20758,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) verify(pendingPaymentRepo, never()).track(any()) verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) @@ -20789,7 +20789,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.ResetConfirm, awaitItem()) } assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) } @@ -20816,7 +20816,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.ResetConfirm, awaitItem()) } assertEquals(raised, sut.sendUiState.value.sparkUpdateQuote) - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) } @Test @@ -20840,7 +20840,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) } @Test From 2de3e680e14215eeb479028df599752f29cb7e50 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 02:56:02 +0100 Subject: [PATCH 06/23] chore: wrap long lines in the update fee check Verified: just format, just compile, just test, just lint --- app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt | 3 ++- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index db5a0e7a7c..7450fd553d 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -150,7 +150,8 @@ class MoveToSparkRepo internal constructor( withContext(bgDispatcher) { runSuspendCatching { val usedQuote = knownQuote ?: quote().getOrThrow() - val feeSats = feeAfterUpdateOrNull(bolt11, amountSats) ?: throw MoveToSparkError.UpdateFallsShort(amountSats) + val feeSats = feeAfterUpdateOrNull(bolt11, amountSats) + ?: throw MoveToSparkError.UpdateFallsShort(amountSats) if (!MoveToSparkMath.coversPayment(usedQuote, sparkRepo.state.value, amountSats, feeSats)) { throw MoveToSparkError.UpdateFallsShort(amountSats) } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index ef137d149b..394944ff3b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7871,9 +7871,9 @@ class AppViewModel @Inject constructor( } /** - * Before a payment of [bolt11] for [amountSats] that fits only across the channels and Spark, moves the channels' balance to - * Spark. Once the move settles, closes the channels it emptied in the background, even when the payment then fails. - * A failure after the move leaves the funds in Spark. + * Before a payment of [bolt11] for [amountSats] that fits only across the channels and Spark, moves the channels' + * balance to Spark. Once the move settles, closes the channels it emptied in the background, even when the payment + * then fails. A failure after the move leaves the funds in Spark. */ private suspend fun updateSpendingBalanceIfNeeded(bolt11: String, amountSats: ULong): Result { if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) From af59005ea8969ba252cabe8156d24b1985abb0bb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 03:02:24 +0100 Subject: [PATCH 07/23] fix: let tests dismiss the update modal in every state Verified: just format, just compile, just test, just lint --- .../to/bitkit/ui/sheets/MoveToSparkSheet.kt | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt index 49cef78d41..a0ed059c79 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt @@ -46,6 +46,9 @@ import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent import to.bitkit.ui.utils.withAccentBoldBright +/** On every state's dismiss button, so tests can close the modal in whichever state it opened. */ +private const val DISMISS_TAG = "UpdateSpendingBalanceDismiss" + /** * The Update Spending Balance modal: quotes moving the channels' balance to Spark when it opens, moves it on Update and * reports the outcome in place, from Spending Balance Updated to the states that need another step. @@ -138,7 +141,11 @@ private fun Done( testTag = "MoveToSparkInFlight", modifier = modifier, ) { - PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + PrimaryButton( + stringResource(R.string.common__ok), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) + ) } return } @@ -154,7 +161,7 @@ private fun Done( SecondaryButton( stringResource(R.string.common__later), onClick = onDismiss, - modifier = Modifier.weight(1f) + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) ) PrimaryButton( stringResource(R.string.lightning__move_to_spark__move_rest), @@ -205,10 +212,18 @@ private fun TooLarge( modifier = modifier, ) { if (smallerSats == null) { - PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + PrimaryButton( + stringResource(R.string.common__ok), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) + ) return@Modal } - SecondaryButton(stringResource(R.string.common__cancel), onClick = onDismiss, modifier = Modifier.weight(1f)) + SecondaryButton( + stringResource(R.string.common__cancel), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) + ) PrimaryButton( stringResource(R.string.lightning__move_to_spark__move_half), onClick = { onQuote(smallerSats) }, @@ -239,10 +254,18 @@ private fun Failed( modifier = modifier, ) { if (failure == MoveToSparkFailure.NOTHING_TO_MOVE) { - PrimaryButton(stringResource(R.string.common__ok), onClick = onDismiss, modifier = Modifier.weight(1f)) + PrimaryButton( + stringResource(R.string.common__ok), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) + ) return@Modal } - SecondaryButton(stringResource(R.string.common__cancel), onClick = onDismiss, modifier = Modifier.weight(1f)) + SecondaryButton( + stringResource(R.string.common__cancel), + onClick = onDismiss, + modifier = Modifier.weight(1f).testTag(DISMISS_TAG) + ) PrimaryButton( stringResource(R.string.common__try_again), onClick = { onQuote(null) }, From b5328f88dd278af9179570a2ac084f95c743ac56 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 03:35:53 +0100 Subject: [PATCH 08/23] fix: show the update fee before any spending balance move Quotes LNURL-pay updates before confirm, releases payment requests on any update failure, keeps repeated confirm resets observable, and stops a send whose update fee was not shown or rose since. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 18 +- .../screens/wallets/send/SendConfirmScreen.kt | 19 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 41 ++++- .../repositories/MoveToSparkRepoTest.kt | 7 + .../wallets/send/SendConfirmResetTest.kt | 21 +++ .../viewmodels/AppViewModelSendFlowTest.kt | 174 +++++++++++++++++- 6 files changed, 248 insertions(+), 32 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmResetTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 7450fd553d..81147f8f16 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -135,27 +135,26 @@ class MoveToSparkRepo internal constructor( /** * Updates the spending balance for a payment of [amountSats]: moves the channels' balance to Spark with - * [knownQuote], or a new quote, and waits until Spark can pay the amount. A move still in flight, or a balance + * [quote], whose fee the user saw, and waits until Spark can pay the amount. A move still in flight, or a balance * Spark does not show in time, fails with [MoveToSparkError.UpdateUnsettled]; the funds then reach Spark on their * own. [onMove] gets the move's outcome as soon as the move returns, before the wait. A quote whose amount, with * Spark's balance, would not cover the payment of [bolt11] and Spark's fee for it, or a fee nothing can price, * fails with [MoveToSparkError.UpdateFallsShort] before any move. */ suspend fun updateToSend( - knownQuote: MoveToSparkQuote?, + quote: MoveToSparkQuote, bolt11: String, amountSats: ULong, onMove: (MoveToSparkOutcome) -> Unit = {}, ): Result = withContext(bgDispatcher) { runSuspendCatching { - val usedQuote = knownQuote ?: quote().getOrThrow() val feeSats = feeAfterUpdateOrNull(bolt11, amountSats) ?: throw MoveToSparkError.UpdateFallsShort(amountSats) - if (!MoveToSparkMath.coversPayment(usedQuote, sparkRepo.state.value, amountSats, feeSats)) { + if (!MoveToSparkMath.coversPayment(quote, sparkRepo.state.value, amountSats, feeSats)) { throw MoveToSparkError.UpdateFallsShort(amountSats) } - val outcome = move(usedQuote).getOrThrow().also(onMove) + val outcome = move(quote).getOrThrow().also(onMove) val moved = outcome as? MoveToSparkOutcome.Moved ?: throw MoveToSparkError.UpdateUnsettled() val shown = withTimeoutOrNull(SPARK_BALANCE_WAIT) { while (!sparkRepo.canSend(amountSats)) { @@ -172,10 +171,10 @@ class MoveToSparkRepo internal constructor( /** * The fee Spark charges for paying [bolt11] once the spending balance is updated; Spark's service fee alone when - * nothing can price it. + * nothing can price it, or when there is no invoice yet, as for an LNURL before its callback. */ - suspend fun estimateFeeAfterUpdate(bolt11: String, amountSats: ULong): ULong = withContext(bgDispatcher) { - feeAfterUpdateOrNull(bolt11, amountSats) ?: SparkFees.serviceFeeSats(amountSats).also { + suspend fun estimateFeeAfterUpdate(bolt11: String?, amountSats: ULong): ULong = withContext(bgDispatcher) { + bolt11?.let { feeAfterUpdateOrNull(it, amountSats) } ?: SparkFees.serviceFeeSats(amountSats).also { Logger.debug("Fell back to Spark's service fee for an update payment", context = TAG) } } @@ -455,6 +454,9 @@ sealed class MoveToSparkError(message: String, cause: Throwable? = null) : AppEr class UpdateFallsShort(val amountSats: ULong) : MoveToSparkError("An update would not cover a payment of '$amountSats' sats") + /** The update's fee is new or above the one the user saw, so nothing moved until they see it. */ + class UpdateFeeUnseen : MoveToSparkError("The update fee changed since the user saw it") + /** The update moved the balance, but Spark cannot pay with it yet: the move or Spark's balance has not settled. */ class UpdateUnsettled : MoveToSparkError("The update to Spark has not settled yet") diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 95147f78fa..2072ed281b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -114,6 +114,18 @@ private val EXPIRY_REFRESH_INTERVAL = 60.seconds private const val PROVIDER_KEY_LENGTH = 12 const val SEND_CONFIRM_RESET_RESULT_KEY = "SEND_CONFIRM_RESET_RESULT_KEY" +/** + * Calls [onReset] for each reset [SEND_CONFIRM_RESET_RESULT_KEY] carries. The key goes back to false rather than + * away, since removing it detaches this collector from any later reset. + */ +internal suspend fun SavedStateHandle.collectConfirmResets(onReset: () -> Unit) { + getStateFlow(SEND_CONFIRM_RESET_RESULT_KEY, false).collect { + if (!it) return@collect + onReset() + set(SEND_CONFIRM_RESET_RESULT_KEY, false) + } +} + @Composable fun SendConfirmScreen( savedStateHandle: SavedStateHandle, @@ -154,12 +166,7 @@ fun SendConfirmScreen( } LaunchedEffect(savedStateHandle) { - savedStateHandle.getStateFlow(SEND_CONFIRM_RESET_RESULT_KEY, false) - .collect { - if (!it) return@collect - isLoading = false - savedStateHandle.remove(SEND_CONFIRM_RESET_RESULT_KEY) - } + savedStateHandle.collectConfirmResets { isLoading = false } } // Confirm with pin or bio if required diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 394944ff3b..09c3f92681 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6458,6 +6458,7 @@ class AppViewModel @Inject constructor( if (quickPayHandled) return navigateToSendRoute(fromMainScanner, SendRoute.Confirm, SendEffect.NavigateToConfirm, walletGeneration) + estimateLightningRoutingFeesIfNeeded(walletGeneration) return } @@ -7800,10 +7801,11 @@ class AppViewModel @Inject constructor( ?.takeIf { moveToSparkRepo.needsUpdateToSend(displayAmountSats) } ?.let { paykitPaymentRequestRepo.ensurePaymentAllowed(it).exceptionOrNull() } var authorizationError: Throwable? = refusedBeforeUpdate + var updateFailed = false val result = if (refusedBeforeUpdate != null) { Result.failure(refusedBeforeUpdate) } else { - updateSpendingBalanceIfNeeded(decodedInvoice.bolt11, displayAmountSats) + updateSpendingBalanceIfNeeded(decodedInvoice.bolt11, displayAmountSats).onFailure { updateFailed = true } }.fold( onSuccess = { sendLightning( @@ -7842,7 +7844,7 @@ class AppViewModel @Inject constructor( ) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } }.onFailure { error -> - if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest != null)) { + if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest != null, updateFailed)) { val pendingHash = (error as? PaymentPendingException)?.paymentHash ?: paymentHash proofRequest = null Logger.info("Lightning payment pending", context = TAG) @@ -7858,6 +7860,11 @@ class AppViewModel @Inject constructor( finishManualAllowancePayment(allowanceAttemptId, succeeded = false) createdMetadataPaymentId?.let { preActivityMetadataRepo.deletePreActivityMetadata(it) } lnurlComment?.let { activityRepo.clearPendingLightningMessage(paymentHash) } + if (error is MoveToSparkError.UpdateFeeUnseen) { + Logger.info("Stopped a payment to show the update fee", context = TAG) + setSendEffect(SendEffect.ResetConfirm) + return@onFailure + } Logger.error("Error sending lightning payment", error, context = TAG) val failure = when (error) { is LightningPaymentFailedError -> error.reason.toSendFailureDetails(context, error.paymentRequest) @@ -7873,12 +7880,20 @@ class AppViewModel @Inject constructor( /** * Before a payment of [bolt11] for [amountSats] that fits only across the channels and Spark, moves the channels' * balance to Spark. Once the move settles, closes the channels it emptied in the background, even when the payment - * then fails. A failure after the move leaves the funds in Spark. + * then fails. A failure after the move leaves the funds in Spark. Moves nothing and fails with + * [MoveToSparkError.UpdateFeeUnseen] when no update fee was shown, or a fresh quote's fee is above it, keeping the + * fresh quote to show. */ private suspend fun updateSpendingBalanceIfNeeded(bolt11: String, amountSats: ULong): Result { if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) + val shown = _sendUiState.value.sparkUpdateQuote + val fresh = moveToSparkRepo.quote().getOrElse { return Result.failure(it) } + if (shown == null || fresh.feeSats > shown.feeSats) { + _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } + return Result.failure(MoveToSparkError.UpdateFeeUnseen()) + } val channelsBefore = lightningRepo.lightningState.value.channels.toList() - return moveToSparkRepo.updateToSend(_sendUiState.value.sparkUpdateQuote, bolt11, amountSats) { + return moveToSparkRepo.updateToSend(fresh, bolt11, amountSats) { closeChannelsEmptiedBy(it, channelsBefore) }.map { } } @@ -7927,11 +7942,12 @@ class AppViewModel @Inject constructor( paymentHash: String, error: Throwable, isPaymentRequest: Boolean, + updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false else if !isPaymentRequest -> true - // A failed spending balance update happens before the invoice is paid, so nothing was sent. - is LightningPaymentFailedError, is MoveToSparkError -> { + // Any failed spending balance update happens before the invoice is paid, so nothing was sent. + else if updateFailed || error is LightningPaymentFailedError -> { paykitPaymentProofRepo.failLightningPayment(paymentHash) true } @@ -8611,7 +8627,16 @@ class AppViewModel @Inject constructor( if (currentState.payMethod != SendMethod.LIGHTNING) return // A Spark leg pays the contact's other endpoint, so its fee is the leg's, never the retained invoice's. if (currentState.routedPaykitRoute?.serviceLeg != null) return - val decodedInvoice = currentState.decodedInvoice ?: return + val decodedInvoice = currentState.decodedInvoice + if (decodedInvoice == null) { + // An LNURL's invoice comes only with the swipe, so its update is quoted before the callback. + if (currentState.lnurl is LnurlParams.LnurlPay && currentState.activePaykitSwapRoute == null && + moveToSparkRepo.needsUpdateToSend(currentState.amount) + ) { + estimateSparkUpdateFees(null, currentState.amount, generation, walletGeneration) + } + return + } val payAmount = decodedInvoice.amountSatoshis.takeIf { it > 0uL } ?: currentState.amount if (moveToSparkRepo.needsUpdateToSend(payAmount)) { estimateSparkUpdateFees(decodedInvoice.bolt11, payAmount, generation, walletGeneration) @@ -8638,7 +8663,7 @@ class AppViewModel @Inject constructor( /** Quotes the spending balance update a payment of [payAmount] needs, and Spark's fee for the payment after it. */ private suspend fun estimateSparkUpdateFees( - bolt11: String, + bolt11: String?, payAmount: ULong, generation: Long, walletGeneration: Long?, diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index e1c992e42d..098b790ed6 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -518,6 +518,13 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) } + @Test + fun `the fee after an update is Spark's service fee before there is an invoice`() = test { + assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(null, 60_000uL)) + verify(sparkRepo, never()).estimateFeeSats(any(), any()) + verify(lightningRepo, never()).estimateLdkRoutingFeesForAmount(any(), any()) + } + private fun channel(id: String, sendableSats: ULong) = createChannelDetails().copy( channelId = id, isUsable = true, diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmResetTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmResetTest.kt new file mode 100644 index 0000000000..f15d37d67b --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmResetTest.kt @@ -0,0 +1,21 @@ +package to.bitkit.ui.screens.wallets.send + +import androidx.lifecycle.SavedStateHandle +import kotlinx.coroutines.launch +import org.junit.Test +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +class SendConfirmResetTest : BaseUnitTest() { + @Test + fun `every reset of the confirm screen reaches its collector`() = test { + val savedStateHandle = SavedStateHandle() + var resets = 0 + backgroundScope.launch { savedStateHandle.collectConfirmResets { resets++ } } + + savedStateHandle[SEND_CONFIRM_RESET_RESULT_KEY] = true + savedStateHandle[SEND_CONFIRM_RESET_RESULT_KEY] = true + + assertEquals(2, resets) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 53d575f3ce..979270ca42 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20564,7 +20564,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val bolt11 = "lnbcrt1updatefails" whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setSendState( SendUiState( @@ -20590,7 +20590,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val bolt11 = "lnbcrt1movedunsettled" whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setSendState( SendUiState( @@ -20607,7 +20607,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() - verify(moveToSparkRepo).updateToSend(anyOrNull(), any(), eq(60_000uL), onMove.capture()) + verify(moveToSparkRepo).updateToSend(any(), any(), eq(60_000uL), onMove.capture()) onMove.firstValue(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL)) advanceUntilIdle() verify(closeChannelUseCase).closeEmptiedByMove(any()) @@ -20619,7 +20619,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(60_000uL), any())) + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(60_000uL), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) whenever(moveToSparkRepo.awaitSettled(inFlight)) .thenReturn(Result.success(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL))) @@ -20637,7 +20637,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() - verify(moveToSparkRepo).updateToSend(anyOrNull(), any(), eq(60_000uL), onMove.capture()) + verify(moveToSparkRepo).updateToSend(any(), any(), eq(60_000uL), onMove.capture()) onMove.firstValue(inFlight) advanceUntilIdle() verify(moveToSparkRepo).awaitSettled(inFlight) @@ -20687,7 +20687,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success("update-attempt")) whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) - whenever(moveToSparkRepo.updateToSend(anyOrNull(), any(), eq(request.amount.atomic), any())) + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(request.amount.atomic), any())) .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( @@ -20714,6 +20714,97 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitAllowanceRepo).finishManualPayment("update-attempt", false, null) } + @Test + fun `a payment request whose update fails with any error is released, never left pending`() = test { + val request = paymentRequest() + val bolt11 = "lnbcrt1updatenodeerror" + val paymentHash = "010203" + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever( + paykitPaymentProofRepo.prepare( + request, + MethodId.Bolt11.rawValue, + "bitkit", + PaykitPaymentProofKind.Lightning + ) + ) + .doSuspendableAnswer { + setSendState( + sut.sendUiState.value.copy(decodedInvoice = lightningInvoice(bolt11, request.amount.atomic)) + ) + Result.success(Unit) + } + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitAllowanceRepo.beginManualPayment(eq(request), any(), anyOrNull())) + .thenReturn(Result.success("node-error-attempt")) + whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + val error = NodeException.InsufficientFunds("refused") + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(request.amount.atomic), any())) + .thenReturn(Result.failure(error)) + whenever(paykitPaymentProofRepo.failLightningPayment(paymentHash, error)).thenReturn(false) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = bolt11, + amount = request.amount.atomic, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(pendingPaymentRepo, never()).track(any()) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).cancelPreparation(request) + verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any()) + verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(paykitAllowanceRepo).finishManualPayment("node-error-attempt", false, null) + } + + @Test + fun `an lnurl payment that needs the update shows its fee and pays on the first swipe`() = test { + val input = "lnurl1updatefirstswipe" + val bolt11 = "lnbcrt1lnurlupdate" + val data = + LnurlPayData(input, "https://example.com/callback", 1_000_000uL, 1_000_000uL, "[]", null, false, null) + whenever(coreService.decode(input)).thenReturn(Scanner.LnurlPay(data)) + whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + whenever(moveToSparkRepo.estimateFeeAfterUpdate(null, 1_000uL)).thenReturn(3uL) + whenever(lightningRepo.fetchLnurlInvoice(data, 1_000_000uL, null)) + .thenReturn(Result.success(lightningInvoice(bolt11, 1_000uL))) + whenever(moveToSparkRepo.updateToSend(eq(UPDATE_QUOTE), any(), eq(1_000uL), any())) + .thenReturn(Result.success(MoveToSparkOutcome.Moved(1_000uL, feeSats = 9uL))) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) + sut.setIsAuthenticated(true) + + sut.onScanResult(input) + advanceUntilIdle() + + assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) + assertEquals(3L, sut.sendUiState.value.lightningFeeSats) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertNotEquals(SendEffect.ResetConfirm, awaitItem()) + cancelAndIgnoreRemainingEvents() + } + verify(moveToSparkRepo).updateToSend(eq(UPDATE_QUOTE), any(), eq(1_000uL), any()) + verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) + } + @Test fun `a refused payment request moves nothing and closes nothing`() = test { val request = paymentRequest() @@ -20758,7 +20849,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) verify(pendingPaymentRepo, never()).track(any()) verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) @@ -20789,7 +20880,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.ResetConfirm, awaitItem()) } assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) } @@ -20816,7 +20907,70 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.ResetConfirm, awaitItem()) } assertEquals(raised, sut.sendUiState.value.sparkUpdateQuote) - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + } + + @Test + fun `an update needed only by send time moves nothing and shows its fee`() = test { + val bolt11 = "lnbcrt1unseenatsend" + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(60_000uL), any())) + .thenReturn(Result.success(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL))) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(false, true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + expectNoEvents() + } + assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(pendingPaymentRepo, never()).track(any()) + } + + @Test + fun `an update fee that rose by send time moves nothing and shows the new fee`() = test { + val bolt11 = "lnbcrt1feeroseatsend" + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(60_000uL), any())) + .thenReturn(Result.success(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL))) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success("010203")) + val raised = UPDATE_QUOTE.copy(feeSats = UPDATE_QUOTE.feeSats + 1uL) + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE), Result.success(raised)) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + expectNoEvents() + } + assertEquals(raised, sut.sendUiState.value.sparkUpdateQuote) + verify(moveToSparkRepo, times(2)).quote() + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(pendingPaymentRepo, never()).track(any()) } @Test @@ -20840,7 +20994,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } - verify(moveToSparkRepo, never()).updateToSend(anyOrNull(), any(), any(), any()) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) } @Test From ec914541514a728a57065d033b4d5d0a65e92eb7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 03:47:29 +0100 Subject: [PATCH 09/23] fix: price an update payment with spark's own quote Spark's prepare prices any amount whatever its balance, so the LDK routing fallback could never price a payment that needs an update. Also lists the new journeys' pending iOS port. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 7 ++----- .../bitkit/repositories/MoveToSparkRepoTest.kt | 18 ++---------------- journeys/README.md | 1 + 3 files changed, 5 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 81147f8f16..3d40e56815 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -180,14 +180,11 @@ class MoveToSparkRepo internal constructor( } /** - * Spark's fee for paying [bolt11] once the spending balance is updated: its own quote, or, while Spark cannot price - * an amount above its balance, its service fee plus the routing fee the payment's route costs; null when neither - * prices it. + * Spark's fee for paying [bolt11] once the spending balance is updated, from Spark's own quote, which prices the + * amount whatever its balance; null when Spark cannot price it. */ private suspend fun feeAfterUpdateOrNull(bolt11: String, amountSats: ULong): ULong? = sparkRepo.estimateFeeSats(bolt11, amountSats).getOrNull() - ?: lightningRepo.estimateLdkRoutingFeesForAmount(bolt11, amountSats).getOrNull() - ?.let { SparkFees.serviceFeeSats(amountSats).safe() + it.safe() } /** * Quotes moving [targetSats], or everything the channels can send, to a new Spark invoice. diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 098b790ed6..9f6365cebe 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -405,8 +405,7 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `update to send moves nothing when Spark's routing fee would leave the payment short`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 10_000uL) - whenever(sparkRepo.estimateFeeSats(INVOICE, 59_800uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) - whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 59_800uL)).thenReturn(Result.success(500uL)) + whenever(sparkRepo.estimateFeeSats(INVOICE, 59_800uL)).thenReturn(Result.success(500uL)) val result = sut.updateToSend(quote, INVOICE, 59_800uL) @@ -418,8 +417,6 @@ class MoveToSparkRepoTest : BaseUnitTest() { fun `update to send moves nothing when no fee for the payment can be priced`() = test { sparkState.value = SparkState(isReady = true, balanceSats = 20_000uL) whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) - whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)) - .thenReturn(Result.failure(SparkError.SendRefused(""))) val result = sut.updateToSend(quote, INVOICE, 60_000uL) @@ -502,18 +499,8 @@ class MoveToSparkRepoTest : BaseUnitTest() { } @Test - fun `the fee after an update adds the routing fee to Spark's service fee when Spark cannot price it yet`() = test { + fun `the fee after an update falls back to Spark's service fee when Spark cannot price it`() = test { whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) - whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)).thenReturn(Result.success(40uL)) - - assertEquals(SparkFees.serviceFeeSats(60_000uL) + 40uL, sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) - } - - @Test - fun `the fee after an update falls back to Spark's service fee when nothing can price it`() = test { - whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) - whenever(lightningRepo.estimateLdkRoutingFeesForAmount(INVOICE, 60_000uL)) - .thenReturn(Result.failure(SparkError.SendRefused(""))) assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(INVOICE, 60_000uL)) } @@ -522,7 +509,6 @@ class MoveToSparkRepoTest : BaseUnitTest() { fun `the fee after an update is Spark's service fee before there is an invoice`() = test { assertEquals(SparkFees.serviceFeeSats(60_000uL), sut.estimateFeeAfterUpdate(null, 60_000uL)) verify(sparkRepo, never()).estimateFeeSats(any(), any()) - verify(lightningRepo, never()).estimateLdkRoutingFeesForAmount(any(), any()) } private fun channel(id: String, sendableSats: ULong) = createChannelDetails().copy( diff --git a/journeys/README.md b/journeys/README.md index 534c2f0a09..71872a67b1 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -172,6 +172,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `send/own-invoice-guard.xml` | not ported — iOS has no own-invoice guard | | `send/recovery-pin-system-back.xml` | not ported — iOS has no system Back button, and `SendPinScreen` already answers cancel in `onDisappear` | | `send/retry-original-dialog-style.xml` | not ported — iOS shows the two Retry original payment steps as native alerts | +| `send/update-spending-balance-payment.xml`, `transfer/move-to-spark.xml` | port pending — the iOS Update Spending Balance modal and combined payment are not built yet; port both journeys with it, after synonymdev/bitkit-ios#1355 | | `send/onchain-connecting-view.xml` | ported with another route — on iOS the LDK Debug Restart keeps the node in the running state and a launch shows home only once the node runs, so the iOS journey opens Send while the node is still starting | | `send/prepared-fee-recovery.md` | Same four manual fault cases and file on both platforms; the recipe records original-send versus replacement fee retention and iOS Max/identity-flow adaptations. These faults are not journey capabilities. | | `settings/electrum-server-error-toasts.xml` | not ported — iOS still shows one generic message for every manual Electrum connect failure | From 76b903e1c4e42674906c9b1410a53c65a4172727 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 14:19:32 +0100 Subject: [PATCH 10/23] fix: show the update fee before the swipe Verified: just format, compile, test, lint; SendConfirmUpdateFeeTest fails without the fix --- .../to/bitkit/ext/PaymentFailureReasonExt.kt | 7 +- .../screens/wallets/send/SendConfirmScreen.kt | 4 ++ .../bitkit/ext/PaymentFailureReasonExtTest.kt | 9 +++ .../wallets/send/SendConfirmUpdateFeeTest.kt | 68 +++++++++++++++++++ .../send/update-spending-balance-payment.xml | 2 +- 5 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt diff --git a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt index fa3790a8aa..fe8e3ac87f 100644 --- a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt @@ -5,6 +5,7 @@ import breez_sdk_spark.SdkException import org.lightningdevkit.ldknode.PaymentFailureReason import to.bitkit.R import to.bitkit.models.SendFailureDetails +import to.bitkit.repositories.MoveToSparkError import to.bitkit.services.SparkError import to.bitkit.utils.LdkError @@ -55,8 +56,10 @@ fun Throwable.toSendFailureMessage(context: Context): String { return context.getString(R.string.wallet__payment_restored_invoice) } - // Spark and its SDK speak in English developer messages; they go to the log, the user gets the existing copy. - if (this is LdkError || this is SparkError || this is SdkException || rawMessage.isBlank() || + // Spark, its SDK and the spending balance update speak in English developer messages; they go to the log, the + // user gets the existing copy. + if (this is LdkError || this is SparkError || this is SdkException || this is MoveToSparkError || + rawMessage.isBlank() || rawMessage.looksInternalPaymentError() ) { return fallbackMessage diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 2072ed281b..4e5b32d2a8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -374,6 +374,10 @@ private fun ContentRunning( onSwipeToConfirm: () -> Unit = {}, ) { var showDetails by rememberSaveable(initialShowDetails) { mutableStateOf(initialShowDetails) } + // The update fee sits in the details: each new quote opens them, so no swipe pays a fee the user has not seen. + LaunchedEffect(uiState.sparkUpdateQuote) { + if (uiState.sparkUpdateQuote != null) showDetails = true + } val swipeProgress = remember { mutableFloatStateOf(0f) } val isPreparing = preparingRequest != null val isLnurlPay = !isPreparing && uiState.paysLnurl diff --git a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt index b7c2f92e9e..a61cfb8746 100644 --- a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt @@ -9,6 +9,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.models.SendFailureDetails +import to.bitkit.repositories.MoveToSparkError import to.bitkit.services.SparkError import to.bitkit.utils.LdkError import kotlin.test.assertEquals @@ -71,6 +72,14 @@ class PaymentFailureReasonExtTest { assertEquals(message, SdkException.Generic("insufficient funds").toSendFailureMessage(context)) } + @Test + fun `a failed spending balance update shows the existing payment failure copy`() { + val message = "Generic payment failed" + whenever(context.getString(R.string.wallet__payment_failed_description)).thenReturn(message) + + assertEquals(message, MoveToSparkError.UpdateFallsShort(50_000uL).toSendFailureMessage(context)) + } + @Test fun `payment failure reason compact failure types use lower camel case`() { assertEquals("routeNotFound", PaymentFailureReason.ROUTE_NOT_FOUND.toCompactFailureType()) diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt new file mode 100644 index 0000000000..861569ae39 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt @@ -0,0 +1,68 @@ +package to.bitkit.ui.screens.wallets.send + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import com.synonym.bitkitcore.LightningInvoice +import com.synonym.bitkitcore.NetworkType +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.repositories.MoveToSparkQuote +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.SendMethod +import to.bitkit.viewmodels.SendUiState + +@RunWith(RobolectricTestRunner::class) +class SendConfirmUpdateFeeTest { + @get:Rule + val composeRule = createComposeRule() + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `a payment that needs an update shows its fee without opening the details`() { + composeRule.setContent { + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { + SendConfirmContent( + uiState = SendUiState( + amount = 50_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = INVOICE, + lightningFeeSats = 12, + sparkUpdateQuote = MoveToSparkQuote("lnbcrt1spark", amountSats = 29_967uL, feeSats = 2uL), + ), + isNodeRunning = true, + isLoading = false, + showBiometrics = false, + initialShowDetails = false, + modifier = Modifier.sheetHeight() + ) + } + } + } + + composeRule.onNodeWithTag("ReviewUpdateFee").assertIsDisplayed() + } + + private companion object { + val INVOICE = LightningInvoice( + bolt11 = "lnbcrt1p5frwyedq2gf5hg6mfwsnp4qdkkcte90vc7c5z6z72uu5p2schwkmlx9j704tuwm2z59wfgku46xpp56yfmwmfxtl", + paymentHash = ByteArray(0), + amountSatoshis = 50_000u, + timestampSeconds = 0u, + expirySeconds = 3600u, + isExpired = false, + networkType = NetworkType.REGTEST, + payeeNodeId = null, + description = "Coffee", + ) + } +} diff --git a/journeys/send/update-spending-balance-payment.xml b/journeys/send/update-spending-balance-payment.xml index 774015f4cf..677392cd3e 100644 --- a/journeys/send/update-spending-balance-payment.xml +++ b/journeys/send/update-spending-balance-payment.xml @@ -14,7 +14,7 @@ On the receiving side, create a 50 000-sat Lightning invoice and open it on the sending wallet with a lightning: deep link - Verify the Confirm screen (testTag "SendConfirm") shows 50 000 sats, then tap Show Details (testTag "SendConfirmToggleDetails") + Verify the Confirm screen (testTag "SendConfirm") shows 50 000 sats with its details open on their own (Hide Details, testTag "SendConfirmToggleDetails") Verify the fee row shows the payment's own fee and the "Update fee" row (testTag "ReviewUpdateFee") shows an amount, without "up to", and that no "Route" row shows Swipe to pay (testTag "GRAB"); the payment is over half of the Spending balance, so verify the "Are You Sure?" dialog warns about sending over 50% of the balance and tap "Yes, Send" Verify the Bitcoin Sent screen (testTag "SendSuccess") shows 50 000 From 148892dd2ddad988988bc214dafc9e356c978ec3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 16:25:02 +0100 Subject: [PATCH 11/23] fix: wait for the update quote before the swipe Verified: just format, compile, test, lint --- .../screens/wallets/send/SendConfirmScreen.kt | 3 ++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 19 +++++++++----- .../viewmodels/AppViewModelSendFlowTest.kt | 26 +++++++++++++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 4e5b32d2a8..891011fcfa 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -374,7 +374,7 @@ private fun ContentRunning( onSwipeToConfirm: () -> Unit = {}, ) { var showDetails by rememberSaveable(initialShowDetails) { mutableStateOf(initialShowDetails) } - // The update fee sits in the details: each new quote opens them, so no swipe pays a fee the user has not seen. + // The update fee sits in the details: each new quote opens them, and the swipe waits for the quote. LaunchedEffect(uiState.sparkUpdateQuote) { if (uiState.sparkUpdateQuote != null) showDetails = true } @@ -555,6 +555,7 @@ private fun ContentRunning( private fun SendUiState.canSwipeToPay() = isAmountInputValid && !isFundingSourceLoading && isHardwareFeeReady && + !isSparkUpdateQuoting && !(payMethod == SendMethod.ONCHAIN && onchainFeeUi.isLoading) @Composable diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 09c3f92681..b84ee11547 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8668,12 +8668,17 @@ class AppViewModel @Inject constructor( generation: Long, walletGeneration: Long?, ) { - val quote = moveToSparkRepo.quote().getOrNull() - val fee = moveToSparkRepo.estimateFeeAfterUpdate(bolt11, payAmount) - requireCurrentPaymentPreparation(walletGeneration) - _sendUiState.update { - if (generation != sendStateGeneration) return@update it - it.copy(lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), sparkUpdateQuote = quote) + _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(isSparkUpdateQuoting = true) } + try { + val quote = moveToSparkRepo.quote().getOrNull() + val fee = moveToSparkRepo.estimateFeeAfterUpdate(bolt11, payAmount) + requireCurrentPaymentPreparation(walletGeneration) + _sendUiState.update { + if (generation != sendStateGeneration) return@update it + it.copy(lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), sparkUpdateQuote = quote) + } + } finally { + _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(isSparkUpdateQuoting = false) } } } @@ -10358,6 +10363,8 @@ data class SendUiState( val lightningFeeSats: Long? = null, /** The spending balance update a Lightning payment that fits only across the channels and Spark runs first. */ val sparkUpdateQuote: MoveToSparkQuote? = null, + /** True while the update a Lightning payment needs is quoted, so no swipe pays an update fee not yet shown. */ + val isSparkUpdateQuoting: Boolean = false, val estimatedRoutingFee: ULong = 0uL, val lastLightningFee: Long = 0L, val contactPaymentProfile: PubkyProfile? = null, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 979270ca42..76cb11734a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20772,6 +20772,32 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitAllowanceRepo).finishManualPayment("node-error-attempt", false, null) } + @Test + fun `a payment that needs the update is quoting until its update quote arrives`() = test { + val input = "lnurl1updatequoting" + val data = + LnurlPayData(input, "https://example.com/callback", 1_000_000uL, 1_000_000uL, "[]", null, false, null) + val quoted = CompletableDeferred() + whenever(coreService.decode(input)).thenReturn(Scanner.LnurlPay(data)) + whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { + quoted.await() + Result.success(UPDATE_QUOTE) + } + whenever(moveToSparkRepo.estimateFeeAfterUpdate(null, 1_000uL)).thenReturn(3uL) + sut.setIsAuthenticated(true) + + sut.onScanResult(input) + advanceUntilIdle() + + assertTrue(sut.sendUiState.value.isSparkUpdateQuoting) + assertNull(sut.sendUiState.value.sparkUpdateQuote) + quoted.complete(Unit) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isSparkUpdateQuoting) + assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) + } + @Test fun `an lnurl payment that needs the update shows its fee and pays on the first swipe`() = test { val input = "lnurl1updatefirstswipe" From 4d5b3aa86232839b5c5360c825ebbe292545c282 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 17:05:48 +0100 Subject: [PATCH 12/23] fix: clear the update quoting flag after a switch Verified: just format, compile, test, lint --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 ++++- .../viewmodels/AppViewModelSendFlowTest.kt | 28 +++++++++++++++++++ 2 files changed, 34 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 b84ee11547..00088baa27 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -433,6 +433,9 @@ class AppViewModel @Inject constructor( private var onchainSendRefreshJob: Job? = null private var sendStateGeneration = 0L + /** Bumped by each update quote, so only the latest one clears [SendUiState.isSparkUpdateQuoting]. */ + private var sparkUpdateQuoteRun = 0L + /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ private var sendSession = 0L @@ -8668,6 +8671,7 @@ class AppViewModel @Inject constructor( generation: Long, walletGeneration: Long?, ) { + val run = ++sparkUpdateQuoteRun _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(isSparkUpdateQuoting = true) } try { val quote = moveToSparkRepo.quote().getOrNull() @@ -8678,7 +8682,8 @@ class AppViewModel @Inject constructor( it.copy(lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), sparkUpdateQuote = quote) } } finally { - _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(isSparkUpdateQuoting = false) } + // An edit such as a funding switch bumps the generation without quoting again, so the run owns the flag. + if (run == sparkUpdateQuoteRun) _sendUiState.update { it.copy(isSparkUpdateQuoting = false) } } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 76cb11734a..19d5c79e2d 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20798,6 +20798,34 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) } + @Test + fun `an edit during the update quote does not keep the swipe disabled`() = test { + val input = "lnurl1updatequotingedit" + val data = + LnurlPayData(input, "https://example.com/callback", 1_000_000uL, 1_000_000uL, "[]", null, false, null) + val quoted = CompletableDeferred() + whenever(coreService.decode(input)).thenReturn(Scanner.LnurlPay(data)) + whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { + quoted.await() + Result.success(UPDATE_QUOTE) + } + whenever(moveToSparkRepo.estimateFeeAfterUpdate(null, 1_000uL)).thenReturn(3uL) + sut.setIsAuthenticated(true) + sut.onScanResult(input) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isSparkUpdateQuoting) + + // a funding switch bumps the generation and quotes nothing again + val field = AppViewModel::class.java.getDeclaredField("sendStateGeneration") + field.isAccessible = true + field.setLong(sut, field.getLong(sut) + 1) + quoted.complete(Unit) + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.isSparkUpdateQuoting) + } + @Test fun `an lnurl payment that needs the update shows its fee and pays on the first swipe`() = test { val input = "lnurl1updatefirstswipe" From a6e889915ab60bd10c5dfe1229847af92b38cc95 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 17:29:21 +0100 Subject: [PATCH 13/23] fix: keep the swipe off while a newer update quote loads Verified: just format, compile, test, lint --- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++--- 1 file changed, 3 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 00088baa27..797820421b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -434,7 +434,7 @@ class AppViewModel @Inject constructor( private var sendStateGeneration = 0L /** Bumped by each update quote, so only the latest one clears [SendUiState.isSparkUpdateQuoting]. */ - private var sparkUpdateQuoteRun = 0L + private val sparkUpdateQuoteRun = AtomicLong(0L) /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ private var sendSession = 0L @@ -8671,7 +8671,7 @@ class AppViewModel @Inject constructor( generation: Long, walletGeneration: Long?, ) { - val run = ++sparkUpdateQuoteRun + val run = sparkUpdateQuoteRun.incrementAndGet() _sendUiState.update { if (generation != sendStateGeneration) it else it.copy(isSparkUpdateQuoting = true) } try { val quote = moveToSparkRepo.quote().getOrNull() @@ -8683,7 +8683,7 @@ class AppViewModel @Inject constructor( } } finally { // An edit such as a funding switch bumps the generation without quoting again, so the run owns the flag. - if (run == sparkUpdateQuoteRun) _sendUiState.update { it.copy(isSparkUpdateQuoting = false) } + _sendUiState.update { if (run != sparkUpdateQuoteRun.get()) it else it.copy(isSparkUpdateQuoting = false) } } } From 5e1aa01a2dfeea257c11c42b6d7ac675a73c2b9a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 12:31:50 +0100 Subject: [PATCH 14/23] fix: confirm a subscription payment that needs the update An initial subscription payment started on its own with its details collapsed, so it could pay the spending balance update fee unseen. A payment that needs the update now waits for manual confirmation. A payment request refused at move time is prepared again on the next swipe, which a new test covers. Verified: just format, compile, test, lint --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 18 ++++- .../viewmodels/AppViewModelSendFlowTest.kt | 80 +++++++++++++++++++ 2 files changed, 94 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 797820421b..09fc13f93c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6705,6 +6705,11 @@ class AppViewModel @Inject constructor( if (!state.initialSubscriptionPaymentAutoStartPending) return _sendUiState.update { it.copy(initialSubscriptionPaymentAutoStartPending = false) } if (!state.shouldAutomaticallyPay) return + // The automatic start covers the details, so a payment that needs the update waits for its fee to be seen. + if (state.needsSparkUpdate()) { + _sendUiState.update { it.copy(initialSubscriptionPaymentNeedsConfirmation = true) } + return + } val generation = sendStateGeneration viewModelScope.launch { val isFeeKnown = awaitAutomaticOnchainFee() @@ -7907,10 +7912,7 @@ class AppViewModel @Inject constructor( */ private suspend fun confirmSparkUpdateQuote(): Boolean { val state = _sendUiState.value - if (state.payMethod != SendMethod.LIGHTNING || state.routedPaykitRoute?.serviceLeg != null) return true - if (state.activePaykitSwapRoute != null) return true - val payAmount = state.decodedInvoice?.amountSatoshis?.takeIf { it > 0uL } ?: state.amount - if (!moveToSparkRepo.needsUpdateToSend(payAmount)) return true + if (!state.needsSparkUpdate()) return true val generation = sendStateGeneration val fresh = moveToSparkRepo.quote().getOrElse { val failure = it.toSendFailureDetails(context, state.currentLightningPaymentRequest()) @@ -7926,6 +7928,14 @@ class AppViewModel @Inject constructor( return false } + /** Whether this Lightning payment fits only once the spending balance update moves the channels to Spark. */ + private fun SendUiState.needsSparkUpdate(): Boolean { + if (payMethod != SendMethod.LIGHTNING || routedPaykitRoute?.serviceLeg != null) return false + if (activePaykitSwapRoute != null) return false + val payAmount = decodedInvoice?.amountSatoshis?.takeIf { it > 0uL } ?: amount + return moveToSparkRepo.needsUpdateToSend(payAmount) + } + private fun closeChannelsEmptiedBy(outcome: MoveToSparkOutcome, channelsBefore: List) { viewModelScope.launch(bgDispatcher) { if (outcome is MoveToSparkOutcome.InFlight && moveToSparkRepo.awaitSettled(outcome).isFailure) return@launch diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 19d5c79e2d..016195551e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -15459,6 +15459,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertFalse(sut.sendUiState.value.shouldConfirmPay) } + @Test + fun `initial subscription payment that needs the update waits for manual confirmation`() = test { + whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.LIGHTNING, + isAmountInputValid = true, + isInitialSubscriptionPayment = true, + initialSubscriptionPaymentAutoStartPending = true, + ) + ) + + sut.setSendEvent(SendEvent.StartInitialSubscriptionPayment) + advanceUntilIdle() + + assertTrue(sut.sendUiState.value.initialSubscriptionPaymentNeedsConfirmation) + assertFalse(sut.sendUiState.value.shouldAutomaticallyPay) + assertFalse(sut.sendUiState.value.shouldConfirmPay, "the update fee was paid without being seen") + verify(moveToSparkRepo, never()).quote(anyOrNull()) + } + @Test fun `quoted initial subscription payment waits for amount review`() = test { setSendState( @@ -20714,6 +20736,64 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitAllowanceRepo).finishManualPayment("update-attempt", false, null) } + @Test + fun `a payment request whose update fee rose by send time is prepared again for the next swipe`() = test { + val request = paymentRequest() + val bolt11 = "lnbcrt1updaterequestfee" + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever( + paykitPaymentProofRepo.prepare( + request, + MethodId.Bolt11.rawValue, + "bitkit", + PaykitPaymentProofKind.Lightning + ) + ) + .doSuspendableAnswer { + setSendState( + sut.sendUiState.value.copy(decodedInvoice = lightningInvoice(bolt11, request.amount.atomic)) + ) + Result.success(Unit) + } + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitAllowanceRepo.beginManualPayment(eq(request), any(), anyOrNull())) + .thenReturn(Result.success("update-attempt")) + val raised = UPDATE_QUOTE.copy(feeSats = UPDATE_QUOTE.feeSats + 1uL) + whenever(moveToSparkRepo.needsUpdateToSend(request.amount.atomic)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE), Result.success(raised)) + whenever(moveToSparkRepo.updateToSend(any(), any(), eq(request.amount.atomic), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = bolt11, + amount = request.amount.atomic, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + assertEquals(SendEffect.ResetConfirm, awaitItem()) + + // The placeholder invoice fails the request's amount check, which a real one passes. + setSendState(sut.sendUiState.value.copy(decodedInvoice = null)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + cancelAndIgnoreRemainingEvents() + } + verify(paykitPaymentProofRepo, times(2)) + .prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning) + verify(privatePaykitRepo, times(2)).consumePrivatePaymentList(testPublicKey, privateContext) + verify(moveToSparkRepo).updateToSend(eq(raised), any(), eq(request.amount.atomic), any()) + } + @Test fun `a payment request whose update fails with any error is released, never left pending`() = test { val request = paymentRequest() From 2f8ed8927235e459d8b39959c649cb6b16dc44d8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:20:22 +0100 Subject: [PATCH 15/23] fix: guard the spending balance update's edge cases - A move closes no channel while another payment is in flight. - QuickPay decides on the update once the channels are usable. - The coverage check before a move uses the rule the wait after it uses. - The update fee paid is capped by the quote approved at the swipe. - A swap route accepts only an amount one rail can send. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 12 ++- .../to/bitkit/usecases/CloseChannelUseCase.kt | 10 ++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 22 ++++- .../repositories/MoveToSparkRepoTest.kt | 11 +++ .../usecases/CloseChannelUseCaseTest.kt | 23 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 95 ++++++++++++++++++- 6 files changed, 164 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 3d40e56815..3a8a10d85a 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -403,9 +403,15 @@ object MoveToSparkMath { fun needsUpdateToSend(amountSats: ULong, channels: List?, spark: SparkState): Boolean = amountSats > singleRailSendableSats(channels, spark) && amountSats <= combinedSendableSats(channels, spark) - /** Whether Spark can pay [amountSats] and its [feeSats] for the payment once [quote] has moved to it. */ - fun coversPayment(quote: MoveToSparkQuote, spark: SparkState, amountSats: ULong, feeSats: ULong): Boolean = - spark.isUsable && spark.balanceSats.safe() + quote.amountSats.safe() >= amountSats.safe() + feeSats.safe() + /** + * Whether Spark can pay [amountSats] and its [feeSats] for the payment once [quote] has moved to it, also by the + * rule the wait after the move applies, which keeps Spark's service fee aside. + */ + fun coversPayment(quote: MoveToSparkQuote, spark: SparkState, amountSats: ULong, feeSats: ULong): Boolean { + val have = spark.balanceSats.safe() + quote.amountSats.safe() + if (!spark.isUsable || have < amountSats.safe() + feeSats.safe()) return false + return SparkFees.sendableSats(have) >= amountSats + } /** The open channels in [after] that could send at least [MIN_MOVE_SATS] in [before] and no longer can. */ fun emptiedChannels(before: List, after: List?): List { diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index cc8df01d79..e8ba25049f 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -3,6 +3,8 @@ package to.bitkit.usecases import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.lightningdevkit.ldknode.ChannelDetails +import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.di.IoDispatcher import to.bitkit.ext.amountOnClose import to.bitkit.ext.runSuspendCatching @@ -44,11 +46,19 @@ class CloseChannelUseCase @Inject constructor( /** * Closes each channel a move to Spark emptied: one that could send at least the move minimum in [before] and can * no longer, read from the node after a sync. A close that fails leaves its channel listed for a manual close. + * While another payment is in flight its funds lower each channel's limit without leaving it, so nothing closes + * and the channels stay listed for a manual close. */ suspend fun closeEmptiedByMove(before: List) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() // A sync already running returns at once, so the channels are read from the node directly. lightningRepo.syncState() + val inFlight = lightningRepo.listPaymentsOrNull().orEmpty() + .any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING } + if (inFlight) { + Logger.info("Kept the channels a move may have emptied open while a payment is in flight", context = TAG) + return@withContext + } val emptied = MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) emptied.forEach { channel -> invoke(channel) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 09fc13f93c..cb5a122342 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5313,6 +5313,10 @@ class AppViewModel @Inject constructor( SendMethod.LIGHTNING -> { sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() + // A swap's hold payment goes out over one rail, never after a spending balance update. + if (_sendUiState.value.activePaykitSwapRoute != null) { + return amount <= minOf(maxSendable, moveToSparkRepo.singleRailSendableSats()) + } when (val lnurl = _sendUiState.value.lnurl) { null -> amount <= maxSendable && canSendLightning(amount) is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat() @@ -6619,7 +6623,9 @@ class AppViewModel @Inject constructor( if (hasActiveContactPaymentContext()) return false val invoiceHash = invoice?.paymentHash?.toHex()?.takeIf { it.isNotBlank() } val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) - // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. + // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. While + // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. + if (!open && channelsAreSettling()) waitForUsableChannels(walletGeneration) if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) @@ -6671,6 +6677,13 @@ class AppViewModel @Inject constructor( return true } + private fun channelsAreSettling(): Boolean { + val state = lightningRepo.lightningState.value + if (!state.nodeLifecycleState.canRun()) return false + if (!state.nodeLifecycleState.isRunning()) return true + return state.channels.isNotEmpty() && state.channels.none { it.isUsable } + } + private suspend fun canApplyQuickPay(amountSats: ULong): Boolean { if (hasActiveContactPaymentContext()) return false return quickPayRepo.canApply(amountSats).getOrDefault(false) @@ -6689,6 +6702,7 @@ class AppViewModel @Inject constructor( private fun onSwipeToPay() { Logger.debug("Swipe to pay event, checking send confirmation conditions", context = TAG) if (!_sendUiState.value.isAmountInputValid || !_sendUiState.value.isHardwareFeeReady) return + _sendUiState.update { it.copy(approvedSparkUpdateQuote = it.sparkUpdateQuote) } viewModelScope.launch { if (!prepareCoinSelection()) return@launch val amount = _sendUiState.value.amount @@ -7894,7 +7908,7 @@ class AppViewModel @Inject constructor( */ private suspend fun updateSpendingBalanceIfNeeded(bolt11: String, amountSats: ULong): Result { if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) - val shown = _sendUiState.value.sparkUpdateQuote + val shown = _sendUiState.value.approvedSparkUpdateQuote val fresh = moveToSparkRepo.quote().getOrElse { return Result.failure(it) } if (shown == null || fresh.feeSats > shown.feeSats) { _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } @@ -7920,7 +7934,7 @@ class AppViewModel @Inject constructor( return false } if (generation != sendStateGeneration) return false - val shown = state.sparkUpdateQuote + val shown = state.approvedSparkUpdateQuote _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } if (shown != null && fresh.feeSats <= shown.feeSats) return true Logger.info("Stopped a payment to show the update fee '${fresh.feeSats}'", context = TAG) @@ -10378,6 +10392,8 @@ data class SendUiState( val lightningFeeSats: Long? = null, /** The spending balance update a Lightning payment that fits only across the channels and Spark runs first. */ val sparkUpdateQuote: MoveToSparkQuote? = null, + /** The update quote shown at the swipe, whose fee caps the one paid; a later re-quote never raises it. */ + val approvedSparkUpdateQuote: MoveToSparkQuote? = null, /** True while the update a Lightning payment needs is quoted, so no swipe pays an update fee not yet shown. */ val isSparkUpdateQuoting: Boolean = false, val estimatedRoutingFee: ULong = 0uL, diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 9f6365cebe..e3b269dde7 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -434,6 +434,17 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertTrue(!MoveToSparkMath.coversPayment(quote, spark.copy(isExiting = true), 1_000uL, SPARK_FEE)) } + @Test + fun `a quote covers a payment only if the wait after the move would accept it`() { + val spark = SparkState(isReady = true, balanceSats = 20_000uL) + val have = 20_000uL + quote.amountSats + val priced = 2uL + + // A fee priced below Spark's service fee passes the plain sum, yet Spark keeps the service fee aside. + assertTrue(!MoveToSparkMath.coversPayment(quote, spark, have - priced, priced)) + assertTrue(MoveToSparkMath.coversPayment(quote, spark, SparkFees.sendableSats(have), priced)) + } + @Test fun `single rail sendable is the larger of the channels and a ready Spark`() { val channels = listOf(channel("a", 30_000uL)) diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index 5fd8d48e68..ea0b9ed9f3 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -4,6 +4,10 @@ import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Before import org.junit.Test +import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq @@ -83,6 +87,25 @@ class CloseChannelUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(eq(kept), any(), anyOrNull()) } + @Test + fun `a move's close keeps a channel open whose limit only a payment in flight lowered`() = test { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + val inFlight = PaymentDetails( + id = "hash", + kind = PaymentKind.Bolt11(hash = "hash", preimage = null, secret = null, description = null, bolt11 = "ln"), + amountMsat = 49_500_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = PaymentStatus.PENDING, + latestUpdateTimestamp = 0uL, + ) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(inFlight)) + + sut.closeEmptiedByMove(listOf(channel)) + + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + @Test fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { lightningState.value = LightningState(channels = persistentListOf(channel)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 016195551e..1b4a0a270b 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20329,12 +20329,26 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(swapRouteQuote().totalFeeSat.toLong(), sut.sendUiState.value.lightningFeeSats) } + @Test + fun `a swap route accepts only an amount one rail can send`() = test { + openSwapRoutedContactPayment() + assertTrue(sut.sendUiState.value.isAmountInputValid) + whenever(moveToSparkRepo.singleRailSendableSats()).thenReturn(SWAP_DELIVERED_SATS - 1uL) + whenever(moveToSparkRepo.needsUpdateToSend(SWAP_DELIVERED_SATS)).thenReturn(true) + + sut.setSendEvent(SendEvent.AmountChange(SWAP_DELIVERED_SATS)) + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.isAmountInputValid, "a swap took an amount only an update funds") + } + private suspend fun TestScope.openSwapRoutedContactPayment( quote: Result = Result.success(PaykitRoute.Swap(swapRouteQuote())), endpoints: List = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), // `advanceUntilIdle` fires the hold watch's timer, which ends a swap payment still awaiting its claim. settle: TestScope.() -> Unit = { advanceUntilIdle() }, privatePaymentContext: PrivatePaykitPaymentContext? = null, + singleRailSats: ULong = 100_000uL, ) { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) @@ -20348,6 +20362,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { Scanner.Lightning(lightningInvoice(SWAP_HOLD_INVOICE, amountSats = SWAP_DEBIT_SATS)), ) balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(moveToSparkRepo.singleRailSendableSats()).thenReturn(singleRailSats) sut.openContactPayment( paymentRequest = REGTEST_ADDRESS, publicKey = testPublicKey, @@ -20565,6 +20580,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = quote, + approvedSparkUpdateQuote = quote, ), ) @@ -20595,6 +20611,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20621,6 +20638,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20652,6 +20670,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20719,6 +20738,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20774,6 +20794,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20783,7 +20804,12 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.ResetConfirm, awaitItem()) // The placeholder invoice fails the request's amount check, which a real one passes. - setSendState(sut.sendUiState.value.copy(decodedInvoice = null)) + // The next swipe approves the raised fee now shown. + setSendState( + sut.sendUiState.value.let { + it.copy(decodedInvoice = null, approvedSparkUpdateQuote = it.sparkUpdateQuote) + } + ) sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() cancelAndIgnoreRemainingEvents() @@ -20834,6 +20860,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -20928,6 +20955,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(UPDATE_QUOTE, sut.sendUiState.value.sparkUpdateQuote) assertEquals(3L, sut.sendUiState.value.lightningFeeSats) + // The swipe approves the update fee shown. + setSendState(sut.sendUiState.value.let { it.copy(approvedSparkUpdateQuote = it.sparkUpdateQuote) }) sut.sendEffect.test { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() @@ -20977,6 +21006,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -21031,6 +21061,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -21044,6 +21075,62 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) } + @Test + fun `a re-quote after the swipe never raises the update fee the swipe approved`() = test { + val bolt11 = "lnbcrt1requoted" + val raised = UPDATE_QUOTE.copy(feeSats = UPDATE_QUOTE.feeSats + 1uL) + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(raised)) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + // A re-quote while the PIN shows replaces the quote on screen with a higher fee. + setSendState(sut.sendUiState.value.copy(sparkUpdateQuote = raised)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + cancelAndIgnoreRemainingEvents() + } + assertEquals(UPDATE_QUOTE, sut.sendUiState.value.approvedSparkUpdateQuote) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + } + + @Test + fun `a scan while the node starts decides on QuickPay once the channels are usable`() = test { + val bolt11 = "lnbcrt1quickpaystarting" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 60_000u) + val nodeState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting)) + whenever(lightningRepo.lightningState).thenReturn(nodeState) + var channelsUsable = false + whenever(lightningRepo.waitForUsableChannels()).thenAnswer { + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + channelsUsable = true + Unit + } + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenAnswer { channelsUsable } + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(UPDATE_QUOTE)) + whenever(moveToSparkRepo.estimateFeeAfterUpdate(any(), eq(60_000uL))).thenReturn(3uL) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo, atLeastOnce()).waitForUsableChannels() + assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") + } + @Test fun `an update needed only by send time moves nothing and shows its fee`() = test { val bolt11 = "lnbcrt1unseenatsend" @@ -21090,6 +21177,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -21119,6 +21207,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 60_000uL), sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -21139,6 +21228,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { isAmountInputValid = true, payMethod = SendMethod.LIGHTNING, sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, ), ) @@ -21150,8 +21240,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `a swap route is quoted with what one rail can pay, never the update's combined amount`() = test { - whenever(moveToSparkRepo.singleRailSendableSats()).thenReturn(20_000uL) - openSwapRoutedContactPayment() + openSwapRoutedContactPayment(singleRailSats = 20_000uL) sut.setSendEvent(SendEvent.AmountContinue) advanceUntilIdle() From b4d1cbbeee20c4fc9c0b73298ea2edbc96cea1e8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 17:46:28 +0100 Subject: [PATCH 16/23] fix: keep channels that still hold a balance after a move An HTLC still counting against the peer's in-flight limit lowers a channel's send limit without emptying it, so a channel closes only when its outbound capacity, less the commitment fee the funder keeps back, is under the move minimum too. The close is also skipped when the payments read before and after the channels read differ or cannot be read. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 41 ++++++++++++++++++- .../to/bitkit/usecases/CloseChannelUseCase.kt | 9 +++- .../repositories/MoveToSparkRepoTest.kt | 31 ++++++++++++++ .../usecases/CloseChannelUseCaseTest.kt | 30 ++++++++++++++ 4 files changed, 108 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 3a8a10d85a..e25d1c558d 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -18,7 +18,10 @@ import org.lightningdevkit.ldknode.Bolt11Invoice import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException +import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentFailureReason +import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.data.CacheStore import to.bitkit.di.BgDispatcher @@ -340,6 +343,10 @@ class MoveToSparkRepo internal constructor( object MoveToSparkMath { /** Below this a move is not offered: what is left is about the routing fee. */ const val MIN_MOVE_SATS = 1_000uL + private const val ANCHOR_COMMITMENT_WEIGHT = 1_124uL + private const val LEGACY_COMMITMENT_WEIGHT = 724uL + private const val HTLC_OUTPUT_WEIGHT = 172uL + private const val ANCHOR_OUTPUT_SATS = 330uL /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ private const val FIRST_FEE_GUESS_PPM = 5_000uL @@ -418,9 +425,41 @@ object MoveToSparkMath { val beforeSats = before.associate { it.channelId to msatFloorOf(it.nextOutboundHtlcLimitMsat) } return after.orEmpty().filterOpen().filter { val wasSats = beforeSats[it.channelId] ?: return@filter false - wasSats >= MIN_MOVE_SATS && msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS + // The outbound capacity too: an HTLC still counting against the peer's in-flight limit lowers only the + // send limit. + wasSats >= MIN_MOVE_SATS && msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS && + sendableAfterCommitmentFeeSats(it) < MIN_MOVE_SATS } } + + /** + * The outbound capacity less the commitment fee the funder keeps back, which LDK's capacity does not count: the + * higher of an anchor commitment (two 330-sat anchors) and a legacy one at twice the feerate, each with one HTLC. + */ + fun sendableAfterCommitmentFeeSats(channel: ChannelDetails): ULong { + val capacitySats = msatFloorOf(channel.outboundCapacityMsat) + if (!channel.isOutbound) return capacitySats + val feerate = channel.feerateSatPer1000Weight.toULong() + val anchorFeeSats = + feerate * (ANCHOR_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL + 2uL * ANCHOR_OUTPUT_SATS + val legacyFeeSats = 2uL * feerate * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL + val feeSats = maxOf(anchorFeeSats, legacyFeeSats) + return if (capacitySats > feeSats) capacitySats - feeSats else 0uL + } + + /** + * The payments read before and after a read of the channels, or null when either could not be read or an outbound + * Lightning payment appeared or changed between them: it may have held an HTLC while the channels were read. + */ + fun paymentsAround(before: List?, after: List?): List? { + if (before == null || after == null || outboundLightning(before) != outboundLightning(after)) return null + return before + after + } + + private fun outboundLightning(payments: List) = payments + .filter { it.direction == PaymentDirection.OUTBOUND && it.kind !is PaymentKind.Onchain } + .map { Triple(it.id, it.status, it.latestUpdateTimestamp) } + .toSet() } data class MoveToSparkQuote( diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index e8ba25049f..11a5c5ece3 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -51,10 +51,15 @@ class CloseChannelUseCase @Inject constructor( */ suspend fun closeEmptiedByMove(before: List) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() + val paymentsBefore = lightningRepo.listPaymentsOrNull() // A sync already running returns at once, so the channels are read from the node directly. lightningRepo.syncState() - val inFlight = lightningRepo.listPaymentsOrNull().orEmpty() - .any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING } + val payments = MoveToSparkMath.paymentsAround(paymentsBefore, lightningRepo.listPaymentsOrNull()) + if (payments == null) { + Logger.info("Kept the channels a move may have emptied open while its payments are unclear", context = TAG) + return@withContext + } + val inFlight = payments.any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING } if (inFlight) { Logger.info("Kept the channels a move may have emptied open while a payment is in flight", context = TAG) return@withContext diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index e3b269dde7..387c48a0f1 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -366,6 +366,37 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertEquals(listOf("emptied"), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) } + @Test + fun `a channel whose limit an in-flight htlc lowered still holds its capacity and stays open`() { + val before = listOf(channel("held", 50_000uL)) + val after = listOf(channel("held", 0uL).copy(outboundCapacityMsat = 20_000_000uL)) + + assertEquals(emptyList(), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) + } + + @Test + fun `a funded channel's capacity counts without the commitment fee it keeps back`() { + val funded = channel("funded", 0uL).copy( + outboundCapacityMsat = 1_500_000uL, + isOutbound = true, + feerateSatPer1000Weight = 1_000u, + ) + val before = listOf(channel("funded", 50_000uL), channel("inbound", 50_000uL)) + val after = listOf(funded, funded.copy(channelId = "inbound", isOutbound = false)) + + assertEquals(0uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded)) + assertEquals(listOf("funded"), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) + } + + @Test + fun `payments around the channels read are unclear when one changed or could not be read`() { + val sent = nodeSend(PaymentStatus.FAILED) + assertEquals(null, MoveToSparkMath.paymentsAround(null, emptyList())) + assertEquals(null, MoveToSparkMath.paymentsAround(emptyList(), null)) + assertEquals(null, MoveToSparkMath.paymentsAround(emptyList(), listOf(sent)), "a payment appeared") + assertEquals(listOf(sent, sent), MoveToSparkMath.paymentsAround(listOf(sent), listOf(sent))) + } + @Test fun `combined amounts keep their invariants for generated balances`() { val random = Random(seed = 64) diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index ea0b9ed9f3..d7d1c60ee0 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -51,6 +51,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { ) }.thenReturn(Result.success("transfer")) whenever { walletRepo.syncNodeAndWallet(anyOrNull()) }.thenReturn(Result.success(Unit)) + whenever { lightningRepo.listPaymentsOrNull() }.thenReturn(emptyList()) sut = CloseChannelUseCase(testDispatcher, lightningRepo, transferRepo, walletRepo) } @@ -106,6 +107,35 @@ class CloseChannelUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `a move's close keeps channels open while its payments cannot be read`() = test { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList(), null) + + sut.closeEmptiedByMove(listOf(channel)) + + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + + @Test + fun `a move's close keeps channels open when a payment changed while the channels were read`() = test { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + val failed = PaymentDetails( + id = "late", + kind = PaymentKind.Bolt11(hash = "late", preimage = null, secret = null, description = null, bolt11 = "ln"), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = PaymentStatus.FAILED, + latestUpdateTimestamp = 1uL, + ) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList(), listOf(failed)) + + sut.closeEmptiedByMove(listOf(channel)) + + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + @Test fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { lightningState.value = LightningState(channels = persistentListOf(channel)) From fec6da7a971854cef6292e7e1070c2288abdf4b8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 18:04:50 +0100 Subject: [PATCH 17/23] fix: close only channels the move itself emptied A send from another channel while a move ran could empty that channel and settle before the move, and the move then closed it too. Each move now reads the payments when it starts and closes nothing if a payment other than a move's changed since. The commitment fee taken off a funded channel's capacity no longer counts the anchors LDK already took off: an anchor commitment with two HTLCs, as LDK reserves. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 30 ++++++++------ .../settings/lightning/MoveToSparkManager.kt | 10 +++-- .../to/bitkit/usecases/CloseChannelUseCase.kt | 17 +++++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 12 ++++-- .../repositories/MoveToSparkRepoTest.kt | 24 +++++++---- .../lightning/MoveToSparkViewModelTest.kt | 8 ++-- .../usecases/CloseChannelUseCaseTest.kt | 41 ++++++++++++++++--- .../viewmodels/AppViewModelSendFlowTest.kt | 10 ++--- 8 files changed, 107 insertions(+), 45 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index e25d1c558d..ecd2930b9c 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -344,9 +344,7 @@ object MoveToSparkMath { /** Below this a move is not offered: what is left is about the routing fee. */ const val MIN_MOVE_SATS = 1_000uL private const val ANCHOR_COMMITMENT_WEIGHT = 1_124uL - private const val LEGACY_COMMITMENT_WEIGHT = 724uL private const val HTLC_OUTPUT_WEIGHT = 172uL - private const val ANCHOR_OUTPUT_SATS = 330uL /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ private const val FIRST_FEE_GUESS_PPM = 5_000uL @@ -433,26 +431,32 @@ object MoveToSparkMath { } /** - * The outbound capacity less the commitment fee the funder keeps back, which LDK's capacity does not count: the - * higher of an anchor commitment (two 330-sat anchors) and a legacy one at twice the feerate, each with one HTLC. + * The outbound capacity less the commitment fee the funder keeps back for its next HTLC, which LDK's capacity does + * not count; LDK already took the anchors off. An anchor commitment with two HTLCs, as LDK reserves. */ fun sendableAfterCommitmentFeeSats(channel: ChannelDetails): ULong { val capacitySats = msatFloorOf(channel.outboundCapacityMsat) if (!channel.isOutbound) return capacitySats - val feerate = channel.feerateSatPer1000Weight.toULong() - val anchorFeeSats = - feerate * (ANCHOR_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL + 2uL * ANCHOR_OUTPUT_SATS - val legacyFeeSats = 2uL * feerate * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL - val feeSats = maxOf(anchorFeeSats, legacyFeeSats) + val weight = ANCHOR_COMMITMENT_WEIGHT + 2uL * HTLC_OUTPUT_WEIGHT + val feeSats = channel.feerateSatPer1000Weight.toULong() * weight / 1000uL return if (capacitySats > feeSats) capacitySats - feeSats else 0uL } /** - * The payments read before and after a read of the channels, or null when either could not be read or an outbound - * Lightning payment appeared or changed between them: it may have held an HTLC while the channels were read. + * The payments read before and after a read of the channels, or null when a read failed or an outbound Lightning + * payment appeared or changed between them: it may have held an HTLC while the channels were read. Also null when a + * payment other than a move's changed since the move started ([moveStart]): it may have emptied another channel. */ - fun paymentsAround(before: List?, after: List?): List? { - if (before == null || after == null || outboundLightning(before) != outboundLightning(after)) return null + fun paymentsAround( + moveStart: List?, + before: List?, + after: List?, + isMovePayment: (id: String) -> Boolean, + ): List? { + if (moveStart == null || before == null || after == null) return null + if (outboundLightning(before) != outboundLightning(after)) return null + val othersAtStart = outboundLightning(moveStart).filterNot { isMovePayment(it.first) }.toSet() + if (othersAtStart != outboundLightning(before).filterNot { isMovePayment(it.first) }.toSet()) return null return before + after } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index a852f78969..e45e3d4378 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.ChannelDetails +import org.lightningdevkit.ldknode.PaymentDetails import to.bitkit.async.appScope import to.bitkit.di.BgDispatcher import to.bitkit.repositories.LightningRepo @@ -124,6 +125,7 @@ class MoveToSparkManager @Inject constructor( isMoveInFlight = true _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } moveJob = scope.launch { + val paymentsBefore = lightningRepo.listPaymentsOrNull() try { moveToSparkRepo.move(quote).fold( onSuccess = { outcome -> @@ -132,10 +134,10 @@ class MoveToSparkManager @Inject constructor( } val done = done(outcome) if (generation.get() == moveGeneration) _uiState.update { done } - if (outcome is MoveToSparkOutcome.Moved) closeEmptied(channelsBefore) + if (outcome is MoveToSparkOutcome.Moved) closeEmptied(channelsBefore, paymentsBefore) settled?.await()?.let { showLateOutcome(it, moveGeneration) - if (it.isSuccess) closeEmptied(channelsBefore) + if (it.isSuccess) closeEmptied(channelsBefore, paymentsBefore) } }, onFailure = { error -> @@ -154,8 +156,8 @@ class MoveToSparkManager @Inject constructor( return MoveToSparkUiState.Done(outcome, hasRest) } - private fun closeEmptied(channelsBefore: List) { - scope.launch { closeChannelUseCase.closeEmptiedByMove(channelsBefore) } + private fun closeEmptied(channelsBefore: List, paymentsBefore: List?) { + scope.launch { closeChannelUseCase.closeEmptiedByMove(channelsBefore, paymentsBefore) } } private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index 11a5c5ece3..a9b4878f45 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -1,8 +1,10 @@ package to.bitkit.usecases import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import org.lightningdevkit.ldknode.ChannelDetails +import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.di.IoDispatcher @@ -11,6 +13,7 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.models.TransferType import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.WalletRepo import to.bitkit.utils.Logger @@ -24,6 +27,7 @@ class CloseChannelUseCase @Inject constructor( private val lightningRepo: LightningRepo, private val transferRepo: TransferRepo, private val walletRepo: WalletRepo, + private val moveToSparkRepo: MoveToSparkRepo, ) { companion object { private const val TAG = "CloseChannelUseCase" @@ -49,12 +53,21 @@ class CloseChannelUseCase @Inject constructor( * While another payment is in flight its funds lower each channel's limit without leaving it, so nothing closes * and the channels stay listed for a manual close. */ - suspend fun closeEmptiedByMove(before: List) = withContext(ioDispatcher) { + /** Closes the channels a move emptied, from the channels and payments read when it started. */ + suspend fun closeEmptiedByMove( + before: List, + paymentsAtStart: List?, + ) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() val paymentsBefore = lightningRepo.listPaymentsOrNull() // A sync already running returns at once, so the channels are read from the node directly. lightningRepo.syncState() - val payments = MoveToSparkMath.paymentsAround(paymentsBefore, lightningRepo.listPaymentsOrNull()) + val moveHashes = moveToSparkRepo.moveHashes.first() + val payments = MoveToSparkMath.paymentsAround( + moveStart = paymentsAtStart, + before = paymentsBefore, + after = lightningRepo.listPaymentsOrNull(), + ) { it.lowercase() in moveHashes } if (payments == null) { Logger.info("Kept the channels a move may have emptied open while its payments are unclear", context = TAG) return@withContext diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 108386bca0..7bc30c6653 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -93,6 +93,7 @@ import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.ClosureReason import org.lightningdevkit.ldknode.Event +import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import org.lightningdevkit.ldknode.SpendableUtxo @@ -8079,8 +8080,9 @@ class AppViewModel @Inject constructor( return Result.failure(MoveToSparkError.UpdateFeeUnseen()) } val channelsBefore = lightningRepo.lightningState.value.channels.toList() + val paymentsBefore = lightningRepo.listPaymentsOrNull() return moveToSparkRepo.updateToSend(fresh, bolt11, amountSats) { - closeChannelsEmptiedBy(it, channelsBefore) + closeChannelsEmptiedBy(it, channelsBefore, paymentsBefore) }.map { } } @@ -8114,10 +8116,14 @@ class AppViewModel @Inject constructor( return moveToSparkRepo.needsUpdateToSend(payAmount) } - private fun closeChannelsEmptiedBy(outcome: MoveToSparkOutcome, channelsBefore: List) { + private fun closeChannelsEmptiedBy( + outcome: MoveToSparkOutcome, + channelsBefore: List, + paymentsBefore: List?, + ) { viewModelScope.launch(bgDispatcher) { if (outcome is MoveToSparkOutcome.InFlight && moveToSparkRepo.awaitSettled(outcome).isFailure) return@launch - closeChannelUseCase.closeEmptiedByMove(channelsBefore) + closeChannelUseCase.closeEmptiedByMove(channelsBefore, paymentsBefore) } } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 387c48a0f1..d58c274839 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -377,24 +377,32 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `a funded channel's capacity counts without the commitment fee it keeps back`() { val funded = channel("funded", 0uL).copy( - outboundCapacityMsat = 1_500_000uL, + outboundCapacityMsat = 1_900_000uL, isOutbound = true, - feerateSatPer1000Weight = 1_000u, + feerateSatPer1000Weight = 253u, ) val before = listOf(channel("funded", 50_000uL), channel("inbound", 50_000uL)) val after = listOf(funded, funded.copy(channelId = "inbound", isOutbound = false)) - assertEquals(0uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded)) - assertEquals(listOf("funded"), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) + assertEquals(1_529uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded)) + assertEquals(emptyList(), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) + val nearlyEmpty = after.map { it.copy(outboundCapacityMsat = 1_300_000uL) } + assertEquals(listOf("funded"), MoveToSparkMath.emptiedChannels(before, nearlyEmpty).map { it.channelId }) } @Test fun `payments around the channels read are unclear when one changed or could not be read`() { val sent = nodeSend(PaymentStatus.FAILED) - assertEquals(null, MoveToSparkMath.paymentsAround(null, emptyList())) - assertEquals(null, MoveToSparkMath.paymentsAround(emptyList(), null)) - assertEquals(null, MoveToSparkMath.paymentsAround(emptyList(), listOf(sent)), "a payment appeared") - assertEquals(listOf(sent, sent), MoveToSparkMath.paymentsAround(listOf(sent), listOf(sent))) + fun around(start: List?, before: List?, after: List?) = + MoveToSparkMath.paymentsAround(start, before, after) { it == "move" } + assertEquals(null, around(emptyList(), null, emptyList())) + assertEquals(null, around(emptyList(), emptyList(), null)) + assertEquals(null, around(null, emptyList(), emptyList())) + assertEquals(null, around(listOf(sent), emptyList(), listOf(sent)), "a payment appeared") + assertEquals(null, around(emptyList(), listOf(sent), listOf(sent)), "another send since the move started") + val move = sent.copy(id = "move") + assertEquals(listOf(move, move), around(emptyList(), listOf(move), listOf(move)), "the move's own send") + assertEquals(listOf(sent, sent), around(listOf(sent), listOf(sent), listOf(sent))) } @Test diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index 051d30b1dd..de1d795881 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -182,18 +182,18 @@ class MoveToSparkViewModelTest : BaseUnitTest() { createViewModel().move() - verify(closeChannelUseCase).closeEmptiedByMove(listOf(openChannel)) + verify(closeChannelUseCase).closeEmptiedByMove(eq(listOf(openChannel)), anyOrNull()) } @Test fun `an in-flight move closes nothing until it settles`() = test { lightningState.value = LightningState(channels = persistentListOf(openChannel)) createViewModel().move() - verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) firstSettled.complete(Result.success(moved)) - verify(closeChannelUseCase).closeEmptiedByMove(listOf(openChannel)) + verify(closeChannelUseCase).closeEmptiedByMove(eq(listOf(openChannel)), anyOrNull()) } @Test @@ -202,7 +202,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { firstSettled.complete(Result.failure(MoveToSparkError.PaymentFailed(null))) - verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) } @Test diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index d7d1c60ee0..20cd488cea 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -2,6 +2,7 @@ package to.bitkit.usecases import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf import org.junit.Before import org.junit.Test import org.lightningdevkit.ldknode.PaymentDetails @@ -21,6 +22,7 @@ import to.bitkit.ext.createChannelDetails import to.bitkit.models.TransferType import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.WalletRepo import to.bitkit.test.BaseUnitTest @@ -30,6 +32,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { private val lightningRepo = mock() private val transferRepo = mock() private val walletRepo = mock() + private val moveToSparkRepo = mock() private val lightningState = MutableStateFlow(LightningState()) private val channel = channel("channel_1", 50_000uL) private lateinit var sut: CloseChannelUseCase @@ -52,7 +55,8 @@ class CloseChannelUseCaseTest : BaseUnitTest() { }.thenReturn(Result.success("transfer")) whenever { walletRepo.syncNodeAndWallet(anyOrNull()) }.thenReturn(Result.success(Unit)) whenever { lightningRepo.listPaymentsOrNull() }.thenReturn(emptyList()) - sut = CloseChannelUseCase(testDispatcher, lightningRepo, transferRepo, walletRepo) + whenever(moveToSparkRepo.moveHashes).thenReturn(flowOf(setOf("move"))) + sut = CloseChannelUseCase(testDispatcher, lightningRepo, transferRepo, walletRepo, moveToSparkRepo) } @Test @@ -82,7 +86,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { val kept = channel("channel_2", 20_000uL) lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL), kept)) - sut.closeEmptiedByMove(listOf(channel, kept)) + sut.closeEmptiedByMove(listOf(channel, kept), emptyList()) verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) verify(lightningRepo, never()).closeChannel(eq(kept), any(), anyOrNull()) @@ -102,7 +106,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { ) whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(inFlight)) - sut.closeEmptiedByMove(listOf(channel)) + sut.closeEmptiedByMove(listOf(channel), emptyList()) verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } @@ -112,7 +116,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList(), null) - sut.closeEmptiedByMove(listOf(channel)) + sut.closeEmptiedByMove(listOf(channel), emptyList()) verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } @@ -131,11 +135,36 @@ class CloseChannelUseCaseTest : BaseUnitTest() { ) whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList(), listOf(failed)) - sut.closeEmptiedByMove(listOf(channel)) + sut.closeEmptiedByMove(listOf(channel), emptyList()) verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `a move's close keeps channels open after another send since the move started, not after the move's own`() = + test { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + val other = send("other") + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(other)) + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(send("move"))) + sut.closeEmptiedByMove(listOf(channel), emptyList()) + verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) + } + + private fun send(id: String) = PaymentDetails( + id = id, + kind = PaymentKind.Bolt11(hash = id, preimage = null, secret = null, description = null, bolt11 = "ln"), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = PaymentStatus.SUCCEEDED, + latestUpdateTimestamp = 1uL, + ) + @Test fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { lightningState.value = LightningState(channels = persistentListOf(channel)) @@ -144,7 +173,7 @@ class CloseChannelUseCaseTest : BaseUnitTest() { Unit } - sut.closeEmptiedByMove(listOf(channel)) + sut.closeEmptiedByMove(listOf(channel), emptyList()) inOrder(walletRepo, lightningRepo) { verify(walletRepo).syncNodeAndWallet(anyOrNull()) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b030963f11..02a746c287 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -21128,7 +21128,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } onMove.firstValue(moved) advanceUntilIdle() - verify(closeChannelUseCase).closeEmptiedByMove(any()) + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) } @Test @@ -21155,7 +21155,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) - verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) } @Test @@ -21184,7 +21184,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(moveToSparkRepo).updateToSend(any(), any(), eq(60_000uL), onMove.capture()) onMove.firstValue(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL)) advanceUntilIdle() - verify(closeChannelUseCase).closeEmptiedByMove(any()) + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) } @Test @@ -21216,7 +21216,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { onMove.firstValue(inFlight) advanceUntilIdle() verify(moveToSparkRepo).awaitSettled(inFlight) - verify(closeChannelUseCase).closeEmptiedByMove(any()) + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) } @Test @@ -21548,7 +21548,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) - verify(closeChannelUseCase, never()).closeEmptiedByMove(any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) verify(pendingPaymentRepo, never()).track(any()) verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) verify(paykitPaymentProofRepo).cancelPreparation(request) From be6e3f7f597c10b31c2bcca3a85af8d7998206fa Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 18:59:24 +0100 Subject: [PATCH 18/23] fix: use the legacy reserve for channels without anchors The close check took an anchor commitment's fee off every channel we funded, so a legacy channel a move emptied could still read over 1 000 sats and stay open. ldk-node does not expose the channel type, so it is read from the channel before the move: a send limit at least the legacy reserve under the capacity means a legacy commitment, whose fee is one HTLC at twice the feerate. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 37 +++++++++++++++---- .../repositories/MoveToSparkRepoTest.kt | 31 +++++++++++++++- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index ecd2930b9c..0f508abe03 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -344,6 +344,7 @@ object MoveToSparkMath { /** Below this a move is not offered: what is left is about the routing fee. */ const val MIN_MOVE_SATS = 1_000uL private const val ANCHOR_COMMITMENT_WEIGHT = 1_124uL + private const val LEGACY_COMMITMENT_WEIGHT = 724uL private const val HTLC_OUTPUT_WEIGHT = 172uL /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ @@ -420,28 +421,48 @@ object MoveToSparkMath { /** The open channels in [after] that could send at least [MIN_MOVE_SATS] in [before] and no longer can. */ fun emptiedChannels(before: List, after: List?): List { - val beforeSats = before.associate { it.channelId to msatFloorOf(it.nextOutboundHtlcLimitMsat) } + val beforeById = before.associateBy { it.channelId } return after.orEmpty().filterOpen().filter { - val wasSats = beforeSats[it.channelId] ?: return@filter false + val was = beforeById[it.channelId] ?: return@filter false // The outbound capacity too: an HTLC still counting against the peer's in-flight limit lowers only the // send limit. - wasSats >= MIN_MOVE_SATS && msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS && - sendableAfterCommitmentFeeSats(it) < MIN_MOVE_SATS + msatFloorOf(was.nextOutboundHtlcLimitMsat) >= MIN_MOVE_SATS && + msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS && + sendableAfterCommitmentFeeSats(it, isLegacy = reservesLegacyFee(was)) < MIN_MOVE_SATS } } /** * The outbound capacity less the commitment fee the funder keeps back for its next HTLC, which LDK's capacity does - * not count; LDK already took the anchors off. An anchor commitment with two HTLCs, as LDK reserves. + * not count, as LDK reserves it: an anchor commitment with two HTLCs (LDK already took the anchors off), or a + * legacy one with one HTLC at twice the feerate. */ - fun sendableAfterCommitmentFeeSats(channel: ChannelDetails): ULong { + fun sendableAfterCommitmentFeeSats(channel: ChannelDetails, isLegacy: Boolean): ULong { val capacitySats = msatFloorOf(channel.outboundCapacityMsat) if (!channel.isOutbound) return capacitySats - val weight = ANCHOR_COMMITMENT_WEIGHT + 2uL * HTLC_OUTPUT_WEIGHT - val feeSats = channel.feerateSatPer1000Weight.toULong() * weight / 1000uL + val feeSats = commitmentFeeSats(channel.feerateSatPer1000Weight, isLegacy) return if (capacitySats > feeSats) capacitySats - feeSats else 0uL } + /** + * ldk-node does not expose a channel's type, so it is read from the channel before the move, with no move HTLC in + * flight: a legacy channel's send limit sits at least the legacy reserve under its capacity, an anchor one's less. + * A limit capped lower by the peer also reads as legacy, which only takes a little more off. + */ + fun reservesLegacyFee(channel: ChannelDetails): Boolean { + if (!channel.isOutbound) return false + val capacityMsat = channel.outboundCapacityMsat + val limitMsat = channel.nextOutboundHtlcLimitMsat + val gapSats = if (capacityMsat > limitMsat) (capacityMsat - limitMsat) / 1000uL else 0uL + return gapSats + 1uL >= commitmentFeeSats(channel.feerateSatPer1000Weight, isLegacy = true) + } + + private fun commitmentFeeSats(feerate: UInt, isLegacy: Boolean): ULong = if (isLegacy) { + 2uL * feerate.toULong() * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL + } else { + feerate.toULong() * (ANCHOR_COMMITMENT_WEIGHT + 2uL * HTLC_OUTPUT_WEIGHT) / 1000uL + } + /** * The payments read before and after a read of the channels, or null when a read failed or an outbound Lightning * payment appeared or changed between them: it may have held an HTLC while the channels were read. Also null when a diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index d58c274839..e61bf520c9 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -30,6 +30,7 @@ import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.LdkError import kotlin.random.Random import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue @@ -381,15 +382,41 @@ class MoveToSparkRepoTest : BaseUnitTest() { isOutbound = true, feerateSatPer1000Weight = 253u, ) - val before = listOf(channel("funded", 50_000uL), channel("inbound", 50_000uL)) + val anchorBefore = channel("funded", 50_000uL).copy( + outboundCapacityMsat = 50_371_000uL, + isOutbound = true, + feerateSatPer1000Weight = 253u, + ) + val before = listOf(anchorBefore, channel("inbound", 50_000uL)) val after = listOf(funded, funded.copy(channelId = "inbound", isOutbound = false)) - assertEquals(1_529uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded)) + assertFalse(MoveToSparkMath.reservesLegacyFee(anchorBefore)) + assertEquals(1_529uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded, isLegacy = false)) assertEquals(emptyList(), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) val nearlyEmpty = after.map { it.copy(outboundCapacityMsat = 1_300_000uL) } assertEquals(listOf("funded"), MoveToSparkMath.emptiedChannels(before, nearlyEmpty).map { it.channelId }) } + @Test + fun `a move closes a legacy channel at its reserve`() { + // 2 500 sat/kW: a legacy commitment keeps back 4 480 sats, so 5 342 sats of capacity send only 862. + val legacyBefore = channel("legacy", 50_000uL).copy( + outboundCapacityMsat = 54_480_000uL, + isOutbound = true, + feerateSatPer1000Weight = 2_500u, + ) + val after = channel("legacy", 0uL).copy( + outboundCapacityMsat = 5_342_000uL, + isOutbound = true, + feerateSatPer1000Weight = 2_500u, + ) + + assertTrue(MoveToSparkMath.reservesLegacyFee(legacyBefore)) + assertEquals(862uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(after, isLegacy = true)) + val emptied = MoveToSparkMath.emptiedChannels(listOf(legacyBefore), listOf(after)) + assertEquals(listOf("legacy"), emptied.map { it.channelId }) + } + @Test fun `payments around the channels read are unclear when one changed or could not be read`() { val sent = nodeSend(PaymentStatus.FAILED) From e9942d10fcfb06d9dcd0ef3ec71e980ee1157d33 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 19:42:21 +0100 Subject: [PATCH 19/23] fix: recheck a moved channel before closing it A peer's in-flight cap made an anchor channel read as legacy, so the close took the legacy fee off a channel that could still send once the move's HTLC cleared. The close no longer estimates any commitment fee: a channel with capacity left whose send limit is under the minimum is read again every 2 s for up to 30 s, and closes only if its limit stays under it. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 42 +++------------- .../to/bitkit/usecases/CloseChannelUseCase.kt | 47 +++++++++++------ .../repositories/MoveToSparkRepoTest.kt | 50 +++---------------- .../usecases/CloseChannelUseCaseTest.kt | 29 +++++++++++ 4 files changed, 75 insertions(+), 93 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 0f508abe03..88854b24a1 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -343,9 +343,6 @@ class MoveToSparkRepo internal constructor( object MoveToSparkMath { /** Below this a move is not offered: what is left is about the routing fee. */ const val MIN_MOVE_SATS = 1_000uL - private const val ANCHOR_COMMITMENT_WEIGHT = 1_124uL - private const val LEGACY_COMMITMENT_WEIGHT = 724uL - private const val HTLC_OUTPUT_WEIGHT = 172uL /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ private const val FIRST_FEE_GUESS_PPM = 5_000uL @@ -424,44 +421,19 @@ object MoveToSparkMath { val beforeById = before.associateBy { it.channelId } return after.orEmpty().filterOpen().filter { val was = beforeById[it.channelId] ?: return@filter false - // The outbound capacity too: an HTLC still counting against the peer's in-flight limit lowers only the - // send limit. msatFloorOf(was.nextOutboundHtlcLimitMsat) >= MIN_MOVE_SATS && - msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS && - sendableAfterCommitmentFeeSats(it, isLegacy = reservesLegacyFee(was)) < MIN_MOVE_SATS + msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS } } /** - * The outbound capacity less the commitment fee the funder keeps back for its next HTLC, which LDK's capacity does - * not count, as LDK reserves it: an anchor commitment with two HTLCs (LDK already took the anchors off), or a - * legacy one with one HTLC at twice the feerate. + * Whether an emptied channel still holds the move minimum in outbound capacity. Its send limit is then under the + * minimum for one of two reasons ldk-node does not tell apart: the commitment fee its funder keeps back, which + * stays, or the move's settled HTLC still counting against the peer's in-flight cap, which clears. Such a channel + * is read again before it closes. */ - fun sendableAfterCommitmentFeeSats(channel: ChannelDetails, isLegacy: Boolean): ULong { - val capacitySats = msatFloorOf(channel.outboundCapacityMsat) - if (!channel.isOutbound) return capacitySats - val feeSats = commitmentFeeSats(channel.feerateSatPer1000Weight, isLegacy) - return if (capacitySats > feeSats) capacitySats - feeSats else 0uL - } - - /** - * ldk-node does not expose a channel's type, so it is read from the channel before the move, with no move HTLC in - * flight: a legacy channel's send limit sits at least the legacy reserve under its capacity, an anchor one's less. - * A limit capped lower by the peer also reads as legacy, which only takes a little more off. - */ - fun reservesLegacyFee(channel: ChannelDetails): Boolean { - if (!channel.isOutbound) return false - val capacityMsat = channel.outboundCapacityMsat - val limitMsat = channel.nextOutboundHtlcLimitMsat - val gapSats = if (capacityMsat > limitMsat) (capacityMsat - limitMsat) / 1000uL else 0uL - return gapSats + 1uL >= commitmentFeeSats(channel.feerateSatPer1000Weight, isLegacy = true) - } - - private fun commitmentFeeSats(feerate: UInt, isLegacy: Boolean): ULong = if (isLegacy) { - 2uL * feerate.toULong() * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000uL - } else { - feerate.toULong() * (ANCHOR_COMMITMENT_WEIGHT + 2uL * HTLC_OUTPUT_WEIGHT) / 1000uL - } + fun mayHoldTheMoveHtlc(emptied: List): Boolean = + emptied.any { msatFloorOf(it.outboundCapacityMsat) >= MIN_MOVE_SATS } /** * The payments read before and after a read of the channels, or null when a read failed or an outbound Lightning diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index a9b4878f45..574f2c5ea5 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -1,6 +1,7 @@ package to.bitkit.usecases import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import org.lightningdevkit.ldknode.ChannelDetails @@ -19,6 +20,7 @@ import to.bitkit.repositories.WalletRepo import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Duration.Companion.seconds /** Closes a channel cooperatively and records its transfer to Savings, so the close shows in Activity. */ @Singleton @@ -31,6 +33,10 @@ class CloseChannelUseCase @Inject constructor( ) { companion object { private const val TAG = "CloseChannelUseCase" + + /** How long a close waits for a move's HTLC to stop counting against the peer's in-flight cap. */ + private const val HTLC_CLEAR_RECHECKS = 15 + private val HTLC_CLEAR_RECHECK = 2.seconds } suspend operator fun invoke(channel: ChannelDetails): Result = withContext(ioDispatcher) { @@ -49,16 +55,35 @@ class CloseChannelUseCase @Inject constructor( /** * Closes each channel a move to Spark emptied: one that could send at least the move minimum in [before] and can - * no longer, read from the node after a sync. A close that fails leaves its channel listed for a manual close. - * While another payment is in flight its funds lower each channel's limit without leaving it, so nothing closes - * and the channels stay listed for a manual close. + * no longer, read from the node after a sync. Nothing closes while the payments are unclear or another is in + * flight, or when a payment other than a move's changed since [paymentsAtStart]. A channel that still holds the + * minimum in capacity is read again until its limit rises or the wait ends. A close that fails leaves its channel + * listed for a manual close. */ - /** Closes the channels a move emptied, from the channels and payments read when it started. */ suspend fun closeEmptiedByMove( before: List, paymentsAtStart: List?, ) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() + var emptied = readEmptied(before, paymentsAtStart) + // A channel whose limit rises once the move's HTLC clears drops out; one still under it is its reserve. + repeat(HTLC_CLEAR_RECHECKS) { + if (!MoveToSparkMath.mayHoldTheMoveHtlc(emptied)) return@repeat + delay(HTLC_CLEAR_RECHECK) + emptied = readEmptied(before, paymentsAtStart) + } + emptied.forEach { channel -> + invoke(channel) + .onSuccess { Logger.info("Closed channel '${channel.channelId}' emptied by a move", context = TAG) } + .onFailure { Logger.warn("Failed to close channel '${channel.channelId}'", it, context = TAG) } + } + } + + /** The channels a move emptied, read between two reads of the payments; none while those are unclear. */ + private suspend fun readEmptied( + before: List, + paymentsAtStart: List?, + ): List { val paymentsBefore = lightningRepo.listPaymentsOrNull() // A sync already running returns at once, so the channels are read from the node directly. lightningRepo.syncState() @@ -70,18 +95,12 @@ class CloseChannelUseCase @Inject constructor( ) { it.lowercase() in moveHashes } if (payments == null) { Logger.info("Kept the channels a move may have emptied open while its payments are unclear", context = TAG) - return@withContext + return emptyList() } - val inFlight = payments.any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING } - if (inFlight) { + if (payments.any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING }) { Logger.info("Kept the channels a move may have emptied open while a payment is in flight", context = TAG) - return@withContext - } - val emptied = MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) - emptied.forEach { channel -> - invoke(channel) - .onSuccess { Logger.info("Closed channel '${channel.channelId}' emptied by a move", context = TAG) } - .onFailure { Logger.warn("Failed to close channel '${channel.channelId}'", it, context = TAG) } + return emptyList() } + return MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) } } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index e61bf520c9..19ad702e05 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -368,53 +368,15 @@ class MoveToSparkRepoTest : BaseUnitTest() { } @Test - fun `a channel whose limit an in-flight htlc lowered still holds its capacity and stays open`() { + fun `an emptied channel that still holds the minimum in capacity may hold the move's htlc`() { val before = listOf(channel("held", 50_000uL)) - val after = listOf(channel("held", 0uL).copy(outboundCapacityMsat = 20_000_000uL)) + val held = channel("held", 0uL).copy(outboundCapacityMsat = 5_002_000uL) - assertEquals(emptyList(), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) - } - - @Test - fun `a funded channel's capacity counts without the commitment fee it keeps back`() { - val funded = channel("funded", 0uL).copy( - outboundCapacityMsat = 1_900_000uL, - isOutbound = true, - feerateSatPer1000Weight = 253u, - ) - val anchorBefore = channel("funded", 50_000uL).copy( - outboundCapacityMsat = 50_371_000uL, - isOutbound = true, - feerateSatPer1000Weight = 253u, - ) - val before = listOf(anchorBefore, channel("inbound", 50_000uL)) - val after = listOf(funded, funded.copy(channelId = "inbound", isOutbound = false)) - - assertFalse(MoveToSparkMath.reservesLegacyFee(anchorBefore)) - assertEquals(1_529uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(funded, isLegacy = false)) - assertEquals(emptyList(), MoveToSparkMath.emptiedChannels(before, after).map { it.channelId }) - val nearlyEmpty = after.map { it.copy(outboundCapacityMsat = 1_300_000uL) } - assertEquals(listOf("funded"), MoveToSparkMath.emptiedChannels(before, nearlyEmpty).map { it.channelId }) - } - - @Test - fun `a move closes a legacy channel at its reserve`() { - // 2 500 sat/kW: a legacy commitment keeps back 4 480 sats, so 5 342 sats of capacity send only 862. - val legacyBefore = channel("legacy", 50_000uL).copy( - outboundCapacityMsat = 54_480_000uL, - isOutbound = true, - feerateSatPer1000Weight = 2_500u, - ) - val after = channel("legacy", 0uL).copy( - outboundCapacityMsat = 5_342_000uL, - isOutbound = true, - feerateSatPer1000Weight = 2_500u, - ) + val emptied = MoveToSparkMath.emptiedChannels(before, listOf(held)) - assertTrue(MoveToSparkMath.reservesLegacyFee(legacyBefore)) - assertEquals(862uL, MoveToSparkMath.sendableAfterCommitmentFeeSats(after, isLegacy = true)) - val emptied = MoveToSparkMath.emptiedChannels(listOf(legacyBefore), listOf(after)) - assertEquals(listOf("legacy"), emptied.map { it.channelId }) + assertEquals(listOf("held"), emptied.map { it.channelId }) + assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(emptied)) + assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(listOf(held.copy(outboundCapacityMsat = 999_000uL)))) } @Test diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index 20cd488cea..d4caea32b5 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -15,6 +15,7 @@ import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.ext.amountOnClose @@ -165,6 +166,34 @@ class CloseChannelUseCaseTest : BaseUnitTest() { latestUpdateTimestamp = 1uL, ) + @Test + fun `a move's close keeps a channel whose limit rises once the move's htlc clears`() = test { + val held = channel("channel_1", 0uL).copy(outboundCapacityMsat = 5_002_000uL) + lightningState.value = LightningState(channels = persistentListOf(held)) + var reads = 0 + whenever(lightningRepo.syncState()).thenAnswer { + if (++reads == 3) { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 1_332uL))) + } + Unit + } + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + + @Test + fun `a move's close takes a channel whose limit stays under the minimum through the wait`() = test { + val reserved = channel("channel_1", 0uL).copy(outboundCapacityMsat = 5_002_000uL) + lightningState.value = LightningState(channels = persistentListOf(reserved)) + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + + verify(lightningRepo, times(16)).syncState() + verify(lightningRepo).closeChannel(eq(reserved), any(), anyOrNull()) + } + @Test fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { lightningState.value = LightningState(channels = persistentListOf(channel)) From d552fc3c363a47334dfd787b9965a5acf057fa33 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 20:13:26 +0100 Subject: [PATCH 20/23] fix: leave a channel open while the move may still hold it After the 30 s recheck a channel could still close on a send limit the move's HTLC held down, though it could send once that cleared. A channel with capacity left now closes only when the gap between its capacity and limit is exactly LDK's commitment fee for an anchor or a legacy commitment on a channel we funded; otherwise it stays open for a manual close. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 27 ++++++++++++++----- .../to/bitkit/usecases/CloseChannelUseCase.kt | 7 ++--- .../repositories/MoveToSparkRepoTest.kt | 18 ++++++++----- .../usecases/CloseChannelUseCaseTest.kt | 14 +++++++--- 4 files changed, 47 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 88854b24a1..69f6049610 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -38,6 +38,7 @@ import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.abs import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @@ -343,6 +344,9 @@ class MoveToSparkRepo internal constructor( object MoveToSparkMath { /** Below this a move is not offered: what is left is about the routing fee. */ const val MIN_MOVE_SATS = 1_000uL + private const val ANCHOR_COMMITMENT_WEIGHT = 1_124L + private const val LEGACY_COMMITMENT_WEIGHT = 724L + private const val HTLC_OUTPUT_WEIGHT = 172L /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ private const val FIRST_FEE_GUESS_PPM = 5_000uL @@ -427,13 +431,24 @@ object MoveToSparkMath { } /** - * Whether an emptied channel still holds the move minimum in outbound capacity. Its send limit is then under the - * minimum for one of two reasons ldk-node does not tell apart: the commitment fee its funder keeps back, which - * stays, or the move's settled HTLC still counting against the peer's in-flight cap, which clears. Such a channel - * is read again before it closes. + * Whether a channel's send limit may still be held under the minimum by the move's settled HTLC counting against + * the peer's in-flight cap, which clears, rather than by what stays. ldk-node exposes neither the HTLCs nor the + * channel type, so it is ruled out only when the capacity itself is under the minimum, or when the gap between + * capacity and limit is exactly the commitment fee LDK keeps back for a channel we funded: an anchor commitment + * with two HTLCs, or a legacy one with one HTLC at twice the feerate, within a sat of rounding. */ - fun mayHoldTheMoveHtlc(emptied: List): Boolean = - emptied.any { msatFloorOf(it.outboundCapacityMsat) >= MIN_MOVE_SATS } + fun mayHoldTheMoveHtlc(channel: ChannelDetails): Boolean { + val capacitySats = msatFloorOf(channel.outboundCapacityMsat).toLong() + if (capacitySats < MIN_MOVE_SATS.toLong()) return false + if (!channel.isOutbound) return true + val gapSats = capacitySats - msatFloorOf(channel.nextOutboundHtlcLimitMsat).toLong() + val feerate = channel.feerateSatPer1000Weight.toLong() + val reserves = listOf( + feerate * (ANCHOR_COMMITMENT_WEIGHT + 2 * HTLC_OUTPUT_WEIGHT) / 1000, + 2 * feerate * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000, + ) + return reserves.none { abs(gapSats - it) <= 1 } + } /** * The payments read before and after a read of the channels, or null when a read failed or an outbound Lightning diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index 574f2c5ea5..54dfbcc790 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -66,13 +66,14 @@ class CloseChannelUseCase @Inject constructor( ) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() var emptied = readEmptied(before, paymentsAtStart) - // A channel whose limit rises once the move's HTLC clears drops out; one still under it is its reserve. + // A channel whose limit rises once the move's HTLC clears drops out. One that may still hold it after the wait + // stays open for a manual close, so a close never starts on a reading the HTLC may have lowered. repeat(HTLC_CLEAR_RECHECKS) { - if (!MoveToSparkMath.mayHoldTheMoveHtlc(emptied)) return@repeat + if (emptied.none(MoveToSparkMath::mayHoldTheMoveHtlc)) return@repeat delay(HTLC_CLEAR_RECHECK) emptied = readEmptied(before, paymentsAtStart) } - emptied.forEach { channel -> + emptied.filterNot(MoveToSparkMath::mayHoldTheMoveHtlc).forEach { channel -> invoke(channel) .onSuccess { Logger.info("Closed channel '${channel.channelId}' emptied by a move", context = TAG) } .onFailure { Logger.warn("Failed to close channel '${channel.channelId}'", it, context = TAG) } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 19ad702e05..f78c87eecb 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -368,15 +368,21 @@ class MoveToSparkRepoTest : BaseUnitTest() { } @Test - fun `an emptied channel that still holds the minimum in capacity may hold the move's htlc`() { - val before = listOf(channel("held", 50_000uL)) + fun `a channel with capacity left may hold the move's htlc unless its gap is the commitment fee`() { val held = channel("held", 0uL).copy(outboundCapacityMsat = 5_002_000uL) + // 2 500 sat/kW: a legacy commitment keeps back 4 480 sats, so 5 342 sats of capacity send only 862. + val legacy = channel("legacy", 862uL).copy( + outboundCapacityMsat = 5_342_000uL, + isOutbound = true, + feerateSatPer1000Weight = 2_500u, + ) - val emptied = MoveToSparkMath.emptiedChannels(before, listOf(held)) - + val emptied = MoveToSparkMath.emptiedChannels(listOf(channel("held", 50_000uL)), listOf(held)) assertEquals(listOf("held"), emptied.map { it.channelId }) - assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(emptied)) - assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(listOf(held.copy(outboundCapacityMsat = 999_000uL)))) + assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(held), "a peer-funded channel with capacity left") + assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(held.copy(isOutbound = true, feerateSatPer1000Weight = 2_500u))) + assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(legacy), "a legacy reserve gap") + assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(held.copy(outboundCapacityMsat = 999_000uL))) } @Test diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index d4caea32b5..e9faa2e00e 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -184,14 +184,20 @@ class CloseChannelUseCaseTest : BaseUnitTest() { } @Test - fun `a move's close takes a channel whose limit stays under the minimum through the wait`() = test { - val reserved = channel("channel_1", 0uL).copy(outboundCapacityMsat = 5_002_000uL) - lightningState.value = LightningState(channels = persistentListOf(reserved)) + fun `a move's close takes a channel whose limit sits at its reserve and leaves one that stays held`() = test { + val reserved = channel("channel_1", 862uL).copy( + outboundCapacityMsat = 5_342_000uL, + isOutbound = true, + feerateSatPer1000Weight = 2_500u, + ) + val held = channel("channel_2", 0uL).copy(outboundCapacityMsat = 5_002_000uL) + lightningState.value = LightningState(channels = persistentListOf(reserved, held)) - sut.closeEmptiedByMove(listOf(channel), emptyList()) + sut.closeEmptiedByMove(listOf(channel, channel("channel_2", 50_000uL)), emptyList()) verify(lightningRepo, times(16)).syncState() verify(lightningRepo).closeChannel(eq(reserved), any(), anyOrNull()) + verify(lightningRepo, never()).closeChannel(eq(held), any(), anyOrNull()) } @Test From 4f83d5103a14dacbd982007169c8f39751bb2462 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 21:11:29 +0100 Subject: [PATCH 21/23] fix: close a moved channel only on a reading that holds A send limit the peer's in-flight cap held down could match a commitment reserve by chance, so the first read skipped the recheck and closed a channel the move had not emptied. A channel with capacity left now closes only when its reserve explains its limit in two reads 2 s apart with nothing changed between them. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 14 ++++++++++++++ .../to/bitkit/usecases/CloseChannelUseCase.kt | 8 +++++--- .../bitkit/repositories/MoveToSparkRepoTest.kt | 17 +++++++++++++++++ .../bitkit/usecases/CloseChannelUseCaseTest.kt | 15 +++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 69f6049610..f7542c8b5d 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -450,6 +450,20 @@ object MoveToSparkMath { return reserves.none { abs(gapSats - it) <= 1 } } + /** + * Whether [channel] can close: its capacity is under the minimum, or its reserve explains its limit in this read + * and in the one before ([previous]), unchanged. One read can match a reserve by chance while the move's HTLC still + * counts against the peer's cap; the HTLC clears within the recheck, so a reading that holds across it is what + * stays. + */ + fun isEmptiedForGood(channel: ChannelDetails, previous: List?): Boolean { + if (msatFloorOf(channel.outboundCapacityMsat) < MIN_MOVE_SATS) return true + if (mayHoldTheMoveHtlc(channel)) return false + val was = previous?.firstOrNull { it.channelId == channel.channelId } ?: return false + return was.outboundCapacityMsat == channel.outboundCapacityMsat && + was.nextOutboundHtlcLimitMsat == channel.nextOutboundHtlcLimitMsat + } + /** * The payments read before and after a read of the channels, or null when a read failed or an outbound Lightning * payment appeared or changed between them: it may have held an HTLC while the channels were read. Also null when a diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index 54dfbcc790..1ab775d6ed 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -66,14 +66,16 @@ class CloseChannelUseCase @Inject constructor( ) = withContext(ioDispatcher) { walletRepo.syncNodeAndWallet() var emptied = readEmptied(before, paymentsAtStart) - // A channel whose limit rises once the move's HTLC clears drops out. One that may still hold it after the wait + var previous: List? = null + // A channel whose limit rises once the move's HTLC clears drops out. One not emptied for good after the wait // stays open for a manual close, so a close never starts on a reading the HTLC may have lowered. repeat(HTLC_CLEAR_RECHECKS) { - if (emptied.none(MoveToSparkMath::mayHoldTheMoveHtlc)) return@repeat + if (emptied.all { MoveToSparkMath.isEmptiedForGood(it, previous) }) return@repeat delay(HTLC_CLEAR_RECHECK) + previous = emptied emptied = readEmptied(before, paymentsAtStart) } - emptied.filterNot(MoveToSparkMath::mayHoldTheMoveHtlc).forEach { channel -> + emptied.filter { MoveToSparkMath.isEmptiedForGood(it, previous) }.forEach { channel -> invoke(channel) .onSuccess { Logger.info("Closed channel '${channel.channelId}' emptied by a move", context = TAG) } .onFailure { Logger.warn("Failed to close channel '${channel.channelId}'", it, context = TAG) } diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index f78c87eecb..55f508b3ab 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -385,6 +385,23 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(held.copy(outboundCapacityMsat = 999_000uL))) } + @Test + fun `a channel with capacity left is emptied for good only on two unchanged reads at its reserve`() { + // 4 000 sat/kW: a peer-capped 2-sat limit on 7 170 sats matches the 7 168-sat legacy reserve by chance. + val capped = channel("capped", 2uL).copy( + outboundCapacityMsat = 7_170_000uL, + isOutbound = true, + feerateSatPer1000Weight = 4_000u, + ) + + assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(capped)) + assertFalse(MoveToSparkMath.isEmptiedForGood(capped, previous = null), "closed on a single read") + val risen = capped.copy(nextOutboundHtlcLimitMsat = 1_332_000uL) + assertFalse(MoveToSparkMath.isEmptiedForGood(capped, previous = listOf(risen)), "closed on a changed read") + assertTrue(MoveToSparkMath.isEmptiedForGood(capped, previous = listOf(capped))) + assertTrue(MoveToSparkMath.isEmptiedForGood(channel("small", 0uL), previous = null)) + } + @Test fun `payments around the channels read are unclear when one changed or could not be read`() { val sent = nodeSend(PaymentStatus.FAILED) diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index e9faa2e00e..64ca8b5065 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -200,6 +200,21 @@ class CloseChannelUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(eq(held), any(), anyOrNull()) } + @Test + fun `a move's close reads a channel at its reserve twice before taking it`() = test { + val reserved = channel("channel_1", 862uL).copy( + outboundCapacityMsat = 5_342_000uL, + isOutbound = true, + feerateSatPer1000Weight = 2_500u, + ) + lightningState.value = LightningState(channels = persistentListOf(reserved)) + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + + verify(lightningRepo, times(2)).syncState() + verify(lightningRepo).closeChannel(eq(reserved), any(), anyOrNull()) + } + @Test fun `a move's close reads the channels from the node after a sync, not the stale state`() = test { lightningState.value = LightningState(channels = persistentListOf(channel)) From aa5984665b9e83832d9891f9b6cd267b973aaa7d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 21:28:41 +0100 Subject: [PATCH 22/23] fix: match LDK's send limit before closing a moved channel The reserve check used one HTLC for a legacy commitment, so a legacy channel a move emptied (1 400 sats of capacity sending 860 at 253 sat/kW) matched neither reserve and stayed open. It now predicts the limit as LDK 0.2 computes it once HTLCs clear: an above-dust HTLC and the fee spike buffer HTLC, doubled for legacy, and one HTLC less under the dust limit. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 43 +++++++++++++------ .../repositories/MoveToSparkRepoTest.kt | 4 ++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index f7542c8b5d..d39779fc3d 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -347,6 +347,8 @@ object MoveToSparkMath { private const val ANCHOR_COMMITMENT_WEIGHT = 1_124L private const val LEGACY_COMMITMENT_WEIGHT = 724L private const val HTLC_OUTPUT_WEIGHT = 172L + private const val HTLC_TIMEOUT_WEIGHT = 663L + private const val DUST_LIMIT_SATS = 354L /** The fee guessed for the first quote of a full move, as a share of the amount in parts per million. */ private const val FIRST_FEE_GUESS_PPM = 5_000uL @@ -433,21 +435,38 @@ object MoveToSparkMath { /** * Whether a channel's send limit may still be held under the minimum by the move's settled HTLC counting against * the peer's in-flight cap, which clears, rather than by what stays. ldk-node exposes neither the HTLCs nor the - * channel type, so it is ruled out only when the capacity itself is under the minimum, or when the gap between - * capacity and limit is exactly the commitment fee LDK keeps back for a channel we funded: an anchor commitment - * with two HTLCs, or a legacy one with one HTLC at twice the feerate, within a sat of rounding. + * channel type, so it is ruled out only when the capacity itself is under the minimum, or when the limit read is, + * within a sat, the one LDK leaves on a channel we funded once its HTLCs clear, for an anchor or a legacy + * commitment. */ fun mayHoldTheMoveHtlc(channel: ChannelDetails): Boolean { - val capacitySats = msatFloorOf(channel.outboundCapacityMsat).toLong() - if (capacitySats < MIN_MOVE_SATS.toLong()) return false + if (msatFloorOf(channel.outboundCapacityMsat) < MIN_MOVE_SATS) return false if (!channel.isOutbound) return true - val gapSats = capacitySats - msatFloorOf(channel.nextOutboundHtlcLimitMsat).toLong() - val feerate = channel.feerateSatPer1000Weight.toLong() - val reserves = listOf( - feerate * (ANCHOR_COMMITMENT_WEIGHT + 2 * HTLC_OUTPUT_WEIGHT) / 1000, - 2 * feerate * (LEGACY_COMMITMENT_WEIGHT + HTLC_OUTPUT_WEIGHT) / 1000, - ) - return reserves.none { abs(gapSats - it) <= 1 } + val limitSats = msatFloorOf(channel.nextOutboundHtlcLimitMsat).toLong() + return listOf(false, true).none { isLegacy -> + val predictedSats = clearedLimitMsat( + capacityMsat = channel.outboundCapacityMsat.toLong(), + feerate = channel.feerateSatPer1000Weight.toLong(), + isLegacy = isLegacy, + ) / 1000 + abs(limitSats - predictedSats) <= 1 + } + } + + /** + * The send limit LDK 0.2 leaves on a channel we funded with no HTLCs pending (`get_available_balances_for_scope`): + * capacity less the commitment fee for an above-dust HTLC and its fee spike buffer HTLC, doubled for a legacy + * commitment; under the dust limit it reserves one HTLC less and stays under the limit. The dust limit is LDK's + * default 354 sats, plus the HTLC timeout transaction's fee on a legacy commitment. + */ + fun clearedLimitMsat(capacityMsat: Long, feerate: Long, isLegacy: Boolean): Long { + val baseWeight = if (isLegacy) LEGACY_COMMITMENT_WEIGHT else ANCHOR_COMMITMENT_WEIGHT + val multiplier = if (isLegacy) 2 else 1 + fun feeMsat(htlcs: Long) = feerate * (baseWeight + htlcs * HTLC_OUTPUT_WEIGHT) / 1000 * 1000 * multiplier + val dustMsat = ((if (isLegacy) feerate * HTLC_TIMEOUT_WEIGHT / 1000 else 0L) + DUST_LIMIT_SATS) * 1000 + val aboveDust = capacityMsat - feeMsat(2) + if (aboveDust >= dustMsat) return aboveDust + return maxOf(0L, minOf(capacityMsat - feeMsat(1), dustMsat - 1, capacityMsat)) } /** diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 55f508b3ab..82d9431283 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -382,6 +382,10 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(held), "a peer-funded channel with capacity left") assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(held.copy(isOutbound = true, feerateSatPer1000Weight = 2_500u))) assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(legacy), "a legacy reserve gap") + // A legacy channel at 253 sat/kW reserves 540 sats above dust: 1 400 of capacity sends 860. + val small = legacy.copy(outboundCapacityMsat = 1_400_000uL, feerateSatPer1000Weight = 253u) + assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(small.copy(nextOutboundHtlcLimitMsat = 860_000uL))) + assertTrue(MoveToSparkMath.mayHoldTheMoveHtlc(small.copy(nextOutboundHtlcLimitMsat = 947_000uL))) assertFalse(MoveToSparkMath.mayHoldTheMoveHtlc(held.copy(outboundCapacityMsat = 999_000uL))) } From 670996266e247fcd23344807c013c6b913cfd19b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 10:54:44 +0100 Subject: [PATCH 23/23] fix: close emptied channels past on-chain sends and skip quickpay's channel wait An unconfirmed on-chain send no longer counts as a payment in flight when closing the channels a move emptied, and a scan waits for usable channels a second time only while QuickPay is on. Verified: just format, compile, test, lint --- .../to/bitkit/usecases/CloseChannelUseCase.kt | 8 ++++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 3 ++- .../usecases/CloseChannelUseCaseTest.kt | 20 ++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 24 +++++++++++++++++++ 4 files changed, 53 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt index 1ab775d6ed..2033ecc200 100644 --- a/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.withContext import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.di.IoDispatcher import to.bitkit.ext.amountOnClose @@ -100,7 +101,12 @@ class CloseChannelUseCase @Inject constructor( Logger.info("Kept the channels a move may have emptied open while its payments are unclear", context = TAG) return emptyList() } - if (payments.any { it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.PENDING }) { + val isInFlight = payments.any { + it.direction == PaymentDirection.OUTBOUND && + it.status == PaymentStatus.PENDING && + it.kind !is PaymentKind.Onchain + } + if (isInFlight) { Logger.info("Kept the channels a move may have emptied open while a payment is in flight", context = TAG) return emptyList() } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 7bc30c6653..223bc526d3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6652,7 +6652,8 @@ class AppViewModel @Inject constructor( val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. While // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. - if (!open && channelsAreSettling()) waitForUsableChannels(walletGeneration) + val isQuickPayOn = settingsStore.data.first().isQuickPayEnabled + if (!open && isQuickPayOn && channelsAreSettling()) waitForUsableChannels(walletGeneration) if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) diff --git a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt index 64ca8b5065..596dee1230 100644 --- a/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import org.junit.Before import org.junit.Test +import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentKind @@ -112,6 +113,25 @@ class CloseChannelUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `a move's close takes an emptied channel while an on-chain send is unconfirmed`() = test { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + val onchainSend = PaymentDetails( + id = "txid", + kind = PaymentKind.Onchain(txid = "txid", status = ConfirmationStatus.Unconfirmed), + amountMsat = 10_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = PaymentStatus.PENDING, + latestUpdateTimestamp = 0uL, + ) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(onchainSend)) + + sut.closeEmptiedByMove(listOf(channel), listOf(onchainSend)) + + verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) + } + @Test fun `a move's close keeps channels open while its payments cannot be read`() = test { lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 02a746c287..41d6b435df 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -77,6 +77,7 @@ import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentFailureReason @@ -21665,6 +21666,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") } + @Test + fun `a fixed-amount scan with QuickPay off does not wait for channels whose peer is offline`() = test { + val bolt11 = "lnbcrt1quickpayoffpeeroffline" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.0002&lightning=$bolt11" + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 20_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + val offlinePeerChannel = mock { on { isUsable } doReturn false } + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = persistentListOf(offlinePeerChannel), + ) + ) + ) + + sut.onScanResult(uri) + advanceUntilIdle() + + // The unified scan's own Lightning check waits once; QuickPay, off here, must not wait a second time. + verify(lightningRepo, times(1)).waitForUsableChannels() + assertEquals(bolt11, sut.sendUiState.value.decodedInvoice?.bolt11) + } + @Test fun `an update needed only by send time moves nothing and shows its fee`() = test { val bolt11 = "lnbcrt1unseenatsend"