Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
420d613
feat: spark transfer to savings and force transfer design
ovitrif Nov 17, 2026
d5a1de1
fix: match force transfer spacing to figma
ovitrif Nov 17, 2026
3663ad1
fix: widen force transfer confirm table gaps
ovitrif Nov 17, 2026
09a5d85
chore: add changelog fragment
ovitrif Nov 17, 2026
6823000
fix: show returned amounts without raw accent tags
ovitrif Nov 17, 2026
aea14d8
fix: let a failed pay-to-confirm start retry
ovitrif Nov 17, 2026
001e203
fix: show the fee amount on force transfer progress
ovitrif Nov 17, 2026
ee8c419
fix: show force transfer amounts without an exchange rate
ovitrif Nov 17, 2026
ee6c817
fix: name spark under open connections in the move to spark journey
ovitrif Nov 17, 2026
5066fca
chore: translate spark transfer to savings strings
ovitrif Nov 18, 2026
d003628
fix: hide the refresh spinner on force transfer progress entry
ovitrif Nov 18, 2026
ff738a6
fix: trim force transfer overview and progress to figma
ovitrif Nov 18, 2026
cda0b44
fix: title-case the force transfer done button
ovitrif Nov 18, 2026
bf3ae64
fix: split returned fee funding from the spending balance
ovitrif Nov 18, 2026
5eca93f
fix: keep a replaced sweep's returned funding as fees
ovitrif Nov 18, 2026
d00bc51
fix: hold pay to confirm while a force transfer starts
ovitrif Nov 18, 2026
49cd43b
fix: show a starting force transfer on pay to confirm
ovitrif Nov 18, 2026
4134b9a
fix: match force transfer screens to v64 frames
ovitrif Nov 18, 2026
e6f8b0e
fix: keep unconfirmed leftover sweeps on the completed screen
ovitrif Nov 18, 2026
8e36808
fix: keep watching the funding address after a cancelled back swipe
ovitrif Nov 18, 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
122 changes: 85 additions & 37 deletions app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package to.bitkit.repositories

import breez_sdk_spark.CpfpInput
import breez_sdk_spark.ExitTransactionStatus
import breez_sdk_spark.PrepareRecoverFundsResponse
import breez_sdk_spark.RecoverFundsResponse
Expand All @@ -11,6 +12,7 @@ import to.bitkit.models.FeeRate
import to.bitkit.models.safe
import to.bitkit.utils.AppError
import to.bitkit.utils.BlockTimeHelpers
import to.bitkit.utils.SignedTransactionId
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.time.Duration
Expand Down Expand Up @@ -71,8 +73,8 @@ object SparkExitFundingKey {

/**
* What an exit costs and returns, from a `prepareRecoverFunds` quote, next to Spark's balance when it was taken
* ([sparkBalanceSats]), so value the quote cannot exit is named rather than silently left out. [lostLeafSats] are the
* values of the leaves an older state claimed that the operators still list, which the quote leaves out.
* ([sparkBalanceSats]), so value the quote cannot exit is counted as staying on Spark. [lostLeafSats] are the values of
* the leaves an older state claimed that the operators still list, which the quote leaves out.
*/
data class SparkExitQuote(
val prepared: PrepareRecoverFundsResponse,
Expand All @@ -96,8 +98,6 @@ data class SparkExitQuote(
*/
val incomingSats: ULong get() = receiveSats.safe() + fundingSats.safe()

val leftBehindSats: ULong get() = prepared.skipped.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }

val leafIds: List<String> get() = prepared.leaves.map { it.leafId }

/** Each listed leaf's value, kept with the exit for a leaf its first build leaves behind. */
Expand All @@ -106,12 +106,6 @@ data class SparkExitQuote(
/** The value of the leaves the quote lists, which the exit takes on-chain. */
val leafTotalSats: ULong get() = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }

/**
* What the quote cannot exit now: the leaves it skips, and Spark's balance beyond every leaf it lists, such as a
* counter-swap still unclaimed. Null when nothing.
*/
val unexitableSats: ULong? get() = SparkExitMath.unexitableSats(sparkBalanceSats, this)

/**
* What stays on Spark once the exit took its leaves: Spark's balance beyond them, skipped leaves included, less the
* lost leaves it still counts until a sync drops them. Null when nothing.
Expand All @@ -121,20 +115,6 @@ data class SparkExitQuote(
?.let { SparkExitMath.beyondLostLeaves(it, lostLeafSats) }
?.takeIf { it > 0uL }

/** Spark's balance beyond every leaf the quote lists, skipped ones included, less the lost leaves it holds. */
val beyondLeavesSats: ULong?
get() {
val leaves = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }
val beyond = SparkExitMath.outsideExitSats(leaves.safe() + leftBehindSats.safe(), sparkBalanceSats)
return beyond?.let { SparkExitMath.beyondLostLeaves(it, lostLeafSats) }?.takeIf { it > 0uL }
}

/**
* How many UTXOs the SDK splits the fee funding into, one per transaction it fee-bumps under per-node funding: the
* funding screen names it when more than one.
*/
val fundedSteps: Int get() = prepared.funding?.perBranch?.size ?: 0

/** Breez's rule: only exit when the value is more than its fees. */
val isWorthExiting: Boolean get() = prepared.leaves.isNotEmpty() && exitSats > networkFeeSats
}
Expand Down Expand Up @@ -199,6 +179,78 @@ object SparkExitMath {
return (record.earlierReceivedSats + current).values.fold(0uL) { sum, sats -> sum.safe() + sats.safe() }
}

