Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion Bitkit/Components/Button/PrimaryButtonView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct PrimaryButtonView: View {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .textPrimary))
.frame(width: 20, height: 20)
} else {
} else if !title.isEmpty {
if size == .small {
CaptionBText(title, textColor: .textPrimary, kerning: titleKerning, lineHeight: titleLineHeight)
} else {
Expand Down
1 change: 1 addition & 0 deletions Bitkit/MainNavView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,7 @@ struct MainNavView: View {
case .sparkExitIntro: SparkExitIntroView()
case .sparkExitQuote: SparkExitQuoteView()
case .sparkExitFunding: SparkExitFundingView()
case .sparkExitPay: SparkExitPayView()
case .sparkExitConfirm: SparkExitConfirmView()
case .sparkExitProgress: SparkExitProgressView()
case .sparkExitFeeBump: SparkExitFeeBumpView()
Expand Down
18 changes: 13 additions & 5 deletions Bitkit/Managers/SparkExitManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -918,17 +918,25 @@ final class SparkExitManager {
self.fundingAddress = fundingAddress
}

/// Watches the funding address while the user funds it from another wallet.
func watchFundingAddress() async {
guard let chain, let fundingAddress else { return }
/// Watches the funding address while the user pays the emergency fees from another wallet, calling `onRead` after
/// each read that succeeded.
func watchFundingAddress(onRead: () -> Void = {}) async {
while !Task.isCancelled {
if let utxos = try? await chain.utxos(address: fundingAddress) {
noteFundingSeen(utxos)
if await readFundingAddress() != nil {
onRead()
}
try? await Task.sleep(nanoseconds: 15 * 1_000_000_000)
}
}

/// Reads the funding address once: what reached it, or nil when it could not be read.
@discardableResult
func readFundingAddress() async -> UInt64? {
guard let chain, let fundingAddress, let utxos = try? await chain.utxos(address: fundingAddress) else { return nil }
noteFundingSeen(utxos)
return fundingSeenSats
}

/// What reached the funding address before the exit starts.
func noteFundingSeen(_ utxos: [EsploraUtxo]) {
fundingSeenSats = utxos.reduce(0) { $0 + $1.value }
Expand Down
141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/ar.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/ca.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/cs.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/de.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/el.lproj/Localizable.strings

Large diffs are not rendered by default.

146 changes: 74 additions & 72 deletions Bitkit/Resources/Localization/en.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/es-419.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/es.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/fr.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/it.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/nl.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/pl.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings

Large diffs are not rendered by default.

143 changes: 75 additions & 68 deletions Bitkit/Resources/Localization/pt.lproj/Localizable.strings

Large diffs are not rendered by default.

141 changes: 74 additions & 67 deletions Bitkit/Resources/Localization/ru.lproj/Localizable.strings

Large diffs are not rendered by default.

86 changes: 71 additions & 15 deletions Bitkit/Services/SparkExit/SparkExitFunding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,11 @@ struct SparkExitQuote: Equatable {
}

/// The on-chain payment that funds the CPFP fees, or 0 when every leaf is recovered cooperatively. One payment,
/// from savings or another wallet: the SDK splits it into one output per fee-bumped transaction (`fundedSteps`).
/// from savings or another wallet: the SDK splits it into one output per fee-bumped transaction.
var fundingSats: UInt64 {
prepared.funding?.singleUtxoSats ?? 0
}

/// The transactions the funding pays a fee for, each from its own share.
var fundedSteps: Int {
prepared.funding?.perBranch.count ?? 0
}

/// What the sweep and the cooperative recoveries pay to savings: `receiveSats` plus the fee funding the exit
/// did not spend, which the sweep returns.
var incomingSats: UInt64 {
Expand Down Expand Up @@ -211,6 +206,12 @@ struct SparkExitFeeBumpOption: Equatable, Identifiable {
}
}

/// What an ended exit returned to savings: `spendingSats` of spending balance, `feesSats` of unspent emergency fees.
struct SparkExitReturned: Equatable {
let spendingSats: UInt64
let feesSats: UInt64
}

/// A local notification that brings the user back to an exit; `id` is stable across runs for the same step.
struct SparkExitReminder: Equatable {
let id: String
Expand Down Expand Up @@ -381,6 +382,70 @@ enum SparkExitMath {
return (sats, transactions.first { $0.kind == .sweep }?.txid ?? record.landedSweepTxid)
}

/// The unspent fee funding the SWEEP steps of `record`'s recovery return to savings: the value of their inputs that
/// spend the funding address, which are funding UTXOs 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, nor is the sweep
/// of a replaced generation: the record keeps what it paid (`earlierReceivedSats`) and returned
/// (`earlierReturnedFundingSats`).
static func returnedFundingSats(_ record: SparkExitRecord) -> UInt64 {
guard let recovery = record.recovery?.response else { return 0 }
var funding: [String: UInt64] = [:]
for input in record.fundingInputs + recovery.fundingInputs {
if case let .p2wpkh(txid, vout, valueSats, _) = input {
funding["\(txid):\(vout)"] = valueSats
}
}
var parents: [String: String] = [:]
for tx in recovery.transactions {
if let hex = tx.cpfpTxHex, let txid = SparkExitTxid.txid(hex: hex) {
parents[txid] = hex
}
}
for tx in recovery.transactions where tx.kind == .fanOut {
parents[tx.txid] = tx.txHex
}
var seen: Set<String> = []
var sats: UInt64 = 0
for sweep in recovery.transactions where sweep.kind == .sweep {
for input in SparkExitTxid.inputOutpoints(hex: sweep.txHex) ?? [] {
let outpoint = "\(input.txid):\(input.vout)"
guard seen.insert(outpoint).inserted else { continue }
let parentOutputs = parents[input.txid].flatMap { SparkExitTxid.outputs(hex: $0) }
let value = funding[outpoint] ?? parentOutputs.flatMap { Int(input.vout) < $0.count ? $0[Int(input.vout)].value : nil }
sats = sats.saturatingAdd(value ?? 0)
}
}
return sats
}

/// The leftover fee funding the ended exit swept back on its own: earlier sweeps and the confirmed last one.
static func sweptLeftoverSats(_ record: SparkExitRecord) -> UInt64 {
let swept = (record.sweptLeftover ?? []).reduce(UInt64(0)) { $0.saturatingAdd($1.valueSats) }
let sending = record.leftoverSweep?.isConfirmed == true ? record.leftoverSweep?.valueSats ?? 0 : 0
return swept.saturatingAdd(sending)
}

/// What the ended exit returned to savings, split as the done screen names it: `received` 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, with what sweeps of replaced generations returned.
/// Nil before it ended done or when no output to savings can be read.
static func returned(_ record: SparkExitRecord) -> SparkExitReturned? {
guard let received = received(record)?.sats else { return nil }
let current = Set((record.recovery?.response.transactions ?? []).filter { $0.kind == .sweep }.map(\.txid))
let earlier = (record.earlierReturnedFundingSats ?? [:]).filter { !current.contains($0.key) }.values
.reduce(UInt64(0)) { $0.saturatingAdd($1) }
// Capped at what was received, so the two parts always add up to what reached savings.
let funding = min(returnedFundingSats(record).saturatingAdd(earlier), received)
return SparkExitReturned(spendingSats: received - funding, feesSats: sweptLeftoverSats(record).saturatingAdd(funding))
}

/// Pay to confirm starts the exit on its own, once, for a payment that arrived after its first read of the funding
/// address (`entrySeenCount`, nil until that read) and covers the funding. Funding already there when it opened
/// waits for a tap, so nothing starts unseen. A start already running, such as one Continue began, is the only one.
static func canAutoStartFunding(isFunded: Bool, isStarting: Bool, hasAutoStarted: Bool, entrySeenCount: Int?, seenCount: Int) -> Bool {
isFunded && !isStarting && !hasAutoStarted && entrySeenCount.map { seenCount > $0 } == true
}

/// The exit's sweeps to savings: the recovery's, else the one that landed before a retry replaced it, and those of
/// generations a Redo replaced.
static func sweepTxids(_ record: SparkExitRecord) -> [String] {
Expand Down Expand Up @@ -616,15 +681,6 @@ enum SparkExitMath {
return outside > 0 ? outside : nil
}

/// The Spark balance a quote cannot exit: the leaves it skips, and what the balance holds beyond every leaf the
/// SDK lists, such as a counter-swap still unclaimed. Nil when there is none.
static func unexitableSats(sparkBalanceSats: UInt64, quote: SparkExitQuote) -> UInt64? {
let listed = quote.leafTotalSats + quote.leftBehindSats
let beyond = beyondLostLeaves(sparkBalanceSats.saturatingSub(listed), lostLeafSats: quote.lostLeafSats)
let unexitable = quote.leftBehindSats + beyond
return unexitable > 0 ? unexitable : nil
}

/// `sats` less the lost leaves it still holds. Spark's balance keeps a leaf an older state claimed until a later
/// sync drops it, so each lost leaf, largest first, is taken out only while what is left still covers it.
static func beyondLostLeaves(_ sats: UInt64, lostLeafSats: [UInt64]) -> UInt64 {
Expand Down
12 changes: 11 additions & 1 deletion Bitkit/Services/SparkExit/SparkExitRecord.swift
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,9 @@ struct SparkExitRecord: Codable, Equatable {
var rebuiltFromChainConfirmedCount: Int?
/// What confirmed sweeps and cooperative recoveries of replaced generations paid to savings, by txid.
var earlierReceivedSats: [String: UInt64]?
/// The unspent fee funding confirmed sweeps of replaced generations returned to savings, by txid: part of
/// `earlierReceivedSats` that counts as fees, not spending balance.
var earlierReturnedFundingSats: [String: UInt64]?
var leftBehindLeaves: [LeftBehindLeaf]?
/// Set once the user opened the result of an exit that failed or lost leaves.
var isResultSeen: Bool?
Expand Down Expand Up @@ -422,6 +425,10 @@ struct SparkExitRecord: Codable, Equatable {
}
if let sweep = recovery.response.transactions.first(where: { $0.kind == .sweep }), case .confirmed = sweep.status {
landedSweepTxid = sweep.txid
let funding = SparkExitMath.returnedFundingSats(self)
if funding > 0 {
earlierReturnedFundingSats = (earlierReturnedFundingSats ?? [:]).merging([sweep.txid: funding]) { $1 }
}
}
}
generation += 1
Expand Down Expand Up @@ -749,6 +756,7 @@ enum SparkExitRecordCoder {
record.exitStateSnapshot = kept.exitStateSnapshot
record.fundingStrategy = kept.fundingStrategy
record.earlierReceivedSats = kept.earlierReceivedSats
record.earlierReturnedFundingSats = kept.earlierReturnedFundingSats
record.outsideSats = kept.outsideSats
// Change and fan-out outputs of earlier generations at the funding address stay the exit's own, not new funding.
let chained = (kept.earlierCpfpTxids ?? []) + (kept.recovery.map { SparkExitTxid.chainedTxids($0.response) } ?? [])
Expand All @@ -775,12 +783,13 @@ enum SparkExitRecordCoder {
let recovery: StoredRecovery?
let fundingStrategy: String?
let earlierReceivedSats: [String: UInt64]?
let earlierReturnedFundingSats: [String: UInt64]?
let outsideSats: UInt64?

private enum CodingKeys: String, CodingKey {
case network, createdAt, phase, feeRateSatPerVbyte, destination, leafIds, leafTotalSats, funding, transferId, expectedSats
case lostLeaves, leftBehindLeaves, exitStateSnapshot, earlierCpfpTxids, recovery, fundingStrategy, earlierReceivedSats
case outsideSats
case earlierReturnedFundingSats, outsideSats
}

init(from decoder: Decoder) throws {
Expand All @@ -802,6 +811,7 @@ enum SparkExitRecordCoder {
recovery = try? c.decodeIfPresent(StoredRecovery.self, forKey: .recovery)
fundingStrategy = try? c.decodeIfPresent(String.self, forKey: .fundingStrategy)
earlierReceivedSats = try? c.decodeIfPresent([String: UInt64].self, forKey: .earlierReceivedSats)
earlierReturnedFundingSats = try? c.decodeIfPresent([String: UInt64].self, forKey: .earlierReturnedFundingSats)
outsideSats = try? c.decodeIfPresent(UInt64.self, forKey: .outsideSats)
}
}
Expand Down
5 changes: 3 additions & 2 deletions Bitkit/Utilities/AppStatusHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ enum HealthStatus: String {
}
}

/// The step of a running emergency exit, named like its App Status subtitle key.
/// The step of a running force transfer, which picks its App Status subtitle: `settings__status__exit__funding` while it
/// asks for fee funding, `settings__status__spark__exit` otherwise.
enum ExitStatusStep: String {
case funding
case pending
Expand Down Expand Up @@ -95,12 +96,12 @@ struct AppStatusHelper {
)
}

/// Nil where Spark is unsupported.
/// Spark can take payments only while the device is online, the same check that shows it "Offline...".
static func isSparkReceiving(network: NetworkMonitor) -> Bool {
network.isConnected && SparkManager.shared.isReceiving
}

/// Nil where Spark is unsupported.
static func sparkStatus(network: NetworkMonitor) -> HealthStatus? {
let spark = SparkManager.shared
return sparkStatus(
Expand Down
37 changes: 37 additions & 0 deletions Bitkit/ViewModels/NavigationViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ enum Route: Hashable {
case sparkExitIntro
case sparkExitQuote
case sparkExitFunding
case sparkExitPay
case sparkExitConfirm
case sparkExitProgress
case sparkExitFeeBump
Expand Down Expand Up @@ -265,4 +266,40 @@ class NavigationViewModel: ObservableObject {
func reset() {
path.removeAll()
}

/// Opens a started force transfer's progress right above the Spark connection screen it started from, so leaving
/// progress returns there.
func openSparkExitProgress() {
if let index = path.lastIndex(of: .sparkConnectionDetail) {
path = Array(path[...index])
}
path.append(.sparkExitProgress)
}

/// Opens Transfer to Savings for the wallet's balances now; see `navigateToTransferSavings(isSparkOnly:transfer:)`.
func navigateToTransferSavings(wallet: WalletViewModel, transfer: TransferViewModel) {
let spark = SparkManager.shared
let isSparkOnly = Self.isSparkOnly(
nodeLifecycleState: wallet.nodeLifecycleState,
channels: wallet.channels,
sparkSpendingSats: spark.isExiting ? 0 : spark.balanceSats
)
navigateToTransferSavings(isSparkOnly: isSparkOnly, transfer: transfer)
}

/// Opens Transfer to Savings, past Network Fee & Availability when only Spark's balance moves: it lands at once.
func navigateToTransferSavings(isSparkOnly: Bool, transfer: TransferViewModel) {
guard isSparkOnly else {
navigate(.savingsAvailability)
return
}
transfer.beginSavingsTransfer()
navigate(.savingsConfirm)
}

/// Spark holds the whole spending balance: the node runs, its channels are loaded, and none is open.
nonisolated static func isSparkOnly(nodeLifecycleState: NodeLifecycleState, channels: [ChannelDetails]?, sparkSpendingSats: UInt64) -> Bool {
guard nodeLifecycleState == .running, let channels else { return false }
return !channels.contains(where: \.isChannelReady) && sparkSpendingSats > 0
}
}
4 changes: 3 additions & 1 deletion Bitkit/Views/Settings/Advanced/SparkConnectionViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ struct SparkConnectionDetailView: View {
@EnvironmentObject var app: AppViewModel
@EnvironmentObject var navigation: NavigationViewModel
@EnvironmentObject var network: NetworkMonitor
@EnvironmentObject var transfer: TransferViewModel
@EnvironmentObject var wallet: WalletViewModel
@Environment(\.openURL) private var openURL

@State private var depositAddress: String?
Expand Down Expand Up @@ -220,7 +222,7 @@ struct SparkConnectionDetailView: View {
.foregroundColor(.textPrimary)
) {
if app.hasSeenTransferToSavingsIntro {
navigation.navigate(.savingsAvailability)
navigation.navigateToTransferSavings(wallet: wallet, transfer: transfer)
} else {
navigation.navigate(.savingsIntro)
}
Expand Down
Loading
Loading