From 9a456274285ccd598fe03d6159e834dc0173c288 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 22:52:18 +0100 Subject: [PATCH 01/23] feat: spark connection and app status design Verified: just format, compile, test, lint; journeys on a regtest emulator --- .../java/to/bitkit/repositories/HealthRepo.kt | 36 +-- .../bitkit/ui/components/LightningChannel.kt | 45 ++- .../ui/settings/appStatus/AppStatusScreen.kt | 99 ++++--- .../settings/appStatus/AppStatusViewModel.kt | 3 + .../lightning/LightningConnectionsScreen.kt | 63 +--- .../LightningConnectionsViewModel.kt | 12 +- .../settings/lightning/SparkDetailScreen.kt | 272 ++++++++++++++---- .../lightning/SparkDetailViewModel.kt | 10 + app/src/main/res/values-ar/strings.xml | 4 - app/src/main/res/values-b+es+419/strings.xml | 4 - app/src/main/res/values-ca/strings.xml | 4 - app/src/main/res/values-cs/strings.xml | 4 - app/src/main/res/values-de/strings.xml | 4 - app/src/main/res/values-el/strings.xml | 4 - app/src/main/res/values-es-rES/strings.xml | 4 - app/src/main/res/values-es/strings.xml | 4 - app/src/main/res/values-fr/strings.xml | 4 - app/src/main/res/values-it/strings.xml | 4 - app/src/main/res/values-nl/strings.xml | 4 - app/src/main/res/values-pl/strings.xml | 4 - app/src/main/res/values-pt-rBR/strings.xml | 4 - app/src/main/res/values-pt/strings.xml | 4 - app/src/main/res/values-ru/strings.xml | 4 - app/src/main/res/values/strings.xml | 19 +- .../to/bitkit/repositories/HealthRepoTest.kt | 60 ++++ .../lightning/SparkDetailScreenTest.kt | 100 +++++++ .../lightning/SparkDetailViewModelTest.kt | 63 ++++ .../ui/settings/lightning/SparkUiTest.kt | 19 ++ docs/screens-map.md | 2 +- .../settings/app-status-emergency-exit.xml | 15 +- journeys/settings/app-status-spark-row.xml | 9 +- .../settings/spark-connection-details.xml | 32 +++ journeys/transfer/spark-emergency-exit.xml | 10 +- 33 files changed, 676 insertions(+), 253 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt create mode 100644 app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt create mode 100644 journeys/settings/spark-connection-details.xml diff --git a/app/src/main/java/to/bitkit/repositories/HealthRepo.kt b/app/src/main/java/to/bitkit/repositories/HealthRepo.kt index 4a50965471..b020067387 100644 --- a/app/src/main/java/to/bitkit/repositories/HealthRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HealthRepo.kt @@ -28,6 +28,7 @@ class HealthRepo @Inject constructor( private val connectivityRepo: ConnectivityRepo, private val lightningRepo: LightningRepo, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, private val cacheStore: CacheStore, private val clock: Clock, ) { @@ -53,8 +54,9 @@ class HealthRepo @Inject constructor( internetHealthState, lightningRepo.lightningState, sparkRepo.state, - ) { internetHealth, lightningState, sparkState -> - computeHealthState(internetHealth, lightningState, sparkState) + sparkExitRepo.state.map { it.record?.isActive == true }, + ) { internetHealth, lightningState, sparkState, isSparkExiting -> + computeHealthState(internetHealth, lightningState, sparkState).copy(isSparkExiting = isSparkExiting) }.collect { newHealthState -> updateState { it.copy( @@ -64,6 +66,7 @@ class HealthRepo @Inject constructor( channels = newHealthState.channels, isLightningViaSpark = newHealthState.isLightningViaSpark, spark = newHealthState.spark, + isSparkExiting = newHealthState.isSparkExiting, ) } } @@ -169,21 +172,7 @@ class HealthRepo @Inject constructor( _healthState.update { currentState -> val updatedState = update(currentState) - // Compute app health status from all individual states - val states = listOf( - updatedState.internet, - updatedState.electrum, - updatedState.node, - updatedState.backups, - ) - - val appStatus = when { - HealthState.ERROR in states -> HealthState.ERROR - HealthState.PENDING in states -> HealthState.PENDING - else -> HealthState.READY - } - - updatedState.copy(app = appStatus) + updatedState.copy(app = updatedState.computeApp()) } } } @@ -198,7 +187,20 @@ data class AppHealthState( /** Null where Spark is unsupported. */ val spark: HealthState? = null, val backups: HealthState = HealthState.READY, + /** A force transfer to savings runs, which App Status shows on Spark's row. */ + val isSparkExiting: Boolean = false, val app: HealthState = HealthState.READY, ) { fun isOnline() = internet == HealthState.READY + + /** The menu's status: red when any part fails, else yellow while any is pending; Spark counts where supported. */ + internal fun computeApp(): HealthState { + val sparkState = spark?.let { if (isSparkExiting) HealthState.PENDING else it } + val states = listOfNotNull(internet, electrum, node, backups, sparkState) + return when { + HealthState.ERROR in states -> HealthState.ERROR + HealthState.PENDING in states -> HealthState.PENDING + else -> HealthState.READY + } + } } diff --git a/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt index bdcb5d046b..43cab1d8d7 100644 --- a/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt +++ b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt @@ -40,15 +40,24 @@ fun LightningChannel( status: ChannelStatusUi = ChannelStatusUi.PENDING, showLabels: Boolean = false, showReceiving: Boolean = true, + receivingUnlimited: Boolean = false, ) { - val isEmptySpendingBar = !showReceiving && localBalance == 0L + val isEmptySpendingBar = (!showReceiving || receivingUnlimited) && localBalance == 0L val spendingColor = if (status == ChannelStatusUi.CLOSED || isEmptySpendingBar) Colors.Gray5 else Colors.Purple50 val spendingAvailableColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray3 else Colors.Purple - val receivingColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray5 else Colors.White64 + val receivingColor = when { + receivingUnlimited -> Colors.White + status == ChannelStatusUi.CLOSED -> Colors.Gray5 + else -> Colors.White64 + } val receivingAvailableColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray3 else Colors.White val spendingAvailableFraction = if (capacity > 0) localBalance.toFloat() / capacity else 0f - val receivingAvailableFraction = if (capacity > 0) remoteBalance.toFloat() / capacity else 0f + val receivingAvailableFraction = when { + receivingUnlimited -> 1f + capacity > 0 -> remoteBalance.toFloat() / capacity + else -> 0f + } Column( modifier = modifier @@ -90,10 +99,17 @@ fun LightningChannel( tint = receivingAvailableColor, modifier = Modifier.size(14.dp) ) - MoneyCaptionB( - sats = remoteBalance, - color = receivingAvailableColor, - ) + if (receivingUnlimited) { + CaptionB( + text = stringResource(R.string.lightning__spark_receiving_unlimited), + color = receivingAvailableColor, + ) + } else { + MoneyCaptionB( + sats = remoteBalance, + color = receivingAvailableColor, + ) + } } } } @@ -202,4 +218,19 @@ private fun PreviewChannelClosed() { } } +@Preview(showBackground = true) +@Composable +private fun PreviewReceivingUnlimited() { + AppThemeSurface { + LightningChannel( + capacity = 580_000, + localBalance = 580_000, + remoteBalance = 0, + status = ChannelStatusUi.OPEN, + receivingUnlimited = true, + modifier = Modifier.padding(16.dp) + ) + } +} + // endregion diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index afa20d7177..dd502990a3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -5,9 +5,9 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight @@ -24,6 +24,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -35,6 +36,7 @@ import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.HealthState import to.bitkit.repositories.AppHealthState import to.bitkit.ui.Routes +import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.CaptionB import to.bitkit.ui.components.HorizontalSpacer @@ -92,7 +94,8 @@ private fun Content( Column( modifier = Modifier - .fillMaxSize() + .weight(1f) + .fillMaxWidth() .verticalScroll(rememberScrollState()) .padding(horizontal = 16.dp) ) { @@ -167,39 +170,12 @@ private fun Content( onClick = onChannelsClick, ) - uiState.health.spark?.let { sparkHealth -> - StatusItem( - statusUi = StatusUi( - id = "spark", - title = stringResource(R.string.settings__status__spark__title), - subtitle = when (sparkHealth) { - HealthState.READY -> stringResource(R.string.settings__status__spark__ready) - HealthState.PENDING -> stringResource(R.string.settings__status__spark__pending) - HealthState.ERROR -> stringResource(R.string.settings__status__spark__error) - }, - iconRes = R.drawable.ic_asterisk, - state = sparkHealth, - ), - // Spark's detail shows a zero balance until Spark has read its state. - onClick = onSparkClick.takeIf { sparkHealth == HealthState.READY }, - ) - } - - uiState.exitStep?.let { exitStep -> - StatusItem( - statusUi = StatusUi( - id = "spark_exit", - title = stringResource(R.string.settings__status__exit__title), - subtitle = when (exitStep) { - ExitStep.FUNDING -> stringResource(R.string.settings__status__exit__funding) - ExitStep.RUNNING -> stringResource(R.string.settings__status__exit__pending) - }, - iconRes = R.drawable.ic_warning, - state = HealthState.PENDING, - ), - onClick = onExitClick, - ) - } + SparkStatusItem( + sparkHealth = uiState.health.spark, + exitStep = uiState.exitStep, + onSparkClick = onSparkClick, + onExitClick = onExitClick, + ) StatusItem( statusUi = StatusUi( @@ -221,9 +197,61 @@ private fun Content( VerticalSpacer(16.dp) } + + BodyM( + text = stringResource(R.string.settings__status__app_version).replace("{version}", uiState.appVersion), + color = Colors.White64, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + .navigationBarsPadding() + .testTag("AppVersion") + ) } } +@Composable +private fun SparkStatusItem( + sparkHealth: HealthState?, + exitStep: ExitStep?, + onSparkClick: () -> Unit, + onExitClick: () -> Unit, +) { + if (exitStep != null) { + StatusItem( + statusUi = StatusUi( + id = "spark_exit", + title = stringResource(R.string.settings__status__spark__title), + subtitle = when (exitStep) { + ExitStep.FUNDING -> stringResource(R.string.settings__status__exit__funding) + ExitStep.RUNNING -> stringResource(R.string.settings__status__spark__exit) + }, + iconRes = R.drawable.ic_warning, + state = HealthState.PENDING, + ), + onClick = onExitClick, + ) + return + } + if (sparkHealth == null) return + StatusItem( + statusUi = StatusUi( + id = "spark", + title = stringResource(R.string.settings__status__spark__title), + subtitle = when (sparkHealth) { + HealthState.READY -> stringResource(R.string.settings__status__spark__ready) + HealthState.PENDING -> stringResource(R.string.settings__status__spark__pending) + HealthState.ERROR -> stringResource(R.string.settings__status__spark__error) + }, + iconRes = R.drawable.ic_asterisk, + state = sparkHealth, + ), + // Spark's detail shows a zero balance until Spark has read its state. + onClick = onSparkClick.takeIf { sparkHealth == HealthState.READY }, + ) +} + @Composable private fun StatusItem( statusUi: StatusUi, @@ -313,6 +341,7 @@ private fun Preview() { backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toLocalizedTimestamp(), nodeSubtitle = "Running", exitStep = ExitStep.RUNNING, + appVersion = "3.2.0 (182)", ), ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index 81f8840de3..255381e052 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.data.CacheStore +import to.bitkit.env.Env import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus @@ -88,6 +89,8 @@ data class AppStatusUiState( val nodeSubtitle: String = "", /** Null while no emergency exit runs. */ val exitStep: ExitStep? = null, + /** The app's version and build, as "3.2.0 (182)". */ + val appVersion: String = Env.version, ) enum class ExitStep { FUNDING, RUNNING } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsScreen.kt index f7959f2bc7..31b3fe503c 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 @@ -1,6 +1,5 @@ package to.bitkit.ui.settings.lightning -import android.content.Intent import androidx.annotation.DrawableRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image @@ -39,7 +38,6 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import kotlinx.collections.immutable.ImmutableList @@ -74,7 +72,6 @@ import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.shared.util.shareZipFile import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors -import to.bitkit.ui.utils.getBlockExplorerUrl import to.bitkit.ui.utils.withAccent private const val CLOSED_CHANNEL_ALPHA = 0.64f @@ -109,7 +106,6 @@ fun LightningConnectionsScreen( }, onClickSpark = { navController.navigateTo(Routes.SparkDetail) }, onClickMoveToSpark = { navController.navigateTo(Routes.MoveToSpark) }, - onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, onRefresh = { viewModel.onPullToRefresh() }, @@ -126,7 +122,6 @@ private fun Content( onClickChannel: (ChannelUi) -> Unit = {}, onClickSpark: () -> Unit = {}, onClickMoveToSpark: () -> Unit = {}, - onOpenTx: (String) -> Unit = {}, onRefresh: () -> Unit = {}, ) { var showClosed by remember { mutableStateOf(false) } @@ -178,7 +173,7 @@ private fun Content( uiState.remoteBalance, isReceivingUnlimited = uiState.isSparkReceiving ) - HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) + HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) EmptyStateContent(modifier = Modifier.weight(1f)) @@ -204,19 +199,13 @@ private fun Content( uiState.remoteBalance, isReceivingUnlimited = uiState.isSparkReceiving ) - HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) + HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) if (!uiState.isNodeRunning) { VerticalSpacer(16.dp) SyncingRow() } - uiState.spark?.let { spark -> - VerticalSpacer(16.dp) - Caption13Up(stringResource(R.string.lightning__spark), color = Colors.White64) - SparkItem(spark = spark, onClick = onClickSpark, onOpenTx = onOpenTx) - } - // Pending Channels Section if (uiState.pendingConnections.isNotEmpty()) { VerticalSpacer(16.dp) @@ -228,8 +217,8 @@ private fun Content( ) } - // Open Channels Section - if (uiState.openChannels.isNotEmpty()) { + // Open Channels Section, with Spark after the channels + if (uiState.openChannels.isNotEmpty() || uiState.spark != null) { VerticalSpacer(16.dp) Caption13Up(stringResource(R.string.lightning__conn_open), color = Colors.White64) ChannelList( @@ -237,6 +226,7 @@ private fun Content( channels = uiState.openChannels, onClickChannel = onClickChannel, ) + uiState.spark?.let { SparkItem(spark = it, onClick = onClickSpark) } } if (uiState.canMoveToSpark) { @@ -340,7 +330,7 @@ private fun BalanceColumn( ) { Column { Caption13Up(text = label, color = Colors.White64) - VerticalSpacer(8.dp) + VerticalSpacer(12.dp) Row( verticalAlignment = Alignment.CenterVertically, ) { @@ -425,7 +415,6 @@ private fun ChannelItem( private fun SparkItem( spark: SparkUi, onClick: () -> Unit, - onOpenTx: (String) -> Unit, ) { Column( modifier = Modifier @@ -456,30 +445,14 @@ private fun SparkItem( localBalance = spark.balanceSats.toLong(), remoteBalance = 0L, status = ChannelStatusUi.OPEN, - showReceiving = false, + showReceiving = spark.isReceiving, + receivingUnlimited = spark.isReceiving, ) - spark.pendingDeposits.forEach { SparkDepositRow(it, onOpenTx) } VerticalSpacer(16.dp) HorizontalDivider() } } -@Composable -internal fun SparkDepositRow( - depositUi: SparkDepositUi, - onOpenTx: (String) -> Unit, - modifier: Modifier = Modifier, -) { - SparkTransactionRow( - title = stringResource(R.string.lightning__spark_deposit), - txid = depositUi.deposit.txid, - amountSats = depositUi.deposit.amountSats, - confirmations = depositUi.confirmations, - onOpenTx = onOpenTx, - modifier = modifier.testTag("SparkDeposit") - ) -} - @Composable internal fun SparkTransactionRow( title: String, @@ -487,7 +460,6 @@ internal fun SparkTransactionRow( amountSats: ULong, onOpenTx: (String) -> Unit, modifier: Modifier = Modifier, - confirmations: UInt? = null, ) { Row( horizontalArrangement = Arrangement.SpaceBetween, @@ -506,18 +478,11 @@ internal fun SparkTransactionRow( overflow = TextOverflow.MiddleEllipsis, ) } - Column( - horizontalAlignment = Alignment.End, + MoneyCaptionB( + sats = amountSats.toLong(), + symbol = true, modifier = Modifier.padding(start = 16.dp) - ) { - MoneyCaptionB(sats = amountSats.toLong(), symbol = true) - confirmations?.let { - CaptionB( - text = stringResource(R.string.lightning__spark_confirmations, minOf(it.toInt(), 3)), - color = Colors.Purple, - ) - } - } + ) } } @@ -607,7 +572,9 @@ private fun Preview() { inboundCapacityMsat = 700_000_000u, ), ), - ).toImmutableList() + ).toImmutableList(), + spark = SparkUi(balanceSats = 580_000uL, isReceiving = true), + isSparkReceiving = true, ) ) } 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 2cf199ddda..63f7992a32 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 @@ -262,22 +262,25 @@ data class SparkUi( val showsExitResult: Boolean = false, /** Earlier exits' funding addresses that hold, or may still receive, coins. */ val earlierAddresses: ImmutableList = persistentListOf(), + /** Spark is connected with no exit running, so it receives with no limit. */ + val isReceiving: Boolean = false, ) { /** * The emergency exit is offered while Spark holds funds, also a kept balance while it reads 0, and leads to its * progress while it shows one. */ val showsExit get() = balanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult - - val pendingDeposits get() = deposits.filterNot { it.deposit.isClaimed } - val claimedDeposits get() = deposits.filter { it.deposit.isClaimed } } data class SparkDepositUi( val deposit: SparkDeposit, /** On-chain confirmations, known for deposits this wallet sent. */ val confirmations: UInt? = null, -) +) { + /** The amount sent on-chain, which stays the same once Spark claims it for a fee. */ + val grossSats: ULong + get() = if (deposit.isClaimed) deposit.amountSats.safe() + deposit.feeSats.safe() else deposit.amountSats +} internal suspend fun SparkState.toUi( lightningRepo: LightningRepo, @@ -304,6 +307,7 @@ internal suspend fun SparkState.toUi( isExiting = isExiting, showsExitResult = showsExit, earlierAddresses = earlierAddresses.toImmutableList(), + isReceiving = isUsable, ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 53df70e275..338f74e738 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -1,21 +1,31 @@ package to.bitkit.ui.settings.lightning import android.content.Intent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +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.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow @@ -26,21 +36,27 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.collections.immutable.persistentListOf import to.bitkit.R +import to.bitkit.ext.ellipsisMiddle import to.bitkit.ext.setClipboardText +import to.bitkit.models.HealthState import to.bitkit.repositories.SparkDeposit import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkWithdrawal +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.CaptionB import to.bitkit.ui.components.ChannelStatusUi +import to.bitkit.ui.components.HorizontalSpacer import to.bitkit.ui.components.LightningChannel import to.bitkit.ui.components.MoneyCaptionB import to.bitkit.ui.components.PrimaryButton -import to.bitkit.ui.components.TertiaryButton +import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.getBlockExplorerUrl @@ -80,7 +96,7 @@ private fun Content( val spark = uiState.spark ?: SparkUi(balanceSats = 0uL) ScreenColumn { AppTopBar( - titleText = stringResource(R.string.lightning__spark), + titleText = stringResource(R.string.lightning__spark_provider_value), onBackClick = onBack, actions = { DrawerNavIcon() }, ) @@ -102,57 +118,36 @@ private fun Content( localBalance = spark.balanceSats.toLong(), remoteBalance = 0L, status = ChannelStatusUi.OPEN, - showReceiving = false, + showReceiving = spark.isReceiving, + receivingUnlimited = spark.isReceiving, ) - VerticalSpacer(32.dp) + VerticalSpacer(16.dp) HorizontalDivider() - SectionTitle(stringResource(R.string.lightning__spark_provider)) - SectionRow( - name = stringResource(R.string.lightning__spark_provider), - valueContent = { CaptionB(text = stringResource(R.string.lightning__spark_provider_value)) }, - ) - VerticalSpacer(12.dp) - BodyS(text = stringResource(R.string.lightning__spark_trust), color = Colors.White64) + SectionTitle(stringResource(R.string.lightning__status)) + SparkStatusRow(uiState.status) + HorizontalDivider() - uiState.depositAddress?.let { address -> + ProviderSection(depositAddress = uiState.depositAddress, onCopyText = onCopyText) + + SectionTitle(stringResource(R.string.lightning__balance)) + if (spark.isReceiving) { SectionRow( - name = stringResource(R.string.wallet__activity_address), + name = stringResource(R.string.lightning__receiving_label), valueContent = { - CaptionB( - text = address, - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - textAlign = TextAlign.End, - ) + CaptionB(text = stringResource(R.string.lightning__spark_receiving_unlimited)) }, - onClick = { onCopyText(address) }, - modifier = Modifier.testTag("SparkDepositAddress"), ) } - - SectionTitle(stringResource(R.string.lightning__balance)) SectionRow( name = stringResource(R.string.lightning__spending_label), valueContent = { MoneyCaptionB(sats = spark.balanceSats.toLong(), symbol = true) }, ) - if (spark.pendingDeposits.isNotEmpty()) { - SectionTitle(stringResource(R.string.lightning__spark_deposits_pending)) - spark.pendingDeposits.forEach { SparkDepositRow(it, onOpenTx) } - } - - if (spark.claimedDeposits.isNotEmpty()) { - SectionTitle(stringResource(R.string.lightning__spark_deposits_claimed)) - spark.claimedDeposits.forEach { depositUi -> - SparkDepositRow(depositUi, onOpenTx) - SectionRow( - name = stringResource(R.string.lightning__spark_claim_fee), - valueContent = { - MoneyCaptionB(sats = depositUi.deposit.feeSats.toLong(), symbol = true) - }, - ) - } + if (spark.deposits.isNotEmpty()) { + SectionTitle(stringResource(R.string.lightning__spark_deposits)) + HorizontalDivider() + spark.deposits.forEach { SparkDepositRows(it, onOpenTx) } } if (spark.earlierAddresses.isNotEmpty()) { @@ -184,32 +179,195 @@ private fun Content( VerticalSpacer(32.dp) } } - Column( + Buttons( + spark = spark, + onTransferToSavings = onTransferToSavings, + onEmergencyExit = onEmergencyExit, + ) + } +} + +@Composable +private fun SparkStatusRow(status: HealthState) { + val (text, color, background) = when (status) { + HealthState.READY -> Triple(R.string.lightning__order_state__open, Colors.Green, Colors.Green16) + HealthState.PENDING -> Triple(R.string.settings__status__spark__pending, Colors.Yellow, Colors.Yellow16) + HealthState.ERROR -> Triple(R.string.settings__status__spark__error, Colors.Red, Colors.Red16) + } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .padding(top = 8.dp, bottom = 16.dp) + .testTag("SparkStatus") + ) { + Box( + contentAlignment = Alignment.Center, modifier = Modifier - .padding(horizontal = 16.dp) - .navigationBarsPadding() + .size(32.dp) + .background(background, CircleShape) ) { - PrimaryButton( - text = stringResource(R.string.wallet__transfer_to_savings), - onClick = onTransferToSavings, - enabled = spark.balanceSats > 0uL && !spark.isExiting, - modifier = Modifier - .fillMaxWidth() - .testTag("SparkTransferToSavings") + Icon( + painter = painterResource(R.drawable.ic_lightning_alt), + contentDescription = null, + tint = color, + modifier = Modifier.size(16.dp) + ) + } + HorizontalSpacer(16.dp) + BodyMSB(text = stringResource(text), color = color) + } +} + +@Composable +private fun ProviderSection(depositAddress: String?, onCopyText: (String) -> Unit) { + SectionTitle(stringResource(R.string.lightning__spark_provider)) + SectionRow( + name = stringResource(R.string.lightning__spark), + valueContent = { + CaptionB(text = stringResource(R.string.lightning__spark_operators), textAlign = TextAlign.End) + }, + ) + depositAddress?.let { address -> + SectionRow( + name = stringResource(R.string.wallet__activity_address), + valueContent = { + CaptionB( + text = address, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + textAlign = TextAlign.End, + ) + }, + onClick = { onCopyText(address) }, + modifier = Modifier.testTag("SparkDepositAddress"), + ) + } + BodyM( + text = stringResource(R.string.lightning__spark_trust), + color = Colors.White50, + modifier = Modifier.padding(vertical = 16.dp) + ) + HorizontalDivider() +} + +@Composable +internal fun SparkDepositRows(depositUi: SparkDepositUi, onOpenTx: (String) -> Unit) { + val deposit = depositUi.deposit + Column(modifier = Modifier.padding(vertical = 8.dp)) { + CompactRow( + name = stringResource(R.string.lightning__spark_deposit_tx), + onClick = { onOpenTx(deposit.txid) }, + modifier = Modifier.testTag("SparkDeposit"), + ) { + CaptionB( + text = deposit.txid.ellipsisMiddle(DEPOSIT_TXID_LENGTH), + maxLines = 1, + textAlign = TextAlign.End, ) - if (spark.showsExit) { - VerticalSpacer(8.dp) - TertiaryButton( - text = stringResource(R.string.lightning__spark_exit__button), - onClick = onEmergencyExit, - modifier = Modifier.testTag("SparkEmergencyExit") + } + CompactRow(name = stringResource(R.string.lightning__spark_deposit)) { + MoneyCaptionB(sats = depositUi.grossSats.toLong(), symbol = true) + } + when { + deposit.isClaimed -> CompactRow(name = stringResource(R.string.lightning__spark_claim_fee)) { + MoneyCaptionB(sats = deposit.feeSats.toLong(), symbol = true) + } + + else -> CompactRow(name = stringResource(R.string.lightning__status)) { + CaptionB( + text = depositUi.confirmations?.let { + stringResource( + R.string.lightning__spark_confirmations, + minOf(it.toInt(), SPARK_CLAIM_CONFIRMATIONS), + ) + } ?: stringResource(R.string.wallet__activity_pending), + color = Colors.Purple, ) } - VerticalSpacer(16.dp) + } + } + HorizontalDivider() +} + +@Composable +private fun CompactRow( + name: String, + modifier: Modifier = Modifier, + onClick: (() -> Unit)? = null, + valueContent: @Composable () -> Unit, +) { + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = modifier + .fillMaxWidth() + .height(34.dp) + .clickableAlpha(onClick = onClick) + ) { + CaptionB(text = name, modifier = Modifier.weight(1f)) + Box( + contentAlignment = Alignment.CenterEnd, + modifier = Modifier.weight(1.5f), + ) { + valueContent() + } + } +} + +@Composable +private fun Buttons( + spark: SparkUi, + onTransferToSavings: () -> Unit, + onEmergencyExit: () -> Unit, +) { + Column( + verticalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier + .padding(horizontal = 16.dp) + .padding(top = 16.dp, bottom = 16.dp) + .navigationBarsPadding() + ) { + PrimaryButton( + text = stringResource(R.string.wallet__transfer_to_savings), + onClick = onTransferToSavings, + enabled = spark.balanceSats > 0uL && !spark.isExiting, + icon = { + Icon( + painter = painterResource(R.drawable.ic_transfer), + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkTransferToSavings") + ) + if (spark.showsExit) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__button), + onClick = onEmergencyExit, + icon = { + Icon( + painter = painterResource(R.drawable.ic_warning), + contentDescription = null, + tint = Colors.Yellow, + modifier = Modifier.size(16.dp) + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkEmergencyExit") + ) } } } +/** Confirmations after which Spark claims a deposit, shown as its "n/3 confirmations". */ +private const val SPARK_CLAIM_CONFIRMATIONS = 3 + +/** A deposit's txid shown as its first and last 8 characters, as the design shows it. */ +private const val DEPOSIT_TXID_LENGTH = 17 + @Composable private fun EarlierExitAddressRows(entry: SparkExitEarlierAddress, onCopyText: (String) -> Unit) { SectionRow( @@ -246,12 +404,14 @@ private fun Preview() { uiState = SparkDetailUiState( spark = SparkUi( balanceSats = 35_000uL, + isReceiving = true, deposits = persistentListOf( SparkDepositUi(SparkDeposit("6c8706b8a9cbd18f", 15_000uL, isClaimed = false), 1u), SparkDepositUi(SparkDeposit("d0067b2497c7b905", 35_000uL, isClaimed = true, feeSats = 312uL)), ), withdrawals = persistentListOf(SparkWithdrawal("4f1d0c55e2a9b713", 4_917uL, feeSats = 1_470uL)), ), + status = HealthState.READY, ), ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index fb62bd377a..f153ed8f82 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -14,6 +14,8 @@ import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.Network import to.bitkit.di.BgDispatcher import to.bitkit.env.Env +import to.bitkit.models.HealthState +import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkRepo @@ -26,6 +28,7 @@ class SparkDetailViewModel @Inject constructor( private val lightningRepo: LightningRepo, private val sparkRepo: SparkRepo, private val sparkExitRepo: SparkExitRepo, + private val healthRepo: HealthRepo, ) : ViewModel() { private val _uiState = MutableStateFlow(SparkDetailUiState()) val uiState = _uiState.asStateFlow() @@ -39,6 +42,11 @@ class SparkDetailViewModel @Inject constructor( } } } + viewModelScope.launch(bgDispatcher) { + healthRepo.healthState.collect { health -> + _uiState.update { it.copy(status = health.spark ?: HealthState.ERROR) } + } + } viewModelScope.launch(bgDispatcher) { // A cancelled exit's address may still receive a late payment: its balance shows here. sparkExitRepo.refreshEarlierAddresses() @@ -75,6 +83,8 @@ class SparkDetailViewModel @Inject constructor( data class SparkDetailUiState( val spark: SparkUi? = null, val isRefreshing: Boolean = false, + /** Spark's connection, as App Status shows it. */ + val status: HealthState = HealthState.PENDING, /** Spark's on-chain deposit address, shown on regtest to fund Spark from Lightspark's regtest faucet. */ val depositAddress: String? = null, ) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 4f4961f82c..791707b392 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -218,8 +218,6 @@ %1$d/3 تأكيدات إيداع انتظر - إيداعات تمت المطالبة بها - إيداعات قيد التنفيذ المبلغ المراد إخراجه خروج طارئ إلغاء الخروج @@ -1816,8 +1814,6 @@ عريض جارٍ تحديث الرصيد… يلزم تمويل الرسوم - قيد التنفيذ - الخروج الطارئ يستخدم Spark غير متصل جارٍ الاتصال... 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 036689fdc6..3fee149ddd 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -225,8 +225,6 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso Monto a retirar Salida de emergencia Cancelar salida @@ -1813,8 +1811,6 @@ Ancho Actualizando saldo… Financiación de comisiones necesaria - En curso - Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 1969719f21..ac169d01b3 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -222,8 +222,6 @@ %1$d/3 confirmacions Dipòsit Espera - Dipòsits reclamats - Dipòsits en curs Import a retirar Sortida d\'emergència Cancel·lar la sortida @@ -1813,8 +1811,6 @@ Ample S’està actualitzant el saldo… Cal finançament de comissions - En curs - Sortida d\'emergència Utilitzant Spark Fora de línia Connectant... diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2d9d49e79d..57ebf1c1df 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -225,8 +225,6 @@ %1$d/3 potvrzení Vklad Počkat - Připsané vklady - Probíhající vklady Částka k odchodu Nouzový odchod Zrušit odchod @@ -1814,8 +1812,6 @@ Široký Aktualizace zůstatku… Je potřeba financovat poplatky - Probíhá - Nouzový odchod Používá Spark Offline Připojování... diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 769d103e1e..b8e15dadae 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -107,8 +107,6 @@ %1$d/3 Bestätigungen Einzahlung Warten - Eingelöste Einzahlungen - Laufende Einzahlungen Auszahlungsbetrag Notausstieg Ausstieg abbrechen @@ -1812,8 +1810,6 @@ Breit Kontostand wird aktualisiert… Gebührenfinanzierung nötig - Läuft - Notausstieg Nutzt Spark Offline Verbinden... diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 280d225d59..8e1d4df709 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -218,8 +218,6 @@ %1$d/3 επιβεβαιώσεις Κατάθεση Αναμονή - Εξαργυρωμένες καταθέσεις - Καταθέσεις σε εξέλιξη Ποσό εξόδου Έξοδος έκτακτης ανάγκης Ακύρωση εξόδου @@ -1812,8 +1810,6 @@ Φαρδύ Ενημέρωση υπολοίπου… Απαιτείται χρηματοδότηση τελών - Σε εξέλιξη - Έξοδος Έκτακτης Ανάγκης Χρήση Spark Εκτός σύνδεσης Σύνδεση... diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 9906dff08c..fba1595639 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -224,8 +224,6 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso Importe a retirar Salida de emergencia Cancelar salida @@ -1813,8 +1811,6 @@ Ancho Actualizando saldo… Financiación de comisiones necesaria - En curso - Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a10b8fb1e0..92bbac2722 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -166,8 +166,6 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso Importe a retirar Salida de emergencia Cancelar salida @@ -1813,8 +1811,6 @@ Ancho Actualizando saldo… Financiación de comisiones necesaria - En curso - Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index ff086f8d6e..8910f9e925 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -106,8 +106,6 @@ %1$d/3 confirmations Dépôt Attendre - Dépôts réclamés - Dépôts en cours Montant à sortir Sortie d\'urgence Annuler la sortie @@ -1813,8 +1811,6 @@ Large Mise à jour du solde… Financement des frais requis - En cours - Sortie d\'urgence Via Spark Hors ligne Connexion... diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 92b86015f2..85f9d3a523 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -223,8 +223,6 @@ %1$d/3 conferme Deposito Attendi - Depositi riscattati - Depositi in corso Importo da far uscire Uscita di emergenza Annulla uscita @@ -1813,8 +1811,6 @@ Largo Aggiornamento del saldo… Finanziamento delle commissioni necessario - In corso - Uscita di Emergenza Tramite Spark Offline In connessione... diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index e58f279205..93f1159a8e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -222,8 +222,6 @@ %1$d/3 bevestigingen Storting Wachten - Geclaimde stortingen - Lopende stortingen Bedrag voor exit Noodexit Exit annuleren @@ -1812,8 +1810,6 @@ Breed Saldo bijwerken… Kostenfinanciering nodig - Bezig - Noodexit Via Spark Offline Verbinden... diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a15183132d..3b9d3bad34 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -108,8 +108,6 @@ %1$d/3 potwierdzeń Wpłata Czekaj - Odebrane wpłaty - Wpłaty w toku Kwota do wyjścia Wyjście awaryjne Anuluj wyjście @@ -1814,8 +1812,6 @@ Szeroki Aktualizowanie salda… Potrzebne finansowanie opłat - W toku - Wyjście awaryjne Przez Spark Offline Łączenie... diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 2d9c7afe25..ea6343c8c3 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -226,8 +226,6 @@ %1$d/3 confirmações Depósito Esperar - Depósitos resgatados - Depósitos em andamento Valor a retirar Saída de emergência Cancelar saída @@ -1813,8 +1811,6 @@ Largo Atualizando saldo… Financiamento das taxas necessário - Em andamento - Saída de Emergência Usando o Spark Offline Conectando... diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index e8701c7b86..965d10b791 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -103,8 +103,6 @@ %1$d/3 confirmações Depósito Esperar - Depósitos resgatados - Depósitos em curso Montante a retirar Saída de emergência Cancelar saída @@ -1813,8 +1811,6 @@ Largo A atualizar o saldo… Financiamento das taxas necessário - Em curso - Saída de Emergência Usando o Spark Offline Conectando... diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 7965ffb807..e8d6f7099d 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -234,8 +234,6 @@ %1$d/3 подтверждений Депозит Ждать - Зачисленные депозиты - Депозиты в обработке Сумма выхода Экстренный выход Отменить выход @@ -1828,8 +1826,6 @@ Широкий Обновление баланса… Нужны средства на комиссии - Выполняется - Экстренный Выход Через Spark Не в сети Подключение... diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1cf91009b3..0471ca1982 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -419,10 +419,10 @@ %1$d/3 confirmations Deposit Wait - Claimed deposits - Deposits in progress + Deposit tx + Deposits Amount to exit - Emergency exit + Force Transfer To Savings Cancel exit Couldn\'t check the funding address. Try again. Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. @@ -517,10 +517,11 @@ The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Lightspark, Breez and Flashnet Provider Spark via Breez - No limit - This balance is held on Spark, run by Lightspark, Breez and Flashnet. It is safe while at least one of them acts honestly. They can pause access, and leaving without them takes an on-chain exit. + no limit + Your spending balance uses Spark, operated by Lightspark, Breez and Flashnet. Its security depends on at least one operator acting honestly. Operators can pause access, and withdrawing without their cooperation requires you to initiate an on-chain exit. Spendable Onchain Spending Your savings cannot cover this transfer and its fees. Try a smaller amount. @@ -1162,6 +1163,7 @@ Warn when sending over $100 Security Settings + Bitkit v{version} Failed to complete a full backup Backing up... Backed up @@ -1171,8 +1173,6 @@ Connected Bitcoin Node Fee funding needed - In progress - Emergency Exit Disconnected Reconnecting... Connected @@ -1186,10 +1186,11 @@ Syncing... Synced Lightning Node - Offline + Offline... + Force transfer to savings in progress... Connecting... Connected - Spark + Lightning Provider (Spark) App Status Help Center Email address diff --git a/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt index f07f1b2a07..28ee099050 100644 --- a/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt @@ -28,6 +28,7 @@ class HealthRepoTest : BaseUnitTest() { private val connectivityRepo = mock() private val lightningRepo = mock() private val sparkRepo = mock() + private val sparkExitRepo = mock() private val cacheStore = mock() private val clock: Clock = mock() @@ -40,6 +41,7 @@ class HealthRepoTest : BaseUnitTest() { whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.CONNECTED)) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) + whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) whenever(cacheStore.backupStatuses).thenReturn(flowOf(emptyMap())) whenever(clock.now()).thenReturn(fixedTime) } @@ -50,6 +52,7 @@ class HealthRepoTest : BaseUnitTest() { connectivityRepo = connectivityRepo, lightningRepo = lightningRepo, sparkRepo = sparkRepo, + sparkExitRepo = sparkExitRepo, cacheStore = cacheStore, clock = clock, ) @@ -237,6 +240,63 @@ class HealthRepoTest : BaseUnitTest() { } } + @Test + fun `app status counts spark`() = test { + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + val sparkState = MutableStateFlow(SparkState(isSupported = true, isReady = true)) + whenever(sparkRepo.state).thenReturn(sparkState) + + sut = createSut() + + sut.healthState.test { + assertEquals(HealthState.READY, awaitItem().app) + sparkState.value = SparkState(isSupported = true) + assertEquals(HealthState.PENDING, awaitItem().app) + sparkState.value = SparkState(isSupported = true, hasStartFailed = true) + assertEquals(HealthState.ERROR, awaitItem().app) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `app status is pending while a force transfer to savings runs`() = test { + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState(isSupported = true, hasStartFailed = true))) + val exitState = MutableStateFlow(SparkExitState(record = SparkExitFixtures.record())) + whenever(sparkExitRepo.state).thenReturn(exitState) + + sut = createSut() + + sut.healthState.test { + val state = awaitItem() + assertEquals(true, state.isSparkExiting) + assertEquals(HealthState.ERROR, state.spark) + assertEquals(HealthState.PENDING, state.app) + exitState.value = SparkExitState(record = SparkExitFixtures.record(SparkExitRecord.Phase.Done)) + val ended = awaitItem() + assertEquals(false, ended.isSparkExiting) + assertEquals(HealthState.ERROR, ended.app) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `app status ignores spark where it is unsupported`() { + val state = AppHealthState(spark = null) + + assertEquals(HealthState.READY, state.computeApp()) + assertEquals(HealthState.READY, state.copy(isSparkExiting = true).computeApp()) + } + + @Test + fun `app status is pending while ready spark runs a force transfer`() { + val state = AppHealthState(spark = HealthState.READY, isSparkExiting = true) + + assertEquals(HealthState.PENDING, state.computeApp()) + } + @Test fun `spark is error when its start failed`() = test { whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState(isSupported = true, hasStartFailed = true))) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt new file mode 100644 index 0000000000..ba0035637c --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt @@ -0,0 +1,100 @@ +package to.bitkit.ui.settings.lightning + +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 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.repositories.SparkDeposit +import to.bitkit.ui.components.ChannelStatusUi +import to.bitkit.ui.components.LightningChannel +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) +class SparkDetailScreenTest { + private companion object { + const val TXID = "8a6716ce0a1b2c3d4e5f60718293a4b5c6d7e8f9011223344556677848ace8f6" + } + + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `a claimed deposit shows its claim fee and opens its transaction`() { + val opened = mutableListOf() + setDeposit(SparkDepositUi(SparkDeposit(TXID, 35_000uL, isClaimed = true, feeSats = 312uL)), opened::add) + + composeRule.onNodeWithText("Deposit tx").assertExists() + composeRule.onNodeWithText("8a6716ce…48ace8f6").assertExists() + composeRule.onNodeWithText("Claim fee").assertExists() + composeRule.onNodeWithText("Status").assertDoesNotExist() + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + composeRule.onNodeWithTag("SparkDeposit").performClick() + + assertEquals(listOf(TXID), opened) + } + + @Test + fun `an unclaimed deposit shows its confirmations up to three`() { + setDeposit(SparkDepositUi(SparkDeposit(TXID, 15_000uL, isClaimed = false), confirmations = 5u)) + + composeRule.onNodeWithText("Status").assertExists() + composeRule.onNodeWithText("3/3 confirmations").assertExists() + composeRule.onNodeWithText("Claim fee").assertDoesNotExist() + } + + @Test + fun `an unclaimed deposit with unknown confirmations shows as pending`() { + setDeposit(SparkDepositUi(SparkDeposit(TXID, 15_000uL, isClaimed = false), confirmations = null)) + + composeRule.onNodeWithText("Status").assertExists() + composeRule.onNodeWithText("Pending").assertExists() + composeRule.onNodeWithText("Claim fee").assertDoesNotExist() + } + + @Test + fun `the bar reads no limit while spark receives`() { + setBar(isReceiving = true) + + composeRule.onNodeWithText("no limit").assertExists() + } + + @Test + fun `the bar claims no receiving while spark cannot receive`() { + setBar(isReceiving = false) + + composeRule.onNodeWithText("no limit").assertDoesNotExist() + } + + private fun setDeposit(depositUi: SparkDepositUi, onOpenTx: (String) -> Unit = {}) { + composeRule.setContent { + AppThemeSurface { + SparkDepositRows(depositUi = depositUi, onOpenTx = onOpenTx) + } + } + } + + private fun setBar(isReceiving: Boolean) { + composeRule.setContent { + AppThemeSurface { + LightningChannel( + capacity = 580_000L, + localBalance = 580_000L, + remoteBalance = 0L, + status = ChannelStatusUi.OPEN, + showReceiving = isReceiving, + receivingUnlimited = isReceiving, + ) + } + } + } +} diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt new file mode 100644 index 0000000000..aae22fa943 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -0,0 +1,63 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.models.HealthState +import to.bitkit.repositories.AppHealthState +import to.bitkit.repositories.HealthRepo +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +class SparkDetailViewModelTest : BaseUnitTest() { + private val healthState = MutableStateFlow(AppHealthState()) + private val lightningRepo = mock() + private val sparkRepo = mock() + private val sparkExitRepo = mock() + private val healthRepo = mock() + + @Before + fun setUp() { + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) + whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) + whenever(healthRepo.healthState).thenReturn(healthState) + } + + private fun createSut() = SparkDetailViewModel( + bgDispatcher = testDispatcher, + lightningRepo = lightningRepo, + sparkRepo = sparkRepo, + sparkExitRepo = sparkExitRepo, + healthRepo = healthRepo, + ) + + @Test + fun `status follows spark's health as app status shows it`() = test { + whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) + healthState.value = AppHealthState(spark = HealthState.READY) + val sut = createSut() + + assertEquals(HealthState.READY, sut.uiState.value.status) + healthState.value = AppHealthState(spark = HealthState.PENDING) + assertEquals(HealthState.PENDING, sut.uiState.value.status) + healthState.value = AppHealthState(spark = HealthState.ERROR) + assertEquals(HealthState.ERROR, sut.uiState.value.status) + } + + @Test + fun `status is offline while spark's health is unknown`() = test { + whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) + healthState.value = AppHealthState(spark = null) + + val sut = createSut() + + assertEquals(HealthState.ERROR, sut.uiState.value.status) + } +} diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index d00e9bf478..2af3d039e0 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -2,6 +2,7 @@ package to.bitkit.ui.settings.lightning import org.junit.Test import org.mockito.kotlin.mock +import to.bitkit.repositories.SparkDeposit import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest @@ -37,5 +38,23 @@ class SparkUiTest : BaseUnitTest() { assertEquals(listOf(earlier), ui.earlierAddresses) assertFalse(ui.showsExit, "an empty spark offers no exit") + assertFalse(ui.isReceiving, "an offline spark receives nothing") + } + + @Test + fun `a deposit shows the amount sent on-chain before and after spark claims it`() { + val pending = SparkDepositUi(SparkDeposit("txid", 5_000uL, isClaimed = false)) + val claimed = SparkDepositUi(SparkDeposit("txid", 4_901uL, isClaimed = true, feeSats = 99uL)) + + assertEquals(5_000uL, pending.grossSats) + assertEquals(5_000uL, claimed.grossSats) + } + + @Test + fun `spark receives with no limit only while connected and not exiting`() = test { + val ready = SparkState(isReady = true, balanceSats = 10_000uL) + + assertTrue(assertNotNull(ready.toUi(mock())).isReceiving) + assertFalse(assertNotNull(ready.copy(isExiting = true).toUi(mock())).isReceiving) } } diff --git a/docs/screens-map.md b/docs/screens-map.md index 7ef0a7c707..cd223bccf7 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -317,7 +317,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | CloseConnectionScreen.kt | Settings > Advanced › Close connection | | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | | MoveToSparkScreen.kt | `todo` | -| SparkDetailScreen.kt | `todo` | +| SparkDetailScreen.kt | Settings > Advanced › Connection details Spark | | SparkExitConfirmScreen.kt | `todo` | | SparkExitFeeBumpScreen.kt | `todo` | | SparkExitFundingScreen.kt | `todo` | diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml index 6173f75650..20fdda5c00 100644 --- a/journeys/settings/app-status-emergency-exit.xml +++ b/journeys/settings/app-status-emergency-exit.xml @@ -1,22 +1,23 @@ - While an emergency exit is active, App Status shows an "Emergency Exit" row under Lightning Connection. - It reads "Fee funding needed" while the exit asks for fee funding and "In progress" otherwise, including + While an emergency exit is active, App Status shows the force transfer on the "Lightning Provider (Spark)" + row under Lightning Connection, with a yellow warning icon. It reads "Fee funding needed" while the exit asks for fee funding and "Force transfer to savings in progress..." otherwise, including while a payment that covers the funding waits to confirm. The row opens the exit's progress screen, and - leaving that screen returns to App Status. With no active exit the row is absent. An exit paid from savings cannot be - cancelled and runs for days, so the row's removal once an exit ends is covered by unit tests, not here. An exit takes Spark off the Lightning rail, so with no usable channel + leaving that screen returns to App Status. With no active exit the row shows Spark's connection again. An exit paid from savings cannot be + cancelled and runs for days, so the row's return to the connection once an exit ends is covered by unit tests, not here. An exit takes Spark off the Lightning rail, so with no usable channel Lightning Connection stops reading "Using Spark" while it runs. - Precondition: dev build on regtest with Spark connected, a Spark balance and savings that can pay the exit's + Precondition: dev build on regtest with Spark connected, a Spark balance (send from Lightspark's regtest faucet (https://app.lightspark.com/regtest-faucet) to + the Spark connection screen's deposit address, testTag "SparkDepositAddress") and savings that can pay the exit's fee funding. The wallet has no Lightning channel. Start an emergency exit from Spark (spark emergency exit journey), pick "Pay from savings" and swipe to start it. Starting an exit takes the Spark balance out of Spending for days, so use a throwaway wallet. Start on the wallet home screen. Tap the menu button (testTag "HeaderMenu") and tap App Status (testTag "DrawerAppStatus") - Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "In progress", since savings paid the funding + Verify the "Lightning Provider (Spark)" row (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "Force transfer to savings in progress...", since savings paid the funding Verify Lightning Connection (testTag "Status-lightning_connection") reads "No open connections", not "Using Spark" Tap the row and verify the exit's progress screen (testTag "SparkExitProgress") opens - Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again with the "Emergency Exit" row still there + Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again with the row (testTag "Status-spark_exit") still reading "Force transfer to savings in progress..." diff --git a/journeys/settings/app-status-spark-row.xml b/journeys/settings/app-status-spark-row.xml index 9a4e58a884..3626afb7fb 100644 --- a/journeys/settings/app-status-spark-row.xml +++ b/journeys/settings/app-status-spark-row.xml @@ -1,9 +1,9 @@ - App Status shows a Spark row under Lightning Connection on builds where Spark is supported. A dev build + App Status shows a "Lightning Provider (Spark)" row under Lightning Connection on builds where Spark is supported. A dev build on regtest connects Spark to its hosted regtest with no key (journeys/README.md capabilities), so with no channel the row reads Connected and Lightning Connection reads "Using Spark". Once Connected, the - row opens Spark's detail screen. Connecting and Offline are covered by unit tests and the PR's + row opens Spark's detail screen. Connecting and "Offline..." are covered by unit tests and the PR's screenshots. If the row never reads Connected within 2 minutes, the run is blocked on the hosted regtest, not failed. @@ -11,8 +11,9 @@ Tap the menu button (testTag "HeaderMenu") and tap App Status (testTag "DrawerAppStatus") - Verify a row titled "Spark" (testTag "Status-spark") sits directly under Lightning Connection (testTag "Status-lightning_connection") and reads "Connected" within 2 minutes + Verify a row titled "Lightning Provider (Spark)" (testTag "Status-spark") sits directly under Lightning Connection (testTag "Status-lightning_connection") and reads "Connected" within 2 minutes Verify Lightning Connection reads "Using Spark" - Tap the Spark row and verify Spark's detail screen opens + Verify "Bitkit v" with the app's version and build (testTag "AppVersion") shows centred at the bottom + Tap the row and verify Spark's detail screen opens diff --git a/journeys/settings/spark-connection-details.xml b/journeys/settings/spark-connection-details.xml new file mode 100644 index 0000000000..3ebbf75fb6 --- /dev/null +++ b/journeys/settings/spark-connection-details.xml @@ -0,0 +1,32 @@ + + + Lightning Connections lists Spark last under OPEN CONNECTIONS, after any open channel, as "Spark via Breez" + with a channel bar whose receiving side reads "no limit". Its detail screen shows the same bar, then STATUS + ("Connection open" in green while Spark is connected, "Connecting..." in yellow, "Offline..." in red), + PROVIDER (Spark operators, the regtest deposit address, the trust paragraph), BALANCE (receiving capacity + "no limit", spending balance) and DEPOSITS, one group per deposit: its transaction (first and last 8 + characters), the amount sent on-chain, which stays the same once claimed, and the claim fee once claimed or + the confirmations until then. The footer holds "Transfer To Savings" and, while Spark holds funds or a force + transfer runs, "Force Transfer To Savings". + Spark's row shows once Spark is connected, so "Connecting..." and "Offline..." are covered by unit tests and + the PR's screenshots, not here. On Spark's regtest the app's block explorer is the staging one, which does + not know Spark's chain, so the deposit's page keeps waiting for the transaction; the journey checks only + that the explorer opens at the deposit's txid. + + Precondition: dev build on regtest with Spark connected on its regtest (journeys/README.md capabilities), + no Lightning channel, and a claimed Spark deposit: send from Lightspark's regtest faucet (https://app.lightspark.com/regtest-faucet) + to the deposit address the Spark connection screen shows (testTag "SparkDepositAddress") and wait for 3 + confirmations. Start on the wallet home screen. + + + Tap the menu button (testTag "HeaderMenu"), Settings (testTag "DrawerSettings"), the Advanced tab (testTag "Tab-advanced") and Lightning Connections (testTag "Channels") + Verify the header's receiving reads "no limit" and OPEN CONNECTIONS lists "Spark via Breez" (testTag "SparkConnection") with its bar's receiving side reading "no limit", and no separate SPARK section + Tap "Spark via Breez" and verify the title "Spark via Breez" and the same bar at the top + Verify STATUS shows "Connection open" in green (testTag "SparkStatus") + Verify PROVIDER shows "Spark" with "Lightspark, Breez and Flashnet", the deposit address (testTag "SparkDepositAddress") and the paragraph starting "Your spending balance uses Spark" + Verify BALANCE shows "Receiving capacity" with "no limit" and "Spending balance" with the Spark balance + Verify DEPOSITS shows "Deposit tx" with the transaction id's first and last 8 characters (testTag "SparkDeposit"), "Deposit" with the amount sent from the faucet and "Claim fee" + Verify the footer shows "Transfer To Savings" (testTag "SparkTransferToSavings") enabled and "Force Transfer To Savings" (testTag "SparkEmergencyExit") with a warning icon inside the button, left of its text + Tap "Deposit tx" and verify the browser opens the block explorer at a URL ending in the deposit's txid + + diff --git a/journeys/transfer/spark-emergency-exit.xml b/journeys/transfer/spark-emergency-exit.xml index 827922da94..3fd6aedc78 100644 --- a/journeys/transfer/spark-emergency-exit.xml +++ b/journeys/transfer/spark-emergency-exit.xml @@ -1,7 +1,7 @@ Verifies the Spark emergency exit up to the swipe. With a Spark balance, the Spark connection screen shows - "Emergency exit" (testTag "SparkEmergencyExit") under "Transfer to Savings". It opens the explainer, then the + "Force Transfer To Savings" (testTag "SparkEmergencyExit") under "Transfer To Savings". It opens the explainer, then the quote, which asks the SDK's prepareRecoverFunds for every leaf and lists "Amount to exit", "Network fees", "You receive about" and, when the exit needs CPFP fee funding, "Fee funding needed". Continue leads to the funding screen, whose "Fund from another wallet" shows the funding address as a QR code. The journey stops before @@ -11,7 +11,7 @@ Precondition: dev build with Spark connected on its regtest (no key needed) and a Spark balance, funded at the deposit address the Spark connection screen shows (testTag "SparkDepositAddress") from Lightspark's regtest - faucet. Start on the wallet home screen. + faucet (https://app.lightspark.com/regtest-faucet). Start on the wallet home screen. Tap the menu icon (testTag "HeaderMenu") @@ -19,12 +19,12 @@ Tap the Advanced tab (testTag "Tab-advanced") Tap Lightning Connections (testTag "Channels") Tap the Spark connection (testTag "SparkConnection") - Scroll down and verify "Transfer to Savings" (testTag "SparkTransferToSavings") is enabled and "Emergency exit" (testTag "SparkEmergencyExit") shows under it - Tap "Emergency exit" and verify the "Leave Spark on-chain" explainer says the exit takes up to 4 weeks, runs in the background and that Bitkit notifies you if it needs you + Scroll down and verify "Transfer To Savings" (testTag "SparkTransferToSavings") is enabled and "Force Transfer To Savings" (testTag "SparkEmergencyExit") shows under it + Tap "Force Transfer To Savings" and verify the "Leave Spark on-chain" explainer says the exit takes up to 4 weeks, runs in the background and that Bitkit notifies you if it needs you Tap "Continue" (testTag "SparkExitIntroContinue") and verify the "Exit quote" screen shows "Getting a quote…" and then "Amount to exit", "Network fees" and "You receive about" Verify no reason shows in red (testTag "SparkExitQuoteBlocked") and "Continue" (testTag "SparkExitQuoteContinue") is enabled Tap "Continue" and verify the "Fund the fees" screen names the fee funding amount, with "Pay from savings" (testTag "SparkExitFundSavings") and "Fund from another wallet" (testTag "SparkExitFundExternal") Tap "Fund from another wallet" and verify a QR code and a bcrt1 address (testTag "SparkExitFundingAddress") show, and "Continue" (testTag "SparkExitFundingContinue") is disabled - Go back to the Spark connection screen and verify "Transfer to Savings" is still enabled: nothing started + Go back to the Spark connection screen and verify "Transfer To Savings" is still enabled: nothing started From 63cd701fe5bd03a26bdbd8bd6fc7c98194fccfad Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:29:52 +0100 Subject: [PATCH 02/23] fix: show an unconfirmed spark deposit as pending Verified: just format, just compile, just test, just lint --- .../to/bitkit/ui/settings/lightning/SparkDetailScreen.kt | 2 +- .../bitkit/ui/settings/lightning/SparkDetailScreenTest.kt | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 338f74e738..68684e4c7e 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -275,7 +275,7 @@ internal fun SparkDepositRows(depositUi: SparkDepositUi, onOpenTx: (String) -> U else -> CompactRow(name = stringResource(R.string.lightning__status)) { CaptionB( - text = depositUi.confirmations?.let { + text = depositUi.confirmations?.takeIf { it > 0u }?.let { stringResource( R.string.lightning__spark_confirmations, minOf(it.toInt(), SPARK_CLAIM_CONFIRMATIONS), diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt index ba0035637c..9d64583e7c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt @@ -61,6 +61,14 @@ class SparkDetailScreenTest { composeRule.onNodeWithText("Claim fee").assertDoesNotExist() } + @Test + fun `an unclaimed deposit still in the mempool shows as pending`() { + setDeposit(SparkDepositUi(SparkDeposit(TXID, 15_000uL, isClaimed = false), confirmations = 0u)) + + composeRule.onNodeWithText("Pending").assertExists() + composeRule.onNodeWithText("0/3 confirmations").assertDoesNotExist() + } + @Test fun `the bar reads no limit while spark receives`() { setBar(isReceiving = true) From 3540ddeac374f067567078aa74fd130f38c9362c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:31:00 +0100 Subject: [PATCH 03/23] chore: add changelog fragment Verified: none (changelog text only) --- changelog.d/next/1964.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1964.changed.md diff --git a/changelog.d/next/1964.changed.md b/changelog.d/next/1964.changed.md new file mode 100644 index 0000000000..e611a7ca71 --- /dev/null +++ b/changelog.d/next/1964.changed.md @@ -0,0 +1 @@ +Spark connection details and App Status show Spark's status, provider, balance and deposits, and a force transfer to savings on the Spark row. From 54acd5ae2c14f8eec54c4e487770bc1e3be04afa Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:04:04 +0100 Subject: [PATCH 04/23] fix: drop spark's unlimited receiving while offline Verified: just format, just compile, just test, just lint --- .../LightningConnectionsViewModel.kt | 20 ++++++++++++---- .../lightning/SparkDetailViewModel.kt | 24 ++++++++++++++----- .../LightningConnectionsViewModelTest.kt | 3 +++ .../ui/settings/lightning/SparkUiTest.kt | 3 ++- 4 files changed, 39 insertions(+), 11 deletions(-) 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 63f7992a32..5489c90e97 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 @@ -17,6 +17,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.ChannelDetails @@ -31,10 +33,12 @@ import to.bitkit.ext.calculateRemoteBalance import to.bitkit.ext.createChannelDetails import to.bitkit.ext.filterOpen import to.bitkit.ext.filterPending +import to.bitkit.models.HealthState import to.bitkit.models.Toast import to.bitkit.models.safe import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo +import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.LogsRepo @@ -61,6 +65,7 @@ class LightningConnectionsViewModel @Inject constructor( private val activityRepo: ActivityRepo, private val sparkRepo: SparkRepo, private val sparkExitRepo: SparkExitRepo, + private val healthRepo: HealthRepo, ) : ViewModel() { companion object { @@ -108,8 +113,9 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lastKnownChannels, sparkRepo.state, sparkExitRepo.state, - ) { lightningState, channels, sparkState, exitState -> - ConnectionsSnapshot(lightningState, channels, sparkState, exitState) + healthRepo.healthState.map { it.internet == HealthState.READY }.distinctUntilChanged(), + ) { lightningState, channels, sparkState, exitState, isOnline -> + ConnectionsSnapshot(lightningState, channels, sparkState, exitState, isOnline) }.collect { snapshot -> val (lightningState, channels, sparkState) = snapshot val isNodeRunning = lightningState.nodeLifecycleState.isRunning() @@ -132,8 +138,9 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo, snapshot.exitState.showsResult, snapshot.exitState.earlierAddresses, + snapshot.isOnline, ), - isSparkReceiving = sparkState.isUsable, + isSparkReceiving = sparkState.isReceiving(snapshot.isOnline), ) } } @@ -286,6 +293,7 @@ internal suspend fun SparkState.toUi( lightningRepo: LightningRepo, showsExitResult: Boolean = false, earlierAddresses: List = emptyList(), + isOnline: Boolean = true, ): SparkUi? { val showsExit = isExiting || showsExitResult // An emergency exit keeps Spark listed, also while it cannot connect, so its progress stays reachable. So do an @@ -307,15 +315,19 @@ internal suspend fun SparkState.toUi( isExiting = isExiting, showsExitResult = showsExit, earlierAddresses = earlierAddresses.toImmutableList(), - isReceiving = isUsable, + isReceiving = isReceiving(isOnline), ) } +/** Spark receives with no limit only while the device is online and Spark is usable, as its status shows. */ +internal fun SparkState.isReceiving(isOnline: Boolean) = isOnline && isUsable + private data class ConnectionsSnapshot( val lightningState: LightningState, val channels: List, val sparkState: SparkState, val exitState: SparkExitState, + val isOnline: Boolean, ) data class ChannelUi( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index f153ed8f82..4060287672 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -9,6 +9,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.Network @@ -35,12 +37,13 @@ class SparkDetailViewModel @Inject constructor( init { viewModelScope.launch(bgDispatcher) { - combine(sparkRepo.state, sparkExitRepo.state) { state, exit -> state to exit } - .collect { (state, exit) -> - _uiState.update { - it.copy(spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses)) - } + combine(sparkRepo.state, sparkExitRepo.state, isOnline()) { state, exit, isOnline -> + Triple(state, exit, isOnline) + }.collect { (state, exit, isOnline) -> + _uiState.update { + it.copy(spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline)) } + } } viewModelScope.launch(bgDispatcher) { healthRepo.healthState.collect { health -> @@ -64,6 +67,8 @@ class SparkDetailViewModel @Inject constructor( } } + private fun isOnline() = healthRepo.healthState.map { it.internet == HealthState.READY }.distinctUntilChanged() + fun onPullToRefresh() { viewModelScope.launch { _uiState.update { it.copy(isRefreshing = true) } @@ -71,7 +76,14 @@ class SparkDetailViewModel @Inject constructor( sparkExitRepo.refreshEarlierAddresses() val exit = sparkExitRepo.state.value _uiState.update { - it.copy(spark = sparkRepo.state.value.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses)) + it.copy( + spark = sparkRepo.state.value.toUi( + lightningRepo, + exit.showsResult, + exit.earlierAddresses, + healthRepo.healthState.value.internet == HealthState.READY, + ) + ) } delay(500.milliseconds) _uiState.update { it.copy(isRefreshing = false) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt index a594d2f6fe..4ddc814c5a 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt @@ -16,7 +16,9 @@ import to.bitkit.R import to.bitkit.ext.createChannelDetails import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.ActivityRepo +import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.BlocktankRepo +import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.LogsRepo @@ -83,5 +85,6 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { activityRepo = activityRepo, sparkRepo = sparkRepo, sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, + healthRepo = mock { on { healthState } doReturn MutableStateFlow(AppHealthState()) }, ) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index 2af3d039e0..e9bb9999ab 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -51,10 +51,11 @@ class SparkUiTest : BaseUnitTest() { } @Test - fun `spark receives with no limit only while connected and not exiting`() = test { + fun `spark receives with no limit only while online, connected and not exiting`() = test { val ready = SparkState(isReady = true, balanceSats = 10_000uL) assertTrue(assertNotNull(ready.toUi(mock())).isReceiving) assertFalse(assertNotNull(ready.copy(isExiting = true).toUi(mock())).isReceiving) + assertFalse(assertNotNull(ready.toUi(mock(), isOnline = false)).isReceiving) } } From 65a0d29862300f09fef5417ee78c1ffbc4950229 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 01:53:21 +0100 Subject: [PATCH 05/23] chore: translate spark connection and status strings Verified: just compile, just lint --- app/src/main/res/values-ar/strings.xml | 13 +++++++++---- app/src/main/res/values-b+es+419/strings.xml | 15 ++++++++++----- app/src/main/res/values-ca/strings.xml | 15 ++++++++++----- app/src/main/res/values-cs/strings.xml | 15 ++++++++++----- app/src/main/res/values-de/strings.xml | 15 ++++++++++----- app/src/main/res/values-el/strings.xml | 15 ++++++++++----- app/src/main/res/values-es-rES/strings.xml | 15 ++++++++++----- app/src/main/res/values-es/strings.xml | 15 ++++++++++----- app/src/main/res/values-fr/strings.xml | 15 ++++++++++----- app/src/main/res/values-it/strings.xml | 15 ++++++++++----- app/src/main/res/values-nl/strings.xml | 15 ++++++++++----- app/src/main/res/values-pl/strings.xml | 15 ++++++++++----- app/src/main/res/values-pt-rBR/strings.xml | 15 ++++++++++----- app/src/main/res/values-pt/strings.xml | 15 ++++++++++----- app/src/main/res/values-ru/strings.xml | 15 ++++++++++----- 15 files changed, 149 insertions(+), 74 deletions(-) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 791707b392..c2ac231ece 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -218,8 +218,10 @@ %1$d/3 تأكيدات إيداع انتظر + معاملة الإيداع + الإيداعات المبلغ المراد إخراجه - خروج طارئ + تحويل قسري إلى المدخرات إلغاء الخروج تعذّر التحقق من عنوان التمويل. حاول مرة أخرى. يعود Spark إلى ما كان عليه. إذا وصلت دفعة إلى عنوان تمويل رسوم الخروج، يعيدها Bitkit إلى المدخرات. @@ -311,10 +313,11 @@ الرسوم أعلى مما ستستلمه. لا يمكن قراءة جزء من هذا الخروج على السلسلة الآن. يحاول Bitkit مجددًا لمدة تصل إلى أسبوع. ينتظر {amount} الذي نقله مشغّلو Spark على السلسلة أن يفرجوا عنه. يطلب Bitkit مجددًا لمدة تصل إلى أسبوع. + Lightspark وBreez وFlashnet المزوّد Spark عبر Breez بلا حد - يُحفظ هذا الرصيد على Spark الذي تديره Lightspark وBreez وFlashnet. يبقى آمنًا ما دام أحدهم على الأقل يتصرف بأمانة. يمكنهم إيقاف الوصول مؤقتًا، والخروج من دونهم يتطلب خروجًا على السلسلة. + يستخدم رصيد الإنفاق Spark، الذي تديره Lightspark وBreez وFlashnet. يعتمد أمانه على تصرّف مشغّل واحد على الأقل بأمانة. يمكن للمشغّلين إيقاف الوصول مؤقتًا، والسحب من دون تعاونهم يتطلب منك بدء خروج على السلسلة. قابل للإنفاق على السلسلة الإنفاق لا تكفي مدخراتك لتغطية هذا التحويل ورسومه. جرّب مبلغًا أصغر. @@ -776,6 +779,7 @@ الأمان الأمان والخصوصية الإعدادات + Bitkit v{version} فشل إكمال النسخة الاحتياطية الكاملة جارٍ النسخ الاحتياطي... تم النسخ الاحتياطي @@ -796,6 +800,7 @@ جارٍ المزامنة... متزامن عقدة Lightning + جارٍ التحويل القسري إلى المدخرات... حالة التطبيق مركز المساعدة عنوان البريد الإلكتروني @@ -1815,8 +1820,8 @@ جارٍ تحديث الرصيد… يلزم تمويل الرسوم يستخدم Spark - غير متصل + غير متصل... جارٍ الاتصال... متصل - Spark + مزوّد Lightning (Spark) 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 3fee149ddd..8651e034f0 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -225,8 +225,10 @@ %1$d/3 confirmaciones Depósito Esperar + Tx de depósito + Depósitos Monto a retirar - Salida de emergencia + Transferencia forzada a ahorros Cancelar salida No se pudo comprobar la dirección de financiación. Intenta de nuevo. Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. @@ -318,10 +320,11 @@ Las comisiones son mayores que lo que recibirías. En este momento no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. + Lightspark, Breez y Flashnet Proveedor Spark mediante Breez - Sin límite - Este saldo se guarda en Spark, operado por Lightspark, Breez y Flashnet. Está seguro mientras al menos uno de ellos actúe con honestidad. Pueden pausar el acceso, y salir sin ellos requiere una salida on-chain. + sin límite + Tu saldo de gastos usa Spark, operado por Lightspark, Breez y Flashnet. Su seguridad depende de que al menos un operador actúe con honestidad. Los operadores pueden pausar el acceso, y retirar sin su cooperación requiere que inicies una salida on-chain. Gastable onchain Gasto Sus ahorros no alcanzan para cubrir esta transferencia y sus comisiones. Intente con un monto menor. @@ -797,6 +800,7 @@ Seguridad Seguridad y Privacidad Ajustes + Bitkit v{version} No se ha podido completar una copia de seguridad completa Respaldando... Copia de seguridad @@ -817,6 +821,7 @@ Sincronización... Sincronizado Nodo Lightning + Transferencia forzada a ahorros en curso... Estatus del App Centro de ayuda Dirección de correo electrónico @@ -1812,8 +1817,8 @@ Actualizando saldo… Financiación de comisiones necesaria Usando Spark - Sin conexión + Sin conexión... Conectando... Conectado - Spark + Proveedor Lightning (Spark) diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index ac169d01b3..187eb77f7c 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -222,8 +222,10 @@ %1$d/3 confirmacions Dipòsit Espera + Tx del dipòsit + Dipòsits Import a retirar - Sortida d\'emergència + Transferència forçosa a estalvis Cancel·lar la sortida No s\'ha pogut comprovar l\'adreça de finançament. Torna-ho a intentar. Spark torna a l\'estat anterior. Si un pagament ha arribat a l\'adreça de finançament de comissions de la sortida, Bitkit el retorna als estalvis. @@ -315,10 +317,11 @@ Les comissions són més altes del que rebries. Ara mateix no es pot llegir on-chain part d\'aquesta sortida. Bitkit ho torna a intentar durant un màxim d\'una setmana. {amount} que els operadors de Spark han mogut on-chain espera que l\'alliberin. Bitkit els ho torna a demanar durant un màxim d\'una setmana. + Lightspark, Breez i Flashnet Proveïdor Spark mitjançant Breez - Sense límit - Aquest saldo es guarda a Spark, gestionat per Lightspark, Breez i Flashnet. Està segur mentre almenys un d’ells actuï amb honestedat. Poden pausar l’accés, i sortir-ne sense ells requereix una sortida on-chain. + sense límit + El teu saldo de despesa utilitza Spark, gestionat per Lightspark, Breez i Flashnet. La seva seguretat depèn que almenys un operador actuï amb honestedat. Els operadors poden pausar l\'accés, i retirar sense la seva cooperació requereix que iniciïs una sortida on-chain. Gastable Onchain Despesa Els teus estalvis no poden cobrir aquesta transferència i les seves tarifes. Prova un import més petit. @@ -791,6 +794,7 @@ Seguretat Seguretat i privacitat Configuracions + Bitkit v{version} No s\'ha pogut completar una còpia de seguretat completa Fent còpia de seguretat... Còpia de seguretat feta @@ -811,6 +815,7 @@ Sincronitzant... Sincronitzat Node de Lightning + Transferència forçosa a estalvis en curs... Estat de l\'aplicació Centre d\'ajuda Adreça de correu electrònic @@ -1812,8 +1817,8 @@ S’està actualitzant el saldo… Cal finançament de comissions Utilitzant Spark - Fora de línia + Fora de línia... Connectant... Connectat - Spark + Proveïdor Lightning (Spark) diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 57ebf1c1df..58d5705d7f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -225,8 +225,10 @@ %1$d/3 potvrzení Vklad Počkat + Tx vkladu + Vklady Částka k odchodu - Nouzový odchod + Vynutit převod do úspor Zrušit odchod Adresu pro financování se nepodařilo zkontrolovat. Zkuste to znovu. Spark se vrátí do původního stavu. Pokud na adresu pro financování poplatků odchodu dorazila platba, Bitkit ji pošle zpět do úspor. @@ -318,10 +320,11 @@ Poplatky jsou vyšší, než kolik byste obdrželi. Část tohoto odchodu teď nelze on-chain načíst. Bitkit to bude zkoušet znovu až týden. {amount}, které operátoři Sparku přesunuli on-chain, čeká, až je uvolní. Bitkit se bude ptát znovu až týden. + Lightspark, Breez a Flashnet Poskytovatel Spark přes Breez - Bez limitu - Tento zůstatek je uložen na Spark, který provozují Lightspark, Breez a Flashnet. Je v bezpečí, dokud alespoň jeden z nich jedná poctivě. Mohou pozastavit přístup a odchod bez nich vyžaduje on-chain výstup. + bez limitu + Váš výdajový zůstatek využívá Spark, který provozují Lightspark, Breez a Flashnet. Jeho bezpečnost závisí na tom, že alespoň jeden provozovatel jedná poctivě. Provozovatelé mohou pozastavit přístup a výběr bez jejich spolupráce vyžaduje, abyste zahájili on-chain výstup. Utratitelné onchain Útraty Vaše úspory nepokryjí tento převod a jeho poplatky. Zkuste menší částku. @@ -796,6 +799,7 @@ Bezpečnost Bezpečnost a soukromí Nastavení + Bitkit v{version} Selhalo dokončení úplné zálohy Zálohování... Zálohováno @@ -816,6 +820,7 @@ Synchronizace... Synchronizováno Lightning uzel + Probíhá vynucený převod do úspor... Stav aplikace Centrum pomoci E-mailová adresa @@ -1813,8 +1818,8 @@ Aktualizace zůstatku… Je potřeba financovat poplatky Používá Spark - Offline + Offline... Připojování... Připojeno - Spark + Poskytovatel Lightning (Spark) diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b8e15dadae..0ceb3528ef 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -107,8 +107,10 @@ %1$d/3 Bestätigungen Einzahlung Warten + Einzahlungs-Tx + Einzahlungen Auszahlungsbetrag - Notausstieg + Übertragung zum Sparkonto forcieren Ausstieg abbrechen Die Finanzierungsadresse konnte nicht geprüft werden. Versuche es erneut. Spark kehrt in den vorherigen Zustand zurück. Wenn eine Zahlung die Gebührenfinanzierungsadresse des Ausstiegs erreicht hat, sendet Bitkit sie zurück auf dein Sparkonto. @@ -200,10 +202,11 @@ Die Gebühren sind höher als der Betrag, den du erhalten würdest. Ein Teil dieses Ausstiegs kann gerade nicht on-chain gelesen werden. Bitkit versucht es bis zu einer Woche lang erneut. {amount}, das die Spark-Betreiber on-chain verschoben haben, wartet auf deren Freigabe. Bitkit fragt bis zu einer Woche lang erneut nach. + Lightspark, Breez und Flashnet Anbieter Spark über Breez - Kein Limit - Dieses Guthaben liegt auf Spark, betrieben von Lightspark, Breez und Flashnet. Es ist sicher, solange mindestens einer von ihnen ehrlich handelt. Sie können den Zugang sperren, und ein Ausstieg ohne sie erfordert einen On-Chain-Exit. + kein Limit + Dein Ausgabenguthaben nutzt Spark, betrieben von Lightspark, Breez und Flashnet. Seine Sicherheit hängt davon ab, dass mindestens ein Betreiber ehrlich handelt. Betreiber können den Zugang sperren, und eine Auszahlung ohne ihre Mitwirkung erfordert, dass du einen On-Chain-Exit startest. Spending Balance Fund your <accent>spending balance</accent> Von Sparkonto übertragen @@ -643,6 +646,8 @@ Allgemein Sicherheit und Privatsphäre Fortgeschritten + Bitkit v{version} + Forcierte Übertragung zum Sparkonto läuft... Support Systemeinstellungen Sprache @@ -1811,8 +1816,8 @@ Kontostand wird aktualisiert… Gebührenfinanzierung nötig Nutzt Spark - Offline + Offline... Verbinden... Verbunden - Spark + Lightning-Anbieter (Spark) diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8e1d4df709..b0e146834e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -218,8 +218,10 @@ %1$d/3 επιβεβαιώσεις Κατάθεση Αναμονή + Συναλλαγή κατάθεσης + Καταθέσεις Ποσό εξόδου - Έξοδος έκτακτης ανάγκης + Αναγκαστική μεταφορά σε αποταμιεύσεις Ακύρωση εξόδου Δεν ήταν δυνατός ο έλεγχος της διεύθυνσης χρηματοδότησης. Δοκιμάστε ξανά. Το Spark επιστρέφει όπως ήταν. Αν μια πληρωμή έφτασε στη διεύθυνση χρηματοδότησης τελών της εξόδου, το Bitkit την επιστρέφει στις αποταμιεύσεις. @@ -311,10 +313,11 @@ Τα τέλη είναι υψηλότερα από όσα θα λαμβάνατε. Μέρος αυτής της εξόδου δεν μπορεί να διαβαστεί on-chain αυτή τη στιγμή. Το Bitkit προσπαθεί ξανά για έως μία εβδομάδα. {amount} που μετέφεραν on-chain οι διαχειριστές του Spark περιμένουν να τα αποδεσμεύσουν. Το Bitkit ζητά ξανά για έως μία εβδομάδα. + Lightspark, Breez και Flashnet Πάροχος Spark μέσω Breez - Χωρίς όριο - Αυτό το υπόλοιπο φυλάσσεται στο Spark, που λειτουργούν οι Lightspark, Breez και Flashnet. Είναι ασφαλές όσο τουλάχιστον ένας από αυτούς ενεργεί έντιμα. Μπορούν να αναστείλουν την πρόσβαση, και η έξοδος χωρίς αυτούς απαιτεί έξοδο on-chain. + χωρίς όριο + Το υπόλοιπο δαπανών σου χρησιμοποιεί το Spark, που λειτουργούν οι Lightspark, Breez και Flashnet. Η ασφάλειά του εξαρτάται από το να ενεργεί έντιμα τουλάχιστον ένας διαχειριστής. Οι διαχειριστές μπορούν να αναστείλουν την πρόσβαση, και η ανάληψη χωρίς τη συνεργασία τους απαιτεί να ξεκινήσεις έξοδο on-chain. Διαθέσιμα onchain Δαπάνες Οι αποταμιεύσεις σου δεν επαρκούν για αυτή τη μεταφορά και τα τέλη της. Δοκίμασε μικρότερο ποσό. @@ -776,6 +779,7 @@ Ασφάλεια Ασφάλεια και απόρρητο Ρυθμίσεις + Bitkit v{version} Αποτυχία ολοκλήρωσης πλήρους αντιγράφου ασφαλείας Δημιουργία αντιγράφου... Δημιουργήθηκε αντίγραφο @@ -796,6 +800,7 @@ Συγχρονισμός... Συγχρονισμένο Κόμβος Lightning + Αναγκαστική μεταφορά σε αποταμιεύσεις σε εξέλιξη... Κατάσταση εφαρμογής Κέντρο βοήθειας Διεύθυνση email @@ -1811,8 +1816,8 @@ Ενημέρωση υπολοίπου… Απαιτείται χρηματοδότηση τελών Χρήση Spark - Εκτός σύνδεσης + Εκτός σύνδεσης... Σύνδεση... Συνδεδεμένο - Spark + Πάροχος Lightning (Spark) diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index fba1595639..f381b4e111 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -224,8 +224,10 @@ %1$d/3 confirmaciones Depósito Esperar + Tx de depósito + Depósitos Importe a retirar - Salida de emergencia + Forzar transferencia a ahorros Cancelar salida No se pudo comprobar la dirección de financiación. Inténtalo de nuevo. Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. @@ -317,10 +319,11 @@ Las comisiones son mayores que lo que recibirías. Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. + Lightspark, Breez y Flashnet Proveedor Spark mediante Breez - Sin límite - Este saldo se guarda en Spark, gestionado por Lightspark, Breez y Flashnet. Está seguro mientras al menos uno de ellos actúe con honestidad. Pueden pausar el acceso, y salir sin ellos requiere una salida on-chain. + sin límite + Tu saldo de gastos usa Spark, gestionado por Lightspark, Breez y Flashnet. Su seguridad depende de que al menos un operador actúe con honestidad. Los operadores pueden pausar el acceso, y retirar sin su cooperación requiere que inicies una salida on-chain. Gastable en cadena Gasto Tus ahorros no cubren esta transferencia y sus comisiones. Prueba con una cantidad menor. @@ -794,6 +797,7 @@ Seguridad Seguridad y Privacidad Ajustes + Bitkit v{version} Falló al hacer una copia de seguridad completa Haciendo copia... Copia realizada @@ -814,6 +818,7 @@ Sincronizando... Sincronizado Nodo Lightning + Transferencia forzada a ahorros en curso... Estado de la App Centro de Ayuda Dirección Email @@ -1812,8 +1817,8 @@ Actualizando saldo… Financiación de comisiones necesaria Usando Spark - Sin conexión + Sin conexión... Conectando... Conectado - Spark + Proveedor Lightning (Spark) diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 92bbac2722..9541615431 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -166,8 +166,10 @@ %1$d/3 confirmaciones Depósito Esperar + Tx de depósito + Depósitos Importe a retirar - Salida de emergencia + Forzar transferencia a ahorros Cancelar salida No se pudo comprobar la dirección de financiación. Inténtalo de nuevo. Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. @@ -259,10 +261,11 @@ Las comisiones son mayores que lo que recibirías. Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. + Lightspark, Breez y Flashnet Proveedor Spark mediante Breez - Sin límite - Este saldo se guarda en Spark, operado por Lightspark, Breez y Flashnet. Está seguro mientras al menos uno de ellos actúe con honestidad. Pueden pausar el acceso, y salir sin ellos requiere una salida on-chain. + sin límite + Tu saldo de gastos usa Spark, operado por Lightspark, Breez y Flashnet. Su seguridad depende de que al menos un operador actúe con honestidad. Los operadores pueden pausar el acceso, y retirar sin su cooperación requiere que inicies una salida on-chain. Gastable onchain La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}. Máximo del Saldo de Gastos @@ -642,6 +645,8 @@ Avanzado Ajustes del sistema Idioma + Bitkit v{version} + Transferencia forzada a ahorros en curso... Soporte Legal Compartir @@ -1812,8 +1817,8 @@ Actualizando saldo… Financiación de comisiones necesaria Usando Spark - Sin conexión + Sin conexión... Conectando... Conectado - Spark + Proveedor Lightning (Spark) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8910f9e925..dfee70d427 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -106,8 +106,10 @@ %1$d/3 confirmations Dépôt Attendre + Tx de dépôt + Dépôts Montant à sortir - Sortie d\'urgence + Forcer le transfert vers l\'Épargne Annuler la sortie Impossible de vérifier l\'adresse de financement. Réessayez. Spark revient à son état précédent. Si un paiement a atteint l\'adresse de financement des frais de la sortie, Bitkit le renvoie vers l\'épargne. @@ -199,10 +201,11 @@ Les frais sont supérieurs à ce que vous recevriez. Une partie de cette sortie ne peut pas être lue on-chain pour le moment. Bitkit réessaie pendant une semaine au maximum. {amount} que les opérateurs Spark ont déplacé on-chain attend qu\'ils le libèrent. Bitkit le leur redemande pendant une semaine au maximum. + Lightspark, Breez et Flashnet Fournisseur Spark via Breez - Sans limite - Ce solde est détenu sur Spark, géré par Lightspark, Breez et Flashnet. Il est en sécurité tant qu’au moins l’un d’eux agit honnêtement. Ils peuvent suspendre l’accès, et en sortir sans eux nécessite une sortie on-chain. + sans limite + Votre solde de dépenses utilise Spark, géré par Lightspark, Breez et Flashnet. Sa sécurité repose sur au moins un opérateur agissant honnêtement. Les opérateurs peuvent suspendre l\'accès, et retirer sans leur coopération vous oblige à lancer une sortie on-chain. Solde Dépenses Financez votre <accent>solde Dépenses</accent> Transfert depuis l\'épargne @@ -645,6 +648,8 @@ Langue Sécurité et vie privée Avancé + Bitkit v{version} + Transfert forcé vers l\'Épargne en cours... Support Juridique Partager @@ -1812,8 +1817,8 @@ Mise à jour du solde… Financement des frais requis Via Spark - Hors ligne + Hors ligne... Connexion... Connecté - Spark + Fournisseur Lightning (Spark) diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 85f9d3a523..46c5cb4513 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -223,8 +223,10 @@ %1$d/3 conferme Deposito Attendi + Tx di deposito + Depositi Importo da far uscire - Uscita di emergenza + Trasferimento forzato ai Risparmi Annulla uscita Impossibile verificare l\'indirizzo di finanziamento. Riprova. Spark torna com\'era prima. Se un pagamento ha raggiunto l\'indirizzo di finanziamento delle commissioni dell\'uscita, Bitkit lo rimanda ai risparmi. @@ -316,10 +318,11 @@ Le commissioni sono più alte di quanto riceveresti. Al momento una parte di questa uscita non può essere letta on-chain. Bitkit riprova per un massimo di una settimana. {amount} che gli operatori Spark hanno spostato on-chain attende che lo sblocchino. Bitkit lo richiede di nuovo per un massimo di una settimana. + Lightspark, Breez e Flashnet Fornitore Spark tramite Breez - Nessun limite - Questo saldo è custodito su Spark, gestito da Lightspark, Breez e Flashnet. È al sicuro finché almeno uno di loro agisce onestamente. Possono sospendere l’accesso e uscire senza di loro richiede un’uscita on-chain. + nessun limite + Il tuo saldo di spesa usa Spark, gestito da Lightspark, Breez e Flashnet. La sua sicurezza dipende dal fatto che almeno un operatore agisca onestamente. Gli operatori possono sospendere l\'accesso, e prelevare senza la loro collaborazione richiede di avviare un\'uscita on-chain. Spendibile Onchain Spesa I tuoi risparmi non coprono questo trasferimento e le relative commissioni. Prova un importo minore. @@ -793,6 +796,7 @@ Sicurezza Sicurezza e Privacy Impostazioni + Bitkit v{version} Impossibile completare un backup completo Backup in esecuzione... Backup eseguito @@ -813,6 +817,7 @@ Sincronizzazione... Sincronizzato Nodo Lightning + Trasferimento forzato ai risparmi in corso... Stato dell\'app Centro assistenza Indirizzo e-mail @@ -1812,8 +1817,8 @@ Aggiornamento del saldo… Finanziamento delle commissioni necessario Tramite Spark - Offline + Offline... In connessione... Connesso - Spark + Fornitore Lightning (Spark) diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 93f1159a8e..8e2597fa20 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -222,8 +222,10 @@ %1$d/3 bevestigingen Storting Wachten + Stortings-tx + Stortingen Bedrag voor exit - Noodexit + Overboeking naar spaargeld forceren Exit annuleren Kon het financieringsadres niet controleren. Probeer opnieuw. Spark keert terug naar hoe het was. Als er een betaling op het financieringsadres voor de kosten van de exit is aangekomen, stuurt Bitkit die terug naar spaargeld. @@ -315,10 +317,11 @@ De kosten zijn hoger dan wat je zou ontvangen. Een deel van deze exit kan nu niet on-chain worden gelezen. Bitkit probeert het tot een week lang opnieuw. {amount} dat de Spark-beheerders on-chain hebben verplaatst, wacht tot zij het vrijgeven. Bitkit vraagt het tot een week lang opnieuw. + Lightspark, Breez en Flashnet Aanbieder Spark via Breez - Geen limiet - Dit saldo staat op Spark, beheerd door Lightspark, Breez en Flashnet. Het is veilig zolang ten minste één van hen eerlijk handelt. Zij kunnen de toegang pauzeren, en vertrekken zonder hen vereist een on-chain exit. + geen limiet + Je bestedingssaldo gebruikt Spark, beheerd door Lightspark, Breez en Flashnet. De veiligheid hangt ervan af dat ten minste één operator eerlijk handelt. Operators kunnen de toegang pauzeren, en opnemen zonder hun medewerking vereist dat je een on-chain exit start. Besteedbaar onchain Bestedingssaldo Uw spaargeld is niet voldoende voor deze overboeking en de vergoedingen. Probeer een kleiner bedrag. @@ -791,6 +794,7 @@ Veiligheid Beveiliging en privacy Instellingen + Bitkit v{version} Volledige backup niet voltooid Back-up maken... Geback-upt @@ -811,6 +815,7 @@ Synchroniseren... Gesynchroniseerd Lightning Node + Geforceerde overboeking naar spaargeld bezig... App-status Helpcentrum E-mailadres @@ -1811,8 +1816,8 @@ Saldo bijwerken… Kostenfinanciering nodig Via Spark - Offline + Offline... Verbinden... Verbonden - Spark + Lightning-provider (Spark) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3b9d3bad34..71bd841c43 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -108,8 +108,10 @@ %1$d/3 potwierdzeń Wpłata Czekaj + Tx wpłaty + Wpłaty Kwota do wyjścia - Wyjście awaryjne + Wymuś transfer na oszczędności Anuluj wyjście Nie udało się sprawdzić adresu finansowania. Spróbuj ponownie. Spark wraca do poprzedniego stanu. Jeśli płatność dotarła na adres finansowania opłat wyjścia, Bitkit odeśle ją do Oszczędności. @@ -201,10 +203,11 @@ Opłaty są wyższe niż kwota, którą otrzymasz. Części tego wyjścia nie można teraz odczytać on-chain. Bitkit będzie próbować ponownie przez maksymalnie tydzień. {amount} przeniesione on-chain przez operatorów Spark czeka, aż je zwolnią. Bitkit będzie pytać ponownie przez maksymalnie tydzień. + Lightspark, Breez i Flashnet Dostawca Spark przez Breez - Bez limitu - To saldo jest przechowywane na Spark, prowadzonym przez Lightspark, Breez i Flashnet. Jest bezpieczne, dopóki co najmniej jeden z nich działa uczciwie. Mogą wstrzymać dostęp, a wyjście bez nich wymaga wyjścia on-chain. + bez limitu + Twoje saldo wydatków korzysta ze Spark, prowadzonego przez Lightspark, Breez i Flashnet. Jego bezpieczeństwo zależy od tego, czy co najmniej jeden operator działa uczciwie. Operatorzy mogą wstrzymać dostęp, a wypłata bez ich współpracy wymaga rozpoczęcia wyjścia on-chain. Saldo wydatków Zasil swoje <accent>saldo wydatków</accent> Prześlij z Oszczędności @@ -646,6 +649,8 @@ Ogólne Bezpieczeństwo i prywatność Zaawansowane + Bitkit v{version} + Trwa wymuszony transfer na oszczędności... Wsparcie Prawne Udostępnij @@ -1813,8 +1818,8 @@ Aktualizowanie salda… Potrzebne finansowanie opłat Przez Spark - Offline + Offline... Łączenie... Połączono - Spark + Dostawca Lightning (Spark) diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ea6343c8c3..df20227eb3 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -226,8 +226,10 @@ %1$d/3 confirmações Depósito Esperar + Tx de depósito + Depósitos Valor a retirar - Saída de emergência + Forçar Transferência Para Poupança Cancelar saída Não foi possível verificar o endereço de financiamento. Tente novamente. A Spark volta a ser como era. Se um pagamento chegou ao endereço de financiamento das taxas da saída, a Bitkit o devolve para a poupança. @@ -319,10 +321,11 @@ As taxas são maiores do que o que você receberia. Parte desta saída não pode ser lida on-chain agora. A Bitkit tenta de novo por até uma semana. {amount} que os operadores da Spark moveram on-chain aguarda a liberação por eles. A Bitkit pede de novo por até uma semana. + Lightspark, Breez e Flashnet Provedor Spark via Breez - Sem limite - Este saldo fica na Spark, operada pela Lightspark, Breez e Flashnet. Ele está seguro enquanto pelo menos um deles agir com honestidade. Eles podem pausar o acesso, e sair sem eles exige uma saída on-chain. + sem limite + Seu saldo de gastos usa a Spark, operada pela Lightspark, Breez e Flashnet. Sua segurança depende de pelo menos um operador agir com honestidade. Os operadores podem pausar o acesso, e sacar sem a cooperação deles exige que você inicie uma saída on-chain. Disponível Onchain Gastos Sua poupança não cobre esta transferência e suas taxas. Tente um valor menor. @@ -798,6 +801,7 @@ Segurança Segurança e Privacidade Ajustes + Bitkit v{version} Falha ao concluir backup Fazendo o backup... Backup Feito @@ -818,6 +822,7 @@ Sincronizando... Sincronizado Nó Lightning + Transferência forçada para a poupança em andamento... Status do Aplicativo Central de Ajuda Endereço de e-mail @@ -1812,8 +1817,8 @@ Atualizando saldo… Financiamento das taxas necessário Usando o Spark - Offline + Offline... Conectando... Conectado - Spark + Provedor Lightning (Spark) diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 965d10b791..01732fb7ef 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -103,8 +103,10 @@ %1$d/3 confirmações Depósito Esperar + Tx de depósito + Depósitos Montante a retirar - Saída de emergência + Forçar Transferência Para Poupança Cancelar saída Não foi possível verificar o endereço de financiamento. Tente novamente. A Spark volta ao estado anterior. Se um pagamento chegou ao endereço de financiamento das taxas da saída, a Bitkit devolve-o à poupança. @@ -196,10 +198,11 @@ As taxas são mais altas do que o que receberia. Parte desta saída não pode ser lida on-chain neste momento. A Bitkit tenta novamente durante até uma semana. {amount} que os operadores da Spark moveram on-chain aguarda que o libertem. A Bitkit volta a pedir durante até uma semana. + Lightspark, Breez e Flashnet Fornecedor Spark via Breez - Sem limite - Este saldo é mantido na Spark, operada pela Lightspark, Breez e Flashnet. Está seguro enquanto pelo menos um deles agir com honestidade. Podem suspender o acesso, e sair sem eles exige uma saída on-chain. + sem limite + O seu saldo de gastos usa a Spark, operada pela Lightspark, Breez e Flashnet. A sua segurança depende de pelo menos um operador agir com honestidade. Os operadores podem suspender o acesso, e levantar sem a cooperação deles exige que inicie uma saída on-chain. Saldo de Gastos Transfira para seu <accent>saldo de gastos</accent> Transferir do Saldo de Poupança @@ -624,6 +627,8 @@ Geral Segurança e Privacidade Avançado + Bitkit v{version} + Transferência forçada para a poupança em curso... Suporte Legal Compartilhar @@ -1812,8 +1817,8 @@ A atualizar o saldo… Financiamento das taxas necessário Usando o Spark - Offline + Offline... Conectando... Conectado - Spark + Fornecedor Lightning (Spark) diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e8d6f7099d..730c1e2a1b 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -234,8 +234,10 @@ %1$d/3 подтверждений Депозит Ждать + Транзакция депозита + Депозиты Сумма выхода - Экстренный выход + Принудительный перевод в сбережения Отменить выход Не удалось проверить адрес пополнения. Попробуйте ещё раз. Spark вернётся в прежнее состояние. Если на адрес для оплаты комиссий выхода пришёл платёж, Bitkit вернёт его в сбережения. @@ -327,10 +329,11 @@ Комиссии больше, чем сумма, которую вы получите. Часть этого выхода сейчас не удаётся прочитать в блокчейне. Bitkit будет пробовать снова в течение недели. {amount}, которые операторы Spark перевели ончейн, ждут, пока операторы их выдадут. Bitkit будет запрашивать снова в течение недели. + Lightspark, Breez и Flashnet Провайдер Spark через Breez - Без ограничений - Этот баланс хранится в Spark, которым управляют Lightspark, Breez и Flashnet. Он в безопасности, пока хотя бы один из них действует честно. Они могут приостановить доступ, а выход без них требует ончейн-вывода. + без ограничений + Ваш баланс расходов использует Spark, которым управляют Lightspark, Breez и Flashnet. Его безопасность зависит от того, что хотя бы один оператор действует честно. Операторы могут приостановить доступ, а чтобы вывести средства без их участия, вам придётся запустить ончейн-вывод. Доступно Onchain Расходы Ваших сбережений не хватает на этот перевод и его комиссии. Попробуйте меньшую сумму. @@ -810,6 +813,7 @@ Безопасность Безопасность и Конфиденциальность Настройки + Bitkit v{version} Не удалось выполнить полное резервное копирование Резервное копирование... Скопировано @@ -830,6 +834,7 @@ Синхронизация... Синхронизировано Лайтнинг-нода + Идёт принудительный перевод в сбережения... Статус Приложения Центр Помощи Электронная Почта @@ -1827,8 +1832,8 @@ Обновление баланса… Нужны средства на комиссии Через Spark - Не в сети + Не в сети... Подключение... Подключено - Spark + Провайдер Lightning (Spark) From 44d854efae873e86751614c3436240f8208bd22c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 02:17:18 +0100 Subject: [PATCH 06/23] fix: match spark bar, node status and backup date to figma Verified: just format, just compile, just test, just lint --- app/src/main/java/to/bitkit/ext/DateTime.kt | 12 ++++++ .../bitkit/ui/components/LightningChannel.kt | 18 ++++++++- .../ui/settings/appStatus/AppStatusScreen.kt | 6 +-- .../settings/appStatus/AppStatusViewModel.kt | 5 ++- .../lightning/LightningConnectionsScreen.kt | 1 + .../settings/lightning/SparkDetailScreen.kt | 1 + .../java/to/bitkit/ext/BackupTimestampTest.kt | 39 +++++++++++++++++++ .../ui/components/LightningChannelTest.kt | 22 +++++++++++ .../appStatus/AppStatusViewModelTest.kt | 9 +++-- 9 files changed, 104 insertions(+), 9 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt create mode 100644 app/src/test/java/to/bitkit/ui/components/LightningChannelTest.kt diff --git a/app/src/main/java/to/bitkit/ext/DateTime.kt b/app/src/main/java/to/bitkit/ext/DateTime.kt index e2f0e0fc85..5e105fe506 100644 --- a/app/src/main/java/to/bitkit/ext/DateTime.kt +++ b/app/src/main/java/to/bitkit/ext/DateTime.kt @@ -29,6 +29,7 @@ import kotlin.time.Clock import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.ExperimentalTime +import android.text.format.DateFormat as AndroidDateFormat import java.text.DateFormat as JavaDateFormat import java.time.LocalDate as JavaLocalDate import kotlin.time.Instant as KInstant @@ -76,6 +77,14 @@ fun Long.toLocalizedTimestamp(locale: Locale = Locale.getDefault()): String { return formatter.format(date) } +fun Long.toBackupTimestamp( + locale: Locale = Locale.getDefault(), + zone: ZoneId = ZoneId.systemDefault(), +): String { + val pattern = AndroidDateFormat.getBestDateTimePattern(locale, DatePattern.BACKUP_TIME_SKELETON) + return Instant.ofEpochMilli(this).formatted(pattern, locale, zone) +} + @OptIn(ExperimentalTime::class) fun Long.toRelativeTimeString( locale: Locale = Locale.getDefault(), @@ -261,6 +270,9 @@ enum class UiDateStyle { object DatePattern { const val DATE_TIME = "dd/MM/yyyy, HH:mm" const val CHANNEL_DETAILS = "MMM d, yyyy, HH:mm" + + /** Skeleton for a backup's time: short month, day, year and 24-hour time, ordered and joined per locale. */ + const val BACKUP_TIME_SKELETON = "MMMdyyyyHHmm" const val LOG_FILE = "yyyy-MM-dd_HH-mm-ss" const val LOG_LINE = "yyyy-MM-dd HH:mm:ss.SSS" diff --git a/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt index 43cab1d8d7..7025f25c9f 100644 --- a/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt +++ b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt @@ -41,6 +41,7 @@ fun LightningChannel( showLabels: Boolean = false, showReceiving: Boolean = true, receivingUnlimited: Boolean = false, + isSpark: Boolean = false, ) { val isEmptySpendingBar = (!showReceiving || receivingUnlimited) && localBalance == 0L val spendingColor = if (status == ChannelStatusUi.CLOSED || isEmptySpendingBar) Colors.Gray5 else Colors.Purple50 @@ -52,7 +53,7 @@ fun LightningChannel( } val receivingAvailableColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray3 else Colors.White - val spendingAvailableFraction = if (capacity > 0) localBalance.toFloat() / capacity else 0f + val spendingAvailableFraction = spendingFillFraction(capacity, localBalance, isSpark) val receivingAvailableFraction = when { receivingUnlimited -> 1f capacity > 0 -> remoteBalance.toFloat() / capacity @@ -153,6 +154,20 @@ fun LightningChannel( } } +/** + * The share of the spending track the balance fills. A channel fills it by its local balance over its capacity; Spark + * has no capacity, so a held balance fills half of it, as in the design. + */ +internal fun spendingFillFraction(capacity: Long, localBalance: Long, isSpark: Boolean = false): Float = when { + localBalance <= 0L -> 0f + isSpark -> SPARK_SPENDING_FILL + capacity > 0L -> localBalance.toFloat() / capacity + else -> 0f +} + +/** The share of the spending track a Spark balance fills, as the design's Spark bar draws it. */ +private const val SPARK_SPENDING_FILL = 0.5f + private val SpendingHalfShape = RoundedCornerShape(topStart = 8.dp, bottomStart = 8.dp) private val FullBarShape = RoundedCornerShape(8.dp) @@ -228,6 +243,7 @@ private fun PreviewReceivingUnlimited() { remoteBalance = 0, status = ChannelStatusUi.OPEN, receivingUnlimited = true, + isSpark = true, modifier = Modifier.padding(16.dp) ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index dd502990a3..cb5b2cb1b9 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -32,7 +32,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import to.bitkit.R import to.bitkit.ext.startActivityAppSettings -import to.bitkit.ext.toLocalizedTimestamp +import to.bitkit.ext.toBackupTimestamp import to.bitkit.models.HealthState import to.bitkit.repositories.AppHealthState import to.bitkit.ui.Routes @@ -338,8 +338,8 @@ private fun Preview() { spark = HealthState.READY, backups = HealthState.READY, ), - backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toLocalizedTimestamp(), - nodeSubtitle = "Running", + backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toBackupTimestamp(), + nodeSubtitle = "Synced", exitStep = ExitStep.RUNNING, appVersion = "3.2.0 (182)", ), diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index 255381e052..f8a0bc109d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -14,7 +14,7 @@ import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.data.CacheStore import to.bitkit.env.Env -import to.bitkit.ext.toLocalizedTimestamp +import to.bitkit.ext.toBackupTimestamp import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus import to.bitkit.models.HealthState @@ -54,6 +54,7 @@ class AppStatusViewModel @Inject constructor( backupSubtitle = computeBackupSubtitle(healthState.backups, backupStatuses), nodeSubtitle = when (healthState.node) { HealthState.ERROR -> context.getString(R.string.settings__status__lightning_node__error) + HealthState.READY -> context.getString(R.string.settings__status__lightning_node__ready) else -> lightningState.nodeLifecycleState.uiText(context) }, exitStep = exitState.record.exitStep(exitState.fundingState), @@ -75,7 +76,7 @@ class AppStatusViewModel @Inject constructor( when (val maxSyncTime = syncTimes.max()) { 0L -> context.getString(R.string.settings__status__backup__ready) - else -> runCatching { maxSyncTime.toLocalizedTimestamp() }.getOrDefault( + else -> runCatching { maxSyncTime.toBackupTimestamp() }.getOrDefault( context.getString(R.string.settings__status__backup__ready) ) } 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 31b3fe503c..b19afb57c4 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 @@ -447,6 +447,7 @@ private fun SparkItem( status = ChannelStatusUi.OPEN, showReceiving = spark.isReceiving, receivingUnlimited = spark.isReceiving, + isSpark = true, ) VerticalSpacer(16.dp) HorizontalDivider() diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 68684e4c7e..a45dcfdd73 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -120,6 +120,7 @@ private fun Content( status = ChannelStatusUi.OPEN, showReceiving = spark.isReceiving, receivingUnlimited = spark.isReceiving, + isSpark = true, ) VerticalSpacer(16.dp) HorizontalDivider() diff --git a/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt new file mode 100644 index 0000000000..3f28cc680a --- /dev/null +++ b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt @@ -0,0 +1,39 @@ +package to.bitkit.ext + +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.time.Instant +import java.time.ZoneId +import java.util.Locale +import kotlin.test.assertEquals + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class BackupTimestampTest { + private val time = Instant.parse("2023-01-02T11:45:00Z").toEpochMilli() + private val utc = ZoneId.of("UTC") + + @Test + fun `toBackupTimestamp follows the US pattern`() { + assertEquals("Jan 2, 2023, 11:45", time.toBackupTimestamp(Locale.US, utc)) + } + + @Test + fun `toBackupTimestamp follows the UK pattern`() { + assertEquals("2 Jan 2023, 11:45", time.toBackupTimestamp(Locale.UK, utc)) + } + + @Test + fun `toBackupTimestamp follows the German pattern with a localized month`() { + assertEquals("2. Jan. 2023, 11:45", time.toBackupTimestamp(Locale.GERMANY, utc)) + } + + @Test + fun `toBackupTimestamp keeps a 24-hour time`() { + val evening = Instant.parse("2023-01-02T23:45:00Z").toEpochMilli() + + assertEquals("Jan 2, 2023, 23:45", evening.toBackupTimestamp(Locale.US, utc)) + } +} diff --git a/app/src/test/java/to/bitkit/ui/components/LightningChannelTest.kt b/app/src/test/java/to/bitkit/ui/components/LightningChannelTest.kt new file mode 100644 index 0000000000..a96fb3c025 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/components/LightningChannelTest.kt @@ -0,0 +1,22 @@ +package to.bitkit.ui.components + +import org.junit.Test +import kotlin.test.assertEquals + +class LightningChannelTest { + @Test + fun `channel fills its spending track by local balance over capacity`() { + assertEquals(0.25f, spendingFillFraction(capacity = 400_000, localBalance = 100_000)) + } + + @Test + fun `spark balance fills half its spending track`() { + assertEquals(0.5f, spendingFillFraction(capacity = 580_000, localBalance = 580_000, isSpark = true)) + } + + @Test + fun `empty balance leaves the spending track unfilled`() { + assertEquals(0f, spendingFillFraction(capacity = 0, localBalance = 0, isSpark = true)) + assertEquals(0f, spendingFillFraction(capacity = 500_000, localBalance = 0)) + } +} diff --git a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index 05f5ff6d5b..677c42e648 100644 --- a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt @@ -47,6 +47,7 @@ class AppStatusViewModelTest : BaseUnitTest() { whenever(context.getString(R.string.other__node_running)).thenReturn("Running") whenever(context.getString(R.string.other__node_stopping)).thenReturn("Stopping") whenever(context.getString(R.string.other__node_initializing)).thenReturn("Setting up wallet…") + whenever(context.getString(R.string.settings__status__lightning_node__ready)).thenReturn("Synced") whenever(healthRepo.healthState).thenReturn(MutableStateFlow(AppHealthState())) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(cacheStore.backupStatuses).thenReturn(flowOf(emptyMap())) @@ -151,25 +152,27 @@ class AppStatusViewModelTest : BaseUnitTest() { } @Test - fun `node subtitle shows NodeLifecycleState uiText`() = test { + fun `node subtitle shows synced when the node is healthy`() = test { val lightningState = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + whenever(healthRepo.healthState).thenReturn(MutableStateFlow(AppHealthState(node = HealthState.READY))) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(lightningState)) sut = createSut() sut.uiState.test { val state = awaitItem() - assertEquals("Running", state.nodeSubtitle) + assertEquals("Synced", state.nodeSubtitle) cancelAndIgnoreRemainingEvents() } } @Test - fun `node subtitle updates when NodeLifecycleState changes`() = test { + fun `node subtitle shows NodeLifecycleState uiText while the node is pending`() = test { val initialState = LightningState(nodeLifecycleState = NodeLifecycleState.Starting) val lightningStateFlow = MutableStateFlow(initialState) + whenever(healthRepo.healthState).thenReturn(MutableStateFlow(AppHealthState(node = HealthState.PENDING))) whenever(lightningRepo.lightningState).thenReturn(lightningStateFlow) sut = createSut() From 16be32ee914140e53be8f01c4c5a77a8b4e32de7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 02:35:52 +0100 Subject: [PATCH 07/23] fix: follow the device clock format for the backup time Verified: just format, just compile, just test, just lint --- app/src/main/java/to/bitkit/ext/DateTime.kt | 8 +++++--- .../ui/settings/appStatus/AppStatusScreen.kt | 2 +- .../settings/appStatus/AppStatusViewModel.kt | 7 ++++--- .../java/to/bitkit/ext/BackupTimestampTest.kt | 20 ++++++++++++++----- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/DateTime.kt b/app/src/main/java/to/bitkit/ext/DateTime.kt index 5e105fe506..ec0c98eaab 100644 --- a/app/src/main/java/to/bitkit/ext/DateTime.kt +++ b/app/src/main/java/to/bitkit/ext/DateTime.kt @@ -78,10 +78,12 @@ fun Long.toLocalizedTimestamp(locale: Locale = Locale.getDefault()): String { } fun Long.toBackupTimestamp( + is24Hour: Boolean, locale: Locale = Locale.getDefault(), zone: ZoneId = ZoneId.systemDefault(), ): String { - val pattern = AndroidDateFormat.getBestDateTimePattern(locale, DatePattern.BACKUP_TIME_SKELETON) + val skeleton = DatePattern.BACKUP_DATE_SKELETON + if (is24Hour) "HHmm" else "hmm" + val pattern = AndroidDateFormat.getBestDateTimePattern(locale, skeleton) return Instant.ofEpochMilli(this).formatted(pattern, locale, zone) } @@ -271,8 +273,8 @@ object DatePattern { const val DATE_TIME = "dd/MM/yyyy, HH:mm" const val CHANNEL_DETAILS = "MMM d, yyyy, HH:mm" - /** Skeleton for a backup's time: short month, day, year and 24-hour time, ordered and joined per locale. */ - const val BACKUP_TIME_SKELETON = "MMMdyyyyHHmm" + /** Skeleton for a backup's date: short month, day and year, ordered and joined per locale. */ + const val BACKUP_DATE_SKELETON = "MMMdyyyy" const val LOG_FILE = "yyyy-MM-dd_HH-mm-ss" const val LOG_LINE = "yyyy-MM-dd HH:mm:ss.SSS" diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index cb5b2cb1b9..61f0075210 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -338,7 +338,7 @@ private fun Preview() { spark = HealthState.READY, backups = HealthState.READY, ), - backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toBackupTimestamp(), + backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toBackupTimestamp(is24Hour = true), nodeSubtitle = "Synced", exitStep = ExitStep.RUNNING, appVersion = "3.2.0 (182)", diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index f8a0bc109d..3c00b05a2e 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -25,6 +25,7 @@ import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import javax.inject.Inject +import android.text.format.DateFormat as AndroidDateFormat @HiltViewModel class AppStatusViewModel @Inject constructor( @@ -76,9 +77,9 @@ class AppStatusViewModel @Inject constructor( when (val maxSyncTime = syncTimes.max()) { 0L -> context.getString(R.string.settings__status__backup__ready) - else -> runCatching { maxSyncTime.toBackupTimestamp() }.getOrDefault( - context.getString(R.string.settings__status__backup__ready) - ) + else -> runCatching { + maxSyncTime.toBackupTimestamp(is24Hour = AndroidDateFormat.is24HourFormat(context)) + }.getOrDefault(context.getString(R.string.settings__status__backup__ready)) } } } diff --git a/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt index 3f28cc680a..6da14d644d 100644 --- a/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt +++ b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt @@ -17,23 +17,33 @@ class BackupTimestampTest { @Test fun `toBackupTimestamp follows the US pattern`() { - assertEquals("Jan 2, 2023, 11:45", time.toBackupTimestamp(Locale.US, utc)) + assertEquals("Jan 2, 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.US, utc)) } @Test fun `toBackupTimestamp follows the UK pattern`() { - assertEquals("2 Jan 2023, 11:45", time.toBackupTimestamp(Locale.UK, utc)) + assertEquals("2 Jan 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.UK, utc)) } @Test fun `toBackupTimestamp follows the German pattern with a localized month`() { - assertEquals("2. Jan. 2023, 11:45", time.toBackupTimestamp(Locale.GERMANY, utc)) + assertEquals("2. Jan. 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.GERMANY, utc)) } @Test - fun `toBackupTimestamp keeps a 24-hour time`() { + fun `toBackupTimestamp follows a 24-hour device setting`() { val evening = Instant.parse("2023-01-02T23:45:00Z").toEpochMilli() - assertEquals("Jan 2, 2023, 23:45", evening.toBackupTimestamp(Locale.US, utc)) + assertEquals("Jan 2, 2023, 23:45", evening.toBackupTimestamp(is24Hour = true, Locale.US, utc)) + } + + @Test + fun `toBackupTimestamp follows a 12-hour device setting`() { + val evening = Instant.parse("2023-01-02T23:45:00Z").toEpochMilli() + + val text = evening.toBackupTimestamp(is24Hour = false, Locale.US, utc) + + // CLDR versions differ in the space before PM. + assertEquals("Jan 2, 2023, 11:45 PM", text.replace('\u202F', ' ').replace('\u00A0', ' ')) } } From 7409d139f968eff5253851fd60f6f5361a5e4205 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 05:14:40 +0100 Subject: [PATCH 08/23] fix: read the backup date as date at time Verified: just format, compile, test, lint --- app/src/main/java/to/bitkit/ext/DateTime.kt | 12 +++++++++--- .../settings/appStatus/AppStatusViewModel.kt | 5 ++++- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../java/to/bitkit/ext/BackupTimestampTest.kt | 19 +++++++++++++------ 19 files changed, 42 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/DateTime.kt b/app/src/main/java/to/bitkit/ext/DateTime.kt index ec0c98eaab..ac8e7862f4 100644 --- a/app/src/main/java/to/bitkit/ext/DateTime.kt +++ b/app/src/main/java/to/bitkit/ext/DateTime.kt @@ -79,12 +79,15 @@ fun Long.toLocalizedTimestamp(locale: Locale = Locale.getDefault()): String { fun Long.toBackupTimestamp( is24Hour: Boolean, + template: String = DatePattern.BACKUP_DATE_TEMPLATE, locale: Locale = Locale.getDefault(), zone: ZoneId = ZoneId.systemDefault(), ): String { - val skeleton = DatePattern.BACKUP_DATE_SKELETON + if (is24Hour) "HHmm" else "hmm" - val pattern = AndroidDateFormat.getBestDateTimePattern(locale, skeleton) - return Instant.ofEpochMilli(this).formatted(pattern, locale, zone) + val instant = Instant.ofEpochMilli(this) + val datePattern = AndroidDateFormat.getBestDateTimePattern(locale, DatePattern.BACKUP_DATE_SKELETON) + val date = instant.formatted(datePattern, locale, zone) + val timePattern = AndroidDateFormat.getBestDateTimePattern(locale, if (is24Hour) "HHmm" else "hmm") + return template.replace("{date}", date).replace("{time}", instant.formatted(timePattern, locale, zone)) } @OptIn(ExperimentalTime::class) @@ -275,6 +278,9 @@ object DatePattern { /** Skeleton for a backup's date: short month, day and year, ordered and joined per locale. */ const val BACKUP_DATE_SKELETON = "MMMdyyyy" + + /** How the latest backup reads in English: its date, then "at" and its time. */ + const val BACKUP_DATE_TEMPLATE = "{date} at {time}" const val LOG_FILE = "yyyy-MM-dd_HH-mm-ss" const val LOG_LINE = "yyyy-MM-dd HH:mm:ss.SSS" diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index 3c00b05a2e..d2b0f58b7d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -78,7 +78,10 @@ class AppStatusViewModel @Inject constructor( when (val maxSyncTime = syncTimes.max()) { 0L -> context.getString(R.string.settings__status__backup__ready) else -> runCatching { - maxSyncTime.toBackupTimestamp(is24Hour = AndroidDateFormat.is24HourFormat(context)) + maxSyncTime.toBackupTimestamp( + is24Hour = AndroidDateFormat.is24HourFormat(context), + template = context.getString(R.string.settings__status__backup__date), + ) }.getOrDefault(context.getString(R.string.settings__status__backup__ready)) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c2ac231ece..bc34e84fe1 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -780,6 +780,7 @@ الأمان والخصوصية الإعدادات Bitkit v{version} + {date} في {time} فشل إكمال النسخة الاحتياطية الكاملة جارٍ النسخ الاحتياطي... تم النسخ الاحتياطي 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 8651e034f0..038bf6efdf 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -801,6 +801,7 @@ Seguridad y Privacidad Ajustes Bitkit v{version} + {date} a las {time} No se ha podido completar una copia de seguridad completa Respaldando... Copia de seguridad diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 187eb77f7c..ffe6bd2777 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -795,6 +795,7 @@ Seguretat i privacitat Configuracions Bitkit v{version} + {date} a les {time} No s\'ha pogut completar una còpia de seguretat completa Fent còpia de seguretat... Còpia de seguretat feta diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 58d5705d7f..35e3949f74 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -800,6 +800,7 @@ Bezpečnost a soukromí Nastavení Bitkit v{version} + {date} v {time} Selhalo dokončení úplné zálohy Zálohování... Zálohováno diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 0ceb3528ef..e27e61dcb9 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -783,6 +783,7 @@ Vollständiges Backup Abgeschlossen In Bearbeitung... + {date} um {time} Fehlgeschlagen Zahlungen Netzwerke diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index b0e146834e..ffe653d6f3 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -780,6 +780,7 @@ Ασφάλεια και απόρρητο Ρυθμίσεις Bitkit v{version} + {date} στις {time} Αποτυχία ολοκλήρωσης πλήρους αντιγράφου ασφαλείας Δημιουργία αντιγράφου... Δημιουργήθηκε αντίγραφο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index f381b4e111..13e44f40d0 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -798,6 +798,7 @@ Seguridad y Privacidad Ajustes Bitkit v{version} + {date} a las {time} Falló al hacer una copia de seguridad completa Haciendo copia... Copia realizada diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9541615431..7a17aa8d92 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -780,6 +780,7 @@ Haciendo copia de seguridad... Copia de seguridad realizada Último Backup de Datos Completo + {date} a las {time} Falló al hacer una copia de seguridad completa Pagos Redes diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index dfee70d427..4dcd01dbbf 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -780,6 +780,7 @@ Dernière sauvegarde complète Sauvegardé Sauvegarde... + {date} à {time} Échec de la sauvegarde Paiements Réseaux diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 46c5cb4513..4e3df6c6b0 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -797,6 +797,7 @@ Sicurezza e Privacy Impostazioni Bitkit v{version} + {date} alle {time} Impossibile completare un backup completo Backup in esecuzione... Backup eseguito diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 8e2597fa20..6e1d08e334 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -795,6 +795,7 @@ Beveiliging en privacy Instellingen Bitkit v{version} + {date} om {time} Volledige backup niet voltooid Back-up maken... Geback-upt diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 71bd841c43..ded39cf783 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -786,6 +786,7 @@ Ostatnia kopia zapasowa Zapisano Zapisywanie... + {date} o {time} Nie udało się wykonać kopii zapasowej Płatności Sieci diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index df20227eb3..5aea13a244 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -802,6 +802,7 @@ Segurança e Privacidade Ajustes Bitkit v{version} + {date} às {time} Falha ao concluir backup Fazendo o backup... Backup Feito diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 01732fb7ef..07a2dd9054 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -746,6 +746,7 @@ Último Backup Completo Backup Feito Fazendo o backup... + {date} às {time} Falha ao concluir backup Pagamentos Redes diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 730c1e2a1b..c3cea1139b 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -814,6 +814,7 @@ Безопасность и Конфиденциальность Настройки Bitkit v{version} + {date} в {time} Не удалось выполнить полное резервное копирование Резервное копирование... Скопировано diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0471ca1982..c59efe9096 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1164,6 +1164,7 @@ Security Settings Bitkit v{version} + {date} at {time} Failed to complete a full backup Backing up... Backed up diff --git a/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt index 6da14d644d..e7d28659e6 100644 --- a/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt +++ b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt @@ -17,33 +17,40 @@ class BackupTimestampTest { @Test fun `toBackupTimestamp follows the US pattern`() { - assertEquals("Jan 2, 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.US, utc)) + assertEquals("Jan 2, 2023 at 11:45", time.toBackupTimestamp(is24Hour = true, locale = Locale.US, zone = utc)) } @Test fun `toBackupTimestamp follows the UK pattern`() { - assertEquals("2 Jan 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.UK, utc)) + assertEquals("2 Jan 2023 at 11:45", time.toBackupTimestamp(is24Hour = true, locale = Locale.UK, zone = utc)) } @Test fun `toBackupTimestamp follows the German pattern with a localized month`() { - assertEquals("2. Jan. 2023, 11:45", time.toBackupTimestamp(is24Hour = true, Locale.GERMANY, utc)) + val text = time.toBackupTimestamp( + is24Hour = true, + template = "{date} um {time}", + locale = Locale.GERMANY, + zone = utc, + ) + + assertEquals("2. Jan. 2023 um 11:45", text) } @Test fun `toBackupTimestamp follows a 24-hour device setting`() { val evening = Instant.parse("2023-01-02T23:45:00Z").toEpochMilli() - assertEquals("Jan 2, 2023, 23:45", evening.toBackupTimestamp(is24Hour = true, Locale.US, utc)) + assertEquals("Jan 2, 2023 at 23:45", evening.toBackupTimestamp(is24Hour = true, locale = Locale.US, zone = utc)) } @Test fun `toBackupTimestamp follows a 12-hour device setting`() { val evening = Instant.parse("2023-01-02T23:45:00Z").toEpochMilli() - val text = evening.toBackupTimestamp(is24Hour = false, Locale.US, utc) + val text = evening.toBackupTimestamp(is24Hour = false, locale = Locale.US, zone = utc) // CLDR versions differ in the space before PM. - assertEquals("Jan 2, 2023, 11:45 PM", text.replace('\u202F', ' ').replace('\u00A0', ' ')) + assertEquals("Jan 2, 2023 at 11:45 PM", text.replace('\u202F', ' ').replace('\u00A0', ' ')) } } From f8367760c4e0037124f9a56e9e48a3f5f3b02d92 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 11:28:06 +0100 Subject: [PATCH 09/23] fix: show a running force transfer on the spark connection screen The status reads as App Status's Spark row while an exit runs, in yellow, instead of Connection open. Verified: just format, compile, test, lint --- .../settings/lightning/SparkDetailScreen.kt | 16 ++++++---- .../lightning/SparkDetailViewModel.kt | 16 ++++++++-- .../lightning/SparkDetailViewModelTest.kt | 32 ++++++++++++++++++- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index a45dcfdd73..419cf15587 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -56,6 +56,7 @@ import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.settings.appStatus.ExitStep import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -126,7 +127,7 @@ private fun Content( HorizontalDivider() SectionTitle(stringResource(R.string.lightning__status)) - SparkStatusRow(uiState.status) + SparkStatusRow(uiState.status, uiState.exitStep) HorizontalDivider() ProviderSection(depositAddress = uiState.depositAddress, onCopyText = onCopyText) @@ -189,11 +190,14 @@ private fun Content( } @Composable -private fun SparkStatusRow(status: HealthState) { - val (text, color, background) = when (status) { - HealthState.READY -> Triple(R.string.lightning__order_state__open, Colors.Green, Colors.Green16) - HealthState.PENDING -> Triple(R.string.settings__status__spark__pending, Colors.Yellow, Colors.Yellow16) - HealthState.ERROR -> Triple(R.string.settings__status__spark__error, Colors.Red, Colors.Red16) +private fun SparkStatusRow(status: HealthState, exitStep: ExitStep?) { + val (text, color, background) = when { + exitStep == ExitStep.FUNDING -> Triple(R.string.settings__status__exit__funding, Colors.Yellow, Colors.Yellow16) + exitStep == ExitStep.RUNNING -> Triple(R.string.settings__status__spark__exit, Colors.Yellow, Colors.Yellow16) + status == HealthState.READY -> Triple(R.string.lightning__order_state__open, Colors.Green, Colors.Green16) + status == HealthState.PENDING -> + Triple(R.string.settings__status__spark__pending, Colors.Yellow, Colors.Yellow16) + else -> Triple(R.string.settings__status__spark__error, Colors.Red, Colors.Red16) } Row( verticalAlignment = Alignment.CenterVertically, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index 4060287672..73f6ad2feb 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -21,6 +21,8 @@ import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkRepo +import to.bitkit.ui.settings.appStatus.ExitStep +import to.bitkit.ui.settings.appStatus.exitStep import javax.inject.Inject import kotlin.time.Duration.Companion.milliseconds @@ -41,13 +43,21 @@ class SparkDetailViewModel @Inject constructor( Triple(state, exit, isOnline) }.collect { (state, exit, isOnline) -> _uiState.update { - it.copy(spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline)) + it.copy( + spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline), + exitStep = exit.record.exitStep(exit.fundingState), + ) } } } viewModelScope.launch(bgDispatcher) { healthRepo.healthState.collect { health -> - _uiState.update { it.copy(status = health.spark ?: HealthState.ERROR) } + _uiState.update { + it.copy( + status = health.spark?.let { s -> if (health.isSparkExiting) HealthState.PENDING else s } + ?: HealthState.ERROR, + ) + } } } viewModelScope.launch(bgDispatcher) { @@ -97,6 +107,8 @@ data class SparkDetailUiState( val isRefreshing: Boolean = false, /** Spark's connection, as App Status shows it. */ val status: HealthState = HealthState.PENDING, + /** A running force transfer to savings: the status reads as App Status's Spark row does. */ + val exitStep: ExitStep? = null, /** Spark's on-chain deposit address, shown on regtest to fund Spark from Lightspark's regtest faucet. */ val depositAddress: String? = null, ) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt index aae22fa943..d253b7153f 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -3,21 +3,25 @@ package to.bitkit.ui.settings.lightning import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.models.HealthState import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.settings.appStatus.ExitStep import kotlin.test.assertEquals class SparkDetailViewModelTest : BaseUnitTest() { private val healthState = MutableStateFlow(AppHealthState()) + private val exitState = MutableStateFlow(SparkExitState()) private val lightningRepo = mock() private val sparkRepo = mock() private val sparkExitRepo = mock() @@ -26,7 +30,7 @@ class SparkDetailViewModelTest : BaseUnitTest() { @Before fun setUp() { whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) - whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) + whenever(sparkExitRepo.state).thenReturn(exitState) whenever(healthRepo.healthState).thenReturn(healthState) } @@ -51,6 +55,32 @@ class SparkDetailViewModelTest : BaseUnitTest() { assertEquals(HealthState.ERROR, sut.uiState.value.status) } + @Test + fun `status is not open while a force transfer runs with spark connected`() = test { + whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) + healthState.value = AppHealthState(spark = HealthState.READY, isSparkExiting = true) + + val sut = createSut() + + assertEquals(HealthState.PENDING, sut.uiState.value.status) + } + + @Test + fun `status reads as app status's spark row while a force transfer runs`() = test { + whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) + val record = mock { + on { isActive } doReturn true + on { phase } doReturn SparkExitRecord.Phase.Running + } + exitState.value = SparkExitState(record = record) + + val sut = createSut() + + assertEquals(ExitStep.RUNNING, sut.uiState.value.exitStep) + exitState.value = SparkExitState() + assertEquals(null, sut.uiState.value.exitStep) + } + @Test fun `status is offline while spark's health is unknown`() = test { whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) From 55d53c10d05db840035405ea38b654d8b5c36b41 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 11:55:35 +0100 Subject: [PATCH 10/23] fix: show receiving on an empty spark connection An empty connected Spark is left out of the connections list, yet its detail screen still shows it receives. Verified: just format, compile, test, lint --- .../ui/settings/lightning/SparkDetailViewModel.kt | 4 +++- .../settings/lightning/SparkDetailViewModelTest.kt | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index 73f6ad2feb..30959857ee 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -44,7 +44,9 @@ class SparkDetailViewModel @Inject constructor( }.collect { (state, exit, isOnline) -> _uiState.update { it.copy( - spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline), + // An empty Spark is left out of the connections list, yet still receives here. + spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline) + ?: SparkUi(balanceSats = 0uL, isReceiving = state.isReceiving(isOnline)), exitStep = exit.record.exitStep(exit.fundingState), ) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt index d253b7153f..795bf0688c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -22,6 +22,7 @@ import kotlin.test.assertEquals class SparkDetailViewModelTest : BaseUnitTest() { private val healthState = MutableStateFlow(AppHealthState()) private val exitState = MutableStateFlow(SparkExitState()) + private val sparkState = MutableStateFlow(SparkState()) private val lightningRepo = mock() private val sparkRepo = mock() private val sparkExitRepo = mock() @@ -29,7 +30,7 @@ class SparkDetailViewModelTest : BaseUnitTest() { @Before fun setUp() { - whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) + whenever(sparkRepo.state).thenReturn(sparkState) whenever(sparkExitRepo.state).thenReturn(exitState) whenever(healthRepo.healthState).thenReturn(healthState) } @@ -81,6 +82,17 @@ class SparkDetailViewModelTest : BaseUnitTest() { assertEquals(null, sut.uiState.value.exitStep) } + @Test + fun `an empty connected spark still shows it receives`() = test { + whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) + sparkState.value = SparkState(isReady = true) + healthState.value = AppHealthState(internet = HealthState.READY, spark = HealthState.READY) + + val sut = createSut() + + assertEquals(true, sut.uiState.value.spark?.isReceiving) + } + @Test fun `status is offline while spark's health is unknown`() = test { whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) From ae4e293eb766824116e3f19f7c7bbbd42c5fcfa5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 12:28:26 +0100 Subject: [PATCH 11/23] fix: keep receiving on an empty spark after a refresh Pull to refresh builds the Spark detail the same way the state collector does. Verified: just format, compile, test, lint --- .../settings/lightning/SparkDetailViewModel.kt | 17 ++++++++++------- .../lightning/SparkDetailViewModelTest.kt | 2 ++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index 30959857ee..cef3dc6e9f 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -20,7 +20,9 @@ import to.bitkit.models.HealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.ui.settings.appStatus.ExitStep import to.bitkit.ui.settings.appStatus.exitStep import javax.inject.Inject @@ -44,9 +46,7 @@ class SparkDetailViewModel @Inject constructor( }.collect { (state, exit, isOnline) -> _uiState.update { it.copy( - // An empty Spark is left out of the connections list, yet still receives here. - spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline) - ?: SparkUi(balanceSats = 0uL, isReceiving = state.isReceiving(isOnline)), + spark = state.toDetailUi(exit, isOnline), exitStep = exit.record.exitStep(exit.fundingState), ) } @@ -89,10 +89,8 @@ class SparkDetailViewModel @Inject constructor( val exit = sparkExitRepo.state.value _uiState.update { it.copy( - spark = sparkRepo.state.value.toUi( - lightningRepo, - exit.showsResult, - exit.earlierAddresses, + spark = sparkRepo.state.value.toDetailUi( + exit, healthRepo.healthState.value.internet == HealthState.READY, ) ) @@ -101,6 +99,11 @@ class SparkDetailViewModel @Inject constructor( _uiState.update { it.copy(isRefreshing = false) } } } + + /** An empty Spark is left out of the connections list, yet still receives here. */ + private suspend fun SparkState.toDetailUi(exit: SparkExitState, isOnline: Boolean) = + toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline) + ?: SparkUi(balanceSats = 0uL, isReceiving = isReceiving(isOnline)) } @Immutable diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt index 795bf0688c..94622ca17f 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -91,6 +91,8 @@ class SparkDetailViewModelTest : BaseUnitTest() { val sut = createSut() assertEquals(true, sut.uiState.value.spark?.isReceiving) + sut.onPullToRefresh() + assertEquals(true, sut.uiState.value.spark?.isReceiving) } @Test From 5c5dd5b9995c0ffcc381848753b4893338f4574c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 13:57:15 +0100 Subject: [PATCH 12/23] fix: set the spark trust note in the frame's small body text Verified: just format, compile, test, lint --- .../java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 419cf15587..7b630e1b84 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -42,7 +42,6 @@ import to.bitkit.models.HealthState import to.bitkit.repositories.SparkDeposit import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkWithdrawal -import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.CaptionB @@ -247,7 +246,7 @@ private fun ProviderSection(depositAddress: String?, onCopyText: (String) -> Uni modifier = Modifier.testTag("SparkDepositAddress"), ) } - BodyM( + BodyS( text = stringResource(R.string.lightning__spark_trust), color = Colors.White50, modifier = Modifier.padding(vertical = 16.dp) From 1f11f45e3e701649214a509c93288b982bbaabf0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 02:14:24 +0100 Subject: [PATCH 13/23] fix: spark not ready after a failed exit reconnect A force transfer's reconnect that disconnected Spark and then failed to connect it left Spark marked ready with no SDK, so its status, bar and card read as connected with no limit. Spark now reads as not ready until the transfer's next tick connects it again. Verified: just format, compile, test, lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 22 +++++++++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 22 +++++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b8b4698efa..d71c50a8c3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -308,6 +308,7 @@ class SparkRepo @Inject constructor( uncertainSends.clear() hasSyncedActivities = false hasMergedRemoteExitState = false + isLostForExit = false _depositClaims.update { emptyMap() } _claimChoices.update { emptyMap() } _state.update { SparkState(isSupported = sparkService.isSupported) } @@ -320,6 +321,10 @@ class SparkRepo @Inject constructor( storage.mapCatching { exitRecords.getOrThrow() } } + /** Set when a reconnect for an exit disconnected Spark and then failed, so [reconnectForExit] connects it again. */ + @Volatile + private var isLostForExit = false + /** * Takes Spark off the Lightning rail while an emergency exit runs, so no payment moves leaves the exit is * spending, and connects Spark again so its leaf optimization follows: off while exiting, on once it ends. @@ -334,20 +339,29 @@ class SparkRepo @Inject constructor( onOptimizationCutShort() sparkService.disconnect() sparkService.connect(walletIndex, isExiting) + isLostForExit = false refresh() }.onFailure { Logger.error("Failed to reconnect Spark with exit '$isExiting'", it, context = TAG) + // Without an SDK Spark neither sends nor receives, so it reads as not ready until it connects again. + if (!sparkService.isConnected) { + isLostForExit = true + _state.update { it.copy(isReady = false) } + } } } /** - * Connects Spark again when a reconnect for an exit disconnected it and then failed: Spark was ready but has no - * SDK, so neither the exit's builds nor its leaf optimization would run until a background run or a restart. + * Connects Spark again when a reconnect for an exit disconnected it and then failed: Spark has no SDK, so neither + * the exit's builds nor its leaf optimization would run, and it reads as not ready, until a background run or a + * restart. */ suspend fun reconnectForExit() = withContext(bgDispatcher) { - if (!_state.value.isReady || sparkService.isConnected) return@withContext + if (!isLostForExit || sparkService.isConnected) return@withContext runSuspendCatching { - if (sparkService.connect(walletIndex, _state.value.isExiting)) refresh() + sparkService.connect(walletIndex, _state.value.isExiting) + isLostForExit = false + refresh() }.onFailure { Logger.warn("Failed to connect Spark again for the exit", it, context = TAG) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 597177f9a3..9bd97cae17 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2735,11 +2735,29 @@ class SparkRepoTest : BaseUnitTest() { sut.holdForExit() // The exit's reconnect disconnected Spark, then failed to connect it. whenever(sparkService.isConnected).thenReturn(false) - whenever { sparkService.connect(any(), any()) }.thenReturn(true) + whenever { sparkService.connect(any(), any()) } + .thenThrow(RuntimeException("operators unreachable")) + .thenReturn(true) + sut.setExiting(true, reconnect = true) + assertFalse(sut.state.value.isReady, "Spark read as ready without a connection") + + sut.reconnectForExit() + + verify(sparkService, times(2)).connect(0, true) + assertTrue(sut.state.value.isReady, "Spark read as not ready once it connected again") + } + + @Test + fun `an exit's tick leaves a connected spark alone`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + whenever(sparkService.isConnected).thenReturn(false) sut.reconnectForExit() - verify(sparkService).connect(0, true) + verify(sparkService, never()).connect(any(), any()) } @Test From 55f1970743b812313097553a33ef58e63156556a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 02:47:19 +0100 Subject: [PATCH 14/23] fix: spark readiness after a disconnected refresh A refresh that read Spark's SDK before an exit reconnect disconnected it could publish ready after the reconnect failed. It now marks Spark ready only while connected. A failed reconnect reads as a failed connection, so App Status shows the error instead of connecting. Verified: just format, compile, test, lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++--- .../to/bitkit/repositories/SparkRepoTest.kt | 27 +++++++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d71c50a8c3..2eadfd2721 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -343,10 +343,10 @@ class SparkRepo @Inject constructor( refresh() }.onFailure { Logger.error("Failed to reconnect Spark with exit '$isExiting'", it, context = TAG) - // Without an SDK Spark neither sends nor receives, so it reads as not ready until it connects again. + // Without an SDK Spark neither sends nor receives, so it reads as failed until it connects again. if (!sparkService.isConnected) { isLostForExit = true - _state.update { it.copy(isReady = false) } + _state.update { it.copy(isReady = false, hasStartFailed = true) } } } } @@ -1230,7 +1230,8 @@ class SparkRepo @Inject constructor( val isStale = withdrawalFailedAtSecs != null || info.lastSyncError != null _state.update { it.copy( - isReady = true, + // A refresh that read an SDK disconnected meanwhile leaves the readiness its reconnect set. + isReady = sparkService.isConnected || it.isReady, balanceSats = info.balanceSats, // An exit moves the balance to savings, so a zero read during one keeps nothing. keptBalanceSats = it.shownBalanceSats.takeIf { kept -> diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9bd97cae17..6be1d68f7b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2734,12 +2734,17 @@ class SparkRepoTest : BaseUnitTest() { sut.refreshState().getOrThrow() sut.holdForExit() // The exit's reconnect disconnected Spark, then failed to connect it. - whenever(sparkService.isConnected).thenReturn(false) + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } whenever { sparkService.connect(any(), any()) } .thenThrow(RuntimeException("operators unreachable")) - .thenReturn(true) + .thenAnswer { + isConnected = true + true + } sut.setExiting(true, reconnect = true) assertFalse(sut.state.value.isReady, "Spark read as ready without a connection") + assertTrue(sut.state.value.hasStartFailed, "the failed reconnect read as connecting") sut.reconnectForExit() @@ -2747,6 +2752,24 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(sut.state.value.isReady, "Spark read as not ready once it connected again") } + @Test + fun `a refresh of a disconnected spark leaves it not ready`() = test { + var isConnected = true + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + whenever { sparkService.connect(any(), any()) }.thenThrow(RuntimeException("operators unreachable")) + whenever { sparkService.disconnect() }.thenAnswer { isConnected = false } + sut.setExiting(false, reconnect = true) + // A refresh that read the SDK before it was disconnected publishes after the reset. + whenever(sparkService.isConnected).thenReturn(true, false) + + sut.refreshState().getOrThrow() + + assertFalse(sut.state.value.isReady, "a stale refresh marked Spark ready without a connection") + } + @Test fun `an exit's tick leaves a connected spark alone`() = test { whenever(sparkService.isConnected).thenReturn(true) From 9166d805aa3f8d132ad23da8a744b863e20a2688 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 14:03:05 +0100 Subject: [PATCH 15/23] fix: keep offline spark's last known state shown A Spark that read its balance and payments stays listed in Lightning Connections, opens from App Status and keeps its detail while it cannot connect, with receiving and payments off until it connects again. Verified: just format, compile, test, lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 3 +++ .../ui/settings/appStatus/AppStatusScreen.kt | 6 ++++-- .../settings/appStatus/AppStatusViewModel.kt | 8 +++++++- .../LightningConnectionsViewModel.kt | 6 +++--- .../to/bitkit/repositories/SparkRepoTest.kt | 2 ++ .../appStatus/AppStatusViewModelTest.kt | 19 +++++++++++++++++++ .../ui/settings/lightning/SparkUiTest.kt | 13 +++++++++++++ 7 files changed, 51 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2eadfd2721..14d8a12bf9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1232,6 +1232,7 @@ class SparkRepo @Inject constructor( it.copy( // A refresh that read an SDK disconnected meanwhile leaves the readiness its reconnect set. isReady = sparkService.isConnected || it.isReady, + hasReadState = true, balanceSats = info.balanceSats, // An exit moves the balance to savings, so a zero read during one keeps nothing. keptBalanceSats = it.shownBalanceSats.takeIf { kept -> @@ -2020,6 +2021,8 @@ data class SparkState( val isReady: Boolean = false, /** Spark synced its payments at least once since it connected, so its payment list is complete. */ val hasSynced: Boolean = false, + /** Spark read its balance and payments at least once, so they stay shown while it cannot connect. */ + val hasReadState: Boolean = false, /** The last start failed; the next start clears it when it begins. */ val hasStartFailed: Boolean = false, /** What Spark read, which sends and withdrawals use. */ diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index 61f0075210..eeb0544fde 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -173,6 +173,7 @@ private fun Content( SparkStatusItem( sparkHealth = uiState.health.spark, exitStep = uiState.exitStep, + hasSparkState = uiState.hasSparkState, onSparkClick = onSparkClick, onExitClick = onExitClick, ) @@ -215,6 +216,7 @@ private fun Content( private fun SparkStatusItem( sparkHealth: HealthState?, exitStep: ExitStep?, + hasSparkState: Boolean, onSparkClick: () -> Unit, onExitClick: () -> Unit, ) { @@ -247,8 +249,8 @@ private fun SparkStatusItem( iconRes = R.drawable.ic_asterisk, state = sparkHealth, ), - // Spark's detail shows a zero balance until Spark has read its state. - onClick = onSparkClick.takeIf { sparkHealth == HealthState.READY }, + // Spark's detail shows a zero balance until Spark has read its state, then its last known one while offline. + onClick = onSparkClick.takeIf { sparkHealth == HealthState.READY || hasSparkState }, ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index d2b0f58b7d..d47299bec3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -24,6 +24,7 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkRepo import javax.inject.Inject import android.text.format.DateFormat as AndroidDateFormat @@ -33,6 +34,7 @@ class AppStatusViewModel @Inject constructor( private val healthRepo: HealthRepo, private val lightningRepo: LightningRepo, private val sparkExitRepo: SparkExitRepo, + private val sparkRepo: SparkRepo, private val cacheStore: CacheStore, ) : ViewModel() { @@ -49,7 +51,8 @@ class AppStatusViewModel @Inject constructor( cacheStore.backupStatuses, lightningRepo.lightningState, sparkExitRepo.state, - ) { healthState, backupStatuses, lightningState, exitState -> + sparkRepo.state, + ) { healthState, backupStatuses, lightningState, exitState, sparkState -> AppStatusUiState( health = healthState, backupSubtitle = computeBackupSubtitle(healthState.backups, backupStatuses), @@ -59,6 +62,7 @@ class AppStatusViewModel @Inject constructor( else -> lightningState.nodeLifecycleState.uiText(context) }, exitStep = exitState.record.exitStep(exitState.fundingState), + hasSparkState = sparkState.hasReadState, ) }.collect { newState -> _uiState.update { newState } @@ -94,6 +98,8 @@ data class AppStatusUiState( val nodeSubtitle: String = "", /** Null while no emergency exit runs. */ val exitStep: ExitStep? = null, + /** Spark read its state, so its detail shows the last known balance and payments, also while it is offline. */ + val hasSparkState: Boolean = false, /** The app's version and build, as "3.2.0 (182)". */ val appVersion: String = Env.version, ) 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 5489c90e97..07c2f057c4 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 @@ -296,10 +296,10 @@ internal suspend fun SparkState.toUi( isOnline: Boolean = true, ): SparkUi? { val showsExit = isExiting || showsExitResult - // An emergency exit keeps Spark listed, also while it cannot connect, so its progress stays reachable. So do an - // earlier exit's addresses, once Spark is empty. + // A Spark that read its state stays listed while it cannot connect, with its last known balance and payments, and + // so does an emergency exit, so its progress stays reachable, and an earlier exit's addresses, once Spark is empty. val hasEarlier = earlierAddresses.isNotEmpty() - if (!isReady && !showsExit && !hasEarlier) return null + if (!isReady && !hasReadState && !showsExit && !hasEarlier) return null // On regtest Spark always shows, so testers reach its deposit address to fund it from the faucet. val hasExit = showsExit || recoverableFundsSats > 0uL if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && !hasEarlier && Env.network != Network.REGTEST) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 6be1d68f7b..aef2f50598 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2768,6 +2768,8 @@ class SparkRepoTest : BaseUnitTest() { sut.refreshState().getOrThrow() assertFalse(sut.state.value.isReady, "a stale refresh marked Spark ready without a connection") + assertTrue(sut.state.value.hasReadState, "a lost connection hid the state Spark read") + assertEquals(10_000uL, sut.state.value.balanceSats) } @Test diff --git a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index d6787301a4..7c5032db0b 100644 --- a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt @@ -23,14 +23,18 @@ import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals +import kotlin.test.assertTrue class AppStatusViewModelTest : BaseUnitTest() { private val context: Context = mock() private val healthRepo: HealthRepo = mock() private val lightningRepo: LightningRepo = mock() private val sparkExitRepo: SparkExitRepo = mock() + private val sparkRepo: SparkRepo = mock() private val cacheStore: CacheStore = mock() private lateinit var sut: AppStatusViewModel @@ -52,6 +56,7 @@ class AppStatusViewModelTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(cacheStore.backupStatuses).thenReturn(flowOf(emptyMap())) whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) } private fun createSut(): AppStatusViewModel { @@ -60,6 +65,7 @@ class AppStatusViewModelTest : BaseUnitTest() { healthRepo = healthRepo, lightningRepo = lightningRepo, sparkExitRepo = sparkExitRepo, + sparkRepo = sparkRepo, cacheStore = cacheStore, ) } @@ -240,6 +246,19 @@ class AppStatusViewModelTest : BaseUnitTest() { } } + @Test + fun `ui state keeps spark's detail reachable once spark read its state`() = test { + val offline = SparkState(isReady = false, hasStartFailed = true, hasReadState = true, balanceSats = 10_000uL) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(offline)) + + sut = createSut() + + sut.uiState.test { + assertTrue(awaitItem().hasSparkState) + cancelAndIgnoreRemainingEvents() + } + } + private fun exitRecord( phase: SparkExitRecord.Phase, shortfallSats: ULong? = null, diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index e9bb9999ab..278c4e761e 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -9,6 +9,7 @@ import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue class SparkUiTest : BaseUnitTest() { @@ -41,6 +42,18 @@ class SparkUiTest : BaseUnitTest() { assertFalse(ui.isReceiving, "an offline spark receives nothing") } + @Test + fun `a spark that read its state stays listed with its balance while it cannot connect`() = test { + val offline = SparkState(isReady = false, hasReadState = true, balanceSats = 10_000uL) + + val ui = assertNotNull(offline.toUi(mock())) + + assertEquals(10_000uL, ui.balanceSats) + assertFalse(ui.isReceiving, "an offline spark receives nothing") + val unread = SparkState(isReady = false, balanceSats = 10_000uL) + assertNull(unread.toUi(mock()), "listed before Spark read anything") + } + @Test fun `a deposit shows the amount sent on-chain before and after spark claims it`() { val pending = SparkDepositUi(SparkDeposit("txid", 5_000uL, isClaimed = false)) From 72c9eb37f861e10735c5136e81d29b8bf4ba4db7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 14:23:25 +0100 Subject: [PATCH 16/23] fix: keep fees in bitcoin without an exchange rate The fee grid on Review and Review & Sign switches to fiat only while a rate exists for the selected currency; switching back always works. Verified: just format, compile, test, lint --- app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt | 4 ++++ .../bitkit/ui/screens/transfer/SpendingConfirmScreen.kt | 6 +++++- .../ui/screens/transfer/hardware/SpendingHwSignScreen.kt | 6 +++++- .../test/java/to/bitkit/repositories/CurrencyRepoTest.kt | 9 +++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt index 06cefa01a7..ef054d54f4 100644 --- a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt @@ -278,6 +278,10 @@ data class CurrencyState( val isRefreshing: Boolean = false, ) +/** Switching to fiat needs a rate for the selected currency, or every fiat amount would be missing. */ +val CurrencyState.canSwitchUnit: Boolean + get() = primaryDisplay == PrimaryDisplay.FIAT || rates.any { it.quote == selectedCurrency } + val CurrencyState.paykitRate: PaykitExchangeRate? get() = rates.firstOrNull { it.quote == "USD" diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt index ca7f1c0353..e4bf93671d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt @@ -43,6 +43,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.repositories.canSwitchUnit +import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodySSB import to.bitkit.ui.components.ButtonSize @@ -82,6 +84,7 @@ fun SpendingConfirmScreen( ) { val state by viewModel.uiState.collectAsStateWithLifecycle() val currency = currencyViewModel + val currencies = LocalCurrencies.current BackHandler(enabled = state.isSending) {} @@ -105,7 +108,8 @@ fun SpendingConfirmScreen( onBackClick = { if (!state.isSending) onBackClick() }, onLearnMoreClick = { if (!state.isSending) onLearnMoreClick() }, onSpeedChange = viewModel::onSpeedChange, - onFeesClick = { currency?.switchUnit() }, + // Without a rate the fees stay in bitcoin. + onFeesClick = { if (currencies.canSwitchUnit) currency?.switchUnit() }, onConfirm = viewModel::onConfirm, ) AnimatedVisibility( diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt index b0a607b5d0..b0ddcfa11d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt @@ -43,6 +43,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.models.HwWalletVendor import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.repositories.canSwitchUnit +import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton @@ -82,6 +84,7 @@ fun SpendingHwSignScreen( var request by remember { mutableStateOf(null) } val isBusy = state.isSending || hwState.isSigning val currency = currencyViewModel + val currencies = LocalCurrencies.current BackHandler(enabled = !hwState.canLeave || state.isSending) {} @@ -123,7 +126,8 @@ fun SpendingHwSignScreen( hasPendingBroadcast = hwState.hasPendingBroadcast, onBackClick = { if (hwState.canLeave && !state.isSending) onBackClick() }, onSpeedChange = { if (!isBusy) viewModel.onSpeedChange(it) }, - onFeesClick = { currency?.switchUnit() }, + // Without a rate the fees stay in bitcoin. + onFeesClick = { if (currencies.canSwitchUnit) currency?.switchUnit() }, onOpenConnect = { // A pending broadcast resumes only for the exact request it was signed for. val pending = request?.takeIf { hwState.hasPendingBroadcast } diff --git a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt index 342cce6162..533fa4e6f6 100644 --- a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import app.cash.turbine.test +import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancelAndJoin @@ -294,6 +295,14 @@ class CurrencyRepoTest : BaseUnitTest() { releaseCollector.countDown() } } + + @Test + fun `switching to fiat needs a rate for the selected currency, switching back does not`() { + val rated = CurrencyState(rates = testRates.toImmutableList(), selectedCurrency = "EUR") + assertTrue(rated.canSwitchUnit) + assertFalse(rated.copy(selectedCurrency = "JPY").canSwitchUnit, "switched to fiat with no rate") + assertTrue(CurrencyState(primaryDisplay = PrimaryDisplay.FIAT).canSwitchUnit, "kept in fiat with no rate") + } } private class CurrencyRepoTestError(message: String) : AppError(message) From f8507452a0fec22229e85ad94c8af77293f7368b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:03:00 +0100 Subject: [PATCH 17/23] fix: keep bitcoin fees and offline spark history shown Bitcoin amounts show also while the selected currency has no exchange rate. Spark's detail keeps Transfer To Savings off until Spark can send again, and keeps its withdrawals once Spark is empty. Verified: just format, compile, test, lint --- .../java/to/bitkit/ui/components/Money.kt | 10 ++-- .../LightningConnectionsViewModel.kt | 3 ++ .../settings/lightning/SparkDetailScreen.kt | 3 +- .../lightning/SparkDetailViewModel.kt | 4 +- .../to/bitkit/ui/components/MoneyTextTest.kt | 47 +++++++++++++++++++ .../lightning/SparkDetailViewModelTest.kt | 12 +++++ .../ui/settings/lightning/SparkUiTest.kt | 2 + 7 files changed, 73 insertions(+), 8 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt diff --git a/app/src/main/java/to/bitkit/ui/components/Money.kt b/app/src/main/java/to/bitkit/ui/components/Money.kt index 113c3cd529..c8330e0475 100644 --- a/app/src/main/java/to/bitkit/ui/components/Money.kt +++ b/app/src/main/java/to/bitkit/ui/components/Money.kt @@ -21,6 +21,7 @@ import to.bitkit.models.PrimaryDisplay import to.bitkit.models.STUB_RATE import to.bitkit.models.asBtc import to.bitkit.models.formatCurrency +import to.bitkit.models.formatMoney import to.bitkit.models.formatToModernDisplay import to.bitkit.repositories.CurrencyState import to.bitkit.ui.LocalCurrencies @@ -243,15 +244,14 @@ fun rememberMoneyText( val currency = currencyViewModel ?: return null return remember(currencies, sats, unit) { - val converted = currency.convert(sats) ?: return@remember null - + // Bitcoin amounts need no exchange rate, so they show also while the selected currency has none. if (unit == PrimaryDisplay.BITCOIN) { - val btcComponents = converted.bitcoinDisplay(currencies.displayUnit) buildString { - if (showSymbol) append("${btcComponents.symbol} ") - append(btcComponents.value) + if (showSymbol) append("$BITCOIN_SYMBOL ") + append(sats.formatMoney(currencies.displayUnit)) } } else { + val converted = currency.convert(sats) ?: return@remember null buildString { if (showSymbol && !converted.isSymbolSuffix) append("${converted.symbol} ") append(converted.formatted) 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 07c2f057c4..f816dbbfe5 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 @@ -271,6 +271,8 @@ data class SparkUi( val earlierAddresses: ImmutableList = persistentListOf(), /** Spark is connected with no exit running, so it receives with no limit. */ val isReceiving: Boolean = false, + /** Spark is connected with no exit running, so it can send, Transfer To Savings included. */ + val isUsable: Boolean = false, ) { /** * The emergency exit is offered while Spark holds funds, also a kept balance while it reads 0, and leads to its @@ -316,6 +318,7 @@ internal suspend fun SparkState.toUi( showsExitResult = showsExit, earlierAddresses = earlierAddresses.toImmutableList(), isReceiving = isReceiving(isOnline), + isUsable = isUsable, ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 7b630e1b84..2705d2c1e2 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -334,7 +334,7 @@ private fun Buttons( PrimaryButton( text = stringResource(R.string.wallet__transfer_to_savings), onClick = onTransferToSavings, - enabled = spark.balanceSats > 0uL && !spark.isExiting, + enabled = spark.balanceSats > 0uL && spark.isUsable, icon = { Icon( painter = painterResource(R.drawable.ic_transfer), @@ -409,6 +409,7 @@ private fun Preview() { spark = SparkUi( balanceSats = 35_000uL, isReceiving = true, + isUsable = true, deposits = persistentListOf( SparkDepositUi(SparkDeposit("6c8706b8a9cbd18f", 15_000uL, isClaimed = false), 1u), SparkDepositUi(SparkDeposit("d0067b2497c7b905", 35_000uL, isClaimed = true, feeSats = 312uL)), diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index cef3dc6e9f..42c18bfdd7 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -100,10 +100,10 @@ class SparkDetailViewModel @Inject constructor( } } - /** An empty Spark is left out of the connections list, yet still receives here. */ + /** An empty Spark is left out of the connections list, yet still receives here and keeps its withdrawals. */ private suspend fun SparkState.toDetailUi(exit: SparkExitState, isOnline: Boolean) = toUi(lightningRepo, exit.showsResult, exit.earlierAddresses, isOnline) - ?: SparkUi(balanceSats = 0uL, isReceiving = isReceiving(isOnline)) + ?: SparkUi(balanceSats = 0uL, withdrawals = withdrawals, isReceiving = isReceiving(isOnline)) } @Immutable diff --git a/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt new file mode 100644 index 0000000000..22300ee504 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt @@ -0,0 +1,47 @@ +package to.bitkit.ui.components + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.junit4.createComposeRule +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.models.PrimaryDisplay +import to.bitkit.repositories.CurrencyState +import to.bitkit.ui.LocalCurrencyViewModel +import to.bitkit.viewmodels.CurrencyViewModel +import kotlin.test.assertEquals +import kotlin.test.assertNull + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class MoneyTextTest { + @get:Rule + val composeRule = createComposeRule() + + private val currencyViewModel = mock() + + @Test + fun `bitcoin amounts show while the selected currency has no rate`() { + whenever(currencyViewModel.convert(any(), anyOrNull())).thenReturn(null) + var bitcoin: String? = "unset" + var fiat: String? = "unset" + + composeRule.setContent { + CompositionLocalProvider(LocalCurrencyViewModel provides currencyViewModel) { + val currencies = CurrencyState(primaryDisplay = PrimaryDisplay.BITCOIN) + bitcoin = rememberMoneyText(1_234L, currencies = currencies, showSymbol = false) + fiat = rememberMoneyText(1_234L, currencies = currencies, unit = PrimaryDisplay.FIAT) + } + } + composeRule.waitForIdle() + + assertEquals("1 234", bitcoin?.replace(' ', ' ')) + assertNull(fiat, "a fiat amount showed without a rate") + } +} diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt index 94622ca17f..ae58211425 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -1,5 +1,6 @@ package to.bitkit.ui.settings.lightning +import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Before import org.junit.Test @@ -15,6 +16,7 @@ import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState +import to.bitkit.repositories.SparkWithdrawal import to.bitkit.test.BaseUnitTest import to.bitkit.ui.settings.appStatus.ExitStep import kotlin.test.assertEquals @@ -104,4 +106,14 @@ class SparkDetailViewModelTest : BaseUnitTest() { assertEquals(HealthState.ERROR, sut.uiState.value.status) } + + @Test + fun `the detail keeps spark's withdrawals when the connections list leaves spark out`() = test { + val withdrawal = SparkWithdrawal("4f1d0c55e2a9b713", 4_917uL, feeSats = 1_470uL) + sparkState.value = SparkState(isReady = false, withdrawals = persistentListOf(withdrawal)) + + val sut = createSut() + + assertEquals?>(listOf(withdrawal), sut.uiState.value.spark?.withdrawals) + } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index 278c4e761e..24841324da 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -50,6 +50,8 @@ class SparkUiTest : BaseUnitTest() { assertEquals(10_000uL, ui.balanceSats) assertFalse(ui.isReceiving, "an offline spark receives nothing") + assertFalse(ui.isUsable, "an offline spark offered Transfer To Savings") + assertTrue(assertNotNull(offline.copy(isReady = true).toUi(mock())).isUsable) val unread = SparkState(isReady = false, balanceSats = 10_000uL) assertNull(unread.toUi(mock()), "listed before Spark read anything") } From 45ba38eb603ae8b21396bbd2993da0a1586c5344 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:14:36 +0100 Subject: [PATCH 18/23] fix: treat only a positive exchange rate as a rate A rate priced at zero or one that does not parse no longer counts, so the fee grid stays in bitcoin. Fiat to sats fails on a zero or negative rate and on a negative or out of range result instead of wrapping. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/CurrencyRepo.kt | 8 ++++--- .../bitkit/repositories/CurrencyRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt index ef054d54f4..a15f097966 100644 --- a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt @@ -194,7 +194,8 @@ class CurrencyRepo @Inject constructor( fun getCurrentRate(currency: String): FxRate { val rates = _currencyState.value.rates - val rate = rates.firstOrNull { it.quote == currency } + // A price of zero or one that does not parse converts nothing, so it counts as no rate. + val rate = rates.firstOrNull { it.quote == currency && it.rate > 0.0 } return checkNotNull(rate) { "Rate not found for currency: $currency in: ${rates.joinToString { it.quote }}" @@ -246,7 +247,8 @@ class CurrencyRepo @Inject constructor( val btcAmount = fiatValue.divide(BigDecimal.valueOf(rate.rate), BTC_SCALE, RoundingMode.HALF_UP) val satsDecimal = btcAmount.multiply(BigDecimal(SATS_IN_BTC)) val roundedSats = satsDecimal.setScale(0, RoundingMode.HALF_UP) - roundedSats.toLong().toULong() + require(roundedSats.signum() >= 0) { "Negative sats for fiat '$fiatValue'" } + roundedSats.longValueExact().toULong() } fun convertFiatToSats(fiat: Double, currency: String?) = convertFiatToSats(BigDecimal.valueOf(fiat), currency) @@ -280,7 +282,7 @@ data class CurrencyState( /** Switching to fiat needs a rate for the selected currency, or every fiat amount would be missing. */ val CurrencyState.canSwitchUnit: Boolean - get() = primaryDisplay == PrimaryDisplay.FIAT || rates.any { it.quote == selectedCurrency } + get() = primaryDisplay == PrimaryDisplay.FIAT || rates.any { it.quote == selectedCurrency && it.rate > 0.0 } val CurrencyState.paykitRate: PaykitExchangeRate? get() = rates.firstOrNull { diff --git a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt index 533fa4e6f6..1fb9860e99 100644 --- a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt @@ -155,6 +155,27 @@ class CurrencyRepoTest : BaseUnitTest() { } } + @Test + fun `convertFiatToSats refuses a zero, negative or out of range result`() = test { + val usd = testRates.first { it.quote == "USD" } + val rates = testRates.map { if (it.quote == "EUR") it.copy(lastPrice = "0") else it } + + usd.copy(quote = "GBP", lastPrice = "-50000") + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(cachedRates = rates))) + whenever(settingsStore.data).thenReturn(flowOf(SettingsData(selectedCurrency = "EUR"))) + + sut = createSut() + + sut.currencyState.take(1).test(timeout = 1000.milliseconds) { + awaitItem() + + assertTrue(sut.convertFiatToSats(BigDecimal("45.00"), "EUR").isFailure, "converted at a zero rate") + assertTrue(sut.convertFiatToSats(BigDecimal("45.00"), "GBP").isFailure, "converted at a negative rate") + assertTrue(sut.convertFiatToSats(BigDecimal("-45.00"), "USD").isFailure, "wrapped negative sats") + assertTrue(sut.convertFiatToSats(BigDecimal("1e30"), "USD").isFailure, "wrapped an out of range amount") + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `getCurrentRate should match by quote currency`() = test { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(cachedRates = testRates))) @@ -302,6 +323,8 @@ class CurrencyRepoTest : BaseUnitTest() { assertTrue(rated.canSwitchUnit) assertFalse(rated.copy(selectedCurrency = "JPY").canSwitchUnit, "switched to fiat with no rate") assertTrue(CurrencyState(primaryDisplay = PrimaryDisplay.FIAT).canSwitchUnit, "kept in fiat with no rate") + val zeroPrice = testRates.map { it.copy(lastPrice = "0") }.toImmutableList() + assertFalse(rated.copy(rates = zeroPrice).canSwitchUnit, "switched to fiat with a zero rate") } } From 0a643ed74948d958970c17900a2650e3afd26b3a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:38:57 +0100 Subject: [PATCH 19/23] fix: redraw a typed amount after a unit switch elsewhere The keypad remembers the unit its amount was typed in. Once another screen, such as the fee grid, switches the unit, it redraws the amount from sats, so the next key never reads fiat digits as bitcoin. Verified: just format, compile, test, lint --- .../ui/components/NumberPadTextField.kt | 2 ++ .../bitkit/viewmodels/AmountInputViewModel.kt | 24 ++++++++++++++++++ .../viewmodels/AmountInputViewModelTest.kt | 25 +++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/components/NumberPadTextField.kt b/app/src/main/java/to/bitkit/ui/components/NumberPadTextField.kt index fba4c3e8d1..4bf9be3d06 100644 --- a/app/src/main/java/to/bitkit/ui/components/NumberPadTextField.kt +++ b/app/src/main/java/to/bitkit/ui/components/NumberPadTextField.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -48,6 +49,7 @@ fun NumberPadTextField( currencies: CurrencyState = LocalCurrencies.current, onClick: (() -> Unit)? = { viewModel.switchUnit(currencies) }, ) { + LaunchedEffect(currencies.primaryDisplay, currencies.displayUnit) { viewModel.syncUnit(currencies) } MoneyAmount( modifier = modifier.then(Modifier.clickableAlpha(onClick = onClick)), value = uiState.value.text, diff --git a/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt index beb2a439b7..407f462e53 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt @@ -60,6 +60,9 @@ class AmountInputViewModel @Inject constructor( private var maxAmount: Long = MAX_AMOUNT private var rawInputText: String = "" + /** The unit, and for bitcoin whether modern, [rawInputText] was typed or drawn in. */ + private var inputUnit: Pair? = null + fun setMaxAmount(amount: Long) { maxAmount = if (amount > 0) amount.coerceAtMost(MAX_AMOUNT) else MAX_AMOUNT } @@ -68,6 +71,7 @@ class AmountInputViewModel @Inject constructor( key: String, currencyState: CurrencyState, ) { + syncUnit(currencyState) val primaryDisplay = currencyState.primaryDisplay val isModern = currencyState.displayUnit.isModern() val maxLength = getMaxLength(currencyState) @@ -79,6 +83,7 @@ class AmountInputViewModel @Inject constructor( triggerErrorState(key) return } + inputUnit = primaryDisplay to isModern // For modern Bitcoin (integer input), format the final amount if (primaryDisplay == PrimaryDisplay.BITCOIN && isModern) { @@ -148,6 +153,23 @@ class AmountInputViewModel @Inject constructor( PrimaryDisplay.FIAT -> _uiState.value.text.replace(",", "") else -> _uiState.value.text.stripSatsGrouping() } + inputUnit = primaryDisplay to isModern + } + + /** + * Redraws the amount from its sats once the unit it was typed in no longer shows, as after a switch on another + * screen, so the next key never reads its digits in the other unit. + */ + fun syncUnit(currencyState: CurrencyState) { + val shown = currencyState.primaryDisplay to currencyState.displayUnit.isModern() + if (inputUnit == null || inputUnit == shown) return + if (_uiState.value.sats > 0) { + setSats(_uiState.value.sats, currencyState) + } else { + rawInputText = "" + inputUnit = shown + _uiState.update { it.copy(text = "", sats = 0) } + } } /** @@ -158,6 +180,7 @@ class AmountInputViewModel @Inject constructor( val currentRawInput = rawInputText val isModern = currencies.displayUnit.isModern() val newPrimaryDisplay = amountInputHandler.switchUnit(currencies.primaryDisplay) + inputUnit = newPrimaryDisplay to isModern // Update display text when currency changes val amountSats = _uiState.value.sats @@ -261,6 +284,7 @@ class AmountInputViewModel @Inject constructor( fun clearInput() { rawInputText = "" + inputUnit = null maxAmount = MAX_AMOUNT _uiState.update { AmountInputUiState() } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt index 2ff8dc23c9..fee83b01e1 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt @@ -89,6 +89,31 @@ class AmountInputViewModelTest : BaseUnitTest() { displayUnit = displayUnit ) + @Test + fun `fiat typed before a switch elsewhere is redrawn in bitcoin, never read as bitcoin digits`() = test { + val fiat = mockCurrency(PrimaryDisplay.FIAT) + val bitcoin = mockCurrency(PrimaryDisplay.BITCOIN, BitcoinDisplayUnit.MODERN) + "12".forEach { viewModel.handleNumberPadInput(it.toString(), fiat) } + val sats = viewModel.uiState.value.sats + assertTrue(sats > 0L) + + viewModel.syncUnit(bitcoin) + assertEquals(sats, viewModel.uiState.value.sats) + + viewModel.handleNumberPadInput("0", bitcoin) + assertEquals("the typed fiat digits were read as sats", sats * 10, viewModel.uiState.value.sats) + } + + @Test + fun `a key typed after a switch elsewhere reads the amount in the unit shown`() = test { + "12".forEach { viewModel.handleNumberPadInput(it.toString(), mockCurrency(PrimaryDisplay.FIAT)) } + val sats = viewModel.uiState.value.sats + + viewModel.handleNumberPadInput("0", mockCurrency(PrimaryDisplay.BITCOIN, BitcoinDisplayUnit.MODERN)) + + assertEquals(sats * 10, viewModel.uiState.value.sats) + } + // MARK: - Modern Bitcoin Tests @Test From ed58bac04fab6ab2626d620efb2d78202d247ca0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 16:03:15 +0100 Subject: [PATCH 20/23] fix: show bitcoin fees without a usable rate The rate lookup is back to master's, so a zero price no longer hides bitcoin amounts drawn from a conversion; fiat-to-sats and the unit switch still refuse it. The fee grid and the claim speed fees show bitcoin while fiat is selected without a usable rate. Transfer To Savings also needs the device online. Verified: just format, compile, test, lint --- .../java/to/bitkit/repositories/CurrencyRepo.kt | 15 +++++++++++---- .../main/java/to/bitkit/ui/components/FeeInfo.kt | 4 +++- .../ui/screens/transfer/SpendingConfirmScreen.kt | 3 ++- .../lightning/LightningConnectionsViewModel.kt | 4 ++-- .../to/bitkit/repositories/CurrencyRepoTest.kt | 14 ++++++++++++++ .../bitkit/ui/settings/lightning/SparkUiTest.kt | 2 ++ 6 files changed, 34 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt index a15f097966..d18a61feba 100644 --- a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt @@ -194,8 +194,7 @@ class CurrencyRepo @Inject constructor( fun getCurrentRate(currency: String): FxRate { val rates = _currencyState.value.rates - // A price of zero or one that does not parse converts nothing, so it counts as no rate. - val rate = rates.firstOrNull { it.quote == currency && it.rate > 0.0 } + val rate = rates.firstOrNull { it.quote == currency } return checkNotNull(rate) { "Rate not found for currency: $currency in: ${rates.joinToString { it.quote }}" @@ -280,9 +279,17 @@ data class CurrencyState( val isRefreshing: Boolean = false, ) -/** Switching to fiat needs a rate for the selected currency, or every fiat amount would be missing. */ +/** The selected currency has a rate that converts, so fiat amounts can show. */ +val CurrencyState.hasUsableRate: Boolean + get() = rates.any { it.quote == selectedCurrency && it.rate > 0.0 } + +/** Switching to fiat needs a usable rate, or every fiat amount would be missing. */ val CurrencyState.canSwitchUnit: Boolean - get() = primaryDisplay == PrimaryDisplay.FIAT || rates.any { it.quote == selectedCurrency && it.rate > 0.0 } + get() = primaryDisplay == PrimaryDisplay.FIAT || hasUsableRate + +/** The unit amounts show in: bitcoin while fiat is selected without a usable rate, so they never go blank. */ +val CurrencyState.shownUnit: PrimaryDisplay + get() = if (primaryDisplay == PrimaryDisplay.FIAT && !hasUsableRate) PrimaryDisplay.BITCOIN else primaryDisplay val CurrencyState.paykitRate: PaykitExchangeRate? get() = rates.firstOrNull { diff --git a/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt b/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt index 0318c2913a..175ceeebfc 100644 --- a/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt +++ b/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt @@ -13,6 +13,8 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import to.bitkit.repositories.shownUnit +import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.theme.Colors @Composable @@ -45,7 +47,7 @@ fun RowScope.FeeInfo( .size(16.dp), ) } else { - MoneySSB(sats = amount, showSymbol = true) + MoneySSB(sats = amount, unit = LocalCurrencies.current.shownUnit, showSymbol = true) } } Spacer(modifier = Modifier.weight(1f)) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt index e4bf93671d..db15061344 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt @@ -44,6 +44,7 @@ import to.bitkit.R import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.canSwitchUnit +import to.bitkit.repositories.shownUnit import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodySSB @@ -335,7 +336,7 @@ private fun SpeedItem( if (feeSats != null) { HorizontalSpacer(12.dp) Column(horizontalAlignment = Alignment.End) { - MoneyMSB(sats = feeSats, showSymbol = true) + MoneyMSB(sats = feeSats, unit = LocalCurrencies.current.shownUnit, showSymbol = true) BodySSB(feeCaption, color = Colors.White64) } } 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 f816dbbfe5..a07fec6376 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 @@ -271,7 +271,7 @@ data class SparkUi( val earlierAddresses: ImmutableList = persistentListOf(), /** Spark is connected with no exit running, so it receives with no limit. */ val isReceiving: Boolean = false, - /** Spark is connected with no exit running, so it can send, Transfer To Savings included. */ + /** Online, with Spark connected and no exit running, so it can send, Transfer To Savings included. */ val isUsable: Boolean = false, ) { /** @@ -318,7 +318,7 @@ internal suspend fun SparkState.toUi( showsExitResult = showsExit, earlierAddresses = earlierAddresses.toImmutableList(), isReceiving = isReceiving(isOnline), - isUsable = isUsable, + isUsable = isOnline && isUsable, ) } diff --git a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt index 1fb9860e99..88ceeee7cb 100644 --- a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt @@ -326,6 +326,20 @@ class CurrencyRepoTest : BaseUnitTest() { val zeroPrice = testRates.map { it.copy(lastPrice = "0") }.toImmutableList() assertFalse(rated.copy(rates = zeroPrice).canSwitchUnit, "switched to fiat with a zero rate") } + + @Test + fun `amounts show in bitcoin while fiat is selected without a usable rate`() { + val fiat = CurrencyState( + rates = testRates.toImmutableList(), + selectedCurrency = "EUR", + primaryDisplay = PrimaryDisplay.FIAT + ) + assertEquals(PrimaryDisplay.FIAT, fiat.shownUnit) + assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(selectedCurrency = "JPY").shownUnit, "blank fiat with no rate") + val zeroPrice = testRates.map { it.copy(lastPrice = "0") }.toImmutableList() + assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(rates = zeroPrice).shownUnit, "blank fiat with a zero rate") + assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(primaryDisplay = PrimaryDisplay.BITCOIN).shownUnit) + } } private class CurrencyRepoTestError(message: String) : AppError(message) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index 24841324da..5dcc7fcdad 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -52,6 +52,8 @@ class SparkUiTest : BaseUnitTest() { assertFalse(ui.isReceiving, "an offline spark receives nothing") assertFalse(ui.isUsable, "an offline spark offered Transfer To Savings") assertTrue(assertNotNull(offline.copy(isReady = true).toUi(mock())).isUsable) + val noNetwork = assertNotNull(offline.copy(isReady = true).toUi(mock(), isOnline = false)) + assertFalse(noNetwork.isUsable, "offered Transfer To Savings while the device is offline") val unread = SparkState(isReady = false, balanceSats = 10_000uL) assertNull(unread.toUi(mock()), "listed before Spark read anything") } From 4dccc2a7e0a4c0fc183e2310bb7460678a0ad506 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 16:38:47 +0100 Subject: [PATCH 21/23] fix: show transfer change toasts in bitcoin without a usable rate The fees and max changed toasts fall back to bitcoin while fiat has no usable rate, like the fee grid, so a change never reads as zero. Verified: just format, compile, test, lint --- .../screens/transfer/SparkFundingViewModel.kt | 7 ++-- .../transfer/SparkFundingViewModelTest.kt | 34 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 106a47ea12..232f3f352a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt @@ -45,6 +45,7 @@ import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.WalletRepo +import to.bitkit.repositories.shownUnit import to.bitkit.ui.screens.transfer.SparkFundingContract.Quote import to.bitkit.ui.screens.transfer.SparkFundingContract.SideEffect import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState @@ -573,8 +574,10 @@ class SparkFundingViewModel @Inject constructor( private fun formatPrimaryAmount(sats: Long): String { val state = currencyRepo.currencyState.value - val fiat = currencyRepo.convertSatsToFiat(sats).getOrNull() - if (state.primaryDisplay == PrimaryDisplay.FIAT && fiat != null) return fiat.formattedWithSymbol() + // Like the fee grid, bitcoin while fiat has no usable rate, so a change never reads as zero. + if (state.shownUnit == PrimaryDisplay.FIAT) { + currencyRepo.convertSatsToFiat(sats).getOrNull()?.let { return it.formattedWithSymbol() } + } return "$BITCOIN_SYMBOL ${sats.formatMoney(state.displayUnit)}" } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt index d0f3c6eb8d..fc820e4d22 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -26,7 +26,10 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.models.BITCOIN_SYMBOL import to.bitkit.models.BalanceState +import to.bitkit.models.ConvertedAmount +import to.bitkit.models.PrimaryDisplay import to.bitkit.models.Toast import to.bitkit.models.TransactionSpeed import to.bitkit.models.WalletScope @@ -53,6 +56,7 @@ import to.bitkit.repositories.WalletRepo import to.bitkit.test.BaseUnitTest import to.bitkit.ui.screens.transfer.SparkFundingContract.SideEffect import to.bitkit.ui.shared.toast.ToastEventBus +import java.math.BigDecimal import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -199,6 +203,36 @@ class SparkFundingViewModelTest : BaseUnitTest() { ) } + @Test + fun `a fee rise reads in bitcoin while fiat has no usable rate`() = test { + whenever(context.getString(R.string.lightning__spending_confirm__fees_changed_network)) + .thenReturn("rose {amount}") + whenever( + currencyRepo.currencyState + ).thenReturn(MutableStateFlow(CurrencyState(primaryDisplay = PrimaryDisplay.FIAT))) + whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())) + .thenReturn(Result.success(ConvertedAmount(BigDecimal.ZERO, "0.00", "$", "USD", "", 200L))) + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), + ) + }.thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 700uL)))) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + + val toasts = collectToasts { sut.onConfirm() } + + assertEquals("rose $BITCOIN_SYMBOL 200", toasts.single().description) + } + @Test fun `a fixed amount whose prepared fee rose is refused and priced again at that fee`() = test { whenever(context.getString(R.string.lightning__spending_confirm__fees_changed_network)) From 5020b49efc6fe4c4e3ea7a159cc8c5d205968c4d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 17:21:33 +0100 Subject: [PATCH 22/23] fix: keep redrawn amounts editable and rates checked A redrawn amount gives the keypad ASCII digits, so an edit in Arabic no longer reads it as zero. Fiat shows only while the ticker conversions use, the first, has a finite positive price. Regtest Spark Details loads the deposit address again once Spark connects. Verified: just format, compile, test, lint --- .../to/bitkit/repositories/CurrencyRepo.kt | 4 ++-- .../settings/lightning/SparkDetailViewModel.kt | 10 +++++----- .../bitkit/viewmodels/AmountInputViewModel.kt | 12 ++++++++---- .../to/bitkit/repositories/CurrencyRepoTest.kt | 5 +++++ .../lightning/SparkDetailViewModelTest.kt | 13 +++++++++++++ .../viewmodels/AmountInputViewModelTest.kt | 18 ++++++++++++++++++ 6 files changed, 51 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt index d18a61feba..0e0d077e4b 100644 --- a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt @@ -279,9 +279,9 @@ data class CurrencyState( val isRefreshing: Boolean = false, ) -/** The selected currency has a rate that converts, so fiat amounts can show. */ +/** The rate conversions use for the selected currency, its first, is finite and positive, so fiat amounts can show. */ val CurrencyState.hasUsableRate: Boolean - get() = rates.any { it.quote == selectedCurrency && it.rate > 0.0 } + get() = rates.firstOrNull { it.quote == selectedCurrency }?.rate?.let { it.isFinite() && it > 0.0 } == true /** Switching to fiat needs a usable rate, or every fiat amount would be missing. */ val CurrencyState.canSwitchUnit: Boolean diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index 42c18bfdd7..00360cce39 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -68,11 +68,11 @@ class SparkDetailViewModel @Inject constructor( } if (Env.network == Network.REGTEST) { viewModelScope.launch(bgDispatcher) { - sparkRepo.depositAddress().onSuccess { address -> - _uiState.update { - it.copy( - depositAddress = address - ) + // Details also open from Spark's last known state, so the address loads again once Spark connects. + sparkRepo.state.map { it.isReady }.distinctUntilChanged().collect { + if (_uiState.value.depositAddress != null) return@collect + sparkRepo.depositAddress().onSuccess { address -> + _uiState.update { it.copy(depositAddress = address) } } } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt index 407f462e53..dad0c78604 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt @@ -150,8 +150,8 @@ class AmountInputViewModel @Inject constructor( } // Update raw input text based on the formatted display rawInputText = when (primaryDisplay) { - PrimaryDisplay.FIAT -> _uiState.value.text.replace(",", "") - else -> _uiState.value.text.stripSatsGrouping() + PrimaryDisplay.FIAT -> _uiState.value.text.replace(",", "").asciiDigits() + else -> _uiState.value.text.stripSatsGrouping().asciiDigits() } inputUnit = primaryDisplay to isModern } @@ -192,8 +192,8 @@ class AmountInputViewModel @Inject constructor( } // Update raw input text based on the new display rawInputText = when (newPrimaryDisplay) { - PrimaryDisplay.FIAT -> _uiState.value.text.replace(",", "") - else -> _uiState.value.text.stripSatsGrouping() + PrimaryDisplay.FIAT -> _uiState.value.text.replace(",", "").asciiDigits() + else -> _uiState.value.text.stripSatsGrouping().asciiDigits() } } else if (currentRawInput.isNotEmpty()) { // Convert the raw input from the old currency to the new currency @@ -359,6 +359,10 @@ class AmountInputViewModel @Inject constructor( private fun String.stripSatsGrouping(): String = replace("$SATS_GROUPING_SEPARATOR", "") + /** The keypad reads ASCII digits, while a redrawn amount shows the locale's, as Arabic-Indic in Arabic. */ + private fun String.asciiDigits(): String = map { if (it.isDigit()) '0' + Character.digit(it, 10) else it } + .joinToString("") + private fun convertToSats( text: String, primaryDisplay: PrimaryDisplay, diff --git a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt index 88ceeee7cb..8978402884 100644 --- a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt @@ -339,6 +339,11 @@ class CurrencyRepoTest : BaseUnitTest() { val zeroPrice = testRates.map { it.copy(lastPrice = "0") }.toImmutableList() assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(rates = zeroPrice).shownUnit, "blank fiat with a zero rate") assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(primaryDisplay = PrimaryDisplay.BITCOIN).shownUnit) + val eur = testRates.first { it.quote == "EUR" } + val zeroFirst = (listOf(eur.copy(lastPrice = "0")) + testRates).toImmutableList() + assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(rates = zeroFirst).shownUnit, "fiat from a later ticker") + val infinite = testRates.map { if (it.quote == "EUR") it.copy(lastPrice = "1e400") else it }.toImmutableList() + assertEquals(PrimaryDisplay.BITCOIN, fiat.copy(rates = infinite).shownUnit, "fiat at an infinite rate") } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt index ae58211425..0920d233c7 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -97,6 +97,19 @@ class SparkDetailViewModelTest : BaseUnitTest() { assertEquals(true, sut.uiState.value.spark?.isReceiving) } + @Test + fun `the deposit address loads once a spark opened offline connects`() = test { + whenever(sparkRepo.depositAddress()) + .thenReturn(Result.failure(IllegalStateException("not connected")), Result.success("bcrt1qaddress")) + sparkState.value = SparkState(isReady = false, hasReadState = true) + + val sut = createSut() + + assertEquals(null, sut.uiState.value.depositAddress) + sparkState.value = SparkState(isReady = true, hasReadState = true) + assertEquals("bcrt1qaddress", sut.uiState.value.depositAddress) + } + @Test fun `status is offline while spark's health is unknown`() = test { whenever(sparkRepo.depositAddress()).thenReturn(Result.success("bcrt1qaddress")) diff --git a/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt index fee83b01e1..ae5234cc85 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt @@ -32,6 +32,7 @@ import to.bitkit.ui.components.KEY_000 import to.bitkit.ui.components.KEY_DECIMAL import to.bitkit.ui.components.KEY_DELETE import to.bitkit.ui.components.NumberPadType +import java.util.Locale import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds import kotlin.time.ExperimentalTime @@ -104,6 +105,23 @@ class AmountInputViewModelTest : BaseUnitTest() { assertEquals("the typed fiat digits were read as sats", sats * 10, viewModel.uiState.value.sats) } + @Test + fun `a redrawn amount stays editable with arabic digits`() = test { + val default = Locale.getDefault() + Locale.setDefault(Locale.forLanguageTag("ar-EG-u-nu-arab")) + try { + "20000".forEach { viewModel.handleNumberPadInput(it.toString(), mockCurrency(PrimaryDisplay.BITCOIN)) } + val fiat = mockCurrency(PrimaryDisplay.FIAT) + viewModel.syncUnit(fiat) + + viewModel.handleNumberPadInput(KEY_DELETE, fiat) + + assertTrue("the redrawn fiat read as zero", viewModel.uiState.value.sats > 0L) + } finally { + Locale.setDefault(default) + } + } + @Test fun `a key typed after a switch elsewhere reads the amount in the unit shown`() = test { "12".forEach { viewModel.handleNumberPadInput(it.toString(), mockCurrency(PrimaryDisplay.FIAT)) } From 3d9cf927b8ae6894d45eaeca0641ce0eb91946ae Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 18:26:30 +0100 Subject: [PATCH 23/23] fix: show bitcoin captions without a fiat rate MoneyCaptionB formats bitcoin from sats, so Spark's balance, bars, deposits, withdrawals, fees and earlier exit balances show while the selected currency has no rate. Typography is lazy, so loading the app text styles before the theme no longer leaves the button style unset. Verified: just format, compile, test, lint --- .../java/to/bitkit/ui/components/Money.kt | 27 ++++-------- app/src/main/java/to/bitkit/ui/theme/Type.kt | 43 ++++++++++--------- .../to/bitkit/ui/components/MoneyTextTest.kt | 19 ++++++++ 3 files changed, 51 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/components/Money.kt b/app/src/main/java/to/bitkit/ui/components/Money.kt index c8330e0475..4a3dbead22 100644 --- a/app/src/main/java/to/bitkit/ui/components/Money.kt +++ b/app/src/main/java/to/bitkit/ui/components/Money.kt @@ -196,27 +196,18 @@ fun MoneyCaptionB( return } - val currency = currencyViewModel ?: return val currencies = LocalCurrencies.current - - val displayText = remember(currencies, sats, symbol) { - currency.convert(sats)?.let { converted -> - val btc = converted.bitcoinDisplay(currencies.displayUnit) - if (symbol) { - "${btc.symbol} ${btc.value}" - } else { - btc.value - } - } + // A bitcoin amount needs no exchange rate, so it shows also while the selected currency has none. + val text = remember(currencies.displayUnit, sats, symbol) { + val value = sats.formatMoney(currencies.displayUnit) + if (symbol) "$BITCOIN_SYMBOL $value" else value } - displayText?.let { text -> - CaptionB( - text = text.withAccent(accentColor = symbolColor), - color = color, - modifier = modifier.testTag("MoneyText") - ) - } + CaptionB( + text = text.withAccent(accentColor = symbolColor), + color = color, + modifier = modifier.testTag("MoneyText") + ) } @Composable diff --git a/app/src/main/java/to/bitkit/ui/theme/Type.kt b/app/src/main/java/to/bitkit/ui/theme/Type.kt index 0c3c7e3469..eac30e18e6 100644 --- a/app/src/main/java/to/bitkit/ui/theme/Type.kt +++ b/app/src/main/java/to/bitkit/ui/theme/Type.kt @@ -21,26 +21,29 @@ val DamionFontFamily = FontFamily( Font(R.font.damion_regular, FontWeight.Normal), ) -val Typography = Typography( - // Default Text: - bodyLarge = TextStyle( - fontFamily = InterFontFamily, - fontWeight = FontWeight.Normal, - fontSize = 16.sp, - letterSpacing = 0.4.sp, - ), - bodyMedium = TextStyle( - fontFamily = InterFontFamily, - fontWeight = FontWeight.Normal, - fontSize = 14.sp, - ), - bodySmall = TextStyle( - fontFamily = InterFontFamily, - fontWeight = FontWeight.Normal, - fontSize = 12.sp, - ), - labelLarge = AppTextStyles.BodySSB, // Buttons Text -) +// Lazy, so loading AppTextStyles first, which reads InterFontFamily here, never reads its BodySSB before it is set. +val Typography by lazy { + Typography( + // Default Text: + bodyLarge = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + letterSpacing = 0.4.sp, + ), + bodyMedium = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 14.sp, + ), + bodySmall = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 12.sp, + ), + labelLarge = AppTextStyles.BodySSB, // Buttons Text + ) +} object AppTextStyles { val Display = TextStyle( diff --git a/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt index 22300ee504..bc839e82ed 100644 --- a/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt +++ b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt @@ -1,7 +1,9 @@ package to.bitkit.ui.components import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -13,6 +15,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import to.bitkit.models.PrimaryDisplay import to.bitkit.repositories.CurrencyState +import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.LocalCurrencyViewModel import to.bitkit.viewmodels.CurrencyViewModel import kotlin.test.assertEquals @@ -44,4 +47,20 @@ class MoneyTextTest { assertEquals("1 234", bitcoin?.replace(' ', ' ')) assertNull(fiat, "a fiat amount showed without a rate") } + + @Test + fun `bitcoin captions show while the selected currency has no rate`() { + whenever(currencyViewModel.convert(any(), anyOrNull())).thenReturn(null) + + composeRule.setContent { + CompositionLocalProvider( + LocalCurrencyViewModel provides currencyViewModel, + LocalCurrencies provides CurrencyState(primaryDisplay = PrimaryDisplay.FIAT), + ) { + MoneyCaptionB(sats = 1_234L) + } + } + + composeRule.onNodeWithTag("MoneyText").assertIsDisplayed() + } }