/**
* The unspent fee funding the SWEEP steps of [record]'s recovery return to savings, with what the confirmed sweeps
* of replaced generations returned ([SparkExitRecord.earlierReturnedFundingSats]).
*/
fun returnedFundingSats(record: SparkExitRecord): ULong {
val current = record.recovery?.let { sweepFunding(record.fundingInputs, it) }.orEmpty()
return (record.earlierReturnedFundingSats + current).values
.fold(0uL) { sum, sats -> sum.safe() + sats.safe() }
}

/**
* The fee funding each SWEEP step of [recovery] returns, by txid: the value of its inputs that spend the funding
* address, which are funding UTXOs ([fundingInputs] and the recovery's own) and the outputs of a CPFP child or the
* fan-out. An input whose parent this recovery does not hold, such as an earlier generation's CPFP change, is not
* counted. Only confirmed sweeps when [confirmedOnly].
*/
fun sweepFunding(
fundingInputs: List<CpfpInput>,
recovery: RecoverFundsResponse,
confirmedOnly: Boolean = false,
): Map<String, ULong> {
val funding = (fundingInputs + recovery.fundingInputs)
.filterIsInstance<CpfpInput.P2wpkh>()
.associate { "${it.txid}:${it.vout}" to it.valueSats }
val children = recovery.transactions.mapNotNull { tx ->
val hex = tx.cpfpTxHex ?: return@mapNotNull null
runCatching { SignedTransactionId.fromHex(hex) }.getOrNull()?.let { it to hex }
}
val fanOuts = recovery.transactions.filter { it.kind == RecoveryTxKind.FAN_OUT }.map { it.txid to it.txHex }
val parents = (children + fanOuts).toMap()
val counted = mutableSetOf<String>()
return recovery.transactions
.filter { it.kind == RecoveryTxKind.SWEEP }
.filter { !confirmedOnly || it.status is ExitTransactionStatus.Confirmed }
.associate { tx ->
val sats = SparkExitTxInputs.decode(tx.txHex).orEmpty()
.filter { counted.add("${it.prevTxid}:${it.vout}") }
.mapNotNull { input ->
funding["${input.prevTxid}:${input.vout}"]
?: parents[input.prevTxid]
?.let { SparkExitTxOutputs.decode(it) }
?.getOrNull(input.vout.toInt())
?.valueSats
}
.fold(0uL) { sum, value -> sum.safe() + value.safe() }
tx.txid to sats
}
.filterValues { it > 0uL }
}

/** The leftover fee funding the ended exit swept back on its own: earlier sweeps and the confirmed last one. */
fun sweptLeftoverSats(record: SparkExitRecord): ULong {
val swept = record.sweptLeftover.fold(0uL) { sum, leftover -> sum.safe() + leftover.valueSats.safe() }
val sending = record.leftoverSweep?.takeIf { it.isConfirmed }?.valueSats ?: 0uL
return swept.safe() + sending.safe()
}

