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/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/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..d39779fc3d 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -4,23 +4,31 @@ 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 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 +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 @@ -30,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 @@ -57,6 +66,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 +86,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 +116,80 @@ 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, + ) + + /** 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, + 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 + * [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( + quote: MoveToSparkQuote, + bolt11: String, + amountSats: ULong, + onMove: (MoveToSparkOutcome) -> Unit = {}, + ): Result = + withContext(bgDispatcher) { + runSuspendCatching { + val feeSats = feeAfterUpdateOrNull(bolt11, amountSats) + ?: throw MoveToSparkError.UpdateFallsShort(amountSats) + if (!MoveToSparkMath.coversPayment(quote, sparkRepo.state.value, amountSats, feeSats)) { + throw MoveToSparkError.UpdateFallsShort(amountSats) + } + 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)) { + 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 + * 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) { + bolt11?.let { feeAfterUpdateOrNull(it, amountSats) } ?: SparkFees.serviceFeeSats(amountSats).also { + Logger.debug("Fell back to Spark's service fee for an update payment", context = TAG) + } + } + + /** + * 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() + /** * 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 +230,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) @@ -250,6 +344,11 @@ 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 + 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 @@ -288,8 +387,124 @@ 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()) + } + + /** 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 = + 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, 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 { + val beforeById = before.associateBy { it.channelId } + return after.orEmpty().filterOpen().filter { + val was = beforeById[it.channelId] ?: return@filter false + msatFloorOf(was.nextOutboundHtlcLimitMsat) >= MIN_MOVE_SATS && + msatFloorOf(it.nextOutboundHtlcLimitMsat) < MIN_MOVE_SATS + } + } + + /** + * 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 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 { + if (msatFloorOf(channel.outboundCapacityMsat) < MIN_MOVE_SATS) return false + if (!channel.isOutbound) return true + 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)) + } + + /** + * 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 + * payment other than a move's changed since the move started ([moveStart]): it may have emptied another channel. + */ + 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 + } + + 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( @@ -322,6 +537,16 @@ 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'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") + /** 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 3ffc0a4355..347b27ad3b 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -209,7 +209,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 @@ -673,10 +672,6 @@ fun ContentView( hardwareWalletId = sheet.hardwareWalletId, walletState = walletState, isOffline = connectivityState != ConnectivityState.CONNECTED, - navigateToExternalConnection = { - navController.navigateTo(ExternalConnection()) - appViewModel.hideSheet() - }, ) } } @@ -725,6 +720,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() }, ) @@ -796,11 +795,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 -> { @@ -1059,7 +1055,12 @@ private fun RootNavHost( cjitDetailSettings(navController) swapsSettings(navController) swapDetailSettings(navController) - lightningConnections(navController, walletViewModel, transferViewModel) + lightningConnections( + navController, + walletViewModel, + transferViewModel, + onMoveToSpark = { appViewModel.showSheet(Sheet.MoveToSpark) }, + ) activityItem(activityListViewModel, navController, settingsViewModel) authCheck(navController) logs(navController) @@ -1428,7 +1429,7 @@ private fun NavGraphBuilder.home( hasSparkBalance = sparkState.shownSpendingSats > 0uL, // A move left while it ran keeps its way back to its result, also once nothing is left to move. canMoveToSpark = hasRetainedMove || MoveToSparkMath.canMove(lightningState.channels, sparkState), - onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, + onMoveToSparkClick = { appViewModel.showSheet(Sheet.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { @@ -2063,6 +2064,7 @@ private fun NavGraphBuilder.lightningConnections( navController: NavHostController, walletViewModel: WalletViewModel, transferViewModel: TransferViewModel, + onMoveToSpark: () -> Unit, ) { navigationWithDefaultTransitions( startDestination = Routes.LightningConnections, @@ -2070,7 +2072,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() @@ -2102,18 +2104,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( @@ -2700,9 +2690,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 185ca32729..ead537dbc6 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 @@ -372,6 +379,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, and the swipe waits for the quote. + LaunchedEffect(uiState.sparkUpdateQuote) { + if (uiState.sparkUpdateQuote != null) showDetails = true + } val swipeProgress = remember { mutableFloatStateOf(0f) } val isPreparing = preparingRequest != null val isLnurlPay = !isPreparing && uiState.paysLnurl @@ -549,6 +560,7 @@ private fun ContentRunning( private fun SendUiState.canSwipeToPay() = isAmountInputValid && !isFundingSourceLoading && isHardwareFeeReady && + !isSparkUpdateQuoting && !(payMethod == SendMethod.ONCHAIN && onchainFeeUi.isLoading) @Composable @@ -883,6 +895,8 @@ private fun LightningDetails( } } + UpdateFeeCell(uiState.sparkUpdateQuote?.feeSats) + val swapRoute = uiState.paykitSwapRoute val swapQuote = swapRoute?.quote if (swapQuote != null) { @@ -895,14 +909,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) { @@ -1007,6 +1013,8 @@ private fun LnurlPayDetails( } } + UpdateFeeCell(uiState.sparkUpdateQuote?.feeSats) + if (lnurlPay.data.commentAllowed()) { LnurlCommentSection(uiState, onEvent) } @@ -1370,3 +1378,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 b19afb57c4..948ce5a958 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 @@ -86,6 +86,7 @@ object LightningConnectionsTestTags { fun LightningConnectionsScreen( navController: NavController, viewModel: LightningConnectionsViewModel, + onClickMoveToSpark: () -> Unit, ) { val context = LocalContext.current val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -105,7 +106,7 @@ fun LightningConnectionsScreen( navController.navigateTo(Routes.ChannelDetail(channelUi.details.channelId)) }, onClickSpark = { navController.navigateTo(Routes.SparkDetail) }, - onClickMoveToSpark = { navController.navigateTo(Routes.MoveToSpark) }, + onClickMoveToSpark = onClickMoveToSpark, 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 657ed31caf..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 @@ -9,22 +9,25 @@ 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 org.lightningdevkit.ldknode.PaymentDetails 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 +35,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" @@ -115,11 +119,13 @@ 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 _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } moveJob = scope.launch { + val paymentsBefore = lightningRepo.listPaymentsOrNull() try { moveToSparkRepo.move(quote).fold( onSuccess = { outcome -> @@ -128,7 +134,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, paymentsBefore) + settled?.await()?.let { + showLateOutcome(it, moveGeneration) + if (it.isSuccess) closeEmptied(channelsBefore, paymentsBefore) + } }, onFailure = { error -> if (generation.get() == moveGeneration) _uiState.update { error.toUiState() } @@ -143,7 +153,11 @@ 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, paymentsBefore: List?) { + scope.launch { closeChannelUseCase.closeEmptiedByMove(channelsBefore, paymentsBefore) } } private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { @@ -158,10 +172,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..a0ed059c79 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,274 @@ 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 + +/** 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. + */ +@Composable +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).testTag(DISMISS_TAG) + ) + } + 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).testTag(DISMISS_TAG) + ) + 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).testTag(DISMISS_TAG) + ) + return@Modal + } + 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) }, + modifier = Modifier.weight(1f).testTag("MoveToSparkTrySmaller") + ) + } +} -/** Tells channel holders that Blocktank closes its channels and that moving the balance to Spark costs least. */ @Composable -fun MoveToSparkSheet(onLater: () -> Unit, onMove: () -> Unit, modifier: Modifier = Modifier) { +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).testTag(DISMISS_TAG) + ) + return@Modal + } + 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) }, + 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 +300,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 PreviewUpdate() { + AppThemeSurface { + BottomSheetPreview { + Content(uiState = MoveToSparkUiState.Confirm(MoveToSparkQuote("lnbc", 98_500uL, 12uL))) + } + } +} + @Preview(showSystemUi = true) @Composable -private fun Preview() { - AppThemeSurface { BottomSheetPreview { MoveToSparkSheet({}, {}) } } +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/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 51cdac5b48..d022f04d4c 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -330,6 +330,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 new file mode 100644 index 0000000000..2033ecc200 --- /dev/null +++ b/app/src/main/java/to/bitkit/usecases/CloseChannelUseCase.kt @@ -0,0 +1,115 @@ +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 +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 +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 +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 +class CloseChannelUseCase @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val lightningRepo: LightningRepo, + private val transferRepo: TransferRepo, + private val walletRepo: WalletRepo, + private val moveToSparkRepo: MoveToSparkRepo, +) { + 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) { + 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, 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. + */ + suspend fun closeEmptiedByMove( + before: List, + paymentsAtStart: List?, + ) = withContext(ioDispatcher) { + walletRepo.syncNodeAndWallet() + var emptied = readEmptied(before, paymentsAtStart) + 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.all { MoveToSparkMath.isEmptiedForGood(it, previous) }) return@repeat + delay(HTLC_CLEAR_RECHECK) + previous = emptied + emptied = readEmptied(before, paymentsAtStart) + } + 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) } + } + } + + /** 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() + 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 emptyList() + } + 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() + } + return MoveToSparkMath.emptiedChannels(before, lightningRepo.lightningState.value.channels) + } +} 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 7ab6f964c6..b90423ad8b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -90,8 +90,10 @@ 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.PaymentDetails import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import org.lightningdevkit.ldknode.SpendableUtxo @@ -188,6 +190,9 @@ 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 import to.bitkit.repositories.NodeEventUpdate import to.bitkit.repositories.OnchainPreparedReceipt @@ -276,6 +281,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 @@ -364,6 +370,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, @@ -433,6 +440,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 val sparkUpdateQuoteRun = AtomicLong(0L) + /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ private var sendSession = 0L @@ -3501,7 +3511,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( @@ -3652,7 +3662,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) { @@ -4972,7 +4982,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) } @@ -5329,12 +5340,16 @@ 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 && 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) } } } @@ -5361,6 +5376,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 @@ -5966,7 +5985,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) } } @@ -6358,7 +6377,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( @@ -6438,7 +6457,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), @@ -6473,6 +6492,7 @@ class AppViewModel @Inject constructor( if (quickPayHandled) return navigateToSendRoute(fromMainScanner, SendRoute.Confirm, SendEffect.NavigateToConfirm, walletGeneration) + estimateLightningRoutingFeesIfNeeded(walletGeneration) return } @@ -6630,6 +6650,11 @@ 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. While + // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. + 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) if (!canApply) return false @@ -6680,6 +6705,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) @@ -6698,6 +6730,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 { val review = preparedFeeReview if (review == null && !prepareCoinSelection()) return@launch @@ -6717,6 +6750,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() @@ -6853,6 +6891,7 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToAmount) return } + if (!confirmSparkUpdateQuote()) return val incomingPaymentRequest = contactPaymentContext?.incomingPaymentRequest val proofPreparation = preparePaymentProof(incomingPaymentRequest) @@ -7945,17 +7984,31 @@ 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 = sendLightning( - decodedInvoice.bolt11, - paymentAmount, - incomingPaymentRequest?.submissionDeadline(paykitPaymentTerms), - ) { - authorizationError = incomingPaymentRequest?.let { - paykitPaymentRequestRepo.ensurePaymentAllowed(it).exceptionOrNull() - } - authorizationError == null - } + // 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 + var updateFailed = false + val result = if (refusedBeforeUpdate != null) { + Result.failure(refusedBeforeUpdate) + } else { + updateSpendingBalanceIfNeeded(decodedInvoice.bolt11, displayAmountSats).onFailure { updateFailed = true } + }.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) @@ -7979,7 +8032,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) @@ -7996,6 +8049,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) @@ -8008,6 +8066,69 @@ 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. 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.approvedSparkUpdateQuote + 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() + val paymentsBefore = lightningRepo.listPaymentsOrNull() + return moveToSparkRepo.updateToSend(fresh, bolt11, amountSats) { + closeChannelsEmptiedBy(it, channelsBefore, paymentsBefore) + }.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.needsSparkUpdate()) 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.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) + setSendEffect(SendEffect.ResetConfirm) + 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, + paymentsBefore: List?, + ) { + viewModelScope.launch(bgDispatcher) { + if (outcome is MoveToSparkOutcome.InFlight && moveToSparkRepo.awaitSettled(outcome).isFailure) return@launch + closeChannelUseCase.closeEmptiedByMove(channelsBefore, paymentsBefore) + } + } + /** Resolves a pending send whose outcome was handled before it was tracked, which no later event resolves. */ private suspend fun resolveSettledPendingSend(paymentHash: String) { val event = lightningRepo.settledSparkSendEvent(paymentHash) ?: return @@ -8041,10 +8162,12 @@ class AppViewModel @Inject constructor( paymentHash: String, error: Throwable, isPaymentRequest: Boolean, + updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false else if !isPaymentRequest -> true - is LightningPaymentFailedError -> { + // 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 } @@ -8727,11 +8850,26 @@ 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. 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) + return + } val feeResult = if (decodedInvoice.amountSatoshis > 0uL) { lightningRepo.estimateRoutingFees(decodedInvoice.bolt11) @@ -8751,6 +8889,29 @@ 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 run = sparkUpdateQuoteRun.incrementAndGet() + _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 { + // An edit such as a funding switch bumps the generation without quoting again, so the run owns the flag. + _sendUiState.update { if (run != sparkUpdateQuoteRun.get()) it else it.copy(isSparkUpdateQuoting = false) } + } + } + private suspend fun estimateMaxAmountRoutingFee() { val currentState = _sendUiState.value if (currentState.payMethod != SendMethod.LIGHTNING) return @@ -10451,6 +10612,12 @@ 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, + /** 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, val lastLightningFee: Long = 0L, val contactPaymentProfile: PubkyProfile? = null, @@ -10640,6 +10807,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/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 dbf2910d98..1e0a037503 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -167,31 +167,29 @@ قابل للاستخدام أرصدة 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 في دفعة واحدة. المبلغ\n<accent>كبير جدًا</accent> + تحديث + رسوم التحديث: %1$s + تحديث رصيد الإنفاق + يغيّر Bitkit مزوّد Lightning. حدّث رصيد الإنفاق لمواصلة الدفعات الفورية والرخيصة. + تحديث\n<accent>رصيد الإنفاق</accent> + تم تحديث رصيد الإنفاق + جزء من رصيد الإنفاق موجود الآن على Spark. انقل الباقي بالطريقة نفسها. + تم نقل رصيد الإنفاق بنجاح إلى Spark، مزوّد خدمة Lightning الجديد في Bitkit. + رصيد الإنفاق\n<accent>محدَّث</accent> حد HTLC الصادر التالي الحد الأدنى لـ HTLC الصادر التالي قبل أن تتمكن من تحويل الأموال من رصيد مدخراتك، تحتاج إلى إرسال Bitcoin إلى محفظة Bitkit الخاصة بك. @@ -1116,14 +1114,11 @@ جارٍ إرسال الإيصال تم إرسال الإيصال استلام - استلام أموال Lightning استلام Bitcoin فاتورة Bitcoin تم نسخ الفاتورة إلى الحافظة فاتورة Lightning ملاحظة اختيارية للدافع - استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. - استلم على <accent>رصيد الإنفاق</accent> عرض التفاصيل عرض رمز QR تعديل الفاتورة @@ -1182,6 +1177,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 5f7d70d29d..b58842239c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -174,31 +174,29 @@ 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. 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. @@ -1146,14 +1144,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 @@ -1215,6 +1210,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 200e4ed905..dcd5fcb697 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -171,31 +171,29 @@ É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. 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. @@ -1140,14 +1138,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 @@ -1208,6 +1203,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 3f33af27d0..40607cb7d4 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -174,31 +174,29 @@ 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. Čá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. @@ -1144,14 +1142,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 @@ -1213,6 +1208,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 bae085bd48..e264657704 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -102,31 +102,29 @@ 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. 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> Übertragung auf das Sparkonto fehlgeschlagen Genehmigen @@ -1059,6 +1057,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? @@ -1140,9 +1139,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 bc73f69bcc..cf19c8ad70 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -167,31 +167,29 @@ Είναι χρησιμοποιήσιμο Υπόλοιπα 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 με μία πληρωμή. Πολύ μεγάλο\n<accent>ποσό</accent> + Ενημέρωση + Χρέωση ενημέρωσης: %1$s + Ενημέρωση υπολοίπου δαπανών + Το Bitkit αλλάζει πάροχο Lightning. Ενημερώστε το υπόλοιπο δαπανών σας για να συνεχίσετε να κάνετε άμεσες, φθηνές πληρωμές. + Ενημέρωση\n<accent>υπολοίπου δαπανών</accent> + Το υπόλοιπο δαπανών ενημερώθηκε + Μέρος του υπολοίπου δαπανών σας βρίσκεται τώρα στο Spark. Μεταφέρετε το υπόλοιπο με τον ίδιο τρόπο. + Το υπόλοιπο δαπανών σας μεταφέρθηκε με επιτυχία στο Spark, τον νέο πάροχο υπηρεσιών Lightning του Bitkit. + Υπόλοιπο δαπανών\n<accent>ενημερώθηκε</accent> Όριο επόμενου εξερχόμενου HTLC Ελάχιστο επόμενο εξερχόμενο HTLC Πριν μπορέσεις να μεταφέρεις κεφάλαια από το υπόλοιπο αποταμιεύσεων, πρέπει να στείλεις bitcoin στο πορτοφόλι Bitkit. @@ -1121,14 +1119,11 @@ Αποστολή απόδειξης Η απόδειξη στάλθηκε Λήψη - Λήψη κεφαλαίων Lightning Λήψη Bitcoin Τιμολόγιο Bitcoin Το τιμολόγιο αντιγράφηκε στο πρόχειρο Τιμολόγιο Lightning Προαιρετική σημείωση προς τον πληρωτή - Απόλαυσε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. - Λήψη σε <accent>υπόλοιπο δαπανών</accent> Εμφάνιση λεπτομερειών Εμφάνιση κωδικού QR Επεξεργασία τιμολογίου @@ -1187,6 +1182,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 c17a93ab16..6f90a0ff8a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -173,31 +173,29 @@ ¿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. 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. @@ -1141,14 +1139,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 @@ -1208,6 +1203,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 fca79cbad8..62849364a2 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -140,31 +140,29 @@ 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. 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. @@ -1051,6 +1049,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? @@ -1127,14 +1126,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 6348b5c2d1..5a288356da 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -101,31 +101,29 @@ 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. 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> Impossible de transférer vers l\'épargne Approuver @@ -1060,6 +1058,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 ? @@ -1245,9 +1244,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 0502937533..31f2619b23 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -172,31 +172,29 @@ È 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. 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. @@ -1142,14 +1140,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 @@ -1211,6 +1206,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 668f99f52f..8870ed8a12 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -171,31 +171,29 @@ 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. 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. @@ -1137,14 +1135,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 @@ -1206,6 +1201,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 de3c7af7e1..5eb1034dd8 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -103,31 +103,29 @@ 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ą. 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> Nie udało się przesłać do oszczędności Zatwierdź @@ -1062,6 +1060,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ć? @@ -1251,9 +1250,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 5bbd2d36f3..8ec73508a2 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -175,31 +175,29 @@ É 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. 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. @@ -1146,14 +1144,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 @@ -1215,6 +1210,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 3d7961678c..e18d81de1a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -98,31 +98,29 @@ 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. 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> Não foi possível transferir para a poupança Aprovar @@ -923,6 +921,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? @@ -1095,13 +1094,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 26cc6c978c..a86884589a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -183,31 +183,29 @@ Можно Использовать Балансы 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 одним платежом. Сумма\n<accent>слишком велика</accent> + Обновить + Комиссия за обновление: %1$s + Обновить баланс расходов + Bitkit меняет Lightning-провайдера. Обновите баланс расходов, чтобы и дальше платить мгновенно и дёшево. + Обновить\n<accent>баланс расходов</accent> + Баланс расходов обновлён + Часть вашего баланса расходов уже в Spark. Перенесите остаток тем же способом. + Ваш баланс расходов успешно перенесён в Spark, нового поставщика Lightning-услуг Bitkit. + Баланс расходов\n<accent>обновлён</accent> Лимит след. исходящего HTLC Мин. след. исходящего HTLC Прежде чем вы сможете перевести средства со своего баланса сбережений, вам нужно отправить биткойны в ваш кошелёк Bitkit. @@ -1159,14 +1157,11 @@ Отправка квитанции Квитанция отправлена Получить - Получить Lightning средства Получить Биткоин Биткоин инвойс Инвойс скопирован в буфер обмена Лайтнинг инвойс Опциональная заметка для плательщика - Наслаждайтесь мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. - Получить на <accent>баланс расходов</accent> Показать детали Показать QR-код Редактировать Инвойс @@ -1229,6 +1224,7 @@ Маршрут Отправить Кому + Комиссия за обновление Да, Отправить <accent>Отправьте\nбиткоин</accent>\nна ваш\nБаланс Расходов Расходы diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 829e675a3b..40b0fd890e 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. @@ -1691,14 +1689,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 @@ -1783,9 +1778,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/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/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..82d9431283 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -24,10 +24,13 @@ 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.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue @@ -35,6 +38,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() @@ -302,4 +306,281 @@ 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 `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(listOf(channel("held", 50_000uL)), listOf(held)) + assertEquals(listOf("held"), emptied.map { it.channelId }) + 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))) + } + + @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) + 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 + 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 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, INVOICE, 60_000uL) + + assertIs(result.exceptionOrNull()) + verify(lightningRepo, never()).payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + } + + @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.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(""))) + + 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 total = 10_000uL + quote.amountSats + + 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 + 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)) + + 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(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, INVOICE, 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 { + 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, INVOICE, 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 { + 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, INVOICE, 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`() = test { + whenever(sparkRepo.estimateFeeSats(INVOICE, 60_000uL)).thenReturn(Result.failure(SparkError.SendRefused(""))) + + 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()) + } + + 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/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/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/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..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 @@ -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(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(), anyOrNull()) + + firstSettled.complete(Result.success(moved)) + + verify(closeChannelUseCase).closeEmptiedByMove(eq(listOf(openChannel)), anyOrNull()) + } + + @Test + fun `a move that fails late closes nothing`() = test { + createViewModel().move() + + firstSettled.complete(Result.failure(MoveToSparkError.PaymentFailed(null))) + + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) + } + + @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..596dee1230 --- /dev/null +++ b/app/src/test/java/to/bitkit/usecases/CloseChannelUseCaseTest.kt @@ -0,0 +1,261 @@ +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.ConfirmationStatus +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 +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 +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 +import kotlin.test.assertTrue + +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 + + @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)) + whenever { lightningRepo.listPaymentsOrNull() }.thenReturn(emptyList()) + whenever(moveToSparkRepo.moveHashes).thenReturn(flowOf(setOf("move"))) + sut = CloseChannelUseCase(testDispatcher, lightningRepo, transferRepo, walletRepo, moveToSparkRepo) + } + + @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), emptyList()) + + verify(lightningRepo).closeChannel(eq(channel("channel_1", 0uL)), any(), anyOrNull()) + 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), emptyList()) + + 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))) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList(), null) + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + + 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), 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 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 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, 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 + 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)) + whenever(lightningRepo.syncState()).thenAnswer { + lightningState.value = LightningState(channels = persistentListOf(channel("channel_1", 0uL))) + Unit + } + + sut.closeEmptiedByMove(listOf(channel), emptyList()) + + 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, + 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 6f313e3d07..9c8d00aeba 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 @@ -173,6 +174,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.OnchainPreparedReceipt import to.bitkit.repositories.OnchainSendAttempt @@ -266,6 +271,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 @@ -317,6 +323,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() @@ -1049,10 +1060,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, @@ -15845,6 +15854,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( @@ -20907,12 +20938,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) @@ -20926,6 +20971,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, @@ -21127,6 +21173,713 @@ 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.quote()).thenReturn(Result.success(quote)) + 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( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = quote, + approvedSparkUpdateQuote = quote, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + inOrder(moveToSparkRepo, lightningRepo) { + verify(moveToSparkRepo).updateToSend(eq(quote), any(), eq(60_000uL), onMove.capture()) + verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) + } + onMove.firstValue(moved) + advanceUntilIdle() + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) + } + + @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(any(), any(), eq(60_000uL), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) + } + + @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(any(), any(), eq(60_000uL), any())) + .thenReturn(Result.failure(MoveToSparkError.UpdateUnsettled())) + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + verify(moveToSparkRepo).updateToSend(any(), any(), eq(60_000uL), onMove.capture()) + onMove.firstValue(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL)) + advanceUntilIdle() + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) + } + + @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(any(), any(), 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), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + val onMove = argumentCaptor<(MoveToSparkOutcome) -> Unit>() + verify(moveToSparkRepo).updateToSend(any(), any(), eq(60_000uL), onMove.capture()) + onMove.firstValue(inFlight) + advanceUntilIdle() + verify(moveToSparkRepo).awaitSettled(inFlight) + verify(closeChannelUseCase).closeEmptiedByMove(any(), anyOrNull()) + } + + @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()) + } + + @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(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, + approvedSparkUpdateQuote = 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 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, + approvedSparkUpdateQuote = 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. + // 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() + } + 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() + 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, + approvedSparkUpdateQuote = 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 `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 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" + 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) + // 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() + + 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() + 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, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) + 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(any(), any(), 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, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + } + assertEquals(raised, sut.sendUiState.value.sparkUpdateQuote) + 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 `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" + 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, + approvedSparkUpdateQuote = 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 + 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, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + verify(moveToSparkRepo, never()).updateToSend(any(), any(), 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, + approvedSparkUpdateQuote = 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 { + openSwapRoutedContactPayment(singleRailSats = 20_000uL) + + 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") @@ -22604,6 +23357,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/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. diff --git a/docs/screens-map.md b/docs/screens-map.md index 1c5043b780..e0c4c0d01e 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 | Settings > Advanced › Connection details Spark | | SparkExitConfirmScreen.kt | Force transfer to Savings (Spark emercency exit) › Force Transfer to Savings Confirm | | SparkExitFeeBumpScreen.kt | `todo` | @@ -370,3 +368,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/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 | 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..677392cd3e --- /dev/null +++ b/journeys/send/update-spending-balance-payment.xml @@ -0,0 +1,24 @@ + + + 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 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 + 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 6c70503dce..5c52a7d947 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 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, 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, 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 diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index e6af2bd96f..6b43825e11 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, an empty Spending balance, no channels and Spark failing to start. On regtest Spark needs no Breez key and starts from local @@ -25,8 +25,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)