diff --git a/app/src/main/java/to/bitkit/data/SettingsStore.kt b/app/src/main/java/to/bitkit/data/SettingsStore.kt index e5085ff311..6373c4c520 100644 --- a/app/src/main/java/to/bitkit/data/SettingsStore.kt +++ b/app/src/main/java/to/bitkit/data/SettingsStore.kt @@ -230,6 +230,7 @@ data class SettingsData( val publicPaykitUsdtEnabled: Boolean = true, val usdtPreference: UsdtPreference = UsdtPreference.UNDECIDED, val hasSeenUsdtIntro: Boolean = false, + val hasSeenMoveToSparkIntro: Boolean = false, val publicPaykitBolt11: String = "", val publicPaykitBolt11PaymentHash: String = "", val publicPaykitBolt11ExpiresAtMillis: Long = 0, diff --git a/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt b/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt index b016c232e3..c8d4f2d8c7 100644 --- a/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt +++ b/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt @@ -15,6 +15,7 @@ import to.bitkit.models.NewTransactionSheetType import to.bitkit.models.msatCeilOf import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.SparkRepo import to.bitkit.services.MigrationService import to.bitkit.utils.Logger @@ -37,6 +38,7 @@ class NotifyPaymentReceivedHandler @Inject constructor( private val clock: Clock, private val receivedNotificationContent: ReceivedNotificationContent, private val sparkRepo: SparkRepo, + private val moveToSparkRepo: MoveToSparkRepo, ) { private val presentationClaimsLock = Any() private val presentationClaims = mutableSetOf() @@ -109,6 +111,8 @@ class NotifyPaymentReceivedHandler @Inject constructor( private suspend fun shouldShowLightning(command: NotifyPaymentReceived.Command.Lightning): Boolean { val paymentId = command.event.paymentId ?: return false + // A move to Spark reports its outcome on its own screen. + if (moveToSparkRepo.isMovePayment(command.event.paymentHash)) return false delay(DELAY_FOR_ACTIVITY_SYNC_MS) return !activityRepo.isActivitySeen(paymentId) } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index eba95ee092..63b44b991b 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1620,6 +1620,27 @@ class LightningRepo @Inject constructor( is EarlierSend.Paid -> Result.success(paymentHash) } + /** Pays [bolt11] from the channels only, never falling back to Spark, which moving a channel balance needs. */ + suspend fun payInvoiceOverLdk( + bolt11: String, + paymentHash: String, + sats: ULong?, + maxTotalRoutingFeeMsat: ULong?, + ): Result = payInvoiceWithLdk( + bolt11 = bolt11, + sats = sats, + paymentHash = paymentHash, + paymentDeadlineAt = null, + maxTotalRoutingFeeMsat = maxTotalRoutingFeeMsat, + onBeforeSend = { true }, + ) + + /** The routing fee for paying [amountSats] to [bolt11] from the channels, never quoted on Spark. */ + suspend fun estimateLdkRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = + executeWhenNodeRunning("estimateLdkRoutingFeesForAmount") { + lightningService.estimateRoutingFeesForAmount(bolt11, amountSats) + } + private suspend fun payInvoiceWithLdk( bolt11: String, sats: ULong?, diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt new file mode 100644 index 0000000000..5336be59bd --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -0,0 +1,304 @@ +package to.bitkit.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +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.PaymentFailureReason +import org.lightningdevkit.ldknode.PaymentStatus +import to.bitkit.di.BgDispatcher +import to.bitkit.ext.runSuspendCatching +import to.bitkit.ext.totalNextOutboundHtlcLimitSats +import to.bitkit.models.safe +import to.bitkit.utils.AppError +import to.bitkit.utils.LdkError +import to.bitkit.utils.Logger +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.atomic.AtomicReference +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.minutes + +/** + * Moves the balance of the user's Lightning channels to their own Spark wallet, paying a Spark invoice over the + * channels only. Blocktank is closing its channels, and this is the cheapest way to keep the balance in Spending. + */ +@Singleton +class MoveToSparkRepo @Inject constructor( + @BgDispatcher private val bgDispatcher: CoroutineDispatcher, + private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, +) { + companion object { + private const val TAG = "MoveToSparkRepo" + private const val INVOICE_DESCRIPTION = "Move to Spark" + private const val INVOICE_EXPIRY_SECS = 3600u + private const val MAX_QUOTE_ROUNDS = 4 + + /** How long the move waits for the payment to settle before it reports it as still in flight. */ + private val PAYMENT_TIMEOUT = 2.minutes + + /** 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) + } + + private val ownPaymentHashes = ConcurrentHashMap.newKeySet() + private val watchedPaymentHashes = ConcurrentHashMap.newKeySet() + private val reportedPaymentHashes = ConcurrentHashMap.newKeySet() + + /** Whether [paymentHash] is a move to Spark, whose send and receive the app does not announce as payments. */ + fun isMovePayment(paymentHash: String): Boolean = paymentHash in ownPaymentHashes + + /** + * Whether the move screen waits on [paymentHash] or already reported its outcome, so the app raises no failure + * notice of its own; after a timeout or cancellation the app does. + */ + fun isWatchedMovePayment(paymentHash: String): Boolean = + paymentHash in watchedPaymentHashes || paymentHash in reportedPaymentHashes + + /** Whether the channels hold a balance worth moving to a usable Spark wallet. */ + val canMove: Flow = combine(lightningRepo.lightningState, sparkRepo.state) { lightning, spark -> + MoveToSparkMath.canMove(lightning.channels, spark) + }.distinctUntilChanged() + + /** The most the channels can send now, before routing fees. */ + fun movableSats(): ULong = MoveToSparkMath.movableSats(lightningRepo.lightningState.value.channels) + + /** + * 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. + */ + suspend fun quote(targetSats: ULong? = null): Result = withContext(bgDispatcher) { + runSuspendCatching { + val limitSats = movableSats() + val wantedSats = targetSats?.coerceAtMost(limitSats) ?: limitSats + if (wantedSats < MoveToSparkMath.MIN_MOVE_SATS || !MoveToSparkMath.hasMovableBalance(limitSats)) { + throw MoveToSparkError.NothingToMove() + } + if (!MoveToSparkMath.isSparkUsable(sparkRepo.state.value)) throw MoveToSparkError.SparkUnavailable() + + val invoice = sparkRepo.createInvoice(null, INVOICE_DESCRIPTION, INVOICE_EXPIRY_SECS).getOrThrow() + var amountSats = MoveToSparkMath.firstCandidate(wantedSats, limitSats) + var fitting: MoveToSparkQuote? = null + // The first amount leaves room for a guessed fee; once the real fee is known, the amount grows to fit it. + repeat(MAX_QUOTE_ROUNDS) { + if (amountSats < MoveToSparkMath.MIN_MOVE_SATS) return@repeat + val estimateSats = lightningRepo.estimateLdkRoutingFeesForAmount(invoice, amountSats).getOrElse { + fitting?.let { quote -> return@runSuspendCatching quote } + throw if (it.isNoRoute()) MoveToSparkError.TooLarge(amountSats, it) else it + } + val feeSats = MoveToSparkMath.quotedFeeSats(estimateSats) + val nextSats = minOf(wantedSats, MoveToSparkMath.amountAfterFee(limitSats, estimateSats)) + if (amountSats.safe() + feeSats.safe() <= limitSats) { + fitting = MoveToSparkQuote(invoice, amountSats, feeSats) + if (nextSats <= amountSats) return@runSuspendCatching checkNotNull(fitting) + } + amountSats = nextSats + } + fitting ?: throw MoveToSparkError.TooLarge(amountSats) + }.onFailure { + Logger.warn("Failed to quote move to Spark of '$targetSats'", it, context = TAG) + } + } + + /** Pays [quote] over the channels and waits for it to settle in Spark. */ + suspend fun move(quote: MoveToSparkQuote): Result = withContext(bgDispatcher) { + runSuspendCatching { + val paymentHash = Bolt11Invoice.fromStr(quote.invoice).paymentHash() + ownPaymentHashes += paymentHash + watchedPaymentHashes += paymentHash + try { + payAndWait(quote, paymentHash) + } finally { + watchedPaymentHashes -= paymentHash + } + }.onFailure { + Logger.error("Failed to move '${quote.amountSats}' sats to Spark", it, context = TAG) + } + } + + private suspend fun payAndWait(quote: MoveToSparkQuote, paymentHash: String): MoveToSparkOutcome = + coroutineScope { + // LDK can report a failure without its hash, so the payment's id identifies it too once it is known. + val paymentId = AtomicReference(null) + // A failure without a hash can arrive before the send returns its id, so it is kept until the id is known. + val hashlessFailures = ConcurrentLinkedQueue() + val settled = async(start = CoroutineStart.UNDISPATCHED) { + lightningRepo.nodeEvents.first { + if (it is Event.PaymentFailed && it.paymentHash == null && paymentId.get() == null) { + hashlessFailures += it + } + it.settles(paymentHash, paymentId.get()) + } + } + val sentId = lightningRepo.payInvoiceOverLdk( + bolt11 = quote.invoice, + paymentHash = paymentHash, + sats = quote.amountSats, + maxTotalRoutingFeeMsat = MoveToSparkMath.feeCapMsat(quote.feeSats), + ).onSuccess { paymentId.set(it) }.getOrElse { + settled.cancel() + val isNoRoute = it.isNoRoute() || it.isSendWithoutRoute(quote.invoice) + throw if (isNoRoute) MoveToSparkError.TooLarge(quote.amountSats, it) else it + } + val earlyFailure = hashlessFailures.firstOrNull { it.paymentId == sentId } + val event = earlyFailure?.also { settled.cancel() } + ?: withTimeoutOrNull(PAYMENT_TIMEOUT) { settled.await() } + if (event != null) reportedPaymentHashes += paymentHash + when (event) { + is Event.PaymentSuccessful -> event.moved(quote.amountSats) + is Event.PaymentFailed if event.reason in NO_ROUTE_REASONS -> + throw MoveToSparkError.TooLarge(quote.amountSats, reason = event.reason) + is Event.PaymentFailed -> throw MoveToSparkError.PaymentFailed(event.reason) + else -> { + settled.cancel() + MoveToSparkOutcome.InFlight(quote.amountSats, paymentHash, sentId) + } + } + } + + /** + * Waits for the payment of a move still [inFlight] to settle after the move stopped waiting. It listens first, then + * reads the node's stored payment, so an outcome that arrived after the move stopped listening is not missed. + */ + suspend fun awaitSettled(inFlight: MoveToSparkOutcome.InFlight): Result = + withContext(bgDispatcher) { + runSuspendCatching { + coroutineScope { + val settled = async(start = CoroutineStart.UNDISPATCHED) { + lightningRepo.nodeEvents.first { it.settles(inFlight.paymentHash, inFlight.paymentId) } + } + val stored = lightningRepo.listPaymentsOrNull()?.firstOrNull { it.id == inFlight.paymentId } + when (stored?.status) { + PaymentStatus.SUCCEEDED -> { + settled.cancel() + MoveToSparkOutcome.Moved(inFlight.amountSats, (stored.feePaidMsat ?: 0uL) / 1000uL) + } + PaymentStatus.FAILED -> { + settled.cancel() + throw MoveToSparkError.PaymentFailed(null) + } + else -> when (val event = settled.await()) { + is Event.PaymentSuccessful -> event.moved(inFlight.amountSats) + else -> throw MoveToSparkError.PaymentFailed((event as? Event.PaymentFailed)?.reason) + } + } + } + }.onFailure { + Logger.warn("Failed to move '${inFlight.amountSats}' sats to Spark after the wait", it, context = TAG) + } + } + + private fun Throwable.isNoRoute(): Boolean = this is NodeException.RouteNotFound || + (this as? LdkError)?.compactType == NodeException.RouteNotFound::class.simpleName + + /** LDK reports a route lost since the quote, before any payment exists, as a sending failure on a live invoice. */ + private fun Throwable.isSendWithoutRoute(invoice: String): Boolean { + val isSendingFailed = this is NodeException.PaymentSendingFailed || + (this as? LdkError)?.compactType == NodeException.PaymentSendingFailed::class.simpleName + return isSendingFailed && runCatching { !Bolt11Invoice.fromStr(invoice).isExpired() }.getOrDefault(false) + } + + private fun Event.PaymentSuccessful.moved(amountSats: ULong) = MoveToSparkOutcome.Moved( + amountSats = amountSats, + feeSats = (feePaidMsat ?: 0uL) / 1000uL, + ) + + private fun Event.settles(paymentHash: String, paymentId: String?): Boolean = when (this) { + is Event.PaymentSuccessful -> this.paymentHash == paymentHash + is Event.PaymentFailed -> this.paymentHash == paymentHash || (paymentId != null && this.paymentId == paymentId) + else -> false + } +} + +/** The amounts behind moving the channels' balance, kept apart so they can be tested without a node. */ +object MoveToSparkMath { + /** Below this a move is not offered: what is left is about the routing fee. */ + const val MIN_MOVE_SATS = 1_000uL + + /** 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 + + /** The least fee guessed for the first quote of a full move. */ + private const val MIN_FEE_GUESS_SATS = 10uL + + /** Room left above the quoted fee, in sats, for the fee moving between the quote and the payment. */ + private const val FEE_MARGIN_SATS = 2uL + + fun movableSats(channels: List?): ULong = channels.totalNextOutboundHtlcLimitSats() + + /** Whether Spark can take a move; every Move to Spark check goes through here. */ + fun isSparkUsable(spark: SparkState): Boolean = spark.isReady + + /** Whether the channels hold a balance worth moving to a usable Spark wallet. */ + fun canMove(channels: List?, spark: SparkState): Boolean = + isSparkUsable(spark) && hasMovableBalance(movableSats(channels)) + + /** Whether [limitSats] still leaves at least [MIN_MOVE_SATS] to quote once the first fee guess is reserved. */ + fun hasMovableBalance(limitSats: ULong): Boolean = firstCandidate(limitSats, limitSats) >= MIN_MOVE_SATS + + /** The first amount to quote: [wantedSats] when it leaves room for fees, else the limit less a guessed fee. */ + fun firstCandidate(wantedSats: ULong, limitSats: ULong): ULong { + val guessSats = maxOf(limitSats.safe() * FIRST_FEE_GUESS_PPM.safe() / 1_000_000uL, MIN_FEE_GUESS_SATS) + return minOf(wantedSats, amountAfterFee(limitSats, guessSats)) + } + + /** The amount that fits under [limitSats] together with the fee quoted for [estimateSats]. */ + fun amountAfterFee(limitSats: ULong, estimateSats: ULong): ULong = + limitSats.safe() - quotedFeeSats(estimateSats).safe() + + /** The routing fee to show for an estimate: the estimate and its margin, which also covers its rounding down. */ + fun quotedFeeSats(estimateSats: ULong): ULong = estimateSats.safe() + FEE_MARGIN_SATS.safe() + + /** 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 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 } +} + +data class MoveToSparkQuote( + val invoice: String, + val amountSats: ULong, + val feeSats: ULong, +) + +sealed interface MoveToSparkOutcome { + val amountSats: ULong + + data class Moved(override val amountSats: ULong, val feeSats: ULong) : MoveToSparkOutcome + + /** The payment left but had not settled when the move stopped waiting; Spark shows it once it does. */ + data class InFlight( + override val amountSats: ULong, + val paymentHash: String, + val paymentId: String, + ) : MoveToSparkOutcome +} + +sealed class MoveToSparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { + class NothingToMove : MoveToSparkError("The channels have nothing to move") + class SparkUnavailable : MoveToSparkError("Spark is not ready to receive") + + /** [amountSats] did not route from the channels to Spark in one payment. */ + class TooLarge( + val amountSats: ULong, + cause: Throwable? = null, + val reason: PaymentFailureReason? = null, + ) : MoveToSparkError("Could not route '$amountSats' sats to Spark, reason '$reason'", cause) + + /** 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/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7b0b72144a..f3a06f67f0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1104,6 +1104,20 @@ class SparkRepo @Inject constructor( return false } val existing = (stored as? Activity.Lightning)?.v1 + // A receive sharing its hash with a channel send is a move to Spark, which Activity shows as that send; + // the completed receive proves the send settled. + if (payment.paymentType == SparkPaymentType.RECEIVE && existing?.txType == PaymentType.SENT) { + if (payment.status != PaymentStatus.COMPLETED || existing.status == PaymentState.SUCCEEDED) return true + val settled = Activity.Lightning(existing.copy(status = PaymentState.SUCCEEDED)) + val saved = activityRepo.get().upsertActivity(settled) + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + if (!saved) { + unsavedPayments.add(payment.id) + return false + } + unsavedPayments.remove(payment.id) + return true + } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true val activity = LightningActivity.create( diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index ab6f0e713e..0c3c879510 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -879,10 +879,16 @@ class ActivityService( val pendingMessage = payment.id.takeIf { payment.direction == PaymentDirection.OUTBOUND } ?.let { cacheStore.data.first().pendingLightningMessages[it] } - val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id) - // A Spark retry of an invoice the node failed shares its hash; the earlier failure never undoes its success. + // A send whose hash we received in Spark paid our own invoice, a move to Spark; once it succeeds it replaces + // that receive. + val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id)?.takeUnless { + it is Activity.Lightning && it.v1.txType == PaymentType.RECEIVED && + payment.direction == PaymentDirection.OUTBOUND && state == PaymentState.SUCCEEDED + } + // Another attempt of the same invoice, or the Spark receive of a move, already settled it; a pending or failed + // update never undoes that success. if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.SUCCEEDED && - state == PaymentState.FAILED + state != PaymentState.SUCCEEDED ) { return } @@ -895,10 +901,13 @@ class ActivityService( } if (existingActivity is Activity.Lightning) { val statusChanging = existingActivity.v1.status != state + // The Spark receive of a move can settle the send before the node's routing fee is recorded. + val feeChanging = payment.feePaidMsat?.let { msatFloorOf(it) != existingActivity.v1.fee } == true val needsPrivateContactAttribution = existingActivity.v1.contact == null && payment.direction == PaymentDirection.INBOUND if ((existingActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp && !statusChanging && + !feeChanging && !needsPrivateContactAttribution ) { return diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 1f46fe73fe..d8d91ae6f2 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -70,6 +70,7 @@ import to.bitkit.models.HwWalletBalance import to.bitkit.models.NodeLifecycleState import to.bitkit.models.Toast import to.bitkit.repositories.ConnectivityState +import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.ui.Routes.ExternalConnection @@ -205,6 +206,7 @@ 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.pin.PinManagementScreen import to.bitkit.ui.settings.quickPay.QuickPayIntroScreen @@ -224,6 +226,7 @@ import to.bitkit.ui.sheets.DisablePinSheet import to.bitkit.ui.sheets.ForceTransferSheet import to.bitkit.ui.sheets.HighBalanceWarningSheet import to.bitkit.ui.sheets.LnurlAuthSheet +import to.bitkit.ui.sheets.MoveToSparkSheet import to.bitkit.ui.sheets.PinSheet import to.bitkit.ui.sheets.QrScanningSheet import to.bitkit.ui.sheets.QuickPayIntroSheet @@ -765,6 +768,14 @@ fun ContentView( ) } + TimedSheetType.MOVE_TO_SPARK -> MoveToSparkSheet( + onLater = { appViewModel.dismissTimedSheet() }, + onMove = { + appViewModel.dismissTimedSheet() + navController.navigateTo(Routes.MoveToSpark) + }, + ) + TimedSheetType.HIGH_BALANCE -> { HighBalanceWarningSheet( understoodClick = { appViewModel.dismissTimedSheet() }, @@ -1382,6 +1393,8 @@ private fun NavGraphBuilder.home( SpendingWalletScreen( channels = lightningState.channels, hasSparkBalance = sparkState.shownBalanceSats > 0uL, + canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), + onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { @@ -2041,6 +2054,18 @@ private fun NavGraphBuilder.lightningConnections( }, ) } + 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( @@ -2518,6 +2543,9 @@ sealed interface Routes { @Serializable data class CloseConnection(val channelId: String) : Routes.DeepLinkable + @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 66640d1037..12d42a7539 100644 --- a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt +++ b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt @@ -114,6 +114,7 @@ sealed interface Sheet { /**@param priority Priority levels for timed sheets (higher number = higher priority)*/ enum class TimedSheetType(val priority: Int) { + MOVE_TO_SPARK(priority = 7), APP_UPDATE(priority = 6), USDT(priority = 5), BACKUP(priority = 4), diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt index 169ae8b03a..ff7bd6ce69 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt @@ -43,6 +43,7 @@ import to.bitkit.ui.LocalBalances import to.bitkit.ui.components.BalanceHeaderView import to.bitkit.ui.components.EmptyStateView import to.bitkit.ui.components.IncomingTransfer +import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.StatusBarSpacer import to.bitkit.ui.components.TabBar @@ -70,6 +71,8 @@ fun SpendingWalletScreen( onBackClick: () -> Unit, balances: BalanceState = LocalBalances.current, hasSparkBalance: Boolean = false, + canMoveToSpark: Boolean = false, + onMoveToSparkClick: () -> Unit = {}, ) { val showEmptyState by remember(balances.totalLightningSats, lightningActivities.size) { val hasLnFunds = balances.totalLightningSats == 0uL @@ -176,6 +179,24 @@ fun SpendingWalletScreen( if (!showEmptyState) { item { VerticalSpacer(32.dp) } + if (canMoveToSpark) { + item { + PrimaryButton( + onClick = onMoveToSparkClick, + text = stringResource(R.string.lightning__move_to_spark__nav_title), + icon = { + Icon( + painter = painterResource(R.drawable.ic_lightning), + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + }, + modifier = Modifier.testTag("MoveToSpark") + ) + } + item { VerticalSpacer(16.dp) } + } + if (canTransfer) { item { SecondaryButton( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionScreen.kt index 60755f9603..9819dfd5ef 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/CloseConnectionScreen.kt @@ -92,7 +92,8 @@ private fun Content( Image( painter = painterResource(R.drawable.exclamation_mark), contentDescription = null, - modifier = Modifier.size(256.dp) + // 274 like iOS, so its drawing is as large as the Move to Spark zap. + modifier = Modifier.size(274.dp) ) } Row( 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 4f0d4c0691..f7959f2bc7 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 @@ -108,6 +108,7 @@ fun LightningConnectionsScreen( navController.navigateTo(Routes.ChannelDetail(channelUi.details.channelId)) }, onClickSpark = { navController.navigateTo(Routes.SparkDetail) }, + onClickMoveToSpark = { navController.navigateTo(Routes.MoveToSpark) }, onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, onRefresh = { viewModel.onPullToRefresh() @@ -124,6 +125,7 @@ private fun Content( onClickExportLogs: () -> Unit = {}, onClickChannel: (ChannelUi) -> Unit = {}, onClickSpark: () -> Unit = {}, + onClickMoveToSpark: () -> Unit = {}, onOpenTx: (String) -> Unit = {}, onRefresh: () -> Unit = {}, ) { @@ -237,6 +239,15 @@ private fun Content( ) } + if (uiState.canMoveToSpark) { + VerticalSpacer(16.dp) + PrimaryButton( + text = stringResource(R.string.lightning__move_to_spark__nav_title), + onClick = onClickMoveToSpark, + modifier = Modifier.testTag("MoveToSpark") + ) + } + // Closed Channels Section AnimatedVisibility(visible = showClosed && uiState.closedChannels.isNotEmpty()) { Column { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index b90294382a..2771235bd9 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -37,6 +37,7 @@ import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LogsRepo +import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.SparkDeposit import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState @@ -102,8 +103,9 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lastKnownChannels, sparkRepo.state, ) { lightningState, channels, sparkState -> - Triple(lightningState.nodeLifecycleState.isRunning(), channels, sparkState) - }.collect { (isNodeRunning, channels, sparkState) -> + Triple(lightningState, channels, sparkState) + }.collect { (lightningState, channels, sparkState) -> + val isNodeRunning = lightningState.nodeLifecycleState.isRunning() val connectionText = context.getString(R.string.lightning__connection) _uiState.update { @@ -117,6 +119,8 @@ class LightningConnectionsViewModel @Inject constructor( .reversed().toImmutableList(), localBalance = calculateLocalBalance(channels).safe() + sparkState.shownBalanceSats.safe(), remoteBalance = channels.calculateRemoteBalance(), + // The cached channels outlive a stopped node; the move reads the live ones. + canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), spark = sparkState.toUi(lightningRepo), isSparkReceiving = sparkState.isReady, ) @@ -231,6 +235,8 @@ data class LightningConnectionsUiState( val remoteBalance: ULong = 0u, val spark: SparkUi? = null, val isSparkReceiving: Boolean = false, + /** The channels hold a balance that can move to Spark, which Blocktank's channel closes make the cheaper path. */ + val canMoveToSpark: Boolean = false, ) /** The Spark wallet shown as a connection, present once it holds a balance or a deposit. */ 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 new file mode 100644 index 0000000000..99bc9f8d70 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkScreen.kt @@ -0,0 +1,340 @@ +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 new file mode 100644 index 0000000000..b84ca7b74d --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt @@ -0,0 +1,123 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +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.MoveToSparkQuote +import to.bitkit.repositories.MoveToSparkRepo +import to.bitkit.repositories.WalletRepo +import javax.inject.Inject + +@HiltViewModel +class MoveToSparkViewModel @Inject constructor( + private val moveToSparkRepo: MoveToSparkRepo, + private val lightningRepo: LightningRepo, + private val walletRepo: WalletRepo, +) : ViewModel() { + + private val _uiState = MutableStateFlow(MoveToSparkUiState.Quoting) + val uiState = _uiState.asStateFlow() + + private var moveGeneration = 0 + + init { + quote() + } + + /** Quotes moving [targetSats], or everything the channels can send. */ + fun quote(targetSats: ULong? = null) { + _uiState.update { MoveToSparkUiState.Quoting } + viewModelScope.launch { + moveToSparkRepo.quote(targetSats).fold( + onSuccess = { quote -> _uiState.update { MoveToSparkUiState.Confirm(quote) } }, + onFailure = { error -> _uiState.update { error.toUiState() } }, + ) + } + } + + fun move() { + val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return + if (confirm.isMoving) return + val quote = confirm.quote + _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } + val generation = ++moveGeneration + viewModelScope.launch { + moveToSparkRepo.move(quote).fold( + onSuccess = { outcome -> + val settled = (outcome as? MoveToSparkOutcome.InFlight)?.let { + async(start = CoroutineStart.UNDISPATCHED) { moveToSparkRepo.awaitSettled(it) } + } + val done = done(outcome) + _uiState.update { done } + settled?.await()?.let { showLateOutcome(it, generation) } + }, + onFailure = { error -> _uiState.update { error.toUiState() } }, + ) + } + } + + private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { + walletRepo.syncNodeAndWallet() + val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) + return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) + } + + private suspend fun showLateOutcome(settled: Result, generation: Int) { + if (generation != moveGeneration || !uiState.value.isInFlight()) return + val late = settled.fold( + onSuccess = { done(it) }, + onFailure = { MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) }, + ) + _uiState.update { if (generation == moveGeneration && it.isInFlight()) late else it } + } + + 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, + smallerSats = MoveToSparkMath.smallerAmount(amountSats), + ) + is MoveToSparkError.NothingToMove -> MoveToSparkUiState.Failed(MoveToSparkFailure.NOTHING_TO_MOVE) + is MoveToSparkError.SparkUnavailable -> MoveToSparkUiState.Failed(MoveToSparkFailure.SPARK_UNAVAILABLE) + else -> MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) + } +} + +@Immutable +sealed interface MoveToSparkUiState { + data object Quoting : 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 + + /** [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 + + data class Failed(val failure: MoveToSparkFailure) : MoveToSparkUiState +} + +enum class MoveToSparkFailure { NOTHING_TO_MOVE, SPARK_UNAVAILABLE, UNKNOWN } diff --git a/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt new file mode 100644 index 0000000000..63f1706fb9 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/MoveToSparkSheet.kt @@ -0,0 +1,89 @@ +package to.bitkit.ui.sheets + +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.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.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalDensity +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 to.bitkit.R +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.scaffold.SheetTopBar +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 + +/** 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) { + Column( + modifier = modifier.sheetHeight().navigationBarsPadding().testTag("MoveToSparkIntro") + ) { + SheetTopBar(stringResource(R.string.lightning__move_to_spark__nav_title)) + Column(modifier = Modifier.weight(1f).padding(horizontal = 16.dp)) { + // The illustration shrinks on small screens so the copy below it stays whole. + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.weight(1f).fillMaxWidth() + ) { + Image( + painter = painterResource(R.drawable.lightning), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) + ) + } + VerticalSpacer(32.dp) + Display( + stringResource(R.string.lightning__move_to_spark__intro_title).withAccent(accentColor = Colors.Purple) + ) + VerticalSpacer(8.dp) + BodyM(stringResource(R.string.lightning__move_to_spark__intro_text), 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") + ) + } + VerticalSpacer(16.dp) + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { BottomSheetPreview { MoveToSparkSheet({}, {}) } } +} diff --git a/app/src/main/java/to/bitkit/utils/timedsheets/sheets/MoveToSparkTimedSheet.kt b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/MoveToSparkTimedSheet.kt new file mode 100644 index 0000000000..d886770099 --- /dev/null +++ b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/MoveToSparkTimedSheet.kt @@ -0,0 +1,28 @@ +package to.bitkit.utils.timedsheets.sheets + +import kotlinx.coroutines.flow.first +import to.bitkit.data.SettingsStore +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.SparkRepo +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.utils.timedsheets.TimedSheetItem +import javax.inject.Inject + +/** Shown once after the update to users whose channels still hold a balance worth moving to Spark. */ +class MoveToSparkTimedSheet @Inject constructor( + private val settingsStore: SettingsStore, + private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, +) : TimedSheetItem { + override val type = TimedSheetType.MOVE_TO_SPARK + override val priority = type.priority + + override suspend fun shouldShow(): Boolean { + if (settingsStore.data.first().hasSeenMoveToSparkIntro) return false + return MoveToSparkMath.canMove(lightningRepo.lightningState.value.channels, sparkRepo.state.value) + } + + override suspend fun onShown() = settingsStore.update { it.copy(hasSeenMoveToSparkIntro = true) } + override suspend fun onDismissed() = Unit +} diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1955d021be..0ae3163155 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -177,6 +177,7 @@ import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LnurlPayInvoiceMismatchError import to.bitkit.repositories.MethodId +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.NodeEventUpdate import to.bitkit.repositories.OnchainPreparedReceipt import to.bitkit.repositories.OnchainSendAttempt @@ -263,6 +264,7 @@ import to.bitkit.utils.timedsheets.TimedSheetManager import to.bitkit.utils.timedsheets.sheets.AppUpdateTimedSheet import to.bitkit.utils.timedsheets.sheets.BackupTimedSheet import to.bitkit.utils.timedsheets.sheets.HighBalanceTimedSheet +import to.bitkit.utils.timedsheets.sheets.MoveToSparkTimedSheet import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet @@ -330,6 +332,8 @@ class AppViewModel @Inject constructor( private val usdtSheet: UsdtTimedSheet, private val usdtPreferences: UsdtPreferencesRepo, private val highBalanceSheet: HighBalanceTimedSheet, + private val moveToSparkSheet: MoveToSparkTimedSheet, + private val moveToSparkRepo: MoveToSparkRepo, private val formatMoneyValue: FormatMoneyValue, private val widgetsRepo: WidgetsRepo, private val timeSource: TimeSource, @@ -567,6 +571,7 @@ class AppViewModel @Inject constructor( private val paymentRequestPresentationRetryJobs = mutableMapOf() private val paymentRequestPresentationCompletionJobs = mutableMapOf() private val timedSheetManager = timedSheetManagerProvider(viewModelScope).apply { + registerSheet(moveToSparkSheet) registerSheet(appUpdateSheet) registerSheet(usdtSheet) registerSheet(backupSheet) @@ -735,8 +740,13 @@ class AppViewModel @Inject constructor( sheet == null && authenticated && !forgotPin && receipt == NewTransactionSheetDetails.EMPTY }.collect { if (it) retryUsdtIntro() + if (it) retryMoveToSparkIntro() } } + viewModelScope.launch { + // Channels and Spark load after Home first checks its sheets, so the intro is checked again once they can. + moveToSparkRepo.canMove.collect { if (it) retryMoveToSparkIntro() } + } viewModelScope.launch { pubkyRepo.sessionRestorationFailed.collect { failed -> if (failed) { @@ -2861,6 +2871,7 @@ class AppViewModel @Inject constructor( refreshPaymentActivity(paymentHash) // A failed automatic Allowance payment falls back to the request's manual flow without a send error. if (isAutomaticAllowancePayment(paymentHash)) return + if (moveToSparkRepo.isWatchedMovePayment(paymentHash)) return if (pendingPaymentRepo.isPending(paymentHash)) { clearPendingContactPaymentContext(paymentHash) pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash, event.reason)) @@ -2908,6 +2919,7 @@ class AppViewModel @Inject constructor( event.paymentHash.let { paymentHash -> closeSettledReceiveSheet(receiveSheetToClose) activityRepo.notifyPaymentActivityChanged() + if (moveToSparkRepo.isMovePayment(paymentHash)) return privatePaykitRepo.contactPublicKeyForPrivateInvoicePaymentHash(paymentHash)?.let { publicKey -> activityRepo.setContact( contactPublicKey = publicKey, @@ -2958,6 +2970,8 @@ class AppViewModel @Inject constructor( refreshPaymentActivity(paymentHash) // An automatic Allowance payment settles headlessly; the allowance repo posts its notice and contact tag. if (isAutomaticAllowancePayment(paymentHash)) return + // A move to Spark reports its outcome on its own screen. + if (moveToSparkRepo.isMovePayment(paymentHash)) return if (!pendingPaymentRepo.isPending(paymentHash)) { notifyPaymentSentOnLightning(event) return @@ -8949,6 +8963,10 @@ class AppViewModel @Inject constructor( if (!isUsdtIntroPresented && usdtSheet.shouldShow()) timedSheetManager.reevaluate() } + private suspend fun retryMoveToSparkIntro() { + if (moveToSparkSheet.shouldShow()) timedSheetManager.reevaluate() + } + private fun canShowTimedSheet() = _isAuthenticated.value && !_showForgotPinSheet.value && _currentSheet.value == null && sheetTransitionJob?.isActive != true && diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a36800ae87..fd4734f853 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -321,6 +321,31 @@ 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> 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. diff --git a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt index 110f3521fd..7480bd4112 100644 --- a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt +++ b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt @@ -28,6 +28,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.CurrencyRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.SparkRepo import to.bitkit.services.MigrationService import to.bitkit.test.BaseUnitTest @@ -60,6 +61,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { private val clock: Clock = mock() private val backupRepo: BackupRepo = mock() private val sparkRepo: SparkRepo = mock() + private val moveToSparkRepo: MoveToSparkRepo = mock() private val migrationService: MigrationService = mock() private val isRestoring = MutableStateFlow(false) private val isShowingMigrationLoading = MutableStateFlow(false) @@ -103,6 +105,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { settingsStore = settingsStore, ), sparkRepo = sparkRepo, + moveToSparkRepo = moveToSparkRepo, ) } @@ -288,6 +291,21 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { verify(activityRepo, never()).markActivityAsSeen(any(), any()) } + @Test + fun `lightning payment returns Skip for a move to Spark`() = test { + val event = mock { + on { amountMsat } doReturn 1000000uL + on { paymentHash } doReturn "hash123" + on { paymentId } doReturn "paymentId123" + } + whenever(moveToSparkRepo.isMovePayment("hash123")).thenReturn(true) + + val result = sut(NotifyPaymentReceived.Command.Lightning(event = event)) + + assertTrue(result.getOrThrow() is NotifyPaymentReceived.Result.Skip) + verify(activityRepo, never()).isActivitySeen(any(), any()) + } + @Test fun `lightning payment returns Skip when paymentId is null`() = test { val event = mock { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index b916a6ae05..888909b361 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1674,6 +1674,18 @@ class LightningRepoTest : BaseUnitTest() { verifyBlocking(cacheStore) { addLdkSendHash("bolt11") } } + @Test + fun `a move to spark is recorded under its payment hash so it can be trimmed once paid`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(eq("bolt11"), eq(1_000uL), anyOrNull(), eq(5_000uL))).thenReturn("move-hash") + + sut.payInvoiceOverLdk("bolt11", paymentHash = "MOVE-HASH", sats = 1_000uL, maxTotalRoutingFeeMsat = 5_000uL) + .getOrThrow() + + verifyBlocking(cacheStore) { addLdkSendHash("move-hash") } + } + @Test fun `an invoice spark is still paying is not sent again through the node`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt new file mode 100644 index 0000000000..f40f18134e --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -0,0 +1,220 @@ +package to.bitkit.repositories + +import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Before +import org.junit.Test +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 org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.ext.createChannelDetails +import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.LdkError +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class MoveToSparkRepoTest : BaseUnitTest() { + companion object { + private const val INVOICE = "lnbcrt1spark" + } + + private val lightningRepo = mock() + private val sparkRepo = mock() + private val sparkState = MutableStateFlow(SparkState(isReady = true)) + private val lightningState = MutableStateFlow(LightningState()) + private val nodeEvents = MutableSharedFlow() + private val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") + private lateinit var sut: MoveToSparkRepo + + @Before + fun setUp() { + whenever(lightningRepo.lightningState).thenReturn(lightningState) + whenever(sparkRepo.state).thenReturn(sparkState) + whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) + sut = MoveToSparkRepo(testDispatcher, lightningRepo, sparkRepo) + } + + private fun sendable(sats: ULong) { + val channel = createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = sats * 1000uL) + lightningState.value = LightningState(channels = persistentListOf(channel)) + } + + @Test + fun `quote leaves room under the outbound limit for the routing fee`() = test { + sendable(100_000uL) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(eq(INVOICE), any())).thenReturn(Result.success(30uL)) + + val quote = sut.quote().getOrThrow() + + assertEquals(INVOICE, quote.invoice) + assertEquals(MoveToSparkMath.quotedFeeSats(30uL), quote.feeSats) + assertEquals(MoveToSparkMath.amountAfterFee(100_000uL, 30uL), quote.amountSats) + verify(sparkRepo).createInvoice(eq(null), any(), any()) + } + + @Test + fun `quote shrinks the amount when the fee does not fit the first guess`() = test { + sendable(1_000_000uL) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(eq(INVOICE), any())).thenReturn(Result.success(9_000uL)) + + val quote = sut.quote().getOrThrow() + + assertEquals(MoveToSparkMath.amountAfterFee(1_000_000uL, 9_000uL), quote.amountSats) + assertTrue(quote.amountSats + quote.feeSats <= 1_000_000uL) + } + + @Test + fun `quote of a smaller target keeps the target`() = test { + sendable(100_000uL) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(eq(INVOICE), any())).thenReturn(Result.success(5uL)) + + assertEquals(50_000uL, sut.quote(50_000uL).getOrThrow().amountSats) + } + + @Test + fun `quote fails as too large when no route is found`() = test { + sendable(100_000uL) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(eq(INVOICE), any())) + .thenReturn(Result.failure(LdkError(NodeException.RouteNotFound("no route")))) + + val error = sut.quote().exceptionOrNull() + + assertIs(error) + } + + @Test + fun `quote keeps an estimate error other than no route`() = test { + sendable(100_000uL) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.estimateLdkRoutingFeesForAmount(eq(INVOICE), any())) + .thenReturn(Result.failure(LdkError(NodeException.NotRunning("node stopped")))) + + val error = sut.quote().exceptionOrNull() + + assertIs(error) + } + + @Test + fun `quote fails with nothing to move below the minimum`() = test { + sendable(MoveToSparkMath.MIN_MOVE_SATS - 1uL) + + assertIs(sut.quote().exceptionOrNull()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `quote fails while Spark is not usable`() = test { + sendable(100_000uL) + sparkState.value = SparkState(isReady = false) + + assertIs(sut.quote().exceptionOrNull()) + } + + @Test + fun `a move is offered only with a usable Spark and a balance above the minimum`() { + val channels = listOf(createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = 5_000_000uL)) + assertTrue(MoveToSparkMath.canMove(channels, SparkState(isReady = true))) + assertTrue(!MoveToSparkMath.canMove(channels, SparkState(isReady = false))) + assertTrue(!MoveToSparkMath.canMove(emptyList(), SparkState(isReady = true))) + } + + @Test + fun `a move is offered only when the minimum fits beside the fee reserve`() { + assertTrue(!MoveToSparkMath.hasMovableBalance(1_011uL)) + assertTrue(MoveToSparkMath.hasMovableBalance(1_012uL)) + } + + @Test + fun `quote fails with nothing to move when the fee reserve leaves under the minimum`() = test { + sendable(1_011uL) + + assertIs(sut.quote().exceptionOrNull()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `smaller amount halves until the minimum`() { + assertEquals(50_000uL, MoveToSparkMath.smallerAmount(100_000uL)) + assertNull(MoveToSparkMath.smallerAmount(MoveToSparkMath.MIN_MOVE_SATS)) + } + + @Test + fun `fee cap is the quoted fee, which covers the estimate and its margin`() { + val feeSats = MoveToSparkMath.quotedFeeSats(30uL) + assertEquals(32uL, feeSats) + assertEquals(32_000uL, MoveToSparkMath.feeCapMsat(feeSats)) + assertEquals(1_000_000uL, MoveToSparkMath.amountAfterFee(1_000_000uL, 30uL) + feeSats) + } + + @Test + fun `an in-flight move that fails later matches its payment id when the hash is missing`() = test { + val settled = async(start = CoroutineStart.UNDISPATCHED) { sut.awaitSettled(inFlight) } + + nodeEvents.emit(Event.PaymentFailed(paymentId = "other", paymentHash = null, reason = null)) + nodeEvents.emit( + Event.PaymentFailed(paymentId = "id", paymentHash = null, reason = PaymentFailureReason.RETRIES_EXHAUSTED), + ) + + assertIs(settled.await().exceptionOrNull()) + } + + @Test + fun `an in-flight move that succeeds later reports the fee paid`() = test { + val settled = async(start = CoroutineStart.UNDISPATCHED) { sut.awaitSettled(inFlight) } + + nodeEvents.emit( + Event.PaymentSuccessful( + paymentId = "id", + paymentHash = "hash", + paymentPreimage = null, + feePaidMsat = 7_000uL, + ), + ) + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 7uL), settled.await().getOrThrow()) + } + + @Test + fun `an in-flight move that settled before the late listener started reads the stored payment`() = test { + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(nodeSend(PaymentStatus.SUCCEEDED))) + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 7uL), sut.awaitSettled(inFlight).getOrThrow()) + } + + @Test + fun `an in-flight move that failed before the late listener started reads the stored payment`() = test { + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(nodeSend(PaymentStatus.FAILED))) + + assertIs(sut.awaitSettled(inFlight).exceptionOrNull()) + } + + private fun nodeSend(status: PaymentStatus) = PaymentDetails( + id = "id", + kind = PaymentKind.Bolt11(hash = "hash", preimage = null, secret = null, description = null, bolt11 = INVOICE), + amountMsat = 50_000_000uL, + feePaidMsat = 7_000uL, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 0uL, + ) +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 978d611230..c3d2fa1273 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -582,6 +582,52 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf(0uL, 2uL), activities.allValues.map { (it as Activity.Lightning).v1.fee }) } + @Test + fun `a move to spark received after its channel send keeps the send as its only activity`() = test { + val send = LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = PaymentState.SUCCEEDED, + value = 128uL, + invoice = "lnbc1280n1send", + timestamp = 1uL, + fee = 3uL, + ) + whenever(activityRepo.getActivity(any(), any())).thenReturn(Result.success(Activity.Lightning(send))) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentSucceeded(receivedPayment())) + whenever(sparkService.listPayments()).thenReturn(listOf(receivedPayment())) + sparkEvents.emit(SdkEvent.Synced) + + verify(activityRepo, never()).upsertActivity(any()) + } + + @Test + fun `a move to spark received after its pending channel send marks the send succeeded`() = test { + val send = LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = PaymentState.PENDING, + value = 128uL, + invoice = "lnbc1280n1send", + timestamp = 1uL, + fee = 3uL, + ) + whenever(activityRepo.getActivity(any(), any())).thenReturn(Result.success(Activity.Lightning(send))) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentSucceeded(receivedPayment())) + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals(send.copy(status = PaymentState.SUCCEEDED), (activity.firstValue as Activity.Lightning).v1) + } + @Test fun `a start whose activity write failed syncs the activities again`() = test { whenever(sparkService.isConnected).thenReturn(false, true) diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceMoveToSparkTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceMoveToSparkTest.kt new file mode 100644 index 0000000000..3aad927ab7 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/ActivityServiceMoveToSparkTest.kt @@ -0,0 +1,146 @@ +package to.bitkit.services + +import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.LightningActivity +import com.synonym.bitkitcore.PaymentState +import com.synonym.bitkitcore.PaymentType +import com.synonym.bitkitcore.getActivityById +import com.synonym.bitkitcore.updateActivity +import com.synonym.bitkitcore.upsertActivity +import kotlinx.coroutines.flow.flowOf +import org.junit.Test +import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.async.ServiceQueue +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore +import to.bitkit.ext.create +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +class ActivityServiceMoveToSparkTest : BaseUnitTest() { + companion object { + private const val BITKIT_CORE_FFI_CLASS = "com.synonym.bitkitcore.Bitkitcore_androidKt" + private const val HASH = "payment-hash" + private const val MOVED_SATS = 50_000uL + private const val ROUTING_FEE_SATS = 3uL + } + + private val cacheStore = mock() + + private var row: Activity? = null + + @Test + fun `a move to spark sent after its spark receive replaces it with one outgoing row and the routing fee`() = + coreTest { + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + row = Activity.Lightning(sparkReceive()) + + sut().syncLdkNodePaymentsToActivities(listOf(channelSend())) + + val stored = (row as Activity.Lightning).v1 + assertEquals(PaymentType.SENT, stored.txType) + assertEquals(PaymentState.SUCCEEDED, stored.status) + assertEquals(MOVED_SATS, stored.value) + assertEquals(ROUTING_FEE_SATS, stored.fee) + } + + @Test + fun `a pending move to spark send leaves its spark receive until the send succeeds`() = coreTest { + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + row = Activity.Lightning(sparkReceive()) + + sut().syncLdkNodePaymentsToActivities(listOf(channelSend(PaymentStatus.PENDING))) + + assertEquals(sparkReceive(), (row as Activity.Lightning).v1) + + sut().syncLdkNodePaymentsToActivities(listOf(channelSend())) + + val stored = (row as Activity.Lightning).v1 + assertEquals(PaymentType.SENT, stored.txType) + assertEquals(PaymentState.SUCCEEDED, stored.status) + assertEquals(MOVED_SATS, stored.value) + assertEquals(ROUTING_FEE_SATS, stored.fee) + } + + @Test + fun `a move to spark settled by its spark receive takes the routing fee from the later send update`() = + coreTest { + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + // The Spark receive marked the pending send succeeded after the node's last update of it. + row = Activity.Lightning( + LightningActivity.create( + id = HASH, + txType = PaymentType.SENT, + status = PaymentState.SUCCEEDED, + value = MOVED_SATS, + invoice = "invoice", + timestamp = 100uL, + updatedAt = 300uL, + ) + ) + + sut().syncLdkNodePaymentsToActivities(listOf(channelSend())) + + val stored = (row as Activity.Lightning).v1 + assertEquals(PaymentState.SUCCEEDED, stored.status) + assertEquals(ROUTING_FEE_SATS, stored.fee) + } + + private fun coreTest(block: suspend () -> Unit) = test { + ServiceQueue.CORE.background { + mockStatic(Class.forName(BITKIT_CORE_FFI_CLASS)).use { native -> + native.`when` { getActivityById(any(), any()) }.thenAnswer { row } + native.`when` { updateActivity(any(), any()) }.thenAnswer { + row = it.arguments[1] as Activity + null + } + native.`when` { upsertActivity(any()) }.thenAnswer { + row = it.arguments[0] as Activity + null + } + block() + } + } + } + + private fun sut() = ActivityService( + coreService = mock(), + cacheStore = cacheStore, + lightningService = mock(), + settingsStore = mock(), + privatePaykitContactResolver = mock(), + ) + + private fun sparkReceive() = LightningActivity.create( + id = HASH, + txType = PaymentType.RECEIVED, + status = PaymentState.SUCCEEDED, + value = MOVED_SATS, + invoice = "invoice", + timestamp = 300uL, + fee = 0uL, + ) + + private fun channelSend(status: PaymentStatus = PaymentStatus.SUCCEEDED) = PaymentDetails( + id = HASH, + kind = PaymentKind.Bolt11( + hash = HASH, + preimage = "pre", + secret = null, + description = "Move to Spark", + bolt11 = "invoice", + ), + amountMsat = MOVED_SATS * 1_000uL, + feePaidMsat = ROUTING_FEE_SATS * 1_000uL, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 200uL, + ) +} 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 new file mode 100644 index 0000000000..fdb532eba4 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -0,0 +1,107 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.ext.createChannelDetails +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.LightningState +import to.bitkit.repositories.MoveToSparkError +import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkQuote +import to.bitkit.repositories.MoveToSparkRepo +import to.bitkit.repositories.WalletRepo +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertIs + +class MoveToSparkViewModelTest : BaseUnitTest() { + private val moveToSparkRepo = mock() + private val lightningRepo = mock() + private val walletRepo = 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") + private val moved = MoveToSparkOutcome.Moved(50_000uL, feeSats = 7uL) + private val openChannel = createChannelDetails().copy(channelId = "channel_1", isChannelReady = true) + private val lightningState = MutableStateFlow(LightningState()) + private val secondMove = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash_2", paymentId = "id_2") + private val firstSettled = CompletableDeferred>() + private val secondSettled = CompletableDeferred>() + + @Before + fun setUp() { + whenever(lightningRepo.lightningState).thenReturn(lightningState) + whenever(moveToSparkRepo.movableSats()).thenReturn(0uL) + whenever { moveToSparkRepo.quote(anyOrNull()) }.thenReturn(Result.success(quote)) + whenever { moveToSparkRepo.move(eq(quote)) } + .thenReturn(Result.success(firstMove), Result.success(secondMove)) + whenever { moveToSparkRepo.awaitSettled(eq(firstMove)) }.doSuspendableAnswer { firstSettled.await() } + whenever { moveToSparkRepo.awaitSettled(eq(secondMove)) }.doSuspendableAnswer { secondSettled.await() } + whenever { walletRepo.syncNodeAndWallet(anyOrNull()) }.thenReturn(Result.success(Unit)) + } + + @Test + fun `late failure of the in-flight move shows it could not move`() = test { + val sut = createViewModel() + sut.move() + assertEquals(firstMove, assertIs(sut.uiState.value).outcome) + + firstSettled.complete(Result.failure(MoveToSparkError.PaymentFailed(null))) + + assertEquals(MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN), sut.uiState.value) + } + + @Test + fun `late failure of an older move leaves a newer move in flight`() = test { + val sut = moveTwice() + + firstSettled.complete(Result.failure(MoveToSparkError.PaymentFailed(null))) + + assertEquals(secondMove, assertIs(sut.uiState.value).outcome) + } + + @Test + fun `late success of the in-flight move shows it moved with the fee paid`() = test { + lightningState.value = LightningState(channels = persistentListOf(openChannel)) + whenever(moveToSparkRepo.movableSats()).thenReturn(MoveToSparkMath.MIN_MOVE_SATS * 2uL) + val sut = createViewModel() + sut.move() + + firstSettled.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = "channel_1", hasRest = true), sut.uiState.value) + } + + @Test + fun `late success of an older move leaves a newer move in flight`() = test { + val sut = moveTwice() + + firstSettled.complete(Result.success(moved)) + + assertEquals(secondMove, assertIs(sut.uiState.value).outcome) + } + + private fun moveTwice(): MoveToSparkViewModel { + val sut = createViewModel() + sut.move() + sut.quote() + sut.move() + assertEquals(secondMove, assertIs(sut.uiState.value).outcome) + return sut + } + + private fun createViewModel() = MoveToSparkViewModel( + moveToSparkRepo = moveToSparkRepo, + lightningRepo = lightningRepo, + walletRepo = walletRepo, + ) +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 494c1f86ad..174430c6ba 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -50,6 +50,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf @@ -971,6 +972,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { usdtPreferences = usdtPreferences, highBalanceSheet = mock { on { type } doReturn TimedSheetType.HIGH_BALANCE }, + moveToSparkSheet = mock { + on { type } doReturn TimedSheetType.MOVE_TO_SPARK + onBlocking { shouldShow() } doReturn false + }, + moveToSparkRepo = mock { on { canMove } doReturn emptyFlow() }, formatMoneyValue = formatMoneyValue, widgetsRepo = widgetsRepo, pubkyRepo = pubkyRepo, diff --git a/changelog.d/next/1768.added.md b/changelog.d/next/1768.added.md new file mode 100644 index 0000000000..80633ba9bc --- /dev/null +++ b/changelog.d/next/1768.added.md @@ -0,0 +1 @@ +Move to Spark: move a Lightning connection's balance to Spark, then close the emptied connection to return its reserve to Savings. diff --git a/docs/screens-map.md b/docs/screens-map.md index b46984af02..837f3f1cf8 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -316,6 +316,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | ChannelDetailScreen.kt | Settings > Advanced › Connection details | | CloseConnectionScreen.kt | Settings > Advanced › Close connection | | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | +| MoveToSparkScreen.kt | `todo` | | SparkDetailScreen.kt | `todo` | ## ui/settings/pin diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml new file mode 100644 index 0000000000..2379e4c496 --- /dev/null +++ b/journeys/transfer/move-to-spark.xml @@ -0,0 +1,29 @@ + + + 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. + + 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 + PR's manual test rather than here. + + Precondition: dev build pointed at a local Spark regtest (spark-sdk regtest/local), and a wallet with an open + channel to that stack's SSP Lightning node that holds most of its capacity on the wallet's side (open it from + Lightning Connections, Manual Setup, with the node URI the stack prints). Start on the wallet home screen with the + 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 + Open the Spending wallet and verify the "Move To Spark" button (testTag "MoveToSpark") shows + Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") + Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") + Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no open connection and the Spark balance grew by the moved amount + Go back to Home, open Spending and verify the "Move To Spark" button is gone + +