diff --git a/app/src/main/java/to/bitkit/ext/DateTime.kt b/app/src/main/java/to/bitkit/ext/DateTime.kt index e2f0e0fc85..ac8e7862f4 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,19 @@ fun Long.toLocalizedTimestamp(locale: Locale = Locale.getDefault()): String { return formatter.format(date) } +fun Long.toBackupTimestamp( + is24Hour: Boolean, + template: String = DatePattern.BACKUP_DATE_TEMPLATE, + locale: Locale = Locale.getDefault(), + zone: ZoneId = ZoneId.systemDefault(), +): String { + 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) fun Long.toRelativeTimeString( locale: Locale = Locale.getDefault(), @@ -261,6 +275,12 @@ 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 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/repositories/CurrencyRepo.kt b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt index 06cefa01a7..0e0d077e4b 100644 --- a/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt @@ -246,7 +246,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) @@ -278,6 +279,18 @@ data class CurrencyState( val isRefreshing: Boolean = false, ) +/** 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.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 + 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 { it.quote == "USD" 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/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b8b4698efa..14d8a12bf9 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 failed until it connects again. + if (!sparkService.isConnected) { + isLostForExit = true + _state.update { it.copy(isReady = false, hasStartFailed = true) } + } } } /** - * 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) } } @@ -1216,7 +1230,9 @@ 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, + 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 -> @@ -2005,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/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/components/LightningChannel.kt b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt index bdcb5d046b..7025f25c9f 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,25 @@ fun LightningChannel( status: ChannelStatusUi = ChannelStatusUi.PENDING, showLabels: Boolean = false, showReceiving: Boolean = true, + receivingUnlimited: Boolean = false, + isSpark: 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 spendingAvailableFraction = spendingFillFraction(capacity, localBalance, isSpark) + val receivingAvailableFraction = when { + receivingUnlimited -> 1f + capacity > 0 -> remoteBalance.toFloat() / capacity + else -> 0f + } Column( modifier = modifier @@ -90,10 +100,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, + ) + } } } } @@ -137,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) @@ -202,4 +233,20 @@ 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, + isSpark = true, + modifier = Modifier.padding(16.dp) + ) + } +} + // endregion 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..4a3dbead22 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 @@ -195,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 @@ -243,15 +235,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/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/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/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt index ca7f1c0353..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 @@ -43,6 +43,9 @@ 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.repositories.shownUnit +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 +85,7 @@ fun SpendingConfirmScreen( ) { val state by viewModel.uiState.collectAsStateWithLifecycle() val currency = currencyViewModel + val currencies = LocalCurrencies.current BackHandler(enabled = state.isSending) {} @@ -105,7 +109,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( @@ -331,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/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/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index afa20d7177..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 @@ -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 @@ -31,10 +32,11 @@ 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 +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,13 @@ 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, + hasSparkState = uiState.hasSparkState, + onSparkClick = onSparkClick, + onExitClick = onExitClick, + ) StatusItem( statusUi = StatusUi( @@ -221,9 +198,62 @@ 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?, + hasSparkState: Boolean, + 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, then its last known one while offline. + onClick = onSparkClick.takeIf { sparkHealth == HealthState.READY || hasSparkState }, + ) +} + @Composable private fun StatusItem( statusUi: StatusUi, @@ -310,9 +340,10 @@ 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(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 81f8840de3..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 @@ -13,7 +13,8 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.data.CacheStore -import to.bitkit.ext.toLocalizedTimestamp +import to.bitkit.env.Env +import to.bitkit.ext.toBackupTimestamp import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus import to.bitkit.models.HealthState @@ -23,7 +24,9 @@ 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 @HiltViewModel class AppStatusViewModel @Inject constructor( @@ -31,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() { @@ -47,15 +51,18 @@ 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), 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), + hasSparkState = sparkState.hasReadState, ) }.collect { newState -> _uiState.update { newState } @@ -74,9 +81,12 @@ class AppStatusViewModel @Inject constructor( when (val maxSyncTime = syncTimes.max()) { 0L -> context.getString(R.string.settings__status__backup__ready) - else -> runCatching { maxSyncTime.toLocalizedTimestamp() }.getOrDefault( - context.getString(R.string.settings__status__backup__ready) - ) + else -> runCatching { + maxSyncTime.toBackupTimestamp( + is24Hour = AndroidDateFormat.is24HourFormat(context), + template = context.getString(R.string.settings__status__backup__date), + ) + }.getOrDefault(context.getString(R.string.settings__status__backup__ready)) } } } @@ -88,6 +98,10 @@ 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, ) 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..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 @@ -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,15 @@ private fun SparkItem( localBalance = spark.balanceSats.toLong(), remoteBalance = 0L, status = ChannelStatusUi.OPEN, - showReceiving = false, + showReceiving = spark.isReceiving, + receivingUnlimited = spark.isReceiving, + isSpark = true, ) - 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 +461,6 @@ internal fun SparkTransactionRow( amountSats: ULong, onOpenTx: (String) -> Unit, modifier: Modifier = Modifier, - confirmations: UInt? = null, ) { Row( horizontalArrangement = Arrangement.SpaceBetween, @@ -506,18 +479,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 +573,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..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 @@ -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), ) } } @@ -262,33 +269,39 @@ 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, + /** Online, with Spark connected and 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 * 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, 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 - // 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) { @@ -304,14 +317,20 @@ internal suspend fun SparkState.toUi( isExiting = isExiting, showsExitResult = showsExit, earlierAddresses = earlierAddresses.toImmutableList(), + isReceiving = isReceiving(isOnline), + isUsable = isOnline && isUsable, ) } +/** 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/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 53df70e275..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 @@ -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.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.settings.appStatus.ExitStep +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,37 @@ private fun Content( localBalance = spark.balanceSats.toLong(), remoteBalance = 0L, status = ChannelStatusUi.OPEN, - showReceiving = false, + showReceiving = spark.isReceiving, + receivingUnlimited = spark.isReceiving, + isSpark = true, ) - 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, uiState.exitStep) + 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 +180,198 @@ private fun Content( VerticalSpacer(32.dp) } } - Column( + Buttons( + spark = spark, + onTransferToSavings = onTransferToSavings, + onEmergencyExit = onEmergencyExit, + ) + } +} + +@Composable +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, + 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"), + ) + } + BodyS( + 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?.takeIf { it > 0u }?.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.isUsable, + 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 +408,15 @@ private fun Preview() { uiState = SparkDetailUiState( 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)), ), 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..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 @@ -9,14 +9,22 @@ 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 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.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 import kotlin.time.Duration.Companion.milliseconds @@ -26,18 +34,33 @@ 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() 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.toDetailUi(exit, isOnline), + exitStep = exit.record.exitStep(exit.fundingState), + ) + } + } + } + viewModelScope.launch(bgDispatcher) { + healthRepo.healthState.collect { health -> + _uiState.update { + it.copy( + status = health.spark?.let { s -> if (health.isSparkExiting) HealthState.PENDING else s } + ?: HealthState.ERROR, + ) } + } } viewModelScope.launch(bgDispatcher) { // A cancelled exit's address may still receive a late payment: its balance shows here. @@ -45,17 +68,19 @@ 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) } } } } } } + private fun isOnline() = healthRepo.healthState.map { it.internet == HealthState.READY }.distinctUntilChanged() + fun onPullToRefresh() { viewModelScope.launch { _uiState.update { it.copy(isRefreshing = true) } @@ -63,18 +88,32 @@ 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.toDetailUi( + exit, + healthRepo.healthState.value.internet == HealthState.READY, + ) + ) } delay(500.milliseconds) _uiState.update { it.copy(isRefreshing = false) } } } + + /** 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, withdrawals = withdrawals, isReceiving = isReceiving(isOnline)) } @Immutable data class SparkDetailUiState( val spark: SparkUi? = null, 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/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/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AmountInputViewModel.kt index beb2a439b7..dad0c78604 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) { @@ -145,8 +150,25 @@ 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 + } + + /** + * 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 @@ -169,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 @@ -261,6 +284,7 @@ class AmountInputViewModel @Inject constructor( fun clearInput() { rawInputText = "" + inputUnit = null maxAmount = MAX_AMOUNT _uiState.update { AmountInputUiState() } } @@ -335,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/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8142abb8d9..6c21b02553 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -219,10 +219,10 @@ %1$d/3 تأكيدات إيداع انتظر - إيداعات تمت المطالبة بها - إيداعات قيد التنفيذ + معاملة الإيداع + الإيداعات المبلغ المراد تحويله - تحويل قسري + تحويل قسري إلى المدخرات إلغاء التحويل تعذّر التحقق من عنوان التمويل. حاول مرة أخرى. يعود Spark إلى ما كان عليه. إذا وصلت دفعة إلى عنوان رسوم الطوارئ، يعيدها Bitkit إلى المدخرات. @@ -320,10 +320,11 @@ حول\n<accent>رصيد الإنفاق</accent> تكون أموالك عادةً جاهزة للإنفاق خلال بضع دقائق، دون الحاجة إلى انتظار التأكيدات. تصبح أموالك متاحة بعد 3 تأكيدات، عادةً خلال 30 دقيقة تقريبًا. + Lightspark وBreez وFlashnet المزوّد Spark عبر Breez بلا حد - يُحفظ هذا الرصيد على Spark الذي تديره Lightspark وBreez وFlashnet. يبقى آمنًا ما دام أحدهم على الأقل يتصرف بأمانة. يمكنهم إيقاف الوصول مؤقتًا، والخروج من دونهم يتطلب خروجًا على السلسلة. + يستخدم رصيد الإنفاق Spark، الذي تديره Lightspark وBreez وFlashnet. يعتمد أمانه على تصرّف مشغّل واحد على الأقل بأمانة. يمكن للمشغّلين إيقاف الوصول مؤقتًا، والسحب من دون تعاونهم يتطلب منك بدء خروج على السلسلة. قابل للإنفاق على السلسلة الإنفاق لا تكفي مدخراتك لتغطية هذا التحويل ورسومه. جرّب مبلغًا أصغر. @@ -787,6 +788,8 @@ الأمان الأمان والخصوصية الإعدادات + Bitkit v{version} + {date} في {time} فشل إكمال النسخة الاحتياطية الكاملة جارٍ النسخ الاحتياطي... تم النسخ الاحتياطي @@ -807,6 +810,7 @@ جارٍ المزامنة... متزامن عقدة Lightning + جارٍ التحويل القسري إلى المدخرات... حالة التطبيق مركز المساعدة عنوان البريد الإلكتروني @@ -1825,11 +1829,9 @@ عريض جارٍ تحديث الرصيد… يلزم دفع رسوم الطوارئ - قيد التنفيذ - الخروج الطارئ يستخدم 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 8f093444c3..dde5edbdc1 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -226,10 +226,10 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso + Tx de depósito + Depósitos Monto a transferir - Transferencia forzada + Transferencia forzada a ahorros Cancelar transferencia 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 comisiones de emergencia, Bitkit lo devuelve a tus ahorros. @@ -327,10 +327,11 @@ Acerca de tu\n<accent>saldo de gastos</accent> Tus fondos suelen estar listos para gastar en unos minutos, sin esperar confirmaciones. Tus fondos estarán disponibles tras 3 confirmaciones, normalmente unos 30 minutos. + 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. @@ -808,6 +809,8 @@ Seguridad 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 @@ -828,6 +831,7 @@ Sincronización... Sincronizado Nodo Lightning + Transferencia forzada a ahorros en curso... Estatus del App Centro de ayuda Dirección de correo electrónico @@ -1822,11 +1826,9 @@ Ancho Actualizando saldo… Se necesitan comisiones de emergencia - En curso - Salida de emergencia 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 e8253432d4..5736b9778e 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -223,10 +223,10 @@ %1$d/3 confirmacions Dipòsit Espera - Dipòsits reclamats - Dipòsits en curs + Tx del dipòsit + Dipòsits Import a transferir - Transferència forçosa + Transferència forçosa a estalvis Cancel·lar la transferència 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 comissions d\'emergència, Bitkit el retorna als estalvis. @@ -324,10 +324,11 @@ Sobre el teu\n<accent>saldo de despesa</accent> Els teus fons solen estar llestos per gastar en pocs minuts, sense esperar confirmacions. Els teus fons estaran disponibles després de 3 confirmacions, normalment uns 30 minuts. + 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. @@ -802,6 +803,8 @@ Seguretat 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 @@ -822,6 +825,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 @@ -1822,11 +1826,9 @@ Ample S’està actualitzant el saldo… Calen comissions d\'emergència - En curs - Sortida d\'emergència 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 6c2e710ed0..e4627f480d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -226,10 +226,10 @@ %1$d/3 potvrzení Vklad Počkat - Připsané vklady - Probíhající vklady + Tx vkladu + Vklady Částka k převodu - Vynutit převod + Vynutit převod do úspor Zrušit převod Adresu pro financování se nepodařilo zkontrolovat. Zkuste to znovu. Spark se vrátí do původního stavu. Pokud na adresu pro nouzové poplatky dorazila platba, Bitkit ji pošle zpět do úspor. @@ -327,10 +327,11 @@ O vašem\n<accent>výdajovém zůstatku</accent> Vaše prostředky jsou obvykle připraveny k útratě do několika minut, bez čekání na potvrzení. Vaše prostředky budou dostupné po 3 potvrzeních, obvykle asi za 30 minut. + 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. @@ -807,6 +808,8 @@ Bezpečnost Bezpečnost a soukromí Nastavení + Bitkit v{version} + {date} v {time} Selhalo dokončení úplné zálohy Zálohování... Zálohováno @@ -827,6 +830,7 @@ Synchronizace... Synchronizováno Lightning uzel + Probíhá vynucený převod do úspor... Stav aplikace Centrum pomoci E-mailová adresa @@ -1823,11 +1827,9 @@ Široký Aktualizace zůstatku… Jsou potřeba nouzové poplatky - Probíhá - Nouzový odchod 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 26d6fb8f16..24631a0cb8 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -108,10 +108,10 @@ %1$d/3 Bestätigungen Einzahlung Warten - Eingelöste Einzahlungen - Laufende Einzahlungen + Einzahlungs-Tx + Einzahlungen Übertragungsbetrag - Übertragung forcieren + Übertragung zum Sparkonto forcieren Übertragung abbrechen Die Finanzierungsadresse konnte nicht geprüft werden. Versuche es erneut. Spark kehrt in den vorherigen Zustand zurück. Wenn eine Zahlung die Adresse für Notfallgebühren erreicht hat, sendet Bitkit sie zurück auf dein Sparkonto. @@ -209,10 +209,11 @@ Über dein\n<accent>Ausgaben-Guthaben</accent> Deine Mittel sind meist innerhalb weniger Minuten verfügbar, ohne auf Bestätigungen zu warten. Deine Mittel sind nach 3 Bestätigungen verfügbar, meist nach etwa 30 Minuten. + 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 @@ -654,6 +655,8 @@ Allgemein Sicherheit und Privatsphäre Fortgeschritten + Bitkit v{version} + Forcierte Übertragung zum Sparkonto läuft... Support Systemeinstellungen Sprache @@ -789,6 +792,7 @@ Vollständiges Backup Abgeschlossen In Bearbeitung... + {date} um {time} Fehlgeschlagen Zahlungen Netzwerke @@ -1821,11 +1825,9 @@ Breit Kontostand wird aktualisiert… Notfallgebühren nötig - Läuft - Notausstieg 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 3efb1f358e..790f3fc748 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -219,10 +219,10 @@ %1$d/3 επιβεβαιώσεις Κατάθεση Αναμονή - Εξαργυρωμένες καταθέσεις - Καταθέσεις σε εξέλιξη + Συναλλαγή κατάθεσης + Καταθέσεις Ποσό μεταφοράς - Αναγκαστική μεταφορά + Αναγκαστική μεταφορά σε αποταμιεύσεις Ακύρωση μεταφοράς Δεν ήταν δυνατός ο έλεγχος της διεύθυνσης χρηματοδότησης. Δοκιμάστε ξανά. Το Spark επιστρέφει όπως ήταν. Αν μια πληρωμή έφτασε στη διεύθυνση έκτακτων τελών, το Bitkit την επιστρέφει στις αποταμιεύσεις. @@ -320,10 +320,11 @@ Σχετικά με το\n<accent>υπόλοιπο δαπανών</accent> Τα κεφάλαιά σου είναι συνήθως έτοιμα για χρήση μέσα σε λίγα λεπτά, χωρίς αναμονή για επιβεβαιώσεις. Τα κεφάλαιά σου γίνονται διαθέσιμα μετά από 3 επιβεβαιώσεις, συνήθως σε περίπου 30 λεπτά. + Lightspark, Breez και Flashnet Πάροχος Spark μέσω Breez - Χωρίς όριο - Αυτό το υπόλοιπο φυλάσσεται στο Spark, που λειτουργούν οι Lightspark, Breez και Flashnet. Είναι ασφαλές όσο τουλάχιστον ένας από αυτούς ενεργεί έντιμα. Μπορούν να αναστείλουν την πρόσβαση, και η έξοδος χωρίς αυτούς απαιτεί έξοδο on-chain. + χωρίς όριο + Το υπόλοιπο δαπανών σου χρησιμοποιεί το Spark, που λειτουργούν οι Lightspark, Breez και Flashnet. Η ασφάλειά του εξαρτάται από το να ενεργεί έντιμα τουλάχιστον ένας διαχειριστής. Οι διαχειριστές μπορούν να αναστείλουν την πρόσβαση, και η ανάληψη χωρίς τη συνεργασία τους απαιτεί να ξεκινήσεις έξοδο on-chain. Διαθέσιμα onchain Δαπάνες Οι αποταμιεύσεις σου δεν επαρκούν για αυτή τη μεταφορά και τα τέλη της. Δοκίμασε μικρότερο ποσό. @@ -787,6 +788,8 @@ Ασφάλεια Ασφάλεια και απόρρητο Ρυθμίσεις + Bitkit v{version} + {date} στις {time} Αποτυχία ολοκλήρωσης πλήρους αντιγράφου ασφαλείας Δημιουργία αντιγράφου... Δημιουργήθηκε αντίγραφο @@ -807,6 +810,7 @@ Συγχρονισμός... Συγχρονισμένο Κόμβος Lightning + Αναγκαστική μεταφορά σε αποταμιεύσεις σε εξέλιξη... Κατάσταση εφαρμογής Κέντρο βοήθειας Διεύθυνση email @@ -1821,11 +1825,9 @@ Φαρδύ Ενημέρωση υπολοίπου… Απαιτούνται έκτακτα τέλη - Σε εξέλιξη - Έξοδος Έκτακτης Ανάγκης Χρήση 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 6e6389ba7a..6854976c7c 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -225,10 +225,10 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso + Tx de depósito + Depósitos Importe a transferir - Forzar transferencia + Forzar transferencia a ahorros Cancelar transferencia 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 comisiones de emergencia, Bitkit lo devuelve a tus ahorros. @@ -326,10 +326,11 @@ Acerca de tu\n<accent>saldo de gastos</accent> Tus fondos suelen estar listos para gastar en unos minutos, sin esperar confirmaciones. Tus fondos estarán disponibles tras 3 confirmaciones, normalmente unos 30 minutos. + 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. @@ -805,6 +806,8 @@ Seguridad Seguridad y Privacidad Ajustes + Bitkit v{version} + {date} a las {time} Falló al hacer una copia de seguridad completa Haciendo copia... Copia realizada @@ -825,6 +828,7 @@ Sincronizando... Sincronizado Nodo Lightning + Transferencia forzada a ahorros en curso... Estado de la App Centro de Ayuda Dirección Email @@ -1822,11 +1826,9 @@ Ancho Actualizando saldo… Se necesitan comisiones de emergencia - En curso - Salida de emergencia 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 2caf07ae43..0e1a5b9e4e 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -167,10 +167,10 @@ %1$d/3 confirmaciones Depósito Esperar - Depósitos reclamados - Depósitos en curso + Tx de depósito + Depósitos Importe a transferir - Forzar transferencia + Forzar transferencia a ahorros Cancelar transferencia 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 comisiones de emergencia, Bitkit lo devuelve a tus ahorros. @@ -268,10 +268,11 @@ Acerca de tu\n<accent>saldo de gastos</accent> Tus fondos suelen estar listos para gastar en unos minutos, sin esperar confirmaciones. Tus fondos estarán disponibles tras 3 confirmaciones, normalmente unos 30 minutos. + 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 @@ -653,6 +654,8 @@ Avanzado Ajustes del sistema Idioma + Bitkit v{version} + Transferencia forzada a ahorros en curso... Soporte Legal Compartir @@ -786,6 +789,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 @@ -1822,11 +1826,9 @@ Ancho Actualizando saldo… Se necesitan comisiones de emergencia - En curso - Salida de emergencia 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 8d7a39bded..1d14c19336 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -107,10 +107,10 @@ %1$d/3 confirmations Dépôt Attendre - Dépôts réclamés - Dépôts en cours + Tx de dépôt + Dépôts Montant à transférer - Forcer le transfert + Forcer le transfert vers l\'Épargne Annuler le transfert Impossible de vérifier l\'adresse de financement. Réessayez. Spark revient à son état précédent. Si un paiement a atteint l\'adresse des frais d\'urgence, Bitkit le renvoie vers l\'épargne. @@ -208,10 +208,11 @@ À propos de votre\n<accent>solde de dépenses</accent> Vos fonds sont généralement disponibles en quelques minutes, sans attendre de confirmations. Vos fonds deviennent disponibles après 3 confirmations, généralement environ 30 minutes. + 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 @@ -656,6 +657,8 @@ Langue Sécurité et vie privée Avancé + Bitkit v{version} + Transfert forcé vers l\'Épargne en cours... Support Juridique Partager @@ -786,6 +789,7 @@ Dernière sauvegarde complète Sauvegardé Sauvegarde... + {date} à {time} Échec de la sauvegarde Paiements Réseaux @@ -1822,11 +1826,9 @@ Large Mise à jour du solde… Frais d\'urgence requis - En cours - Sortie d\'urgence 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 baa9e08b1a..e5783d5bd7 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -224,10 +224,10 @@ %1$d/3 conferme Deposito Attendi - Depositi riscattati - Depositi in corso + Tx di deposito + Depositi Importo da trasferire - Trasferimento forzato + Trasferimento forzato ai Risparmi Annulla trasferimento Impossibile verificare l\'indirizzo di finanziamento. Riprova. Spark torna com\'era prima. Se un pagamento ha raggiunto l\'indirizzo delle commissioni di emergenza, Bitkit lo rimanda ai risparmi. @@ -325,10 +325,11 @@ Info sul tuo\n<accent>saldo di spesa</accent> I tuoi fondi sono di solito pronti da spendere in pochi minuti, senza attendere conferme. I tuoi fondi diventano disponibili dopo 3 conferme, di solito circa 30 minuti. + 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. @@ -804,6 +805,8 @@ Sicurezza Sicurezza e Privacy Impostazioni + Bitkit v{version} + {date} alle {time} Impossibile completare un backup completo Backup in esecuzione... Backup eseguito @@ -824,6 +827,7 @@ Sincronizzazione... Sincronizzato Nodo Lightning + Trasferimento forzato ai risparmi in corso... Stato dell\'app Centro assistenza Indirizzo e-mail @@ -1822,11 +1826,9 @@ Largo Aggiornamento del saldo… Commissioni di emergenza necessarie - In corso - Uscita di Emergenza 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 4eb48d34e6..cc4cc8433b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -223,10 +223,10 @@ %1$d/3 bevestigingen Storting Wachten - Geclaimde stortingen - Lopende stortingen + Stortings-tx + Stortingen Bedrag om over te boeken - Overboeking forceren + Overboeking naar spaargeld forceren Overboeking annuleren Kon het financieringsadres niet controleren. Probeer opnieuw. Spark keert terug naar hoe het was. Als er een betaling op het adres voor de noodkosten is aangekomen, stuurt Bitkit die terug naar spaargeld. @@ -324,10 +324,11 @@ Over je\n<accent>bestedingssaldo</accent> Je geld is meestal binnen een paar minuten klaar om te besteden, zonder op bevestigingen te wachten. Je geld is beschikbaar na 3 bevestigingen, meestal na ongeveer 30 minuten. + 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. @@ -802,6 +803,8 @@ Veiligheid Beveiliging en privacy Instellingen + Bitkit v{version} + {date} om {time} Volledige backup niet voltooid Back-up maken... Geback-upt @@ -822,6 +825,7 @@ Synchroniseren... Gesynchroniseerd Lightning Node + Geforceerde overboeking naar spaargeld bezig... App-status Helpcentrum E-mailadres @@ -1821,11 +1825,9 @@ Breed Saldo bijwerken… Noodkosten nodig - Bezig - Noodexit 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 2ba2c4c4aa..b9b6e5cf83 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -109,10 +109,10 @@ %1$d/3 potwierdzeń Wpłata Czekaj - Odebrane wpłaty - Wpłaty w toku + Tx wpłaty + Wpłaty Kwota do przesłania - Wymuś transfer + Wymuś transfer na oszczędności Anuluj transfer Nie udało się sprawdzić adresu finansowania. Spróbuj ponownie. Spark wraca do poprzedniego stanu. Jeśli płatność dotarła na adres opłat awaryjnych, Bitkit odeśle ją do Oszczędności. @@ -210,10 +210,11 @@ O Twoim\n<accent>saldzie wydatków</accent> Twoje środki są zwykle gotowe do wydania w ciągu kilku minut, bez czekania na potwierdzenia. Twoje środki będą dostępne po 3 potwierdzeniach, zwykle po około 30 minutach. + 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 @@ -657,6 +658,8 @@ Ogólne Bezpieczeństwo i prywatność Zaawansowane + Bitkit v{version} + Trwa wymuszony transfer na oszczędności... Wsparcie Prawne Udostępnij @@ -792,6 +795,7 @@ Ostatnia kopia zapasowa Zapisano Zapisywanie... + {date} o {time} Nie udało się wykonać kopii zapasowej Płatności Sieci @@ -1823,11 +1827,9 @@ Szeroki Aktualizowanie salda… Potrzebne opłaty awaryjne - W toku - Wyjście awaryjne 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 1c9b6c67ca..cef87c8aa6 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -227,10 +227,10 @@ %1$d/3 confirmações Depósito Esperar - Depósitos resgatados - Depósitos em andamento + Tx de depósito + Depósitos Valor a transferir - Forçar transferência + Forçar Transferência Para Poupança Cancelar transferência 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 das taxas de emergência, a Bitkit o devolve para a poupança. @@ -328,10 +328,11 @@ Sobre seu\n<accent>saldo de gastos</accent> Seus fundos geralmente ficam prontos para gastar em poucos minutos, sem esperar confirmações. Seus fundos ficam disponíveis após 3 confirmações, geralmente em cerca de 30 minutos. + 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. @@ -809,6 +810,8 @@ Segurança Segurança e Privacidade Ajustes + Bitkit v{version} + {date} às {time} Falha ao concluir backup Fazendo o backup... Backup Feito @@ -829,6 +832,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 @@ -1822,11 +1826,9 @@ Largo Atualizando saldo… Taxas de emergência necessárias - Em andamento - Saída de Emergência 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 6e8a1f7991..1af2790b77 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -104,10 +104,10 @@ %1$d/3 confirmações Depósito Esperar - Depósitos resgatados - Depósitos em curso + Tx de depósito + Depósitos Montante a transferir - Forçar transferência + Forçar Transferência Para Poupança Cancelar transferência 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 das taxas de emergência, a Bitkit devolve-o à poupança. @@ -205,10 +205,11 @@ Sobre o seu\n<accent>saldo de gastos</accent> Os seus fundos ficam normalmente prontos a gastar em poucos minutos, sem esperar por confirmações. Os seus fundos ficam disponíveis após 3 confirmações, normalmente cerca de 30 minutos. + 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 @@ -635,6 +636,8 @@ Geral Segurança e Privacidade Avançado + Bitkit v{version} + Transferência forçada para a poupança em curso... Suporte Legal Compartilhar @@ -752,6 +755,7 @@ Último Backup Completo Backup Feito Fazendo o backup... + {date} às {time} Falha ao concluir backup Pagamentos Redes @@ -1822,11 +1826,9 @@ Largo A atualizar o saldo… Taxas de emergência necessárias - Em curso - Saída de Emergência 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 e06ffdadb0..eeea28e188 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -235,10 +235,10 @@ %1$d/3 подтверждений Депозит Ждать - Зачисленные депозиты - Депозиты в обработке + Транзакция депозита + Депозиты Сумма перевода - Принудительный перевод + Принудительный перевод в сбережения Отменить перевод Не удалось проверить адрес пополнения. Попробуйте ещё раз. Spark вернётся в прежнее состояние. Если на адрес экстренных комиссий пришёл платёж, Bitkit вернёт его в сбережения. @@ -336,10 +336,11 @@ О вашем\n<accent>балансе расходов</accent> Ваши средства обычно готовы к использованию через несколько минут, без ожидания подтверждений. Ваши средства станут доступны после 3 подтверждений, обычно примерно через 30 минут. + Lightspark, Breez и Flashnet Провайдер Spark через Breez - Без ограничений - Этот баланс хранится в Spark, которым управляют Lightspark, Breez и Flashnet. Он в безопасности, пока хотя бы один из них действует честно. Они могут приостановить доступ, а выход без них требует ончейн-вывода. + без ограничений + Ваш баланс расходов использует Spark, которым управляют Lightspark, Breez и Flashnet. Его безопасность зависит от того, что хотя бы один оператор действует честно. Операторы могут приостановить доступ, а чтобы вывести средства без их участия, вам придётся запустить ончейн-вывод. Доступно Onchain Расходы Ваших сбережений не хватает на этот перевод и его комиссии. Попробуйте меньшую сумму. @@ -821,6 +822,8 @@ Безопасность Безопасность и Конфиденциальность Настройки + Bitkit v{version} + {date} в {time} Не удалось выполнить полное резервное копирование Резервное копирование... Скопировано @@ -841,6 +844,7 @@ Синхронизация... Синхронизировано Лайтнинг-нода + Идёт принудительный перевод в сбережения... Статус Приложения Центр Помощи Электронная Почта @@ -1837,11 +1841,9 @@ Широкий Обновление баланса… Нужны экстренные комиссии - Выполняется - Экстренный Выход Через Spark - Не в сети + Не в сети... Подключение... Подключено - Spark + Провайдер Lightning (Spark) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0b68747204..f06bfe34c6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -420,10 +420,10 @@ %1$d/3 confirmations Deposit Wait - Claimed deposits - Deposits in progress + Deposit tx + Deposits Amount to transfer - Force transfer + Force Transfer To Savings Cancel transfer Couldn\'t check the funding address. Try again. Spark goes back to how it was. If a payment reached the emergency fees address, Bitkit sends it back to savings. @@ -522,10 +522,11 @@ About your\n<accent>spending balance</accent> Your funds are usually ready to spend within a few minutes, no need to wait for confirmations. Your funds become available after 3 confirmations, usually around 30 minutes. + 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. @@ -1168,6 +1169,8 @@ Warn when sending over $100 Security Settings + Bitkit v{version} + {date} at {time} Failed to complete a full backup Backing up... Backed up @@ -1177,8 +1180,6 @@ Connected Bitcoin Node Emergency fees needed - In progress - Emergency Exit Disconnected Reconnecting... Connected @@ -1192,10 +1193,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/ext/BackupTimestampTest.kt b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt new file mode 100644 index 0000000000..e7d28659e6 --- /dev/null +++ b/app/src/test/java/to/bitkit/ext/BackupTimestampTest.kt @@ -0,0 +1,56 @@ +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 at 11:45", time.toBackupTimestamp(is24Hour = true, locale = Locale.US, zone = utc)) + } + + @Test + fun `toBackupTimestamp follows the UK pattern`() { + 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`() { + 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 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 = Locale.US, zone = utc) + + // CLDR versions differ in the space before PM. + assertEquals("Jan 2, 2023 at 11:45 PM", text.replace('\u202F', ' ').replace('\u00A0', ' ')) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/CurrencyRepoTest.kt index 342cce6162..8978402884 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 @@ -154,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))) @@ -294,6 +316,35 @@ 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") + 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) + 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") + } } private class CurrencyRepoTestError(message: String) : AppError(message) 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/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 597177f9a3..aef2f50598 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2734,12 +2734,55 @@ class SparkRepoTest : BaseUnitTest() { sut.refreshState().getOrThrow() sut.holdForExit() // The exit's reconnect disconnected Spark, then failed to connect it. + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) } + .thenThrow(RuntimeException("operators unreachable")) + .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() + + verify(sparkService, times(2)).connect(0, true) + 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") + assertTrue(sut.state.value.hasReadState, "a lost connection hid the state Spark read") + assertEquals(10_000uL, sut.state.value.balanceSats) + } + + @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) - whenever { sparkService.connect(any(), any()) }.thenReturn(true) sut.reconnectForExit() - verify(sparkService).connect(0, true) + verify(sparkService, never()).connect(any(), any()) } @Test 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/components/MoneyTextTest.kt b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt new file mode 100644 index 0000000000..bc839e82ed --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/components/MoneyTextTest.kt @@ -0,0 +1,66 @@ +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 +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.LocalCurrencies +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") + } + + @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() + } +} 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)) 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 a7dc707fea..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 @@ -47,10 +51,12 @@ 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())) whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) } private fun createSut(): AppStatusViewModel { @@ -59,6 +65,7 @@ class AppStatusViewModelTest : BaseUnitTest() { healthRepo = healthRepo, lightningRepo = lightningRepo, sparkExitRepo = sparkExitRepo, + sparkRepo = sparkRepo, cacheStore = cacheStore, ) } @@ -151,25 +158,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() @@ -237,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/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/SparkDetailScreenTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt new file mode 100644 index 0000000000..9d64583e7c --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailScreenTest.kt @@ -0,0 +1,108 @@ +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 `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) + + 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..0920d233c7 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkDetailViewModelTest.kt @@ -0,0 +1,132 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.collections.immutable.persistentListOf +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.repositories.SparkWithdrawal +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 sparkState = MutableStateFlow(SparkState()) + private val lightningRepo = mock() + private val sparkRepo = mock() + private val sparkExitRepo = mock() + private val healthRepo = mock() + + @Before + fun setUp() { + whenever(sparkRepo.state).thenReturn(sparkState) + whenever(sparkExitRepo.state).thenReturn(exitState) + 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 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 `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) + sut.onPullToRefresh() + 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")) + healthState.value = AppHealthState(spark = null) + + val sut = createSut() + + 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 d00e9bf478..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 @@ -2,12 +2,14 @@ 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 import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue class SparkUiTest : BaseUnitTest() { @@ -37,5 +39,40 @@ 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 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") + 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") + } + + @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 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) } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/AmountInputViewModelTest.kt index 2ff8dc23c9..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 @@ -89,6 +90,48 @@ 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 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)) } + 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 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. diff --git a/docs/screens-map.md b/docs/screens-map.md index cae3a8b81f..1c5043b780 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 | Force transfer to Savings (Spark emercency exit) › Force Transfer to Savings Confirm | | SparkExitFeeBumpScreen.kt | `todo` | | SparkExitFundingScreen.kt | Force transfer to Savings (Spark emercency exit) › Force Transfer to Savings Emercency fees / Force Transfer to Savings Emercency fees External | diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml index ce30a4bf6c..209f011195 100644 --- a/journeys/settings/app-status-emergency-exit.xml +++ b/journeys/settings/app-status-emergency-exit.xml @@ -1,22 +1,23 @@ - While a Spark force transfer (emergency exit) is active, App Status shows an "Emergency Exit" row under Lightning Connection. - It reads "Emergency fees needed" while the exit asks for fee funding and "In progress" otherwise, including + While a Spark force transfer (emergency exit) is active, App Status shows it on the "Lightning Provider (Spark)" + row under Lightning Connection, with a yellow warning icon. It reads "Emergency fees 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 a force transfer from Spark (spark emergency exit journey), paid from savings, and swipe to start it. Starting a force transfer 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 "Continue Using Bitkit" (testTag "SparkExitProgressOk") and verify App Status shows again with the "Emergency Exit" row still there + Tap "Continue Using Bitkit" (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 3b4115c537..2fd3cede8a 100644 --- a/journeys/transfer/spark-emergency-exit.xml +++ b/journeys/transfer/spark-emergency-exit.xml @@ -1,7 +1,7 @@ Verifies the Spark force transfer (the emergency exit) up to the swipe. With a Spark balance, the Spark connection - screen shows "Force transfer" (testTag "SparkEmergencyExit") under "Transfer to Savings". It opens the "Force + screen shows "Force Transfer To Savings" (testTag "SparkEmergencyExit") under "Transfer To Savings". It opens the "Force Transfer" intro, then the "Transfer overview", which asks the SDK's prepareRecoverFunds for every leaf and lists "Amount to transfer", "Network fees" and "You receive (estimate)" under "Overview". When the transfer needs emergency fees, Continue leads to the "Emergency fees" screen: one row, "Deducted from your Savings balance*" when @@ -21,12 +21,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 "Force transfer" (testTag "SparkEmergencyExit") shows under it - Tap "Force transfer" and verify the "Force Transfer" intro says your funds may be unavailable for up to 4 weeks + 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 "Force Transfer" intro says your funds may be unavailable for up to 4 weeks Tap "Continue" (testTag "SparkExitIntroContinue") and verify the "Transfer overview" screen shows "Getting the costs…" and then "Amount to transfer", "Network fees" and "You receive (estimate)" Verify no reason shows in red (testTag "SparkExitQuoteBlocked") and "Continue" (testTag "SparkExitQuoteContinue") is enabled Tap "Continue" and verify the "Emergency fees" screen shows one amount, "Deducted from your Savings balance*" (testTag "SparkExitFeesSavings"), and the note that unused fees return to savings Tap "Continue" (testTag "SparkExitFundingContinue") and verify "Please confirm" lists the overview and the emergency fees, with a yellow swipe - 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