/**
* What the ended exit returned to savings, split as the done screen names it: [receivedSats] less the fee funding
* the main sweep returned is the spending balance, which bears the sweep's own fee; that funding and
* [sweptLeftoverSats] are the emergency fees it did not spend. Null when the destination cannot be read.
*/
fun returned(record: SparkExitRecord): SparkExitReturned? {
val received = receivedSats(record) ?: return null
// Capped at what was received, so the two parts always add up to what reached savings.
val funding = minOf(returnedFundingSats(record), received)
return SparkExitReturned(
spendingSats = received - funding,
feesSats = sweptLeftoverSats(record).safe() + funding.safe(),
)
}

/** What the confirmed SWEEP and COOPERATIVE steps of [recovery] paid [destination], by txid. */
fun confirmedReceived(recovery: RecoverFundsResponse, destination: String): Map<String, ULong> {
val script = runCatching { AddressScript.of(destination) }.getOrNull() ?: return emptyMap()
Expand Down Expand Up @@ -300,12 +352,6 @@ object SparkExitMath {
return fundedSats.safe() + maxOf(missing, 1uL).safe()
}

/** The skipped leaves of [quote] plus Spark's [balanceSats] beyond every leaf it lists, or null when nothing. */
fun unexitableSats(balanceSats: ULong?, quote: SparkExitQuote): ULong? {
val beyond = quote.copy(sparkBalanceSats = balanceSats).beyondLeavesSats ?: 0uL
return (quote.leftBehindSats.safe() + beyond.safe()).takeIf { it > 0uL }
}

/**
* What Spark's [balanceSats] holds beyond [record]'s leaves, in any phase: what a stopped exit leaves on Spark,
* such as value it could not exit. Lost leaves count only while the balance still holds them ([beyondLostLeaves]).
Expand Down Expand Up @@ -351,7 +397,7 @@ object SparkExitMath {
record.fundingPaymentTxid?.let { txid ->
val isAdopted = record.funding.any { it.txid == txid }
val isConfirmed = utxos?.any { it.txid == txid && it.status.confirmed } == true
if (!isAdopted && !isConfirmed) return SparkExitFundingState.Paid(txid)
if (!isAdopted && !isConfirmed) return SparkExitFundingState.Paid
}
val fresh = utxos?.let { newFunding(it, record) }.orEmpty()
val seen = fresh.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() }
Expand All @@ -360,8 +406,7 @@ object SparkExitMath {
val shortfall = needed.safe() + (inputFee.safe() * maxOf(fresh.size - 1, 0).toULong().safe()).safe()
if (fresh.isNotEmpty() && seen >= shortfall) {
// Covered: waiting for it to confirm, or for the next tick to take it once it has.
val txid = (fresh.firstOrNull { !it.status.confirmed } ?: fresh.first()).txid
return SparkExitFundingState.Seen(txid)
return SparkExitFundingState.Seen
}
// A partial payment leaves another coin to send, with its own input fee. Nodes refuse an output under its dust
// limit, so a smaller remainder is asked as the funding output's dust.
Expand Down Expand Up @@ -565,11 +610,11 @@ object SparkExitMath {

/** The fee funding an exit still needs, as progress shows it. */
sealed interface SparkExitFundingState {
/** Savings paid it in [txid], which has not confirmed yet. */
data class Paid(val txid: String) : SparkExitFundingState
/** Savings paid it, and the payment has not confirmed yet. */
data object Paid : SparkExitFundingState

/** A payment covering it, [txid] among them, was seen and waits to confirm. */
data class Seen(val txid: String) : SparkExitFundingState
/** A payment covering it was seen and waits to confirm. */
data object Seen : SparkExitFundingState

/**
* [sats] are still missing at the funding address, at least dust, after [receivedSats] of new funding seen there
Expand Down Expand Up @@ -613,6 +658,9 @@ data class SparkExitFeeBumpOption(
}
}

/** What an ended exit returned to savings: [spendingSats] of spending balance, [feesSats] of unspent emergency fees. */
data class SparkExitReturned(val spendingSats: ULong, val feesSats: ULong)

/** Whether the funding address covers the quote before the exit starts, and the hint while it does not. */
data class SparkExitPrestartFunding(val isCovered: Boolean, val partial: SparkExitPartialFunding?)

Expand Down
24 changes: 18 additions & 6 deletions app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ data class SparkExitRecord(
val feeBumpBuiltAtHeight: UInt? = null,
/** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */
val earlierReceivedSats: Map<String, ULong> = emptyMap(),
/** The fee funding confirmed SWEEP steps of replaced generations returned to [destination], by txid. */
val earlierReturnedFundingSats: Map<String, ULong> = emptyMap(),
/** Each quoted leaf's value, so a leaf the first build leaves behind before any recovery lists it keeps it. */
val leafSats: Map<String, ULong> = emptyMap(),
/**
Expand Down Expand Up @@ -444,6 +446,9 @@ data class SparkExitRecord(
feeBumpBuiltAtHeight = null,
earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) }
.orEmpty(),
earlierReturnedFundingSats = earlierReturnedFundingSats + recovery
?.let { SparkExitMath.sweepFunding(fundingInputs, it, confirmedOnly = true) }
.orEmpty(),
earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::fundingTxids).orEmpty()).distinct(),
landedSweepTxid = recovery?.transactions
?.firstOrNull { it.kind == RecoveryTxKind.SWEEP && it.status is ExitTransactionStatus.Confirmed }
Expand Down Expand Up @@ -806,6 +811,9 @@ object SparkExitJson {
earlierReceivedSats = read {
o.objectOrNull("earlierReceivedSats")?.mapValues { it.value.jsonPrimitive.content.toULong() }
}.orEmpty(),
earlierReturnedFundingSats = read {
o.objectOrNull("earlierReturnedFundingSats")?.mapValues { it.value.jsonPrimitive.content.toULong() }
}.orEmpty(),
leafSats = read { leafSatsFromJson(o) }.orEmpty(),
landedSweepTxid = read { o.stringOrNull("landedSweepTxid") },
sweptLeftover = read { sweptLeftoverFromJson(o) }.orEmpty(),
Expand Down Expand Up @@ -934,6 +942,11 @@ object SparkExitJson {
}
}

private fun JsonObjectBuilder.putSatsByTxid(key: String, sats: Map<String, ULong>) {
if (sats.isEmpty()) return
put(key, buildJsonObject { sats.forEach { (txid, value) -> put(txid, value.toLong()) } })
}

private fun sweepToJson(sweep: SparkExitRecord.LeftoverSweep) = buildJsonObject {
sweep.txid?.let { put("txid", it) }
sweep.txHex?.let { put("txHex", it) }
Expand Down Expand Up @@ -1042,12 +1055,8 @@ object SparkExitJson {
r.fundingPaymentSeenAtHeight?.let { put("fundingPaymentSeenAtHeight", it.toLong()) }
r.fundingPaymentMissingSince?.let { put("fundingPaymentMissingSince", it.toLong()) }
if (r.isCancelled) put("isCancelled", true)
if (r.earlierReceivedSats.isNotEmpty()) {
put(
"earlierReceivedSats",
buildJsonObject { r.earlierReceivedSats.forEach { (txid, sats) -> put(txid, sats.toLong()) } },
)
}
putSatsByTxid("earlierReceivedSats", r.earlierReceivedSats)
putSatsByTxid("earlierReturnedFundingSats", r.earlierReturnedFundingSats)
if (r.leafSats.isNotEmpty()) {
put("leafSats", buildJsonObject { r.leafSats.forEach { (leafId, sats) -> put(leafId, sats.toLong()) } })
}
Expand Down Expand Up @@ -1152,6 +1161,9 @@ object SparkExitJson {
earlierReceivedSats = o.objectOrNull("earlierReceivedSats")
?.mapValues { it.value.jsonPrimitive.content.toULong() }
.orEmpty(),
earlierReturnedFundingSats = o.objectOrNull("earlierReturnedFundingSats")
?.mapValues { it.value.jsonPrimitive.content.toULong() }
.orEmpty(),
leafSats = leafSatsFromJson(o),
)

Expand Down
3 changes: 0 additions & 3 deletions app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,6 @@ class SparkExitWork @Inject constructor(
return SparkExitBackgroundLimits(
isRestricted = battery.isBackgroundRestricted == true,
isPowerSaveMode = battery.isPowerSaveMode == true,
isOptimized = battery.isIgnoringBatteryOptimizations == false,
areNotificationsEnabled = context.areNotificationsEnabled(),
)
}
Expand Down Expand Up @@ -344,8 +343,6 @@ data class SparkExitBackgroundLimits(
/** The user restricted Bitkit's background use: no work or alarm runs while it is closed. */
val isRestricted: Boolean = false,
val isPowerSaveMode: Boolean = false,
/** Battery optimization is on, Android's default, so background runs wait for Doze's windows. */
val isOptimized: Boolean = false,
val areNotificationsEnabled: Boolean = true,
)

Expand Down
Loading
Loading