Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9a45627
feat: spark connection and app status design
ovitrif Nov 17, 2026
63cd701
fix: show an unconfirmed spark deposit as pending
ovitrif Nov 17, 2026
3540dde
chore: add changelog fragment
ovitrif Nov 17, 2026
54acd5a
fix: drop spark's unlimited receiving while offline
ovitrif Nov 17, 2026
65a0d29
chore: translate spark connection and status strings
ovitrif Nov 18, 2026
44d854e
fix: match spark bar, node status and backup date to figma
ovitrif Nov 18, 2026
16be32e
fix: follow the device clock format for the backup time
ovitrif Nov 18, 2026
7409d13
fix: read the backup date as date at time
ovitrif Nov 18, 2026
f836776
fix: show a running force transfer on the spark connection screen
ovitrif Nov 18, 2026
55d53c1
fix: show receiving on an empty spark connection
ovitrif Nov 18, 2026
ae4e293
fix: keep receiving on an empty spark after a refresh
ovitrif Nov 18, 2026
aeb0628
chore: merge master into spark connection status
ovitrif Nov 18, 2026
5c5dd5b
fix: set the spark trust note in the frame's small body text
ovitrif Nov 18, 2026
1f11f45
fix: spark not ready after a failed exit reconnect
ovitrif Nov 19, 2026
55f1970
fix: spark readiness after a disconnected refresh
ovitrif Nov 19, 2026
9badbca
Merge remote-tracking branch 'origin/master' into feat/spark-connecti…
ovitrif Nov 19, 2026
9166d80
fix: keep offline spark's last known state shown
ovitrif Nov 19, 2026
72c9eb3
fix: keep fees in bitcoin without an exchange rate
ovitrif Nov 19, 2026
f850745
fix: keep bitcoin fees and offline spark history shown
ovitrif Nov 19, 2026
45ba38e
fix: treat only a positive exchange rate as a rate
ovitrif Nov 19, 2026
0a643ed
fix: redraw a typed amount after a unit switch elsewhere
ovitrif Nov 19, 2026
ed58bac
fix: show bitcoin fees without a usable rate
ovitrif Nov 19, 2026
4dccc2a
fix: show transfer change toasts in bitcoin without a usable rate
ovitrif Nov 19, 2026
5020b49
fix: keep redrawn amounts editable and rates checked
ovitrif Nov 19, 2026
3d9cf92
fix: show bitcoin captions without a fiat rate
ovitrif Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions app/src/main/java/to/bitkit/ext/DateTime.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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"

Expand Down
15 changes: 14 additions & 1 deletion app/src/main/java/to/bitkit/repositories/CurrencyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Comment thread
ovitrif marked this conversation as resolved.
Resolved

val CurrencyState.paykitRate: PaykitExchangeRate?
get() = rates.firstOrNull {
it.quote == "USD"
Expand Down
36 changes: 19 additions & 17 deletions app/src/main/java/to/bitkit/repositories/HealthRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
) {
Expand All @@ -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(
Expand All @@ -64,6 +66,7 @@ class HealthRepo @Inject constructor(
channels = newHealthState.channels,
isLightningViaSpark = newHealthState.isLightningViaSpark,
spark = newHealthState.spark,
isSparkExiting = newHealthState.isSparkExiting,
)
}
}
Expand Down Expand Up @@ -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())
}
}
}
Expand All @@ -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
}
}
}
28 changes: 23 additions & 5 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand All @@ -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.
Expand All @@ -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) }
}

Expand Down Expand Up @@ -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 ->
Expand Down Expand Up @@ -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. */
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/to/bitkit/ui/components/FeeInfo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down
63 changes: 55 additions & 8 deletions app/src/main/java/to/bitkit/ui/components/LightningChannel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
}
}
}
}
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
37 changes: 14 additions & 23 deletions app/src/main/java/to/bitkit/ui/components/Money.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
"<accent>${btc.symbol}</accent> ${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) "<accent>$BITCOIN_SYMBOL</accent> $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
Expand Down Expand Up @@ -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("<accent>${btcComponents.symbol}</accent> ")
append(btcComponents.value)
if (showSymbol) append("<accent>$BITCOIN_SYMBOL</accent> ")
append(sats.formatMoney(currencies.displayUnit))
}
} else {
val converted = currency.convert(sats) ?: return@remember null
Comment thread
ovitrif marked this conversation as resolved.
Resolved
buildString {
if (showSymbol && !converted.isSymbolSuffix) append("<accent>${converted.symbol}</accent> ")
append(converted.formatted)
Expand Down
Loading